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
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function(ed) { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(), fl = tinyMCEPopup.getParam('external_image_list', 'tinyMCEImageList'); tinyMCEPopup.resizeToInnerSize(); this.fillClassList('class_list'); this.fillFileList('src_list', fl); this.fillFileList('over_list', fl); this.fillFileList('out_list', fl); TinyMCE_EditableSelects.init(); if (n.nodeName == 'IMG') { nl.src.value = dom.getAttrib(n, 'src'); nl.width.value = dom.getAttrib(n, 'width'); nl.height.value = dom.getAttrib(n, 'height'); nl.alt.value = dom.getAttrib(n, 'alt'); nl.title.value = dom.getAttrib(n, 'title'); nl.vspace.value = this.getAttrib(n, 'vspace'); nl.hspace.value = this.getAttrib(n, 'hspace'); nl.border.value = this.getAttrib(n, 'border'); selectByValue(f, 'align', this.getAttrib(n, 'align')); selectByValue(f, 'class_list', dom.getAttrib(n, 'class'), true, true); nl.style.value = dom.getAttrib(n, 'style'); nl.id.value = dom.getAttrib(n, 'id'); nl.dir.value = dom.getAttrib(n, 'dir'); nl.lang.value = dom.getAttrib(n, 'lang'); nl.usemap.value = dom.getAttrib(n, 'usemap'); nl.longdesc.value = dom.getAttrib(n, 'longdesc'); nl.insert.value = ed.getLang('update'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover'))) nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout'))) nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (ed.settings.inline_styles) { // Move attribs to styles if (dom.getAttrib(n, 'align')) this.updateStyle('align'); if (dom.getAttrib(n, 'hlspace')) this.updateStyle('hlspace'); if (dom.getAttrib(n, 'hrspace')) this.updateStyle('hrspace'); if (dom.getAttrib(n, 'border')) this.updateStyle('border'); if (dom.getAttrib(n, 'vtspace')) this.updateStyle('vtspace'); if (dom.getAttrib(n, 'vbspace')) this.updateStyle('vbspace'); } } // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '260px'; // Setup browse button document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image'); if (isVisible('overbrowser')) document.getElementById('onmouseoversrc').style.width = '260px'; // Setup browse button document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image'); if (isVisible('outbrowser')) document.getElementById('onmouseoutsrc').style.width = '260px'; // If option enabled default contrain proportions to checked if (ed.getParam("advimage_constrain_proportions", true)) f.constrain.checked = true; // Check swap image if valid data if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value) this.setSwapImage(true); else this.setSwapImage(false); this.changeAppearance(); this.showPreviewImage(nl.src.value, 1); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, t = this, f = document.forms[0]; if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (tinyMCEPopup.getParam("accessibility_warnings", 1)) { if (!f.alt.value) { tinyMCEPopup.confirm(tinyMCEPopup.getLang('advimage_dlg.missing_alt'), function(s) { if (s) t.insertAndClose(); }); return; } } t.insertAndClose(); }, insertAndClose : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el; tinyMCEPopup.restoreSelection(); // Fixes crash in Safari if (tinymce.isWebKit) ed.getWin().focus(); if (!ed.settings.inline_styles) { args = { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }; } else { // Remove deprecated values args = { vspace : '', hspace : '', border : '', align : '' }; } tinymce.extend(args, { src : nl.src.value.replace(/ /g, '%20'), width : nl.width.value, height : nl.height.value, alt : nl.alt.value, title : nl.title.value, 'class' : getSelectValue(f, 'class_list'), style : nl.style.value, id : nl.id.value, dir : nl.dir.value, lang : nl.lang.value, usemap : nl.usemap.value, longdesc : nl.longdesc.value }); args.onmouseover = args.onmouseout = ''; if (f.onmousemovecheck.checked) { if (nl.onmouseoversrc.value) args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';"; if (nl.onmouseoutsrc.value) args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';"; } el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); } else { tinymce.each(args, function(value, name) { if (value === "") { delete args[name]; } }); ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1}); ed.undoManager.add(); } tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); tinyMCEPopup.close(); }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, setSwapImage : function(st) { var f = document.forms[0]; f.onmousemovecheck.checked = st; setBrowserDisabled('overbrowser', !st); setBrowserDisabled('outbrowser', !st); if (f.over_list) f.over_list.disabled = !st; if (f.out_list) f.out_list.disabled = !st; f.onmouseoversrc.disabled = !st; f.onmouseoutsrc.disabled = !st; }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options.length = 0; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = typeof(l) === 'function' ? l() : window[l]; lst.options.length = 0; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, resetImageData : function() { var f = document.forms[0]; f.elements.width.value = f.elements.height.value = ''; }, updateImageData : function(img, st) { var f = document.forms[0]; if (!st) { f.elements.width.value = img.width; f.elements.height.value = img.height; } this.preloadImg = img; }, changeAppearance : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg'); if (img) { if (ed.getParam('inline_styles')) { ed.dom.setAttrib(img, 'style', f.style.value); } else { img.align = f.align.value; img.border = f.border.value; img.hspace = f.hspace.value; img.vspace = f.vspace.value; } } }, changeHeight : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height; f.height.value = tp.toFixed(0); }, changeWidth : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width; f.width.value = tp.toFixed(0); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, b, bStyle, bColor, v, isIE = tinymce.isIE, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { b = img.style.border ? img.style.border.split(' ') : []; bStyle = dom.getStyle(img, 'border-style'); bColor = dom.getStyle(img, 'border-color'); dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = isIE ? '0' : '0 none none'; else { if (b.length == 3 && b[isIE ? 2 : 1]) bStyle = b[isIE ? 2 : 1]; else if (!bStyle || bStyle == 'none') bStyle = 'solid'; if (b.length == 3 && b[isIE ? 0 : 2]) bColor = b[isIE ? 0 : 2]; else if (!bColor || bColor == 'none') bColor = 'black'; img.style.border = v + 'px ' + bStyle + ' ' + bColor; } } } // Handle hspace if (ty == 'hlspace') { dom.setStyle(img, 'marginLeft', ''); v = f.hlspace.value; if (v) { img.style.marginLeft = v + 'px'; } } // Handle hspace if (ty == 'hrspace') { dom.setStyle(img, 'marginRight', ''); v = f.hrspace.value; if (v) { img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vtspace') { dom.setStyle(img, 'marginTop', ''); v = f.vtspace.value; if (v) { img.style.marginTop = v + 'px'; } } if (ty == 'vbspace') { dom.setStyle(img, 'marginBottom', ''); v = f.vbspace.value; if (v) { img.style.marginBottom = v + 'px'; } } // Merge dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText), 'img'); } }, changeMouseMove : function() { }, showPreviewImage : function(u, st) { if (!u) { tinyMCEPopup.dom.setHTML('prev', ''); return; } if (!st && tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true)) this.resetImageData(); u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u); if (!st) tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this);" onerror="ImageDialog.resetImageData();" />'); else tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this, 1);" />'); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
irony-rust/nickel-cms
static/themes/admin/components/tinymce/jscripts/tiny_mce/plugins/advimage/js/image.js
JavaScript
mit
13,170
SOCIAL_AUTH_VK_LOGIN_URL = 'https://oauth.vk.com/authorize' SOCIAL_AUTH_VK_OAUTH2_KEY = '3911688' SOCIAL_AUTH_VK_OAUTH2_SECRET = '2Y5FYZB3cqDsPteHXBBO' SOCIAL_AUTH_VK_OAUTH2_SCOPE = ['friends'] AUTHENTICATION_BACKENDS = ( 'social.backends.vk.VKOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/registration/' SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error/' SOCIAL_AUTH_LOGIN_URL = '/login/' SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/registration/' SOCIAL_AUTH_STRATEGY = 'social.strategies.django_strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social.apps.django_app.default.models.DjangoStorage' SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/registration/' SOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/registration/' SOCIAL_AUTH_INACTIVE_USER_URL = '/inactive-user/' """These URLs are used on different steps of the auth process, some for successful results and others for error situations. SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/logged-in/' Used to redirect the user once the auth process ended successfully. The value of ?next=/foo is used if it was present SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error/' URL where the user will be redirected in case of an error Is used as a fallback for LOGIN_ERROR_URL SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/new-users-redirect-url/' Used to redirect new registered users, will be used in place of SOCIAL_AUTH_LOGIN_REDIRECT_URL if defined. SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/new-association-redirect-url/' Like SOCIAL_AUTH_NEW_USER_REDIRECT_URL but for new associated accounts (user is already logged in). Used in place of SOCIAL_AUTH_LOGIN_REDIRECT_URL SOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/account-disconnected-redirect-url/' The user will be redirected to this URL when a social account is disconnected SOCIAL_AUTH_INACTIVE_USER_URL = '/inactive-user/' Inactive users can be redirected to this URL when trying to authenticate. Successful URLs will default to SOCIAL_AUTH_LOGIN_URL while error URLs will fallback to SOCIAL_AUTH_LOGIN_ERROR_URL.""" SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.mail.mail_validation', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' )
ox1omon/movement_fefu
movement/settings/social.py
Python
mit
2,521
import { IGenerator } from "./IGenerator"; export class CachingGenerator implements IGenerator { private cache: { [i: number]: number }; public constructor() { this.cache = {}; } public generate(index: number): number { if (index < 2) { return index; } let one: number = this.generate(index - 1); let two: number = this.generate(index - 2); let result: number = one + two; this.cache[index] = result; return result; } public isCached(index: number): boolean { return {}.hasOwnProperty.call(this.cache, index); } }
general-language-syntax/GLS
test/end-to-end/Fibonacci/TypeScript/Generation/CachingGenerator.ts
TypeScript
mit
633
version https://git-lfs.github.com/spec/v1 oid sha256:2c3adeeb6c0341f0567979d93b5aceef7ac52df657743c63d840e686dd82e9cd size 24839
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.15.0/model-sync-rest/model-sync-rest.js
JavaScript
mit
130
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using DataFactory.Tests.Utils; namespace DataFactory.Tests.JsonSamples { public class PipelineJsonSamples : JsonSampleCollection<PipelineJsonSamples> { [JsonSample] public const string CopyActivity = @" { ""name"": ""MyPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""Copy"", ""typeProperties"": { ""source"": { ""type"": ""SqlSource"" }, ""sink"": { ""type"": ""SqlDWSink"", ""allowPolyBase"": true, ""writeBatchSize"": 0, ""writeBatchTimeout"": ""PT0S"" }, ""enableStaging"": true, ""stagingSettings"": { ""linkedServiceName"": { ""referenceName"": ""StagingLinkedService"", ""type"": ""LinkedServiceReference"" } } }, ""inputs"": [ { ""referenceName"": ""SourceDataset"", ""type"": ""DatasetReference"" } ], ""outputs"": [ { ""referenceName"": ""SinkDataset"", ""type"": ""DatasetReference"" } ] } ] } } "; [JsonSample] public const string CopyActivityWithSkipIncompatibleRows = @" { ""name"": ""MyPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""Copy"", ""typeProperties"": { ""source"": { ""type"": ""SqlSource"" }, ""sink"": { ""type"": ""SqlDWSink"", ""allowPolyBase"": true, ""writeBatchSize"": 0, ""writeBatchTimeout"": ""PT0S"" }, ""enableStaging"": true, ""stagingSettings"": { ""linkedServiceName"": { ""referenceName"": ""StagingLinkedService"", ""type"": ""LinkedServiceReference"" } }, enableSkipIncompatibleRow: true, redirectIncompatibleRowSettings: { ""linkedServiceName"": { ""referenceName"": ""StagingLinkedService"", ""type"": ""LinkedServiceReference"" }, ""path"": ""fakePath"" } }, ""inputs"": [ { ""referenceName"": ""SourceDataset"", ""type"": ""DatasetReference"" } ], ""outputs"": [ { ""referenceName"": ""SinkDataset"", ""type"": ""DatasetReference"" } ] } ] } }"; [JsonSample] public const string HiveActivity = @" { ""name"": ""MyPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""HDInsightHive"", ""typeProperties"": { ""scriptPath"": ""testing"" }, ""linkedServiceName"": { ""referenceName"": ""MyLinkedServiceName"", ""type"": ""LinkedServiceReference"" } } ] } } "; [JsonSample] public const string ChainedActivitiesWithParametersPipeline = @" { 'properties': { 'activities': [ { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity_0_0', 'inputs': [ { 'referenceName': 'MyTestDatasetIn', 'type': 'DatasetReference' } ], 'outputs': [ { 'referenceName': 'MyComplexDS0_0', 'type': 'DatasetReference' } ] }, { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity_1_0', 'dependsOn': [ { 'activity': 'MyCopyActivity_0_0', 'dependencyConditions': [ 'Succeeded' ] } ], 'inputs': [ { 'referenceName': 'MyComplexDS0_0', 'type': 'DatasetReference' } ], 'outputs': [ { 'referenceName': 'MyComplexDS1_0', 'type': 'DatasetReference' } ] }, { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity_1_1', 'dependsOn': [ { 'activity': 'MyCopyActivity_0_0', 'dependencyConditions': [ 'Succeeded', 'Failed', 'Skipped', 'Completed' ] } ], 'inputs': [ { 'referenceName': 'MyComplexDS0_0', 'type': 'DatasetReference' } ], 'outputs': [ { 'referenceName': 'MyComplexDS1_1', 'type': 'DatasetReference' } ] } ], 'parameters': { 'OutputBlobName': { 'type': 'String' } } } } "; [JsonSample] public const string DatasetReferenceArgumentsPipeline = @" { 'properties': { 'activities': [ { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity_0_0', 'inputs': [ { 'referenceName': 'MyTestDatasetIn', 'type': 'DatasetReference' } ], 'outputs': [ { 'referenceName': 'MyComplexDS', 'type': 'DatasetReference', 'parameters': { 'FileName': { 'value': ""@concat('variant0_0_', parameters('OutputBlobName'))"", 'type': 'Expression' } } } ] }, { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity_1_0', 'dependsOn': [ { 'activity': 'MyCopyActivity_0_0', 'dependencyConditions': [ 'Succeeded' ] } ], 'inputs': [ { 'referenceName': 'MyComplexDS', 'type': 'DatasetReference', 'parameters': { 'FileName': { 'value': ""@concat('variant0_0_', parameters('OutputBlobName'))"", 'type': 'Expression' } } } ], 'outputs': [ { 'referenceName': 'MyComplexDS', 'type': 'DatasetReference', 'parameters': { 'FileName': { 'value': ""@concat('variant1_0_', parameters('OutputBlobName'))"", 'type': 'Expression' } } } ] }, { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity_1_1', 'dependsOn': [ { 'activity': 'MyCopyActivity_0_0', 'dependencyConditions': [ 'Succeeded', 'Failed', 'Skipped', 'Completed' ] } ], 'inputs': [ { 'referenceName': 'MyComplexDS', 'type': 'DatasetReference', 'parameters': { 'FileName': { 'value': ""@concat('variant0_0_', parameters('OutputBlobName'))"", 'type': 'Expression' } } } ], 'outputs': [ { 'referenceName': 'MyComplexDS', 'type': 'DatasetReference', 'parameters': { 'FileName': { 'value': ""@concat('variant1_1_', parameters('OutputBlobName'))"", 'type': 'Expression' } } } ] } ], 'parameters': { 'OutputBlobName': { 'type': 'String' } } } } "; [JsonSample] public const string FullInlinePipeline = @" { 'properties': { 'activities': [ { 'type': 'Copy', 'typeProperties': { 'source': { 'type': 'BlobSource' }, 'sink': { 'type': 'BlobSink' } }, 'name': 'MyCopyActivity', 'inputs': [ { 'referenceName': 'MyTestDatasetIn', 'type': 'DatasetReference' } ], 'outputs': [ { 'referenceName': 'MyTestDatasetOut', 'type': 'DatasetReference' } ] } ], 'parameters': { 'OutputBlobName': { 'type': 'String' } } } } "; // Below are adapted from V1 ActivityExtensibleJsonSamples20151001.cs // Some systematic differences from V1: // 0. no hubName property // 1. references to datasets and linked services use objects, not just names // 2. activity doesn't have scheduler property // 3. activity policy only has timeout, retry, longRetry, longRetryInterval (not concurrency, executionPriorityOrder or delay) // 4. pipelines/datasets/linked services can take parameters, pass arguments, and use expressions for most primitive property values // 5. pending issue about case sensitivity of property names, see comments about propertyBagKeys // 6. no pipeline start, end, isPaused, runtimeInfo properties // 7. no inline script for HDI // 8. no on-demand HDI [JsonSample(version: "Copy")] public const string WebTablePipeline = @" { name: ""DataPipeline_WebTableSample"", properties: { activities: [ { name: ""WebToBlobCopyActivity"", inputs: [ { referenceName: ""DA_Input"", type: ""DatasetReference"" } ], outputs: [ {referenceName: ""DA_Output"", type: ""DatasetReference""} ], type: ""Copy"", typeProperties: { source: { type: ""WebSource"", }, sink: { type: ""BlobSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"" } }, policy: { retry: 2, timeout: ""01:00:00"" } } ] } } "; [JsonSample(version: "SqlServerStoredProcedure")] // Original had a propertyBagKeys collection for the paths to the sproc params (Text and TEXT) which should be case sensitive public const string SprocPipeline = @" { name: ""DataPipeline_SqlServerStoredProcedureSample"", properties: { activities: [ { type: ""SqlServerStoredProcedure"", typeProperties: { storedProcedureName: ""MERGE_PROC"", storedProcedureParameters: { param1 : { value: ""test"", type: ""string"" } } }, name: ""SprocActivitySample"" } ] } } "; [JsonSample(version: "Copy")] public const string CopySqlToBlobWithTabularTranslator = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SQL to Blob"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SqlSource"", sourceRetryCount: 2, sourceRetryWait: ""00:00:01"", sqlReaderQuery: ""$EncryptedString$MyEncryptedQuery"", sqlReaderStoredProcedureName: ""CopyTestSrcStoredProcedureWithParameters"", storedProcedureParameters: { ""stringData"": { value: ""test"", type: ""String""}, ""id"": { value: ""3"", type: ""Int""} } }, sink: { type: ""BlobSink"", blobWriterAddHeader: true, writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"" }, translator: { type: ""TabularTranslator"", columnMappings: ""PartitionKey:PartitionKey"" } }, inputs: [ { referenceName: ""InputSqlDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputBlobDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string MSourcePipeline = @" { name: ""DataPipeline_MSample"", properties: { activities: [ { name: ""MySqlToBlobCopyActivity"", inputs: [ {referenceName: ""DA_Input"", type: ""DatasetReference""} ], outputs: [ {referenceName: ""DA_Output"", type: ""DatasetReference""} ], type: ""Copy"", typeProperties: { source: { type: ""RelationalSource"", query: ""select * from northwind_mysql.orders"" }, sink: { type: ""BlobSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"" } }, policy: { retry: 2, timeout: ""01:00:00"" } } ] } } "; [JsonSample(version: "HDInsightPig")] // original had propertyBagKeys for PropertyBagPropertyName1 // original also had inline script, changed to linked service public const string HDInsightPipeline = @" { name: ""My HDInsight pipeline"", properties: { description : ""HDInsight pipeline description"", activities: [ { name: ""TestActivity"", description: ""Test activity description"", type: ""HDInsightPig"", typeProperties: { scriptPath: ""scripts/script.pig"", scriptLinkedService: { referenceName: ""ScriptLinkedService"", type: ""LinkedServiceReference"" }, storageLinkedServices: [ { referenceName: ""SA1"", type: ""LinkedServiceReference"" }, { referenceName: ""SA2"", type: ""LinkedServiceReference"" } ], defines: { PropertyBagPropertyName1: ""PropertyBagValue1"" } }, linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "HDInsightHive")] public const string HDInsightPipeline2 = @" { name: ""My HDInsight pipeline2"", properties: { description : ""HDInsight pipeline description"", activities: [ { name: ""TestActivity"", description: ""Test activity description"", type: ""HDInsightHive"", typeProperties: { scriptPath: ""scripts/script.hql"", scriptLinkedService: { referenceName: ""storageLinkedService1"", type: ""LinkedServiceReference"" }, storageLinkedServices: [ { referenceName: ""storageLinkedService2"", type: ""LinkedServiceReference"" } ] }, linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "HDInsightMapReduce")] // original had propertyBagKeys for PropertyBagPropertyName1 public const string HDInsightMapReducePipeline = @" { name: ""My HDInsight MapReduce pipeline"", properties: { description : ""HDInsight pipeline description"", activities: [ { name: ""MapReduceActivity"", description: ""Test activity description"", type: ""HDInsightMapReduce"", typeProperties: { className : ""MYClass"", jarFilePath: ""TestData/hadoop-mapreduce-examples.jar"", jarLinkedService: { referenceName: ""storageLinkedService1"", type: ""LinkedServiceReference"" }, arguments: [ ""wasb:///example/data/gutenberg/davinci.txt"" ], jarLibs: [ ""TestData/test1.jar"" ], storageLinkedServices: [ { referenceName: ""storageLinkedService2"", type: ""LinkedServiceReference"" } ], defines: { PropertyBagPropertyName1: ""PropertyBagValue1"" } }, linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample("HDInsightSpark")] public const string HDInsightSparkPipeline = @" { name: ""My HDInsightSpark pipeline"", properties: { description : ""HDInsightSpark pipeline description"", activities: [ { name: ""TestActivity"", description: ""Test activity description"", type: ""HDInsightSpark"", typeProperties: { rootPath: ""release\\1.0"", entryFilePath: ""main.py"", sparkJobLinkedService: { referenceName: ""storageLinkedService1"", type: ""LinkedServiceReference"" }, className:""main"", arguments: [ ""arg1"", ""arg2"" ], sparkConfig: { ""spark.yarn.appMasterEnv.PYSPARK_DRIVER_PYTHON"" : ""python3"" }, proxyUser: ""user1"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyCassandraToBlob = @"{ ""name"": ""Pipeline"", ""properties"": { ""activities"": [ { ""name"": ""blob-table"", ""type"": ""Copy"", ""inputs"": [ { ""referenceName"": ""Table-Blob"", ""type"": ""DatasetReference"" } ], ""outputs"": [ { ""referenceName"": ""Table-AzureTable"", ""type"": ""DatasetReference"" } ], ""policy"": { }, ""typeProperties"": { ""source"": { ""type"": ""CassandraSource"", ""query"":""select * from table"", ""consistencyLevel"":""TWO"", }, ""sink"": { ""type"": ""AzureTableSink"", ""writeBatchSize"": 1000000, ""azureTableDefaultPartitionKeyValue"": ""defaultParitionKey"" }, } } ] } } "; [JsonSample(version: "Copy")] public const string CopyMongoDbToBlob = @"{ name: ""MongoDbToBlobPipeline"", properties: { activities: [ { name: ""CopyFromMongoDbToBlob"", type: ""Copy"", inputs: [ { referenceName: ""MongoDbDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""AzureBlobOut"", type: ""DatasetReference"" } ], policy: { }, typeProperties: { source: { type: ""MongoDbSource"", query:""select * from collection"" }, sink: { type: ""BlobSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"" } } } ] } } "; [JsonSample(version: "Copy")] // note original had internal DataInsightTranslator, removed that public const string CopySqlToBlobWithCopyBehaviorProperty = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SQL to Blob with CopyBehavior property"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SqlSource"", sourceRetryCount: 2, sourceRetryWait: ""00:00:01"", sqlReaderQuery: ""$EncryptedString$MyEncryptedQuery"", sqlReaderStoredProcedureName: ""$EncryptedString$MyEncryptedQuery"", storedProcedureParameters: { ""stringData"": { value: ""tr3"" }, ""id"": { value: ""$$MediaTypeNames.Text.Format('{0:yyyy}', SliceStart)"", type: ""Int""} } }, sink: { type: ""BlobSink"", blobWriterAddHeader: true, writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", copyBehavior: ""PreserveHierarchy"" } }, inputs: [ { referenceName: ""InputSqlDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputBlobDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyBlobToFileSystemSink = @" { name: ""MyPipelineName"", properties: { description : ""Copy from Blob to Azure Queue"", activities: [ { type: ""Copy"", name: ""MyActivityName"", typeProperties: { source: { type: ""BlobSource"", sourceRetryCount: 2, sourceRetryWait: ""00:00:01"", treatEmptyAsNull: false }, sink: { type: ""FileSystemSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"" } }, inputs: [ { referenceName: ""RawBlob"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""ProcessedBlob"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyAzureTableToSql = @" { name: ""MyPipelineName"", properties: { description : ""Copy from Azure table to Sql"", activities: [ { type: ""Copy"", name: ""MyActivityName"", typeProperties: { source: { type: ""AzureTableSource"", sourceRetryCount: 2, sourceRetryWait: ""00:00:01"", azureTableSourceQuery: ""$$Text.Format('PartitionKey eq \\'ContosoSampleDevice\\' and RowKey eq \\'{0:yyyy-MM-ddTHH:mm:ss.fffffffZ}!{1:yyyy-MM-ddTHH:mm:ss.fffffffZ}\\'', Time.AddMinutes(SliceStart, -10), Time.AddMinutes(SliceStart, -9))"", azureTableSourceIgnoreTableNotFound: false }, sink: { type: ""SqlSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", sinkRetryCount: 3, sinkRetryWait: ""00:00:01"", sqlWriterStoredProcedureName: ""MySprocName"", sqlWriterTableType: ""MyTableType"" } }, inputs: [ { referenceName: ""RawBlob"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""ProcessedBlob"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyBlobToAzureQueue = @" { name: ""MyPipelineName"", properties: { description : ""Copy from Blob to Azure Queue"", activities: [ { type: ""Copy"", name: ""MyActivityName"", typeProperties: { source: { type: ""BlobSource"", sourceRetryCount: 2, sourceRetryWait: ""00:00:01"", treatEmptyAsNull: false }, sink: { type: ""AzureQueueSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", sinkRetryCount: 3, sinkRetryWait: ""00:00:01"" } }, inputs: [ { referenceName: ""RawBlob"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""ProcessedBlob"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopySqlDWToSqlDW = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SQL DW to SQL DW"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SqlDWSource"", sqlReaderQuery: ""$EncryptedString$MyEncryptedQuery"", sqlReaderStoredProcedureName: ""CopyTestSrcStoredProcedureWithParameters"", storedProcedureParameters: { ""stringData"": { value: ""test"", type: ""String""}, ""id"": { value: ""3"", type: ""Int""} } }, sink: { type: ""SqlDWSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", allowPolyBase: true, polyBaseSettings: { rejectType: ""percentage"", rejectValue: 20.42341, rejectSampleValue: 80, useTypeDefault: true } } }, inputs: [ { referenceName: ""InputSqlDWDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputSqlDWDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopySqlDWToSqlDWWithIntegerRejectValue = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SQL DW to SQL DW"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SqlDWSource"", sqlReaderQuery: ""$EncryptedString$MyEncryptedQuery"", sqlReaderStoredProcedureName: ""CopyTestSrcStoredProcedureWithParameters"", storedProcedureParameters: { ""stringData"": { value: ""test"", type: ""String""}, ""id"": { value: ""3"", type: ""Int""} } }, sink: { type: ""SqlDWSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", allowPolyBase: true, polyBaseSettings: { rejectType: ""percentage"", rejectValue: 20, rejectSampleValue: 80, useTypeDefault: true } } }, inputs: [ { referenceName: ""InputSqlDWDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputSqlDWDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopySqlDWToSqlDWWithDummyZeroRejectValue = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SQL DW to SQL DW"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SqlDWSource"", sqlReaderQuery: ""$EncryptedString$MyEncryptedQuery"", sqlReaderStoredProcedureName: ""CopyTestSrcStoredProcedureWithParameters"", storedProcedureParameters: { ""stringData"": { value: ""test"", type: ""String""}, ""id"": { value: ""3"", type: ""Int""} } }, sink: { type: ""SqlDWSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", allowPolyBase: true, polyBaseSettings: { rejectType: ""percentage"", rejectValue: 20.0000000, rejectSampleValue: 80, useTypeDefault: true } } }, inputs: [ { referenceName: ""InputSqlDWDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputSqlDWDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopySqlDWToSqlDW_WithoutPolybaseSettings = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SQL DW to SQL DW"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SqlDWSource"", sqlReaderQuery: ""$EncryptedString$MyEncryptedQuery"" }, sink: { type: ""SqlDWSink"", preCopyScript: ""script"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"" } }, inputs: [ { referenceName: ""InputSqlDWDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputSqlDWDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopyAdlsToAdls = @" { name: ""MyPipelineName"", properties: { description : ""Copy from Azure Data Lake Store to Azure Data Lake Store"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""AzureDataLakeStoreSource"", recursive: ""true"" }, sink: { type: ""AzureDataLakeStoreSink"", copyBehavior: ""FlattenHierarchy"" } }, inputs: [ { referenceName: ""InputAdlsDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputAdlsDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopyHttpSourceToAzureSearchIndexSink = @" { name: ""MyPipelineName"", properties: { description : ""Copy from Http to Azure Search Index"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""HttpSource"", httpRequestTimeout: ""01:00:00"" }, sink: { type: ""AzureSearchIndexSink"", writeBehavior: ""Upload"" } }, inputs: [ { referenceName: ""InputHttpDA"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputAzureSearchIndexDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "HDInsightStreaming")] // original had a propertyBagKeys for PropertyBagPropertyName1 public const string StreamingWithDefines = @" { name: ""HadoopStreamingPipeline"", properties: { description : ""Hadoop Streaming Demo"", activities: [ { name: ""HadoopStreamingActivity"", description: ""HadoopStreamingActivity"", type: ""HDInsightStreaming"", linkedServiceName: { referenceName: ""HDInsightLinkedService"", type: ""LinkedServiceReference"" }, typeProperties: { mapper: ""cat.exe"", reducer: ""wc.exe"", input: ""example/data/gutenberg/davinci.txt"", output: ""example/data/StreamingOutput/wc.txt"", filePaths: [ ""aureleu/example/apps/wc.exe"" , ""aureleu/example/apps/cat.exe"" ], defines: { PropertyBagPropertyName1: ""PropertyBagValue1"" }, fileLinkedService : { referenceName: ""StorageLinkedService"", type: ""LinkedServiceReference"" } }, policy: { retry: 1, timeout: ""01:00:00"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyFileSystemSourceToFileSystemSink = @" { name: ""MyPipelineName"", properties: { description : ""Copy from File to File"", activities: [ { type: ""Copy"", name: ""MyActivityName"", typeProperties: { source: { type: ""FileSystemSource"", recursive: false }, sink: { type: ""FileSystemSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", copyBehavior: ""FlattenHierarchy"" } }, inputs: [ { referenceName: ""RawFileSource"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""ProcessedFileSink"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyPipelineUsingStaging = @"{ ""name"": ""Pipeline"", ""properties"": { ""activities"": [ { ""name"": ""blob-table"", ""type"": ""Copy"", ""inputs"": [ { ""referenceName"": ""Table-Blob"", type: ""DatasetReference"" } ], ""outputs"": [ { ""referenceName"": ""Table-AzureTable"", type: ""DatasetReference"" } ], ""policy"": { }, ""typeProperties"": { ""source"": { ""type"": ""BlobSource"" }, ""sink"": { ""type"": ""AzureTableSink"", ""writeBatchSize"": 1000000, ""writeBatchTimeout"": ""01:00:00"", ""azureTableDefaultPartitionKeyValue"": ""defaultParitionKey"" }, ""enableStaging"": true, ""stagingSettings"": { ""linkedServiceName"": { referenceName: ""MyStagingBlob"", type: ""LinkedServiceReference"" }, ""path"": ""stagingcontainer/path"", ""enableCompression"": true } } } ] } } "; [JsonSample(version: "Copy")] public const string CopyFileSystemSourceToBlobSink = @" { name: ""MyPipelineName"", properties: { description : ""Copy from File to Blob"", activities: [ { type: ""Copy"", name: ""MyActivityName"", typeProperties: { source: { type: ""FileSystemSource"", recursive: true }, sink: { type: ""BlobSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", copyBehavior: ""FlattenHierarchy"" } }, inputs: [ { referenceName: ""RawFileSource"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobSink"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } } "; [JsonSample(version: "Copy")] public const string CopyHdfsSourceToBlobSink = @" { name: ""MyPipelineName"", properties: { description : ""Copy from HDFS File to Blob"", activities: [ { type: ""Copy"", name: ""MyActivityName"", typeProperties: { source: { type: ""HdfsSource"", distcpSettings: { resourceManagerEndpoint: ""fakeEndpoint"", tempScriptPath: ""fakePath"", distcpOptions: ""fakeOptions"" } }, sink: { type: ""BlobSink"", writeBatchSize: 1000000, writeBatchTimeout: ""01:00:00"", copyBehavior: ""FlattenHierarchy"" } }, inputs: [ { referenceName: ""RawFileSource"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobSink"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } }"; [JsonSample(version: "Lookup")] public const string LookupBlobSource = @" { name: ""MyPipelineName"", properties: { description : ""Lookup data from Blob"", activities: [ { type: ""Lookup"", name: ""MyActivityName"", typeProperties: { source: { type: ""BlobSource"" }, dataset: { referenceName: ""MyDataset"", type: ""DatasetReference"" } } } ] } } "; [JsonSample(version: "Lookup")] public const string LookupBlobSourceWithAllRows = @" { name: ""MyPipelineName"", properties: { description : ""Lookup data from Blob with all rows"", activities: [ { type: ""Lookup"", name: ""MyActivityName"", typeProperties: { source: { type: ""BlobSource"" }, dataset: { referenceName: ""MyDataset"", type: ""DatasetReference"" }, firstRowOnly: false } } ] } }"; [JsonSample(version: "Lookup")] public const string LookupAzureSqlSource = @" { name: ""MyPipelineName"", properties: { description : ""Lookup data from Azure Sql"", activities: [ { type: ""Lookup"", name: ""MyActivityName"", typeProperties: { source: { type: ""SqlSource"", sqlReaderQuery: ""select * from MyTable"" }, dataset: { referenceName: ""MyDataset"", type: ""DatasetReference"" } } } ] } } "; [JsonSample(version: "Lookup")] public const string LookupAzureTableSource = @" { name: ""MyPipelineName"", properties: { description : ""Lookup data from Azure Table"", activities: [ { type: ""Lookup"", name: ""MyActivityName"", typeProperties: { source: { type: ""AzureTableSource"", azureTableSourceQuery: ""PartitionKey eq 'SomePartition'"" }, dataset: { referenceName: ""MyDataset"", type: ""DatasetReference"" } } } ] } } "; [JsonSample(version: "Lookup")] public const string LookupFileSource = @" { name: ""MyPipelineName"", properties: { description : ""Lookup data from File"", activities: [ { type: ""Lookup"", name: ""MyActivityName"", typeProperties: { source: { type: ""FileSystemSource"" }, dataset: { referenceName: ""MyDataset"", type: ""DatasetReference"" } } } ] } } "; [JsonSample] public const string GetMetadataActivity = @" { ""name"": ""MyPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""GetMetadata"", ""typeProperties"": { ""fieldList"" : [""field""], ""dataset"": { ""referenceName"": ""MyDataset"", ""type"": ""DatasetReference"" } } } ] } } "; [JsonSample] public const string WebActivityNoAuth = @" { name: ""MyWebPipeline"", properties: { activities: [ { name: ""MyAnonymousWebActivity"", type: ""WebActivity"", typeProperties: { method: ""get"", url: ""http://www.bing.com"" } } ] } } "; [JsonSample(version: "Custom")] public const string CustomActivity = @" { name: ""MyPipeline"", properties: { description : ""Custom activity sample"", activities: [ { type: ""Custom"", name: ""MyActivityName"", ""linkedServiceName"": { ""referenceName"": ""HDILinkedService"", ""type"": ""LinkedServiceReference"" }, typeProperties: { ""command"": ""Echo Hello World!"", ""folderPath"":""Test Folder"", ""resourceLinkedService"": { ""referenceName"": ""imagestoreLinkedService"", ""type"": ""LinkedServiceReference"" }, ""referenceObjects"":{ ""linkedServices"":[ { ""referenceName"": ""HDILinkedService"", ""type"": ""LinkedServiceReference"" } ], ""datasets"":[ { ""referenceName"": ""MyDataset"", ""type"": ""DatasetReference"" }] }, ""extendedProperties"": { ""PropertyBagPropertyName1"": ""PropertyBagValue1"", ""propertyBagPropertyName2"": ""PropertyBagValue2"", ""dateTime1"": ""2015-04-12T12:13:14Z"", } } } ] } } "; [JsonSample] public const string WebActivityWithDatasets = @" { ""name"": ""MyWebPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyAnonymousWebActivity"", ""type"": ""WebActivity"", ""typeProperties"": { ""method"": ""get"", ""url"": ""http://www.bing.com"", ""headers"": { ""Content-Type"": ""application/json"", ""activityName"": ""activityName"" }, ""datasets"":[ { ""referenceName"": ""MyDataset"", ""type"": ""DatasetReference"" } ], ""linkedServices"":[ { ""referenceName"": ""MyStagingBlob"", ""type"": ""LinkedServiceReference"" } ] } } ] } } "; [JsonSample] public const string IfPipeline = @" { ""name"": ""MyForeachPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyIfActivity"", ""type"": ""IfCondition"", ""typeProperties"": { ""expression"": { ""value"": ""@bool(pipeline().parameters.routeSelection)"", ""type"": ""Expression"" }, ""ifTrueActivities"":[ { ""name"": ""MyActivity"", ""type"": ""GetMetadata"", ""typeProperties"": { ""fieldList"" : [""field""], ""dataset"": { ""referenceName"": ""MyDataset"", ""type"": ""DatasetReference"" } } } ] } } ] } } "; [JsonSample] public const string ForeachPipeline= @" { ""name"": ""MyForeachPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyForeachActivity"", ""type"": ""ForEach"", ""typeProperties"": { ""isSequential"": true, ""items"": { ""value"": ""@pipeline().parameters.OutputBlobNameList"", ""type"": ""Expression"" }, ""activities"":[ { ""name"": ""MyActivity"", ""type"": ""GetMetadata"", ""typeProperties"": { ""fieldList"" : [""field""], ""dataset"": { ""referenceName"": ""MyDataset"", ""type"": ""DatasetReference"" } } } ] } } ] } } "; [JsonSample] public const string UntilWaitPipeline = @" { ""name"": ""MyUntilWaitPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyUntilActivity"", ""type"": ""Until"", ""typeProperties"": { ""expression"": { ""value"": ""@bool(equals(activity('MyActivity').status, 'Succeeded'))"", ""type"": ""Expression"" }, ""activities"":[ { ""name"": ""MyActivity"", ""type"": ""GetMetadata"", ""typeProperties"": { ""fieldList"" : [""field""], ""dataset"": { ""referenceName"": ""MyDataset"", ""type"": ""DatasetReference"" } } }, { ""name"": ""MyWaitActivity"", ""type"": ""Wait"", ""typeProperties"": { ""waitTimeInSeconds"" : 300, } } ] } } ] } } "; [JsonSample] public const string AzureMLUpdateResourcePipeline = @" { name: ""MyAzureMLUpdateResourcePipeline"", properties: { description : ""MyAzureMLUpdateResourcePipeline pipeline description"", activities: [ { name: ""TestActivity"", description: ""Test activity description"", type: ""AzureMLUpdateResource"", typeProperties: { ""trainedModelName"": ""Training Exp for ADF ML TiP tests[trained model]"", ""trainedModelLinkedServiceName"": { ""type"": ""LinkedServiceReference"", ""referenceName"": ""StorageLinkedService"" }, ""trainedModelFilePath"": ""azuremltesting/testInput.ilearner"" }, linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" } } ] } }"; [JsonSample] public const string AzureMLBatchExecutionPipeline = @" { ""name"": ""MyAzureMLPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""AzureMLBatchExecution"", ""typeProperties"": { ""webServiceInputs"": { ""input1"": { ""linkedServiceName"": { ""type"": ""LinkedServiceReference"", ""referenceName"": ""StorageLinkedService"" }, ""filePath"": ""azuremltesting/IrisInput/Two Class Data.1.arff"" } }, ""webServiceOutputs"": { ""output1"": { ""linkedServiceName"": { ""type"": ""LinkedServiceReference"", ""referenceName"": ""StorageLinkedService"" }, ""filePath"": ""azuremltesting/categorized/##folderPath##/result.csv"" } } }, ""linkedServiceName"":{ ""type"": ""LinkedServiceReference"", ""referenceName"": ""UpdatableDecisionTreeLinkedService"" } } ] } }"; [JsonSample] public const string DataLakeAnalyticsUSqlnPipeline = @" { ""name"": ""MyAzureDataLakeAnalyticsActivity"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""DataLakeAnalyticsU-SQL"", ""typeProperties"": { ""scriptPath"": ""fakepath"", ""scriptLinkedService"": { ""type"": ""LinkedServiceReference"", ""referenceName"": ""MyAzureStorageLinkedService"" }, ""degreeOfParallelism"": 3, ""priority"": 100, ""parameters"": { ""in"": ""/Samples/Data/SearchLog.tsv"", ""out"": ""wasb://output@sfadfteststorage.blob.core.windows.net/Result.tsv"" } }, ""linkedServiceName"":{ ""type"": ""LinkedServiceReference"", ""referenceName"": ""MyAzureDataLakeAnalyticsLinkedService"" } } ] } }"; [JsonSample(version: "Copy")] public const string CopyAzureMySqlToBlob = @"{ name: ""AzureMySqlToBlobPipeline"", properties: { activities: [ { name: ""CopyFromAzureMySqlToBlob"", type: ""Copy"", inputs: [ { referenceName: ""AzureMySQLDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""AzureBlobOut"", type: ""DatasetReference"" } ], policy: { }, typeProperties: { source: { type: ""AzureMySqlSource"", query:""select * from azuremysqltable"" }, sink: { type: ""BlobSink"" } } } ] } } "; [JsonSample(version: "Copy")] public const string CopyFromSalesforceToSalesforce = @" { ""name"": ""SalesforceToSalesforce"", ""properties"": { ""activities"": [ { ""name"": ""CopyFromSalesforceToSalesforce"", ""type"": ""Copy"", ""inputs"": [ { ""referenceName"": ""SalesforceSourceDataset"", ""type"": ""DatasetReference"" } ], ""outputs"": [ { ""referenceName"": ""SalesforceSinkDataset"", ""type"": ""DatasetReference"" } ], ""typeProperties"": { ""source"": { ""type"": ""SalesforceSource"", ""query"":""select Id from table"", ""readBehavior"": ""QueryAll"" }, ""sink"": { ""type"": ""SalesforceSink"", ""writeBehavior"": ""Insert"", ""ignoreNullValues"": false } } } ] } }"; [JsonSample(version: "Copy")] public const string CopyFromDynamicsToDynamics = @"{ name: ""DynamicsToDynamicsPipeline"", properties: { activities: [ { name: ""CopyFromDynamicsToDynamics"", type: ""Copy"", inputs: [ { referenceName: ""DynamicsIn"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""DynamicsOut"", type: ""DatasetReference"" } ], policy: { }, typeProperties: { source: { type: ""DynamicsSource"", query:""fetchXml query"" }, sink: { type: ""DynamicsSink"", writeBehavior: ""Upsert"", ignoreNullValues: false } } } ] } } "; [JsonSample(version: "Copy")] public const string CopySapC4CToAdls = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SAP Cloud for Customer to Azure Data Lake Store"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SapCloudForCustomerSource"", query: ""$select=Column0"" }, sink: { type: ""AzureDataLakeStoreSink"", copyBehavior: ""FlattenHierarchy"" } }, inputs: [ { referenceName: ""InputSapC4C"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputAdlsDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopyAmazonMWSToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyAmazonMWSToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""AmazonMWSSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""AmazonMWSDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyAzurePostgreSqlToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyAzurePostgreSqlToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""AzurePostgreSqlSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""AzurePostgreSqlDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyConcurToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyConcurToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""ConcurSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""ConcurDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyCouchbaseToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyCouchbaseToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""CouchbaseSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""CouchbaseDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyDrillToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyDrillToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""DrillSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""DrillDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyEloquaToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyEloquaToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""EloquaSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""EloquaDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyGoogleBigQueryToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyGoogleBigQueryToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""GoogleBigQuerySource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""GoogleBigQueryDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyGreenplumToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyGreenplumToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""GreenplumSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""GreenplumDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyHBaseToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyHBaseToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""HBaseSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""HBaseDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyHiveToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyHiveToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""HiveSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""HiveDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyHubspotToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyHubspotToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""HubspotSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""HubspotDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyImpalaToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyImpalaToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""ImpalaSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""ImpalaDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyJiraToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyJiraToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""JiraSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""JiraDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyMagentoToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyMagentoToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""MagentoSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""MagentoDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyMariaDBToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyMariaDBToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""MariaDBSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""MariaDBDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyMarketoToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyMarketoToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""MarketoSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""MarketoDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyPaypalToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyPaypalToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""PaypalSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""PaypalDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyPhoenixToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyPhoenixToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""PhoenixSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""PhoenixDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyPrestoToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyPrestoToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""PrestoSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""PrestoDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyQuickBooksToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyQuickBooksToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""QuickBooksSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""QuickBooksDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyServiceNowToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyServiceNowToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""ServiceNowSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""ServiceNowDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyShopifyToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyShopifyToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""ShopifySource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""ShopifyDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopySparkToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopySparkToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""SparkSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""SparkDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopySquareToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopySquareToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""SquareSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""SquareDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyXeroToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyXeroToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""XeroSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""XeroDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyZohoToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyZohoToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""ZohoSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""ZohoDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample] public const string CopyFromBlobToSapC4C = @"{ name: ""MyPipelineName"", properties: { activities: [ { name: ""CopyBlobToSapC4c"", type: ""Copy"", typeProperties: { source: { type: ""BlobSource"" }, sink: { type: ""SapCloudForCustomerSink"", writeBehavior: ""Insert"", writeBatchSize: 50 }, enableSkipIncompatibleRow: true, parallelCopies: 32, cloudDataMovementUnits: 16, enableSkipIncompatibleRow: true, redirectIncompatibleRowSettings: { linkedServiceName: { referenceName: ""AzureBlobLinkedService"", type: ""LinkedServiceReference"" }, path: ""redirectcontainer/erroroutput"" } }, inputs: [ { referenceName: ""SourceBlobDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""SapC4CDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopySapEccToAdls = @" { name: ""MyPipelineName"", properties: { description : ""Copy from SAP ECC to Azure Data Lake Store"", activities: [ { type: ""Copy"", name: ""TestActivity"", description: ""Test activity description"", typeProperties: { source: { type: ""SapEccSource"", query: ""$top=1"" }, sink: { type: ""AzureDataLakeStoreSink"", copyBehavior: ""FlattenHierarchy"" } }, inputs: [ { referenceName: ""InputSapEcc"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""OutputAdlsDA"", type: ""DatasetReference"" } ], linkedServiceName: { referenceName: ""MyLinkedServiceName"", type: ""LinkedServiceReference"" }, policy: { retry: 3, timeout: ""00:00:05"", } } ] } } "; [JsonSample(version: "Copy")] public const string CopyNetezzaToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyNetezzaToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""NetezzaSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""NetezzaDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample(version: "Copy")] public const string CopyVerticaToBlob = @" { name: ""MyPipelineName"", properties: { activities: [ { type: ""Copy"", name: ""CopyVerticaToBlob"", description: ""Test activity description"", typeProperties: { source: { type: ""VerticaSource"", query: ""select * from a table"" }, sink: { type: ""BlobSink"" } }, inputs: [ { referenceName: ""VerticaDataset"", type: ""DatasetReference"" } ], outputs: [ { referenceName: ""BlobDataset"", type: ""DatasetReference"" } ] } ] } }"; [JsonSample] public const string DatabrickNotebookActivity = @" { ""name"": ""MyPipeline"", ""properties"": { ""activities"": [ { ""name"": ""MyActivity"", ""type"": ""DatabricksNotebook"", ""typeProperties"": { ""notebookPath"": ""/testing"", ""baseParameters"": { ""test"":""test"" } }, ""linkedServiceName"": { ""referenceName"": ""MyLinkedServiceName"", ""type"": ""LinkedServiceReference"" } } ] } } "; } }
yaakoviyun/azure-sdk-for-net
src/SDKs/DataFactory/DataFactory.Tests/JsonSamples/PipelineJsonSamples.cs
C#
mit
98,956
Package.describe({ name: 'violet:test-support', version: '0.1.0', summary: 'libraries and helpers that are used to run tests', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); var packages =[ 'mike:mocha-package@0.5.8', 'practicalmeteor:sinon@1.14.1_2', 'violet:user@0.1.0' ]; api.use(packages); api.imply(packages); api.addFiles([ 'helpers.js' ]); api.export('expect'); api.export('testHelpers'); });
violetjs/violet
packages/test-support/package.js
JavaScript
mit
490
<?php namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Form\EventListener; use Oro\Bundle\EntityConfigBundle\Config\Config; use Oro\Bundle\EntityConfigBundle\Config\Id\EntityConfigId; use Oro\Bundle\EntityExtendBundle\Form\EventListener\EnumFieldConfigSubscriber; use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper; class EnumFieldConfigSubscriberTest extends \PHPUnit_Framework_TestCase { /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $configManager; /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $translator; /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $enumSynchronizer; /** @var EnumFieldConfigSubscriber */ protected $subscriber; public function setUp() { $this->configManager = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Config\ConfigManager') ->disableOriginalConstructor() ->getMock(); $this->translator = $this->createMock('Symfony\Component\Translation\TranslatorInterface'); $this->enumSynchronizer = $this->getMockBuilder('Oro\Bundle\EntityExtendBundle\Tools\EnumSynchronizer') ->disableOriginalConstructor() ->getMock(); $this->translator->expects($this->any()) ->method('trans') ->will($this->returnArgument(0)); $this->subscriber = new EnumFieldConfigSubscriber( $this->configManager, $this->translator, $this->enumSynchronizer ); } public function testPreSetDataForEntityConfigModel() { $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\EntityConfigModel') ->disableOriginalConstructor() ->getMock(); $event = $this->getFormEventMock($configModel); $event->expects($this->never()) ->method('setData'); $this->subscriber->preSetData($event); } public function testPreSetDataForNotEnumFieldType() { $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue('manyToOne')); $event = $this->getFormEventMock($configModel); $event->expects($this->never()) ->method('setData'); $this->subscriber->preSetData($event); } /** * @dataProvider enumTypeProvider */ public function testPreSetDataForNewEnum($dataType) { $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue($dataType)); $configModel->expects($this->once()) ->method('toArray') ->with('enum') ->will($this->returnValue(['enum_name' => 'Test Enum'])); $event = $this->getFormEventMock($configModel); $event->expects($this->never()) ->method('setData'); $this->subscriber->preSetData($event); } /** * @dataProvider enumTypeProvider */ public function testPreSetDataForExistingEnum($dataType) { $enumCode = 'test_enum'; $enumLabel = ExtendHelper::getEnumTranslationKey('label', $enumCode); $enumValueClassName = ExtendHelper::buildEnumValueClassName($enumCode); $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue($dataType)); $configModel->expects($this->once()) ->method('toArray') ->with('enum') ->will($this->returnValue(['enum_code' => $enumCode])); $event = $this->getFormEventMock($configModel); $initialData = []; $enumOptions = [ ['id' => 'val1', 'label' => 'Value 1', 'priority' => 1], ]; $expectedData = [ 'enum' => [ 'enum_name' => $enumLabel, 'enum_public' => true, 'enum_options' => $enumOptions, ] ]; $event->expects($this->once()) ->method('getData') ->will($this->returnValue($initialData)); $enumConfig = new Config(new EntityConfigId('enum', $enumValueClassName)); $enumConfig->set('public', true); $this->enumSynchronizer->expects($this->once()) ->method('getEnumOptions') ->with($enumValueClassName) ->will($this->returnValue($enumOptions)); $enumConfigProvider = $this->getConfigProviderMock(); $this->configManager->expects($this->once()) ->method('getProvider') ->with('enum') ->will($this->returnValue($enumConfigProvider)); $enumConfigProvider->expects($this->once()) ->method('hasConfig') ->with($enumValueClassName) ->will($this->returnValue(true)); $enumConfigProvider->expects($this->once()) ->method('getConfig') ->with($enumValueClassName) ->will($this->returnValue($enumConfig)); $event->expects($this->once()) ->method('setData') ->with($expectedData); $this->subscriber->preSetData($event); } public function testPostSubmitForEntityConfigModel() { $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\EntityConfigModel') ->disableOriginalConstructor() ->getMock(); $event = $this->getFormEventMock($configModel); $event->expects($this->never()) ->method('setData'); $this->subscriber->postSubmit($event); } public function testPostSubmitForNotEnumFieldType() { $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue('manyToOne')); $event = $this->getFormEventMock($configModel); $event->expects($this->never()) ->method('setData'); $this->subscriber->postSubmit($event); } /** * @dataProvider enumTypeProvider */ public function testPostSubmitForNotValidForm($dataType) { $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue($dataType)); $form = $this->createMock('Symfony\Component\Form\Test\FormInterface'); $form->expects($this->once()) ->method('isValid') ->will($this->returnValue(false)); $event = $this->getFormEventMock($configModel, $form); $event->expects($this->never()) ->method('setData'); $this->subscriber->postSubmit($event); } /** * @dataProvider enumTypeProvider */ public function testPostSubmitForNewEnum($dataType) { $enumCode = 'test_enum'; $enumName = 'Test Enum'; $enumValueClassName = ExtendHelper::buildEnumValueClassName($enumCode); $locale = 'fr'; $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->never()) ->method('getId'); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue($dataType)); $form = $this->createMock('Symfony\Component\Form\Test\FormInterface'); $form->expects($this->once()) ->method('isValid') ->will($this->returnValue(true)); $event = $this->getFormEventMock($configModel, $form); $enumOptions = [ ['id' => 'val1', 'label' => 'Value 1', 'priority' => 1], ['id' => 'val1', 'label' => 'Value 1', 'priority' => 4], ['label' => 'Value 1', 'priority' => 2], ]; $submittedData = [ 'enum' => [ 'enum_name' => $enumName, 'enum_public' => true, 'enum_options' => $enumOptions ] ]; $expectedData = [ 'enum' => [ 'enum_name' => $enumName, 'enum_public' => true, 'enum_options' => [ ['id' => 'val1', 'label' => 'Value 1', 'priority' => 1], ['label' => 'Value 1', 'priority' => 2], ['id' => 'val1', 'label' => 'Value 1', 'priority' => 3], ], 'enum_locale' => $locale ] ]; $event->expects($this->once()) ->method('getData') ->will($this->returnValue($submittedData)); $configModel->expects($this->once()) ->method('toArray') ->with('enum') ->will($this->returnValue([])); $this->translator->expects($this->once()) ->method('getLocale') ->will($this->returnValue($locale)); $enumConfigProvider = $this->getConfigProviderMock(); $this->configManager->expects($this->once()) ->method('getProvider') ->with('enum') ->will($this->returnValue($enumConfigProvider)); $enumConfigProvider->expects($this->once()) ->method('hasConfig') ->with($enumValueClassName) ->will($this->returnValue(false)); $event->expects($this->once()) ->method('setData') ->with($expectedData); $this->subscriber->postSubmit($event); } /** * @dataProvider enumTypeProvider */ public function testPostSubmitForNewEnumWithoutNameAndPublic($dataType) { $entityClassName = 'Test\Entity'; $fieldName = 'testField'; $enumCode = ExtendHelper::generateEnumCode($entityClassName, $fieldName); $enumValueClassName = ExtendHelper::buildEnumValueClassName($enumCode); $locale = 'fr'; $entityConfigModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\EntityConfigModel') ->disableOriginalConstructor() ->getMock(); $entityConfigModel->expects($this->once()) ->method('getClassName') ->will($this->returnValue($entityClassName)); $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->never()) ->method('getId'); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue($dataType)); $configModel->expects($this->once()) ->method('getEntity') ->will($this->returnValue($entityConfigModel)); $configModel->expects($this->once()) ->method('getFieldName') ->will($this->returnValue($fieldName)); $form = $this->createMock('Symfony\Component\Form\Test\FormInterface'); $form->expects($this->once()) ->method('isValid') ->will($this->returnValue(true)); $event = $this->getFormEventMock($configModel, $form); $enumOptions = [ ['id' => 'val1', 'label' => 'Value 1', 'priority' => 1], ]; $submittedData = [ 'enum' => [ 'enum_options' => $enumOptions ] ]; $expectedData = [ 'enum' => [ 'enum_options' => $enumOptions, 'enum_locale' => $locale ] ]; $event->expects($this->once()) ->method('getData') ->will($this->returnValue($submittedData)); $configModel->expects($this->once()) ->method('toArray') ->with('enum') ->will($this->returnValue([])); $this->translator->expects($this->once()) ->method('getLocale') ->will($this->returnValue($locale)); $enumConfigProvider = $this->getConfigProviderMock(); $this->configManager->expects($this->once()) ->method('getProvider') ->with('enum') ->will($this->returnValue($enumConfigProvider)); $enumConfigProvider->expects($this->once()) ->method('hasConfig') ->with($enumValueClassName) ->will($this->returnValue(false)); $event->expects($this->once()) ->method('setData') ->with($expectedData); $this->subscriber->postSubmit($event); } /** * @dataProvider enumTypeProvider */ public function testPostSubmitForExistingEnum($dataType) { $enumCode = 'test_enum'; $enumName = 'Test Enum'; $enumPublic = false; $enumValueClassName = ExtendHelper::buildEnumValueClassName($enumCode); $locale = 'fr'; $configModel = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Entity\FieldConfigModel') ->disableOriginalConstructor() ->getMock(); $configModel->expects($this->once()) ->method('getId') ->will($this->returnValue(123)); $configModel->expects($this->once()) ->method('getType') ->will($this->returnValue($dataType)); $form = $this->createMock('Symfony\Component\Form\Test\FormInterface'); $form->expects($this->once()) ->method('isValid') ->will($this->returnValue(true)); $event = $this->getFormEventMock($configModel, $form); $enumOptions = [ ['id' => 'val1', 'label' => 'Value 1', 'priority' => 1], ]; $submittedData = [ 'enum' => [ 'enum_name' => $enumName, 'enum_public' => $enumPublic, 'enum_options' => $enumOptions ] ]; $expectedData = [ 'enum' => [] ]; $event->expects($this->once()) ->method('getData') ->will($this->returnValue($submittedData)); $configModel->expects($this->once()) ->method('toArray') ->with('enum') ->will($this->returnValue(['enum_code' => $enumCode])); $this->translator->expects($this->once()) ->method('getLocale') ->will($this->returnValue($locale)); $enumConfigProvider = $this->getConfigProviderMock(); $this->configManager->expects($this->once()) ->method('getProvider') ->with('enum') ->will($this->returnValue($enumConfigProvider)); $enumConfigProvider->expects($this->once()) ->method('hasConfig') ->with($enumValueClassName) ->will($this->returnValue(true)); $this->enumSynchronizer->expects($this->once()) ->method('applyEnumNameTrans') ->with($enumCode, $enumName, $locale); $this->enumSynchronizer->expects($this->once()) ->method('applyEnumOptions') ->with($enumValueClassName, $enumOptions, $locale); $this->enumSynchronizer->expects($this->once()) ->method('applyEnumEntityOptions') ->with($enumValueClassName, $enumPublic); $event->expects($this->once()) ->method('setData') ->with($expectedData); $this->subscriber->postSubmit($event); } public function enumTypeProvider() { return [ ['enum'], ['multiEnum'], ]; } /** * @param mixed $configModel * @param \PHPUnit_Framework_MockObject_MockObject|null $form * @return \PHPUnit_Framework_MockObject_MockObject */ protected function getFormEventMock($configModel, $form = null) { if (!$form) { $form = $this->createMock('Symfony\Component\Form\Test\FormInterface'); } $formConfig = $this->createMock('Symfony\Component\Form\FormConfigInterface'); $form->expects($this->once()) ->method('getConfig') ->will($this->returnValue($formConfig)); $formConfig->expects($this->once()) ->method('getOption') ->with('config_model') ->will($this->returnValue($configModel)); $event = $this->getMockBuilder('Symfony\Component\Form\FormEvent') ->disableOriginalConstructor() ->getMock(); $event->expects($this->once()) ->method('getForm') ->will($this->returnValue($form)); return $event; } /** * @return \PHPUnit_Framework_MockObject_MockObject */ protected function getConfigProviderMock() { return $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider') ->disableOriginalConstructor() ->getMock(); } }
Djamy/platform
src/Oro/Bundle/EntityExtendBundle/Tests/Unit/Form/EventListener/EnumFieldConfigSubscriberTest.php
PHP
mit
17,747
module Moysklad::Resources class Products < Base private def entity_class Moysklad::Entities::Product end end end
BrandyMint/moysklad
lib/moysklad/resources/products.rb
Ruby
mit
138
using System; using System.Globalization; namespace DateDifference { class DateDifference { /* 16. Write a program that reads two dates in the format: day.month.year and calculates the number of days between them. */ static void Main() { Console.WriteLine("Input two dates in the format\nday.month.year ..."); try { Console.Write("Enter the first date: "); string firstDateInString = Console.ReadLine(); DateTime firstDate = DateTime.Parse(firstDateInString); Console.Write("Enter the second date: "); string secondDateInString = Console.ReadLine(); DateTime secondDate = DateTime.Parse(secondDateInString); Console.WriteLine("Distance {0} days", (firstDate - secondDate).Days); } catch (FormatException) { Console.Error.WriteLine("Invalid date!"); } } } }
d-georgiev-91/TelerikAcademy
Programming/CSharp/CSharpPart2/StringsAndTextProcessing/DateDifference/DateDifference.cs
C#
mit
1,017
namespace Post_Publisher.Models.PostCommentModels { public class DeleteModel { public string Id { get; set; } public string ReturnUrl { get; set; } public bool IsDeleted { get; set; } } }
interopbyt/postpublisher
Post Publisher.Web/Models/PostCommentModels/DeleteModel.cs
C#
mit
198
Fabricator :backtrace do lines(count: 99) do { number: rand(999), file: "[PROJECT_ROOT]/path/to/file/#{SecureRandom.hex(4)}.rb", method: ActiveSupport.methods.sample } end end
bonanza-market/errbit
spec/fabricators/backtrace_fabricator.rb
Ruby
mit
206
$(document).ready(function() { $('rulang').click(function() { alert( "Handler for .click() called." ); }); $('enlang').click(function() { alert( "Handler for .click() called." ); }); $('pllang').click(function() { alert( "Handler for .click() called." ); }); });
4johndoe/sh
tmpl/js/my.js
JavaScript
mit
278
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitsend developers // Copyright (c) 2014-2015 The bitsend developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "primitives/transaction.h" #include "core_io.h" #include "init.h" #include "keystore.h" #include "main.h" #include "net.h" #include "rpcserver.h" #include "script/script.h" #include "script/sign.h" #include "script/standard.h" #include "uint256.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <stdint.h> #include <boost/assign/list_of.hpp> #include "json/json_spirit_utils.h" #include "json/json_spirit_value.h" using namespace boost; using namespace boost::assign; using namespace json_spirit; using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitsendAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, true); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight)); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction \"txid\" ( verbose )\n" "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n" "or there is an unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option.\n" "\nReturn the raw transaction data.\n" "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n" "If verbose is non-zero, returns an Object with information about 'txid'.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n" "\nResult (if verbose is not set or set to 0):\n" "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" "\nResult (if verbose > 0):\n" "{\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in btc\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"bitsendaddress\" (string) bitsend address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1") ); uint256 hash = ParseHashV(params[0], "parameter 1"); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); string strHex = EncodeHexTx(tx); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } #ifdef ENABLE_WALLET Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent ( minconf maxconf [\"address\",...] )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n" "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n" "3. \"addresses\" (string) A json array of bitsend addresses to filter\n" " [\n" " \"address\" (string) bitsend address\n" " ,...\n" " ]\n" "\nResult\n" "[ (array of json object)\n" " {\n" " \"txid\" : \"txid\", (string) the transaction id \n" " \"vout\" : n, (numeric) the vout value\n" " \"address\" : \"address\", (string) the bitsend address\n" " \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n" " \"scriptPubKey\" : \"key\", (string) the script key\n" " \"amount\" : x.xxx, (numeric) the transaction amount in btc\n" " \"confirmations\" : n (numeric) The number of confirmations\n" " }\n" " ,...\n" "]\n" "\nExamples\n" + HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") ); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitsendAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitsendAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid bitsend address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; assert(pwalletMain != NULL); pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if (setAddress.size()) { CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } CAmount nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitsendAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name)); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<CScriptID>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); entry.push_back(Pair("spendable", out.fSpendable)); results.push_back(entry); } return results; } #endif Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n" "\nCreate a transaction spending the given inputs and sending to the given addresses.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n" "\nArguments:\n" "1. \"transactions\" (string, required) A json array of json objects\n" " [\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n (numeric, required) The output number\n" " }\n" " ,...\n" " ]\n" "2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n" " {\n" " \"address\": x.xxx (numeric, required) The key is the bitsend address, the value is the btc amount\n" " ,...\n" " }\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" "\nExamples\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"") ); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CMutableTransaction rawTx; BOOST_FOREACH(const Value& input, inputs) { const Object& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(txid, nOutput)); rawTx.vin.push_back(in); } set<CBitsendAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitsendAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid bitsend address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } return EncodeHexTx(rawTx); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction \"hexstring\"\n" "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n" "\nArguments:\n" "1. \"hex\" (string, required) The transaction hex string\n" "\nResult:\n" "{\n" " \"txid\" : \"id\", (string) The transaction id\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) The output number\n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in btc\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitsend address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" "}\n" "\nExamples:\n" + HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\"") ); RPCTypeCheck(params, list_of(str_type)); CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript \"hex\"\n" "\nDecode a hex-encoded script.\n" "\nArguments:\n" "1. \"hex\" (string) the hex encoded script\n" "\nResult:\n" "{\n" " \"asm\":\"asm\", (string) Script public key\n" " \"hex\":\"hex\", (string) hex encoded public key\n" " \"type\":\"type\", (string) The output type\n" " \"reqSigs\": n, (numeric) The required signatures\n" " \"addresses\": [ (json array of string)\n" " \"address\" (string) bitsend address\n" " ,...\n" " ],\n" " \"p2sh\",\"address\" (string) script address\n" "}\n" "\nExamples:\n" + HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\"") ); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitsendAddress(CScriptID(script)).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n" "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n" "The third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" #ifdef ENABLE_WALLET + HelpRequiringPassphrase() + "\n" #endif "\nArguments:\n" "1. \"hexstring\" (string, required) The transaction hex string\n" "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n" " [ (json array of json objects, or 'null' if none provided)\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n, (numeric, required) The output number\n" " \"scriptPubKey\": \"hex\", (string, required) script key\n" " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n" " }\n" " ,...\n" " ]\n" "3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n" " [ (json array of strings, or 'null' if none provided)\n" " \"privatekey\" (string) private key in base58-encoding\n" " ,...\n" " ]\n" "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\"\n" "\nResult:\n" "{\n" " \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n" " \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n" "}\n" "\nExamples:\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\"") ); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHexV(params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CMutableTransaction> txVariants; while (!ssData.empty()) { try { CMutableTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (const std::exception &) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CMutableTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache &viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) { const uint256& prevHash = txin.prevout.hash; CCoins coins; view.AccessCoins(prevHash); // this is certainly allowed to fail } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitsendSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); tempKeystore.AddKey(key); } } #ifdef ENABLE_WALLET else EnsureWalletIsUnlocked(); #endif // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { CCoinsModifier coins = view.ModifyCoins(txid); if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } if ((unsigned int)nOut >= coins->vout.size()) coins->vout.resize(nOut+1); coins->vout[nOut].scriptPubKey = scriptPubKey; coins->vout[nOut].nValue = 0; // we don't know the actual output value } // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type)); Value v = find_value(prevOut, "redeemScript"); if (!(v == Value::null)) { vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } #ifdef ENABLE_WALLET const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); #else const CKeyStore& keystore = tempKeystore; #endif int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const CCoins* coins = view.AccessCoins(txin.prevout.hash); if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) { fComplete = false; continue; } const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CMutableTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i))) fComplete = false; } Object result; result.push_back(Pair("hex", EncodeHexTx(mergedTx))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "sendrawtransaction \"hexstring\" ( allowhighfees )\n" "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n" "\nAlso see createrawtransaction and signrawtransaction calls.\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n" "2. allowhighfees (boolean, optional, default=false) Allow high fees\n" "\nResult:\n" "\"hex\" (string) The transaction hash in hex\n" "\nExamples:\n" "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\"") ); RPCTypeCheck(params, list_of(str_type)(bool_type)); // parse hex string from parameter CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); uint256 hashTx = tx.GetHash(); bool fOverrideFees = false; if (params.size() > 1) fOverrideFees = params[1].get_bool(); CCoinsViewCache &view = *pcoinsTip; const CCoins* existingCoins = view.AccessCoins(hashTx); bool fHaveMempool = mempool.exists(hashTx); bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000; if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets CValidationState state; if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) { if(state.IsInvalid()) throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); else throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason()); } } else if (fHaveChain) { throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain"); } RelayTransaction(tx); return hashTx.GetHex(); }
madzebra/BitSend
src/rpcrawtransaction.cpp
C++
mit
32,225
import { imageDemoTest } from '../../../tests/shared/imageTest'; describe('Checkbox image', () => { imageDemoTest('checkbox'); });
ant-design/ant-design
components/checkbox/__tests__/image.test.ts
TypeScript
mit
134
import static org.junit.Assert.*; import org.junit.Test; import mx.itesm.a01139626.p6.src.DataSetAnalyzer; public class DataSetAnalyzerTest { @Test public void test1DataPoint () { DataSetAnalyzer datS = new DataSetAnalyzer(); datS.setsFileName("Arch1.txt"); datS.analyze(); assertEquals(datS.getDatSet().getdYK(), 644.42938, 0.00005); } @Test public void testEmpty () { DataSetAnalyzer datS = new DataSetAnalyzer(); datS.setsFileName("Vacio.txt"); datS.analyze(); assertEquals(datS.getDatSet().getdYK(), 0, 0.00005); } @SuppressWarnings("deprecation") @Test public void testStringsInFile () { DataSetAnalyzer datS = new DataSetAnalyzer(); datS.setsFileName("datosStrings.txt"); datS.analyze(); assertEquals(datS.getDatSet().getdYK(), 0, 0.00005); } }
betoesquivel/PSPTraining
Programa6/test/DataSetAnalyzerTest.java
Java
mit
793
require 'tempfile' require 'openssl' require_relative 'helper' module FastlaneCore # This class checks if a specific certificate is installed on the current mac class CertChecker def self.installed?(path, in_keychain: nil) UI.user_error!("Could not find file '#{path}'") unless File.exist?(path) ids = installed_identies(in_keychain: in_keychain) finger_print = sha1_fingerprint(path) return ids.include?(finger_print) end # Legacy Method, use `installed?` instead def self.is_installed?(path) installed?(path) end def self.installed_identies(in_keychain: nil) install_wwdr_certificate unless wwdr_certificate_installed? available = list_available_identities # Match for this text against word boundaries to avoid edge cases around multiples of 10 identities! if /\b0 valid identities found\b/ =~ available UI.error([ "There are no local code signing identities found.", "You can run `security find-identity -v -p codesigning` to get this output.", "This Stack Overflow thread has more information: https://stackoverflow.com/q/35390072/774.", "(Check in Keychain Access for an expired WWDR certificate: https://stackoverflow.com/a/35409835/774 has more info.)" ].join("\n")) end ids = [] available.split("\n").each do |current| next if current.include?("REVOKED") begin (ids << current.match(/.*\) ([[:xdigit:]]*) \".*/)[1]) rescue # the last line does not match end end return ids end def self.list_available_identities(in_keychain: nil) commands = ['security find-identity -v -p codesigning'] commands << in_keychain if in_keychain `#{commands.join(' ')}` end def self.wwdr_certificate_installed? certificate_name = "Apple Worldwide Developer Relations Certification Authority" keychain = wwdr_keychain response = Helper.backticks("security find-certificate -c '#{certificate_name}' #{keychain.shellescape}", print: FastlaneCore::Globals.verbose?) return response.include?("attributes:") end def self.install_wwdr_certificate url = 'https://developer.apple.com/certificationauthority/AppleWWDRCA.cer' file = Tempfile.new('AppleWWDRCA') filename = file.path keychain = wwdr_keychain keychain = "-k #{keychain.shellescape}" unless keychain.empty? require 'open3' import_command = "curl -f -o #{filename} #{url} && security import #{filename} #{keychain}" UI.verbose("Installing WWDR Cert: #{import_command}") stdout, stderr, _status = Open3.capture3(import_command) if FastlaneCore::Globals.verbose? UI.command_output(stdout) UI.command_output(stderr) end unless $?.success? UI.verbose("Failed to install WWDR Certificate, checking output to see why") # Check the command output, WWDR might already exist unless /The specified item already exists in the keychain./ =~ stderr UI.user_error!("Could not install WWDR certificate") end UI.verbose("WWDR Certificate was already installed") end return true end def self.wwdr_keychain priority = [ "security list-keychains -d user", "security default-keychain -d user" ] priority.each do |command| keychains = Helper.backticks(command, print: FastlaneCore::Globals.verbose?).split("\n") unless keychains.empty? # Select first keychain name from returned keychains list return keychains[0].strip.tr('"', '') end end return "" end def self.sha1_fingerprint(path) file_data = File.read(path.to_s) cert = OpenSSL::X509::Certificate.new(file_data) return OpenSSL::Digest::SHA1.new(cert.to_der).to_s.upcase rescue => error UI.error(error) UI.user_error!("Error parsing certificate '#{path}'") end end end
revile/fastlane
fastlane_core/lib/fastlane_core/cert_checker.rb
Ruby
mit
4,042
(function () { var ns = Y.namespace("a11ychecker"), testName = "link-button-test", re = /(^#$)|(^javascript:)/i; function findLinkButtons() { Y.all("a").each(function (link) { var href = link.get('href'); if ((!href || (href && href.search(re) === 0)) && (!link.get('role'))) { ns.logError(testName, link, "Link used to create a button. Consider adding ARIA role of \"button\" or switch to button element.", "warn"); } }); } findLinkButtons.testName = testName; ns.findLinkButtons = findLinkButtons; }());
inikoo/fact
libs/yui/yui3-gallery/src/gallery-a11ychecker-base/js/link-button-checker.js
JavaScript
mit
573
package com.github.nettybook.ch3; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.oio.OioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.oio.OioServerSocketChannel; public class BlockingEchoServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new OioEventLoopGroup(1); EventLoopGroup workerGroup = new OioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(OioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new EchoServerHandler()); } }); ChannelFuture f = b.bind(8888).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } }
krisjey/netty.book.kor
example/src/java/com/github/nettybook/ch3/BlockingEchoServer.java
Java
mit
1,344
//Dependencies import React, {PropTypes, PureComponent} from 'react'; import {getConfig} from '../config'; function translateDate(date) { const {translateDate} = getConfig(); return translateDate(date); } class Notification extends PureComponent { constructor(props) { super(props); this.handleOnRead = this.handleOnRead.bind(this); } handleOnRead(event){ const {onRead, uuid} = this.props; event.preventDefault(); event.stopPropagation(); onRead(uuid); } render() { const {creationDate, content, hasDate, icon, onClick, onRead, uuid, sender, targetUrl, title, type} = this.props; return ( <li data-focus='notification' data-type={type} onClick={()=>{ onClick({targetUrl})}}> {icon && <div data-focus='notification-icon'><img src={icon}/></div>} <div data-focus='notification-body' > <h4 data-focus='notification-title'>{title}</h4> <div data-focus='notification-content'>{content}</div> </div> {hasDate && <div data-focus='notification-date'> <button className='mdl-button mdl-js-button mdl-button--icon' onClick={this.handleOnRead}> <i className='material-icons'>done</i> </button> <div>{translateDate(creationDate)}</div> </div> } </li> ); }; } Notification.displayName = 'Notification'; Notification.propTypes = { hasDate: PropTypes.bool, uuid: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, title: PropTypes.string.isRequired, content: PropTypes.string.isRequired, creationDate: PropTypes.string.isRequired, type: PropTypes.string.isRequired, sender: PropTypes.string.isRequired, targetUrl: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, onRead: PropTypes.func.isRequired, onClick: PropTypes.func.isRequired }; Notification.defaultProps = { hasDate: true } export default Notification;
KleeGroup/focus-notifications
src/component/notification.js
JavaScript
mit
2,185
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Globalization; using Azure.Core.Amqp; using Microsoft.Azure.Amqp.Framing; namespace Azure.Messaging.EventHubs.Amqp { /// <summary> /// Provides an abstraction over an <see cref="AmqpAnnotatedMessage" /> to represent /// broker-owned data in the form of a "system properties" dictionary for the /// associated <see cref="EventData" /> instance. /// </summary> /// /// <remarks> /// This wrapper is necessary to preserve the behavior of the <see cref="EventData.SystemProperties" /> /// member without potentially drifting from the mutable data that exists on the AMQP message. /// </remarks> /// /// <seealso cref="IReadOnlyDictionary{TKey, TValue}" /> /// internal class AmqpSystemProperties : IReadOnlyDictionary<string, object> { /// <summary>The set of system properties that are sourced from the Properties section of the <see cref="AmqpAnnotatedMessage" />.</summary> private static readonly string[] PropertySectionNames = new[] { Properties.MessageIdName, Properties.UserIdName, Properties.ToName, Properties.SubjectName, Properties.ReplyToName, Properties.CorrelationIdName, Properties.ContentTypeName, Properties.ContentEncodingName, Properties.AbsoluteExpiryTimeName, Properties.CreationTimeName, Properties.GroupIdName, Properties.GroupSequenceName, Properties.ReplyToGroupIdName }; /// <summary>The AMQP message to use as the source for the system properties data.</summary> private readonly AmqpAnnotatedMessage _amqpMessage; /// <summary> /// Attempts to retrieve the value of the requested <paramref name="key" /> /// from the dictionary. /// </summary> /// /// <param name="key">The key of the dictionary item to retrieve.</param> /// /// <returns>The value in the dictionary associated with the specified <paramref name="key"/>.</returns> /// /// <exception cref="KeyNotFoundException">Occurs when the specified <paramref name="key" /> does not exist in the dictionary.</exception> /// public object this[string key] { get { if (_amqpMessage.HasSection(AmqpMessageSection.Properties)) { if (key == Properties.MessageIdName) { return _amqpMessage.Properties.MessageId; } if (key == Properties.UserIdName) { return _amqpMessage.Properties.UserId; } if (key == Properties.ToName) { return _amqpMessage.Properties.To; } if (key == Properties.SubjectName) { return _amqpMessage.Properties.Subject; } if (key == Properties.ReplyToName) { return _amqpMessage.Properties.ReplyTo; } if (key == Properties.CorrelationIdName) { return _amqpMessage.Properties.CorrelationId; } if (key == Properties.ContentTypeName) { return _amqpMessage.Properties.ContentType; } if (key == Properties.ContentEncodingName) { return _amqpMessage.Properties.ContentEncoding; } if (key == Properties.AbsoluteExpiryTimeName) { return _amqpMessage.Properties.AbsoluteExpiryTime; } if (key == Properties.CreationTimeName) { return _amqpMessage.Properties.CreationTime; } if (key == Properties.GroupIdName) { return _amqpMessage.Properties.GroupId; } if (key == Properties.GroupSequenceName) { return _amqpMessage.Properties.GroupSequence; } if (key == Properties.ReplyToGroupIdName) { return _amqpMessage.Properties.ReplyToGroupId; } } if (_amqpMessage.HasSection(AmqpMessageSection.MessageAnnotations)) { return _amqpMessage.MessageAnnotations[key]; } // If no section was available to delegate to, mimic the behavior of the standard dictionary implementation. throw new KeyNotFoundException(string.Format(CultureInfo.InvariantCulture, Resources.DictionaryKeyNotFoundMask, key)); } } /// <summary> /// Allows iteration over the keys contained in the dictionary. /// </summary> /// public IEnumerable<string> Keys { get { if (_amqpMessage.HasSection(AmqpMessageSection.Properties)) { foreach (var name in PropertySectionNames) { if (ContainsKey(name)) { yield return name; } } } if (_amqpMessage.HasSection(AmqpMessageSection.MessageAnnotations)) { foreach (var name in _amqpMessage.MessageAnnotations.Keys) { yield return name; } } } } /// <summary> /// Allows iteration over the values contained in the dictionary. /// </summary> /// public IEnumerable<object> Values { get { if (_amqpMessage.HasSection(AmqpMessageSection.Properties)) { foreach (var name in PropertySectionNames) { if (ContainsKey(name)) { yield return this[name]; } } } if (_amqpMessage.HasSection(AmqpMessageSection.MessageAnnotations)) { foreach (var name in _amqpMessage.MessageAnnotations.Keys) { yield return _amqpMessage.MessageAnnotations[name]; } } } } /// <summary> /// The number of items contained in the dictionary. /// </summary> /// public int Count { get { var count = 0; if (_amqpMessage.HasSection(AmqpMessageSection.Properties)) { foreach (var name in PropertySectionNames) { if (ContainsKey(name)) { ++count; } } } if (_amqpMessage.HasSection(AmqpMessageSection.MessageAnnotations)) { foreach (var name in _amqpMessage.MessageAnnotations.Keys) { ++count; } } return count; } } /// <summary> /// Initializes a new instance of the <see cref="AmqpSystemProperties"/> class. /// </summary> /// /// <param name="amqpMessage">The <see cref="AmqpAnnotatedMessage" /> to use as the source of the system properties data.</param> /// public AmqpSystemProperties(AmqpAnnotatedMessage amqpMessage) => _amqpMessage = amqpMessage; /// <summary> /// Determines whether the specified key exists in the dictionary. /// </summary> /// /// <param name="key">The key to locate.</param> /// /// <returns><c>true</c> if the dictionary contains the specified key; otherwise, <c>false</c>.</returns> /// public bool ContainsKey(string key) { // Check the set of well-known items from the Properties section. For the key to be considered present, // the section must exist and there must be a value present. This logic is necessary to preserve the behavior // of system properties in EventData before the AMQP annotated message abstraction was incorporated. if (_amqpMessage.HasSection(AmqpMessageSection.Properties)) { if (key == Properties.MessageIdName) { return (_amqpMessage.Properties.MessageId != null); } if (key == Properties.UserIdName) { return (_amqpMessage.Properties.UserId != null); } if (key == Properties.ToName) { return (_amqpMessage.Properties.To != null); } if (key == Properties.SubjectName) { return (_amqpMessage.Properties.Subject != null); } if (key == Properties.ReplyToName) { return (_amqpMessage.Properties.ReplyTo != null); } if (key == Properties.CorrelationIdName) { return (_amqpMessage.Properties.CorrelationId != null); } if (key == Properties.ContentTypeName) { return (_amqpMessage.Properties.ContentType != null); } if (key == Properties.ContentEncodingName) { return (_amqpMessage.Properties.ContentEncoding != null); } if (key == Properties.AbsoluteExpiryTimeName) { return (_amqpMessage.Properties.AbsoluteExpiryTime != null); } if (key == Properties.CreationTimeName) { return (_amqpMessage.Properties.CreationTime != null); } if (key == Properties.GroupIdName) { return (_amqpMessage.Properties.GroupId != null); } if (key == Properties.GroupSequenceName) { return (_amqpMessage.Properties.GroupSequence != null); } if (key == Properties.ReplyToGroupIdName) { return (_amqpMessage.Properties.ReplyToGroupId != null); } } // If the well-known property items were not found, then any message annotation with a matching // key is acceptable. if (_amqpMessage.HasSection(AmqpMessageSection.MessageAnnotations)) { return _amqpMessage.MessageAnnotations.ContainsKey(key); } // If neither a well-known property or message annotation matched, the key // does not exist. return false; } /// <summary> /// Attempts to retrieve the value that is associated with the specified key from the dictionary. /// </summary> /// /// <param name="key">The key to locate.</param> /// <param name="value">The value associated with the specified key, if the key is found; otherwise, <c>null</c>. This parameter should be passed uninitialized.</param> /// /// <returns><c>true</c> the dictionary contains the specified <paramref name="key" />; otherwise, <c>false</c>.</returns> /// public bool TryGetValue(string key, out object value) { if (!ContainsKey(key)) { value = default; return false; } value = this[key]; return true; } /// <summary> /// Produces an enumerator for the items in the dictionary. /// </summary> /// /// <returns>An enumerator can be used to iterate through the items in the dictionary.</returns> /// public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { foreach (var key in Keys) { yield return new KeyValuePair<string, object>(key, this[key]); } } /// <summary> /// Produces an enumerator for the items in the dictionary. /// </summary> /// /// <returns>An enumerator can be used to iterate through the items in the dictionary.</returns> /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
AsrOneSdk/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpSystemProperties.cs
C#
mit
13,517
package v6 import ( "code.cloudfoundry.org/cli/actor/actionerror" "code.cloudfoundry.org/cli/actor/sharedaction" "code.cloudfoundry.org/cli/actor/v3action" "code.cloudfoundry.org/cli/api/cloudcontroller/ccversion" "code.cloudfoundry.org/cli/command" "code.cloudfoundry.org/cli/command/flag" "code.cloudfoundry.org/cli/command/v6/shared" ) //go:generate counterfeiter . V3UnsetEnvActor type V3UnsetEnvActor interface { CloudControllerAPIVersion() string UnsetEnvironmentVariableByApplicationNameAndSpace(appName string, spaceGUID string, EnvironmentVariableName string) (v3action.Warnings, error) } type V3UnsetEnvCommand struct { RequiredArgs flag.UnsetEnvironmentArgs `positional-args:"yes"` usage interface{} `usage:"CF_NAME v3-unset-env APP_NAME ENV_VAR_NAME"` relatedCommands interface{} `related_commands:"v3-apps, v3-env, v3-restart, v3-set-env, v3-stage"` UI command.UI Config command.Config SharedActor command.SharedActor Actor V3UnsetEnvActor } func (cmd *V3UnsetEnvCommand) Setup(config command.Config, ui command.UI) error { cmd.UI = ui cmd.Config = config cmd.SharedActor = sharedaction.NewActor(config) ccClient, _, err := shared.NewV3BasedClients(config, ui, true, "") if err != nil { return err } cmd.Actor = v3action.NewActor(ccClient, config, nil, nil) return nil } func (cmd V3UnsetEnvCommand) Execute(args []string) error { cmd.UI.DisplayWarning(command.ExperimentalWarning) err := command.MinimumCCAPIVersionCheck(cmd.Actor.CloudControllerAPIVersion(), ccversion.MinVersionApplicationFlowV3) if err != nil { return err } err = cmd.SharedActor.CheckTarget(true, true) if err != nil { return err } user, err := cmd.Config.CurrentUser() if err != nil { return err } appName := cmd.RequiredArgs.AppName cmd.UI.DisplayTextWithFlavor("Removing env variable {{.EnvVarName}} from app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{ "AppName": appName, "EnvVarName": cmd.RequiredArgs.EnvironmentVariableName, "OrgName": cmd.Config.TargetedOrganization().Name, "SpaceName": cmd.Config.TargetedSpace().Name, "Username": user.Name, }) warnings, err := cmd.Actor.UnsetEnvironmentVariableByApplicationNameAndSpace( appName, cmd.Config.TargetedSpace().GUID, cmd.RequiredArgs.EnvironmentVariableName, ) cmd.UI.DisplayWarnings(warnings) if err != nil { switch errVal := err.(type) { case actionerror.EnvironmentVariableNotSetError: cmd.UI.DisplayText(errVal.Error()) default: return err } } cmd.UI.DisplayOK() if err == nil { cmd.UI.DisplayText("TIP: Use 'cf v3-stage {{.AppName}}' to ensure your env variable changes take effect.", map[string]interface{}{ "AppName": appName, }) } return nil }
odlp/antifreeze
vendor/github.com/cloudfoundry/cli/command/v6/v3_unset_env_command.go
GO
mit
2,830
using System.Collections.Generic; using UnityEngine; using ExitGames.Client.Photon; namespace Photon.Pun.Demo.Procedural { /// <summary> /// The Cluster component has references to all Blocks that are part of this Cluster. /// It provides functions for modifying single Blocks inside this Cluster. /// It also handles modifications made to the world by other clients. /// </summary> public class Cluster : MonoBehaviourPunCallbacks { private string propertiesKey; private Dictionary<int, float> propertiesValue; public int ClusterId { get; set; } public Dictionary<int, GameObject> Blocks { get; private set; } #region UNITY public void Awake() { Blocks = new Dictionary<int, GameObject>(); propertiesValue = new Dictionary<int, float>(); } /// <summary> /// Sets the unique key of this Cluster used for storing modifications within the Custom Room Properties. /// </summary> private void Start() { propertiesKey = "Cluster " + ClusterId; } #endregion #region CLASS FUNCTIONS /// <summary> /// Adds a Block to the Cluster. /// This is called by the WorldGenerator while the generation process is running. /// In order to modify Blocks directly, we are storing the ID as well as a reference to the certain GameObject. /// </summary> public void AddBlock(int blockId, GameObject block) { Blocks.Add(blockId, block); } /// <summary> /// Gets called before a new world can be generated. /// Destroys each Block from this Cluster and removes the data stored in the Custom Room Properties. /// </summary> public void DestroyCluster() { foreach (GameObject block in Blocks.Values) { Destroy(block); } Blocks.Clear(); if (PhotonNetwork.IsMasterClient) { RemoveClusterFromRoomProperties(); } } /// <summary> /// Decreases a Block's height locally before applying the modification to the Custom Room Properties. /// </summary> public void DecreaseBlockHeight(int blockId) { float height = Blocks[blockId].transform.localScale.y; height = Mathf.Max((height - 1.0f), 0.0f); SetBlockHeightLocal(blockId, height); } /// <summary> /// Increases a Block's height locally before applying the modification to the Custom Room Properties. /// </summary> public void IncreaseBlockHeight(int blockId) { float height = Blocks[blockId].transform.localScale.y; height = Mathf.Min((height + 1.0f), 8.0f); SetBlockHeightLocal(blockId, height); } /// <summary> /// Gets called when a remote client has modified a certain Block within this Cluster. /// Called by the WorldGenerator or the Cluster itself after the Custom Room Properties have been updated. /// </summary> public void SetBlockHeightRemote(int blockId, float height) { GameObject block = Blocks[blockId]; Vector3 scale = block.transform.localScale; Vector3 position = block.transform.localPosition; block.transform.localScale = new Vector3(scale.x, height, scale.z); block.transform.localPosition = new Vector3(position.x, height / 2.0f, position.z); } /// <summary> /// Gets called whenever the local client modifies any Block within this Cluster. /// The modification will be applied to the Block first before it is published to the Custom Room Properties. /// </summary> private void SetBlockHeightLocal(int blockId, float height) { GameObject block = Blocks[blockId]; Vector3 scale = block.transform.localScale; Vector3 position = block.transform.localPosition; block.transform.localScale = new Vector3(scale.x, height, scale.z); block.transform.localPosition = new Vector3(position.x, height / 2.0f, position.z); UpdateRoomProperties(blockId, height); } /// <summary> /// Gets called in order to update the Custom Room Properties with the modification made by the local client. /// </summary> private void UpdateRoomProperties(int blockId, float height) { propertiesValue[blockId] = height; Hashtable properties = new Hashtable {{propertiesKey, propertiesValue}}; PhotonNetwork.CurrentRoom.SetCustomProperties(properties); } /// <summary> /// Removes the modifications of this Cluster from the Custom Room Properties. /// </summary> private void RemoveClusterFromRoomProperties() { Hashtable properties = new Hashtable {{propertiesKey, null}}; PhotonNetwork.CurrentRoom.SetCustomProperties(properties); } #endregion #region PUN CALLBACKS /// <summary> /// Gets called whenever the Custom Room Properties are updated. /// When the changed properties contain the previously set PropertiesKey (basically the Cluster ID), /// the Cluster and its Blocks will be updated accordingly. /// </summary> public override void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged) { if (propertiesThatChanged.ContainsKey(propertiesKey)) { if (propertiesThatChanged[propertiesKey] == null) { propertiesValue = new Dictionary<int, float>(); return; } propertiesValue = (Dictionary<int, float>) propertiesThatChanged[propertiesKey]; foreach (KeyValuePair<int, float> pair in propertiesValue) { SetBlockHeightRemote(pair.Key, pair.Value); } } } #endregion } }
yumemi-inc/vr-studies
vol2/VR-studies/Assets/Photon/PhotonUnityNetworking/Demos/DemoProcedural/Scripts/Cluster.cs
C#
mit
6,408
package eu.hangar.watcher.ac; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.potion.PotionEffectType; public class Fly implements Listener { @EventHandler public void FlyHack(PlayerMoveEvent e) { Player player = e.getPlayer(); if((e.getTo().getY() - e.getFrom().getY()) >= 2.0) { if((e.getTo().getX() - e.getFrom().getX()) >= 3.0) { player.teleport(e.getFrom()); } } } //The following thing doesn't work. But, eh, it's cool @EventHandler public void Flying(PlayerMoveEvent e){ Player p = e.getPlayer(); if(!p.isOp()){ if(!p.hasPermission("watcher.fly.bypass")){ if(p.getGameMode().equals(0)){ if(p.getAllowFlight() == false){ if(p.isFlying()){ if(!p.hasPotionEffect(PotionEffectType.JUMP)){ if(!p.hasPotionEffect(PotionEffectType.LEVITATION)){ p.kickPlayer(ChatColor.RED + "Kicked for Flying by Watcher"); }return; }return; }return; }return; }return; }return; }return; } }
Hangar555/HatrexWatcherF
src/src/eu/hangar/watcher/ac/Fly.java
Java
mit
1,263
var levelsState = { create: function(){ game.add.image(0,0,'back2'); game.world.setBounds(1,1, 1500, 500);//-1000,-10000 cursors = game.input.keyboard.createCursorKeys(); //player this.player = game.add.sprite(game.width/8, game.height/2, 'player'); this.player.anchor.setTo(0.5, 0.5); game.physics.arcade.enable(this.player); this.player.body.gravity.y = 500; //player control this.cursor = game.input.keyboard.createCursorKeys(); //walls this.walls = game.add.group(); this.walls.enableBody = true; this.wal = game.add.group(); this.wal.enableBody = true; // // // this.music = game.add.audio('bgSong'); this.music.loop = true; this.music.play(); // //timeeeeeeeeeeeeeee var me = this; me.startTime = new Date(); me.totalTime = 120; me.timeElapsed = 0; me.createTimer(); me.gameTimer = game.time.events.loop(100, function(){ me.updateTimer(); }); // var middleBotto = game.add.sprite(290, 140, 'wallH', 0, this.wal); middleBotto.scale.setTo(2, 1); // game.add.sprite(0, 0, 'wallV', 0, this.walls); // game.add.sprite(480, 0, 'wallV', 0, this.walls); // game.add.sprite(0, 0, 'wallH', 0, this.walls); // game.add.sprite(300,0, 'wallH', 0, this.walls); // game.add.sprite(0,320, 'wallH', 0, this.walls); // game.add.sprite(300,320, 'wallH', 0, this.walls); // game.add.sprite(-100,160, 'wallH',0, this.walls); // game.add.sprite(400,160, 'wallH',0, this.walls); var middleTop = game.add.sprite(100, 80, 'wallH', 0, this.walls); middleTop.scale.setTo(1.5, 1); var middleBottom = game.add.sprite(10, 340, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //2 var middletwo = game.add.sprite(90, 140, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //3 var middlethree = game.add.sprite(50, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //4 var middlefour = game.add.sprite(250, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //5 var middlefive = game.add.sprite(400, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //6 var middlesix = game.add.sprite(650, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //7 var middleseven = game.add.sprite(750, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //8 var middleeight = game.add.sprite(1050, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //9 var middlenine = game.add.sprite(1350, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //10 var middleten = game.add.sprite(1750, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //11 var middleeleven = game.add.sprite(1950, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //12 var middletwelve = game.add.sprite(2250, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //13 var middlethirten = game.add.sprite(2550, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //14 var middlefourten = game.add.sprite(2850, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); //15 var middlefiften = game.add.sprite(3050, 240, 'wallH', 0, this.walls); middleBottom.scale.setTo(1, 1); this.wal.setAll('body.movable', true); this.walls.setAll('body.movable', true); //coin this.coin = game.add.sprite(100, 140, 'coin'); game.physics.arcade.enable(this.coin); this.coin.anchor.setTo(0.5, 0.5); this.goal = game.add.sprite(1450, 200, 'goal'); game.physics.arcade.enable(this.goal); this.goal.anchor.setTo(0.5, 0.5); this.slimes = game.add.group(); this.slimes.enableBody = true; //create 10 enemies this.slimes.createMultiple(30, 'slime'); //call add enemy every 2.2 second this.time.events.loop(2200, this.addSlimeFromBottom, this); this.scoreLabel = game.add.text(30, 30, 'score: 0', {font: '18px Arial', fill: '#ffffff'}); this.scoreLabel.fixedToCamera = true; game.global.score = 0; //create enemy group this.enemies = game.add.group(); this.enemies.enableBody = true; //create 10 enemies this.enemies.createMultiple(20, 'enemy'); //call add enemy every 2.2 second //this.time.events.loop(2200, this.addEnemyFromTop, this); this.time.events.loop(2200, this.addEnemyFromBottom, this); //sound this.jumpSound = game.add.audio('jump'); this.coinSound = game.add.audio('coin'); this.deadSound = game.add.audio('dead'); this.winSound = game.add.audio('win'); //animation this.player.animations.add('right',[5, 6, 7, 8], 10,true); //left anim this.player.animations.add('left',[0, 1, 2, 3], 10,true); this.emitter = game.add.emitter(0,0,15); this.emitter.makeParticles('pixel'); this.emitter.setYSpeed(-150,150); this.emitter.setXSpeed(-150,150); this.emitter.gravity=0; }, update: function(){ if (cursors.left.isDown) { game.camera.x -= 2; } else if (cursors.right.isDown) { game.camera.x += 2; } //player game.physics.arcade.collide(this.player, this.walls); this.movePlayer(); if (!this.player.inWorld){ this.playerDie(); } //coin game.physics.arcade.overlap(this.player, this.coin, this.takeCoin, null, this); game.physics.arcade.overlap(this.player, this.goal, this.win, null, this); game.physics.arcade.collide(this.slimes, this.walls); game.physics.arcade.overlap(this.player, this.slimes, this.playerDie, null, this); //enemies game.physics.arcade.collide(this.enemies, this.walls); game.physics.arcade.overlap(this.player, this.enemies, this.playerDie, null, this); if(!this.player.alive){ return; } }, movePlayer: function(){ if (this.cursor.left.isDown){ this.player.body.velocity.x = -200; this.player.animations.play('left'); } else if (this.cursor.right.isDown){ this.player.body.velocity.x = 200; this.player.animations.play('right'); } else { this.player.body.velocity.x = 0; this.player.animations.stop();//stop anim this.player.frame=0;//stand still } if (this.cursor.up.isDown && this.player.body.touching.down){ this.jumpSound.play(); this.player.body.velocity.y = -320; } } , startMenu: function(){ game.state.start('play'); }, playerDie: function(){ this.music.stop(); this.player.kill(); this.deadSound.play(); this.emitter.x=this.player.x; this.emitter.y=this.player.y; this.emitter.start(true,800,null,15); game.time.events.add(1000,this.startMenu,this); game.camera.shake(0.02,300); }, updateCoinPosition: function(){ var coinPosition = [ {x: 140, y: 180}, {x: 260, y: 180}, {x: 440, y: 140}, {x: 640, y: 140}, // {x: 130, y: 140}, {x: 170, y: 130}, ]; for (var i = 0; i < coinPosition.length; i++){ if(coinPosition[i].x ==this.coin.x) { coinPosition.splice(i, 1); } } var newPosition = game.rnd.pick(coinPosition); this.coin.reset(newPosition.x, newPosition.y); }, takeCoin: function(player, coin){ // this.coin.kill(); this.coin.scale.setTo(0,0); game.add.tween(this.coin.scale).to({x:1,y:1},1000).start(); game.add.tween(this.player.scale).to({x:1.3,y:1.3},100).yoyo(true).start(); game.global.score += 5; this.scoreLabel.text = 'score: ' + game.global.score; this.updateCoinPosition(); this.coinSound.play(); }, win: function(player, goal){ // this.coin.kill(); this.goal.scale.setTo(0,0); game.add.tween(this.goal.scale).to({x:1,y:1},1000).start(); game.add.tween(this.player.scale).to({x:1.3,y:1.3},100).yoyo(true).start(); game.global.score += 5; this.scoreLabel.text = 'score: ' + game.global.score; this.home(); this.music.stop(); //this.winSound.play(); }, home: function(){ game.state.start('home'); }, addSlimeFromBottom: function() { var slimeb = this.slimes.getFirstDead(); if (!slimeb) { return; } //initialize an enemy slimeb.anchor.setTo(0.5, 1); slimeb.reset(game.width/2,1); slimeb.body.gravity.y = 500; slimeb.body.velocity.x = 100 * game.rnd.pick([-1, 1]); slimeb.body.bounce.x = 1; slimeb.checkWorldBounds = true; slimeb.outOfBoundsKill = true; }, //add enemy function // addEnemyFromTop: function() { // //get 1st dead enemy of group // var enemy = this.enemies.getFirstDead(); // //do nothing if no enemy // if (!enemy) { // return; // } // //initialize an enemy // //set anchor to center bottom // enemy.anchor.setTo(0.5, 1); // enemy.reset(game.width/2, 0); // //add gravity // enemy.body.gravity.y = 500; // enemy.body.velocity.x = 100 * game.rnd.pick([-1, 1]); // enemy.body.bounce.x = 1; // enemy.checkWorldBounds = true; // enemy.outOfBoundsKill = true; // }, addEnemyFromBottom: function() { var enemyb = this.enemies.getFirstDead(); if (!enemyb) { return; } //initialize an enemy enemyb.anchor.setTo(0.5, 1); //add enemy from bottom enemyb.reset(game.width/2,game.height); //add gravity enemyb.body.gravity.y = -500; enemyb.body.velocity.x = 100 * game.rnd.pick([-1, 1]); enemyb.body.bounce.x = 1; enemyb.checkWorldBounds = true; enemyb.outOfBoundsKill = true; }, createTimer: function(){ var me = this; me.timeLabel = me.game.add.text(60, 60, "00:00", {font: "18px Arial", fill: "#ffffff"}); me.timeLabel.anchor.setTo(0.5, 0); //me.timeLabel.align = 'center'; this.timeLabel.fixedToCamera = true; }, updateTimer: function(){ var me = this; var currentTime = new Date(); var timeDifference = me.startTime.getTime() - currentTime.getTime(); //Time elapsed in seconds me.timeElapsed = Math.abs(timeDifference / 1000); //Time remaining in seconds // var timeRemaining = me.totalTime - me.timeElapsed; var timeRemaining = me.timeElapsed; var minutes = Math.floor(me.timeElapsed / 60); var seconds = Math.floor(me.timeElapsed) - (60 * minutes); //Convert seconds into minutes and seconds var minutes = Math.floor(timeRemaining / 60); var seconds = Math.floor(timeRemaining) - (60 * minutes); //Display minutes, add a 0 to the start if less than 10 var result = (minutes < 10) ? "0" + minutes : minutes; //Display seconds, add a 0 to the start if less than 10 result += (seconds < 10) ? ":0" + seconds : ":" + seconds; me.timeLabel.text = result; if(me.timeElapsed >= me.totalTime){ //Do what you need to do game.state.start('play'); this.music.stop(); } }, };
nickchulani99/ITE-445
final/alien/js/levels.js
JavaScript
mit
10,651
using System; using System.Collections.Generic; namespace Microsoft.binutils.elflib { public class SectionReference { public class SymbolReference { public uint Offset; public RelocationEntry RelocationRef; public SectionReference Owner; public SymbolReference(uint offset, RelocationEntry relocationRef, SectionReference owner) { Offset = offset; RelocationRef = relocationRef; Owner = owner; } } internal SectionReference(ElfSection sec, RelocationEntry relocRef, uint callOffset) : this( sec, relocRef, callOffset, 0 ) { } internal SectionReference(ElfSection sec, RelocationEntry relocRef, uint callOffset, uint sectionOffset) { Section = sec; SectionName = relocRef.m_symbolRef.Name; SectionOffset = sectionOffset; CallOffsets = new List<SymbolReference>(); FinalAddress = 0; DataBaseOffset = callOffset; CallOffsets.Add( new SymbolReference( callOffset, relocRef, this ) ); sec.ElementStatusChangedEvent += new Action<ElfSection, ElfElementStatus>( sec_ElementStatusChangedEvent ); } void sec_ElementStatusChangedEvent(ElfSection section, ElfElementStatus action) { if( action == ElfElementStatus.AddressChanged ) { FinalAddress = section.Header.sh_addr; } } public ElfSection Section; public string SectionName; public uint SectionOffset; public readonly uint DataBaseOffset; public List<SymbolReference> CallOffsets; public uint FinalAddress; } }
x335/llilum
Zelig/ext-tools/binutils/elflib/SectionReference.cs
C#
mit
1,803
import Dispatcher from 'core/dispatcher.js'; import ActionTypes from 'const/actions.js'; import Action from 'core/action.js'; import { API } from 'lib/api.js'; let defaultAction = Action.create(function(argument) { API.prototype.formRawSubmit.apply(this, arguments); }) export default { shouldDefaultAction: defaultAction, shouldFormSubmit: defaultAction, goodAddToCart: Action.create(function(argument) { API.prototype.goodAddToCart(argument); }), shouldRemoveGood: API.prototype.goodRemoveFromCart, shouldRecountOrder: API.prototype.orderRecount, shouldReset: API.prototype.cartReset, shouldRefresh: API.prototype.cartRefresh, shouldAuth: Action.create(function() { API.prototype.userAuth.apply(this, arguments); }) }
proxyfabio/modx-shopmodx-frontend
src/actions/appViewActions.js
JavaScript
mit
779
/// //////////////////////////////////////// // GOOGLE BOOKS /// //////////////////////////////////////// console.log('google books connector loading...') /// //////////////////////////////////////// // GOOGLEBOOKS VARIABLES /// //////////////////////////////////////// var url = '' var key = '' /// //////////////////////////////////////// // Function: search /// //////////////////////////////////////// exports.search = function (query, callback) { }
LibrariesHacked/catalogues-librarydata
connectors/googlebooks.js
JavaScript
mit
457
using System; using Com.Aspose.Imaging.Api; using Com.Aspose.Imaging.Model; using Com.Aspose.Storage.Api; namespace Images { class UpdatePngProperties { public static void Run() { // ExStart:1 ImagingApi imagingApi = new ImagingApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH); StorageApi storageApi = new StorageApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH); String fileName = "aspose_imaging_for_cloud.png"; bool fromScratch = true; String outPath = ""; String folder = ""; String storage = ""; try { // Upload source file to aspose cloud storage storageApi.PutCreate(fileName, "", "", System.IO.File.ReadAllBytes(Common.GetDataDir() + fileName)); // Invoke Aspose.Imaging Cloud SDK API to update Png image properties ResponseMessage apiResponse = imagingApi.GetImagePng(fileName, fromScratch, outPath, folder, storage); if (apiResponse != null) { System.IO.File.WriteAllBytes(Common.GetDataDir() + fileName, apiResponse.ResponseStream); Console.WriteLine("Working with PNG Properties - Update PNG Image Properties, Done!"); Console.ReadKey(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("error:" + ex.Message + "\n" + ex.StackTrace); } // ExEnd:1 } } }
aspose-imaging/Aspose.Imaging-for-Cloud
Examples/DotNET/CSharp/Images/UpdatePngProperties.cs
C#
mit
1,618
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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 SharpDX.IO; using SharpDX.Multimedia; using SharpDX.Toolkit.Content; using SharpDX.Toolkit.Serialization; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A delegate to load binary bitmap data from a bitmap name (currently used to load external bitmap referenced in AngelCode Bitmap data). /// </summary> /// <param name="bitmapName">The name of the bitmap data to load.</param> /// <returns>A bitmap data object.</returns> public delegate object SpriteFontBitmapDataLoaderDelegate(string bitmapName); /// <summary> /// Data for a SpriteFont object that supports kerning. /// </summary> /// <remarks> /// Loading of SpriteFontData supports DirectXTk "MakeSpriteFont" format and AngelCode Bitmap Font Maker (binary format). /// </remarks> [ContentReader(typeof(SpriteFontDataContentReader))] public partial class SpriteFontData : IDataSerializable { public const string FontMagicCode = "TKFT"; public const int Version = 0x100; /// <summary> /// The number of pixels from the absolute top of the line to the base of the characters. /// </summary> public float BaseOffset; /// <summary> /// This is the distance in pixels between each line of text. /// </summary> public float LineSpacing; /// <summary> /// The default character fallback. /// </summary> public char DefaultCharacter; /// <summary> /// An array of <see cref="Glyph"/> data. /// </summary> public Glyph[] Glyphs; /// <summary> /// An array of <see cref="Bitmap"/> data. /// </summary> public Bitmap[] Bitmaps; /// <summary> /// An array of <see cref="Kerning"/> data. /// </summary> public Kerning[] Kernings; /// <summary> /// Loads a <see cref="SpriteFontData"/> from the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <param name="bitmapDataLoader">A delegate to load bitmap data that are not stored in the buffer.</param> /// <returns>An <see cref="SpriteFontData"/>. Null if the stream is not a serialized <see cref="SpriteFontData"/>.</returns> public static SpriteFontData Load(Stream stream, SpriteFontBitmapDataLoaderDelegate bitmapDataLoader = null) { var serializer = new BinarySerializer(stream, SerializerMode.Read, Text.Encoding.ASCII) {ArrayLengthType = ArrayLengthType.Int}; var data = new SpriteFontData(); var magicCode = FourCC.Empty; serializer.Serialize(ref magicCode); if (magicCode == "DXTK") { data.SerializeMakeSpriteFont(serializer); } else if (magicCode == new FourCC(0x03464D42)) // BMF\3 { data.SerializeBMFFont(serializer); } else { return null; } // Glyphs are null, then this is not a SpriteFondData if (data.Glyphs == null) return null; if (bitmapDataLoader != null) { foreach (var bitmap in data.Bitmaps) { // If the bitmap data is a string, then this is a texture to load if (bitmap.Data is string) { bitmap.Data = bitmapDataLoader((string) bitmap.Data); } } } return data; } /// <summary> /// Loads a <see cref="SpriteFontData"/> from the specified stream. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="bitmapDataLoader">A delegate to load bitmap data that are not stored in the buffer.</param> /// <returns>An <see cref="SpriteFontData"/>. Null if the stream is not a serialized <see cref="SpriteFontData"/>.</returns> public static SpriteFontData Load(byte[] buffer, SpriteFontBitmapDataLoaderDelegate bitmapDataLoader = null) { return Load(new MemoryStream(buffer), bitmapDataLoader); } /// <summary> /// Loads a <see cref="SpriteFontData"/> from the specified stream. /// </summary> /// <param name="fileName">The filename.</param> /// <param name="bitmapDataLoader">A delegate to load bitmap data that are not stored in the buffer.</param> /// <returns>An <see cref="SpriteFontData"/>. Null if the stream is not a serialized <see cref="SpriteFontData"/>.</returns> public static SpriteFontData Load(string fileName, SpriteFontBitmapDataLoaderDelegate bitmapDataLoader = null) { using (var stream = new NativeFileStream(fileName, NativeFileMode.Open, NativeFileAccess.Read)) return Load(stream, bitmapDataLoader); } void IDataSerializable.Serialize(BinarySerializer serializer) { // TODO implement a custom serial here throw new NotImplementedException(); // string magic = FontMagicCode; // serializer.Serialize(ref magic, FontMagicCode.Length); // if (magic != FontMagicCode) // { // // Make sure that Glyphs is null // //Glyphs = null; // return; // } // //serializer.Serialize(ref Glyphs); // serializer.Serialize(ref LineSpacing); // serializer.Serialize(ref DefaultCharacter); // //serializer.Serialize(ref Image); } } }
sharpdx/Toolkit
Source/Toolkit/SharpDX.Toolkit/Graphics/SpriteFontData.cs
C#
mit
6,860
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as fs from 'fs'; import * as ts from 'typescript'; import MagicString from 'magic-string'; import {fromObject, generateMapFileComment} from 'convert-source-map'; import {makeProgram} from '../helpers/utils'; import {AnalyzedClass, Analyzer} from '../../src/analyzer'; import {Fesm2015ReflectionHost} from '../../src/host/fesm2015_host'; import {Esm2015FileParser} from '../../src/parsing/esm2015_parser'; import {Renderer} from '../../src/rendering/renderer'; class TestRenderer extends Renderer { addImports(output: MagicString, imports: {name: string, as: string}[]) { output.prepend('\n// ADD IMPORTS\n'); } addConstants(output: MagicString, constants: string, file: ts.SourceFile): void { output.prepend('\n// ADD CONSTANTS\n'); } addDefinitions(output: MagicString, analyzedClass: AnalyzedClass, definitions: string) { output.prepend('\n// ADD DEFINITIONS\n'); } removeDecorators(output: MagicString, decoratorsToRemove: Map<ts.Node, ts.Node[]>) { output.prepend('\n// REMOVE DECORATORS\n'); } } function createTestRenderer() { const renderer = new TestRenderer({} as Fesm2015ReflectionHost); spyOn(renderer, 'addImports').and.callThrough(); spyOn(renderer, 'addDefinitions').and.callThrough(); spyOn(renderer, 'removeDecorators').and.callThrough(); return renderer as jasmine.SpyObj<TestRenderer>; } function analyze(file: {name: string, contents: string}) { const program = makeProgram(file); const host = new Fesm2015ReflectionHost(program.getTypeChecker()); const parser = new Esm2015FileParser(program, host); const analyzer = new Analyzer(program.getTypeChecker(), host); const parsedFiles = parser.parseFile(program.getSourceFile(file.name) !); return parsedFiles.map(file => analyzer.analyzeFile(file)); } describe('Renderer', () => { const INPUT_PROGRAM = { name: '/file.js', contents: `import { Directive } from '@angular/core';\nexport class A {\n foo(x) {\n return x;\n }\n}\nA.decorators = [\n { type: Directive, args: [{ selector: '[a]' }] }\n];\n` }; const INPUT_PROGRAM_MAP = fromObject({ 'version': 3, 'file': '/file.js', 'sourceRoot': '', 'sources': ['/file.ts'], 'names': [], 'mappings': 'AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,MAAM;IACF,GAAG,CAAC,CAAS;QACT,OAAO,CAAC,CAAC;IACb,CAAC;;AACM,YAAU,GAAG;IAChB,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE;CACnD,CAAC', 'sourcesContent': [ 'import { Directive } from \'@angular/core\';\nexport class A {\n foo(x: string): string {\n return x;\n }\n static decorators = [\n { type: Directive, args: [{ selector: \'[a]\' }] }\n ];\n}' ] }); const RENDERED_CONTENTS = `\n// REMOVE DECORATORS\n\n// ADD IMPORTS\n\n// ADD CONSTANTS\n\n// ADD DEFINITIONS\n` + INPUT_PROGRAM.contents; const OUTPUT_PROGRAM_MAP = fromObject({ 'version': 3, 'file': '/output_file.js', 'sources': ['/file.js'], 'sourcesContent': [ 'import { Directive } from \'@angular/core\';\nexport class A {\n foo(x) {\n return x;\n }\n}\nA.decorators = [\n { type: Directive, args: [{ selector: \'[a]\' }] }\n];\n' ], 'names': [], 'mappings': ';;;;;;;;AAAA;;;;;;;;;' }); const MERGED_OUTPUT_PROGRAM_MAP = fromObject({ 'version': 3, 'sources': ['/file.ts'], 'names': [], 'mappings': ';;;;;;;;AAAA', 'file': '/output_file.js', 'sourcesContent': [ 'import { Directive } from \'@angular/core\';\nexport class A {\n foo(x: string): string {\n return x;\n }\n static decorators = [\n { type: Directive, args: [{ selector: \'[a]\' }] }\n ];\n}' ] }); describe('renderFile()', () => { it('should render the modified contents; and a new map file, if the original provided no map file.', () => { const renderer = createTestRenderer(); const analyzedFiles = analyze(INPUT_PROGRAM); const result = renderer.renderFile(analyzedFiles[0], '/output_file.js'); expect(result.source.path).toEqual('/output_file.js'); expect(result.source.contents) .toEqual(RENDERED_CONTENTS + '\n' + generateMapFileComment('/output_file.js.map')); expect(result.map !.path).toEqual('/output_file.js.map'); expect(result.map !.contents).toEqual(OUTPUT_PROGRAM_MAP.toJSON()); }); it('should call addImports with the source code and info about the core Angular library.', () => { const renderer = createTestRenderer(); const analyzedFiles = analyze(INPUT_PROGRAM); renderer.renderFile(analyzedFiles[0], '/output_file.js'); expect(renderer.addImports.calls.first().args[0].toString()).toEqual(RENDERED_CONTENTS); expect(renderer.addImports.calls.first().args[1]).toEqual([ {name: '@angular/core', as: 'ɵngcc0'} ]); }); it('should call addDefinitions with the source code, the analyzed class and the renderered definitions.', () => { const renderer = createTestRenderer(); const analyzedFile = analyze(INPUT_PROGRAM)[0]; renderer.renderFile(analyzedFile, '/output_file.js'); expect(renderer.addDefinitions.calls.first().args[0].toString()) .toEqual(RENDERED_CONTENTS); expect(renderer.addDefinitions.calls.first().args[1]) .toBe(analyzedFile.analyzedClasses[0]); expect(renderer.addDefinitions.calls.first().args[2]) .toEqual( `A.ngDirectiveDef = ɵngcc0.ɵdefineDirective({ type: A, selectors: [["", "a", ""]], factory: function A_Factory(t) { return new (t || A)(); }, features: [ɵngcc0.ɵPublicFeature] });`); }); it('should call removeDecorators with the source code, a map of class decorators that have been analyzed', () => { const renderer = createTestRenderer(); const analyzedFile = analyze(INPUT_PROGRAM)[0]; renderer.renderFile(analyzedFile, '/output_file.js'); expect(renderer.removeDecorators.calls.first().args[0].toString()) .toEqual(RENDERED_CONTENTS); // Each map key is the TS node of the decorator container // Each map value is an array of TS nodes that are the decorators to remove const map = renderer.removeDecorators.calls.first().args[1] as Map<ts.Node, ts.Node[]>; const keys = Array.from(map.keys()); expect(keys.length).toEqual(1); expect(keys[0].getText()) .toEqual(`[\n { type: Directive, args: [{ selector: '[a]' }] }\n]`); const values = Array.from(map.values()); expect(values.length).toEqual(1); expect(values[0].length).toEqual(1); expect(values[0][0].getText()).toEqual(`{ type: Directive, args: [{ selector: '[a]' }] }`); }); it('should merge any inline source map from the original file and write the output as an inline source map', () => { const renderer = createTestRenderer(); const analyzedFiles = analyze({ ...INPUT_PROGRAM, contents: INPUT_PROGRAM.contents + '\n' + INPUT_PROGRAM_MAP.toComment() }); const result = renderer.renderFile(analyzedFiles[0], '/output_file.js'); expect(result.source.path).toEqual('/output_file.js'); expect(result.source.contents) .toEqual(RENDERED_CONTENTS + '\n' + MERGED_OUTPUT_PROGRAM_MAP.toComment()); expect(result.map).toBe(null); }); it('should merge any external source map from the original file and write the output to an external source map', () => { // Mock out reading the map file from disk const readFileSyncSpy = spyOn(fs, 'readFileSync').and.returnValue(INPUT_PROGRAM_MAP.toJSON()); const renderer = createTestRenderer(); const analyzedFiles = analyze({ ...INPUT_PROGRAM, contents: INPUT_PROGRAM.contents + '\n//# sourceMappingURL=file.js.map' }); const result = renderer.renderFile(analyzedFiles[0], '/output_file.js'); expect(result.source.path).toEqual('/output_file.js'); expect(result.source.contents) .toEqual(RENDERED_CONTENTS + '\n' + generateMapFileComment('/output_file.js.map')); expect(result.map !.path).toEqual('/output_file.js.map'); expect(result.map !.contents).toEqual(MERGED_OUTPUT_PROGRAM_MAP.toJSON()); }); }); });
mgiambalvo/angular
packages/compiler-cli/src/ngcc/test/rendering/renderer_spec.ts
TypeScript
mit
8,733
require 'spec_helper' RSpec.describe Vpsa::Api::Receipts do let(:header) {{"Content-Type" => "application/json", "Accept" => "application/json"}} describe "listing" do before(:each) do stub_request(:get, "#{Vpsa::API_ADDRESS}/contas-receber/").to_return(:status => 200) end it "should issue a get to the receipts url" do expect(Vpsa::Api::Receipts).to receive(:get).with("/", :body => {:token => "abc"}.to_json, :headers => header).and_call_original Vpsa.new("abc").receipts.list() end it "should issue a get to the reciepts url using the searcher" do searcher = Vpsa::Searcher::Financial::ReceiptSearcher.new({:quantidade => 10, :inicio => 0, :desde => '01-01-2015', :ate => '10-01-2015', :filtroData => 'dataVencimento', :alteradoApos => '01-01-2015 10:10:10'}) expect(Vpsa::Api::Receipts).to receive(:get).with("/", :body => searcher.as_parameter.merge!({:token => "abc"}).to_json, :headers => header).and_call_original Vpsa.new("abc").receipts.list(searcher) end it "should raise ArgumentError if the parameter is not a ReceiptSearcher" do expect{Vpsa.new("abc").receipts.list(Array.new)}.to raise_error(ArgumentError) end end describe "find" do before(:each) do stub_request(:get, "#{Vpsa::API_ADDRESS}/contas-receber/1").to_return(:status => 200) end it "should return an especific receipt" do expect(Vpsa::Api::Receipts).to receive(:get).with("/1", :body => {:token => "abc"}.to_json, :headers => header).and_call_original Vpsa.new("abc").receipts.find(1) end end end
coyosoftware/vpsa
spec/vpsa/api/receipts_spec.rb
Ruby
mit
1,646
require './spec/spec_helper.rb' describe "Oxcelix module" do describe 'Workbook' do context 'normal' do it "should open the excel file and return a Workbook object" do file = 'spec/fixtures/test.xlsx' w=Oxcelix::Workbook.new(file) w.sheets.size.should == 2 w.sheets[0].name.should == "Testsheet1" w.sheets[1].name.should == "Testsheet2" end end context 'with excluded sheets' do it "should open the sheets not excluded of the excel file" do file = 'spec/fixtures/test.xlsx' w=Oxcelix::Workbook.new(file, {:exclude=>['Testsheet2']}) w.sheets.size.should == 1 w.sheets[0].name.should == "Testsheet1" end end context 'with included sheets' do it "should open only the included sheets of the excel file" do file = 'spec/fixtures/test.xlsx' w = Oxcelix::Workbook.new(file, {:include=>['Testsheet2']}) w.sheets.size.should == 1 w.sheets[0].name.should == "Testsheet2" end end end end
Orphist/oxcelix_xlsx
spec/oxcelix_spec.rb
Ruby
mit
1,061
/* * Copyright (c) 2005, the JUNG Project and the Regents of the University of * California All rights reserved. * * This software is open-source under the BSD license; see either "license.txt" * or http://jung.sourceforge.net/license.txt for a description. * * Created on Jul 21, 2005 */ package edu.uci.ics.jung.visualization.jai; import java.awt.Dimension; import edu.uci.ics.jung.algorithms.layout.GraphElementAccessor; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.RenderContext; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalLensGraphMouse; import edu.uci.ics.jung.visualization.picking.ViewLensShapePickSupport; import edu.uci.ics.jung.visualization.renderers.BasicRenderer; import edu.uci.ics.jung.visualization.renderers.Renderer; import edu.uci.ics.jung.visualization.renderers.ReshapingEdgeRenderer; import edu.uci.ics.jung.visualization.transform.AbstractLensSupport; import edu.uci.ics.jung.visualization.transform.LensTransformer; import edu.uci.ics.jung.visualization.transform.shape.GraphicsDecorator; import edu.uci.ics.jung.visualization.transform.shape.HyperbolicShapeTransformer; import edu.uci.ics.jung.visualization.transform.shape.TransformingFlatnessGraphics; /** * A class to make it easy to add a Hyperbolic projection * examining lens to a jung graph application. See HyperbolicTransforerDemo * for an example of how to use it. * * @author Tom Nelson * * */ public class HyperbolicImageLensSupport<V,E> extends AbstractLensSupport<V,E> { protected RenderContext<V,E> renderContext; protected GraphicsDecorator lensGraphicsDecorator; protected GraphicsDecorator savedGraphicsDecorator; protected Renderer<V,E> renderer; protected Renderer<V,E> transformingRenderer; protected GraphElementAccessor<V,E> pickSupport; protected Renderer.Edge<V,E> savedEdgeRenderer; protected Renderer.Edge<V,E> reshapingEdgeRenderer; static final String instructions = "<html><center>Mouse-Drag the Lens center to move it<p>"+ "Mouse-Drag the Lens edge to resize it<p>"+ "Ctrl+MouseWheel to change magnification</center></html>"; public HyperbolicImageLensSupport(VisualizationViewer<V,E> vv) { this(vv, new HyperbolicShapeTransformer(vv), new ModalLensGraphMouse()); } /** * create the base class, setting common members and creating * a custom GraphMouse * @param vv the VisualizationViewer to work on */ public HyperbolicImageLensSupport(VisualizationViewer<V,E> vv, LensTransformer lensTransformer, ModalGraphMouse lensGraphMouse) { super(vv, lensGraphMouse); this.renderContext = vv.getRenderContext(); this.pickSupport = renderContext.getPickSupport(); this.renderer = vv.getRenderer(); this.transformingRenderer = new BasicRenderer<V,E>(); this.transformingRenderer.setVertexRenderer(new TransformingImageVertexIconRenderer<V,E>()); this.savedGraphicsDecorator = renderContext.getGraphicsContext(); this.lensTransformer = lensTransformer; this.savedEdgeRenderer = vv.getRenderer().getEdgeRenderer(); this.reshapingEdgeRenderer = new ReshapingEdgeRenderer<V,E>(); this.reshapingEdgeRenderer.setEdgeArrowRenderingSupport(savedEdgeRenderer.getEdgeArrowRenderingSupport()); Dimension d = vv.getSize(); // if(d.width == 0 || d.height == 0) { // d = vv.getPreferredSize(); // } lensTransformer.setViewRadius(d.width/5); this.lensGraphicsDecorator = new TransformingFlatnessGraphics(lensTransformer); } public void activate() { lensTransformer.setDelegate(vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)); if(lens == null) { lens = new Lens(lensTransformer); } if(lensControls == null) { lensControls = new LensControls(lensTransformer); } renderContext.setPickSupport(new ViewLensShapePickSupport<V,E>(vv)); lensTransformer.setDelegate(vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)); vv.getRenderContext().getMultiLayerTransformer().setTransformer(Layer.VIEW, lensTransformer); this.renderContext.setGraphicsContext(lensGraphicsDecorator); vv.setRenderer(transformingRenderer); vv.getRenderer().setEdgeRenderer(reshapingEdgeRenderer); vv.addPreRenderPaintable(lens); vv.addPostRenderPaintable(lensControls); vv.setGraphMouse(lensGraphMouse); vv.setToolTipText(instructions); vv.repaint(); } public void deactivate() { renderContext.setPickSupport(pickSupport); vv.getRenderContext().getMultiLayerTransformer().setTransformer(Layer.VIEW, lensTransformer.getDelegate()); vv.removePreRenderPaintable(lens); vv.removePostRenderPaintable(lensControls); this.renderContext.setGraphicsContext(savedGraphicsDecorator); vv.setRenderer(renderer); vv.setToolTipText(defaultToolTipText); vv.setGraphMouse(graphMouse); vv.repaint(); } }
pdeboer/wikilanguage
lib/jung2/jung-jai/src/main/java/edu/uci/ics/jung/visualization/jai/HyperbolicImageLensSupport.java
Java
mit
5,311
<?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About GoldCoin</source> <translation>Apie GoldCoiną</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;GoldCoin (GLD)&lt;/b&gt; version</source> <translation>&lt;b&gt;GoldCoin (GLD)&lt;/b&gt; versija</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="97"/> <source>Copyright © 2013-2015 GoldCoin (GLD) Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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>Autorystės teisės© 2009-2012 GoldCoin Developers DĖMESIO: programa eksperimentinė! Platinama pagal licenziją MIT/X11, papildomą informaciją rasite faile license.txt arba dokumente pagal nuorodą: http://www.opensource.org/licenses/mit-license.php. Šiame produkte yra projekto OpenSSL (http://www.openssl.org/), Eriko Jango (eay@cryptsoft.com) parašyti kriptografinės funkcijos ir algoritmai ir UPnP darbui skirtos funkcijos parašytos Tomo Bernardo. </translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>Adresų knygelė</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your GoldCoin 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>Čia yra Jūsų adresai skirti mokėjimams gauti. Jūs galite skirtingiems žmonėms duoti skirtingus adresus. Tai Jums palengvins kontroliuoti mokėjimus bei padidins anonimiškumą. </translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="36"/> <source>Double-click to edit address or label</source> <translation>Tam, kad pakeisti ar redaguoti adresą arba žymę turite objektą dukart spragtelti pele.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="63"/> <source>Create a new address</source> <translation>Sukurti naują adresą</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="77"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopijuoti esamą adresą į mainų atmintį</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="66"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="80"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="91"/> <source>Show &amp;QR Code</source> <translation>Rodyti &amp;QR kodą</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="102"/> <source>Sign a message to prove you own this address</source> <translation>Registruotis žinute įrodančia, kad turite šį adresą</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="105"/> <source>&amp;Sign Message</source> <translation>&amp;S Registruotis žinute</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="116"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>Pašalinti iš sąrašo pažymėtą adresą(gali būti pašalinti tiktai adresų knygelės įrašai).</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="119"/> <source>&amp;Delete</source> <translation>&amp;D Pašalinti</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="65"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="292"/> <source>Export Address Book Data</source> <translation>Eksportuoti adresų knygelės duomenis</translation> </message> <message> <location filename="../addressbookpage.cpp" line="293"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais išskirtas failas (*.csv)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Error exporting</source> <translation>Eksportavimo klaida</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Could not write to file %1.</source> <translation>Nepavyko įrašyti į failą %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="178"/> <source>(no label)</source> <translation>(nėra žymės)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="47"/> <source>Enter passphrase</source> <translation>Įvesti slaptažodį</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="61"/> <source>New passphrase</source> <translation>Naujas slaptažodis</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="75"/> <source>Repeat new passphrase</source> <translation>Pakartoti naują slaptažodį</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Įveskite naują slaptažodį piniginei &lt;br/&gt; Prašome naudoti slaptažodį iš &lt;b&gt; 10 ar daugiau atsitiktinių simbolių &lt;/b&gt; arba &lt;b&gt; aštuonių ar daugiau žodžių &lt;/b&gt;.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Encrypt wallet</source> <translation>Užšifruoti piniginę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="37"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptažodžio jai atrakinti.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="42"/> <source>Unlock wallet</source> <translation>Atrakinti piniginę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="45"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptažodžio jai iššifruoti.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="50"/> <source>Decrypt wallet</source> <translation>Iššifruoti piniginę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="53"/> <source>Change passphrase</source> <translation>Pakeisti slaptažodį</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Įveskite seną ir naują piniginės slaptažodžius</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="100"/> <source>Confirm wallet encryption</source> <translation>Patvirtinkite piniginės užšifravimą</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>ĮSPĖJIMAS: Jei užšifruosite savo piniginę ir prarasite savo slaptažodį, Jūs &lt;b&gt; PRARASITE VISUS SAVO BITKOINUS, &lt;/b&gt;! Ar jūs tikrai norite užšifruoti savo piniginę?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="110"/> <location filename="../askpassphrasedialog.cpp" line="159"/> <source>Wallet encrypted</source> <translation>Piniginė užšifruota</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <source>GoldCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>GoldCoin dabar užsidarys šifravimo proceso pabaigai. Atminkite, kad piniginės šifravimas negali pilnai apsaugoti bitcoinų vagysčių kai tinkle esančios kenkėjiškos programos patenka į jūsų kompiuterį.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="207"/> <location filename="../askpassphrasedialog.cpp" line="231"/> <source>Warning: The Caps Lock key is on.</source> <translation>ĮSPĖJIMAS: Įjungtos didžiosios raidės</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="116"/> <location filename="../askpassphrasedialog.cpp" line="123"/> <location filename="../askpassphrasedialog.cpp" line="165"/> <location filename="../askpassphrasedialog.cpp" line="171"/> <source>Wallet encryption failed</source> <translation>Nepavyko užšifruoti piniginę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>The supplied passphrases do not match.</source> <translation>Įvestas slaptažodis nesutampa</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="135"/> <source>Wallet unlock failed</source> <translation>Nepavyko atrakinti piniginę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <location filename="../askpassphrasedialog.cpp" line="147"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation> Neteisingai įvestas slaptažodis piniginės iššifravimui</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="146"/> <source>Wallet decryption failed</source> <translation>Nepavyko iššifruoti piniginę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet passphrase was succesfully changed.</source> <translation>Sėkmingai pakeistas piniginės slaptažodis</translation> </message> </context> <context> <name>GoldCoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="73"/> <source>GoldCoin Wallet</source> <translation>Bitkoinų piniginė</translation> </message> <message> <location filename="../bitcoingui.cpp" line="215"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>Show/Hide &amp;GoldCoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="515"/> <source>Synchronizing with network...</source> <translation>Sinchronizavimas su tinklu ...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="185"/> <source>&amp;Overview</source> <translation>&amp;O Apžvalga</translation> </message> <message> <location filename="../bitcoingui.cpp" line="186"/> <source>Show general overview of wallet</source> <translation>Rodyti piniginės bendrą apžvalgą</translation> </message> <message> <location filename="../bitcoingui.cpp" line="191"/> <source>&amp;Transactions</source> <translation>&amp;T Sandoriai</translation> </message> <message> <location filename="../bitcoingui.cpp" line="192"/> <source>Browse transaction history</source> <translation>Apžvelgti sandorių istoriją</translation> </message> <message> <location filename="../bitcoingui.cpp" line="197"/> <source>&amp;Address Book</source> <translation>&amp;Adresų knygelė</translation> </message> <message> <location filename="../bitcoingui.cpp" line="198"/> <source>Edit the list of stored addresses and labels</source> <translation>Redaguoti išsaugotus adresus bei žymes</translation> </message> <message> <location filename="../bitcoingui.cpp" line="203"/> <source>&amp;Receive coins</source> <translation>&amp;R Gautos monetos</translation> </message> <message> <location filename="../bitcoingui.cpp" line="204"/> <source>Show the list of addresses for receiving payments</source> <translation>Parodyti adresų sąraša mokėjimams gauti</translation> </message> <message> <location filename="../bitcoingui.cpp" line="209"/> <source>&amp;Send coins</source> <translation>&amp;Siųsti monetas</translation> </message> <message> <location filename="../bitcoingui.cpp" line="216"/> <source>Prove you control an address</source> <translation>Įrodyti, kad jūs valdyti adresą</translation> </message> <message> <location filename="../bitcoingui.cpp" line="235"/> <source>E&amp;xit</source> <translation>&amp;x išėjimas</translation> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>Quit application</source> <translation>Išjungti programą</translation> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>&amp;About %1</source> <translation>&amp;Apie %1</translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show information About GoldCoin</source> <translation>Rodyti informaciją apie Bitkoiną</translation> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>About &amp;Qt</source> <translation>Apie &amp;Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>Show information about Qt</source> <translation>Rodyti informaciją apie Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="245"/> <source>&amp;Options...</source> <translation>&amp;Opcijos...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="252"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="255"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="257"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="517"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="528"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="250"/> <source>&amp;Export...</source> <translation>&amp;Eksportas...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="210"/> <source>Send coins to a GoldCoin address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>Modify configuration options for GoldCoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Show or hide the GoldCoin window</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="251"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="253"/> <source>Encrypt or decrypt wallet</source> <translation>Užšifruoti ar iššifruoti piniginę</translation> </message> <message> <location filename="../bitcoingui.cpp" line="256"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="258"/> <source>Change the passphrase used for wallet encryption</source> <translation>Pakeisti slaptažodį naudojamą piniginės užšifravimui</translation> </message> <message> <location filename="../bitcoingui.cpp" line="259"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="260"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="261"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="262"/> <source>Verify a message signature</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="286"/> <source>&amp;File</source> <translation>&amp;Failas</translation> </message> <message> <location filename="../bitcoingui.cpp" line="296"/> <source>&amp;Settings</source> <translation>Nu&amp;Statymai</translation> </message> <message> <location filename="../bitcoingui.cpp" line="302"/> <source>&amp;Help</source> <translation>&amp;H Pagelba</translation> </message> <message> <location filename="../bitcoingui.cpp" line="311"/> <source>Tabs toolbar</source> <translation>Tabs įrankių juosta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="322"/> <source>Actions toolbar</source> <translation>Veiksmų įrankių juosta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="334"/> <location filename="../bitcoingui.cpp" line="343"/> <source>[testnet]</source> <translation>[testavimotinklas]</translation> </message> <message> <location filename="../bitcoingui.cpp" line="343"/> <location filename="../bitcoingui.cpp" line="399"/> <source>GoldCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="492"/> <source>%n active connection(s) to GoldCoin network</source> <translation><numerusform>%n GoldCoin tinklo aktyvus ryšys</numerusform><numerusform>%n GoldCoin tinklo aktyvūs ryšiai</numerusform><numerusform>%n GoldCoin tinklo aktyvūs ryšiai</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="540"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Atsisiuntė %1 iš %2 sandorių istorijos blokų</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="555"/> <source>%n second(s) ago</source> <translation><numerusform>Prieš %n sekundę</numerusform><numerusform>Prieš %n sekundes</numerusform><numerusform>Prieš %n sekundžių</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="559"/> <source>%n minute(s) ago</source> <translation><numerusform>Prieš %n minutę</numerusform><numerusform>Prieš %n minutes</numerusform><numerusform>Prieš %n minutčių</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="563"/> <source>%n hour(s) ago</source> <translation><numerusform>Prieš %n valandą</numerusform><numerusform>Prieš %n valandas</numerusform><numerusform>Prieš %n valandų</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="567"/> <source>%n day(s) ago</source> <translation><numerusform>Prieš %n dieną</numerusform><numerusform>Prieš %n dienas</numerusform><numerusform>Prieš %n dienų</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="573"/> <source>Up to date</source> <translation>Iki šiol</translation> </message> <message> <location filename="../bitcoingui.cpp" line="580"/> <source>Catching up...</source> <translation>Gaudo...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="590"/> <source>Last received block was generated %1.</source> <translation>Paskutinis gautas blokas buvo sukurtas %1.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="649"/> <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>Šis sandoris viršija leistiną dydį. Jūs galite įvykdyti jį papildomai sumokėję %1 mokesčių, kurie bus išsiųsti tais pačiais mazgais kuriais vyko sandoris ir padės palaikyti tinklą. Ar jūs norite apmokėti papildomą mokestį?</translation> </message> <message> <location filename="../bitcoingui.cpp" line="654"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="681"/> <source>Sent transaction</source> <translation>Sandoris nusiųstas</translation> </message> <message> <location filename="../bitcoingui.cpp" line="682"/> <source>Incoming transaction</source> <translation>Ateinantis sandoris</translation> </message> <message> <location filename="../bitcoingui.cpp" line="683"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Suma: %2 Tipas: %3 Adresas: %4</translation> </message> <message> <location filename="../bitcoingui.cpp" line="804"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;atrakinta&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="812"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;užrakinta&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="112"/> <source>A fatal error occured. GoldCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="84"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="246"/> <source>Display</source> <translation>Ekranas</translation> </message> <message> <location filename="../optionsdialog.cpp" line="257"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="263"/> <source>The user interface language can be set here. This setting will only take effect after restarting GoldCoin.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="252"/> <source>User Interface &amp;Language:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="273"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="277"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation> </message> <message> <location filename="../optionsdialog.cpp" line="284"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="285"/> <source>Whether to show GoldCoin addresses in the transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>This setting will take effect after restarting GoldCoin.</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Redaguoti adresą</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>&amp;L Žymė</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>Žymė yra susieta su šios adresų knygelęs turiniu</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;Adresas</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresas yra susietas su šios adresų knygelęs turiniu. Tai gali būti keičiama tik siuntimo adresams.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>Naujas gavimo adresas</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>Naujas siuntimo adresas</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>Taisyti gavimo adresą</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>Taisyti siuntimo adresą</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Įvestas adresas &quot;%1&quot;yra adresų knygelėje</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid GoldCoin address.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>Neįmanoma atrakinti piniginės</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>Naujas raktas nesukurtas</translation> </message> </context> <context> <name>HelpMessageBox</name> <message> <location filename="../bitcoin.cpp" line="133"/> <location filename="../bitcoin.cpp" line="143"/> <source>GoldCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="133"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="135"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location filename="../bitcoin.cpp" line="136"/> <source>options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="138"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="139"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="140"/> <source>Start minimized</source> <translation>Pradžia sumažinta</translation> </message> <message> <location filename="../bitcoin.cpp" line="141"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="227"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="212"/> <source>Pay transaction &amp;fee</source> <translation>&amp;f Mokėti sandorio mokestį</translation> </message> <message> <location filename="../optionsdialog.cpp" line="204"/> <source>Main</source> <translation>Pagrindinis</translation> </message> <message> <location filename="../optionsdialog.cpp" line="206"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Neprivaloma sandorio mokestis už KB, kuris padeda įsitikinti, kad jūsų sandoriai tvarkomi greitai. Daugelis sandorių yra tik 1KB dydžio. Rekomenduojamas 0,01 mokestis.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="222"/> <source>&amp;Start GoldCoin on system login</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Automatically start GoldCoin after logging in to the system</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>Pasirinkite adresą iš adresų knygelės</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation>Įveskite pranešimą, kurį norite pasirašyti čia</translation> </message> <message> <location filename="../forms/messagepage.ui" line="128"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>&amp;Copy Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="142"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="145"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="31"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation>Spragtelėkite &quot;Registruotis žinutę&quot; tam, kad gauti parašą</translation> </message> <message> <location filename="../forms/messagepage.ui" line="114"/> <source>Sign a message to prove you own this address</source> <translation>Registruotis žinute įrodymuii, kad turite šį adresą</translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>&amp;Sign Message</source> <translation>&amp;S Registravimosi žinutė</translation> </message> <message> <location filename="../messagepage.cpp" line="30"/> <source>Enter a GoldCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Įveskite bitkoinų adresą (pvz. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <location filename="../messagepage.cpp" line="90"/> <location filename="../messagepage.cpp" line="105"/> <location filename="../messagepage.cpp" line="117"/> <source>Error signing</source> <translation>Klaida pasirašant</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <source>%1 is not a valid address.</source> <translation>%1 tai negaliojantis adresas</translation> </message> <message> <location filename="../messagepage.cpp" line="90"/> <source>%1 does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="105"/> <source>Private key for %1 is not available.</source> <translation>Privataus rakto %1 nėra</translation> </message> <message> <location filename="../messagepage.cpp" line="117"/> <source>Sign failed</source> <translation>Registravimas nepavyko</translation> </message> </context> <context> <name>NetworkOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="345"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="347"/> <source>Map port using &amp;UPnP</source> <translation>Prievado struktūra naudojant &amp; UPnP</translation> </message> <message> <location filename="../optionsdialog.cpp" line="348"/> <source>Automatically open the GoldCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatiškai atidaryti GoldCoin kliento maršrutizatoriaus prievadą. Tai veikia tik tada, kai jūsų maršrutizatorius palaiko UPnP ir ji įjungta.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="351"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>&amp;C Jungtis per socks4 proxy:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="352"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>Jungtis į Bitkoin tinklą per socks4 proxy (pvz. jungiantis per Tor)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="357"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="366"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="363"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresas proxy (pvz. 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="372"/> <source>Port of the proxy (e.g. 1234)</source> <translation>Proxy prievadas (pvz. 1234)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="135"/> <source>Options</source> <translation>Opcijos</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <location filename="../forms/overviewpage.ui" line="204"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GoldCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="89"/> <source>Balance:</source> <translation>Balansas</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="147"/> <source>Number of transactions:</source> <translation>Sandorių kiekis</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="118"/> <source>Unconfirmed:</source> <translation>Nepatvirtinti:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="197"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Naujausi sandoris&lt;/b&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="105"/> <source>Your current balance</source> <translation>Jūsų einamasis balansas</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="134"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Iš viso sandorių, įskaitant tuos kurie dar turi būti patvirtinti, ir jie dar nėra įskaičiuotii į einamosios sąskaitos balansą</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="154"/> <source>Total number of transactions in wallet</source> <translation>Bandras sandorių kiekis piniginėje</translation> </message> <message> <location filename="../overviewpage.cpp" line="110"/> <location filename="../overviewpage.cpp" line="111"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation>QR kodas</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="55"/> <source>Request Payment</source> <translation>Prašau išmokėti</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="70"/> <source>Amount:</source> <translation>Suma:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="105"/> <source>BTC</source> <translation>BTC</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="121"/> <source>Label:</source> <translation>Žymė:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="144"/> <source>Message:</source> <translation>Žinutė:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="186"/> <source>&amp;Save As...</source> <translation>&amp;S išsaugoti kaip...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="45"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="63"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="14"/> <source>GoldCoin debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="56"/> <location filename="../forms/rpcconsole.ui" line="79"/> <location filename="../forms/rpcconsole.ui" line="102"/> <location filename="../forms/rpcconsole.ui" line="125"/> <location filename="../forms/rpcconsole.ui" line="161"/> <location filename="../forms/rpcconsole.ui" line="214"/> <location filename="../forms/rpcconsole.ui" line="237"/> <location filename="../forms/rpcconsole.ui" line="260"/> <location filename="../rpcconsole.cpp" line="245"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="69"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="24"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="39"/> <source>Client</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="115"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="144"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="151"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="174"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="197"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="204"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="227"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="250"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="292"/> <source>Debug logfile</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="299"/> <source>Open the GoldCoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="302"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="323"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="92"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="372"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="212"/> <source>Welcome to the GoldCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="213"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="214"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>Siųsti monetas</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>Siųsti keliems gavėjams vienu metu</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add Recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation>Pašalinti visus sandorio laukus</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>Balansas:</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>Patvirtinti siuntimo veiksmą</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>&amp;Siųsti</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>Patvirtinti siuntimui monetas</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>Ar esate įsitikinę, kad norite siųsti %1?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation>ir</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>Apmokėjimo suma turi būti didesnė negu 0.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>Mokėti &amp;T gavėjui:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>&amp;L žymė:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresas mokėjimo siuntimui (pvz. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>Pasirinkite adresą iš adresų knygelės</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>Pašalinti šitą gavėją</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a GoldCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Įveskite bitkoinų adresą (pvz. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="21"/> <source>Open for %1 blocks</source> <translation>Atidaryta %1 blokams</translation> </message> <message> <location filename="../transactiondesc.cpp" line="23"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location filename="../transactiondesc.cpp" line="29"/> <source>%1/offline?</source> <translation>%1/atjungtas?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="31"/> <source>%1/unconfirmed</source> <translation>%1/nepatvirtintas</translation> </message> <message> <location filename="../transactiondesc.cpp" line="33"/> <source>%1 confirmations</source> <translation>%1 patvirtinimai</translation> </message> <message> <location filename="../transactiondesc.cpp" line="51"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;Būsena:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, has not been successfully broadcast yet</source> <translation>, transliavimas dar nebuvo sėkmingas</translation> </message> <message> <location filename="../transactiondesc.cpp" line="58"/> <source>, broadcast through %1 node</source> <translation>, transliuota per %1 mazgą</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>, broadcast through %1 nodes</source> <translation>, transliuota per %1 mazgus</translation> </message> <message> <location filename="../transactiondesc.cpp" line="64"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;Data:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="71"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;Šaltinis:&lt;/b&gt; Sukurta&lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="77"/> <location filename="../transactiondesc.cpp" line="94"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;Nuo:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source>unknown</source> <translation>nežinomas</translation> </message> <message> <location filename="../transactiondesc.cpp" line="95"/> <location filename="../transactiondesc.cpp" line="118"/> <location filename="../transactiondesc.cpp" line="178"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;Skirta:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="98"/> <source> (yours, label: </source> <translation> (jūsų, žymė: </translation> </message> <message> <location filename="../transactiondesc.cpp" line="100"/> <source> (yours)</source> <translation> (jūsų)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="136"/> <location filename="../transactiondesc.cpp" line="150"/> <location filename="../transactiondesc.cpp" line="195"/> <location filename="../transactiondesc.cpp" line="212"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;Kreditas:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="138"/> <source>(%1 matures in %2 more blocks)</source> <translation>(%1 apmokėtinas %2 daugiau blokais)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="142"/> <source>(not accepted)</source> <translation>(nepriimta)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="186"/> <location filename="../transactiondesc.cpp" line="194"/> <location filename="../transactiondesc.cpp" line="209"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>&lt;b&gt;Debitas:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="200"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>&lt;b&gt;Sandorio mokestis:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="216"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;Neto suma:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="222"/> <source>Message:</source> <translation>Žinutė:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Comment:</source> <translation>Komentaras:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="226"/> <source>Transaction ID:</source> <translation>Sandorio ID:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="229"/> <source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Išgautos monetos turi sulaukti 120 blokų, kol jos gali būti naudojamos. Kai sukūrėte šį bloką, jis buvo transliuojamas tinkle ir turėjo būti įtrauktas į blokų grandinę. Jei nepavyksta patekti į grandinę, bus pakeista į &quot;nepriėmė&quot;, o ne &quot;vartojamas&quot;. Tai kartais gali atsitikti, jei kitas mazgas per keletą sekundžių sukuria bloką po jūsų bloko.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>Sandorio išsami informacija</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>Šis langas sandorio detalų aprašymą</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Date</source> <translation>Data</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Amount</source> <translation>Suma</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="281"/> <source>Open for %n block(s)</source> <translation><numerusform>Atidaryta %n blokui</numerusform><numerusform>Atidaryta %n blokams</numerusform><numerusform>Atidaryta %n blokų</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="284"/> <source>Open until %1</source> <translation>Atidaryta kol %n</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="287"/> <source>Offline (%1 confirmations)</source> <translation>Atjungta (%1 patvirtinimai)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="290"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepatvirtintos (%1 iš %2 patvirtinimų)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="293"/> <source>Confirmed (%1 confirmations)</source> <translation>Patvirtinta (%1 patvirtinimai)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="301"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>Išgautas balansas bus pasiekiamas po %n bloko</numerusform><numerusform>Išgautas balansas bus pasiekiamas po %n blokų</numerusform><numerusform>Išgautas balansas bus pasiekiamas po %n blokų</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="307"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="310"/> <source>Generated but not accepted</source> <translation>Išgauta bet nepriimta</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="353"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="355"/> <source>Received from</source> <translation>Gauta iš</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="358"/> <source>Sent to</source> <translation>Siųsta </translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="360"/> <source>Payment to yourself</source> <translation>Mokėjimas sau</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="362"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="400"/> <source>(n/a)</source> <translation>nepasiekiama</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Date and time that the transaction was received.</source> <translation>Sandorio gavimo data ir laikas</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="603"/> <source>Type of transaction.</source> <translation>Sandorio tipas</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="605"/> <source>Destination address of transaction.</source> <translation>Sandorio paskirties adresas</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="607"/> <source>Amount removed from or added to balance.</source> <translation>Suma pridėta ar išskaičiuota iš balanso</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>Visi</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>Šiandien</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>Šią savaitę</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>Šį mėnesį</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>Paskutinį mėnesį</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>Šiais metais</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>Grupė</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>Išsiųsta</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>Skirta sau</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>Kita</translation> </message> <message> <location filename="../transactionview.cpp" line="85"/> <source>Enter address or label to search</source> <translation>Įveskite adresą ar žymę į paiešką</translation> </message> <message> <location filename="../transactionview.cpp" line="92"/> <source>Min amount</source> <translation>Minimali suma</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy address</source> <translation>Kopijuoti adresą</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Copy label</source> <translation>Kopijuoti žymę</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Copy amount</source> <translation>Kopijuoti sumą</translation> </message> <message> <location filename="../transactionview.cpp" line="129"/> <source>Edit label</source> <translation>Taisyti žymę</translation> </message> <message> <location filename="../transactionview.cpp" line="130"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="270"/> <source>Export Transaction Data</source> <translation>Sandorio duomenų eksportavimas</translation> </message> <message> <location filename="../transactionview.cpp" line="271"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais atskirtų duomenų failas (*.csv)</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Confirmed</source> <translation>Patvirtintas</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Date</source> <translation>Data</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location filename="../transactionview.cpp" line="284"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location filename="../transactionview.cpp" line="285"/> <source>ID</source> <translation>ID</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Error exporting</source> <translation>Eksportavimo klaida</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Could not write to file %1.</source> <translation>Neįmanoma įrašyti į failą %1.</translation> </message> <message> <location filename="../transactionview.cpp" line="384"/> <source>Range:</source> <translation>Grupė:</translation> </message> <message> <location filename="../transactionview.cpp" line="392"/> <source>to</source> <translation>skirta</translation> </message> </context> <context> <name>VerifyMessageDialog</name> <message> <location filename="../forms/verifymessagedialog.ui" line="14"/> <source>Verify Signed Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="20"/> <source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the GoldCoin address used to sign the message.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="62"/> <source>Verify a message and obtain the GoldCoin address used to sign the message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="65"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="79"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopijuoti pasirinktą adresą į sistemos mainų atmintį</translation> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="82"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="93"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="96"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="28"/> <source>Enter GoldCoin signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="29"/> <source>Click &quot;Verify Message&quot; to obtain address</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <location filename="../verifymessagedialog.cpp" line="62"/> <source>Invalid Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <source>The signature could not be decoded. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="62"/> <source>The signature did not match the message digest. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address not found in address book.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address found in address book: %1</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="158"/> <source>Sending...</source> <translation>Siunčiama</translation> </message> </context> <context> <name>WindowOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="313"/> <source>Window</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="316"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;M sumažinti langą bet ne užduočių juostą</translation> </message> <message> <location filename="../optionsdialog.cpp" line="317"/> <source>Show only a tray icon after minimizing the window</source> <translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="320"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="321"/> <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>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>GoldCoin version</source> <translation>GoldCoin versija</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Send command to -server or bitcoind</source> <translation>Siųsti komandą serveriui arba bitcoind</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>List commands</source> <translation>Komandų sąrašas</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source>Get help for a command</source> <translation>Suteikti pagalba komandai</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="49"/> <source>Options:</source> <translation>Opcijos:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Nurodyti konfigūracijos failą (pagal nutylėjimąt: bitcoin.conf)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>Nurodyti pid failą (pagal nutylėjimą: bitcoind.pid)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Generate coins</source> <translation>Sukurti monetas</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Don&apos;t generate coins</source> <translation>Neišgavinėti monetų</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="54"/> <source>Specify data directory</source> <translation>Nustatyti duomenų direktoriją</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="55"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="56"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Specify connection timeout (in milliseconds)</source> <translation>Nustatyti sujungimo trukmę (milisekundėmis)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Sujungimo klausymas prijungčiai &lt;port&gt; (pagal nutylėjimą: 8333 arba testnet: 18333)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Palaikyti ne daugiau &lt;n&gt; jungčių kolegoms (pagal nutylėjimą: 125)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Connect only to the specified node</source> <translation>Prisijungti tik prie nurodyto mazgo</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="69"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4 or IPv6)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="70"/> <source>Try to discover public IP address (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="75"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="79"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maksimalus buferis priėmimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="80"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maksimalus buferis siuntimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="83"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="86"/> <source>Accept command line and JSON-RPC commands</source> <translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="87"/> <source>Run in the background as a daemon and accept commands</source> <translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="88"/> <source>Use the test network</source> <translation>Naudoti testavimo tinklą</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="89"/> <source>Output extra debugging information</source> <translation>Išėjimo papildomas derinimo informacija</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="90"/> <source>Prepend debug output with timestamp</source> <translation>Prideėti laiko žymę derinimo rezultatams</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="91"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="92"/> <source>Send trace/debug info to debugger</source> <translation>Siųsti sekimo/derinimo info derintojui</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="93"/> <source>Username for JSON-RPC connections</source> <translation>Vartotojo vardas JSON-RPC jungimuisi</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="94"/> <source>Password for JSON-RPC connections</source> <translation>Slaptažodis JSON-RPC sujungimams</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="95"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>Klausymas JSON-RPC sujungimui prijungčiai &lt;port&gt; (pagal nutylėjimą: 8332)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="96"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="97"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Siųsti komandą mazgui dirbančiam &lt;ip&gt; (pagal nutylėjimą: 127.0.0.1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="98"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="101"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="102"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nustatyti rakto apimties dydį &lt;n&gt; (pagal nutylėjimą: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="103"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="104"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="105"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="106"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="108"/> <source> SSL options: (see the GoldCoin Wiki for SSL setup instructions)</source> <translation>SSL opcijos (žr.e GoldCoin Wiki for SSL setup instructions)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="111"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="112"/> <source>Server certificate file (default: server.cert)</source> <translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="113"/> <source>Server private key (default: server.pem)</source> <translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="114"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Priimtini šifrai (pagal nutylėjimą: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="145"/> <source>Warning: Disk space is low</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="107"/> <source>This help message</source> <translation>Pagelbos žinutė</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="121"/> <source>Cannot obtain a lock on data directory %s. GoldCoin is probably already running.</source> <translation>Negali gauti duomenų katalogo %s rakto. GoldCoin tikriausiai jau veikia.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="48"/> <source>GoldCoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="58"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="59"/> <source>Select the version of socks proxy to use (4 or 5, 5 is default)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>Do not use proxy for connections to network &lt;net&gt; (IPv4 or IPv6)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source>Pass DNS requests to (SOCKS5) proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="142"/> <source>Loading addresses...</source> <translation>Užkraunami adresai...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="132"/> <source>Error loading blkindex.dat</source> <translation>blkindex.dat pakrovimo klaida</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="134"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="135"/> <source>Error loading wallet.dat: Wallet requires newer version of GoldCoin</source> <translation> wallet.dat pakrovimo klaida, wallet.dat reikalauja naujasnės GoldCoin versijos</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="136"/> <source>Wallet needed to be rewritten: restart GoldCoin to complete</source> <translation>Piniginė turi būti prrašyta: įvykdymui perkraukite GoldCoin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="137"/> <source>Error loading wallet.dat</source> <translation> wallet.dat pakrovimo klaida</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="124"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="125"/> <source>Unknown network specified in -noproxy: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="127"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="126"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="128"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="129"/> <source>Not listening on any port</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="130"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="117"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="143"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="35"/> <source>Error: Transaction creation failed </source> <translation>KLAIDA:nepavyko sudaryti sandorio</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Sending...</source> <translation>Siunčiama</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <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>Klaida: sandoris buvo atmestas.Tai gali įvykti, jei kai kurios monetos iš jūsų piniginėje jau buvo panaudotos, pvz. jei naudojote wallet.dat kopiją ir monetos buvo išleistos kopijoje, bet nepažymėtos kaip skirtos išleisti čia.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="131"/> <source>Loading block index...</source> <translation>Užkraunami blokų indeksai...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Unable to bind to %s on this computer. GoldCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Accept connections from outside (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="74"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Use Universal Plug and Play to map the listening port (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="82"/> <source>Use Universal Plug and Play to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="85"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="118"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="133"/> <source>Loading wallet...</source> <translation>Užkraunama piniginė...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="138"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="139"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="140"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="141"/> <source>Rescanning...</source> <translation>Peržiūra</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="144"/> <source>Done loading</source> <translation>Pakrovimas baigtas</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) If the file does not exist, create it with owner-readable-only file permissions. </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>An error occured while setting up the RPC port %i for listening: %s</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong GoldCoin will not work properly.</source> <translation>Įspėjimas: Patikrinkite, kad kompiuterio data ir laikas yra teisingi.Jei Jūsų laikrodis neteisingai nustatytas GoldCoin, veiks netinkamai.</translation> </message> </context> </TS>
goldcoin/gldcoin
src/qt/locale/bitcoin_lt.ts
TypeScript
mit
108,593
'use strict'; var virtualbox = require('../../lib/virtualbox'), async = require('async'), args = process.argv.slice(2), vm = 'node-virtualbox-test-machine', key = args.length > 1 && args[1], delay = 250, sequence; var SCAN_CODES = virtualbox.SCAN_CODES; var fns = []; /** * * Uncomment the following if you want to * test a particular key down/up (make/break) * sequence. * **/ // SHIFT + A Sequence sequence = [ { key: 'SHIFT', type: 'make', code: SCAN_CODES['SHIFT'] }, { key: 'A', type: 'make', code: SCAN_CODES['A'] }, { key: 'SHIFT', type: 'break', code: SCAN_CODES.getBreakCode('SHIFT') }, { key: 'A', type: 'break', code: SCAN_CODES.getBreakCode('A') }, ]; function onResponse(err) { if (err) { throw err; } } function generateFunc(key, type, code) { return function (cb) { setTimeout(function () { console.info('Sending %s %s code', key, type); virtualbox.keyboardputscancode(vm, code, function (err) { onResponse(err); cb(); }); }, delay); }; } function addKeyFuncs(key) { var makeCode = SCAN_CODES[key]; var breakCode = SCAN_CODES.getBreakCode(key); if (makeCode && makeCode.length) { fns.push(generateFunc(key, 'make', makeCode)); if (breakCode && breakCode.length) { fns.push(generateFunc(key, 'break', breakCode)); } } } if (sequence) { fns = sequence.map(function (s) { return generateFunc(s.key, s.type, s.code); }); } else if (key) { addKeyFuncs(key); } else { for (var key in SCAN_CODES) { if (key === 'getBreakCode') { continue; } addKeyFuncs(key); } } async.series(fns, function () { console.info('Keyboard Put Scan Code Test Complete'); });
Node-Virtualization/node-virtualbox
test/integration/keyboardputscancode.js
JavaScript
mit
1,713
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/extensions'; import { localize } from 'vs/nls'; import * as errors from 'vs/base/common/errors'; import { KeyMod, KeyChord, KeyCode } from 'vs/base/common/keyCodes'; import { Registry } from 'vs/platform/registry/common/platform'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IExtensionGalleryService, IExtensionTipsService, ExtensionsLabel, ExtensionsChannelId, PreferencesLabel } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService'; import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actions'; import { ExtensionTipsService } from 'vs/workbench/parts/extensions/electron-browser/extensionTipsService'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IOutputChannelRegistry, Extensions as OutputExtensions } from 'vs/workbench/parts/output/common/output'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { VIEWLET_ID, IExtensionsWorkbenchService } from '../common/extensions'; import { ExtensionsWorkbenchService } from 'vs/workbench/parts/extensions/node/extensionsWorkbenchService'; import { OpenExtensionsViewletAction, InstallExtensionsAction, ShowOutdatedExtensionsAction, ShowRecommendedExtensionsAction, ShowRecommendedKeymapExtensionsAction, ShowPopularExtensionsAction, ShowEnabledExtensionsAction, ShowInstalledExtensionsAction, ShowDisabledExtensionsAction, UpdateAllAction, EnableAllAction, EnableAllWorkpsaceAction, DisableAllAction, DisableAllWorkpsaceAction, CheckForUpdatesAction, ShowLanguageExtensionsAction, ShowAzureExtensionsAction, EnableAutoUpdateAction, DisableAutoUpdateAction, ConfigureRecommendedExtensionsCommandsContributor } from 'vs/workbench/parts/extensions/browser/extensionsActions'; import { OpenExtensionsFolderAction, InstallVSIXAction } from 'vs/workbench/parts/extensions/electron-browser/extensionsActions'; import { ExtensionsInput } from 'vs/workbench/parts/extensions/common/extensionsInput'; import { ViewletRegistry, Extensions as ViewletExtensions, ViewletDescriptor } from 'vs/workbench/browser/viewlet'; import { ExtensionEditor } from 'vs/workbench/parts/extensions/browser/extensionEditor'; import { StatusUpdater, ExtensionsViewlet, MaliciousExtensionChecker } from 'vs/workbench/parts/extensions/electron-browser/extensionsViewlet'; import { IQuickOpenRegistry, Extensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry'; import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry'); import { ExtensionsConfigurationSchema, ExtensionsConfigurationSchemaId } from 'vs/workbench/parts/extensions/common/extensionsFileTemplate'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeymapExtensions, BetterMergeDisabled } from 'vs/workbench/parts/extensions/electron-browser/extensionsUtils'; import { adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { GalleryExtensionsHandler, ExtensionsHandler } from 'vs/workbench/parts/extensions/browser/extensionsQuickOpen'; import { EditorDescriptor, IEditorRegistry, Extensions as EditorExtensions } from 'vs/workbench/browser/editor'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { RuntimeExtensionsEditor, RuntimeExtensionsInput, ShowRuntimeExtensionsAction, IExtensionHostProfileService } from 'vs/workbench/parts/extensions/electron-browser/runtimeExtensionsEditor'; import { EditorInput, IEditorInputFactory, IEditorInputFactoryRegistry, Extensions as EditorInputExtensions } from 'vs/workbench/common/editor'; import { ExtensionHostProfileService } from 'vs/workbench/parts/extensions/electron-browser/extensionProfileService'; // Singletons registerSingleton(IExtensionGalleryService, ExtensionGalleryService); registerSingleton(IExtensionTipsService, ExtensionTipsService); registerSingleton(IExtensionsWorkbenchService, ExtensionsWorkbenchService); registerSingleton(IExtensionHostProfileService, ExtensionHostProfileService); const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(StatusUpdater, LifecyclePhase.Running); workbenchRegistry.registerWorkbenchContribution(MaliciousExtensionChecker, LifecyclePhase.Eventually); workbenchRegistry.registerWorkbenchContribution(ConfigureRecommendedExtensionsCommandsContributor, LifecyclePhase.Eventually); workbenchRegistry.registerWorkbenchContribution(KeymapExtensions, LifecyclePhase.Running); workbenchRegistry.registerWorkbenchContribution(BetterMergeDisabled, LifecyclePhase.Running); Registry.as<IOutputChannelRegistry>(OutputExtensions.OutputChannels) .registerChannel(ExtensionsChannelId, ExtensionsLabel); // Quickopen Registry.as<IQuickOpenRegistry>(Extensions.Quickopen).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( ExtensionsHandler, ExtensionsHandler.ID, 'ext ', null, localize('extensionsCommands', "Manage Extensions"), true ) ); Registry.as<IQuickOpenRegistry>(Extensions.Quickopen).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( GalleryExtensionsHandler, GalleryExtensionsHandler.ID, 'ext install ', null, localize('galleryExtensionsCommands', "Install Gallery Extensions"), true ) ); // Editor const editorDescriptor = new EditorDescriptor( ExtensionEditor, ExtensionEditor.ID, localize('extension', "Extension") ); Registry.as<IEditorRegistry>(EditorExtensions.Editors) .registerEditor(editorDescriptor, [new SyncDescriptor(ExtensionsInput)]); // Running Extensions Editor const runtimeExtensionsEditorDescriptor = new EditorDescriptor( RuntimeExtensionsEditor, RuntimeExtensionsEditor.ID, localize('runtimeExtension', "Running Extensions") ); Registry.as<IEditorRegistry>(EditorExtensions.Editors) .registerEditor(runtimeExtensionsEditorDescriptor, [new SyncDescriptor(RuntimeExtensionsInput)]); class RuntimeExtensionsInputFactory implements IEditorInputFactory { serialize(editorInput: EditorInput): string { return ''; } deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): EditorInput { return new RuntimeExtensionsInput(); } } Registry.as<IEditorInputFactoryRegistry>(EditorInputExtensions.EditorInputFactories).registerEditorInputFactory(RuntimeExtensionsInput.ID, RuntimeExtensionsInputFactory); // Viewlet const viewletDescriptor = new ViewletDescriptor( ExtensionsViewlet, VIEWLET_ID, localize('extensions', "Extensions"), 'extensions', 100 ); Registry.as<ViewletRegistry>(ViewletExtensions.Viewlets) .registerViewlet(viewletDescriptor); // Global actions const actionRegistry = Registry.as<IWorkbenchActionRegistry>(WorkbenchActionExtensions.WorkbenchActions); const openViewletActionDescriptor = new SyncActionDescriptor(OpenExtensionsViewletAction, OpenExtensionsViewletAction.ID, OpenExtensionsViewletAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_X }); actionRegistry.registerWorkbenchAction(openViewletActionDescriptor, 'View: Show Extensions', localize('view', "View")); const installActionDescriptor = new SyncActionDescriptor(InstallExtensionsAction, InstallExtensionsAction.ID, InstallExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(installActionDescriptor, 'Extensions: Install Extensions', ExtensionsLabel); const listOutdatedActionDescriptor = new SyncActionDescriptor(ShowOutdatedExtensionsAction, ShowOutdatedExtensionsAction.ID, ShowOutdatedExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(listOutdatedActionDescriptor, 'Extensions: Show Outdated Extensions', ExtensionsLabel); const recommendationsActionDescriptor = new SyncActionDescriptor(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, ShowRecommendedExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(recommendationsActionDescriptor, 'Extensions: Show Recommended Extensions', ExtensionsLabel); const keymapRecommendationsActionDescriptor = new SyncActionDescriptor(ShowRecommendedKeymapExtensionsAction, ShowRecommendedKeymapExtensionsAction.ID, ShowRecommendedKeymapExtensionsAction.SHORT_LABEL, { primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_M) }); actionRegistry.registerWorkbenchAction(keymapRecommendationsActionDescriptor, 'Preferences: Keymaps', PreferencesLabel); const languageExtensionsActionDescriptor = new SyncActionDescriptor(ShowLanguageExtensionsAction, ShowLanguageExtensionsAction.ID, ShowLanguageExtensionsAction.SHORT_LABEL); actionRegistry.registerWorkbenchAction(languageExtensionsActionDescriptor, 'Preferences: Language Extensions', PreferencesLabel); const azureExtensionsActionDescriptor = new SyncActionDescriptor(ShowAzureExtensionsAction, ShowAzureExtensionsAction.ID, ShowAzureExtensionsAction.SHORT_LABEL); actionRegistry.registerWorkbenchAction(azureExtensionsActionDescriptor, 'Preferences: Azure Extensions', PreferencesLabel); const popularActionDescriptor = new SyncActionDescriptor(ShowPopularExtensionsAction, ShowPopularExtensionsAction.ID, ShowPopularExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(popularActionDescriptor, 'Extensions: Show Popular Extensions', ExtensionsLabel); const enabledActionDescriptor = new SyncActionDescriptor(ShowEnabledExtensionsAction, ShowEnabledExtensionsAction.ID, ShowEnabledExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(enabledActionDescriptor, 'Extensions: Show Enabled Extensions', ExtensionsLabel); const installedActionDescriptor = new SyncActionDescriptor(ShowInstalledExtensionsAction, ShowInstalledExtensionsAction.ID, ShowInstalledExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(installedActionDescriptor, 'Extensions: Show Installed Extensions', ExtensionsLabel); const disabledActionDescriptor = new SyncActionDescriptor(ShowDisabledExtensionsAction, ShowDisabledExtensionsAction.ID, ShowDisabledExtensionsAction.LABEL); actionRegistry.registerWorkbenchAction(disabledActionDescriptor, 'Extensions: Show Disabled Extensions', ExtensionsLabel); const updateAllActionDescriptor = new SyncActionDescriptor(UpdateAllAction, UpdateAllAction.ID, UpdateAllAction.LABEL); actionRegistry.registerWorkbenchAction(updateAllActionDescriptor, 'Extensions: Update All Extensions', ExtensionsLabel); const openExtensionsFolderActionDescriptor = new SyncActionDescriptor(OpenExtensionsFolderAction, OpenExtensionsFolderAction.ID, OpenExtensionsFolderAction.LABEL); actionRegistry.registerWorkbenchAction(openExtensionsFolderActionDescriptor, 'Extensions: Open Extensions Folder', ExtensionsLabel); const installVSIXActionDescriptor = new SyncActionDescriptor(InstallVSIXAction, InstallVSIXAction.ID, InstallVSIXAction.LABEL); actionRegistry.registerWorkbenchAction(installVSIXActionDescriptor, 'Extensions: Install from VSIX...', ExtensionsLabel); const disableAllAction = new SyncActionDescriptor(DisableAllAction, DisableAllAction.ID, DisableAllAction.LABEL); actionRegistry.registerWorkbenchAction(disableAllAction, 'Extensions: Disable All Installed Extensions', ExtensionsLabel); const disableAllWorkspaceAction = new SyncActionDescriptor(DisableAllWorkpsaceAction, DisableAllWorkpsaceAction.ID, DisableAllWorkpsaceAction.LABEL); actionRegistry.registerWorkbenchAction(disableAllWorkspaceAction, 'Extensions: Disable All Installed Extensions for this Workspace', ExtensionsLabel); const enableAllAction = new SyncActionDescriptor(EnableAllAction, EnableAllAction.ID, EnableAllAction.LABEL); actionRegistry.registerWorkbenchAction(enableAllAction, 'Extensions: Enable All Installed Extensions', ExtensionsLabel); const enableAllWorkspaceAction = new SyncActionDescriptor(EnableAllWorkpsaceAction, EnableAllWorkpsaceAction.ID, EnableAllWorkpsaceAction.LABEL); actionRegistry.registerWorkbenchAction(enableAllWorkspaceAction, 'Extensions: Enable All Installed Extensions for this Workspace', ExtensionsLabel); const checkForUpdatesAction = new SyncActionDescriptor(CheckForUpdatesAction, CheckForUpdatesAction.ID, CheckForUpdatesAction.LABEL); actionRegistry.registerWorkbenchAction(checkForUpdatesAction, `Extensions: Check for Updates`, ExtensionsLabel); actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(EnableAutoUpdateAction, EnableAutoUpdateAction.ID, EnableAutoUpdateAction.LABEL), `Extensions: Enable Auto Updating Extensions`, ExtensionsLabel); actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(DisableAutoUpdateAction, DisableAutoUpdateAction.ID, DisableAutoUpdateAction.LABEL), `Extensions: Disable Auto Updating Extensions`, ExtensionsLabel); actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowRuntimeExtensionsAction, ShowRuntimeExtensionsAction.ID, ShowRuntimeExtensionsAction.LABEL), 'Show Running Extensions', localize('developer', "Developer")); Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration) .registerConfiguration({ id: 'extensions', order: 30, title: localize('extensionsConfigurationTitle', "Extensions"), type: 'object', properties: { 'extensions.autoUpdate': { type: 'boolean', description: localize('extensionsAutoUpdate', "Automatically update extensions"), default: true }, 'extensions.ignoreRecommendations': { type: 'boolean', description: localize('extensionsIgnoreRecommendations', "If set to true, the notifications for extension recommendations will stop showing up."), default: false } } }); const jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(ExtensionsConfigurationSchemaId, ExtensionsConfigurationSchema); // Register Commands CommandsRegistry.registerCommand('_extensions.manage', (accessor: ServicesAccessor, extensionId: string) => { const extensionService = accessor.get(IExtensionsWorkbenchService); extensionId = adoptToGalleryExtensionId(extensionId); const extension = extensionService.local.filter(e => e.id === extensionId); if (extension.length === 1) { extensionService.open(extension[0]).done(null, errors.onUnexpectedError); } });
cra0zy/VSCode
src/vs/workbench/parts/extensions/electron-browser/extensions.contribution.ts
TypeScript
mit
15,077
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import winjs = require('vs/base/common/winjs.base'); import nls = require('vs/nls'); import platform = require('vs/base/common/platform'); import errors = require('vs/base/common/errors'); import paths = require('vs/base/common/paths'); import severity from 'vs/base/common/severity'; import lifecycle = require('vs/base/common/lifecycle'); import dom = require('vs/base/browser/dom'); import keyboard = require('vs/base/browser/keyboardEvent'); import mouse = require('vs/base/browser/mouseEvent'); import comparers = require('vs/base/common/comparers'); import actions = require('vs/base/common/actions'); import actionbar = require('vs/base/browser/ui/actionbar/actionbar'); import countbadge = require('vs/base/browser/ui/countBadge/countBadge'); import tree = require('vs/base/parts/tree/browser/tree'); import treednd = require('vs/base/parts/tree/browser/treeDnd'); import treedefaults = require('vs/base/parts/tree/browser/treeDefaults'); import actionsrenderer = require('vs/base/parts/tree/browser/actionsRenderer'); import git = require('vs/workbench/parts/git/common/git'); import gitmodel = require('vs/workbench/parts/git/common/gitModel'); import gitactions = require('vs/workbench/parts/git/browser/gitActions'); import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService } from 'vs/platform/message/common/message'; import { CommonKeybindings } from 'vs/base/common/keyCodes'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import URI from 'vs/base/common/uri'; import IGitService = git.IGitService function toReadablePath(path: string): string { if (!platform.isWindows) { return path; } return path.replace(/\//g, '\\'); } var $ = dom.emmet; export class ActionContainer implements lifecycle.IDisposable { private cache: { [actionId:string]:actions.IAction; }; private instantiationService: IInstantiationService; constructor(instantiationService: IInstantiationService) { this.cache = <any> {}; this.instantiationService = instantiationService; } protected getAction(ctor: any, ...args: any[]): any { var action = this.cache[ctor.ID]; if (!action) { args.unshift(ctor); action = this.cache[ctor.ID] = this.instantiationService.createInstance.apply(this.instantiationService, args); } return action; } public dispose(): void { Object.keys(this.cache).forEach(k => { this.cache[k].dispose(); }); this.cache = null; } } export class DataSource implements tree.IDataSource { public getId(tree: tree.ITree, element: any): string { if (element instanceof gitmodel.StatusModel) { return 'root'; } else if (element instanceof gitmodel.StatusGroup) { var statusGroup = <git.IStatusGroup> element; switch (statusGroup.getType()) { case git.StatusType.INDEX: return 'index'; case git.StatusType.WORKING_TREE: return 'workingTree'; case git.StatusType.MERGE: return 'merge'; default: throw new Error('Invalid group type'); } } var status = <git.IFileStatus> element; return status.getId(); } public hasChildren(tree: tree.ITree, element: any): boolean { if (element instanceof gitmodel.StatusModel) { return true; } else if (element instanceof gitmodel.StatusGroup) { var statusGroup = <git.IStatusGroup> element; return statusGroup.all().length > 0; } } public getChildren(tree: tree.ITree, element: any): winjs.Promise { if (element instanceof gitmodel.StatusModel) { var model = <git.IStatusModel> element; return winjs.TPromise.as(model.getGroups()); } else if (element instanceof gitmodel.StatusGroup) { var statusGroup = <git.IStatusGroup> element; return winjs.TPromise.as(statusGroup.all()); } return winjs.TPromise.as([]); } public getParent(tree: tree.ITree, element: any): winjs.Promise { return winjs.TPromise.as(null); } } export class ActionProvider extends ActionContainer implements actionsrenderer.IActionProvider { private gitService: git.IGitService; constructor(@IInstantiationService instantiationService: IInstantiationService, @IGitService gitService: IGitService) { super(instantiationService); this.gitService = gitService; } public hasActions(tree: tree.ITree, element: any): boolean { if (element instanceof gitmodel.FileStatus) { return true; } else if (element instanceof gitmodel.StatusGroup && (<git.IStatusGroup> element).all().length > 0) { return true; } return false; } public getActions(tree: tree.ITree, element: any): winjs.TPromise<actions.IAction[]> { if (element instanceof gitmodel.StatusGroup) { return winjs.TPromise.as(this.getActionsForGroupStatusType(element.getType())); } else { return winjs.TPromise.as(this.getActionsForFileStatusType(element.getType())); } } public getActionsForFileStatusType(statusType: git.StatusType): actions.IAction[] { switch (statusType) { case git.StatusType.INDEX: return [this.getAction(gitactions.UnstageAction)]; case git.StatusType.WORKING_TREE: return [this.getAction(gitactions.UndoAction), this.getAction(gitactions.StageAction)]; case git.StatusType.MERGE: return [this.getAction(gitactions.StageAction)]; default: return []; } } public getActionsForGroupStatusType(statusType: git.StatusType): actions.IAction[] { switch (statusType) { case git.StatusType.INDEX: return [this.getAction(gitactions.GlobalUnstageAction)]; case git.StatusType.WORKING_TREE: return [this.getAction(gitactions.GlobalUndoAction), this.getAction(gitactions.GlobalStageAction)]; case git.StatusType.MERGE: return [this.getAction(gitactions.StageAction)]; default: return []; } } public hasSecondaryActions(tree: tree.ITree, element: any): boolean { return this.hasActions(tree, element); } public getSecondaryActions(tree: tree.ITree, element: any): winjs.TPromise<actions.IAction[]> { return this.getActions(tree, element).then((actions: actions.IAction[]) => { if (element instanceof gitmodel.FileStatus) { var fileStatus = <gitmodel.FileStatus> element; var status = fileStatus.getStatus(); actions.push(new actionbar.Separator()); if (status !== git.Status.DELETED && status !== git.Status.INDEX_DELETED) { actions.push(this.getAction(gitactions.OpenFileAction)); } actions.push(this.getAction(gitactions.OpenChangeAction)); } actions.reverse(); return actions; }); } public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem { return null; } } interface IFileStatusTemplateData { root: HTMLElement; status: HTMLElement; name: HTMLElement; folder: HTMLElement; renameName: HTMLElement; renameFolder: HTMLElement; actionBar: actionbar.ActionBar; } interface IStatusGroupTemplateData { root: HTMLElement; count: countbadge.CountBadge; actionBar: actionbar.ActionBar; } export class Renderer implements tree.IRenderer { constructor( private actionProvider:ActionProvider, private actionRunner: actions.IActionRunner, @IMessageService private messageService: IMessageService, @IGitService private gitService: IGitService, @IWorkspaceContextService private contextService: IWorkspaceContextService ) { // noop } public getHeight(tree:tree.ITree, element:any): number { return 22; } public getTemplateId(tree: tree.ITree, element: any): string { if (element instanceof gitmodel.StatusGroup) { switch (element.getType()) { case git.StatusType.INDEX: return 'index'; case git.StatusType.WORKING_TREE: return 'workingTree'; case git.StatusType.MERGE: return 'merge'; } } if (element instanceof gitmodel.FileStatus) { switch (element.getType()) { case git.StatusType.INDEX: return 'file:index'; case git.StatusType.WORKING_TREE: return 'file:workingTree'; case git.StatusType.MERGE: return 'file:merge'; } } return null; } public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any { if (/^file:/.test(templateId)) { return this.renderFileStatusTemplate(Renderer.templateIdToStatusType(templateId), container); } else { return this.renderStatusGroupTemplate(Renderer.templateIdToStatusType(templateId), container); } } private renderStatusGroupTemplate(statusType: git.StatusType, container: HTMLElement): IStatusGroupTemplateData { var data: IStatusGroupTemplateData = Object.create(null); data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner }); data.actionBar.push(this.actionProvider.getActionsForGroupStatusType(statusType), { icon: true, label: false }); data.actionBar.addListener2('run', e => e.error && this.onError(e.error)); const wrapper = dom.append(container, $('.count-badge-wrapper')); data.count = new countbadge.CountBadge(wrapper); data.root = dom.append(container, $('.status-group')); switch (statusType) { case git.StatusType.INDEX: data.root.textContent = nls.localize('stagedChanges', "Staged Changes"); break; case git.StatusType.WORKING_TREE: data.root.textContent = nls.localize('allChanges', "Changes"); break; case git.StatusType.MERGE: data.root.textContent = nls.localize('mergeChanges', "Merge Changes"); break; } return data; } private renderFileStatusTemplate(statusType: git.StatusType, container: HTMLElement): IFileStatusTemplateData { var data: IFileStatusTemplateData = Object.create(null); data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner }); data.actionBar.push(this.actionProvider.getActionsForFileStatusType(statusType), { icon: true, label: false }); data.actionBar.addListener2('run', e => e.error && this.onError(e.error)); data.root = dom.append(container, $('.file-status')); data.status = dom.append(data.root, $('span.status')); data.name = dom.append(data.root, $('a.name.plain')); data.folder = dom.append(data.root, $('span.folder')); var rename = dom.append(data.root, $('span.rename')); var arrow = dom.append(rename, $('span.rename-arrow')); arrow.textContent = '←'; data.renameName = dom.append(rename, $('span.rename-name')); data.renameFolder = dom.append(rename, $('span.rename-folder')); return data; } public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void { if (/^file:/.test(templateId)) { this.renderFileStatus(tree, <git.IFileStatus> element, templateData); } else { Renderer.renderStatusGroup(<git.IStatusGroup> element, templateData); } } private static renderStatusGroup(statusGroup: git.IStatusGroup, data: IStatusGroupTemplateData): void { data.actionBar.context = statusGroup; data.count.setCount(statusGroup.all().length); } private renderFileStatus(tree: tree.ITree, fileStatus: git.IFileStatus, data: IFileStatusTemplateData): void { data.actionBar.context = { tree: tree, fileStatus: fileStatus }; const repositoryRoot = this.gitService.getModel().getRepositoryRoot(); const workspaceRoot = this.contextService.getWorkspace().resource.fsPath; const status = fileStatus.getStatus(); const renamePath = fileStatus.getRename(); const path = fileStatus.getPath(); const lastSlashIndex = path.lastIndexOf('/'); const name = lastSlashIndex === -1 ? path : path.substr(lastSlashIndex + 1, path.length); const folder = (lastSlashIndex === -1 ? '' : path.substr(0, lastSlashIndex)); data.root.className = 'file-status ' + Renderer.statusToClass(status); data.status.textContent = Renderer.statusToChar(status); data.status.title = Renderer.statusToTitle(status); const resource = URI.file(paths.normalize(paths.join(repositoryRoot, path))); let isInWorkspace = paths.isEqualOrParent(resource.fsPath, workspaceRoot); let rename = ''; let renameFolder = ''; if (renamePath) { const renameLastSlashIndex = renamePath.lastIndexOf('/'); rename = renameLastSlashIndex === -1 ? renamePath : renamePath.substr(renameLastSlashIndex + 1, renamePath.length); renameFolder = (renameLastSlashIndex === -1 ? '' : renamePath.substr(0, renameLastSlashIndex)); data.renameName.textContent = name; data.renameFolder.textContent = folder; const resource = URI.file(paths.normalize(paths.join(repositoryRoot, renamePath))); isInWorkspace = paths.isEqualOrParent(resource.fsPath, workspaceRoot) } if (isInWorkspace) { data.root.title = ''; } else { data.root.title = nls.localize('outsideOfWorkspace', "This file is located outside the current workspace."); data.root.className += ' out-of-workspace'; } data.name.textContent = rename || name; data.folder.textContent = toReadablePath(renameFolder || folder); } public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void { if (/^file:/.test(templateId)) { Renderer.disposeFileStatusTemplate(<IFileStatusTemplateData> templateData); } } private static disposeFileStatusTemplate(templateData: IFileStatusTemplateData): void { templateData.actionBar.dispose(); } private static statusToChar(status: git.Status): string { switch (status) { case git.Status.INDEX_MODIFIED: return nls.localize('modified-char', "M"); case git.Status.MODIFIED: return nls.localize('modified-char', "M"); case git.Status.INDEX_ADDED: return nls.localize('added-char', "A"); case git.Status.INDEX_DELETED: return nls.localize('deleted-char', "D"); case git.Status.DELETED: return nls.localize('deleted-char', "D"); case git.Status.INDEX_RENAMED: return nls.localize('renamed-char', "R"); case git.Status.INDEX_COPIED: return nls.localize('copied-char', "C"); case git.Status.UNTRACKED: return nls.localize('untracked-char', "U"); case git.Status.IGNORED: return nls.localize('ignored-char', "!"); case git.Status.BOTH_DELETED: return nls.localize('deleted-char', "D"); case git.Status.ADDED_BY_US: return nls.localize('added-char', "A"); case git.Status.DELETED_BY_THEM: return nls.localize('deleted-char', "D"); case git.Status.ADDED_BY_THEM: return nls.localize('added-char', "A"); case git.Status.DELETED_BY_US: return nls.localize('deleted-char', "D"); case git.Status.BOTH_ADDED: return nls.localize('added-char', "A"); case git.Status.BOTH_MODIFIED: return nls.localize('modified-char', "M"); default: return ''; } } public static statusToTitle(status: git.Status): string { switch (status) { case git.Status.INDEX_MODIFIED: return nls.localize('title-index-modified', "Modified in index"); case git.Status.MODIFIED: return nls.localize('title-modified', "Modified"); case git.Status.INDEX_ADDED: return nls.localize('title-index-added', "Added to index"); case git.Status.INDEX_DELETED: return nls.localize('title-index-deleted', "Deleted in index"); case git.Status.DELETED: return nls.localize('title-deleted', "Deleted"); case git.Status.INDEX_RENAMED: return nls.localize('title-index-renamed', "Renamed in index"); case git.Status.INDEX_COPIED: return nls.localize('title-index-copied', "Copied in index"); case git.Status.UNTRACKED: return nls.localize('title-untracked', "Untracked"); case git.Status.IGNORED: return nls.localize('title-ignored', "Ignored"); case git.Status.BOTH_DELETED: return nls.localize('title-conflict-both-deleted', "Conflict: both deleted"); case git.Status.ADDED_BY_US: return nls.localize('title-conflict-added-by-us', "Conflict: added by us"); case git.Status.DELETED_BY_THEM: return nls.localize('title-conflict-deleted-by-them', "Conflict: deleted by them"); case git.Status.ADDED_BY_THEM: return nls.localize('title-conflict-added-by-them', "Conflict: added by them"); case git.Status.DELETED_BY_US: return nls.localize('title-conflict-deleted-by-us', "Conflict: deleted by us"); case git.Status.BOTH_ADDED: return nls.localize('title-conflict-both-added', "Conflict: both added"); case git.Status.BOTH_MODIFIED: return nls.localize('title-conflict-both-modified', "Conflict: both modified"); default: return ''; } } private static statusToClass(status: git.Status): string { switch (status) { case git.Status.INDEX_MODIFIED: return 'modified'; case git.Status.MODIFIED: return 'modified'; case git.Status.INDEX_ADDED: return 'added'; case git.Status.INDEX_DELETED: return 'deleted'; case git.Status.DELETED: return 'deleted'; case git.Status.INDEX_RENAMED: return 'renamed'; case git.Status.INDEX_COPIED: return 'copied'; case git.Status.UNTRACKED: return 'untracked'; case git.Status.IGNORED: return 'ignored'; case git.Status.BOTH_DELETED: return 'conflict both-deleted'; case git.Status.ADDED_BY_US: return 'conflict added-by-us'; case git.Status.DELETED_BY_THEM: return 'conflict deleted-by-them'; case git.Status.ADDED_BY_THEM: return 'conflict added-by-them'; case git.Status.DELETED_BY_US: return 'conflict deleted-by-us'; case git.Status.BOTH_ADDED: return 'conflict both-added'; case git.Status.BOTH_MODIFIED: return 'conflict both-modified'; default: return ''; } } private static templateIdToStatusType(templateId: string): git.StatusType { if (/index$/.test(templateId)) { return git.StatusType.INDEX; } else if (/workingTree$/.test(templateId)) { return git.StatusType.WORKING_TREE; } else { return git.StatusType.MERGE; } } private onError(error: any): void { this.messageService.show(severity.Error, error); } } export class Filter implements tree.IFilter { public isVisible(tree: tree.ITree, element: any): boolean { if (element instanceof gitmodel.StatusGroup) { var statusGroup = <git.IStatusGroup> element; switch (statusGroup.getType()) { case git.StatusType.INDEX: case git.StatusType.MERGE: return statusGroup.all().length > 0; case git.StatusType.WORKING_TREE: return true; } } return true; } } export class Sorter implements tree.ISorter { public compare(tree: tree.ITree, element: any, otherElement: any): number { if (!(element instanceof gitmodel.FileStatus && otherElement instanceof gitmodel.FileStatus)) { return 0; } return Sorter.compareStatus(element, otherElement); } private static compareStatus(element: git.IFileStatus, otherElement: git.IFileStatus): number { var one = element.getPathComponents(); var other = otherElement.getPathComponents(); var lastOne = one.length - 1; var lastOther = other.length - 1; var endOne: boolean, endOther: boolean, onePart: string, otherPart: string; for (var i = 0; ; i++) { endOne = lastOne === i; endOther = lastOther === i; if (endOne && endOther) { return comparers.compareFileNames(one[i], other[i]); } else if (endOne) { return -1; } else if (endOther) { return 1; } else if ((onePart = one[i].toLowerCase()) !== (otherPart = other[i].toLowerCase())) { return onePart < otherPart ? -1 : 1; } } } } export class DragAndDrop extends ActionContainer implements tree.IDragAndDrop { private gitService: git.IGitService; private messageService: IMessageService; constructor(@IInstantiationService instantiationService: IInstantiationService, @IGitService gitService: IGitService, @IMessageService messageService: IMessageService) { super(instantiationService); this.gitService = gitService; this.messageService = messageService; } public getDragURI(tree: tree.ITree, element: any): string { if (element instanceof gitmodel.StatusGroup) { var statusGroup = <git.IStatusGroup> element; return 'git:' + statusGroup.getType(); } else if (element instanceof gitmodel.FileStatus) { var status = <git.IFileStatus> element; return 'git:' + status.getType() + ':' + status.getPath(); } return null; } public onDragStart(tree: tree.ITree, data: tree.IDragAndDropData, originalEvent:mouse.DragMouseEvent):void { // no-op } public onDragOver(_tree: tree.ITree, data: tree.IDragAndDropData, targetElement: any, originalEvent:mouse.DragMouseEvent): tree.IDragOverReaction { if (!this.gitService.isIdle()) { return tree.DRAG_OVER_REJECT; } if (!(data instanceof treednd.ElementsDragAndDropData)) { return tree.DRAG_OVER_REJECT; } var elements: any[] = data.getData(); var element = elements[0]; if (element instanceof gitmodel.StatusGroup) { var statusGroup = <git.IStatusGroup> element; return this.onDrag(targetElement, statusGroup.getType()); } else if (element instanceof gitmodel.FileStatus) { var status = <git.IFileStatus> element; return this.onDrag(targetElement, status.getType()); } else { return tree.DRAG_OVER_REJECT; } } private onDrag(targetElement: any, type: git.StatusType): tree.IDragOverReaction { if (type === git.StatusType.WORKING_TREE) { return this.onDragWorkingTree(targetElement); } else if (type === git.StatusType.INDEX) { return this.onDragIndex(targetElement); } else if (type === git.StatusType.MERGE) { return this.onDragMerge(targetElement); } else { return tree.DRAG_OVER_REJECT; } } private onDragWorkingTree(targetElement: any): tree.IDragOverReaction { if (targetElement instanceof gitmodel.StatusGroup) { var targetStatusGroup = <git.IStatusGroup> targetElement; return targetStatusGroup.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_DOWN : tree.DRAG_OVER_REJECT; } else if (targetElement instanceof gitmodel.FileStatus) { var targetStatus = <git.IFileStatus> targetElement; return targetStatus.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_UP : tree.DRAG_OVER_REJECT; } else { return tree.DRAG_OVER_REJECT; } } private onDragIndex(targetElement: any): tree.IDragOverReaction { if (targetElement instanceof gitmodel.StatusGroup) { var targetStatusGroup = <git.IStatusGroup> targetElement; return targetStatusGroup.getType() === git.StatusType.WORKING_TREE ? tree.DRAG_OVER_ACCEPT_BUBBLE_DOWN : tree.DRAG_OVER_REJECT; } else if (targetElement instanceof gitmodel.FileStatus) { var targetStatus = <git.IFileStatus> targetElement; return targetStatus.getType() === git.StatusType.WORKING_TREE ? tree.DRAG_OVER_ACCEPT_BUBBLE_UP : tree.DRAG_OVER_REJECT; } else { return tree.DRAG_OVER_REJECT; } } private onDragMerge(targetElement: any): tree.IDragOverReaction { if (targetElement instanceof gitmodel.StatusGroup) { var targetStatusGroup = <git.IStatusGroup> targetElement; return targetStatusGroup.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_DOWN : tree.DRAG_OVER_REJECT; } else if (targetElement instanceof gitmodel.FileStatus) { var targetStatus = <git.IFileStatus> targetElement; return targetStatus.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_UP : tree.DRAG_OVER_REJECT; } else { return tree.DRAG_OVER_REJECT; } } public drop(tree: tree.ITree, data: tree.IDragAndDropData, targetElement: any, originalEvent:mouse.DragMouseEvent): void { var elements: any[] = data.getData(); var element = elements[0]; var files: git.IFileStatus[]; if (element instanceof gitmodel.StatusGroup) { files = (<git.IStatusGroup> element).all(); // } else if (element instanceof gitmodel.FileStatus) { // files = [ element ]; } else { files = elements; // throw new Error('Invalid drag and drop data.'); } var targetGroup = <git.IStatusGroup> targetElement; // Add files to index if (targetGroup.getType() === git.StatusType.INDEX) { this.getAction(gitactions.StageAction).run(files).done(null, (e:Error) => this.onError(e)); } // Remove files from index if (targetGroup.getType() === git.StatusType.WORKING_TREE) { this.getAction(gitactions.UnstageAction).run(files).done(null, (e:Error) => this.onError(e)); } } private onError(error: any): void { this.messageService.show(severity.Error, error); } } export class AccessibilityProvider implements tree.IAccessibilityProvider { public getAriaLabel(tree: tree.ITree, element: any): string { if (element instanceof gitmodel.FileStatus) { const fileStatus = <gitmodel.FileStatus>element; const status = fileStatus.getStatus(); const path = fileStatus.getPath(); const lastSlashIndex = path.lastIndexOf('/'); const name = lastSlashIndex === -1 ? path : path.substr(lastSlashIndex + 1, path.length); const folder = (lastSlashIndex === -1 ? '' : path.substr(0, lastSlashIndex)); return nls.localize('fileStatusAriaLabel', "File {0} in folder {1} has status: {2}, Git", name, folder, Renderer.statusToTitle(status)); } if (element instanceof gitmodel.StatusGroup) { switch ( (<gitmodel.StatusGroup>element).getType()) { case git.StatusType.INDEX: return nls.localize('ariaLabelStagedChanges', "Staged Changes, Git"); case git.StatusType.WORKING_TREE: return nls.localize('ariaLabelChanges', "Changes, Git"); case git.StatusType.MERGE: return nls.localize('ariaLabelMerge', "Merge, Git"); } } } } export class Controller extends treedefaults.DefaultController { private contextMenuService:IContextMenuService; private actionProvider:actionsrenderer.IActionProvider; constructor(actionProvider:actionsrenderer.IActionProvider, @IContextMenuService contextMenuService: IContextMenuService) { super({ clickBehavior: treedefaults.ClickBehavior.ON_MOUSE_UP }); this.actionProvider = actionProvider; this.contextMenuService = contextMenuService; this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_UP_ARROW, this.onUp.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_DOWN_ARROW, this.onDown.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_PAGE_UP, this.onPageUp.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_PAGE_DOWN, this.onPageDown.bind(this)); } protected onLeftClick(tree: tree.ITree, element: any, event: mouse.StandardMouseEvent): boolean { // Status group should never get selected nor expanded/collapsed if (element instanceof gitmodel.StatusGroup) { event.preventDefault(); event.stopPropagation(); return true; } if (event.shiftKey) { var focus = tree.getFocus(); if (!(focus instanceof gitmodel.FileStatus) || !(element instanceof gitmodel.FileStatus)) { return; } var focusStatus = <gitmodel.FileStatus> focus; var elementStatus = <gitmodel.FileStatus> element; if (focusStatus.getType() !== elementStatus.getType()) { return; } if (this.canSelect(tree, element)) { tree.setFocus(element); if (tree.isSelected(element)) { tree.deselectRange(focusStatus, elementStatus); } else { tree.selectRange(focusStatus, elementStatus); } } return; } tree.setFocus(element); if (platform.isMacintosh ? event.metaKey : event.ctrlKey) { if (this.canSelect(tree, element)) { tree.toggleSelection(element, { origin: 'mouse', originalEvent: event }); } return; } return super.onLeftClick(tree, element, event); } protected onEnter(tree: tree.ITree, event: keyboard.StandardKeyboardEvent): boolean { var element = tree.getFocus(); // Status group should never get selected nor expanded/collapsed if (element instanceof gitmodel.StatusGroup) { event.preventDefault(); event.stopPropagation(); return true; } return super.onEnter(tree, event); } protected onSpace(tree: tree.ITree, event: keyboard.StandardKeyboardEvent):boolean { var focus = tree.getFocus(); if (!focus) { event.preventDefault(); event.stopPropagation(); return true; } if (!this.canSelect(tree, focus)) { return false; } tree.toggleSelection(focus, { origin: 'keyboard', originalEvent: event }); event.preventDefault(); event.stopPropagation(); return true; } public onContextMenu(tree:tree.ITree, element:any, event:tree.ContextMenuEvent):boolean { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; } event.preventDefault(); event.stopPropagation(); tree.setFocus(element); if (this.actionProvider.hasSecondaryActions(tree, element)) { var anchor = { x: event.posx + 1, y: event.posy }; var context = { selection: tree.getSelection(), focus: element }; this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this.actionProvider.getSecondaryActions(tree, element), getActionItem: this.actionProvider.getActionItem.bind(this.actionProvider, tree, element), getActionsContext: () => context, onHide: (wasCancelled?:boolean) => { if (wasCancelled) { tree.DOMFocus(); } } }); return true; } return false; } protected onLeft(tree: tree.ITree, event:keyboard.StandardKeyboardEvent):boolean { return true; } protected onRight(tree: tree.ITree, event:keyboard.StandardKeyboardEvent):boolean { return true; } protected onUp(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean { var oldFocus = tree.getFocus(); var base = super.onUp(tree, event); if (!base || !event.shiftKey) { return false; } return this.shiftSelect(tree, oldFocus, event); } protected onPageUp(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean { var oldFocus = tree.getFocus(); var base = super.onPageUp(tree, event); if (!base || !event.shiftKey) { return false; } return this.shiftSelect(tree, oldFocus, event); } protected onDown(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean { var oldFocus = tree.getFocus(); var base = super.onDown(tree, event); if (!base || !event.shiftKey) { return false; } return this.shiftSelect(tree, oldFocus, event); } protected onPageDown(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean { var oldFocus = tree.getFocus(); var base = super.onPageDown(tree, event); if (!base || !event.shiftKey) { return false; } return this.shiftSelect(tree, oldFocus, event); } private canSelect(tree: tree.ITree, ...elements: any[]): boolean { if (elements.some(e => e instanceof gitmodel.StatusGroup || e instanceof gitmodel.StatusModel)) { return false; } return elements.every(e => { var first = <gitmodel.FileStatus> tree.getSelection()[0]; var clicked = <gitmodel.FileStatus> e; return !first || (first.getType() === clicked.getType()); }); } private shiftSelect(tree: tree.ITree, oldFocus: any, event:keyboard.StandardKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; var focus = tree.getFocus(); if (focus === oldFocus) { return false; } var oldFocusIsSelected = tree.isSelected(oldFocus); var focusIsSelected = tree.isSelected(focus); if (oldFocusIsSelected && focusIsSelected) { tree.deselectRange(focus, oldFocus, payload); } else if (!oldFocusIsSelected && !focusIsSelected) { if (this.canSelect(tree, oldFocus, focus)) { tree.selectRange(focus, oldFocus, payload); } } else if (oldFocusIsSelected) { if (this.canSelect(tree, focus)) { tree.selectRange(focus, oldFocus, payload); } } else { tree.deselectRange(focus, oldFocus, payload); } return true; } }
2947721120/vscode
src/vs/workbench/parts/git/browser/views/changes/changesViewer.ts
TypeScript
mit
31,679
# @see https://developers.podio.com/doc/email class Podio::ApplicationEmail < ActivePodio::Base include ActivePodio::Updatable property :attachments, :boolean property :mappings, :hash class << self # @see https://developers.podio.com/doc/email/get-app-email-configuration-622338 def get_app_configuration(app_id) member Podio.connection.get { |req| req.url("/email/app/#{app_id}", {}) }.body end # @see https://developers.podio.com/doc/email/update-app-email-configuration-622851 def update_app_configuration(app_id, options) Podio.connection.put { |req| req.url "/email/app/#{app_id}" req.body = options }.body end end end
cocktail-io/podio-rb
lib/podio/models/application_email.rb
Ruby
mit
711
import React from 'react'; import { Alert } from 'react-bootstrap'; export const NotFound = () => ( <Alert bsStyle="danger"> <p><strong>Error [404]</strong>: { window.location.pathname } does not exist.</p> </Alert> );
irvinlim/free4all
imports/ui/pages/not-found.js
JavaScript
mit
228
using System; using System.Collections.Generic; using System.Text; namespace Lite.ExcelLibrary.CompoundDocumentFormat { /// <summary> /// The master sector allocation table (MSAT) is an array of SecIDs of all sectors /// used by the sector allocation table (SAT). /// </summary> public class MasterSectorAllocation { CompoundDocument Document; int NumberOfSecIDs; int CurrentMSATSector; int SecIDCapacity; List<Int32> MasterSectorAllocationTable; public MasterSectorAllocation(CompoundDocument document) { this.Document = document; this.NumberOfSecIDs = document.Header.NumberOfSATSectors; this.CurrentMSATSector = document.Header.FirstSectorIDofMasterSectorAllocationTable; this.SecIDCapacity = document.SectorSize / 4 - 1; InitializeMasterSectorAllocationTable(); } private void InitializeMasterSectorAllocationTable() { this.MasterSectorAllocationTable = new List<int>(NumberOfSecIDs); SelectSIDs(Document.Header.MasterSectorAllocationTable); int msid = Document.Header.FirstSectorIDofMasterSectorAllocationTable; while (msid != SID.EOC) { CurrentMSATSector = msid; int[] SIDs = Document.ReadSectorDataAsIntegers(msid); SelectSIDs(SIDs); msid = SIDs[SIDs.Length - 1]; } } private void SelectSIDs(int[] SIDs) { for (int i = 0; i < SIDs.Length; i++) { int sid = SIDs[i]; if (MasterSectorAllocationTable.Count < NumberOfSecIDs) { MasterSectorAllocationTable.Add(sid); } else { break; } } } public int GetSATSectorID(int SATSectorIndex) { if (SATSectorIndex < NumberOfSecIDs) { return MasterSectorAllocationTable[SATSectorIndex]; } else if (SATSectorIndex == NumberOfSecIDs) { return AllocateSATSector(); } else { throw new ArgumentOutOfRangeException("SATSectorIndex"); } } public int AllocateSATSector() { int[] sids = new Int32[SecIDCapacity]; for (int i = 0; i < sids.Length; i++) { sids[i] = SID.Free; } int secID = Document.AllocateNewSector(sids); if (NumberOfSecIDs < 109) { Document.Header.MasterSectorAllocationTable[NumberOfSecIDs] = secID; Document.Write(76 + NumberOfSecIDs * 4, secID); } else { if (CurrentMSATSector == SID.EOC) { CurrentMSATSector = AllocateMSATSector(); Document.Header.FirstSectorIDofMasterSectorAllocationTable = CurrentMSATSector; } int index = (NumberOfSecIDs - 109) % SecIDCapacity; Document.WriteInSector(CurrentMSATSector, index * 4, secID); if (index == SecIDCapacity - 1) { int newMSATSector = AllocateMSATSector(); Document.WriteInSector(CurrentMSATSector, SecIDCapacity * 4, newMSATSector); CurrentMSATSector = newMSATSector; } } MasterSectorAllocationTable.Add(secID); NumberOfSecIDs++; Document.SectorAllocation.LinkSectorID(secID, SID.SAT); Document.Header.NumberOfSATSectors++; return secID; } public int AllocateMSATSector() { int[] secIDs = new int[SecIDCapacity + 1]; for (int i = 0; i < SecIDCapacity; i++) { secIDs[i] = SID.Free; } secIDs[SecIDCapacity] = SID.EOC; int newMSATSector = Document.AllocateNewSector(); Document.WriteInSector(newMSATSector, 0, secIDs); Document.SectorAllocation.LinkSectorID(newMSATSector, SID.MSAT); Document.Header.NumberOfMasterSectors++; return newMSATSector; } } }
YHTechnology/ProjectManager
ProductManager/LiteExcelLibrary/CompoundDocumentFormat/MasterSectorAllocation.cs
C#
mit
4,421
using System.Composition; using System.Threading.Tasks; using OmniSharp.Cake.Extensions; using OmniSharp.Mef; using OmniSharp.Models.MembersTree; using OmniSharp.Models.Rename; namespace OmniSharp.Cake.Services.RequestHandlers.Refactoring { [OmniSharpHandler(OmniSharpEndpoints.Rename, Constants.LanguageNames.Cake), Shared] public class RenameHandler : CakeRequestHandler<RenameRequest, RenameResponse> { [ImportingConstructor] public RenameHandler(OmniSharpWorkspace workspace) : base(workspace) { } protected override Task<RenameResponse> TranslateResponse(RenameResponse response, RenameRequest request) { return response.TranslateAsync(Workspace, request); } } }
OmniSharp/omnisharp-roslyn
src/OmniSharp.Cake/Services/RequestHandlers/Refactoring/RenameHandler.cs
C#
mit
757
import { KeysPipePipe } from './keys-pipe.pipe'; describe('KeysPipePipe', () => { it('create an instance', () => { const pipe = new KeysPipePipe(); expect(pipe).toBeTruthy(); }); });
friendsofagape/mt2414ui
src/app/keys-pipe.pipe.spec.ts
TypeScript
mit
196
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Net; using Approve.RuleCenter; using System.Text; using Approve.Common; public partial class ErrorPage : System.Web.UI.Page { public string sMessage = ""; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (string.IsNullOrEmpty(Request.QueryString["Message"])) { sMessage = ComFunction.GetValueByName("EerrorMessage"); if (sMessage == null || sMessage == "") { sMessage = "抱歉,您访问的页面出错了,请您重新登录"; } } else { sMessage = Request.QueryString["Message"]; } } } }
coojee2012/pm3
SurveyDesign/ErrorPage.aspx.cs
C#
mit
1,037
using System; using System.Collections; using System.IO; using System.Text; using BigMath; using Raksha.Asn1; using Raksha.Asn1.CryptoPro; using Raksha.Asn1.Oiw; using Raksha.Asn1.Pkcs; using Raksha.Asn1.Sec; using Raksha.Asn1.X509; using Raksha.Asn1.X9; using Raksha.Crypto; using Raksha.Crypto.Generators; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Pkcs; namespace Raksha.Security { public sealed class PrivateKeyFactory { private PrivateKeyFactory() { } public static AsymmetricKeyParameter CreateKey( byte[] privateKeyInfoData) { return CreateKey( PrivateKeyInfo.GetInstance( Asn1Object.FromByteArray(privateKeyInfoData))); } public static AsymmetricKeyParameter CreateKey( Stream inStr) { return CreateKey( PrivateKeyInfo.GetInstance( Asn1Object.FromStream(inStr))); } public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.ObjectID; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return new DHPrivateKeyParameters(derX.Value, dhParams, algOid); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G)); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger) keyInfo.PrivateKey; Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return new DsaPrivateKeyParameters(derX.Value, parameters); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters ecP; if (para.IsNamedCurve) { ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier) para.Parameters); } else { ecP = new X9ECParameters((Asn1Sequence) para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return new ECPrivateKeyParameters(ec.GetKey(), dParams); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) return null; return new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString) keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } } public static AsymmetricKeyParameter DecryptKey( char[] passPhrase, EncryptedPrivateKeyInfo encInfo) { return CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(passPhrase, encInfo)); } public static AsymmetricKeyParameter DecryptKey( char[] passPhrase, byte[] encryptedPrivateKeyInfoData) { return DecryptKey(passPhrase, Asn1Object.FromByteArray(encryptedPrivateKeyInfoData)); } public static AsymmetricKeyParameter DecryptKey( char[] passPhrase, Stream encryptedPrivateKeyInfoStream) { return DecryptKey(passPhrase, Asn1Object.FromStream(encryptedPrivateKeyInfoStream)); } private static AsymmetricKeyParameter DecryptKey( char[] passPhrase, Asn1Object asn1Object) { return DecryptKey(passPhrase, EncryptedPrivateKeyInfo.GetInstance(asn1Object)); } public static byte[] EncryptKey( DerObjectIdentifier algorithm, char[] passPhrase, byte[] salt, int iterationCount, AsymmetricKeyParameter key) { return EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( algorithm, passPhrase, salt, iterationCount, key).GetEncoded(); } public static byte[] EncryptKey( string algorithm, char[] passPhrase, byte[] salt, int iterationCount, AsymmetricKeyParameter key) { return EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( algorithm, passPhrase, salt, iterationCount, key).GetEncoded(); } } }
Taggersoft/Raksha
src/Raksha.Shared/Security/PrivateKeyFactory.cs
C#
mit
6,643
(function () { 'use strict'; var module = angular.module('fim.base'); module.config(function($routeProvider) { $routeProvider .when('/activity/:engine/:section/:period', { templateUrl: 'partials/activity.html', controller: 'ActivityController' }); }); module.controller('ActivityController', function($scope, $location, $routeParams, nxt, $q, $sce, ActivityProvider, BlocksProvider, ForgersProvider, StatisticsProvider, AllAssetsProvider, BlockStateProvider, $timeout, dateParser, dateFilter, $rootScope) { $rootScope.paramEngine = $routeParams.engine; $scope.paramEngine = $routeParams.engine; $scope.paramSection = $routeParams.section; $scope.paramPeriod = $routeParams.period; $scope.paramTimestamp = 0; $scope.statistics = {}; $scope.blockstate = {}; $scope.filter = {}; if ($scope.paramEngine == 'nxt') { var api = nxt.nxt(); } else if ($scope.paramEngine == 'fim') { var api = nxt.fim(); } else { $location.path('/activity/fim/activity/latest'); return; } if (['activity', 'blockchain', 'forgers', 'assets'].indexOf($scope.paramSection) == -1) { $location.path('/activity/'+$scope.paramEngine+'/activity/latest'); return; } /* Date picker */ $scope.dt = null; $scope.format = 'dd-MMMM-yyyy'; if ($scope.paramPeriod != 'latest') { var d = dateParser.parse($scope.paramPeriod, $scope.format); if (!d) { $location.path('/activity/'+$scope.paramEngine+'/'+$scope.paramSection+'/latest'); return; } $scope.dt = $scope.paramPeriod; /* Timestamp is for 00:00 hour on selected day */ d = new Date(d.getFullYear(), d.getMonth(), d.getDate()+1, 0, 0, 0); $scope.paramTimestamp = nxt.util.convertToEpochTimestamp(d.getTime()); } $scope.symbol = api.engine.symbol; $scope.blockstate['TYPE_FIM'] = new BlockStateProvider(nxt.fim(), $scope); $scope.blockstate['TYPE_FIM'].load(); if ($rootScope.enableDualEngines) { $scope.blockstate['TYPE_NXT'] = new BlockStateProvider(nxt.nxt(), $scope); $scope.blockstate['TYPE_NXT'].load(); } switch ($scope.paramSection) { case 'activity': $scope.showFilter = true; $scope.showTransactionFilter = true; $scope.provider = new ActivityProvider(api, $scope, $scope.paramTimestamp, null, $scope.filter); $scope.provider.reload(); break; case 'blockchain': $scope.showFilter = true; $scope.provider = new BlocksProvider(api, $scope, $scope.paramTimestamp); $scope.provider.reload(); break; case 'forgers': $scope.showFilter = false; $scope.provider = new ForgersProvider(api, $scope); $scope.provider.reload(); break; case 'assets': $scope.showFilter = false; $scope.provider = new AllAssetsProvider(api, $scope, 10); $scope.provider.reload(); break; default: throw new Error('Not reached'); } $scope.minDate = new Date(Date.UTC(2013, 10, 24, 12, 0, 0, 0)); $scope.maxDate = new Date(); $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.openDatePicker = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; var stopWatching = false; $scope.$watch('dt', function (newValue, oldValue) { if (newValue && newValue !== oldValue && typeof oldValue != 'string' && !stopWatching) { stopWatching = true; var formatted = dateFilter(newValue, $scope.format); $location.path('/activity/'+$scope.paramEngine+'/'+$scope.paramSection+'/'+formatted); } }); if ($scope.showTransactionFilter) { $scope.filter.all = true; $scope.filter.payments = true; $scope.filter.messages = true; $scope.filter.aliases = true; $scope.filter.namespacedAliases = true; $scope.filter.polls = true; $scope.filter.accountInfo = true; $scope.filter.announceHub = true; $scope.filter.goodsStore = true; $scope.filter.balanceLeasing = true; $scope.filter.trades = true; $scope.filter.assetIssued = true; $scope.filter.assetTransfer = true; $scope.filter.assetOrder = true; $scope.filter.currencyIssued = true; $scope.filter.currencyTransfer = true; $scope.filter.currencyOther = true; $scope.filterAllChanged = function () { $scope.$evalAsync(function () { var on = $scope.filter.all; $scope.filter.payments = on; $scope.filter.messages = on; $scope.filter.aliases = on; $scope.filter.namespacedAliases = on; $scope.filter.polls = on; $scope.filter.accountInfo = on; $scope.filter.announceHub = on; $scope.filter.goodsStore = on; $scope.filter.balanceLeasing = on; $scope.filter.trades = on; $scope.filter.assetIssued = on; $scope.filter.assetTransfer = on; $scope.filter.assetOrder = on; $scope.filter.currencyIssued = on; $scope.filter.currencyTransfer = on; $scope.filter.currencyOther = on; $scope.filterChanged(); }); } $scope.filterChanged = function () { $scope.provider.applyFilter($scope.filter); } } $scope.loadStatistics = function (engine, collapse_var) { $scope[collapse_var] = !$scope[collapse_var]; if (!$scope[collapse_var]) { if (!$scope.statistics[engine]) { var api = nxt.get(engine); $scope.statistics[engine] = new StatisticsProvider(api, $scope); } $scope.statistics[engine].load(); } } }); })();
aliasgherlakkadshaw/mofowallet-fork
app/scripts/controllers/activity.js
JavaScript
mit
5,627
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <unordered_set> // template <class Value, class Hash = hash<Value>, class Pred = equal_to<Value>, // class Alloc = allocator<Value>> // class unordered_multiset // size_type max_size() const; #include <unordered_set> #include <cassert> int main() { { std::unordered_multiset<int> u; assert(u.max_size() > 0); } }
lunastorm/wissbi
3rd_party/libcxx/test/containers/unord/unord.multiset/max_size.pass.cpp
C++
mit
711
(function($) { var cultures = $.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["sr-Latn-BA"] = $.extend(true, {}, en, { name: "sr-Latn-BA", englishName: "Serbian (Latin, Bosnia and Herzegovina)", nativeName: "srpski (Bosna i Hercegovina)", language: "sr-Latn", numberFormat: { ',': ".", '.': ",", percent: { ',': ".", '.': "," }, currency: { pattern: ["-n $","n $"], ',': ".", '.': ",", symbol: "KM" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["nedelja","ponedeljak","utorak","sreda","četvrtak","petak","subota"], namesAbbr: ["ned","pon","uto","sre","čet","pet","sub"], namesShort: ["ne","po","ut","sr","če","pe","su"] }, months: { names: ["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar",""], namesAbbr: ["jan","feb","mar","apr","maj","jun","jul","avg","sep","okt","nov","dec",""] }, AM: null, PM: null, eras: [{"name":"n.e.","start":null,"offset":0}], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy H:mm", F: "d. MMMM yyyy H:mm:ss", M: "d. MMMM", Y: "MMMM yyyy" } }) } }, cultures["sr-Latn-BA"]); culture.calendar = culture.calendars.standard; })(jQuery);
Leandro-b-03/SmartBracelet
public/library/javascripts/jquery.GlobalMoneyInput/globinfo/jQuery.glob.sr-Latn-BA.js
JavaScript
mit
1,973
<?php /** * This file is automatically @generated by {@link GeneratePhonePrefixData}. * Please don't modify it directly. */ return array ( 2272020 => 'Niamey', 2272031 => 'Niamey', 2272032 => 'Niamey', 2272033 => 'Niamey', 2272034 => 'Niamey', 2272035 => 'Niamey', 2272036 => 'Niamey', 2272037 => 'Niamey', 2272041 => 'Maradi', 2272044 => 'Agadez', 2272045 => 'Arlit', 2272051 => 'Zinder', 2272054 => 'Diffa', 2272061 => 'Tahoua', 2272064 => 'Konni', 2272065 => 'Dosso', 2272068 => 'Gaya', 2272071 => 'Tillabéry', 2272072 => 'Niamey', 2272073 => 'Niamey', 2272074 => 'Niamey', 2272075 => 'Niamey', 2272077 => 'Filingué', 2272078 => 'Say', );
odooo/design
vendor/giggsey/libphonenumber-for-php/src/geocoding/data/en/227.php
PHP
mit
696
<?php namespace Testing\BDDBundle\Features\Context; use Behat\Symfony2Extension\Context\KernelAwareInterface; use Symfony\Component\HttpKernel\KernelInterface; use Behat\MinkExtension\Context\MinkContext; /** * Feature context. */ class FeatureContext extends MinkContext implements KernelAwareInterface { private $kernel; private $parameters; /** * Initializes context. * Every scenario gets its own context object. * * @param array $parameters context parameters (set them up through behat.yml) */ public function __construct(array $parameters) { $this->parameters = $parameters; } /** * Sets HttpKernel instance. * This method will be automatically called by Symfony2Extension ContextInitializer. * * @param KernelInterface $kernel */ public function setKernel(KernelInterface $kernel) { $this->kernel = $kernel; } /** * @When /^I wait until the download button shows up$/ */ public function waitUntilTheDownloadButtonShowsUp() { $this->getSession()->wait(25000, '$("#download-link").is(":visible")'); } // Place your definition and hook methods here: // // /** // * @Given /^I have done something with "([^"]*)"$/ // */ // public function iHaveDoneSomethingWith($argument) // { // doSomethingWith($argument); // } // }
IgniteYourProject/symfony-fast-start
src/Testing/BDDBundle/Features/Context/FeatureContext.php
PHP
mit
1,398
class Blog < ActiveRecord::Base attr_accessible :body, :title end
masao/enju_blog_plugin
app/models/blog.rb
Ruby
mit
68
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class MemberRegistrationExtra { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="AppBundle\Entity\MembershipTypePeriodExtra", inversedBy="memberRegistrationExtra") * @ORM\JoinColumn(name="membership_type_period_extra_id", referencedColumnName="id") */ private $membershipTypePeriodExtra; /** * @ORM\ManyToOne(targetEntity="AppBundle\Entity\MemberRegistration", inversedBy="memberRegistrationExtra") * @ORM\JoinColumn(name="member_registration_id", referencedColumnName="id", onDelete="CASCADE") */ private $memberRegistration; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set membershipTypePeriodExtra * * @param \AppBundle\Entity\MembershipTypePeriodExtra $membershipTypePeriodExtra * * @return MemberRegistrationExtra */ public function setMembershipTypePeriodExtra(\AppBundle\Entity\MembershipTypePeriodExtra $membershipTypePeriodExtra = null) { $this->membershipTypePeriodExtra = $membershipTypePeriodExtra; return $this; } /** * Get membershipTypePeriodExtra * * @return \AppBundle\Entity\MembershipTypePeriodExtra */ public function getMembershipTypePeriodExtra() { return $this->membershipTypePeriodExtra; } /** * Set memberRegistration * * @param \AppBundle\Entity\MemberRegistration $memberRegistration * * @return MemberRegistrationExtra */ public function setMemberRegistration(\AppBundle\Entity\MemberRegistration $memberRegistration = null) { $this->memberRegistration = $memberRegistration; return $this; } /** * Get memberRegistration * * @return \AppBundle\Entity\MemberRegistration */ public function getMemberRegistration() { return $this->memberRegistration; } }
PeteLawrence/EagleWebsite
src/AppBundle/Entity/MemberRegistrationExtra.php
PHP
mit
2,141
import {Routes} from '@angular/router'; import {CubeExistsGuard} from './guards/cube-exists'; import {FindCubePageComponent} from './containers/cube/find-cube-page'; import {NotFoundPageComponent} from './containers/not-found-page'; import {CubeAnalyticsPage} from './containers/cube/cube-analytics'; import {CubeAnalyticsIndexComponent} from './containers/cube/cube-analytics-index-page'; import {CubeAnalyticsEmbedPage} from './containers/cube/cube-analytics-embed-page'; import {LayoutComponent} from './components/layout'; import {CubeExistsLightGuard} from './guards/cube-exists-light'; import {UserGuidePageComponent} from './components/user-guide'; import {UploadPageComponent} from './containers/cube/upload'; import {LinkedPipesPageComponent} from './containers/cube/linkedpipes'; export const routes: Routes = [ { path: 'cube/analytics/:id/:algorithm/:configuration/embed/:part', canActivate: [CubeExistsLightGuard], component: CubeAnalyticsEmbedPage }, { path: '', component: LayoutComponent, children: [ { path: '', component: FindCubePageComponent }, { path: 'cube/find', component: FindCubePageComponent }, { path: 'userguide', component: UserGuidePageComponent }, { path: 'cube/analytics/:id/:algorithm/:configuration', canActivate: [CubeExistsGuard], component: CubeAnalyticsPage }, { path: 'cube/analytics/:id', canActivate: [CubeExistsGuard], component: CubeAnalyticsIndexComponent }, { path: 'upload', component: UploadPageComponent }, { path: 'upload/linkedpipes', component: LinkedPipesPageComponent } ] }, { path: '**', component: NotFoundPageComponent } ] ;
okgreece/indigo
src/app/routes.ts
TypeScript
mit
1,944
// Chunk.cs // // Author: // Mike Krüger <mkrueger@novell.com> // // Copyright (c) 2007 Novell, Inc (http://www.novell.com) // // 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 Mono.TextEditor.Highlighting; using XwtPlus.TextEditor; namespace Mono.TextEditor { public class Chunk { public Chunk Next { get; set; } public string Style { get; set; } CloneableStack<Span> spanStack; static CloneableStack<Span> emptySpan = new CloneableStack<Span> (); public CloneableStack<Span> SpanStack { get { if (spanStack == null) spanStack = emptySpan.Clone (); return spanStack; } set { spanStack = value; } } public int Offset { get; set; } public int Length { get; set; } public int EndOffset { get { return Offset + Length; } } public Chunk () { Next = null; } public Chunk (int offset, int length, string styleName) { this.Style = styleName; this.Offset = offset; this.Length = length; } public static implicit operator TextSegment (Chunk chunk) { return new TextSegment (chunk.Offset, chunk.Length); } } }
luiscubal/XwtPlus.TextEditor
XwtPlus.TextEditor/Mono.TextEditor.Highlighting/Chunk.cs
C#
mit
2,185
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2014-2017 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "closures.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/shading/oslshadingsystem.h" #include "renderer/modeling/bsdf/ashikhminbrdf.h" #include "renderer/modeling/bsdf/blinnbrdf.h" #include "renderer/modeling/bsdf/diffusebtdf.h" #include "renderer/modeling/bsdf/disneybrdf.h" #include "renderer/modeling/bsdf/glassbsdf.h" #include "renderer/modeling/bsdf/glossybrdf.h" #include "renderer/modeling/bsdf/metalbrdf.h" #include "renderer/modeling/bsdf/orennayarbrdf.h" #include "renderer/modeling/bsdf/sheenbrdf.h" #include "renderer/modeling/bssrdf/dipolebssrdf.h" #include "renderer/modeling/bssrdf/directionaldipolebssrdf.h" #include "renderer/modeling/bssrdf/gaussianbssrdf.h" #include "renderer/modeling/bssrdf/normalizeddiffusionbssrdf.h" #include "renderer/modeling/color/colorspace.h" #include "renderer/modeling/edf/diffuseedf.h" // appleseed.foundation headers. #include "foundation/math/cdf.h" #include "foundation/math/scalar.h" #include "foundation/utility/arena.h" #include "foundation/utility/memory.h" #include "foundation/utility/otherwise.h" // OSL headers. #include "foundation/platform/_beginoslheaders.h" #include "OSL/genclosure.h" #include "OSL/oslclosure.h" #include "OSL/oslversion.h" #include "foundation/platform/_endoslheaders.h" // Standard headers. #include <algorithm> using namespace foundation; using namespace renderer; using namespace std; using OSL::TypeDesc; namespace renderer { namespace { // // Global ustrings. // const OIIO::ustring g_beckmann_str("beckmann"); const OIIO::ustring g_ggx_str("ggx"); const OIIO::ustring g_std_str("std"); const OIIO::ustring g_standard_dipole_profile_str("standard_dipole"); const OIIO::ustring g_better_dipole_profile_str("better_dipole"); const OIIO::ustring g_directional_dipole_profile_str("directional_dipole"); const OIIO::ustring g_normalized_diffusion_profile_str("normalized_diffusion"); const OIIO::ustring g_gaussian_profile_str("gaussian"); // // Closure functions. // typedef void (*convert_closure_fun)( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena); convert_closure_fun g_closure_convert_funs[NumClosuresIDs]; void convert_closure_nop( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { } typedef int (*closure_get_modes)(); closure_get_modes g_closure_get_modes_funs[NumClosuresIDs]; int closure_no_modes() { return 0; } // // Closures. // struct AshikhminShirleyClosure { struct Params { OSL::Vec3 N; OSL::Vec3 T; OSL::Color3 diffuse_reflectance; OSL::Color3 glossy_reflectance; float exponent_u; float exponent_v; float fresnel_multiplier; }; static const char* name() { return "as_ashikhmin_shirley"; } static ClosureID id() { return AshikhminShirleyID; } static int modes() { return ScatteringMode::Diffuse | ScatteringMode::Glossy; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_VECTOR_PARAM(Params, T), CLOSURE_COLOR_PARAM(Params, diffuse_reflectance), CLOSURE_COLOR_PARAM(Params, glossy_reflectance), CLOSURE_FLOAT_PARAM(Params, exponent_u), CLOSURE_FLOAT_PARAM(Params, exponent_v), CLOSURE_FLOAT_PARAM(Params, fresnel_multiplier), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); AshikhminBRDFInputValues* values = composite_closure.add_closure<AshikhminBRDFInputValues>( id(), shading_basis, weight, p->N, p->T, arena); values->m_rd.set(Color3f(p->diffuse_reflectance), g_std_lighting_conditions, Spectrum::Reflectance); values->m_rd_multiplier = 1.0f; values->m_rg.set(Color3f(p->glossy_reflectance), g_std_lighting_conditions, Spectrum::Reflectance); values->m_rg_multiplier = 1.0f; values->m_nu = max(p->exponent_u, 0.01f); values->m_nv = max(p->exponent_v, 0.01f); values->m_fr_multiplier = p->fresnel_multiplier; } }; struct BackgroundClosure { struct Params { }; static const char* name() { return "background"; } static ClosureID id() { return BackgroundID; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); } }; struct BlinnClosure { struct Params { OSL::Vec3 N; float exponent; float ior; }; static const char* name() { return "as_blinn"; } static ClosureID id() { return BlinnID; } static int modes() { return ScatteringMode::Glossy; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FLOAT_PARAM(Params, exponent), CLOSURE_FLOAT_PARAM(Params, ior), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); BlinnBRDFInputValues* values = composite_closure.add_closure<BlinnBRDFInputValues>( BlinnID, shading_basis, weight, p->N, arena); values->m_exponent = max(p->exponent, 0.001f); values->m_ior = max(p->ior, 0.001f); } }; struct DebugClosure { struct Params { OSL::ustring tag; }; static const char* name() { return "debug"; } static ClosureID id() { return DebugID; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_STRING_PARAM(Params, tag), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); } }; struct DiffuseClosure { struct Params { OSL::Vec3 N; }; static const char* name() { return "diffuse"; } static ClosureID id() { return DiffuseID; } static int modes() { return ScatteringMode::Diffuse; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); OrenNayarBRDFInputValues* values = composite_closure.add_closure<OrenNayarBRDFInputValues>( OrenNayarID, shading_basis, weight, p->N, arena); values->m_reflectance.set(1.0f); values->m_reflectance_multiplier = 1.0f; values->m_roughness = 0.0f; } }; struct DisneyClosure { struct Params { OSL::Vec3 N; OSL::Vec3 T; OSL::Color3 base_color; float subsurface; float metallic; float specular; float specular_tint; float anisotropic; float roughness; float sheen; float sheen_tint; float clearcoat; float clearcoat_gloss; }; static const char* name() { return "as_disney"; } static ClosureID id() { return DisneyID; } static int modes() { return ScatteringMode::Diffuse | ScatteringMode::Glossy; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_VECTOR_PARAM(Params, T), CLOSURE_COLOR_PARAM(Params, base_color), CLOSURE_FLOAT_PARAM(Params, subsurface), CLOSURE_FLOAT_PARAM(Params, metallic), CLOSURE_FLOAT_PARAM(Params, specular), CLOSURE_FLOAT_PARAM(Params, specular_tint), CLOSURE_FLOAT_PARAM(Params, anisotropic), CLOSURE_FLOAT_PARAM(Params, roughness), CLOSURE_FLOAT_PARAM(Params, sheen), CLOSURE_FLOAT_PARAM(Params, sheen_tint), CLOSURE_FLOAT_PARAM(Params, clearcoat), CLOSURE_FLOAT_PARAM(Params, clearcoat_gloss), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); DisneyBRDFInputValues* values = composite_closure.add_closure<DisneyBRDFInputValues>( id(), shading_basis, weight, p->N, p->T, arena); values->m_base_color.set(Color3f(p->base_color), g_std_lighting_conditions, Spectrum::Reflectance); values->m_subsurface = saturate(p->subsurface); values->m_metallic = saturate(p->metallic); values->m_specular = max(p->specular, 0.0f); values->m_specular_tint = saturate(p->specular_tint); values->m_anisotropic = clamp(p->anisotropic, -1.0f, 1.0f); values->m_roughness = clamp(p->roughness, 0.0001f, 1.0f); values->m_sheen = saturate(p->sheen); values->m_sheen_tint = saturate(p->sheen_tint); values->m_clearcoat = max(p->clearcoat, 0.0f); values->m_clearcoat_gloss = clamp(p->clearcoat_gloss, 0.0001f, 1.0f); } }; struct EmissionClosure { struct Params { }; static const char* name() { return "emission"; } static ClosureID id() { return EmissionID; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); } static void convert_closure( CompositeEmissionClosure& composite_closure, const void* osl_params, const Color3f& weight, const float max_weight_component, Arena& arena) { DiffuseEDFInputValues* values = composite_closure.add_closure<DiffuseEDFInputValues>( id(), weight, max_weight_component, arena); values->m_radiance.set(Color3f(weight / max_weight_component), g_std_lighting_conditions, Spectrum::Illuminance); values->m_radiance_multiplier = max_weight_component; values->m_exposure = 0.0f; } }; struct GlassClosure { struct Params { OSL::ustring dist; OSL::Vec3 N; OSL::Vec3 T; OSL::Color3 surface_transmittance; OSL::Color3 reflection_tint; OSL::Color3 refraction_tint; float roughness; float highlight_falloff; float anisotropy; float ior; OSL::Color3 volume_transmittance; float volume_transmittance_distance; }; static const char* name() { return "as_glass"; } static ClosureID id() { return GlassID; } static int modes() { return ScatteringMode::Glossy | ScatteringMode::Specular; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_STRING_PARAM(Params, dist), CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_VECTOR_PARAM(Params, T), CLOSURE_COLOR_PARAM(Params, surface_transmittance), CLOSURE_COLOR_PARAM(Params, reflection_tint), CLOSURE_COLOR_PARAM(Params, refraction_tint), CLOSURE_FLOAT_PARAM(Params, roughness), CLOSURE_FLOAT_PARAM(Params, highlight_falloff), CLOSURE_FLOAT_PARAM(Params, anisotropy), CLOSURE_FLOAT_PARAM(Params, ior), CLOSURE_COLOR_PARAM(Params, volume_transmittance), CLOSURE_FLOAT_PARAM(Params, volume_transmittance_distance), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; g_closure_get_modes_funs[GlassBeckmannID] = &modes; g_closure_get_modes_funs[GlassGGXID] = &modes; g_closure_get_modes_funs[GlassSTDID] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); GlassBSDFInputValues* values; ClosureID cid; if (p->dist == g_ggx_str) cid = GlassGGXID; else if (p->dist == g_beckmann_str) cid = GlassBeckmannID; else if (p->dist == g_std_str) cid = GlassSTDID; else { string msg("invalid microfacet distribution function: "); msg += p->dist.c_str(); throw ExceptionOSLRuntimeError(msg.c_str()); } values = composite_closure.add_closure<GlassBSDFInputValues>( cid, shading_basis, weight, p->N, p->T, arena); values->m_surface_transmittance.set(Color3f(p->surface_transmittance), g_std_lighting_conditions, Spectrum::Reflectance); values->m_surface_transmittance_multiplier = 1.0f; values->m_reflection_tint.set(Color3f(p->reflection_tint), g_std_lighting_conditions, Spectrum::Reflectance); values->m_refraction_tint.set(Color3f(p->refraction_tint), g_std_lighting_conditions, Spectrum::Reflectance); values->m_roughness = max(p->roughness, 0.0001f); values->m_highlight_falloff = saturate(p->highlight_falloff); values->m_anisotropy = clamp(p->anisotropy, -1.0f, 1.0f); values->m_ior = max(p->ior, 0.001f); values->m_volume_transmittance.set(Color3f(p->volume_transmittance), g_std_lighting_conditions, Spectrum::Reflectance); values->m_volume_transmittance_distance = p->volume_transmittance_distance; composite_closure.add_ior(weight, values->m_ior); } }; struct GlossyClosure { struct Params { OSL::ustring dist; OSL::Vec3 N; OSL::Vec3 T; float roughness; float highlight_falloff; float anisotropy; float ior; }; static const char* name() { return "as_glossy"; } static ClosureID id() { return GlossyID; } static int modes() { return ScatteringMode::Glossy | ScatteringMode::Specular; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_STRING_PARAM(Params, dist), CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_VECTOR_PARAM(Params, T), CLOSURE_FLOAT_PARAM(Params, roughness), CLOSURE_FLOAT_PARAM(Params, highlight_falloff), CLOSURE_FLOAT_PARAM(Params, anisotropy), CLOSURE_FLOAT_PARAM(Params, ior), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; g_closure_get_modes_funs[GlossyBeckmannID] = &modes; g_closure_get_modes_funs[GlossyGGXID] = &modes; g_closure_get_modes_funs[GlossySTDID] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); GlossyBRDFInputValues* values; ClosureID cid; if (p->dist == g_ggx_str) cid = GlossyGGXID; else if (p->dist == g_beckmann_str) cid = GlossyBeckmannID; else if (p->dist == g_std_str) cid = GlossySTDID; else { string msg("invalid microfacet distribution function: "); msg += p->dist.c_str(); throw ExceptionOSLRuntimeError(msg.c_str()); } values = composite_closure.add_closure<GlossyBRDFInputValues>( cid, shading_basis, weight, p->N, p->T, arena); values->m_reflectance.set(1.0f); values->m_reflectance_multiplier = 1.0f; values->m_roughness = max(p->roughness, 0.0f); values->m_highlight_falloff = saturate(p->highlight_falloff); values->m_anisotropy = clamp(p->anisotropy, -1.0f, 1.0f); values->m_ior = max(p->ior, 0.001f); } }; struct HoldoutClosure { struct Params { }; static const char* name() { return "holdout"; } static ClosureID id() { return HoldoutID; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); } }; struct MetalClosure { struct Params { OSL::ustring dist; OSL::Vec3 N; OSL::Vec3 T; OSL::Color3 normal_reflectance; OSL::Color3 edge_tint; float roughness; float highlight_falloff; float anisotropy; }; static const char* name() { return "as_metal"; } static ClosureID id() { return MetalID; } static int modes() { return ScatteringMode::Glossy | ScatteringMode::Specular; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_STRING_PARAM(Params, dist), CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_VECTOR_PARAM(Params, T), CLOSURE_COLOR_PARAM(Params, normal_reflectance), CLOSURE_COLOR_PARAM(Params, edge_tint), CLOSURE_FLOAT_PARAM(Params, roughness), CLOSURE_FLOAT_PARAM(Params, highlight_falloff), CLOSURE_FLOAT_PARAM(Params, anisotropy), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; g_closure_get_modes_funs[MetalBeckmannID] = &modes; g_closure_get_modes_funs[MetalGGXID] = &modes; g_closure_get_modes_funs[MetalSTDID] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); MetalBRDFInputValues* values; ClosureID cid; if (p->dist == g_ggx_str) cid = MetalGGXID; else if (p->dist == g_beckmann_str) cid = MetalBeckmannID; else if (p->dist == g_std_str) cid = MetalSTDID; else { string msg("invalid microfacet distribution function: "); msg += p->dist.c_str(); throw ExceptionOSLRuntimeError(msg.c_str()); } values = composite_closure.add_closure<MetalBRDFInputValues>( cid, shading_basis, weight, p->N, p->T, arena); values->m_normal_reflectance.set(Color3f(p->normal_reflectance), g_std_lighting_conditions, Spectrum::Reflectance); values->m_edge_tint.set(Color3f(p->edge_tint), g_std_lighting_conditions, Spectrum::Reflectance); values->m_reflectance_multiplier = 1.0f; values->m_roughness = max(p->roughness, 0.0f); values->m_highlight_falloff = saturate(p->highlight_falloff); values->m_anisotropy = clamp(p->anisotropy, -1.0f, 1.0f); } }; struct OrenNayarClosure { struct Params { OSL::Vec3 N; float roughness; }; static const char* name() { return "oren_nayar"; } static ClosureID id() { return OrenNayarID; } static int modes() { return ScatteringMode::Diffuse; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FLOAT_PARAM(Params, roughness), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); OrenNayarBRDFInputValues* values = composite_closure.add_closure<OrenNayarBRDFInputValues>( id(), shading_basis, weight, p->N, arena); values->m_reflectance.set(1.0f); values->m_reflectance_multiplier = 1.0f; values->m_roughness = max(p->roughness, 0.0f); } }; struct PhongClosure { struct Params { OSL::Vec3 N; float exponent; }; static const char* name() { return "phong"; } static ClosureID id() { return PhongID; } static int modes() { return ScatteringMode::Glossy; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FLOAT_PARAM(Params, exponent), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); AshikhminBRDFInputValues* values = composite_closure.add_closure<AshikhminBRDFInputValues>( AshikhminShirleyID, shading_basis, weight, p->N, arena); values->m_rd.set(1.0f); values->m_rd_multiplier = 1.0f; values->m_rg.set(1.0f); values->m_rg_multiplier = 1.0f; values->m_nu = max(p->exponent, 0.01f); values->m_nv = max(p->exponent, 0.01f); values->m_fr_multiplier = 1.0f; } }; struct ReflectionClosure { struct Params { OSL::Vec3 N; float ior; }; static const char* name() { return "reflection"; } static ClosureID id() { return ReflectionID; } static int modes() { return ScatteringMode::Specular; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FLOAT_PARAM(Params, ior), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); GlossyBRDFInputValues* values = composite_closure.add_closure<GlossyBRDFInputValues>( GlossyBeckmannID, shading_basis, weight, p->N, arena); values->m_reflectance.set(1.0f); values->m_reflectance_multiplier = 1.0f; values->m_roughness = 0.0f; values->m_anisotropy = 0.0f; values->m_ior = max(p->ior, 0.001f); } }; struct SheenClosure { struct Params { OSL::Vec3 N; }; static const char* name() { return "as_sheen"; } static ClosureID id() { return SheenID; } static int modes() { return ScatteringMode::Diffuse; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); SheenBRDFInputValues* values = composite_closure.add_closure<SheenBRDFInputValues>( id(), shading_basis, weight, p->N, arena); values->m_reflectance.set(1.0f); values->m_reflectance_multiplier = 1.0f; } }; struct SubsurfaceClosure { struct Params { OSL::ustring profile; OSL::Vec3 N; OSL::Color3 reflectance; OSL::Color3 mean_free_path; float ior; float fresnel_weight; }; static const char* name() { return "as_subsurface"; } static ClosureID id() { return SubsurfaceID; } static void prepare_closure( OSL::RendererServices* render_services, int id, void* data) { // Initialize keyword parameter defaults. Params* params = new (data) Params(); params->fresnel_weight = 1.0f; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_STRING_PARAM(Params, profile), CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_COLOR_PARAM(Params, reflectance), CLOSURE_COLOR_PARAM(Params, mean_free_path), CLOSURE_FLOAT_PARAM(Params, ior), CLOSURE_FLOAT_KEYPARAM(Params, fresnel_weight, "fresnel_weight"), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, &prepare_closure, nullptr); } static void convert_closure( CompositeSubsurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); if (p->profile == g_normalized_diffusion_profile_str) { NormalizedDiffusionBSSRDFInputValues* values = composite_closure.add_closure<NormalizedDiffusionBSSRDFInputValues>( SubsurfaceNormalizedDiffusionID, shading_basis, weight, p->N, arena); copy_parameters(p, values); } else if (p->profile == g_gaussian_profile_str) { GaussianBSSRDFInputValues* values = composite_closure.add_closure<GaussianBSSRDFInputValues>( SubsurfaceGaussianID, shading_basis, weight, p->N, arena); copy_parameters(p, values); } else { DipoleBSSRDFInputValues* values; if (p->profile == g_better_dipole_profile_str) { values = composite_closure.add_closure<DipoleBSSRDFInputValues>( SubsurfaceBetterDipoleID, shading_basis, weight, p->N, arena); } else if (p->profile == g_standard_dipole_profile_str) { values = composite_closure.add_closure<DipoleBSSRDFInputValues>( SubsurfaceStandardDipoleID, shading_basis, weight, p->N, arena); } else if (p->profile == g_directional_dipole_profile_str) { values = composite_closure.add_closure<DipoleBSSRDFInputValues>( SubsurfaceDirectionalDipoleID, shading_basis, weight, p->N, arena); } else { string msg = "unknown subsurface profile: "; msg += p->profile.c_str(); throw ExceptionOSLRuntimeError(msg.c_str()); } copy_parameters(p, values); } } template <typename InputValues> static void copy_parameters( const Params* p, InputValues* values) { values->m_weight = 1.0f; values->m_reflectance.set(Color3f(p->reflectance), g_std_lighting_conditions, Spectrum::Reflectance); values->m_reflectance_multiplier = 1.0f; values->m_mfp.set(Color3f(p->mean_free_path), g_std_lighting_conditions, Spectrum::Reflectance); values->m_mfp_multiplier = 1.0f; values->m_ior = p->ior; values->m_fresnel_weight = saturate(p->fresnel_weight); } }; struct TranslucentClosure { struct Params { OSL::Vec3 N; }; static const char* name() { return "translucent"; } static ClosureID id() { return TranslucentID; } static int modes() { return ScatteringMode::Diffuse; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_VECTOR_PARAM(Params, N), CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); g_closure_convert_funs[id()] = &convert_closure; g_closure_get_modes_funs[id()] = &modes; } static void convert_closure( CompositeSurfaceClosure& composite_closure, const Basis3f& shading_basis, const void* osl_params, const Color3f& weight, Arena& arena) { const Params* p = static_cast<const Params*>(osl_params); DiffuseBTDFInputValues* values = composite_closure.add_closure<DiffuseBTDFInputValues>( id(), shading_basis, weight, p->N, arena); values->m_transmittance.set(1.0f); values->m_transmittance_multiplier = 1.0f; } }; struct TransparentClosure { struct Params { }; static const char* name() { return "transparent"; } static ClosureID id() { return TransparentID; } static void register_closure(OSLShadingSystem& shading_system) { const OSL::ClosureParam params[] = { CLOSURE_FINISH_PARAM(Params) }; shading_system.register_closure(name(), id(), params, nullptr, nullptr); } }; } // // CompositeClosure class implementation. // CompositeClosure::CompositeClosure() : m_closure_count(0) { } void CompositeClosure::compute_closure_shading_basis( const Vector3f& normal, const Basis3f& original_shading_basis) { const float normal_square_norm = square_norm(normal); if APPLESEED_LIKELY(normal_square_norm != 0.0f) { const float rcp_normal_norm = 1.0f / sqrt(normal_square_norm); m_bases[m_closure_count] = Basis3f( normal * rcp_normal_norm, original_shading_basis.get_tangent_u()); } else { // Fallback to the original shading basis if the normal is zero. m_bases[m_closure_count] = original_shading_basis; } } void CompositeClosure::compute_closure_shading_basis( const Vector3f& normal, const Vector3f& tangent, const Basis3f& original_shading_basis) { const float tangent_square_norm = square_norm(tangent); if APPLESEED_LIKELY(tangent_square_norm != 0.0f) { const float normal_square_norm = square_norm(normal); if APPLESEED_LIKELY(normal_square_norm != 0.0f) { const float rcp_normal_norm = 1.0f / sqrt(normal_square_norm); const float rcp_tangent_norm = 1.0f / sqrt(tangent_square_norm); m_bases[m_closure_count] = Basis3f( normal * rcp_normal_norm, tangent * rcp_tangent_norm); } else { // Fallback to the original shading basis if the normal is zero. m_bases[m_closure_count] = original_shading_basis; } } else { // If the tangent is zero, ignore it. // This can happen when using the isotropic microfacet closure overloads, for example. compute_closure_shading_basis(normal, original_shading_basis); } } template <typename InputValues> InputValues* CompositeClosure::add_closure( const ClosureID closure_type, const Basis3f& original_shading_basis, const Color3f& weight, const Vector3f& normal, Arena& arena) { return do_add_closure<InputValues>( closure_type, original_shading_basis, weight, normal, false, Vector3f(0.0f), arena); } template <typename InputValues> InputValues* CompositeClosure::add_closure( const ClosureID closure_type, const Basis3f& original_shading_basis, const Color3f& weight, const Vector3f& normal, const Vector3f& tangent, Arena& arena) { return do_add_closure<InputValues>( closure_type, original_shading_basis, weight, normal, true, tangent, arena); } template <typename InputValues> InputValues* CompositeClosure::do_add_closure( const ClosureID closure_type, const Basis3f& original_shading_basis, const Color3f& weight, const Vector3f& normal, const bool has_tangent, const Vector3f& tangent, Arena& arena) { // Make sure we have enough space. if APPLESEED_UNLIKELY(get_closure_count() >= MaxClosureEntries) { throw ExceptionOSLRuntimeError( "maximum number of closures in osl shader group exceeded"); } // We use the luminance of the weight as the BSDF weight. const float w = luminance(weight); assert(w > 0.0f); m_weights[m_closure_count].set(weight, g_std_lighting_conditions, Spectrum::Reflectance); m_scalar_weights[m_closure_count] = w; if (!has_tangent) compute_closure_shading_basis(normal, original_shading_basis); else compute_closure_shading_basis(normal, tangent, original_shading_basis); m_closure_types[m_closure_count] = closure_type; InputValues* values = arena.allocate<InputValues>(); m_input_values[m_closure_count] = values; ++m_closure_count; return values; } void CompositeClosure::compute_pdfs(float pdfs[MaxClosureEntries]) { const size_t closure_count = get_closure_count(); float total_weight = 0.0f; for (size_t i = 0; i < closure_count; ++i) { pdfs[i] = m_scalar_weights[i]; total_weight += pdfs[i]; } if (total_weight != 0.0f) { const float rcp_total_weight = 1.0f / total_weight; for (size_t i = 0; i < closure_count; ++i) pdfs[i] *= rcp_total_weight; } } // // CompositeSurfaceClosure class implementation. // CompositeSurfaceClosure::CompositeSurfaceClosure( const Basis3f& original_shading_basis, const OSL::ClosureColor* ci, Arena& arena) : m_ior_count(0) { process_closure_tree(ci, original_shading_basis, Color3f(1.0f), arena); if (m_ior_count == 0) { m_ior_count = 1; m_iors[0] = 1.0f; return; } // Build the IOR CDF in place if needed. if (m_ior_count > 1) { float total_weight = m_ior_cdf[0]; for (size_t i = 1; i < m_ior_count; ++i) { total_weight += m_ior_cdf[i]; m_ior_cdf[i] = total_weight; } const float rcp_total_weight = 1.0f / total_weight; for (size_t i = 0; i < m_ior_count - 1; ++i) m_ior_cdf[i] *= rcp_total_weight; m_ior_cdf[m_ior_count - 1] = 1.0f; } } int CompositeSurfaceClosure::compute_pdfs( const int modes, float pdfs[MaxClosureEntries]) const { memset(pdfs, 0, sizeof(float) * MaxClosureEntries); int num_closures = 0; float sum_weights = 0.0f; for (size_t i = 0, e = get_closure_count(); i < e; ++i) { const ClosureID cid = m_closure_types[i]; const int closure_modes = g_closure_get_modes_funs[cid](); if (closure_modes & modes) { pdfs[i] = m_scalar_weights[i]; sum_weights += m_scalar_weights[i]; ++num_closures; } else pdfs[i] = 0.0f; } if (sum_weights != 0.0f) { const float rcp_sum_weights = 1.0f / sum_weights; for (size_t i = 0, e = get_closure_count(); i < e; ++i) pdfs[i] *= rcp_sum_weights; } return num_closures; } size_t CompositeSurfaceClosure::choose_closure( const float w, const size_t num_closures, float pdfs[MaxClosureEntries]) const { assert(num_closures > 0); assert(num_closures < MaxClosureEntries); return sample_pdf_linear_search(pdfs, num_closures, w); } void CompositeSurfaceClosure::add_ior( const foundation::Color3f& weight, const float ior) { // We use the luminance of the weight as the IOR weight. const float w = luminance(weight); assert(w > 0.0f); m_iors[m_ior_count] = ior; m_ior_cdf[m_ior_count] = w; ++m_ior_count; } float CompositeSurfaceClosure::choose_ior(const float w) const { assert(m_ior_count > 0); if APPLESEED_LIKELY(m_ior_count == 1) return m_iors[0]; const size_t index = sample_cdf_linear_search(m_ior_cdf, w); return m_iors[index]; } void CompositeSurfaceClosure::process_closure_tree( const OSL::ClosureColor* closure, const Basis3f& original_shading_basis, const Color3f& weight, Arena& arena) { if (closure == nullptr) return; switch (closure->id) { case OSL::ClosureColor::MUL: { const OSL::ClosureMul* c = reinterpret_cast<const OSL::ClosureMul*>(closure); const Color3f w = weight * Color3f(c->weight); process_closure_tree(c->closure, original_shading_basis, w, arena); } break; case OSL::ClosureColor::ADD: { const OSL::ClosureAdd* c = reinterpret_cast<const OSL::ClosureAdd*>(closure); process_closure_tree(c->closureA, original_shading_basis, weight, arena); process_closure_tree(c->closureB, original_shading_basis, weight, arena); } break; default: { const OSL::ClosureComponent* c = reinterpret_cast<const OSL::ClosureComponent*>(closure); const Color3f w = weight * Color3f(c->w); if (luminance(w) > 0.0f) g_closure_convert_funs[c->id](*this, original_shading_basis, c->data(), w, arena); } break; } } // // CompositeSubsurfaceClosure class implementation. // CompositeSubsurfaceClosure::CompositeSubsurfaceClosure( const Basis3f& original_shading_basis, const OSL::ClosureColor* ci, Arena& arena) { process_closure_tree(ci, original_shading_basis, Color3f(1.0f), arena); compute_pdfs(m_pdfs); } size_t CompositeSubsurfaceClosure::choose_closure(const float w) const { assert(get_closure_count() > 0); return sample_pdf_linear_search(m_pdfs, get_closure_count(), w); } void CompositeSubsurfaceClosure::process_closure_tree( const OSL::ClosureColor* closure, const Basis3f& original_shading_basis, const foundation::Color3f& weight, Arena& arena) { if (closure == nullptr) return; switch (closure->id) { case OSL::ClosureColor::MUL: { const OSL::ClosureMul* c = reinterpret_cast<const OSL::ClosureMul*>(closure); process_closure_tree(c->closure, original_shading_basis, weight * Color3f(c->weight), arena); } break; case OSL::ClosureColor::ADD: { const OSL::ClosureAdd* c = reinterpret_cast<const OSL::ClosureAdd*>(closure); process_closure_tree(c->closureA, original_shading_basis, weight, arena); process_closure_tree(c->closureB, original_shading_basis, weight, arena); } break; default: { const OSL::ClosureComponent* c = reinterpret_cast<const OSL::ClosureComponent*>(closure); if (c->id == SubsurfaceID) { const Color3f w = weight * Color3f(c->w); if (luminance(w) > 0.0f) { SubsurfaceClosure::convert_closure( *this, original_shading_basis, c->data(), w, arena); } } } break; } } // // CompositeEmissionClosure class implementation. // CompositeEmissionClosure::CompositeEmissionClosure( const OSL::ClosureColor* ci, Arena& arena) { process_closure_tree(ci, Color3f(1.0f), arena); compute_pdfs(m_pdfs); } size_t CompositeEmissionClosure::choose_closure(const float w) const { assert(get_closure_count() > 0); return sample_pdf_linear_search(m_pdfs, get_closure_count(), w); } template <typename InputValues> InputValues* CompositeEmissionClosure::add_closure( const ClosureID closure_type, const Color3f& weight, const float max_weight_component, Arena& arena) { // Make sure we have enough space. if APPLESEED_UNLIKELY(get_closure_count() >= MaxClosureEntries) { throw ExceptionOSLRuntimeError( "maximum number of closures in osl shader group exceeded"); } m_closure_types[m_closure_count] = closure_type; m_weights[m_closure_count].set(weight, g_std_lighting_conditions, Spectrum::Reflectance); m_pdfs[m_closure_count] = max_weight_component; InputValues* values = arena.allocate<InputValues>(); m_input_values[m_closure_count] = values; ++m_closure_count; return values; } void CompositeEmissionClosure::process_closure_tree( const OSL::ClosureColor* closure, const Color3f& weight, Arena& arena) { if (closure == nullptr) return; switch (closure->id) { case OSL::ClosureColor::MUL: { const OSL::ClosureMul* c = reinterpret_cast<const OSL::ClosureMul*>(closure); process_closure_tree(c->closure, weight * Color3f(c->weight), arena); } break; case OSL::ClosureColor::ADD: { const OSL::ClosureAdd* c = reinterpret_cast<const OSL::ClosureAdd*>(closure); process_closure_tree(c->closureA, weight, arena); process_closure_tree(c->closureB, weight, arena); } break; default: { const OSL::ClosureComponent* c = reinterpret_cast<const OSL::ClosureComponent*>(closure); const Color3f w = weight * Color3f(c->w); const float max_weight_component = max_value(w); if (max_weight_component > 0.0f) { if (c->id == EmissionID) { EmissionClosure::convert_closure( *this, c->data(), w, max_weight_component, arena); } } } break; } } // // Utility functions implementation. // namespace { Color3f do_process_closure_id_tree( const OSL::ClosureColor* closure, const int closure_id) { if (closure) { switch (closure->id) { case OSL::ClosureColor::MUL: { const OSL::ClosureMul* c = reinterpret_cast<const OSL::ClosureMul*>(closure); return Color3f(c->weight) * do_process_closure_id_tree(c->closure, closure_id); } break; case OSL::ClosureColor::ADD: { const OSL::ClosureAdd* c = reinterpret_cast<const OSL::ClosureAdd*>(closure); return do_process_closure_id_tree(c->closureA, closure_id) + do_process_closure_id_tree(c->closureB, closure_id); } break; default: { const OSL::ClosureComponent* c = reinterpret_cast<const OSL::ClosureComponent*>(closure); if (c->id == closure_id) return Color3f(c->w); else return Color3f(0.0f); } break; } } return Color3f(0.0f); } } void process_transparency_tree(const OSL::ClosureColor* ci, Alpha& alpha) { // Convert from transparency to opacity. const float transparency = saturate(luminance(do_process_closure_id_tree(ci, TransparentID))); alpha.set(1.0f - transparency); } float process_holdout_tree(const OSL::ClosureColor* ci) { return saturate(luminance(do_process_closure_id_tree(ci, HoldoutID))); } Color3f process_background_tree(const OSL::ClosureColor* ci) { return do_process_closure_id_tree(ci, BackgroundID); } namespace { template <typename ClosureType> void register_closure(OSLShadingSystem& shading_system) { ClosureType::register_closure(shading_system); RENDERER_LOG_DEBUG("registered osl closure %s.", ClosureType::name()); } } void register_closures(OSLShadingSystem& shading_system) { for (size_t i = 0; i < NumClosuresIDs; ++i) { g_closure_convert_funs[i] = &convert_closure_nop; g_closure_get_modes_funs[i] = &closure_no_modes; } register_closure<AshikhminShirleyClosure>(shading_system); register_closure<BackgroundClosure>(shading_system); register_closure<BlinnClosure>(shading_system); register_closure<DebugClosure>(shading_system); register_closure<DiffuseClosure>(shading_system); register_closure<DisneyClosure>(shading_system); register_closure<EmissionClosure>(shading_system); register_closure<GlassClosure>(shading_system); register_closure<GlossyClosure>(shading_system); register_closure<HoldoutClosure>(shading_system); register_closure<MetalClosure>(shading_system); register_closure<OrenNayarClosure>(shading_system); register_closure<PhongClosure>(shading_system); register_closure<ReflectionClosure>(shading_system); register_closure<SheenClosure>(shading_system); register_closure<SubsurfaceClosure>(shading_system); register_closure<TranslucentClosure>(shading_system); register_closure<TransparentClosure>(shading_system); } } // namespace renderer
Aakash1312/appleseed
src/appleseed/renderer/kernel/shading/closures.cpp
C++
mit
58,655
'use strict'; var express = require('express') , router = express.Router(); import * as ctrl from './controller'; router.get('/contact', ctrl.contact); export default router;
calebgregory/portfolio
app/home/routes.js
JavaScript
mit
182
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A Disassembler object is used to disassemble a block of code instruction by // instruction. The default implementation of the NameConverter object can be // overriden to modify register names or to do symbol lookup on addresses. // // The example below will disassemble a block of code and print it to stdout. // // NameConverter converter; // Disassembler d(converter); // for (byte* pc = begin; pc < end;) { // v8::internal::EmbeddedVector<char, 256> buffer; // byte* prev_pc = pc; // pc += d.InstructionDecode(buffer, pc); // printf("%p %08x %s\n", // prev_pc, *reinterpret_cast<int32_t*>(prev_pc), buffer); // } // // The Disassembler class also has a convenience method to disassemble a block // of code into a FILE*, meaning that the above functionality could also be // achieved by just calling Disassembler::Disassemble(stdout, begin, end); #include <assert.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include "v8.h" #if V8_TARGET_ARCH_MIPS #include "mips/constants-mips.h" #include "disasm.h" #include "macro-assembler.h" #include "platform.h" namespace v8 { namespace internal { //------------------------------------------------------------------------------ // Decoder decodes and disassembles instructions into an output buffer. // It uses the converter to convert register names and call destinations into // more informative description. class Decoder { public: Decoder(const disasm::NameConverter& converter, v8::internal::Vector<char> out_buffer) : converter_(converter), out_buffer_(out_buffer), out_buffer_pos_(0) { out_buffer_[out_buffer_pos_] = '\0'; } ~Decoder() {} // Writes one disassembled instruction into 'buffer' (0-terminated). // Returns the length of the disassembled machine instruction in bytes. int InstructionDecode(byte* instruction); private: // Bottleneck functions to print into the out_buffer. void PrintChar(const char ch); void Print(const char* str); // Printing of common values. void PrintRegister(int reg); void PrintFPURegister(int freg); void PrintRs(Instruction* instr); void PrintRt(Instruction* instr); void PrintRd(Instruction* instr); void PrintFs(Instruction* instr); void PrintFt(Instruction* instr); void PrintFd(Instruction* instr); void PrintSa(Instruction* instr); void PrintSd(Instruction* instr); void PrintSs1(Instruction* instr); void PrintSs2(Instruction* instr); void PrintBc(Instruction* instr); void PrintCc(Instruction* instr); void PrintFunction(Instruction* instr); void PrintSecondaryField(Instruction* instr); void PrintUImm16(Instruction* instr); void PrintSImm16(Instruction* instr); void PrintXImm16(Instruction* instr); void PrintXImm26(Instruction* instr); void PrintCode(Instruction* instr); // For break and trap instructions. // Printing of instruction name. void PrintInstructionName(Instruction* instr); // Handle formatting of instructions and their options. int FormatRegister(Instruction* instr, const char* option); int FormatFPURegister(Instruction* instr, const char* option); int FormatOption(Instruction* instr, const char* option); void Format(Instruction* instr, const char* format); void Unknown(Instruction* instr); // Each of these functions decodes one particular instruction type. void DecodeTypeRegister(Instruction* instr); void DecodeTypeImmediate(Instruction* instr); void DecodeTypeJump(Instruction* instr); const disasm::NameConverter& converter_; v8::internal::Vector<char> out_buffer_; int out_buffer_pos_; DISALLOW_COPY_AND_ASSIGN(Decoder); }; // Support for assertions in the Decoder formatting functions. #define STRING_STARTS_WITH(string, compare_string) \ (strncmp(string, compare_string, strlen(compare_string)) == 0) // Append the ch to the output buffer. void Decoder::PrintChar(const char ch) { out_buffer_[out_buffer_pos_++] = ch; } // Append the str to the output buffer. void Decoder::Print(const char* str) { char cur = *str++; while (cur != '\0' && (out_buffer_pos_ < (out_buffer_.length() - 1))) { PrintChar(cur); cur = *str++; } out_buffer_[out_buffer_pos_] = 0; } // Print the register name according to the active name converter. void Decoder::PrintRegister(int reg) { Print(converter_.NameOfCPURegister(reg)); } void Decoder::PrintRs(Instruction* instr) { int reg = instr->RsValue(); PrintRegister(reg); } void Decoder::PrintRt(Instruction* instr) { int reg = instr->RtValue(); PrintRegister(reg); } void Decoder::PrintRd(Instruction* instr) { int reg = instr->RdValue(); PrintRegister(reg); } // Print the FPUregister name according to the active name converter. void Decoder::PrintFPURegister(int freg) { Print(converter_.NameOfXMMRegister(freg)); } void Decoder::PrintFs(Instruction* instr) { int freg = instr->RsValue(); PrintFPURegister(freg); } void Decoder::PrintFt(Instruction* instr) { int freg = instr->RtValue(); PrintFPURegister(freg); } void Decoder::PrintFd(Instruction* instr) { int freg = instr->RdValue(); PrintFPURegister(freg); } // Print the integer value of the sa field. void Decoder::PrintSa(Instruction* instr) { int sa = instr->SaValue(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%d", sa); } // Print the integer value of the rd field, when it is not used as reg. void Decoder::PrintSd(Instruction* instr) { int sd = instr->RdValue(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%d", sd); } // Print the integer value of the rd field, when used as 'ext' size. void Decoder::PrintSs1(Instruction* instr) { int ss = instr->RdValue(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%d", ss + 1); } // Print the integer value of the rd field, when used as 'ins' size. void Decoder::PrintSs2(Instruction* instr) { int ss = instr->RdValue(); int pos = instr->SaValue(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%d", ss - pos + 1); } // Print the integer value of the cc field for the bc1t/f instructions. void Decoder::PrintBc(Instruction* instr) { int cc = instr->FBccValue(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%d", cc); } // Print the integer value of the cc field for the FP compare instructions. void Decoder::PrintCc(Instruction* instr) { int cc = instr->FCccValue(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "cc(%d)", cc); } // Print 16-bit unsigned immediate value. void Decoder::PrintUImm16(Instruction* instr) { int32_t imm = instr->Imm16Value(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%u", imm); } // Print 16-bit signed immediate value. void Decoder::PrintSImm16(Instruction* instr) { int32_t imm = ((instr->Imm16Value()) << 16) >> 16; out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%d", imm); } // Print 16-bit hexa immediate value. void Decoder::PrintXImm16(Instruction* instr) { int32_t imm = instr->Imm16Value(); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "0x%x", imm); } // Print 26-bit immediate value. void Decoder::PrintXImm26(Instruction* instr) { uint32_t imm = instr->Imm26Value() << kImmFieldShift; out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "0x%x", imm); } // Print 26-bit immediate value. void Decoder::PrintCode(Instruction* instr) { if (instr->OpcodeFieldRaw() != SPECIAL) return; // Not a break or trap instruction. switch (instr->FunctionFieldRaw()) { case BREAK: { int32_t code = instr->Bits(25, 6); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "0x%05x (%d)", code, code); break; } case TGE: case TGEU: case TLT: case TLTU: case TEQ: case TNE: { int32_t code = instr->Bits(15, 6); out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "0x%03x", code); break; } default: // Not a break or trap instruction. break; }; } // Printing of instruction name. void Decoder::PrintInstructionName(Instruction* instr) { } // Handle all register based formatting in this function to reduce the // complexity of FormatOption. int Decoder::FormatRegister(Instruction* instr, const char* format) { ASSERT(format[0] == 'r'); if (format[1] == 's') { // 'rs: Rs register. int reg = instr->RsValue(); PrintRegister(reg); return 2; } else if (format[1] == 't') { // 'rt: rt register. int reg = instr->RtValue(); PrintRegister(reg); return 2; } else if (format[1] == 'd') { // 'rd: rd register. int reg = instr->RdValue(); PrintRegister(reg); return 2; } UNREACHABLE(); return -1; } // Handle all FPUregister based formatting in this function to reduce the // complexity of FormatOption. int Decoder::FormatFPURegister(Instruction* instr, const char* format) { ASSERT(format[0] == 'f'); if (format[1] == 's') { // 'fs: fs register. int reg = instr->FsValue(); PrintFPURegister(reg); return 2; } else if (format[1] == 't') { // 'ft: ft register. int reg = instr->FtValue(); PrintFPURegister(reg); return 2; } else if (format[1] == 'd') { // 'fd: fd register. int reg = instr->FdValue(); PrintFPURegister(reg); return 2; } else if (format[1] == 'r') { // 'fr: fr register. int reg = instr->FrValue(); PrintFPURegister(reg); return 2; } UNREACHABLE(); return -1; } // FormatOption takes a formatting string and interprets it based on // the current instructions. The format string points to the first // character of the option string (the option escape has already been // consumed by the caller.) FormatOption returns the number of // characters that were consumed from the formatting string. int Decoder::FormatOption(Instruction* instr, const char* format) { switch (format[0]) { case 'c': { // 'code for break or trap instructions. ASSERT(STRING_STARTS_WITH(format, "code")); PrintCode(instr); return 4; } case 'i': { // 'imm16u or 'imm26. if (format[3] == '1') { ASSERT(STRING_STARTS_WITH(format, "imm16")); if (format[5] == 's') { ASSERT(STRING_STARTS_WITH(format, "imm16s")); PrintSImm16(instr); } else if (format[5] == 'u') { ASSERT(STRING_STARTS_WITH(format, "imm16u")); PrintSImm16(instr); } else { ASSERT(STRING_STARTS_WITH(format, "imm16x")); PrintXImm16(instr); } return 6; } else { ASSERT(STRING_STARTS_WITH(format, "imm26x")); PrintXImm26(instr); return 6; } } case 'r': { // 'r: registers. return FormatRegister(instr, format); } case 'f': { // 'f: FPUregisters. return FormatFPURegister(instr, format); } case 's': { // 'sa. switch (format[1]) { case 'a': { ASSERT(STRING_STARTS_WITH(format, "sa")); PrintSa(instr); return 2; } case 'd': { ASSERT(STRING_STARTS_WITH(format, "sd")); PrintSd(instr); return 2; } case 's': { if (format[2] == '1') { ASSERT(STRING_STARTS_WITH(format, "ss1")); /* ext size */ PrintSs1(instr); return 3; } else { ASSERT(STRING_STARTS_WITH(format, "ss2")); /* ins size */ PrintSs2(instr); return 3; } } } } case 'b': { // 'bc - Special for bc1 cc field. ASSERT(STRING_STARTS_WITH(format, "bc")); PrintBc(instr); return 2; } case 'C': { // 'Cc - Special for c.xx.d cc field. ASSERT(STRING_STARTS_WITH(format, "Cc")); PrintCc(instr); return 2; } }; UNREACHABLE(); return -1; } // Format takes a formatting string for a whole instruction and prints it into // the output buffer. All escaped options are handed to FormatOption to be // parsed further. void Decoder::Format(Instruction* instr, const char* format) { char cur = *format++; while ((cur != 0) && (out_buffer_pos_ < (out_buffer_.length() - 1))) { if (cur == '\'') { // Single quote is used as the formatting escape. format += FormatOption(instr, format); } else { out_buffer_[out_buffer_pos_++] = cur; } cur = *format++; } out_buffer_[out_buffer_pos_] = '\0'; } // For currently unimplemented decodings the disassembler calls Unknown(instr) // which will just print "unknown" of the instruction bits. void Decoder::Unknown(Instruction* instr) { Format(instr, "unknown"); } void Decoder::DecodeTypeRegister(Instruction* instr) { switch (instr->OpcodeFieldRaw()) { case COP1: // Coprocessor instructions. switch (instr->RsFieldRaw()) { case BC1: // bc1 handled in DecodeTypeImmediate. UNREACHABLE(); break; case MFC1: Format(instr, "mfc1 'rt, 'fs"); break; case MFHC1: Format(instr, "mfhc1 'rt, 'fs"); break; case MTC1: Format(instr, "mtc1 'rt, 'fs"); break; // These are called "fs" too, although they are not FPU registers. case CTC1: Format(instr, "ctc1 'rt, 'fs"); break; case CFC1: Format(instr, "cfc1 'rt, 'fs"); break; case MTHC1: Format(instr, "mthc1 'rt, 'fs"); break; case D: switch (instr->FunctionFieldRaw()) { case ADD_D: Format(instr, "add.d 'fd, 'fs, 'ft"); break; case SUB_D: Format(instr, "sub.d 'fd, 'fs, 'ft"); break; case MUL_D: Format(instr, "mul.d 'fd, 'fs, 'ft"); break; case DIV_D: Format(instr, "div.d 'fd, 'fs, 'ft"); break; case ABS_D: Format(instr, "abs.d 'fd, 'fs"); break; case MOV_D: Format(instr, "mov.d 'fd, 'fs"); break; case NEG_D: Format(instr, "neg.d 'fd, 'fs"); break; case SQRT_D: Format(instr, "sqrt.d 'fd, 'fs"); break; case CVT_W_D: Format(instr, "cvt.w.d 'fd, 'fs"); break; case CVT_L_D: { if (kArchVariant == kMips32r2) { Format(instr, "cvt.l.d 'fd, 'fs"); } else { Unknown(instr); } break; } case TRUNC_W_D: Format(instr, "trunc.w.d 'fd, 'fs"); break; case TRUNC_L_D: { if (kArchVariant == kMips32r2) { Format(instr, "trunc.l.d 'fd, 'fs"); } else { Unknown(instr); } break; } case ROUND_W_D: Format(instr, "round.w.d 'fd, 'fs"); break; case FLOOR_W_D: Format(instr, "floor.w.d 'fd, 'fs"); break; case CEIL_W_D: Format(instr, "ceil.w.d 'fd, 'fs"); break; case CVT_S_D: Format(instr, "cvt.s.d 'fd, 'fs"); break; case C_F_D: Format(instr, "c.f.d 'fs, 'ft, 'Cc"); break; case C_UN_D: Format(instr, "c.un.d 'fs, 'ft, 'Cc"); break; case C_EQ_D: Format(instr, "c.eq.d 'fs, 'ft, 'Cc"); break; case C_UEQ_D: Format(instr, "c.ueq.d 'fs, 'ft, 'Cc"); break; case C_OLT_D: Format(instr, "c.olt.d 'fs, 'ft, 'Cc"); break; case C_ULT_D: Format(instr, "c.ult.d 'fs, 'ft, 'Cc"); break; case C_OLE_D: Format(instr, "c.ole.d 'fs, 'ft, 'Cc"); break; case C_ULE_D: Format(instr, "c.ule.d 'fs, 'ft, 'Cc"); break; default: Format(instr, "unknown.cop1.d"); break; } break; case S: UNIMPLEMENTED_MIPS(); break; case W: switch (instr->FunctionFieldRaw()) { case CVT_S_W: // Convert word to float (single). Format(instr, "cvt.s.w 'fd, 'fs"); break; case CVT_D_W: // Convert word to double. Format(instr, "cvt.d.w 'fd, 'fs"); break; default: UNREACHABLE(); } break; case L: switch (instr->FunctionFieldRaw()) { case CVT_D_L: { if (kArchVariant == kMips32r2) { Format(instr, "cvt.d.l 'fd, 'fs"); } else { Unknown(instr); } break; } case CVT_S_L: { if (kArchVariant == kMips32r2) { Format(instr, "cvt.s.l 'fd, 'fs"); } else { Unknown(instr); } break; } default: UNREACHABLE(); } break; case PS: UNIMPLEMENTED_MIPS(); break; default: UNREACHABLE(); } break; case COP1X: switch (instr->FunctionFieldRaw()) { case MADD_D: Format(instr, "madd.d 'fd, 'fr, 'fs, 'ft"); break; default: UNREACHABLE(); }; break; case SPECIAL: switch (instr->FunctionFieldRaw()) { case JR: Format(instr, "jr 'rs"); break; case JALR: Format(instr, "jalr 'rs"); break; case SLL: if ( 0x0 == static_cast<int>(instr->InstructionBits())) Format(instr, "nop"); else Format(instr, "sll 'rd, 'rt, 'sa"); break; case SRL: if (instr->RsValue() == 0) { Format(instr, "srl 'rd, 'rt, 'sa"); } else { if (kArchVariant == kMips32r2) { Format(instr, "rotr 'rd, 'rt, 'sa"); } else { Unknown(instr); } } break; case SRA: Format(instr, "sra 'rd, 'rt, 'sa"); break; case SLLV: Format(instr, "sllv 'rd, 'rt, 'rs"); break; case SRLV: if (instr->SaValue() == 0) { Format(instr, "srlv 'rd, 'rt, 'rs"); } else { if (kArchVariant == kMips32r2) { Format(instr, "rotrv 'rd, 'rt, 'rs"); } else { Unknown(instr); } } break; case SRAV: Format(instr, "srav 'rd, 'rt, 'rs"); break; case MFHI: Format(instr, "mfhi 'rd"); break; case MFLO: Format(instr, "mflo 'rd"); break; case MULT: Format(instr, "mult 'rs, 'rt"); break; case MULTU: Format(instr, "multu 'rs, 'rt"); break; case DIV: Format(instr, "div 'rs, 'rt"); break; case DIVU: Format(instr, "divu 'rs, 'rt"); break; case ADD: Format(instr, "add 'rd, 'rs, 'rt"); break; case ADDU: Format(instr, "addu 'rd, 'rs, 'rt"); break; case SUB: Format(instr, "sub 'rd, 'rs, 'rt"); break; case SUBU: Format(instr, "subu 'rd, 'rs, 'rt"); break; case AND: Format(instr, "and 'rd, 'rs, 'rt"); break; case OR: if (0 == instr->RsValue()) { Format(instr, "mov 'rd, 'rt"); } else if (0 == instr->RtValue()) { Format(instr, "mov 'rd, 'rs"); } else { Format(instr, "or 'rd, 'rs, 'rt"); } break; case XOR: Format(instr, "xor 'rd, 'rs, 'rt"); break; case NOR: Format(instr, "nor 'rd, 'rs, 'rt"); break; case SLT: Format(instr, "slt 'rd, 'rs, 'rt"); break; case SLTU: Format(instr, "sltu 'rd, 'rs, 'rt"); break; case BREAK: Format(instr, "break, code: 'code"); break; case TGE: Format(instr, "tge 'rs, 'rt, code: 'code"); break; case TGEU: Format(instr, "tgeu 'rs, 'rt, code: 'code"); break; case TLT: Format(instr, "tlt 'rs, 'rt, code: 'code"); break; case TLTU: Format(instr, "tltu 'rs, 'rt, code: 'code"); break; case TEQ: Format(instr, "teq 'rs, 'rt, code: 'code"); break; case TNE: Format(instr, "tne 'rs, 'rt, code: 'code"); break; case MOVZ: Format(instr, "movz 'rd, 'rs, 'rt"); break; case MOVN: Format(instr, "movn 'rd, 'rs, 'rt"); break; case MOVCI: if (instr->Bit(16)) { Format(instr, "movt 'rd, 'rs, 'bc"); } else { Format(instr, "movf 'rd, 'rs, 'bc"); } break; default: UNREACHABLE(); } break; case SPECIAL2: switch (instr->FunctionFieldRaw()) { case MUL: Format(instr, "mul 'rd, 'rs, 'rt"); break; case CLZ: Format(instr, "clz 'rd, 'rs"); break; default: UNREACHABLE(); } break; case SPECIAL3: switch (instr->FunctionFieldRaw()) { case INS: { if (kArchVariant == kMips32r2) { Format(instr, "ins 'rt, 'rs, 'sa, 'ss2"); } else { Unknown(instr); } break; } case EXT: { if (kArchVariant == kMips32r2) { Format(instr, "ext 'rt, 'rs, 'sa, 'ss1"); } else { Unknown(instr); } break; } default: UNREACHABLE(); } break; default: UNREACHABLE(); } } void Decoder::DecodeTypeImmediate(Instruction* instr) { switch (instr->OpcodeFieldRaw()) { // ------------- REGIMM class. case COP1: switch (instr->RsFieldRaw()) { case BC1: if (instr->FBtrueValue()) { Format(instr, "bc1t 'bc, 'imm16u"); } else { Format(instr, "bc1f 'bc, 'imm16u"); } break; default: UNREACHABLE(); }; break; // Case COP1. case REGIMM: switch (instr->RtFieldRaw()) { case BLTZ: Format(instr, "bltz 'rs, 'imm16u"); break; case BLTZAL: Format(instr, "bltzal 'rs, 'imm16u"); break; case BGEZ: Format(instr, "bgez 'rs, 'imm16u"); break; case BGEZAL: Format(instr, "bgezal 'rs, 'imm16u"); break; default: UNREACHABLE(); } break; // Case REGIMM. // ------------- Branch instructions. case BEQ: Format(instr, "beq 'rs, 'rt, 'imm16u"); break; case BNE: Format(instr, "bne 'rs, 'rt, 'imm16u"); break; case BLEZ: Format(instr, "blez 'rs, 'imm16u"); break; case BGTZ: Format(instr, "bgtz 'rs, 'imm16u"); break; // ------------- Arithmetic instructions. case ADDI: Format(instr, "addi 'rt, 'rs, 'imm16s"); break; case ADDIU: Format(instr, "addiu 'rt, 'rs, 'imm16s"); break; case SLTI: Format(instr, "slti 'rt, 'rs, 'imm16s"); break; case SLTIU: Format(instr, "sltiu 'rt, 'rs, 'imm16u"); break; case ANDI: Format(instr, "andi 'rt, 'rs, 'imm16x"); break; case ORI: Format(instr, "ori 'rt, 'rs, 'imm16x"); break; case XORI: Format(instr, "xori 'rt, 'rs, 'imm16x"); break; case LUI: Format(instr, "lui 'rt, 'imm16x"); break; // ------------- Memory instructions. case LB: Format(instr, "lb 'rt, 'imm16s('rs)"); break; case LH: Format(instr, "lh 'rt, 'imm16s('rs)"); break; case LWL: Format(instr, "lwl 'rt, 'imm16s('rs)"); break; case LW: Format(instr, "lw 'rt, 'imm16s('rs)"); break; case LBU: Format(instr, "lbu 'rt, 'imm16s('rs)"); break; case LHU: Format(instr, "lhu 'rt, 'imm16s('rs)"); break; case LWR: Format(instr, "lwr 'rt, 'imm16s('rs)"); break; case SB: Format(instr, "sb 'rt, 'imm16s('rs)"); break; case SH: Format(instr, "sh 'rt, 'imm16s('rs)"); break; case SWL: Format(instr, "swl 'rt, 'imm16s('rs)"); break; case SW: Format(instr, "sw 'rt, 'imm16s('rs)"); break; case SWR: Format(instr, "swr 'rt, 'imm16s('rs)"); break; case LWC1: Format(instr, "lwc1 'ft, 'imm16s('rs)"); break; case LDC1: Format(instr, "ldc1 'ft, 'imm16s('rs)"); break; case SWC1: Format(instr, "swc1 'ft, 'imm16s('rs)"); break; case SDC1: Format(instr, "sdc1 'ft, 'imm16s('rs)"); break; default: UNREACHABLE(); break; }; } void Decoder::DecodeTypeJump(Instruction* instr) { switch (instr->OpcodeFieldRaw()) { case J: Format(instr, "j 'imm26x"); break; case JAL: Format(instr, "jal 'imm26x"); break; default: UNREACHABLE(); } } // Disassemble the instruction at *instr_ptr into the output buffer. int Decoder::InstructionDecode(byte* instr_ptr) { Instruction* instr = Instruction::At(instr_ptr); // Print raw instruction bytes. out_buffer_pos_ += OS::SNPrintF(out_buffer_ + out_buffer_pos_, "%08x ", instr->InstructionBits()); switch (instr->InstructionType()) { case Instruction::kRegisterType: { DecodeTypeRegister(instr); break; } case Instruction::kImmediateType: { DecodeTypeImmediate(instr); break; } case Instruction::kJumpType: { DecodeTypeJump(instr); break; } default: { Format(instr, "UNSUPPORTED"); UNSUPPORTED_MIPS(); } } return Instruction::kInstrSize; } } } // namespace v8::internal //------------------------------------------------------------------------------ namespace disasm { const char* NameConverter::NameOfAddress(byte* addr) const { v8::internal::OS::SNPrintF(tmp_buffer_, "%p", addr); return tmp_buffer_.start(); } const char* NameConverter::NameOfConstant(byte* addr) const { return NameOfAddress(addr); } const char* NameConverter::NameOfCPURegister(int reg) const { return v8::internal::Registers::Name(reg); } const char* NameConverter::NameOfXMMRegister(int reg) const { return v8::internal::FPURegisters::Name(reg); } const char* NameConverter::NameOfByteCPURegister(int reg) const { UNREACHABLE(); // MIPS does not have the concept of a byte register. return "nobytereg"; } const char* NameConverter::NameInCode(byte* addr) const { // The default name converter is called for unknown code. So we will not try // to access any memory. return ""; } //------------------------------------------------------------------------------ Disassembler::Disassembler(const NameConverter& converter) : converter_(converter) {} Disassembler::~Disassembler() {} int Disassembler::InstructionDecode(v8::internal::Vector<char> buffer, byte* instruction) { v8::internal::Decoder d(converter_, buffer); return d.InstructionDecode(instruction); } // The MIPS assembler does not currently use constant pools. int Disassembler::ConstantPoolSizeAt(byte* instruction) { return -1; } void Disassembler::Disassemble(FILE* f, byte* begin, byte* end) { NameConverter converter; Disassembler d(converter); for (byte* pc = begin; pc < end;) { v8::internal::EmbeddedVector<char, 128> buffer; buffer[0] = '\0'; byte* prev_pc = pc; pc += d.InstructionDecode(buffer, pc); v8::internal::PrintF(f, "%p %08x %s\n", prev_pc, *reinterpret_cast<int32_t*>(prev_pc), buffer.start()); } } #undef UNSUPPORTED } // namespace disasm #endif // V8_TARGET_ARCH_MIPS
x684867/nemesis
src/node/deps/v8/src/mips/disasm-mips.cc
C++
mit
30,634
#!/usr/bin/env python3 # # linearize-data.py: Construct a linear, no-fork version of the chain. # # Copyright (c) 2013-2019 The Starwels developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from __future__ import print_function, division import struct import re import os import os.path import sys import hashlib import datetime import time from collections import namedtuple from binascii import hexlify, unhexlify settings = {} ##### Switch endian-ness ##### def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode() def uint32(x): return x & 0xffffffff def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return b''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return b''.join(out_words) def calc_hdr_hash(blk_hdr): hash1 = hashlib.sha256() hash1.update(blk_hdr) hash1_o = hash1.digest() hash2 = hashlib.sha256() hash2.update(hash1_o) hash2_o = hash2.digest() return hash2_o def calc_hash_str(blk_hdr): hash = calc_hdr_hash(blk_hdr) hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hexlify(hash).decode('utf-8') return hash_str def get_blk_dt(blk_hdr): members = struct.unpack("<I", blk_hdr[68:68+4]) nTime = members[0] dt = datetime.datetime.fromtimestamp(nTime) dt_ym = datetime.datetime(dt.year, dt.month, 1) return (dt_ym, nTime) # When getting the list of block hashes, undo any byte reversals. def get_block_hashes(settings): blkindex = [] f = open(settings['hashlist'], "r") for line in f: line = line.rstrip() if settings['rev_hash_bytes'] == 'true': line = hex_switchEndian(line) blkindex.append(line) print("Read " + str(len(blkindex)) + " hashes") return blkindex # The block map shouldn't give or receive byte-reversed hashes. def mkblockmap(blkindex): blkmap = {} for height,hash in enumerate(blkindex): blkmap[hash] = height return blkmap # Block header and extent on disk BlockExtent = namedtuple('BlockExtent', ['fn', 'offset', 'inhdr', 'blkhdr', 'size']) class BlockDataCopier: def __init__(self, settings, blkindex, blkmap): self.settings = settings self.blkindex = blkindex self.blkmap = blkmap self.inFn = 0 self.inF = None self.outFn = 0 self.outsz = 0 self.outF = None self.outFname = None self.blkCountIn = 0 self.blkCountOut = 0 self.lastDate = datetime.datetime(2000, 1, 1) self.highTS = 1408893517 - 315360000 self.timestampSplit = False self.fileOutput = True self.setFileTime = False self.maxOutSz = settings['max_out_sz'] if 'output' in settings: self.fileOutput = False if settings['file_timestamp'] != 0: self.setFileTime = True if settings['split_timestamp'] != 0: self.timestampSplit = True # Extents and cache for out-of-order blocks self.blockExtents = {} self.outOfOrderData = {} self.outOfOrderSize = 0 # running total size for items in outOfOrderData def writeBlock(self, inhdr, blk_hdr, rawblock): blockSizeOnDisk = len(inhdr) + len(blk_hdr) + len(rawblock) if not self.fileOutput and ((self.outsz + blockSizeOnDisk) > self.maxOutSz): self.outF.close() if self.setFileTime: os.utime(self.outFname, (int(time.time()), self.highTS)) self.outF = None self.outFname = None self.outFn = self.outFn + 1 self.outsz = 0 (blkDate, blkTS) = get_blk_dt(blk_hdr) if self.timestampSplit and (blkDate > self.lastDate): print("New month " + blkDate.strftime("%Y-%m") + " @ " + self.hash_str) self.lastDate = blkDate if self.outF: self.outF.close() if self.setFileTime: os.utime(self.outFname, (int(time.time()), self.highTS)) self.outF = None self.outFname = None self.outFn = self.outFn + 1 self.outsz = 0 if not self.outF: if self.fileOutput: self.outFname = self.settings['output_file'] else: self.outFname = os.path.join(self.settings['output'], "blk%05d.dat" % self.outFn) print("Output file " + self.outFname) self.outF = open(self.outFname, "wb") self.outF.write(inhdr) self.outF.write(blk_hdr) self.outF.write(rawblock) self.outsz = self.outsz + len(inhdr) + len(blk_hdr) + len(rawblock) self.blkCountOut = self.blkCountOut + 1 if blkTS > self.highTS: self.highTS = blkTS if (self.blkCountOut % 1000) == 0: print('%i blocks scanned, %i blocks written (of %i, %.1f%% complete)' % (self.blkCountIn, self.blkCountOut, len(self.blkindex), 100.0 * self.blkCountOut / len(self.blkindex))) def inFileName(self, fn): return os.path.join(self.settings['input'], "blk%05d.dat" % fn) def fetchBlock(self, extent): '''Fetch block contents from disk given extents''' with open(self.inFileName(extent.fn), "rb") as f: f.seek(extent.offset) return f.read(extent.size) def copyOneBlock(self): '''Find the next block to be written in the input, and copy it to the output.''' extent = self.blockExtents.pop(self.blkCountOut) if self.blkCountOut in self.outOfOrderData: # If the data is cached, use it from memory and remove from the cache rawblock = self.outOfOrderData.pop(self.blkCountOut) self.outOfOrderSize -= len(rawblock) else: # Otherwise look up data on disk rawblock = self.fetchBlock(extent) self.writeBlock(extent.inhdr, extent.blkhdr, rawblock) def run(self): while self.blkCountOut < len(self.blkindex): if not self.inF: fname = self.inFileName(self.inFn) print("Input file " + fname) try: self.inF = open(fname, "rb") except IOError: print("Premature end of block data") return inhdr = self.inF.read(8) if (not inhdr or (inhdr[0] == "\0")): self.inF.close() self.inF = None self.inFn = self.inFn + 1 continue inMagic = inhdr[:4] if (inMagic != self.settings['netmagic']): print("Invalid magic: " + hexlify(inMagic).decode('utf-8')) return inLenLE = inhdr[4:] su = struct.unpack("<I", inLenLE) inLen = su[0] - 80 # length without header blk_hdr = self.inF.read(80) inExtent = BlockExtent(self.inFn, self.inF.tell(), inhdr, blk_hdr, inLen) self.hash_str = calc_hash_str(blk_hdr) if not self.hash_str in blkmap: # Because blocks can be written to files out-of-order as of 0.10, the script # may encounter blocks it doesn't know about. Treat as debug output. if settings['debug_output'] == 'true': print("Skipping unknown block " + self.hash_str) self.inF.seek(inLen, os.SEEK_CUR) continue blkHeight = self.blkmap[self.hash_str] self.blkCountIn += 1 if self.blkCountOut == blkHeight: # If in-order block, just copy rawblock = self.inF.read(inLen) self.writeBlock(inhdr, blk_hdr, rawblock) # See if we can catch up to prior out-of-order blocks while self.blkCountOut in self.blockExtents: self.copyOneBlock() else: # If out-of-order, skip over block data for now self.blockExtents[blkHeight] = inExtent if self.outOfOrderSize < self.settings['out_of_order_cache_sz']: # If there is space in the cache, read the data # Reading the data in file sequence instead of seeking and fetching it later is preferred, # but we don't want to fill up memory self.outOfOrderData[blkHeight] = self.inF.read(inLen) self.outOfOrderSize += inLen else: # If no space in cache, seek forward self.inF.seek(inLen, os.SEEK_CUR) print("Done (%i blocks written)" % (self.blkCountOut)) if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: linearize-data.py CONFIG-FILE") sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() # Force hash byte format setting to be lowercase to make comparisons easier. # Also place upfront in case any settings need to know about it. if 'rev_hash_bytes' not in settings: settings['rev_hash_bytes'] = 'false' settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower() if 'netmagic' not in settings: settings['netmagic'] = 'f9beb4d9' if 'genesis' not in settings: settings['genesis'] = '000000003d69a915e9da53348c5c272978bb743442e3a6341c11061c125811a2' if 'input' not in settings: settings['input'] = 'input' if 'hashlist' not in settings: settings['hashlist'] = 'hashlist.txt' if 'file_timestamp' not in settings: settings['file_timestamp'] = 0 if 'split_timestamp' not in settings: settings['split_timestamp'] = 0 if 'max_out_sz' not in settings: settings['max_out_sz'] = 1000 * 1000 * 1000 if 'out_of_order_cache_sz' not in settings: settings['out_of_order_cache_sz'] = 100 * 1000 * 1000 if 'debug_output' not in settings: settings['debug_output'] = 'false' settings['max_out_sz'] = int(settings['max_out_sz']) settings['split_timestamp'] = int(settings['split_timestamp']) settings['file_timestamp'] = int(settings['file_timestamp']) settings['netmagic'] = unhexlify(settings['netmagic'].encode('utf-8')) settings['out_of_order_cache_sz'] = int(settings['out_of_order_cache_sz']) settings['debug_output'] = settings['debug_output'].lower() if 'output_file' not in settings and 'output' not in settings: print("Missing output file / directory") sys.exit(1) blkindex = get_block_hashes(settings) blkmap = mkblockmap(blkindex) # Block hash map won't be byte-reversed. Neither should the genesis hash. if not settings['genesis'] in blkmap: print("Genesis block not found in hashlist") else: BlockDataCopier(settings, blkindex, blkmap).run()
starwels/starwels
contrib/linearize/linearize-data.py
Python
mit
10,077
package gappsockets.server.jwt; import java.io.UnsupportedEncodingException; import java.util.List; import gappsockets.server.json.JsonObject; public final class Header { public static final class ParameterNames { public static final String ALG = "alg"; public static final String CRIT = "crit"; public static final String CTY = "cty"; public static final String JKU = "jku"; public static final String JWK = "jwk"; public static final String KID = "kid"; public static final String TYP = "typ"; public static final String X5U = "x5u"; public static final String X5C = "x5c"; public static final String X5T = "x5t"; public static final String X5T_S256 = "x5t#S256"; private ParameterNames() { } } public static Header newInstance(final byte[] bytes) { String s = null; try { s = new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } return newInstance(JsonObject.newInstance(s)); } public static Header newInstance(final JsonObject jsonObject) { if (jsonObject.containsName(ParameterNames.ALG)) { List<Object> values = jsonObject.get(ParameterNames.ALG); for (Object value : values) { if (!(value instanceof String)) { throw new IllegalArgumentException(String.format( "value in parameter \"%s\" in Header is not a string", Header.ParameterNames.ALG)); } } } return new Header(jsonObject); } public static Header newInstance(final String string) { return newInstance(Base64.urlDecode(string)); } private final JsonObject jsonObject; Header(final JsonObject jsonObj) { this.jsonObject = jsonObj; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Header)) { return false; } Header other = (Header) obj; if (this.jsonObject == null) { if (other.jsonObject != null) { return false; } } else if (!this.jsonObject.equals(other.jsonObject)) { return false; } return true; } public String getAlg() { String alg = null; if (this.jsonObject.containsName(ParameterNames.ALG)) { alg = (String) this.jsonObject.getLast(ParameterNames.ALG); } return alg; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.jsonObject == null) ? 0 : this.jsonObject.hashCode()); return result; } public byte[] toByteArray() { byte[] bytes = null; try { bytes = this.jsonObject.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } return bytes; } public JsonObject toJsonObject() { return this.jsonObject; } @Override public String toString() { return Base64.urlEncode(this.toByteArray()); } }
jh3nd3rs0n/gappsockets.remoteserver
src/main/java/gappsockets/server/jwt/Header.java
Java
mit
2,863
package cn.edu.gdut.zaoying.Option.legend; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface BottomString { String value() default ""; }
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/legend/BottomString.java
Java
mit
333
<?php if (!class_exists('PHPUnit_Framework_TestCase')) { class PHPUnit_Framework_TestCase extends \PHPUnit\Framework\TestCase {} } require __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
keradus/php-coveralls
tests/bootstrap.php
PHP
mit
255
using System; namespace StackExchange.Opserver.Models { [Flags] public enum Roles { None = 0, Anonymous = 1 << 1, Authenticated = 1 << 2, Exceptions = 1 << 3, ExceptionsAdmin = 1 << 4, HAProxy = 1 << 5, HAProxyAdmin = 1 << 6, SQL = 1 << 7, SQLAdmin = 1 << 8, Elastic = 1 << 9, ElasticAdmin = 1 << 10, Redis = 1 << 11, RedisAdmin = 1 << 12, Dashboard = 1 << 13, DashboardAdmin = 1 << 14, CloudFlare = 1 << 15, CloudFlareAdmin = 1 << 16, InternalRequest = 1 << 19, GlobalAdmin = 1 << 20 } }
navone/Opserver
Opserver/Models/Roles.cs
C#
mit
669
using System; namespace SharpFileSystem { public class FileSystemEntity: IEquatable<FileSystemEntity> { public IFileSystem FileSystem { get; private set; } public FileSystemPath Path { get; private set; } public string Name { get { return Path.EntityName; } } public FileSystemEntity(IFileSystem fileSystem, FileSystemPath path) { FileSystem = fileSystem; Path = path; } public override bool Equals(object obj) { var other = obj as FileSystemEntity; return (other != null) && ((IEquatable<FileSystemEntity>) this).Equals(other); } public override int GetHashCode() { return FileSystem.GetHashCode() ^ Path.GetHashCode(); } bool IEquatable<FileSystemEntity>.Equals(FileSystemEntity other) { return FileSystem.Equals(other.FileSystem) && Path.Equals(other.Path); } public static FileSystemEntity Create(IFileSystem fileSystem, FileSystemPath path) { if (path.IsFile) return new File(fileSystem, path); else return new Directory(fileSystem, path); } } }
bobvanderlinden/sharpfilesystem
SharpFileSystem/FileSystemEntity.cs
C#
mit
1,241
require 'test_helper' class OrderSpecificationTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
lczgywzyy/chihao.de
test/models/order_specification_test.rb
Ruby
mit
132
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; use Doctrine\Common\Annotations\AnnotationException; use Doctrine\Common\Annotations\CachedReader; use Doctrine\Common\Annotations\Reader; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\DoctrineProvider; /** * Warms up annotation caches for classes found in composer's autoload class map * and declared in DI bundle extensions using the addAnnotatedClassesToCache method. * * @author Titouan Galopin <galopintitouan@gmail.com> */ class AnnotationsCacheWarmer extends AbstractPhpFileCacheWarmer { private $annotationReader; private $excludeRegexp; private $debug; /** * @param string $phpArrayFile The PHP file where annotations are cached */ public function __construct(Reader $annotationReader, string $phpArrayFile, string $excludeRegexp = null, bool $debug = false) { parent::__construct($phpArrayFile); $this->annotationReader = $annotationReader; $this->excludeRegexp = $excludeRegexp; $this->debug = $debug; } /** * {@inheritdoc} */ protected function doWarmUp($cacheDir, ArrayAdapter $arrayAdapter) { $annotatedClassPatterns = $cacheDir.'/annotations.map'; if (!is_file($annotatedClassPatterns)) { return true; } $annotatedClasses = include $annotatedClassPatterns; $reader = new CachedReader($this->annotationReader, new DoctrineProvider($arrayAdapter), $this->debug); foreach ($annotatedClasses as $class) { if (null !== $this->excludeRegexp && preg_match($this->excludeRegexp, $class)) { continue; } try { $this->readAllComponents($reader, $class); } catch (\ReflectionException $e) { // ignore failing reflection } catch (AnnotationException $e) { /* * Ignore any AnnotationException to not break the cache warming process if an Annotation is badly * configured or could not be found / read / etc. * * In particular cases, an Annotation in your code can be used and defined only for a specific * environment but is always added to the annotations.map file by some Symfony default behaviors, * and you always end up with a not found Annotation. */ } } return true; } private function readAllComponents(Reader $reader, $class) { $reflectionClass = new \ReflectionClass($class); $reader->getClassAnnotations($reflectionClass); foreach ($reflectionClass->getMethods() as $reflectionMethod) { $reader->getMethodAnnotations($reflectionMethod); } foreach ($reflectionClass->getProperties() as $reflectionProperty) { $reader->getPropertyAnnotations($reflectionProperty); } } }
vincentaubert/symfony
src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AnnotationsCacheWarmer.php
PHP
mit
3,230
// The MIT License (MIT) // // Copyright (c) 2015 Microsoft // // 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. namespace Microsoft.Diagnostics.Tracing.Logging { using System; using System.Diagnostics; /// <summary> /// Assert methods which utilize our internal logging /// </summary> /// <remarks> /// The single method provided (Assert) is intended to be used as a substitute for Trace.Assert or Debug.Assert. /// It provides a wrapper around these and also ensures that assertions are always "process killing" no matter /// what happens. It also ensures that "process killer" assertions get emitted to the console and to the ETW /// stream. /// </remarks> public static class LogAssert { /// <summary> /// Evaluate the given expression and raise a process-murdering error if it is false /// </summary> /// <param name="expr">Anything that evaluates to a boolean. Get creative!</param> public static void Assert(bool expr) { Assert(expr, string.Empty); } /// <summary> /// Evaluate the given expression and raise a process-murdering error if it is false /// </summary> /// <param name="expr">Anything that evaluates to a boolean. Get creative!</param> /// <param name="message">A message to log should expr be false. Express yourself!</param> public static void Assert(bool expr, string message) { if (expr == false) { InternalLogger.Write.AssertionFailed(message, Environment.StackTrace); #if DEBUG Debug.Assert(false, message); #else LogManager.Shutdown(); Environment.Exit(-42); #endif } } /// <summary> /// Evaluate the given expression and raise a process-murdering error if it is false /// </summary> /// <param name="expr">Anything that evaluates to a boolean. Get creative!</param> /// <param name="format">The format of the scintillating message which will crash your process</param> /// <param name="args">One or more captivating arguments for your format</param> public static void Assert(bool expr, string format, params object[] args) { if (expr == false) { try { Assert(false, string.Format(format, args)); } catch (FormatException) { Assert(false, string.Format( "somebody goofed up their string format but really wanted to assert! here 'tis: {0}", format)); } } } } }
doubleyewdee/Microsoft.Diagnostics.Tracing.Logging
src/Assert.cs
C#
mit
3,860
require 'uri' require 'resolv' require 'pathname' module SPF module Common class Validate @@KEYS = [:priority, :allow_services, :service_policies, :dissemination_policy] @@DISTANCE_TYPES = [:linear, :exponential] @@CHANNELS = [:WiFi, :cellular] # @@SERVICES_FOLDER = File.join('src', 'ruby', 'spf', 'gateway', 'service-strategies') # @@PROCESS_FOLDER = File.join('src', 'ruby', 'spf', 'gateway', 'processing-strategies') @@SERVICES_FOLDER = File.expand_path(File.join(File.dirname(__FILE__), '..', 'gateway', 'service-strategies')) @@PROCESS_FOLDER = File.expand_path(File.join(File.dirname(__FILE__), '..', 'gateway', 'processing-strategies')) @@APPLICATION_CONFIG_DIR = File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'etc', 'controller', 'app_configurations')) def self.ip?(ip) return false if ip.nil? (ip.downcase.eql? "localhost") or (ip =~ Regexp.union([Resolv::IPv4::Regex, Resolv::IPv6::Regex]) ? true : false) end def self.port?(port) return false if port.nil? (port.is_a? Numeric and (1..65535).include? port) ? true : false end def self.latitude?(lat) return false if lat.nil? regex = /^-?([1-8]?\d(?:\.\d{1,})?|90(?:\.0{1,6})?)$/ regex =~ lat ? true : false end def self.longitude?(lon) return false if lon.nil? regex = /^-?((?:1[0-7]|[1-9])?\d(?:\.\d{1,})?|180(?:\.0{1,})?)$/ regex =~ lon ? true : false end def self.url?(url) return false if url.nil? url =~ /\A#{URI::regexp(['http', 'https'])}\z/ ? true : false end def self.pig?(pig) return false if pig.nil? Validate.ip? pig[:ip] and Validate.port? pig[:port] and Validate.latitude? pig[:lat] and Validate.longitude? pig[:lon] end def self.gps_coordinates?(gps) Validate.latitude? gps[:lat] and Validate.longitude? gps[:lon] end def self.camera_config?(camera) return false unless camera[:name].length > 0 return false unless camera[:cam_id].length > 0 return false unless camera[:url].length > 0 return false unless camera[:duration] >= 0 if camera.has_key? :source return false unless Validate.latitude? camera[:source][:lat] return false unless Validate.longitude? camera[:source][:lon] else return false end return true end def self.pig_config?(alias_name, location, ip, port, tau_test, min_thread_size, max_thread_size, max_queue_thread_size, queue_size) return false unless alias_name.length > 0 return false unless Validate.latitude? location[:lat] return false unless Validate.longitude? location[:lon] return false unless Validate.ip? ip return false unless Validate.port? port return false unless tau_test.is_a? Numeric return false unless min_thread_size > 0 return false unless max_thread_size > 0 return false unless max_queue_thread_size >= 0 return false unless queue_size > 0 return true end def self.dissemination_config?(dissemination_type, ip, port, dspro_path, dspro_config_path, disservice_path, disservice_config_path) return false unless dissemination_type.is_a? String return false unless dissemination_type == "DisService" || dissemination_type == "DSPro" return false unless Validate.ip? ip return false unless Validate.port? port return false unless Pathname.new(dspro_path).absolute? return false unless Pathname.new(dspro_config_path).absolute? return false unless Pathname.new(disservice_path).absolute? return false unless Pathname.new(disservice_config_path).absolute? return true end def self.app_config?(app_name, opt) return false unless (opt.keys & @@KEYS).any? services = Dir.entries(@@SERVICES_FOLDER) process = Dir.entries(@@PROCESS_FOLDER) applications = Dir.entries(@@APPLICATION_CONFIG_DIR) return false unless applications.include? app_name opt.keys.each do |key| case key when :priority return false unless opt[key].between?(0, 100) when :allow_services opt[key].each do |service| return false unless services.include?(service.to_s + "_service_strategy.rb") end when :service_policies opt[key].keys.each do | service | opt[key][service].each do | service_name, value | case service_name when :processing_pipelines opt[key][service][service_name].each do | pipeline | return false unless process.include?(pipeline.to_s + "_processing_strategy.rb") end when :filtering_threshold return false unless value.between?(0, 1) when :expire_after return false unless value >= 0 when :on_demand return false unless value == true or value == false unless value return false unless opt[key][service][:uninstall_after] >= 0 end when :uninstall_after next when :distance_decay return false unless @@DISTANCE_TYPES.include?(value[:type]) return false unless value[:max] >= 0 when :time_decay return false unless @@DISTANCE_TYPES.include?(value[:type]) return false unless value[:max] >= 0 else return false end end end when :dissemination_policy return false unless opt[key][:subscription].eql? app_name return false unless opt[key][:retries] >= 0 return false unless opt[key][:wait] >= 0 # TODO # return false unless opt[key][service][:on_update] return false unless @@CHANNELS.include?(opt[key][:allow_channels]) else return false end end return true rescue return false end end end end
DSG-UniFE/spf
src/ruby/spf/common/validate.rb
Ruby
mit
6,498
/*! @file @copyright The code is licensed under the MIT License <http://opensource.org/licenses/MIT>, Copyright (c) 2013-2015 Niels Lohmann. @author Niels Lohmann <http://nlohmann.me> @see https://github.com/nlohmann/json */ #include "json.h" #include <cctype> // std::isdigit, std::isspace #include <cstddef> // std::size_t #include <stdexcept> // std::runtime_error #include <utility> // std::swap, std::move namespace nlohmann { /////////////////////////////////// // CONSTRUCTORS OF UNION "value" // /////////////////////////////////// json::value::value(array_t* _array): array(_array) {} json::value::value(object_t* object_): object(object_) {} json::value::value(string_t* _string): string(_string) {} json::value::value(boolean_t _boolean) : boolean(_boolean) {} json::value::value(number_t _number) : number(_number) {} json::value::value(number_float_t _number_float) : number_float(_number_float) {} ///////////////////////////////// // CONSTRUCTORS AND DESTRUCTOR // ///////////////////////////////// /*! Construct an empty JSON given the type. @param t the type from the @ref json::type enumeration. @post Memory for array, object, and string are allocated. */ json::json(const value_t t) : type_(t) { switch (type_) { case (value_t::array): { value_.array = new array_t(); break; } case (value_t::object): { value_.object = new object_t(); break; } case (value_t::string): { value_.string = new string_t(); break; } case (value_t::boolean): { value_.boolean = boolean_t(); break; } case (value_t::number): { value_.number = number_t(); break; } case (value_t::number_float): { value_.number_float = number_float_t(); break; } default: { break; } } } json::json() noexcept : final_type_(0), type_(value_t::null) {} /*! Construct a null JSON object. */ json::json(std::nullptr_t) noexcept : json() {} /*! Construct a string JSON object. @param s a string to initialize the JSON object with */ json::json(const std::string& s) : final_type_(0), type_(value_t::string), value_(new string_t(s)) {} json::json(std::string&& s) : final_type_(0), type_(value_t::string), value_(new string_t(std::move(s))) {} json::json(const char* s) : final_type_(0), type_(value_t::string), value_(new string_t(s)) {} json::json(const bool b) noexcept : final_type_(0), type_(value_t::boolean), value_(b) {} json::json(const array_t& a) : final_type_(0), type_(value_t::array), value_(new array_t(a)) {} json::json(array_t&& a) : final_type_(0), type_(value_t::array), value_(new array_t(std::move(a))) {} json::json(const object_t& o) : final_type_(0), type_(value_t::object), value_(new object_t(o)) {} json::json(object_t&& o) : final_type_(0), type_(value_t::object), value_(new object_t(std::move(o))) {} /*! This function is a bit tricky as it uses an initializer list of JSON objects for both arrays and objects. This is not supported by C++, so we use the following trick. Both initializer lists for objects and arrays will transform to a list of JSON objects. The only difference is that in case of an object, the list will contain JSON array objects with two elements - one for the key and one for the value. As a result, it is sufficient to check if each element of the initializer list is an array (1) with two elements (2) whose first element is of type string (3). If this is the case, we treat the whole initializer list as list of pairs to construct an object. If not, we pass it as is to create an array. @bug With the described approach, we would fail to recognize an array whose first element is again an arrays as array. @param a an initializer list to create from @param type_deduction whether the type (array/object) shall eb deducted @param manual_type if type deduction is switched of, pass a manual type */ json::json(list_init_t a, bool type_deduction, value_t manual_type) : final_type_(0) { // the initializer list could describe an object bool is_object = true; // check if each element is an array with two elements whose first element // is a string for (const auto& element : a) { if ((element.final_type_ == 1 and element.type_ == value_t::array) or (element.type_ != value_t::array or element.size() != 2 or element[0].type_ != value_t::string)) { // we found an element that makes it impossible to use the // initializer list as object is_object = false; break; } } // adjust type if type deduction is not wanted if (not type_deduction) { // mark this object's type as final final_type_ = 1; // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_object = false; } // if object is wanted but impossible, throw an exception if (manual_type == value_t::object and not is_object) { throw std::logic_error("cannot create JSON object"); } } if (is_object) { // the initializer list is a list of pairs -> create object type_ = value_t::object; value_ = new object_t(); for (auto& element : a) { value_.object->emplace(std::make_pair(std::move(element[0]), std::move(element[1]))); } } else { // the initializer list describes an array -> create array type_ = value_t::array; value_ = new array_t(std::move(a)); } } /*! @param a initializer list to create an array from @return array */ json json::array(list_init_t a) { return json(a, false, value_t::array); } /*! @param a initializer list to create an object from @return object */ json json::object(list_init_t a) { // if more than one element is in the initializer list, wrap it if (a.size() > 1) { return json({a}, false, value_t::object); } else { return json(a, false, value_t::object); } } /*! A copy constructor for the JSON class. @param o the JSON object to copy */ json::json(const json& o) : type_(o.type_) { switch (type_) { case (value_t::array): { value_.array = new array_t(*o.value_.array); break; } case (value_t::object): { value_.object = new object_t(*o.value_.object); break; } case (value_t::string): { value_.string = new string_t(*o.value_.string); break; } case (value_t::boolean): { value_.boolean = o.value_.boolean; break; } case (value_t::number): { value_.number = o.value_.number; break; } case (value_t::number_float): { value_.number_float = o.value_.number_float; break; } default: { break; } } } /*! A move constructor for the JSON class. @param o the JSON object to move @post The JSON object \p o is invalidated. */ json::json(json&& o) noexcept : type_(std::move(o.type_)), value_(std::move(o.value_)) { // invalidate payload o.type_ = value_t::null; o.value_ = {}; } /*! A copy assignment operator for the JSON class, following the copy-and-swap idiom. @param o A JSON object to assign to this object. */ json& json::operator=(json o) noexcept { std::swap(type_, o.type_); std::swap(value_, o.value_); return *this; } json::~json() noexcept { switch (type_) { case (value_t::array): { delete value_.array; break; } case (value_t::object): { delete value_.object; break; } case (value_t::string): { delete value_.string; break; } default: { // nothing to do for non-pointer types break; } } } /*! @param s a string representation of a JSON object @return a JSON object */ json json::parse(const std::string& s) { return parser(s).parse(); } /*! @param s a string representation of a JSON object @return a JSON object */ json json::parse(const char* s) { return parser(s).parse(); } std::string json::type_name() const noexcept { switch (type_) { case (value_t::array): { return "array"; } case (value_t::object): { return "object"; } case (value_t::null): { return "null"; } case (value_t::string): { return "string"; } case (value_t::boolean): { return "boolean"; } default: { return "number"; } } } /////////////////////////////// // OPERATORS AND CONVERSIONS // /////////////////////////////// /*! @exception std::logic_error if the function is called for JSON objects whose type is not string */ template<> std::string json::get() const { switch (type_) { case (value_t::string): return *value_.string; default: throw std::logic_error("cannot cast " + type_name() + " to JSON string"); } } /*! @exception std::logic_error if the function is called for JSON objects whose type is not number (int or float) */ template<> int json::get() const { switch (type_) { case (value_t::number): return value_.number; case (value_t::number_float): return static_cast<int>(value_.number_float); default: throw std::logic_error("cannot cast " + type_name() + " to JSON number"); } } /*! @exception std::logic_error if the function is called for JSON objects whose type is not number (int or float) */ template<> int64_t json::get() const { switch (type_) { case (value_t::number): return value_.number; case (value_t::number_float): return static_cast<number_t>(value_.number_float); default: throw std::logic_error("cannot cast " + type_name() + " to JSON number"); } } /*! @exception std::logic_error if the function is called for JSON objects whose type is not number (int or float) */ template<> double json::get() const { switch (type_) { case (value_t::number): return static_cast<number_float_t>(value_.number); case (value_t::number_float): return value_.number_float; default: throw std::logic_error("cannot cast " + type_name() + " to JSON number"); } } /*! @exception std::logic_error if the function is called for JSON objects whose type is not boolean */ template<> bool json::get() const { switch (type_) { case (value_t::boolean): return value_.boolean; default: throw std::logic_error("cannot cast " + type_name() + " to JSON Boolean"); } } /*! @exception std::logic_error if the function is called for JSON objects whose type is an object */ template<> json::array_t json::get() const { if (type_ == value_t::array) { return *value_.array; } if (type_ == value_t::object) { throw std::logic_error("cannot cast " + type_name() + " to JSON array"); } array_t result; result.push_back(*this); return result; } /*! @exception std::logic_error if the function is called for JSON objects whose type is not object */ template<> json::object_t json::get() const { if (type_ == value_t::object) { return *value_.object; } else { throw std::logic_error("cannot cast " + type_name() + " to JSON object"); } } json::operator std::string() const { return get<std::string>(); } json::operator int() const { return get<int>(); } json::operator int64_t() const { return get<int64_t>(); } json::operator double() const { return get<double>(); } json::operator bool() const { return get<bool>(); } json::operator array_t() const { return get<array_t>(); } json::operator object_t() const { return get<object_t>(); } /*! Internal implementation of the serialization function. \param prettyPrint whether the output shall be pretty-printed \param indentStep the indent level \param currentIndent the current indent level (only used internally) */ std::string json::dump(const bool prettyPrint, const unsigned int indentStep, unsigned int currentIndent) const noexcept { // helper function to return whitespace as indentation const auto indent = [prettyPrint, &currentIndent]() { return prettyPrint ? std::string(currentIndent, ' ') : std::string(); }; switch (type_) { case (value_t::string): { return std::string("\"") + escapeString(*value_.string) + "\""; } case (value_t::boolean): { return value_.boolean ? "true" : "false"; } case (value_t::number): { return std::to_string(value_.number); } case (value_t::number_float): { return std::to_string(value_.number_float); } case (value_t::array): { if (value_.array->empty()) { return "[]"; } std::string result = "["; // increase indentation if (prettyPrint) { currentIndent += indentStep; result += "\n"; } for (array_t::const_iterator i = value_.array->begin(); i != value_.array->end(); ++i) { if (i != value_.array->begin()) { result += prettyPrint ? ",\n" : ","; } result += indent() + i->dump(prettyPrint, indentStep, currentIndent); } // decrease indentation if (prettyPrint) { currentIndent -= indentStep; result += "\n"; } return result + indent() + "]"; } case (value_t::object): { if (value_.object->empty()) { return "{}"; } std::string result = "{"; // increase indentation if (prettyPrint) { currentIndent += indentStep; result += "\n"; } for (object_t::const_iterator i = value_.object->begin(); i != value_.object->end(); ++i) { if (i != value_.object->begin()) { result += prettyPrint ? ",\n" : ","; } result += indent() + "\"" + i->first + "\":" + (prettyPrint ? " " : "") + i->second.dump( prettyPrint, indentStep, currentIndent); } // decrease indentation if (prettyPrint) { currentIndent -= indentStep; result += "\n"; } return result + indent() + "}"; } // actually only value_t::null - but making the compiler happy default: { return "null"; } } } /*! Internal function to replace all occurrences of a character in a given string with another string. \param str the string that contains tokens to replace \param c the character that needs to be replaced \param replacement the string that is the replacement for the character */ void json::replaceChar(std::string& str, char c, const std::string& replacement) const { size_t start_pos = 0; while ((start_pos = str.find(c, start_pos)) != std::string::npos) { str.replace(start_pos, 1, replacement); start_pos += replacement.length(); } } /*! Escapes all special characters in the given string according to ECMA-404. Necessary as some characters such as quotes, backslashes and so on can't be used as is when dumping a string value. \param str the string that should be escaped. \return a copy of the given string with all special characters escaped. */ std::string json::escapeString(const std::string& str) const { std::string result(str); // we first need to escape the backslashes as all other methods will insert // legitimate backslashes into the result. replaceChar(result, '\\', "\\\\"); // replace all other characters replaceChar(result, '"', "\\\""); replaceChar(result, '\n', "\\n"); replaceChar(result, '\r', "\\r"); replaceChar(result, '\f', "\\f"); replaceChar(result, '\b', "\\b"); replaceChar(result, '\t', "\\t"); return result; } /*! Serialization function for JSON objects. The function tries to mimick Python's \p json.dumps() function, and currently supports its \p indent parameter. \param indent if indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation \see https://docs.python.org/2/library/json.html#json.dump */ std::string json::dump(int indent) const noexcept { if (indent >= 0) { return dump(true, static_cast<unsigned int>(indent)); } else { return dump(false, 0); } } /////////////////////////////////////////// // ADDING ELEMENTS TO OBJECTS AND ARRAYS // /////////////////////////////////////////// json& json::operator+=(const json& o) { push_back(o); return *this; } /*! @todo comment me */ json& json::operator+=(const object_t::value_type& p) { return operator[](p.first) = p.second; } /*! @todo comment me */ json& json::operator+=(list_init_t a) { push_back(a); return *this; } /*! This function implements the actual "adding to array" function and is called by all other push_back or operator+= functions. If the function is called for an array, the passed element is added to the array. @param o The element to add to the array. @pre The JSON object is an array or null. @post The JSON object is an array whose last element is the passed element o. @exception std::runtime_error The function was called for a JSON type that does not support addition to an array (e.g., int or string). @note Null objects are silently transformed into an array before the addition. */ void json::push_back(const json& o) { // push_back only works for null objects or arrays if (not(type_ == value_t::null or type_ == value_t::array)) { throw std::runtime_error("cannot add element to " + type_name()); } // transform null object into an array if (type_ == value_t::null) { type_ = value_t::array; value_.array = new array_t; } // add element to array value_.array->push_back(o); } /*! This function implements the actual "adding to array" function and is called by all other push_back or operator+= functions. If the function is called for an array, the passed element is added to the array using move semantics. @param o The element to add to the array. @pre The JSON object is an array or null. @post The JSON object is an array whose last element is the passed element o. @post The element o is destroyed. @exception std::runtime_error The function was called for a JSON type that does not support addition to an array (e.g., int or string). @note Null objects are silently transformed into an array before the addition. @note This function applies move semantics for the given element. */ void json::push_back(json&& o) { // push_back only works for null objects or arrays if (not(type_ == value_t::null or type_ == value_t::array)) { throw std::runtime_error("cannot add element to " + type_name()); } // transform null object into an array if (type_ == value_t::null) { type_ = value_t::array; value_.array = new array_t; } // add element to array (move semantics) value_.array->emplace_back(std::move(o)); // invalidate object o.type_ = value_t::null; } /*! @todo comment me */ void json::push_back(const object_t::value_type& p) { operator[](p.first) = p.second; } /*! @todo comment me */ void json::push_back(list_init_t a) { bool is_array = false; // check if each element is an array with two elements whose first element // is a string for (const auto& element : a) { if (element.type_ != value_t::array or element.size() != 2 or element[0].type_ != value_t::string) { // the initializer list describes an array is_array = true; break; } } if (is_array) { for (const json& element : a) { push_back(element); } } else { for (const json& element : a) { const object_t::value_type tmp {element[0].get<std::string>(), element[1]}; push_back(tmp); } } } /*! This operator realizes read/write access to array elements given an integer index. Bounds will not be checked. @note The "index" variable should be of type size_t as it is compared against size() and used in the at() function. However, the compiler will have problems in case integer literals are used. In this case, an implicit conversion to both size_t and JSON is possible. Therefore, we use int as type and convert it to size_t where necessary. @param index the index of the element to return from the array @return reference to element for the given index @pre Object is an array. @exception std::domain_error if object is not an array */ json::reference json::operator[](const int index) { // this [] operator only works for arrays if (type_ != value_t::array) { throw std::domain_error("cannot add entry with index " + std::to_string(index) + " to " + type_name()); } // return reference to element from array at given index return (*value_.array)[static_cast<std::size_t>(index)]; } /*! This operator realizes read-only access to array elements given an integer index. Bounds will not be checked. @note The "index" variable should be of type size_t as it is compared against size() and used in the at() function. However, the compiler will have problems in case integer literals are used. In this case, an implicit conversion to both size_t and JSON is possible. Therefore, we use int as type and convert it to size_t where necessary. @param index the index of the element to return from the array @return read-only reference to element for the given index @pre Object is an array. @exception std::domain_error if object is not an array */ json::const_reference json::operator[](const int index) const { // this [] operator only works for arrays if (type_ != value_t::array) { throw std::domain_error("cannot get entry with index " + std::to_string(index) + " from " + type_name()); } // return element from array at given index return (*value_.array)[static_cast<std::size_t>(index)]; } /*! This function realizes read/write access to array elements given an integer index. Bounds will be checked. @note The "index" variable should be of type size_t as it is compared against size() and used in the at() function. However, the compiler will have problems in case integer literals are used. In this case, an implicit conversion to both size_t and JSON is possible. Therefore, we use int as type and convert it to size_t where necessary. @param index the index of the element to return from the array @return reference to element for the given index @pre Object is an array. @exception std::domain_error if object is not an array @exception std::out_of_range if index is out of range (via std::vector::at) */ json::reference json::at(const int index) { // this function only works for arrays if (type_ != value_t::array) { throw std::domain_error("cannot add entry with index " + std::to_string(index) + " to " + type_name()); } // return reference to element from array at given index return value_.array->at(static_cast<std::size_t>(index)); } /*! This operator realizes read-only access to array elements given an integer index. Bounds will be checked. @note The "index" variable should be of type size_t as it is compared against size() and used in the at() function. However, the compiler will have problems in case integer literals are used. In this case, an implicit conversion to both size_t and JSON is possible. Therefore, we use int as type and convert it to size_t where necessary. @param index the index of the element to return from the array @return read-only reference to element for the given index @pre Object is an array. @exception std::domain_error if object is not an array @exception std::out_of_range if index is out of range (via std::vector::at) */ json::const_reference json::at(const int index) const { // this function only works for arrays if (type_ != value_t::array) { throw std::domain_error("cannot get entry with index " + std::to_string(index) + " from " + type_name()); } // return element from array at given index return value_.array->at(static_cast<std::size_t>(index)); } /*! @copydoc json::operator[](const char* key) */ json::reference json::operator[](const std::string& key) { return operator[](key.c_str()); } /*! This operator realizes read/write access to object elements given a string key. @param key the key index of the element to return from the object @return reference to a JSON object for the given key (null if key does not exist) @pre Object is an object or a null object. @post null objects are silently converted to objects. @exception std::domain_error if object is not an object (or null) */ json::reference json::operator[](const char* key) { // implicitly convert null to object if (type_ == value_t::null) { type_ = value_t::object; value_.object = new object_t; } // this [] operator only works for objects if (type_ != value_t::object) { throw std::domain_error("cannot add entry with key " + std::string(key) + " to " + type_name()); } // if the key does not exist, create it if (value_.object->find(key) == value_.object->end()) { (*value_.object)[key] = json(); } // return reference to element from array at given index return (*value_.object)[key]; } /*! @copydoc json::operator[](const char* key) */ json::const_reference json::operator[](const std::string& key) const { return operator[](key.c_str()); } /*! This operator realizes read-only access to object elements given a string key. @param key the key index of the element to return from the object @return read-only reference to element for the given key @pre Object is an object. @exception std::domain_error if object is not an object @exception std::out_of_range if key is not found in object */ json::const_reference json::operator[](const char* key) const { // this [] operator only works for objects if (type_ != value_t::object) { throw std::domain_error("cannot get entry with key " + std::string(key) + " from " + type_name()); } // search for the key const auto it = value_.object->find(key); // make sure the key exists in the object if (it == value_.object->end()) { throw std::out_of_range("key " + std::string(key) + " not found"); } // return element from array at given key return it->second; } /*! @copydoc json::at(const char* key) */ json::reference json::at(const std::string& key) { return at(key.c_str()); } /*! This function realizes read/write access to object elements given a string key. @param key the key index of the element to return from the object @return reference to a JSON object for the given key (exception if key does not exist) @pre Object is an object. @exception std::domain_error if object is not an object @exception std::out_of_range if key was not found (via std::map::at) */ json::reference json::at(const char* key) { // this function operator only works for objects if (type_ != value_t::object) { throw std::domain_error("cannot add entry with key " + std::string(key) + " to " + type_name()); } // return reference to element from array at given index return value_.object->at(key); } /*! @copydoc json::at(const char *key) const */ json::const_reference json::at(const std::string& key) const { return at(key.c_str()); } /*! This operator realizes read-only access to object elements given a string key. @param key the key index of the element to return from the object @return read-only reference to element for the given key @pre Object is an object. @exception std::domain_error if object is not an object @exception std::out_of_range if key is not found (via std::map::at) */ json::const_reference json::at(const char* key) const { // this [] operator only works for objects if (type_ != value_t::object) { throw std::domain_error("cannot get entry with key " + std::string(key) + " from " + type_name()); } // return element from array at given key return value_.object->at(key); } /*! Returns the size of the JSON object. @return the size of the JSON object; the size is the number of elements in compounds (array and object), 1 for value types (true, false, number, string), and 0 for null. @invariant The size is reported as 0 if and only if empty() would return true. */ json::size_type json::size() const noexcept { switch (type_) { case (value_t::array): { return value_.array->size(); } case (value_t::object): { return value_.object->size(); } case (value_t::null): { return 0; } default: { return 1; } } } /*! Returns the maximal size of the JSON object. @return the maximal size of the JSON object; the maximal size is the maximal number of elements in compounds (array and object), 1 for value types (true, false, number, string), and 0 for null. */ json::size_type json::max_size() const noexcept { switch (type_) { case (value_t::array): { return value_.array->max_size(); } case (value_t::object): { return value_.object->max_size(); } case (value_t::null): { return 0; } default: { return 1; } } } /*! Returns whether a JSON object is empty. @return true for null objects and empty compounds (array and object); false for value types (true, false, number, string) and filled compounds (array and object). @invariant Empty would report true if and only if size() would return 0. */ bool json::empty() const noexcept { switch (type_) { case (value_t::array): { return value_.array->empty(); } case (value_t::object): { return value_.object->empty(); } case (value_t::null): { return true; } default: { return false; } } } /*! Removes all elements from compounds and resets values to default. @invariant Clear will set any value type to its default value which is empty for compounds, false for booleans, 0 for integer numbers, and 0.0 for floating numbers. */ void json::clear() noexcept { switch (type_) { case (value_t::array): { value_.array->clear(); break; } case (value_t::object): { value_.object->clear(); break; } case (value_t::string): { value_.string->clear(); break; } case (value_t::boolean): { value_.boolean = {}; break; } case (value_t::number): { value_.number = {}; break; } case (value_t::number_float): { value_.number_float = {}; break; } default: { break; } } } void json::swap(json& o) noexcept { std::swap(type_, o.type_); std::swap(value_, o.value_); } json::value_t json::type() const noexcept { return type_; } json::iterator json::find(const std::string& key) { return find(key.c_str()); } json::const_iterator json::find(const std::string& key) const { return find(key.c_str()); } json::iterator json::find(const char* key) { auto result = end(); if (type_ == value_t::object) { delete result.oi_; result.oi_ = new object_t::iterator(value_.object->find(key)); result.invalid = (*(result.oi_) == value_.object->end()); } return result; } json::const_iterator json::find(const char* key) const { auto result = cend(); if (type_ == value_t::object) { delete result.oi_; result.oi_ = new object_t::const_iterator(value_.object->find(key)); result.invalid = (*(result.oi_) == value_.object->cend()); } return result; } bool json::operator==(const json& o) const noexcept { switch (type_) { case (value_t::array): { if (o.type_ == value_t::array) { return *value_.array == *o.value_.array; } break; } case (value_t::object): { if (o.type_ == value_t::object) { return *value_.object == *o.value_.object; } break; } case (value_t::null): { if (o.type_ == value_t::null) { return true; } break; } case (value_t::string): { if (o.type_ == value_t::string) { return *value_.string == *o.value_.string; } break; } case (value_t::boolean): { if (o.type_ == value_t::boolean) { return value_.boolean == o.value_.boolean; } break; } case (value_t::number): { if (o.type_ == value_t::number) { return value_.number == o.value_.number; } if (o.type_ == value_t::number_float) { return value_.number == static_cast<number_t>(o.value_.number_float); } break; } case (value_t::number_float): { if (o.type_ == value_t::number) { return value_.number_float == static_cast<number_float_t>(o.value_.number); } if (o.type_ == value_t::number_float) { return value_.number_float == o.value_.number_float; } break; } } return false; } bool json::operator!=(const json& o) const noexcept { return not operator==(o); } json::iterator json::begin() noexcept { return json::iterator(this, true); } json::iterator json::end() noexcept { return json::iterator(this, false); } json::const_iterator json::begin() const noexcept { return json::const_iterator(this, true); } json::const_iterator json::end() const noexcept { return json::const_iterator(this, false); } json::const_iterator json::cbegin() const noexcept { return json::const_iterator(this, true); } json::const_iterator json::cend() const noexcept { return json::const_iterator(this, false); } json::reverse_iterator json::rbegin() noexcept { return reverse_iterator(end()); } json::reverse_iterator json::rend() noexcept { return reverse_iterator(begin()); } json::const_reverse_iterator json::crbegin() const noexcept { return const_reverse_iterator(cend()); } json::const_reverse_iterator json::crend() const noexcept { return const_reverse_iterator(cbegin()); } json::iterator::iterator(json* j, bool begin) : object_(j), invalid(not begin or j == nullptr) { if (object_ != nullptr) { if (object_->type_ == json::value_t::array) { if (begin) { vi_ = new array_t::iterator(object_->value_.array->begin()); invalid = (*vi_ == object_->value_.array->end()); } else { vi_ = new array_t::iterator(object_->value_.array->end()); } } else if (object_->type_ == json::value_t::object) { if (begin) { oi_ = new object_t::iterator(object_->value_.object->begin()); invalid = (*oi_ == object_->value_.object->end()); } else { oi_ = new object_t::iterator(object_->value_.object->end()); } } } } json::iterator::iterator(const json::iterator& o) : object_(o.object_), invalid(o.invalid) { if (o.vi_ != nullptr) { vi_ = new array_t::iterator(*(o.vi_)); } if (o.oi_ != nullptr) { oi_ = new object_t::iterator(*(o.oi_)); } } json::iterator::~iterator() { delete vi_; delete oi_; } json::iterator& json::iterator::operator=(json::iterator o) { std::swap(object_, o.object_); std::swap(vi_, o.vi_); std::swap(oi_, o.oi_); std::swap(invalid, o.invalid); return *this; } bool json::iterator::operator==(const json::iterator& o) const { if (object_ != nullptr and o.object_ != nullptr) { if (object_->type_ == json::value_t::array and o.object_->type_ == json::value_t::array) { return (*vi_ == *(o.vi_)); } if (object_->type_ == json::value_t::object and o.object_->type_ == json::value_t::object) { return (*oi_ == *(o.oi_)); } if (invalid == o.invalid and object_ == o.object_) { return true; } } return false; } bool json::iterator::operator!=(const json::iterator& o) const { return not operator==(o); } json::iterator& json::iterator::operator++() { if (object_ != nullptr) { switch (object_->type_) { case (json::value_t::array): { std::advance(*vi_, 1); invalid = (*vi_ == object_->value_.array->end()); break; } case (json::value_t::object): { std::advance(*oi_, 1); invalid = (*oi_ == object_->value_.object->end()); break; } default: { invalid = true; break; } } } return *this; } json::iterator& json::iterator::operator--() { if (object_ != nullptr) { switch (object_->type_) { case (json::value_t::array): { invalid = (*vi_ == object_->value_.array->begin()); std::advance(*vi_, -1); break; } case (json::value_t::object): { invalid = (*oi_ == object_->value_.object->begin()); std::advance(*oi_, -1); break; } default: { invalid = true; break; } } } return *this; } json& json::iterator::operator*() const { if (object_ == nullptr or invalid) { throw std::out_of_range("cannot get value"); } switch (object_->type_) { case (json::value_t::array): { return **vi_; } case (json::value_t::object): { return (*oi_)->second; } default: { return *object_; } } } json* json::iterator::operator->() const { if (object_ == nullptr or invalid) { throw std::out_of_range("cannot get value"); } switch (object_->type_) { case (json::value_t::array): { return &(**vi_); } case (json::value_t::object): { return &((*oi_)->second); } default: { return object_; } } } std::string json::iterator::key() const { if (object_ == nullptr or invalid or object_->type_ != json::value_t::object) { throw std::out_of_range("cannot get value"); } return (*oi_)->first; } json& json::iterator::value() const { if (object_ == nullptr or invalid) { throw std::out_of_range("cannot get value"); } switch (object_->type_) { case (json::value_t::array): { return **vi_; } case (json::value_t::object): { return (*oi_)->second; } default: { return *object_; } } } json::const_iterator::const_iterator(const json* j, bool begin) : object_(j), invalid(not begin or j == nullptr) { if (object_ != nullptr) { if (object_->type_ == json::value_t::array) { if (begin) { vi_ = new array_t::const_iterator(object_->value_.array->cbegin()); invalid = (*vi_ == object_->value_.array->cend()); } else { vi_ = new array_t::const_iterator(object_->value_.array->cend()); } } else if (object_->type_ == json::value_t::object) { if (begin) { oi_ = new object_t::const_iterator(object_->value_.object->cbegin()); invalid = (*oi_ == object_->value_.object->cend()); } else { oi_ = new object_t::const_iterator(object_->value_.object->cend()); } } } } json::const_iterator::const_iterator(const json::const_iterator& o) : object_(o.object_), invalid(o.invalid) { if (o.vi_ != nullptr) { vi_ = new array_t::const_iterator(*(o.vi_)); } if (o.oi_ != nullptr) { oi_ = new object_t::const_iterator(*(o.oi_)); } } json::const_iterator::const_iterator(const json::iterator& o) : object_(o.object_), invalid(o.invalid) { if (o.vi_ != nullptr) { vi_ = new array_t::const_iterator(*(o.vi_)); } if (o.oi_ != nullptr) { oi_ = new object_t::const_iterator(*(o.oi_)); } } json::const_iterator::~const_iterator() { delete vi_; delete oi_; } json::const_iterator& json::const_iterator::operator=(json::const_iterator o) { std::swap(object_, o.object_); std::swap(vi_, o.vi_); std::swap(oi_, o.oi_); std::swap(invalid, o.invalid); return *this; } bool json::const_iterator::operator==(const json::const_iterator& o) const { if (object_ != nullptr and o.object_ != nullptr) { if (object_->type_ == json::value_t::array and o.object_->type_ == json::value_t::array) { return (*vi_ == *(o.vi_)); } if (object_->type_ == json::value_t::object and o.object_->type_ == json::value_t::object) { return (*oi_ == *(o.oi_)); } if (invalid == o.invalid and object_ == o.object_) { return true; } } return false; } bool json::const_iterator::operator!=(const json::const_iterator& o) const { return not operator==(o); } json::const_iterator& json::const_iterator::operator++() { if (object_ != nullptr) { switch (object_->type_) { case (json::value_t::array): { std::advance(*vi_, 1); invalid = (*vi_ == object_->value_.array->end()); break; } case (json::value_t::object): { std::advance(*oi_, 1); invalid = (*oi_ == object_->value_.object->end()); break; } default: { invalid = true; break; } } } return *this; } json::const_iterator& json::const_iterator::operator--() { if (object_ != nullptr) { switch (object_->type_) { case (json::value_t::array): { invalid = (*vi_ == object_->value_.array->begin()); std::advance(*vi_, -1); break; } case (json::value_t::object): { invalid = (*oi_ == object_->value_.object->begin()); std::advance(*oi_, -1); break; } default: { invalid = true; break; } } } return *this; } const json& json::const_iterator::operator*() const { if (object_ == nullptr or invalid) { throw std::out_of_range("cannot get value"); } switch (object_->type_) { case (json::value_t::array): { return **vi_; } case (json::value_t::object): { return (*oi_)->second; } default: { return *object_; } } } const json* json::const_iterator::operator->() const { if (object_ == nullptr or invalid) { throw std::out_of_range("cannot get value"); } switch (object_->type_) { case (json::value_t::array): { return &(**vi_); } case (json::value_t::object): { return &((*oi_)->second); } default: { return object_; } } } std::string json::const_iterator::key() const { if (object_ == nullptr or invalid or object_->type_ != json::value_t::object) { throw std::out_of_range("cannot get value"); } return (*oi_)->first; } const json& json::const_iterator::value() const { if (object_ == nullptr or invalid) { throw std::out_of_range("cannot get value"); } switch (object_->type_) { case (json::value_t::array): { return **vi_; } case (json::value_t::object): { return (*oi_)->second; } default: { return *object_; } } } /*! Initialize the JSON parser given a string \p s. @note After initialization, the function @ref parse has to be called manually. @param s string to parse @post \p s is copied to the buffer @ref buffer_ and the first character is read. Whitespace is skipped. */ json::parser::parser(const char* s) : buffer_(s) { // read first character next(); } /*! @copydoc json::parser::parser(const char* s) */ json::parser::parser(const std::string& s) : buffer_(s) { // read first character next(); } /*! Initialize the JSON parser given an input stream \p _is. @note After initialization, the function @ref parse has to be called manually. \param _is input stream to parse @post \p _is is copied to the buffer @ref buffer_ and the firsr character is read. Whitespace is skipped. */ json::parser::parser(std::istream& _is) { while (_is) { std::string input_line; std::getline(_is, input_line); buffer_ += input_line; } // read first character next(); } json json::parser::parse() { switch (current_) { case ('{'): { // explicitly set result to object to cope with {} json result(value_t::object); next(); // process nonempty object if (current_ != '}') { do { // key auto key = parseString(); // colon expect(':'); // value result[std::move(key)] = parse(); key.clear(); } while (current_ == ',' and next()); } // closing brace expect('}'); return result; } case ('['): { // explicitly set result to array to cope with [] json result(value_t::array); next(); // process nonempty array if (current_ != ']') { do { result.push_back(parse()); } while (current_ == ',' and next()); } // closing bracket expect(']'); return result; } case ('\"'): { return json(parseString()); } case ('t'): { parseTrue(); return json(true); } case ('f'): { parseFalse(); return json(false); } case ('n'): { parseNull(); return json(); } case ('-'): case ('0'): case ('1'): case ('2'): case ('3'): case ('4'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): { // remember position of number's first character const auto _firstpos_ = pos_ - 1; while (next() and (std::isdigit(current_) or current_ == '.' or current_ == 'e' or current_ == 'E' or current_ == '+' or current_ == '-')); try { const auto float_val = std::stold(buffer_.substr(_firstpos_, pos_ - _firstpos_)); const auto int_val = static_cast<number_t>(float_val); // check if conversion loses precision if (float_val == int_val) { // we would not lose precision -> int return json(int_val); } else { // we would lose precision -> float return json(static_cast<number_float_t>(float_val)); } } catch (...) { error("error translating " + buffer_.substr(_firstpos_, pos_ - _firstpos_) + " to number"); } } default: { error("unexpected character"); } } } /*! This function reads the next character from the buffer while ignoring all trailing whitespace. If another character could be read, the function returns true. If the end of the buffer is reached, false is returned. @return whether another non-whitespace character could be read @post current_ holds the next character */ bool json::parser::next() { if (pos_ == buffer_.size()) { return false; } current_ = buffer_[pos_++]; // skip trailing whitespace while (std::isspace(current_)) { if (pos_ == buffer_.size()) { return false; } current_ = buffer_[pos_++]; } return true; } /*! This function encapsulates the error reporting functions of the parser class. It throws a \p std::invalid_argument exception with a description where the error occurred (given as the number of characters read), what went wrong (using the error message \p msg), and the last read token. @param msg an error message @return <em>This function does not return.</em> @exception std::invalid_argument whenever the function is called */ void json::parser::error(const std::string& msg) const { throw std::invalid_argument("parse error at position " + std::to_string(pos_) + ": " + msg + ", last read: '" + current_ + "'"); } /*! Parses a string after opening quotes (\p ") where read. @return the parsed string @pre An opening quote \p " was read in the main parse function @ref parse. pos_ is the position after the opening quote. @post The character after the closing quote \p " is the current character @ref current_. Whitespace is skipped. @todo Unicode escapes such as \uxxxx are missing - see https://github.com/nlohmann/json/issues/12 */ std::string json::parser::parseString() { // true if and only if the amount of backslashes before the current // character is even bool evenAmountOfBackslashes = true; // the result of the parse process std::string result; // iterate with pos_ over the whole input until we found the end and return // or we exit via error() for (; pos_ < buffer_.size(); pos_++) { char currentChar = buffer_[pos_]; if (not evenAmountOfBackslashes) { // uneven amount of backslashes means the user wants to escape // something so we know there is a case such as '\X' or '\\\X' but // we don't know yet what X is. // at this point in the code, the currentChar has the value of X. // slash, backslash and quote are copied as is if (currentChar == '/' or currentChar == '\\' or currentChar == '"') { result += currentChar; } else { // all other characters are replaced by their respective special // character switch (currentChar) { case 't': { result += '\t'; break; } case 'b': { result += '\b'; break; } case 'f': { result += '\f'; break; } case 'n': { result += '\n'; break; } case 'r': { result += '\r'; break; } case 'u': { // \uXXXX[\uXXXX] is used for escaping unicode, which // has it's own subroutine. result += parseUnicodeEscape(); // the parsing process has brought us one step behind // the unicode escape sequence: // \uXXXX // ^ // we need to go one character back or the parser would // skip the character we are currently pointing at as // the for-loop will decrement pos_ after this iteration pos_--; break; } default: { error("expected one of \\, /, b, f, n, r, t, u behind backslash."); } } } } else { if (currentChar == '"') { // currentChar is a quote, so we found the end of the string // set pos_ behind the trailing quote pos_++; // find next char to parse next(); // bring the result of the parsing process back to the caller return result; } else if (currentChar != '\\') { // all non-backslash characters are added to the end of the // result string. The only backslashes we want in the result // are the ones that are escaped (which happens above). result += currentChar; } } // remember if we have an even amount of backslashes before the current // character if (currentChar == '\\') { // jump between even/uneven for each backslash we encounter evenAmountOfBackslashes = not evenAmountOfBackslashes; } else { // zero backslashes are also an even number, so as soon as we // encounter a non-backslash the chain of backslashes breaks and // we start again from zero evenAmountOfBackslashes = true; } } // we iterated over the whole string without finding a unescaped quote // so the given string is malformed error("expected '\"'"); } /*! Turns a code point into it's UTF-8 representation. You should only pass numbers < 0x10ffff into this function (everything else is a invalid code point). @return the UTF-8 representation of the given code point */ std::string json::parser::codePointToUTF8(unsigned int codePoint) const { // this method contains a lot of bit manipulations to // build the bytes for UTF-8. // the '(... >> S) & 0xHH'-patterns are used to retrieve // certain bits from the code points. // all static casts in this method have boundary checks // we initialize all strings with their final length // (e.g. 1 to 4 bytes) to save the reallocations. if (codePoint <= 0x7f) { // it's just a ASCII compatible codePoint, // so we just interpret the point as a character // and return ASCII return std::string(1, static_cast<char>(codePoint)); } // if true, we need two bytes to encode this as UTF-8 else if (codePoint <= 0x7ff) { // the 0xC0 enables the two most significant two bits // to make this a two-byte UTF-8 character. std::string result(2, static_cast<char>(0xC0 | ((codePoint >> 6) & 0x1F))); result[1] = static_cast<char>(0x80 | (codePoint & 0x3F)); return result; } // if true, now we need three bytes to encode this as UTF-8 else if (codePoint <= 0xffff) { // the 0xE0 enables the three most significant two bits // to make this a three-byte UTF-8 character. std::string result(3, static_cast<char>(0xE0 | ((codePoint >> 12) & 0x0F))); result[1] = static_cast<char>(0x80 | ((codePoint >> 6) & 0x3F)); result[2] = static_cast<char>(0x80 | (codePoint & 0x3F)); return result; } // if true, we need maximal four bytes to encode this as UTF-8 else if (codePoint <= 0x10ffff) { // the 0xE0 enables the four most significant two bits // to make this a three-byte UTF-8 character. std::string result(4, static_cast<char>(0xF0 | ((codePoint >> 18) & 0x07))); result[1] = static_cast<char>(0x80 | ((codePoint >> 12) & 0x3F)); result[2] = static_cast<char>(0x80 | ((codePoint >> 6) & 0x3F)); result[3] = static_cast<char>(0x80 | (codePoint & 0x3F)); return result; } else { // Can't be tested without direct access to this private method. std::string errorMessage = "Invalid codePoint: "; errorMessage += codePoint; error(errorMessage); } } /*! Parses 4 hexadecimal characters as a number. @return the value of the number the hexadecimal characters represent. @pre pos_ is pointing to the first of the 4 hexadecimal characters. @post pos_ is pointing to the character after the 4 hexadecimal characters. */ unsigned int json::parser::parse4HexCodePoint() { const auto startPos = pos_; // check if the remaining buffer is long enough to even hold 4 characters if (pos_ + 3 >= buffer_.size()) { error("Got end of input while parsing unicode escape sequence \\uXXXX"); } // make a string that can hold the pair std::string hexCode(4, ' '); for (; pos_ < startPos + 4; pos_++) { // no boundary check here as we already checked above char currentChar = buffer_[pos_]; // check if we have a hexadecimal character if ((currentChar >= '0' and currentChar <= '9') or (currentChar >= 'a' and currentChar <= 'f') or (currentChar >= 'A' and currentChar <= 'F')) { // all is well, we have valid hexadecimal chars // so we copy that char into our string hexCode[pos_ - startPos] = currentChar; } else { error("Found non-hexadecimal character in unicode escape sequence!"); } } // the cast is safe as 4 hex characters can't present more than 16 bits // the input to stoul was checked to contain only hexadecimal characters // (see above) return static_cast<unsigned int>(std::stoul(hexCode, nullptr, 16)); } /*! Parses the unicode escape codes as defined in the ECMA-404. The escape sequence has two forms: 1. \uXXXX 2. \uXXXX\uYYYY where X and Y are a hexadecimal character (a-zA-Z0-9). Form 1 just contains the unicode code point in the hexadecimal number XXXX. Form 2 is encoding a UTF-16 surrogate pair. The high surrogate is XXXX, the low surrogate is YYYY. @return the UTF-8 character this unicode escape sequence escaped. @pre pos_ is pointing at at the 'u' behind the first backslash. @post pos_ is pointing at the character behind the last X (or Y in form 2). */ std::string json::parser::parseUnicodeEscape() { // jump to the first hex value pos_++; // parse the hex first hex values unsigned int firstCodePoint = parse4HexCodePoint(); if (firstCodePoint >= 0xD800 and firstCodePoint <= 0xDBFF) { // we found invalid code points, which means we either have a malformed // input or we found a high surrogate. // we can only find out by seeing if the next character also wants to // encode a unicode character (so, we have the \uXXXX\uXXXX case here). // jump behind the next \u pos_ += 2; // try to parse the next hex values. // the method does boundary checking for us, so no need to do that here unsigned secondCodePoint = parse4HexCodePoint(); // ok, we have a low surrogate, check if it is a valid one if (secondCodePoint >= 0xDC00 and secondCodePoint <= 0xDFFF) { // calculate the code point from the pair according to the spec unsigned int finalCodePoint = // high surrogate occupies the most significant 22 bits (firstCodePoint << 10) // low surrogate occupies the least significant 15 bits + secondCodePoint // there is still the 0xD800, 0xDC00 and 0x10000 noise in // the result // so we have to substract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00; // we transform the calculated point into UTF-8 return codePointToUTF8(finalCodePoint); } else { error("missing low surrogate"); } } // We have Form 1, so we just interpret the XXXX as a code point return codePointToUTF8(firstCodePoint); } /*! This function is called in case a \p "t" is read in the main parse function @ref parse. In the standard, the \p "true" token is the only candidate, so the next three characters are expected to be \p "rue". In case of a mismatch, an error is raised via @ref error. @pre A \p "t" was read in the main parse function @ref parse. @post The character after the \p "true" is the current character. Whitespace is skipped. */ void json::parser::parseTrue() { if (buffer_.substr(pos_, 3) != "rue") { error("expected true"); } pos_ += 3; // read next character next(); } /*! This function is called in case an \p "f" is read in the main parse function @ref parse. In the standard, the \p "false" token is the only candidate, so the next four characters are expected to be \p "alse". In case of a mismatch, an error is raised via @ref error. @pre An \p "f" was read in the main parse function. @post The character after the \p "false" is the current character. Whitespace is skipped. */ void json::parser::parseFalse() { if (buffer_.substr(pos_, 4) != "alse") { error("expected false"); } pos_ += 4; // read next character next(); } /*! This function is called in case an \p "n" is read in the main parse function @ref parse. In the standard, the \p "null" token is the only candidate, so the next three characters are expected to be \p "ull". In case of a mismatch, an error is raised via @ref error. @pre An \p "n" was read in the main parse function. @post The character after the \p "null" is the current character. Whitespace is skipped. */ void json::parser::parseNull() { if (buffer_.substr(pos_, 3) != "ull") { error("expected null"); } pos_ += 3; // read next character next(); } /*! This function wraps functionality to check whether the current character @ref current_ matches a given character \p c. In case of a match, the next character of the buffer @ref buffer_ is read. In case of a mismatch, an error is raised via @ref error. @param c character that is expected @post The next chatacter is read. Whitespace is skipped. */ void json::parser::expect(const char c) { if (current_ != c) { std::string msg = "expected '"; msg.append(1, c); msg += "'"; error(msg); } else { next(); } } } /*! This operator implements a user-defined string literal for JSON objects. It can be used by adding \p "_json" to a string literal and returns a JSON object if no parse error occurred. @param s a string representation of a JSON object @return a JSON object */ nlohmann::json operator "" _json(const char* s, std::size_t) { return nlohmann::json::parse(s); }
julienlopez/QTacitGame
externals/json.cc
C++
mit
67,378
/* @flow */ import {Seat} from "../core/seat"; import {Bid, BidType, BidSuit} from "../core/bid"; import {Card} from "../core/card"; import {validateBid} from "./validators"; /** * Helper class for analysing board-state. */ export class BoardQuery { constructor(boardState) { this.boardState = boardState; } get hands() { return this.boardState.hands; } get dealer() { return this.boardState.dealer; } get bids() { return this.boardState.bids; } get cards() { return this.boardState.cards; } /** * Returns the last bid to be made of any type */ get lastBid(): Bid { return this.boardState.bids[this.boardState.bids.length - 1]; } /** * Returns the last bid to be made of type Bid.Call */ get lastCall(): Bid { return this.boardState.bids .reduce((lastCall, current) => { if (current.type === BidType.Call) return current; else return lastCall; }, undefined); } /** * Returns the player who made the lastCall */ get lastCaller(): Seat { let call = this.lastCall; if (call) return Seat.rotate(this.boardState.dealer, this.boardState.bids.indexOf(call)); } /** * Returns the last bid to be made which was not a no-bid */ get lastAction(): Bid { return this.boardState.bids .reduce((lastAction, current) => { if (current.type !== BidType.NoBid) return current; else return lastAction; }, undefined); } /** * Returns the seat whic made the lastAction */ get lastActor(): Seat { let act = this.lastAction; if (act) return Seat.rotate(this.boardState.dealer, this.boardState.bids.indexOf(act)); } /** * Returns the suit of the bid contract or undefined if the bidding has not ended * or no suit has been bid yet */ get trumpSuit(): BidSuit { if (this.biddingHasEnded && this.lastCall) return this.lastCall.suit; } /** * Returns true when no more bids can be made */ get biddingHasEnded(): boolean { return (this.bids.length >= 4) && !this.bids.slice(-3).some(bid => bid.type !== BidType.NoBid); } /** * Returns the current trick, which will be an array of the cards which have been * played to the trick, starting with the lead card. If no cards have been played * yet it returns an empty array. */ get currentTrick(): Array<Card> { let played = this.boardState.cards.length % 4; played = played || 4; return this.boardState.cards.slice(played * -1); } /* * Returns the winner of the previous trick */ get previousTrickWinner(): Seat { if (this.boardState.cards.length < 4) return undefined; let played = this.boardState.cards.length % 4; let trick = this.boardState.cards.slice(this.boardState.cards.length - played - 4, this.boardState.cards.length - played); let leadSuit = trick[0].card.suit; let winner = trick.sort((played1, played2) => { return Card.compare(played1.card, played2.card, this.trumpSuit, leadSuit); })[3].seat; return winner; } /* * Returns the number of tricks declarer has won */ get declarerTricks(): number { let trickCount = Math.floor(this.boardState.cards.length / 4); let result = 0; let sortTrick = (trick) => { let leadSuit = trick[0].card.suit; return trick.sort((played1, played2) => Card.compare(played1.card, played2.card, this.trumpSuit, leadSuit)); }; for (let i = 0; i < trickCount; i ++) { let trick = this.boardState.cards.slice(i * 4, (i * 4) + 4); let winner = sortTrick(trick)[3].seat; if ((winner === this.declarer) || Seat.isPartner(this.declarer, winner)) result ++; } return result; } /** * Returns true when no more cards can be played */ get playHasEnded(): boolean { return (this.boardState.cards.length === Seat.all().reduce((total, seat) => total + this.hands[seat].length, 0)); } /** * Returns true if this card has already been played */ hasBeenPlayed(card) { return this.boardState.cards .some((played) => Card.equals(card, played.card)); } /** * Returns the seat of the lead card */ get declarer(): Seat { if (!this.biddingHasEnded) throw new Error("the bidding has not ended yet"); if (this.lastCall) { for (let i = 0; i < this.boardState.bids.length - 1; i ++) { if (this.boardState.bids[i].suit === this.lastCall.suit) return Seat.rotate(this.boardState.dealer, i); } } throw new Error("declarer not found"); } get dummy(): Seat { return Seat.rotate(this.declarer, 2); } /** * Returns the seat of the lead card */ get leader(): Seat { if (this.boardState.cards.length < 4) return Seat.rotate(this.declarer, 1); else return this.previousTrickWinner; } /** * Returns the seat of the player who's turn it is to play */ get nextPlayer(): Seat { if (!this.biddingHasEnded) return Seat.rotate(this.boardState.dealer, this.boardState.bids.length); else if (!this.lastCall) return undefined; else return Seat.rotate(this.leader, this.currentTrick.length); } /* * Returns an array of the cards which can legally be played */ get legalCards() { let hand = this.boardState.hands[this.nextPlayer]; let available = hand.filter((card) => !this.hasBeenPlayed(card)); let trick = this.currentTrick; if ((trick.length > 0) && (trick.length < 4)) { let lead = trick[0].card; let followers = available.filter((card) => (card.suit === lead.suit)); if (followers.length > 0) return followers; } return available; } /* * Returns an array of the cards which can legally be played */ getLegalBids() { return Bid.all().filter((bid) => !validateBid(bid, this)); } /* * Converts the hands to their PBN string */ toPBN() { var result = Seat.toPBNString(this.dealer) + ':'; Seat.all().forEach((s, i) => { let seat = Seat.rotate(this.dealer, i); let cards = this.hands[seat] .filter(card => !this.hasBeenPlayed(card)); result = result + Card.toPBN(cards) + " "; }); return result.trim(); } }
frankwallis/redouble
src/model/game/board-query.js
JavaScript
mit
5,929
/* * @(#)Builder.java 2.0 11/01/11 * * Copyright 2011, Pontificia Universidad Javeriana, All rights reserved. * Takina and SIDRe PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package Control.Builder; import Abstraction.DEF; import Abstraction.Game; import Abstraction.WorldModel; import BESA.ExceptionBESA; import BESA.Kernel.Agent.AgentBESA; import BESA.Kernel.Agent.KernellAgentExceptionBESA; import BESA.Kernel.Agent.StructBESA; import BESA.Log.ReportBESA; import Control.Player.Behavior.PutOnGuard; import Control.Player.Behavior.RespondGuard; import Control.Player.Behavior.TravelGuard; import Control.Player.Data.PlayerState; import Control.Player.PlayerAgent; import java.util.logging.Level; import java.util.logging.Logger; /** * This represents the generalization the system builders. * * @author SIDRe - Pontificia Universidad Javeriana * @author Takina - Pontificia Universidad Javeriana * @version 2.0, 11/01/11 * @since JDK1.0 */ public abstract class Builder { /** * This the object to build. */ protected Game game; /** * Creates a new intance. */ public Builder() { game = new Game(); } /** * Creates a BESA agent. * * @return A reference to the agent that was created. */ protected AgentBESA createAgent(String plareAlias, WorldModel worldModel) { //--------------------------------------------------------------------// // Creates the agent struct. // //--------------------------------------------------------------------// StructBESA agnetStruct = new StructBESA(); try { //----------------------------------------------------------------// // Adds behaviors. // //----------------------------------------------------------------// agnetStruct.addBehavior("PlayerBehavior"); agnetStruct.addBehavior("PlayerTravelBehavior"); //----------------------------------------------------------------// // Binds guards. // //----------------------------------------------------------------// agnetStruct.bindGuard("PlayerBehavior",RespondGuard.class); agnetStruct.bindGuard("PlayerBehavior",PutOnGuard.class); agnetStruct.bindGuard("PlayerTravelBehavior",TravelGuard.class); } catch (ExceptionBESA ex) { ReportBESA.error(ex); } //--------------------------------------------------------------------// // Creates the agent state. // //--------------------------------------------------------------------// double agentPasswd = 0.91; PlayerState playerState = new PlayerState(worldModel); try { //--------------------------------------------------------------------// // Creates and starts the agent. // //--------------------------------------------------------------------// return new PlayerAgent(plareAlias, playerState, agnetStruct, agentPasswd); } catch (KernellAgentExceptionBESA ex) { Logger.getLogger(Builder.class.getName()).log(Level.SEVERE, null, ex); return null; } } /** * Gets the game object. */ public Game getGame() { return game; } /** * Builds the GUI. */ public abstract boolean buildGUI(); /** * Builds the model. */ public abstract boolean buildModel(DEF world); /** * Builds the player A. */ public abstract boolean buildPlayerA(); /** * Builds the player B. */ public abstract boolean buildPlayerB(); }
Coregraph/Ayllu
JigSaw - AYPUY - CS/BESA3/BESA-EXAM/PingPong/src/Control/Builder/Builder.java
Java
mit
3,932
<?php /* FOSUserBundle:Group:edit.html.twig */ class __TwigTemplate_5bdd3b40502a41310ed443a6c728c2375dea32069ae17151dfb34ad2c3e1855f extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig"); $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_fos_user_content($context, array $blocks = array()) { // line 4 $this->env->loadTemplate("FOSUserBundle:Group:edit_content.html.twig")->display($context); } public function getTemplateName() { return "FOSUserBundle:Group:edit.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 31 => 4, 28 => 3,); } }
Joomlamaster/connectionru
app/cache/prod/twig/5b/dd/3b40502a41310ed443a6c728c2375dea32069ae17151dfb34ad2c3e1855f.php
PHP
mit
1,233
<?php /* * This file is part of the BenGorUser package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\BenGorUser\User\Application\Command\ChangePassword; use BenGorUser\User\Application\Command\ChangePassword\ChangeUserPasswordCommand; use PhpSpec\ObjectBehavior; /** * Spec file of ChangeUserPasswordCommand class. * * @author Beñat Espiña <benatespina@gmail.com> * @author Gorka Laucirica <gorka.lauzirika@gmail.com> */ class ChangeUserPasswordCommandSpec extends ObjectBehavior { function it_creates_a_command() { $this->beConstructedWith('id', 'newPassword', 'oldPassword'); $this->shouldHaveType(ChangeUserPasswordCommand::class); $this->id()->shouldReturn('id'); $this->newPlainPassword()->shouldReturn('newPassword'); $this->oldPlainPassword()->shouldReturn('oldPassword'); } }
BenGor/User
spec/BenGorUser/User/Application/Command/ChangePassword/ChangeUserPasswordCommandSpec.php
PHP
mit
1,053
<TS language="ar" version="2.0"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>انقر بالزر الايمن لتعديل العنوان</translation> </message> <message> <source>Create a new address</source> <translation>انشأ عنوان جديد</translation> </message> <message> <source>&amp;New</source> <translation>&amp;جديد</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>قم بنسخ القوانين المختارة لحافظة النظام</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;نسخ</translation> </message> <message> <source>C&amp;lose</source> <translation>&amp;اغلاق</translation> </message> <message> <source>&amp;Copy Address</source> <translation>انسخ العنوان</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>حذف العنوان المحدد من القائمة</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>تحميل البيانات في علامة التبويب الحالية إلى ملف.</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;تصدير</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;أمسح</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>اختر العنوان الذي سترسل له العملات</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>اختر العنوان الذي تستقبل عليه العملات</translation> </message> <message> <source>C&amp;hoose</source> <translation>&amp;اختر</translation> </message> <message> <source>Sending addresses</source> <translation>ارسال العناوين</translation> </message> <message> <source>Receiving addresses</source> <translation>استقبال العناوين</translation> </message> <message> <source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>هذه هي عناوين Bitcion التابعة لك من أجل إرسال الدفعات. تحقق دائما من المبلغ و عنوان المرسل المستقبل قبل إرسال العملات</translation> </message> <message> <source>These are your Bitcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>هذه هي عناوين Bitcion التابعة لك من أجل إستقبال الدفعات. ينصح استخدام عنوان جديد من أجل كل صفقة</translation> </message> <message> <source>Copy &amp;Label</source> <translation>نسخ &amp;الوصف</translation> </message> <message> <source>&amp;Edit</source> <translation>تعديل</translation> </message> <message> <source>Export Address List</source> <translation>تصدير قائمة العناوين</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>ملف مفصول بفواصل (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>فشل التصدير</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>لقد حدث خطأ أثناء حفظ قائمة العناوين إلى %1. يرجى المحاولة مرة أخرى.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>وصف</translation> </message> <message> <source>Address</source> <translation>عنوان</translation> </message> <message> <source>(no label)</source> <translation>(لا وصف)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>حوار جملة السر</translation> </message> <message> <source>Enter passphrase</source> <translation>ادخل كلمة المرور</translation> </message> <message> <source>New passphrase</source> <translation>كلمة مرور جديدة</translation> </message> <message> <source>Repeat new passphrase</source> <translation>ادخل كلمة المرور الجديدة مرة أخرى</translation> </message> <message> <source>Encrypt wallet</source> <translation>تشفير المحفظة</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>هذه العملية تحتاج كلمة مرور محفظتك لفتحها</translation> </message> <message> <source>Unlock wallet</source> <translation>إفتح المحفظة</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>هذه العملية تحتاج كلمة مرور محفظتك لفك تشفيرها </translation> </message> <message> <source>Decrypt wallet</source> <translation>فك تشفير المحفظة</translation> </message> <message> <source>Change passphrase</source> <translation>تغيير كلمة المرور</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>تأكيد تشفير المحفظة</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>تحذير: إذا قمت بتشفير محفظتك وفقدت كلمة المرور الخاص بك, ستفقد كل عملات BITCOINS الخاصة بك.</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>هل أنت متأكد من رغبتك في تشفير محفظتك ؟</translation> </message> <message> <source>BCH Unlimited will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>بتكوين سوف يغلق الآن لإنهاء عملية التشفير. تذكر أن التشفير لا يستطيع حماية محفظتك تمامًا من السرقة من خلال البرمجيات الخبيثة التي تصيب جهازك </translation> </message> <message> <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> <source>Warning: The Caps Lock key is on!</source> <translation>تحذير: مفتاح الحروف الكبيرة مفعل</translation> </message> <message> <source>Wallet encrypted</source> <translation>محفظة مشفرة</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>أدخل عبارة مرور جديدة إلى المحفظة. الرجاء استخدام عبارة مرور تتكون من10 حروف عشوائية على الاقل, أو أكثر من 7 كلمات</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>أدخل كلمة المرور القديمة والجديدة للمحفظة.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>فشل تشفير المحفظة</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>فشل تشفير المحفظة بسبب خطأ داخلي. لم يتم تشفير محفظتك.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>كلمتي المرور ليستا متطابقتان</translation> </message> <message> <source>Wallet unlock failed</source> <translation>فشل فتح المحفظة</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>كلمة المرور التي تم إدخالها لفك تشفير المحفظة غير صحيحة.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>فشل فك التشفير المحفظة</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>لقد تم تغير عبارة مرور المحفظة بنجاح</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>التوقيع و الرسائل</translation> </message> <message> <source>Synchronizing with network...</source> <translation>مزامنة مع الشبكة ...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;نظرة عامة</translation> </message> <message> <source>Node</source> <translation>جهاز</translation> </message> <message> <source>Show general overview of wallet</source> <translation>إظهار نظرة عامة على المحفظة</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;المعاملات</translation> </message> <message> <source>Browse transaction history</source> <translation>تصفح سجل المعاملات</translation> </message> <message> <source>E&amp;xit</source> <translation>خروج</translation> </message> <message> <source>Quit application</source> <translation>الخروج من التطبيق</translation> </message> <message> <source>About &amp;Qt</source> <translation>عن</translation> </message> <message> <source>Show information about Qt</source> <translation>اظهر المعلومات</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;خيارات ...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;تشفير المحفظة</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;نسخ احتياط للمحفظة</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;تغيير كلمة المرور</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>ارسال العناوين.</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>استقبال العناوين</translation> </message> <message> <source>Open &amp;URI...</source> <translation>افتح &amp;URI...</translation> </message> <message> <source>BCH Unlimited client</source> <translation>عميل bitcion core</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>استيراد كتل من القرص ...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>إعادة الفهرسة الكتل على القرص ...</translation> </message> <message> <source>Send coins to a Bitcoin address</source> <translation>ارسل عملات الى عنوان بيتكوين</translation> </message> <message> <source>Backup wallet to another location</source> <translation>احفظ نسخة احتياطية للمحفظة في مكان آخر</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>تغيير كلمة المرور المستخدمة لتشفير المحفظة</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;نافذة المعالجة</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>إفتح وحدة التصحيح و التشخيص</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;التحقق من الرسالة...</translation> </message> <message> <source>Bitcoin</source> <translation>بت كوين</translation> </message> <message> <source>Wallet</source> <translation>محفظة</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;ارسل</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;استقبل</translation> </message> <message> <source>Show information about BCH Unlimited</source> <translation> اظهار معلومات حول bitcion core</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;عرض / اخفاء</translation> </message> <message> <source>Show or hide the main Window</source> <translation>عرض او اخفاء النافذة الرئيسية</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>تشفير المفتاح الخاص بمحفظتك</translation> </message> <message> <source>Sign messages with your Bitcoin addresses to prove you own them</source> <translation>وقَع الرسائل بواسطة ال: Bitcoin الخاص بك لإثبات امتلاكك لهم</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Bitcoin addresses</source> <translation>تحقق من الرسائل للتأكد من أنَها وُقعت برسائل Bitcoin محدَدة</translation> </message> <message> <source>&amp;File</source> <translation>&amp;ملف</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;الاعدادات</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;مساعدة</translation> </message> <message> <source>Tabs toolbar</source> <translation>شريط أدوات علامات التبويب</translation> </message> <message> <source>BCH Unlimited</source> <translation>جوهر البيت كوين</translation> </message> <message> <source>Request payments (generates QR codes and %1 URIs)</source> <translation>أطلب دفعات (يولد كودات الرمز المربع وبيت كوين: العناوين المعطاة)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>عرض قائمة عناوين الإرسال المستخدمة والملصقات</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>عرض قائمة عناوين الإستقبال المستخدمة والملصقات</translation> </message> <message> <source>Open a %1 URI or payment request</source> <translation>فتح URI : Bitcoin أو طلب دفع</translation> </message> <message> <source>&amp;About BCH Unlimited</source> <translation>حول bitcoin core</translation> </message> <message> <source>Modify configuration options for BCH Unlimited</source> <translation>تغيير خيارات الإعداد لأساس Bitcoin</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>عرض قائمة عناوين الإرسال المستخدمة والملصقات</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>عرض قائمة عناوين الإستقبال المستخدمة والملصقات</translation> </message> <message> <source>Open a %1: URI or payment request</source> <translation>فتح URI : %1 أو طلب دفع</translation> </message> <message> <source>%1 and %2</source> <translation>%1 و %2</translation> </message> <message> <source>Error</source> <translation>خطأ</translation> </message> <message> <source>Warning</source> <translation>تحذير</translation> </message> <message> <source>Information</source> <translation>معلومات</translation> </message> <message> <source>Up to date</source> <translation>محدث</translation> </message> <message> <source>Catching up...</source> <translation>اللحاق بالركب ...</translation> </message> <message> <source>Sent transaction</source> <translation>المعاملات المرسلة</translation> </message> <message> <source>Incoming transaction</source> <translation>المعاملات الواردة</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>المحفظة &lt;b&gt;مشفرة&lt;/b&gt; و &lt;b&gt;مفتوحة&lt;/b&gt; حاليا</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>المحفظة &lt;b&gt;مشفرة&lt;/b&gt; و &lt;b&gt;مقفلة&lt;/b&gt; حاليا</translation> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation>تنبيه من الشبكة</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>الكمية :</translation> </message> <message> <source>Amount:</source> <translation>القيمة :</translation> </message> <message> <source>Priority:</source> <translation>افضلية :</translation> </message> <message> <source>Fee:</source> <translation>رسوم :</translation> </message> <message> <source>After Fee:</source> <translation>بعد الرسوم :</translation> </message> <message> <source>Change:</source> <translation>تعديل :</translation> </message> <message> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <source>Date</source> <translation>التاريخ</translation> </message> <message> <source>Confirmations</source> <translation>تأكيد</translation> </message> <message> <source>Confirmed</source> <translation>تأكيد</translation> </message> <message> <source>Priority</source> <translation>أفضلية</translation> </message> <message> <source>Copy address</source> <translation> انسخ عنوان</translation> </message> <message> <source>Copy label</source> <translation> انسخ التسمية</translation> </message> <message> <source>Copy amount</source> <translation>نسخ الكمية</translation> </message> <message> <source>Copy transaction ID</source> <translation>نسخ رقم العملية</translation> </message> <message> <source>Copy quantity</source> <translation>نسخ الكمية </translation> </message> <message> <source>Copy fee</source> <translation>نسخ الرسوم</translation> </message> <message> <source>Copy after fee</source> <translation>نسخ بعد الرسوم</translation> </message> <message> <source>Copy priority</source> <translation>نسخ الافضلية</translation> </message> <message> <source>Copy change</source> <translation>نسخ التعديل</translation> </message> <message> <source>highest</source> <translation>الاعلى</translation> </message> <message> <source>higher</source> <translation>اعلى</translation> </message> <message> <source>high</source> <translation>عالي</translation> </message> <message> <source>medium-high</source> <translation>متوسط-مرتفع</translation> </message> <message> <source>low</source> <translation>منخفض</translation> </message> <message> <source>lower</source> <translation>أدنى</translation> </message> <message> <source>lowest</source> <translation>الأدنى</translation> </message> <message> <source>none</source> <translation>لا شيء</translation> </message> <message> <source>yes</source> <translation>نعم</translation> </message> <message> <source>no</source> <translation>لا</translation> </message> <message> <source>(no label)</source> <translation>(لا وصف)</translation> </message> <message> <source>(change)</source> <translation>(تغير)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>عدل العنوان</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;وصف</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;العنوان</translation> </message> <message> <source>New receiving address</source> <translation>عنوان أستلام جديد</translation> </message> <message> <source>New sending address</source> <translation>عنوان إرسال جديد</translation> </message> <message> <source>Edit receiving address</source> <translation>تعديل عنوان الأستلام</translation> </message> <message> <source>Edit sending address</source> <translation>تعديل عنوان الارسال</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>هدا العنوان "%1" موجود مسبقا في دفتر العناوين</translation> </message> <message> <source>Could not unlock wallet.</source> <translation> يمكن فتح المحفظة.</translation> </message> <message> <source>New key generation failed.</source> <translation>فشل توليد مفتاح جديد.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>سيتم انشاء دليل بيانات جديد</translation> </message> <message> <source>name</source> <translation>الاسم</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>لا يمكن انشاء دليل بيانات هنا .</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>BCH Unlimited</source> <translation>جوهر البيت كوين</translation> </message> <message> <source>version</source> <translation>النسخة</translation> </message> <message> <source>About BCH Unlimited</source> <translation>عن جوهر البيت كوين</translation> </message> <message> <source>Usage:</source> <translation>المستخدم</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>أهلا</translation> </message> <message> <source>Use the default data directory</source> <translation>استخدام دليل البانات الافتراضي</translation> </message> <message> <source>Use a custom data directory:</source> <translation>استخدام دليل بيانات مخصص:</translation> </message> <message> <source>BCH Unlimited</source> <translation>جوهر البيت كوين</translation> </message> <message> <source>Error</source> <translation>خطأ</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Select payment request file</source> <translation>حدد ملف طلب الدفع</translation> </message> <message> <source>Select payment request file to open</source> <translation>حدد ملف طلب الدفع لفتحه</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>خيارات ...</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;الرئيسي</translation> </message> <message> <source>MB</source> <translation>م ب</translation> </message> <message> <source>Accept connections from outside</source> <translation>إقبل التواصل من الخارج</translation> </message> <message> <source>Third party transaction URLs</source> <translation>عنوان النطاق للطرف الثالث</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;استعادة الخيارات</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;الشبكة</translation> </message> <message> <source>W&amp;allet</source> <translation>&amp;محفظة</translation> </message> <message> <source>Expert</source> <translation>تصدير</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>بروكسي &amp;اي بي:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;المنفذ:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>منفذ البروكسي (مثلا 9050)</translation> </message> <message> <source>&amp;Window</source> <translation>نافذه</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;عرض</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>واجهة المستخدم &amp;اللغة:</translation> </message> <message> <source>&amp;OK</source> <translation>تم</translation> </message> <message> <source>&amp;Cancel</source> <translation>الغاء</translation> </message> <message> <source>default</source> <translation>الافتراضي</translation> </message> <message> <source>none</source> <translation>لا شيء</translation> </message> <message> <source>Confirm options reset</source> <translation>تأكيد استعادة الخيارات</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>عنوان الوكيل توفيره غير صالح.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>نمودج</translation> </message> <message> <source>Available:</source> <translation>متوفر</translation> </message> <message> <source>Pending:</source> <translation>معلق:</translation> </message> <message> <source>Immature:</source> <translation>غير ناضجة</translation> </message> <message> <source>Total:</source> <translation>المجموع:</translation> </message> <message> <source>Your current total balance</source> <translation>رصيدك الكلي الحالي</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>Bad response from server %1</source> <translation>استجابة سيئة من الملقم %1</translation> </message> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <source>%1 h</source> <translation>%1 ساعة</translation> </message> <message> <source>%1 m</source> <translation>%1 دقيقة</translation> </message> <message> <source>N/A</source> <translation>غير معروف</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>&amp;حفظ الصورة</translation> </message> <message> <source>&amp;Copy Image</source> <translation>&amp;نسخ الصورة</translation> </message> <message> <source>Save QR Code</source> <translation>حفظ رمز الاستجابة السريعة QR</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>صورة PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation>اسم العميل</translation> </message> <message> <source>N/A</source> <translation>غير معروف</translation> </message> <message> <source>Client version</source> <translation>نسخه العميل</translation> </message> <message> <source>&amp;Information</source> <translation>المعلومات</translation> </message> <message> <source>Debug window</source> <translation>نافذة المعالجة</translation> </message> <message> <source>General</source> <translation>عام</translation> </message> <message> <source>Startup time</source> <translation>وقت البدء</translation> </message> <message> <source>Network</source> <translation>الشبكه</translation> </message> <message> <source>Name</source> <translation>الاسم</translation> </message> <message> <source>Number of connections</source> <translation>عدد الاتصالات</translation> </message> <message> <source>Received</source> <translation>إستقبل</translation> </message> <message> <source>Sent</source> <translation>تم الإرسال</translation> </message> <message> <source>Direction</source> <translation>جهة</translation> </message> <message> <source>Services</source> <translation>خدمات</translation> </message> <message> <source>Last Send</source> <translation>آخر استقبال</translation> </message> <message> <source>Last Receive</source> <translation>آخر إرسال</translation> </message> <message> <source>&amp;Open</source> <translation>الفتح</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;حركة مرور الشبكة</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;مسح</translation> </message> <message> <source>Totals</source> <translation>المجاميع</translation> </message> <message> <source>In:</source> <translation>داخل:</translation> </message> <message> <source>Out:</source> <translation>خارج:</translation> </message> <message> <source>Build date</source> <translation>وقت البناء</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>استخدم اسهم الاعلى و الاسفل للتنقل بين السجلات و &lt;b&gt;Ctrl-L&lt;/b&gt; لمسح الشاشة</translation> </message> <message> <source>%1 B</source> <translation>%1 بايت</translation> </message> <message> <source>%1 KB</source> <translation>%1 كيلو بايت</translation> </message> <message> <source>%1 MB</source> <translation>%1 ميقا بايت</translation> </message> <message> <source>%1 GB</source> <translation>%1 قيقا بايت</translation> </message> <message> <source>Yes</source> <translation>نعم</translation> </message> <message> <source>No</source> <translation>لا</translation> </message> <message> <source>Unknown</source> <translation>غير معرف</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;القيمة</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;وصف :</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;رسالة:</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>مسح كل حقول النموذج المطلوبة</translation> </message> <message> <source>Clear</source> <translation>مسح</translation> </message> <message> <source>Requested payments history</source> <translation>سجل طلبات الدفع</translation> </message> <message> <source>Show</source> <translation>عرض</translation> </message> <message> <source>Remove</source> <translation>ازل</translation> </message> <message> <source>Copy label</source> <translation> انسخ التسمية</translation> </message> <message> <source>Copy message</source> <translation>انسخ الرسالة</translation> </message> <message> <source>Copy amount</source> <translation>نسخ الكمية</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>رمز كيو ار</translation> </message> <message> <source>Copy &amp;URI</source> <translation>نسخ &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>نسخ &amp;العنوان</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;حفظ الصورة</translation> </message> <message> <source>Payment information</source> <translation>معلومات الدفع</translation> </message> <message> <source>URI</source> <translation> URI</translation> </message> <message> <source>Address</source> <translation>عنوان</translation> </message> <message> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <source>Label</source> <translation>وصف</translation> </message> <message> <source>Message</source> <translation>رسالة </translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>التاريخ</translation> </message> <message> <source>Label</source> <translation>وصف</translation> </message> <message> <source>Message</source> <translation>رسالة </translation> </message> <message> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <source>(no label)</source> <translation>(لا وصف)</translation> </message> <message> <source>(no message)</source> <translation>( لا رسائل )</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>إرسال Coins</translation> </message> <message> <source>automatically selected</source> <translation>اختيار تلقائيا</translation> </message> <message> <source>Insufficient funds!</source> <translation>الرصيد غير كافي!</translation> </message> <message> <source>Quantity:</source> <translation>الكمية :</translation> </message> <message> <source>Amount:</source> <translation>القيمة :</translation> </message> <message> <source>Priority:</source> <translation>افضلية :</translation> </message> <message> <source>Fee:</source> <translation>رسوم :</translation> </message> <message> <source>After Fee:</source> <translation>بعد الرسوم :</translation> </message> <message> <source>Change:</source> <translation>تعديل :</translation> </message> <message> <source>Transaction Fee:</source> <translation>رسوم المعاملة:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>إرسال إلى عدة مستلمين في وقت واحد</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>أضافة &amp;مستلم</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>مسح كل حقول النموذج المطلوبة</translation> </message> <message> <source>Clear &amp;All</source> <translation>مسح الكل</translation> </message> <message> <source>Balance:</source> <translation>الرصيد:</translation> </message> <message> <source>Confirm the send action</source> <translation>تأكيد الإرسال</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;ارسال</translation> </message> <message> <source>Confirm send coins</source> <translation>تأكيد الإرسال Coins</translation> </message> <message> <source>%1 to %2</source> <translation>%1 الى %2</translation> </message> <message> <source>Copy quantity</source> <translation>نسخ الكمية </translation> </message> <message> <source>Copy amount</source> <translation>نسخ الكمية</translation> </message> <message> <source>Copy fee</source> <translation>نسخ الرسوم</translation> </message> <message> <source>Copy after fee</source> <translation>نسخ بعد الرسوم</translation> </message> <message> <source>Copy priority</source> <translation>نسخ الافضلية</translation> </message> <message> <source>Copy change</source> <translation>نسخ التعديل</translation> </message> <message> <source>or</source> <translation>أو</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>المبلغ المدفوع يجب ان يكون اكبر من 0</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>القيمة تتجاوز رصيدك</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>المجموع يتجاوز رصيدك عندما يتم اضافة %1 رسوم العملية</translation> </message> <message> <source>(no label)</source> <translation>(لا وصف)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;القيمة</translation> </message> <message> <source>Pay &amp;To:</source> <translation>ادفع &amp;الى :</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>إدخال تسمية لهذا العنوان لإضافته إلى دفتر العناوين الخاص بك</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;وصف :</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>انسخ العنوان من لوحة المفاتيح</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Message:</source> <translation>الرسائل</translation> </message> <message> <source>Pay To:</source> <translation>ادفع &amp;الى :</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>لا توقف عمل الكمبيوتر حتى تختفي هذه النافذة</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>&amp;Sign Message</source> <translation>&amp;توقيع الرسالة</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>انسخ العنوان من لوحة المفاتيح</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>ادخل الرسالة التي تريد توقيعها هنا</translation> </message> <message> <source>Signature</source> <translation>التوقيع</translation> </message> <message> <source>Sign the message to prove you own this Bitcoin address</source> <translation>وقع الرسالة لتثبت انك تمتلك عنوان البت كوين هذا</translation> </message> <message> <source>Sign &amp;Message</source> <translation>توقيع $الرسالة</translation> </message> <message> <source>Clear &amp;All</source> <translation>مسح الكل</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;تحقق رسالة</translation> </message> <message> <source>Verify &amp;Message</source> <translation>تحقق &amp;الرسالة</translation> </message> <message> <source>Click "Sign Message" to generate signature</source> <translation>اضغط "توقيع الرسالة" لتوليد التوقيع</translation> </message> <message> <source>The entered address is invalid.</source> <translation>العنوان المدخل غير صالح</translation> </message> <message> <source>Please check the address and try again.</source> <translation>الرجاء التأكد من العنوان والمحاولة مرة اخرى</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>العنوان المدخل لا يشير الى مفتاح</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>تم الغاء عملية فتح المحفظة</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>المفتاح الخاص للعنوان المدخل غير موجود.</translation> </message> <message> <source>Message signing failed.</source> <translation>فشل توقيع الرسالة.</translation> </message> <message> <source>Message signed.</source> <translation>الرسالة موقعة.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>فضلا تاكد من التوقيع وحاول مرة اخرى</translation> </message> <message> <source>Message verification failed.</source> <translation>فشلت عملية التأكد من الرسالة.</translation> </message> <message> <source>Message verified.</source> <translation>تم تأكيد الرسالة.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>BCH Unlimited</source> <translation>جوهر البيت كوين</translation> </message> <message> <source>The BCH Unlimited developers</source> <translation>مطوري جوهر البيت كوين</translation> </message> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>مفتوح حتى %1</translation> </message> <message> <source>conflicted</source> <translation>يتعارض</translation> </message> <message> <source>%1/offline</source> <translation>%1 غير متواجد</translation> </message> <message> <source>%1/unconfirmed</source> <translation>غير مؤكدة/%1</translation> </message> <message> <source>%1 confirmations</source> <translation>تأكيد %1</translation> </message> <message> <source>Status</source> <translation>الحالة.</translation> </message> <message> <source>Date</source> <translation>التاريخ</translation> </message> <message> <source>Source</source> <translation>المصدر</translation> </message> <message> <source>Generated</source> <translation>تم اصداره.</translation> </message> <message> <source>From</source> <translation>من</translation> </message> <message> <source>To</source> <translation>الى</translation> </message> <message> <source>own address</source> <translation>عنوانه</translation> </message> <message> <source>label</source> <translation>علامة</translation> </message> <message> <source>not accepted</source> <translation>غير مقبولة</translation> </message> <message> <source>Debit</source> <translation>دين</translation> </message> <message> <source>Transaction fee</source> <translation>رسوم المعاملة</translation> </message> <message> <source>Message</source> <translation>رسالة </translation> </message> <message> <source>Comment</source> <translation>تعليق</translation> </message> <message> <source>Transaction ID</source> <translation>رقم المعاملة</translation> </message> <message> <source>Merchant</source> <translation>تاجر</translation> </message> <message> <source>Transaction</source> <translation>معاملة</translation> </message> <message> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <source>true</source> <translation>صحيح</translation> </message> <message> <source>false</source> <translation>خاطئ</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, لم يتم حتى الآن البث بنجاح</translation> </message> <message> <source>unknown</source> <translation>غير معروف</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>تفاصيل المعاملة</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>يبين هذا الجزء وصفا مفصلا لهده المعاملة</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>التاريخ</translation> </message> <message> <source>Type</source> <translation>النوع</translation> </message> <message> <source>Open until %1</source> <translation>مفتوح حتى %1</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>لم يتم تلقى هذه الكتلة (Block) من قبل أي العقد الأخرى وربما لن تكون مقبولة!</translation> </message> <message> <source>Generated but not accepted</source> <translation>ولدت ولكن لم تقبل</translation> </message> <message> <source>Offline</source> <translation>غير متصل</translation> </message> <message> <source>Label</source> <translation>وصف</translation> </message> <message> <source>Conflicted</source> <translation>يتعارض</translation> </message> <message> <source>Received with</source> <translation>استقبل مع</translation> </message> <message> <source>Received from</source> <translation>استقبل من</translation> </message> <message> <source>Sent to</source> <translation>أرسل إلى</translation> </message> <message> <source>Payment to yourself</source> <translation>دفع لنفسك</translation> </message> <message> <source>Mined</source> <translation>Mined</translation> </message> <message> <source>(n/a)</source> <translation>غير متوفر</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>حالة المعاملة. تحوم حول هذا الحقل لعرض عدد التأكيدات.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>التاريخ والوقت الذي تم فيه تلقي المعاملة.</translation> </message> <message> <source>Type of transaction.</source> <translation>نوع المعاملات</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>المبلغ الذي أزيل أو أضيف الى الرصيد</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>الكل</translation> </message> <message> <source>Today</source> <translation>اليوم</translation> </message> <message> <source>This week</source> <translation>هدا الاسبوع</translation> </message> <message> <source>This month</source> <translation>هدا الشهر</translation> </message> <message> <source>Last month</source> <translation>الشهر الماضي</translation> </message> <message> <source>This year</source> <translation>هدا العام</translation> </message> <message> <source>Range...</source> <translation>المدى...</translation> </message> <message> <source>Received with</source> <translation>استقبل مع</translation> </message> <message> <source>Sent to</source> <translation>أرسل إلى</translation> </message> <message> <source>To yourself</source> <translation>إليك</translation> </message> <message> <source>Mined</source> <translation>Mined</translation> </message> <message> <source>Other</source> <translation>اخرى</translation> </message> <message> <source>Enter address or label to search</source> <translation>ادخل عنوان أووصف للبحث</translation> </message> <message> <source>Min amount</source> <translation>الحد الأدنى</translation> </message> <message> <source>Copy address</source> <translation> انسخ عنوان</translation> </message> <message> <source>Copy label</source> <translation> انسخ التسمية</translation> </message> <message> <source>Copy amount</source> <translation>نسخ الكمية</translation> </message> <message> <source>Copy transaction ID</source> <translation>نسخ رقم العملية</translation> </message> <message> <source>Edit label</source> <translation>عدل الوصف</translation> </message> <message> <source>Show transaction details</source> <translation>عرض تفاصيل المعاملة</translation> </message> <message> <source>Exporting Failed</source> <translation>فشل التصدير</translation> </message> <message> <source>Exporting Successful</source> <translation>نجح التصدير</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>ملف مفصول بفواصل (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>تأكيد</translation> </message> <message> <source>Date</source> <translation>التاريخ</translation> </message> <message> <source>Type</source> <translation>النوع</translation> </message> <message> <source>Label</source> <translation>وصف</translation> </message> <message> <source>Address</source> <translation>عنوان</translation> </message> <message> <source>ID</source> <translation>العنوان</translation> </message> <message> <source>Range:</source> <translation>المدى:</translation> </message> <message> <source>to</source> <translation>الى</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>إرسال Coins</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;تصدير</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>تحميل البيانات في علامة التبويب الحالية إلى ملف.</translation> </message> <message> <source>Backup Wallet</source> <translation>نسخ احتياط للمحفظة</translation> </message> <message> <source>Backup Failed</source> <translation>فشل النسخ الاحتياطي</translation> </message> <message> <source>Backup Successful</source> <translation>نجاح النسخ الاحتياطي</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>خيارات: </translation> </message> <message> <source>Specify data directory</source> <translation>حدد مجلد المعلومات</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>قبول الاتصالات من خارج</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>تحذير: مساحة القرص منخفضة</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>فشل في الاستماع على أي منفذ. استخدام الاستماع = 0 إذا كنت تريد هذا.</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>عنوان اونيون غير صحيح : '%s'</translation> </message> <message> <source>Verifying wallet...</source> <translation>التحقق من المحفظة ...</translation> </message> <message> <source>Wallet options:</source> <translation>خيارات المحفظة :</translation> </message> <message> <source>Information</source> <translation>معلومات</translation> </message> <message> <source>Signing transaction failed</source> <translation>فشل توقيع المعاملة</translation> </message> <message> <source>Transaction amount too small</source> <translation>قيمة العملية صغيره جدا</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>يجب ان يكون قيمة العملية بالموجب</translation> </message> <message> <source>Transaction too large</source> <translation>المعاملة طويلة جدا</translation> </message> <message> <source>Warning</source> <translation>تحذير</translation> </message> <message> <source>This help message</source> <translation>رسالة المساعدة هذه</translation> </message> <message> <source>Loading addresses...</source> <translation>تحميل العنوان</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطأ عند تنزيل wallet.dat: المحفظة تالفة</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>خطأ عند تنزيل wallet.dat</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>عنوان البروكسي غير صحيح : '%s'</translation> </message> <message> <source>Make the wallet broadcast transactions</source> <translation>إنتاج معاملات بث المحفظة</translation> </message> <message> <source>Insufficient funds</source> <translation>اموال غير كافية</translation> </message> <message> <source>Loading block index...</source> <translation>تحميل مؤشر الكتلة</translation> </message> <message> <source>Loading wallet...</source> <translation>تحميل المحفظه</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>لا يمكن تخفيض قيمة المحفظة</translation> </message> <message> <source>Cannot write default address</source> <translation>لايمكن كتابة العنوان الافتراضي</translation> </message> <message> <source>Rescanning...</source> <translation>إعادة مسح</translation> </message> <message> <source>Done loading</source> <translation>انتهاء التحميل</translation> </message> <message> <source>Error</source> <translation>خطأ</translation> </message> </context> </TS>
BitcoinUnlimited/BitcoinUnlimited
src/qt/locale/bitcoin_ar.ts
TypeScript
mit
65,039
require 'test_helper' class MyController < DeviseController end class HelpersTest < ActionController::TestCase tests MyController def setup @mock_warden = OpenStruct.new @controller.request.env['warden'] = @mock_warden @controller.request.env['devise.mapping'] = Devise.mappings[:user] end test 'get resource name from env' do assert_equal :user, @controller.resource_name end test 'get resource class from env' do assert_equal User, @controller.resource_class end test 'get resource instance variable from env' do @controller.instance_variable_set(:@user, user = User.new) assert_equal user, @controller.resource end test 'set resource instance variable from env' do user = @controller.send(:resource_class).new @controller.send(:resource=, user) assert_equal user, @controller.send(:resource) assert_equal user, @controller.instance_variable_get(:@user) end test 'resources methods are not controller actions' do assert @controller.class.action_methods.empty? end test 'require no authentication tests current mapping' do @mock_warden.expects(:authenticate?).with(:rememberable, :token_authenticatable, :scope => :user).returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication end test 'require no authentication only checks if already authenticated if no inputs strategies are available' do Devise.mappings[:user].expects(:no_input_strategies).returns([]) @mock_warden.expects(:authenticate?).never @mock_warden.expects(:authenticated?).with(:user).once.returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication end test 'require no authentication sets a flash message' do @mock_warden.expects(:authenticate?).with(:rememberable, :token_authenticatable, :scope => :user).returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication assert flash[:alert] == I18n.t("devise.failure.already_authenticated") end test 'signed in resource returns signed in resource for current scope' do @mock_warden.expects(:authenticate).with(:scope => :user).returns(User.new) assert_kind_of User, @controller.signed_in_resource end test 'is a devise controller' do assert @controller.devise_controller? end test 'does not issue blank flash messages' do MyController.send(:public, :set_flash_message) I18n.stubs(:t).returns(' ') @controller.set_flash_message :notice, :send_instructions assert flash[:notice].nil? MyController.send(:protected, :set_flash_message) end test 'issues non-blank flash messages normally' do MyController.send(:public, :set_flash_message) I18n.stubs(:t).returns('non-blank') @controller.set_flash_message :notice, :send_instructions assert flash[:notice] == 'non-blank' MyController.send(:protected, :set_flash_message) end test 'navigational_formats not returning a wild card' do MyController.send(:public, :navigational_formats) Devise.navigational_formats = [:"*/*", :html] assert_not @controller.navigational_formats.include?(:"*/*") MyController.send(:protected, :navigational_formats) end end
leereilly/devise
test/controllers/internal_helpers_test.rb
Ruby
mit
3,484
/* * Example - Run code contain within transactions * * * Execute it with `node index.js` */ var async = require('async') var VM = require('./../../index.js') var Account = require('ethereumjs-account') var Transaction = require('ethereumjs-tx') var Trie = require('merkle-patricia-tree') var rlp = require('rlp') var utils = require('ethereumjs-util') // creating a trie that just resides in memory var stateTrie = new Trie() // create a new VM instance var vm = new VM({state: stateTrie}) // import the key pair // pre-generated (saves time) // used to sign transactions and generate addresses var keyPair = require('./key-pair') var createdAddress // Transaction to initalize the name register, in this case // it will register the sending address as 'null_radix' // Notes: // - In a transaction, all strings as interpeted as hex // - A transaction has the fiels: // - nonce // - gasPrice // - gasLimit // - data var rawTx1 = require('./raw-tx1') // 2nd Transaction var rawTx2 = require('./raw-tx2') // sets up the initial state and runs the callback when complete function setup (cb) { // the address we are sending from var publicKeyBuf = new Buffer(keyPair.publicKey, 'hex') var address = utils.pubToAddress(publicKeyBuf, true) // create a new account var account = new Account() // give the account some wei. // Note: this needs to be a `Buffer` or a string. All // strings need to be in hex. account.balance = '0xf00000000000000001' // store in the trie stateTrie.put(address, account.serialize(), cb) } // runs a transaction through the vm function runTx (raw, cb) { // create a new transaction out of the json var tx = new Transaction(raw) // tx.from tx.sign(new Buffer(keyPair.secretKey, 'hex')) console.log('----running tx-------') // run the tx \o/ vm.runTx({ tx: tx }, function (err, results) { createdAddress = results.createdAddress // log some results console.log('gas used: ' + results.gasUsed.toString()) console.log('returned: ' + results.vm.return.toString('hex')) if (createdAddress) { console.log('address created: ' + createdAddress.toString('hex')) } cb(err) }) } var storageRoot // used later // Now lets look at what we created. The transaction // should have created a new account for the contranct // in the trie.Lets test to see if it did. function checkResults (cb) { // fetch the new account from the trie. stateTrie.get(createdAddress, function (err, val) { var account = new Account(val) storageRoot = account.stateRoot // used later! :) console.log('------results------') console.log('nonce: ' + account.nonce.toString('hex')) console.log('balance in wei: ' + account.balance.toString('hex')) console.log('stateRoot: ' + storageRoot.toString('hex')) console.log('codeHash:' + account.codeHash.toString('hex')) console.log('-------------------') cb(err) }) } // So if everything went right we should have "null_radix" // stored at "0x9bdf9e2cc4dfa83de3c35da792cdf9b9e9fcfabd". To // see this we need to print out the name register's // storage trie. // reads and prints the storage of a contract function readStorage (cb) { // we need to create a copy of the state root var storageTrie = stateTrie.copy() // Since we are using a copy we won't change the // root of `stateTrie` storageTrie.root = storageRoot var stream = storageTrie.createReadStream() console.log('------Storage------') // prints all of the keys and values in the storage trie stream.on('data', function (data) { // remove the 'hex' if you want to see the ascii values console.log('key: ' + data.key.toString('hex')) console.log('Value: ' + rlp.decode(data.value).toString()) }) stream.on('end', cb) } // run everything async.series([ setup, async.apply(runTx, rawTx1), async.apply(runTx, rawTx2), checkResults, readStorage ]) // Now when you run you should see a complete trace. // `onStep` provides an object that contains all the // information on the current state of the `VM`.
giulidb/ticket_dapp
node_modules/ethereumjs-vm/examples/run-transactions-complete/index.js
JavaScript
mit
4,121
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once(dirname(__FILE__).'/sfGeneratorBaseTask.class.php'); /** * Generates a new application. * * @package symfony * @subpackage task * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id$ */ class sfGenerateAppTask extends sfGeneratorBaseTask { /** * @see sfTask */ protected function doRun(sfCommandManager $commandManager, $options) { $this->process($commandManager, $options); $this->checkProjectExists(); return $this->execute($commandManager->getArgumentValues(), $commandManager->getOptionValues()); } /** * @see sfTask */ protected function configure() { $this->addArguments(array( new sfCommandArgument('application', sfCommandArgument::REQUIRED, 'The application name'), )); $this->aliases = array('init-app'); $this->namespace = 'generate'; $this->name = 'app'; $this->briefDescription = 'Generates a new application'; $this->detailedDescription = <<<EOF The [generate:app|INFO] task creates the basic directory structure for a new application in the current project: [./symfony generate:app frontend|INFO] This task also creates two front controller scripts in the [web/|COMMENT] directory: [web/%application%.php|INFO] for the production environment [web/%application%_dev.php|INFO] for the development environment For the first application, the production environment script is named [index.php|COMMENT]. If an application with the same name already exists, it throws a [sfCommandException|COMMENT]. EOF; } /** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { $app = $arguments['application']; $appDir = sfConfig::get('sf_apps_dir').'/'.$app; if (is_dir($appDir)) { throw new sfCommandException(sprintf('The application "%s" already exists.', $appDir)); } // Create basic application structure $finder = sfFinder::type('any')->ignore_version_control()->discard('.sf'); $this->getFilesystem()->mirror(dirname(__FILE__).'/skeleton/app/app', $appDir, $finder); // Create $app.php or index.php if it is our first app $indexName = 'index'; $firstApp = !file_exists(sfConfig::get('sf_web_dir').'/index.php'); if (!$firstApp) { $indexName = $app; } // Set no_script_name value in settings.yml for production environment $finder = sfFinder::type('file')->name('settings.yml'); $this->getFilesystem()->replaceTokens($finder->in($appDir.'/config'), '##', '##', array('NO_SCRIPT_NAME' => ($firstApp ? 'on' : 'off'))); $this->getFilesystem()->copy(dirname(__FILE__).'/skeleton/app/web/index.php', sfConfig::get('sf_web_dir').'/'.$indexName.'.php'); $this->getFilesystem()->copy(dirname(__FILE__).'/skeleton/app/web/index.php', sfConfig::get('sf_web_dir').'/'.$app.'_dev.php'); $this->getFilesystem()->replaceTokens(sfConfig::get('sf_web_dir').'/'.$indexName.'.php', '##', '##', array( 'APP_NAME' => $app, 'ENVIRONMENT' => 'prod', 'IS_DEBUG' => 'false', )); $this->getFilesystem()->replaceTokens(sfConfig::get('sf_web_dir').'/'.$app.'_dev.php', '##', '##', array( 'APP_NAME' => $app, 'ENVIRONMENT' => 'dev', 'IS_DEBUG' => 'true', )); $this->getFilesystem()->copy(dirname(__FILE__).'/skeleton/app/app/config/ApplicationConfiguration.class.php', $appDir.'/config/'.$app.'Configuration.class.php'); $this->getFilesystem()->replaceTokens($appDir.'/config/'.$app.'Configuration.class.php', '##', '##', array('APP_NAME' => $app)); $fixPerms = new sfProjectPermissionsTask($this->dispatcher, $this->formatter); $fixPerms->setCommandApplication($this->commandApplication); $fixPerms->run(); // Create test dir $this->getFilesystem()->mkdirs(sfConfig::get('sf_test_dir').'/functional/'.$app); } }
jcoby/symfony
lib/task/generator/sfGenerateAppTask.class.php
PHP
mit
4,150
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved. #include <cassert> #include <iostream> #include <limits> #include <memory> #include <vector> #include "./BST_prototype.h" using std::cout; using std::endl; using std::make_unique; using std::numeric_limits; using std::unique_ptr; using std::vector; unique_ptr<BSTNode<int>> RebuildBSTFromPreorderOnValueRange( const vector<int>&, int, int, int*); // @include unique_ptr<BSTNode<int>> RebuildBSTFromPreorder( const vector<int>& preorder_sequence) { int root_idx = 0; return RebuildBSTFromPreorderOnValueRange( preorder_sequence, numeric_limits<int>::min(), numeric_limits<int>::max(), &root_idx); } // Builds a BST on the subtree rooted at root_idx from preorder_sequence on // keys in (lower_bound, upper_bound). unique_ptr<BSTNode<int>> RebuildBSTFromPreorderOnValueRange( const vector<int>& preorder_sequence, int lower_bound, int upper_bound, int* root_idx_pointer) { int& root_idx = *root_idx_pointer; if (root_idx == preorder_sequence.size()) { return nullptr; } int root = preorder_sequence[root_idx]; if (root < lower_bound || root > upper_bound) { return nullptr; } ++root_idx; // Note that RebuildBSTFromPreorderOnValueRange updates root_idx. So the // order of following two calls are critical. auto left_subtree = RebuildBSTFromPreorderOnValueRange( preorder_sequence, lower_bound, root, root_idx_pointer); auto right_subtree = RebuildBSTFromPreorderOnValueRange( preorder_sequence, root, upper_bound, root_idx_pointer); return make_unique<BSTNode<int>>( BSTNode<int>{root, move(left_subtree), move(right_subtree)}); } // @exclude template <typename T> void CheckAns(const unique_ptr<BSTNode<T>>& n, const T& pre) { if (n) { CheckAns(n->left, pre); assert(pre <= n->data); cout << n->data << endl; CheckAns(n->right, n->data); } } int main(int argc, char* argv[]) { // 3 // 2 5 // 1 4 6 // should output 1, 2, 3, 4, 5, 6 // preorder [3, 2, 1, 5, 4, 6] vector<int> preorder = {3, 2, 1, 5, 4, 6}; unique_ptr<BSTNode<int>> tree(RebuildBSTFromPreorder(preorder)); CheckAns<int>(tree, numeric_limits<int>::min()); assert(3 == tree->data); assert(2 == tree->left->data); assert(1 == tree->left->left->data); assert(5 == tree->right->data); assert(4 == tree->right->left->data); assert(6 == tree->right->right->data); return 0; }
adnanaziz/epicode
cpp/Rebuild_BST_preorder_better.cc
C++
mit
2,469
// The MIT License (MIT) // // Copyright (c) Microsoft Corporation // // 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 Microsoft.Deployment.WindowsInstaller; using System.Collections.Generic; namespace Microsoft.Tools.WindowsInstaller.PowerShell.Commands { /// <summary> /// The data for actions to install patches. /// </summary> public class InstallPatchActionData : InstallCommandActionData { /// <summary> /// Creates a new instance of the <see cref="InstallPatchActionData"/> class. /// </summary> public InstallPatchActionData() { this.Patches = new List<string>(); } /// <summary> /// Gets the list of patch paths to apply. /// </summary> public List<string> Patches { get; private set; } /// <summary> /// Gets or sets the user security identifier for the product to which patches apply. /// </summary> public string UserSid { get; set; } /// <summary> /// Gets or sets the <see cref="UserContexts"/> for the product to which patches apply. /// </summary> public UserContexts UserContext { get; set; } } }
SamB/psmsi
src/PowerShell/PowerShell/Commands/InstallPatchActionData.cs
C#
mit
2,231
package com.onelogin.saml2.settings; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.onelogin.saml2.model.Contact; import com.onelogin.saml2.model.Organization; import com.onelogin.saml2.util.Util; /** * SettingsBuilder class of OneLogin's Java Toolkit. * * A class that implements the settings builder */ public class SettingsBuilder { /** * Private property to construct a logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(SettingsBuilder.class); /** * Private property that contain the SAML settings */ private Properties prop = new Properties(); /** * Saml2Settings object */ private Saml2Settings saml2Setting; public final static String STRICT_PROPERTY_KEY = "onelogin.saml2.strict"; public final static String DEBUG_PROPERTY_KEY = "onelogin.saml2.debug"; // SP public final static String SP_ENTITYID_PROPERTY_KEY = "onelogin.saml2.sp.entityid"; public final static String SP_ASSERTION_CONSUMER_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.sp.assertion_consumer_service.url"; public final static String SP_ASSERTION_CONSUMER_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.sp.assertion_consumer_service.binding"; public final static String SP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.sp.single_logout_service.url"; public final static String SP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.sp.single_logout_service.binding"; public final static String SP_NAMEIDFORMAT_PROPERTY_KEY = "onelogin.saml2.sp.nameidformat"; public final static String SP_X509CERT_PROPERTY_KEY = "onelogin.saml2.sp.x509cert"; public final static String SP_PRIVATEKEY_PROPERTY_KEY = "onelogin.saml2.sp.privatekey"; // IDP public final static String IDP_ENTITYID_PROPERTY_KEY = "onelogin.saml2.idp.entityid"; public final static String IDP_SINGLE_SIGN_ON_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.idp.single_sign_on_service.url"; public final static String IDP_SINGLE_SIGN_ON_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.idp.single_sign_on_service.binding"; public final static String IDP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.idp.single_logout_service.url"; public final static String IDP_SINGLE_LOGOUT_SERVICE_RESPONSE_URL_PROPERTY_KEY = "onelogin.saml2.idp.single_logout_service.response.url"; public final static String IDP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.idp.single_logout_service.binding"; public final static String IDP_X509CERT_PROPERTY_KEY = "onelogin.saml2.idp.x509cert"; public final static String CERTFINGERPRINT_PROPERTY_KEY = "onelogin.saml2.idp.certfingerprint"; public final static String CERTFINGERPRINT_ALGORITHM_PROPERTY_KEY = "onelogin.saml2.idp.certfingerprint_algorithm"; // Security public final static String SECURITY_NAMEID_ENCRYPTED = "onelogin.saml2.security.nameid_encrypted"; public final static String SECURITY_AUTHREQUEST_SIGNED = "onelogin.saml2.security.authnrequest_signed"; public final static String SECURITY_LOGOUTREQUEST_SIGNED = "onelogin.saml2.security.logoutrequest_signed"; public final static String SECURITY_LOGOUTRESPONSE_SIGNED = "onelogin.saml2.security.logoutresponse_signed"; public final static String SECURITY_WANT_MESSAGES_SIGNED = "onelogin.saml2.security.want_messages_signed"; public final static String SECURITY_WANT_ASSERTIONS_SIGNED = "onelogin.saml2.security.want_assertions_signed"; public final static String SECURITY_WANT_ASSERTIONS_ENCRYPTED = "onelogin.saml2.security.want_assertions_encrypted"; public final static String SECURITY_WANT_NAMEID = "onelogin.saml2.security.want_nameid"; public final static String SECURITY_WANT_NAMEID_ENCRYPTED = "onelogin.saml2.security.want_nameid_encrypted"; public final static String SECURITY_SIGN_METADATA = "onelogin.saml2.security.sign_metadata"; public final static String SECURITY_REQUESTED_AUTHNCONTEXT = "onelogin.saml2.security.requested_authncontext"; public final static String SECURITY_REQUESTED_AUTHNCONTEXTCOMPARISON = "onelogin.saml2.security.requested_authncontextcomparison"; public final static String SECURITY_WANT_XML_VALIDATION = "onelogin.saml2.security.want_xml_validation"; public final static String SECURITY_SIGNATURE_ALGORITHM = "onelogin.saml2.security.signature_algorithm"; public final static String SECURITY_REJECT_UNSOLICITED_RESPONSES_WITH_INRESPONSETO = "onelogin.saml2.security.reject_unsolicited_responses_with_inresponseto"; // Compress public final static String COMPRESS_REQUEST = "onelogin.saml2.compress.request"; public final static String COMPRESS_RESPONSE = "onelogin.saml2.compress.response"; // Misc public final static String CONTACT_TECHNICAL_GIVEN_NAME = "onelogin.saml2.contacts.technical.given_name"; public final static String CONTACT_TECHNICAL_EMAIL_ADDRESS = "onelogin.saml2.contacts.technical.email_address"; public final static String CONTACT_SUPPORT_GIVEN_NAME = "onelogin.saml2.contacts.support.given_name"; public final static String CONTACT_SUPPORT_EMAIL_ADDRESS = "onelogin.saml2.contacts.support.email_address"; public final static String ORGANIZATION_NAME = "onelogin.saml2.organization.name"; public final static String ORGANIZATION_DISPLAYNAME = "onelogin.saml2.organization.displayname"; public final static String ORGANIZATION_URL = "onelogin.saml2.organization.url"; /** * Load settings from the file. * * @param propFileName * OneLogin_Saml2_Settings * * @return the SettingsBuilder object with the settings loaded from the file * * @throws IOException */ public SettingsBuilder fromFile(String propFileName) throws IOException { this.loadPropFile(propFileName); return this; } /** * Loads the settings from the properties file * * @param propFileName * the name of the file * * @throws IOException */ private void loadPropFile(String propFileName) throws IOException { InputStream inputStream = null; try { inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) { this.prop.load(inputStream); LOGGER.debug("properties file " + propFileName + "loaded succesfully"); } else { throw new FileNotFoundException("properties file '" + propFileName + "' not found in the classpath"); } } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { LOGGER.warn("properties file not closed properly.", e); } } } /** * Builds the Saml2Settings object. Read the Properties object and set all the SAML settings * * @return the Saml2Settings object with all the SAML settings loaded * * @throws IOException */ public Saml2Settings build() throws IOException { saml2Setting = new Saml2Settings(); Boolean strict = loadBooleanProperty(STRICT_PROPERTY_KEY); if (strict != null) saml2Setting.setStrict(strict); Boolean debug = loadBooleanProperty(DEBUG_PROPERTY_KEY); if (debug != null) saml2Setting.setDebug(debug); this.loadSpSetting(); this.loadIdpSetting(); this.loadSecuritySetting(); this.loadCompressSetting(); saml2Setting.setContacts(loadContacts()); saml2Setting.setOrganization(loadOrganization()); return saml2Setting; } /** * Loads the IdP settings from the properties file */ private void loadIdpSetting() { String idpEntityID = loadStringProperty(IDP_ENTITYID_PROPERTY_KEY); if (idpEntityID != null) saml2Setting.setIdpEntityId(idpEntityID); URL idpSingleSignOnServiceUrl = loadURLProperty(IDP_SINGLE_SIGN_ON_SERVICE_URL_PROPERTY_KEY); if (idpSingleSignOnServiceUrl != null) saml2Setting.setIdpSingleSignOnServiceUrl(idpSingleSignOnServiceUrl); String idpSingleSignOnServiceBinding = loadStringProperty(IDP_SINGLE_SIGN_ON_SERVICE_BINDING_PROPERTY_KEY); if (idpSingleSignOnServiceBinding != null) saml2Setting.setIdpSingleSignOnServiceBinding(idpSingleSignOnServiceBinding); URL idpSingleLogoutServiceUrl = loadURLProperty(IDP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY); if (idpSingleLogoutServiceUrl != null) saml2Setting.setIdpSingleLogoutServiceUrl(idpSingleLogoutServiceUrl); URL idpSingleLogoutServiceResponseUrl = loadURLProperty(IDP_SINGLE_LOGOUT_SERVICE_RESPONSE_URL_PROPERTY_KEY); if (idpSingleLogoutServiceResponseUrl != null) saml2Setting.setIdpSingleLogoutServiceResponseUrl(idpSingleLogoutServiceResponseUrl); String idpSingleLogoutServiceBinding = loadStringProperty(IDP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY); if (idpSingleLogoutServiceBinding != null) saml2Setting.setIdpSingleLogoutServiceBinding(idpSingleLogoutServiceBinding); X509Certificate idpX509cert = loadCertificateFromProp(IDP_X509CERT_PROPERTY_KEY); if (idpX509cert != null) saml2Setting.setIdpx509cert(idpX509cert); String idpCertFingerprint = loadStringProperty(CERTFINGERPRINT_PROPERTY_KEY); if (idpCertFingerprint != null) saml2Setting.setIdpCertFingerprint(idpCertFingerprint); String idpCertFingerprintAlgorithm = loadStringProperty(CERTFINGERPRINT_ALGORITHM_PROPERTY_KEY); if (idpCertFingerprintAlgorithm != null && !idpCertFingerprintAlgorithm.isEmpty()) saml2Setting.setIdpCertFingerprintAlgorithm(idpCertFingerprintAlgorithm); } /** * Loads the security settings from the properties file */ private void loadSecuritySetting() { Boolean nameIdEncrypted = loadBooleanProperty(SECURITY_NAMEID_ENCRYPTED); if (nameIdEncrypted != null) saml2Setting.setNameIdEncrypted(nameIdEncrypted); Boolean authnRequestsSigned = loadBooleanProperty(SECURITY_AUTHREQUEST_SIGNED); if (authnRequestsSigned != null) saml2Setting.setAuthnRequestsSigned(authnRequestsSigned); Boolean logoutRequestSigned = loadBooleanProperty(SECURITY_LOGOUTREQUEST_SIGNED); if (logoutRequestSigned != null) saml2Setting.setLogoutRequestSigned(logoutRequestSigned); Boolean logoutResponseSigned = loadBooleanProperty(SECURITY_LOGOUTRESPONSE_SIGNED); if (logoutResponseSigned != null) saml2Setting.setLogoutResponseSigned(logoutResponseSigned); Boolean wantMessagesSigned = loadBooleanProperty(SECURITY_WANT_MESSAGES_SIGNED); if (wantMessagesSigned != null) saml2Setting.setWantMessagesSigned(wantMessagesSigned); Boolean wantAssertionsSigned = loadBooleanProperty(SECURITY_WANT_ASSERTIONS_SIGNED); if (wantAssertionsSigned != null) saml2Setting.setWantAssertionsSigned(wantAssertionsSigned); Boolean wantAssertionsEncrypted = loadBooleanProperty(SECURITY_WANT_ASSERTIONS_ENCRYPTED); if (wantAssertionsEncrypted != null) saml2Setting.setWantAssertionsEncrypted(wantAssertionsEncrypted); Boolean wantNameId = loadBooleanProperty(SECURITY_WANT_NAMEID); if (wantNameId != null) saml2Setting.setWantNameId(wantNameId); Boolean wantNameIdEncrypted = loadBooleanProperty(SECURITY_WANT_NAMEID_ENCRYPTED); if (wantNameIdEncrypted != null) saml2Setting.setWantNameIdEncrypted(wantNameIdEncrypted); Boolean wantXMLValidation = loadBooleanProperty(SECURITY_WANT_XML_VALIDATION); if (wantXMLValidation != null) saml2Setting.setWantXMLValidation(wantXMLValidation); Boolean signMetadata = loadBooleanProperty(SECURITY_SIGN_METADATA); if (signMetadata != null) saml2Setting.setSignMetadata(signMetadata); List<String> requestedAuthnContext = loadListProperty(SECURITY_REQUESTED_AUTHNCONTEXT); if (requestedAuthnContext != null) saml2Setting.setRequestedAuthnContext(requestedAuthnContext); String requestedAuthnContextComparison = loadStringProperty(SECURITY_REQUESTED_AUTHNCONTEXTCOMPARISON); if (requestedAuthnContextComparison != null && !requestedAuthnContextComparison.isEmpty()) saml2Setting.setRequestedAuthnContextComparison(requestedAuthnContextComparison); String signatureAlgorithm = loadStringProperty(SECURITY_SIGNATURE_ALGORITHM); if (signatureAlgorithm != null && !signatureAlgorithm.isEmpty()) saml2Setting.setSignatureAlgorithm(signatureAlgorithm); Boolean rejectUnsolicitedResponsesWithInResponseTo = loadBooleanProperty(SECURITY_REJECT_UNSOLICITED_RESPONSES_WITH_INRESPONSETO); if (rejectUnsolicitedResponsesWithInResponseTo != null) { saml2Setting.setRejectUnsolicitedResponsesWithInResponseTo(rejectUnsolicitedResponsesWithInResponseTo); } } /** * Loads the compress settings from the properties file */ private void loadCompressSetting() { Boolean compressRequest = loadBooleanProperty(COMPRESS_REQUEST); if (compressRequest != null) { saml2Setting.setCompressRequest(compressRequest); } Boolean compressResponse = loadBooleanProperty(COMPRESS_RESPONSE); if (compressResponse != null) { saml2Setting.setCompressResponse(compressResponse); } } /** * Loads the organization settings from the properties file */ private Organization loadOrganization() { Organization orgResult = null; String orgName = loadStringProperty(ORGANIZATION_NAME); String orgDisplayName = loadStringProperty(ORGANIZATION_DISPLAYNAME); URL orgUrl = loadURLProperty(ORGANIZATION_URL); if ((orgName != null && !orgName.isEmpty()) || (orgDisplayName != null && !orgDisplayName.isEmpty()) || (orgUrl != null)) { orgResult = new Organization(orgName, orgDisplayName, orgUrl); } return orgResult; } /** * Loads the contacts settings from the properties file */ private List<Contact> loadContacts() { List<Contact> contacts = new LinkedList<Contact>(); String technicalGn = loadStringProperty(CONTACT_TECHNICAL_GIVEN_NAME); String technicalEmailAddress = loadStringProperty(CONTACT_TECHNICAL_EMAIL_ADDRESS); if ((technicalGn != null && !technicalGn.isEmpty()) || (technicalEmailAddress != null && !technicalEmailAddress.isEmpty())) { Contact technical = new Contact("technical", technicalGn, technicalEmailAddress); contacts.add(technical); } String supportGn = loadStringProperty(CONTACT_SUPPORT_GIVEN_NAME); String supportEmailAddress = loadStringProperty(CONTACT_SUPPORT_EMAIL_ADDRESS); if ((supportGn != null && !supportGn.isEmpty()) || (supportEmailAddress != null && !supportEmailAddress.isEmpty())) { Contact support = new Contact("support", supportGn, supportEmailAddress); contacts.add(support); } return contacts; } /** * Loads the SP settings from the properties file */ private void loadSpSetting() throws IOException { String spEntityID = loadStringProperty(SP_ENTITYID_PROPERTY_KEY); if (spEntityID != null) saml2Setting.setSpEntityId(spEntityID); URL assertionConsumerServiceUrl = loadURLProperty(SP_ASSERTION_CONSUMER_SERVICE_URL_PROPERTY_KEY); if (assertionConsumerServiceUrl != null) saml2Setting.setSpAssertionConsumerServiceUrl(assertionConsumerServiceUrl); String spAssertionConsumerServiceBinding = loadStringProperty(SP_ASSERTION_CONSUMER_SERVICE_BINDING_PROPERTY_KEY); if (spAssertionConsumerServiceBinding != null) saml2Setting.setSpAssertionConsumerServiceBinding(spAssertionConsumerServiceBinding); URL spSingleLogoutServiceUrl = loadURLProperty(SP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY); if (spSingleLogoutServiceUrl != null) saml2Setting.setSpSingleLogoutServiceUrl(spSingleLogoutServiceUrl); String spSingleLogoutServiceBinding = loadStringProperty(SP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY); if (spSingleLogoutServiceBinding != null) saml2Setting.setSpSingleLogoutServiceBinding(spSingleLogoutServiceBinding); String spNameIDFormat = loadStringProperty(SP_NAMEIDFORMAT_PROPERTY_KEY); if (spNameIDFormat != null && !spNameIDFormat.isEmpty()) saml2Setting.setSpNameIDFormat(spNameIDFormat); X509Certificate spX509cert = loadCertificateFromProp(SP_X509CERT_PROPERTY_KEY); if (spX509cert != null) saml2Setting.setSpX509cert(spX509cert); PrivateKey spPrivateKey = loadPrivateKeyFromProp(SP_PRIVATEKEY_PROPERTY_KEY); if (spPrivateKey != null) saml2Setting.setSpPrivateKey(spPrivateKey); } /** * Loads a property of the type String from the Properties object * * @param propertyKey * the property name * * @return the value */ private String loadStringProperty(String propertyKey) { String propValue = prop.getProperty(propertyKey); if (propValue != null) { propValue = propValue.trim(); } return propValue; } /** * Loads a property of the type Boolean from the Properties object * * @param propertyKey * the property name * * @return the value */ private Boolean loadBooleanProperty(String propertyKey) { String booleanPropValue = prop.getProperty(propertyKey); if (booleanPropValue != null) { return Boolean.parseBoolean(booleanPropValue.trim()); } else { return null; } } /** * Loads a property of the type List from the Properties object * * @param propertyKey * the property name * * @return the value */ private List<String> loadListProperty(String propertyKey) { String arrayPropValue = prop.getProperty(propertyKey); if (arrayPropValue != null && !arrayPropValue.isEmpty()) { String [] values = arrayPropValue.trim().split(","); for (int i = 0; i < values.length; i++) { values[i] = values[i].trim(); } return Arrays.asList(values); } else { return null; } } /** * Loads a property of the type URL from the Properties object * * @param propertyKey * the property name * * @return the value */ private URL loadURLProperty(String propertyKey) { String urlPropValue = prop.getProperty(propertyKey); if (urlPropValue == null || urlPropValue.isEmpty()) { return null; } else { try { return new URL(urlPropValue.trim()); } catch (MalformedURLException e) { LOGGER.error("'" + propertyKey + "' contains malformed url.", e); return null; } } } /** * Loads a property of the type X509Certificate from the Properties object * * @param propertyKey * the property name * * @return the X509Certificate object */ protected X509Certificate loadCertificateFromProp(String propertyKey) { String certString = prop.getProperty(propertyKey); if (certString == null || certString.isEmpty()) { return null; } else { try { return Util.loadCert(certString); } catch (CertificateException e) { LOGGER.error("Error loading certificate from properties.", e); return null; } catch (UnsupportedEncodingException e) { LOGGER.error("the certificate is not in correct format.", e); return null; } } } /** * Loads a property of the type X509Certificate from file * * @param filename * the file name of the file that contains the X509Certificate * * @return the X509Certificate object */ /* protected X509Certificate loadCertificateFromFile(String filename) { String certString = null; try { certString = Util.getFileAsString(filename.trim()); } catch (URISyntaxException e) { LOGGER.error("Error loading certificate from file.", e); return null; } catch (IOException e) { LOGGER.error("Error loading certificate from file.", e); return null; } try { return Util.loadCert(certString); } catch (CertificateException e) { LOGGER.error("Error loading certificate from file.", e); return null; } catch (UnsupportedEncodingException e) { LOGGER.error("the certificate is not in correct format.", e); return null; } } */ /** * Loads a property of the type PrivateKey from the Properties object * * @param propertyKey * the property name * * @return the PrivateKey object */ protected PrivateKey loadPrivateKeyFromProp(String propertyKey) { String keyString = prop.getProperty(propertyKey); if (keyString == null || keyString.isEmpty()) { return null; } else { try { return Util.loadPrivateKey(keyString); } catch (Exception e) { LOGGER.error("Error loading privatekey from properties.", e); return null; } } } /** * Loads a property of the type PrivateKey from file * * @param filename * the file name of the file that contains the PrivateKey * * @return the PrivateKey object */ /* protected PrivateKey loadPrivateKeyFromFile(String filename) { String keyString = null; try { keyString = Util.getFileAsString(filename.trim()); } catch (URISyntaxException e) { LOGGER.error("Error loading privatekey from file.", e); return null; } catch (IOException e) { LOGGER.error("Error loading privatekey from file.", e); return null; } try { return Util.loadPrivateKey(keyString); } catch (GeneralSecurityException e) { LOGGER.error("Error loading privatekey from file.", e); return null; } catch (IOException e) { LOGGER.debug("Error loading privatekey from file.", e); return null; } } */ }
jacklotusho/java-saml
core/src/main/java/com/onelogin/saml2/settings/SettingsBuilder.java
Java
mit
21,175
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcMeasureValue.h" #include "ifcpp/IFC4/include/IfcThermodynamicTemperatureMeasure.h" // TYPE IfcThermodynamicTemperatureMeasure = REAL; IfcThermodynamicTemperatureMeasure::IfcThermodynamicTemperatureMeasure( double value ) { m_value = value; } shared_ptr<BuildingObject> IfcThermodynamicTemperatureMeasure::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcThermodynamicTemperatureMeasure> copy_self( new IfcThermodynamicTemperatureMeasure() ); copy_self->m_value = m_value; return copy_self; } void IfcThermodynamicTemperatureMeasure::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCTHERMODYNAMICTEMPERATUREMEASURE("; } appendRealWithoutTrailingZeros( stream, m_value ); if( is_select_type ) { stream << ")"; } } const std::wstring IfcThermodynamicTemperatureMeasure::toString() const { std::wstringstream strs; strs << m_value; return strs.str(); } shared_ptr<IfcThermodynamicTemperatureMeasure> IfcThermodynamicTemperatureMeasure::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcThermodynamicTemperatureMeasure>(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcThermodynamicTemperatureMeasure>(); } shared_ptr<IfcThermodynamicTemperatureMeasure> type_object( new IfcThermodynamicTemperatureMeasure() ); readReal( arg, type_object->m_value ); return type_object; }
ifcquery/ifcplusplus
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcThermodynamicTemperatureMeasure.cpp
C++
mit
1,821
class CreateAuthorizations < ActiveRecord::Migration def change create_table :authorizations do |t| t.string :provider t.string :uid t.integer :user_id t.string :username t.string :token t.string :secret t.timestamps end end end
nembrotorg/nembrot
db/migrate/20131125164749_create_authorizations.rb
Ruby
mit
289
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { FormattedMessage, FormattedRelative } from 'react-intl'; import { Link } from 'react-router-dom'; import Avatar from '../../Avatar'; import './Notification.less'; const NotificationMention = ({ onClick, id, read, date, payload }) => (<div role="presentation" onClick={() => onClick(id)} className={classNames('Notification', { 'Notification--unread': !read, })} > <Avatar username={payload.user} size={40} /> <div className="Notification__text"> <div className="Notification__text__message"> <FormattedMessage id="notification_mention_username_post" defaultMessage="{username} mentioned you on this post {post}." values={{ username: <Link to={`/${payload.user}`}>{payload.user}</Link>, post: <Link to={payload.post_url}>{payload.post_title}</Link>, }} /> </div> <div className="Notification__text__date"> <FormattedRelative value={date} /> </div> </div> </div>); NotificationMention.propTypes = { onClick: PropTypes.func, id: PropTypes.number.isRequired, read: PropTypes.bool.isRequired, date: PropTypes.string.isRequired, payload: PropTypes.shape().isRequired, }; NotificationMention.defaultProps = { onClick: () => {}, }; export default NotificationMention;
ryanbaer/busy
src/components/Navigation/Notifications/NotificationMention.js
JavaScript
mit
1,437
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Graphics.Particle; using FlatRedBall.Content.Particle; using FlatRedBall; using FlatRedBall.IO; using FlatRedBall.Math; using EditorObjects.EditorSettings; using FlatRedBall.Gui; using ParticleEditor.GUI; using FlatRedBall.Math.Geometry; using FlatRedBall.Content.Scene; namespace ParticleEditor.Managers { public class FileCommands { public string CurrentEmixFileName { get; set; } public void SaveEmitters(PositionedObjectList<Emitter> emitters, string fileName) { EmitterSaveList emitterSaveList = EmitterSaveList.FromEmitterList(EditorData.Emitters); emitterSaveList.Save(fileName); #if FRB_MDX FlatRedBallServices.Owner.Text = "ParticleEditor - Currently editing " + fileName; #else FlatRedBallServices.Game.Window.Title = "ParticleEditor - Currently editing " + fileName; #endif fileName = FileManager.RemoveExtension(fileName); EditorData.CurrentEmixFileName = fileName; EmitterEditorSettingsSave settings = new EmitterEditorSettingsSave(); settings.Camera = CameraSave.FromCamera(Camera.Main); if (Camera.Main.Orthogonal && Camera.Main.OrthogonalHeight == Camera.Main.DestinationRectangle.Height) { settings.Camera.OrthogonalWidth = -1; settings.Camera.OrthogonalHeight = -1; } settings.Save(FileManager.RemoveExtension( fileName ) + ".ess"); } public void LoadEmitters(string fileName) { #region Clear all Emitters in memory while (AppState.Self.Emitters.Count != 0) { SpriteManager.RemoveEmitter(AppState.Self.Emitters[0]); } AppState.Self.CurrentEmitter = null; #endregion #region Load the Emitters and add them to the SpriteManager EmitterSaveList emitterSaveList = EmitterSaveList.FromFile(fileName); AppState.Self.Emitters = emitterSaveList.ToEmitterList(AppState.Self.PermanentContentManager); foreach (Emitter emitter in AppState.Self.Emitters) { SpriteManager.AddEmitter(emitter); ShapeManager.AddPolygon(emitter.EmissionBoundary); } CurrentEmixFileName = FileManager.RemoveExtension(fileName); #endregion bool haveAttachments = false; #if FRB_MDX FlatRedBallServices.Owner.Text = "ParticleEditor - Currently editing " + CurrentEmixFileName; #else FlatRedBallServices.Game.Window.Title = "ParticleEditor - Currently editing " + CurrentEmixFileName; #endif for (int i = 0; i < AppState.Self.Emitters.Count; i++) { if (emitterSaveList.emitters[i].ParentSpriteName != null) { // see if the emitter exists in the gameData.emitterArray and set the attachments. If not, then // we need to set haveAttachments to true, indicating there are attachments to .scn Sprites Emitter e = AppState.Self.Emitters.FindWithNameContaining(emitterSaveList.emitters[i].ParentSpriteName); if (e != null) { AppState.Self.Emitters[i].AttachTo(e, false); } else { haveAttachments = true; } } } // TODO: Handle when the ParticleEditor can't find attachments. if (haveAttachments) { EditorData.lastLoadedFile = emitterSaveList; if (EditorData.Scene == null || EditorData.Scene.Sprites.Count == 0) { MultiButtonMessageBox mbmb = GuiManager.AddMultiButtonMessageBox(); mbmb.Name = ".emi attachments found"; mbmb.Text = fileName + " has one or more attachments. There are no " + "Sprites loaded. What would you like to do with the attachment information?"; mbmb.ScaleX = 15; mbmb.AddButton("Forget all attachment information.", new GuiMessage(FileMenuWindow.ForgetAttachmentInfo)); mbmb.AddButton("Remember attachment information, I will load a .scnx file later.", new GuiMessage(FileMenuWindow.RememberAttachmentInfo)); mbmb.AddButton("Manually search for .scnx file now.", new GuiMessage(FileMenuWindow.LoadScnxButtonClick)); mbmb.AddButton("Automatically search for .scnx with Sprites matching attachments.", new GuiMessage(FileMenuWindow.AutoSearchScn)); } else { FileMenuWindow.AttemptEmitterAttachment(""); } } string settingsFileName = FileManager.RemoveExtension( fileName ) + ".ess"; bool doesSettingsFileExist = System.IO.File.Exists(settingsFileName); if (doesSettingsFileExist) { EmitterEditorSettingsSave settings = EmitterEditorSettingsSave.Load(settingsFileName); settings.Camera.SetCamera(Camera.Main); if (settings.Camera.OrthogonalHeight < 0) { Camera.Main.UsePixelCoordinates(); } else { Camera.Main.FixAspectRatioYConstant(); } } } } }
GorillaOne/FlatRedBall
FRBDK/ParticleEditor/Managers/FileCommands.cs
C#
mit
5,743
#include <iostream> #include <cstring> using namespace std; const int MAX_STR = 50; bool isAlpha(char c); int countLetters(char str[], int sizeStr); void extractWord(char str[], int sizeStr, char *word); void isPalindrome(char *word, int counterLetters); int main() { char str[MAX_STR]; cout << "Enter a word to check is it a polindrome: "; cin.getline(str, MAX_STR); int sizeStr = strlen(str); str[sizeStr + 1] = '\0'; int counterLetters = countLetters(str, sizeStr); char *word = new char[counterLetters]; extractWord(str, sizeStr, word); isPalindrome(word, counterLetters); return 0; } bool isAlpha(char c) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { return true; } else { return false; } } int countLetters(char str[], int sizeStr) { int counter = 0; for (size_t i = 0; i < sizeStr; i++) { if (isAlpha(str[i])) { counter++; } } return counter; } void extractWord(char str[], int sizeStr, char *word) { int k = 0; for (size_t i = 0; i < sizeStr; i++) { if (isAlpha(str[i])) { word[k] = str[i]; k++; } } word[k] = '\0'; cout << "The extracted word from the sentence is: " << word << endl; } void isPalindrome(char *word, int counterLetters) { bool isPalindrome = true; for (size_t i = 0; i < counterLetters; i++) { if (word[i] != word[counterLetters - i - 1]) { isPalindrome = false; } } if (isPalindrome) { cout << "The word is a palindrome!" << endl; } else { cout << "The word is not a palindrome!" << endl; } }
pepincho/C-plus-plus-Courses-FMI
Intro-to-programming-course/String Operations/isWordPalindrome/isWordPalindrome.cpp
C++
mit
1,510
import yaml class UiMap(): def __init__(self, path=None): self._map = {} self.observer = None if path: self.load(path) def load(self, path): with open(path, 'r') as f: tree = yaml.load(f) for key in tree: if key.find('__') != 0: self.add_tree(key, tree[key]) self.driver_name = tree['__driver'] module_name = 'uimap.drivers.' + self.driver_name self.driver = getattr(getattr(__import__(module_name), 'drivers'), self.driver_name).Driver(self) def add_tree(self, name, tree, parent=None): if type(tree)==dict: self.add_control(name, tree['__char'], parent) for key in tree: if key.find('__') != 0: self.add_tree(key, tree[key], name) else: self.add_control(name, tree, parent) def add_control(self, name, character, parent): parent = parent and self._map[parent] ctl = Control(self, name, character, parent) self._map[name] = ctl return ctl def all_controls(self): return self._map.keys() def sendkeys(self, keys): return self.driver.sendkeys(None, keys) def fire(self, stage, event): if self.observer: event.stage = stage self.observer(event) def __getattr__(self, control): if control in self._map: return self._map[control] raise AttributeError(control) class Event(object): def __init__(self, control, action): self.control = control self.action = action self.args = None self.stage = 'find' self.ret = None class Control(): def __init__(self, uimap, name, character, parent): self.uimap = uimap self.parent = parent self.name = name self.character = character def __getattr__(self, action): uimap = self.uimap driver = uimap.driver event = UiMap.Event(self, action) if not hasattr(driver, action): raise AttributeError() uimap.fire('find', event) if not driver.wait_exist(self): raise Exception(self.name + ' not exist') def do_action(*args): event.args = args uimap.fire('before', event) event.ret = getattr(driver, action)(self, *args) uimap.fire('done', event) return event.ret return do_action def exist(self): return self.uimap.driver.exist(self) def wait_exist(self, **kwargs): event = UiMap.Event(self, 'wait_exist') self.uimap.fire('before', event) event.ret = self.uimap.driver.wait_exist(self, **kwargs) self.uimap.fire('done', event) return event.ret def wait_vanish(self, **kwargs): event = UiMap.Event(self, 'wait_vanish') self.uimap.fire('before', event) event.ret = self.uimap.driver.wait_vanish(self, **kwargs) self.uimap.fire('done', event) return event.ret def __str__(self): return self.name def __repr__(self): return '<Control "' + self.name + '">'
renorzr/uimap
src/uimap/__init__.py
Python
mit
3,216
require 'ruby-swagger/data/operation' require 'ruby-swagger/grape/type' module Swagger::Grape class Method attr_reader :operation, :types, :scopes def initialize(route_name, route) @route_name = route_name @route = route @types = [] @scopes = [] new_operation operation_params operation_responses operation_security self end private # generate the base of the operation def new_operation @operation = Swagger::Data::Operation.new @operation.tags = grape_tags @operation.operationId = @route.route_api_name if @route.route_api_name && @route.route_api_name.length > 0 @operation.summary = @route.route_description @operation.description = (@route.route_detail && @route.route_detail.length > 0) ? @route.route_detail : @route.route_description @operation.deprecated = @route.route_deprecated if @route.route_deprecated # grape extension @operation end # extract all the parameters from the method definition (in path, url, body) def operation_params extract_params_and_types @params.each do |_param_name, parameter| operation.add_parameter(parameter) end end # extract the data about the response of the method def operation_responses @operation.responses = Swagger::Data::Responses.new # Include all the possible errors in the response (store the types, they are documented separately) (@route.route_errors || {}).each do |code, response| error_response = { 'description' => response['description'] || response[:description] } if (entity = (response[:entity] || response['entity'])) type = Object.const_get entity.to_s error_response['schema'] = {} error_response['schema']['$ref'] = "#/definitions/#{type}" remember_type(type) end @operation.responses.add_response(code, Swagger::Data::Response.parse(error_response)) end if @route.route_response.present? && @route.route_response[:entity].present? rainbow_response = { 'description' => 'Successful result of the operation' } type = Swagger::Grape::Type.new(@route.route_response[:entity].to_s) rainbow_response['schema'] = {} remember_type(@route.route_response[:entity]) # Include any response headers in the documentation of the response if @route.route_response[:headers].present? @route.route_response[:headers].each do |header_key, header_value| next unless header_value.present? rainbow_response['headers'] ||= {} rainbow_response['headers'][header_key] = { 'description' => header_value['description'] || header_value[:description], 'type' => header_value['type'] || header_value[:type], 'format' => header_value['format'] || header_value[:format] } end end if @route.route_response[:root].present? # A case where the response contains a single key in the response if @route.route_response[:isArray] == true # an array that starts from a key named root rainbow_response['schema']['type'] = 'object' rainbow_response['schema']['properties'] = { @route.route_response[:root] => { 'type' => 'array', 'items' => type.to_swagger } } else rainbow_response['schema']['type'] = 'object' rainbow_response['schema']['properties'] = { @route.route_response[:root] => type.to_swagger } end else if @route.route_response[:isArray] == true rainbow_response['schema']['type'] = 'array' rainbow_response['schema']['items'] = type.to_swagger else rainbow_response['schema'] = type.to_swagger end end @operation.responses.add_response('200', Swagger::Data::Response.parse(rainbow_response)) end @operation.responses.add_response('default', Swagger::Data::Response.parse({ 'description' => 'Unexpected error' })) end def operation_security if @route.route_scopes # grape extensions security = Swagger::Data::SecurityRequirement.new security.add_requirement('oauth2', @route.route_scopes) @operation.security = [security] @route.route_scopes.each do |scope| @scopes << scope unless @scopes.include?(scope) end end end # extract the tags def grape_tags (@route.route_tags && !@route.route_tags.empty?) ? @route.route_tags : [@route_name.split('/')[1]] end def extract_params_and_types @params = {} header_params path_params case @route.route_method.downcase when 'get' query_params when 'delete' query_params when 'post' body_params when 'put' body_params when 'patch' body_params when 'head' raise ArgumentError.new("Don't know how to handle the http verb HEAD for #{@route_name}") else raise ArgumentError.new("Don't know how to handle the http verb #{@route.route_method} for #{@route_name}") end @params end def header_params @params ||= {} # include all the parameters that are in the headers if @route.route_headers @route.route_headers.each do |header_key, header_value| @params[header_key] = { 'name' => header_key, 'in' => 'header', 'required' => (header_value[:required] == true), 'type' => 'string', 'description' => header_value[:description] } end end @params end def path_params # include all the parameters that are in the path @route_name.scan(/\{[a-zA-Z0-9\-\_]+\}/).each do |parameter| # scan all parameters in the url param_name = parameter[1..parameter.length - 2] @params[param_name] = { 'name' => param_name, 'in' => 'path', 'required' => true, 'type' => 'string' } end end def query_params @route.route_params.each do |parameter| next if @params[parameter.first.to_s] swag_param = Swagger::Data::Parameter.from_grape(parameter) next unless swag_param swag_param.in = 'query' @params[parameter.first.to_s] = swag_param end end def body_params # include all the parameters that are in the content-body return unless @route.route_params && @route.route_params.length > 0 body_name = @operation.operationId ? "#{@operation.operationId}_body" : 'body' root_param = Swagger::Data::Parameter.parse({ 'name' => body_name, 'in' => 'body', 'description' => 'the content of the request', 'schema' => { 'type' => 'object', 'properties' => {} } }) # create the params schema @route.route_params.each do |parameter| param_name = parameter.first param_value = parameter.last schema = root_param.schema next if @params.keys.include?(param_name) if param_name.scan(/[0-9a-zA-Z_]+/).count == 1 # it's a simple parameter, adding it to the properties of the main object converted_param = Swagger::Grape::Param.new(param_value) schema.properties[param_name] = converted_param.to_swagger required_parameter(schema, param_name, param_value) documented_paramter(schema, param_name, param_value) remember_type(converted_param.type_definition) if converted_param.has_type_definition? else schema_with_subobjects(schema, param_name, parameter.last) end end schema = root_param.schema @params['body'] = root_param if !schema.properties.nil? && schema.properties.keys.length > 0 end # Can potentionelly be used for per-param documentation, for now used for example values def documented_paramter(schema, target, parameter) return if parameter.nil? || parameter[:documentation].nil? unless parameter[:documentation][:example].nil? schema['example'] ||= {} if target.is_a? Array nesting = target[0] target = target[1] schema['example'][nesting] ||= {} schema['example'][nesting][target] = parameter[:documentation][:example] else schema['example'][target] = parameter[:documentation][:example] end end end def required_parameter(schema, name, parameter) return if parameter.nil? || parameter[:required].nil? || parameter[:required] == false schema['required'] = [] unless schema['required'].is_a?(Array) schema['required'] << name end def schema_with_subobjects(schema, param_name, parameter) path = param_name.scan(/[0-9a-zA-Z_]+/) append_to = find_elem_in_schema(schema, path.dup) converted_param = Swagger::Grape::Param.new(parameter) append_to['properties'][path.last] = converted_param.to_swagger remember_type(converted_param.type_definition) if converted_param.has_type_definition? required_parameter(append_to, path.last, parameter) documented_paramter(schema, path, parameter) end def find_elem_in_schema(root, schema_path) return root if schema_path.nil? || schema_path.empty? next_elem = schema_path.shift return root if root['properties'][next_elem].nil? case root['properties'][next_elem]['type'] when 'array' # to descend an array this must be an array of objects root['properties'][next_elem]['items']['type'] = 'object' root['properties'][next_elem]['items']['properties'] ||= {} find_elem_in_schema(root['properties'][next_elem]['items'], schema_path) when 'object' find_elem_in_schema(root['properties'][next_elem], schema_path) else raise ArgumentError.new("Don't know how to handle the schema path #{schema_path.join('/')}") end end # Store an object "type" seen on parameters or response types def remember_type(type) @types ||= [] return if %w(string integer boolean float array symbol virtus::attribute::boolean rack::multipart::uploadedfile date datetime).include?(type.to_s.downcase) type = Object.const_get type.to_s return if @types.include?(type.to_s) @types << type.to_s end end end
brennovich/ruby-swagger
lib/ruby-swagger/grape/method.rb
Ruby
mit
10,865
require 'spec_helper' describe 'Piwik::Site' do before do stub_api_calls end subject { build(:site) } its(:main_url) { should eq('http://test.local') } its(:name) { should eq('Test Site') } its(:config) { should eq({:piwik_url => PIWIK_URL, :auth_token => PIWIK_TOKEN}) } it { subject.save.should eq(true) subject.name = 'Karate Site' subject.update.should eq(true) subject.destroy.should eq(true) } describe 'with wrong id' do before {Piwik::SitesManager.stub(:call).with('SitesManager.getSiteFromId',{:idSite => 666}, /.*/, /.*/).and_return('<result>0</result>')} xit { expect {Piwik::Site.load(666)}.to raise_error } end it { subject.seo_info.first['rank'].to_i.should eq(7) } describe '#annotations' do subject { build(:site).annotations } it { subject.all.size.should eq(2) } it { expect { subject.update(1,{:pattern => 2}) }.not_to raise_error } it { expect { subject.delete(1) }.not_to raise_error } it { subject.add(:name => 'test', :note => 'meah', :starred => 1).size.should eq(6) } it { expect { subject.count_for_dates }.not_to raise_error } end describe '#visits' do subject { build(:site).visits } it { subject.summary.should be_a(Piwik::VisitsSummary) } it { subject.count.should eq(200) } it { subject.actions.should eq(55) } it { subject.uniques.should eq(100) } it { subject.bounces.should eq(51) } it { subject.converted.should eq(0) } it { subject.max_actions.should eq(66) } it { subject.length.should eq(143952) } it { subject.pretty_length.should eq("1 days 15 hours") } end describe '#actions' do subject { build(:site).actions } it { subject.summary.should be_a(Piwik::Actions) } it { subject.urls.size.should eq(7) } it { subject.entry_urls.size.should eq(5) } it { subject.exit_urls.size.should eq(5) } it { subject.downloads.size.should eq(2) } it { subject.outlinks.size.should eq(11) } it { subject.outlink('http://mysite.com').exit_nb_visits.should eq(5) } end describe '#referrers' do subject { build(:site).referrers } it { subject.websites.size.should eq(27) } it { subject.websites_count.should eq(27) } it { subject.keywords.size.should eq(10) } it { subject.keywords_for_title('A page title').size.should eq(1) } it { subject.keywords_for_url('http://mysite.com/page.html').size.should eq(5) } it { subject.keywords_count.should eq(207) } it { subject.search_engines.size.should eq(7) } it { subject.search_engines_count.should eq(7) } it { subject.socials.size.should eq(0) } end describe '#goals' do subject { build(:site).goals } it { subject.all.size.should eq(3) } it { subject.load(1).nb_conversions.should eq(82) } it { expect { subject.update(1,{:pattern => 2}) }.not_to raise_error } it { expect { subject.delete(1) }.not_to raise_error } it { expect { subject.add(:name => 'test', 'matchAttribute' => '/', :pattern => '/', :patternType => 1) }.not_to raise_error } end describe '#transitions' do subject { build(:site).transitions } it { subject.for_action('name','type').should be_a(Piwik::Transitions::TransitionsForAction) } it { subject.for_title('My page title').should be_a(Piwik::Transitions::TransitionsForPageTitle) } it { subject.for_url('http://mysite.com').should be_a(Piwik::Transitions::TransitionsForPageUrl) } it { subject.translations.size.should eq(32) } end describe "that exists" do before { @site = build(:site) @site.save } it { expect {Piwik::Site.load(@site.id)}.to_not raise_error } end end
piwik/piwik-ruby-api
spec/site_spec.rb
Ruby
mit
3,720
@extends('connexion::templates.backend') @section('css') @parent @stop @section('content') <div class="container-fluid spark-screen"> @include('connexion::shared.errors') <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-6"><h4>Events</h4></div> <div class="col-md-6"><a href="{{route('admin.events.create')}}" class="btn btn-primary pull-right"><i class="fa fa-pencil"></i> Add a new event</a></div> </div> </div> <div class="panel-body"> <table id="indexTable" class="table table-striped table-hover table-condensed table-responsive" width="100%" cellspacing="0"> <thead> <tr> <th>Event name</th><th>Participants</th><th>Event date</th> </tr> </thead> <tfoot> <tr> <th>Event name</th><th>Participants</th><th>Event date</th> </tr> </tfoot> <tbody> @forelse ($events as $event) <tr> <td><a href="{{route('admin.events.show',$event->id)}}">{{$event->groupname}}</a></td> <td><a href="{{route('admin.events.show',$event->id)}}">{{count($event->individuals)}}</a></td> <td> <a href="{{route('admin.events.show',$event->id)}}">{{date("Y-m-d H:i",$event->eventdatetime)}}</a> </td> </tr> @empty <tr><td>No events have been added yet</td></tr> @endforelse </tbody> </table> </div> </div> </div> </div> </div> @include('connexion::shared.delete-modal') @endsection @section('js') @parent <script language="javascript"> @include('connexion::shared.delete-modal-script') $(document).ready(function() { $('#indexTable').DataTable(); } ); </script> @endsection
bishopm/connexion
src/Resources/views/events/index.blade.php
PHP
mit
2,649
using S22.Xmpp.Core; using System; using System.Xml; namespace S22.Xmpp.Extensions.Dataforms { /// <summary> /// Represents a field for gathering or providing a single line or word of /// text, which shall be obscured in an interface (e.g., with multiple /// instances of the asterisk character). /// </summary> /// <remarks> /// This corresponds to a Winforms TextBox control with the added /// requirement that entered characters be obscured. /// </remarks> public class PasswordField : DataField { /// <summary> /// The value of the field. /// </summary> public string Value { get { var v = element["value"]; return v != null ? v.InnerText : null; } private set { if (element["value"] != null) { if (value == null) element.RemoveChild(element["value"]); else element["value"].InnerText = value; } else { if (value != null) element.Child(Xml.Element("value").Text(value)); } } } /// <summary> /// Initializes a new instance of the PasswordFild class for use in a /// requesting dataform. /// </summary> /// <param name="name">The name of the field.</param> /// <param name="required">Determines whether the field is required or /// optional.</param> /// <param name="label">A human-readable name for the field.</param> /// <param name="description">A natural-language description of the field, /// intended for presentation in a user-agent.</param> /// <param name="value">The default value of the field.</param> /// <exception cref="ArgumentNullException">The name parameter is /// null.</exception> public PasswordField(string name, bool required = false, string label = null, string description = null, string value = null) : base(DataFieldType.TextPrivate, name, required, label, description) { name.ThrowIfNull("name"); Value = value; } /// <summary> /// Initializes a new instance of the PasswordField class for use in a /// submitting dataform. /// </summary> /// <param name="name">The name of the field.</param> /// <param name="value">The value of the field.</param> /// <exception cref="ArgumentNullException">The name parameter is /// null.</exception> public PasswordField(string name, string value) : this(name, false, null, null, value) { } /// <summary> /// Initializes a new instance of the PasswordField class from the specified /// XML element. /// </summary> /// <param name="element">The XML 'field' element to initialize the instance /// with.</param> /// <exception cref="ArgumentNullException">The element parameter is /// null.</exception> /// <exception cref="ArgumentException">The specified XML element is not a /// valid data-field element, or the element is not a data-field of type /// 'text-private'.</exception> internal PasswordField(XmlElement element) : base(element) { AssertType(DataFieldType.TextPrivate); } } }
timaxoxa/S22.Xmpp
Extensions/XEP-0004/Dataforms/PasswordField.cs
C#
mit
2,946
<?php /** * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit; class Edit extends \Magento\Catalog\Controller\Adminhtml\Product\Edit { }
j-froehlich/magento2_wk
vendor/magento/module-downloadable/Controller/Adminhtml/Downloadable/Product/Edit/Edit.php
PHP
mit
272
import React, { PropTypes } from 'react'; import { InlineThumbnail as Thumbnail } from 'modules/common/thumbnail'; const icon = 'local_grocery_store'; const ShopInlineThumbnail = ({ shop, className, onClick }) => { const image = (shop && shop.thumbnail) && shop.thumbnail.thumbnail_80_80; return ( <Thumbnail onClick={onClick} image={image} icon={icon} className={className} /> ); }; ShopInlineThumbnail.propTypes = { shop: PropTypes.object, className: PropTypes.string, onClick: PropTypes.func, }; export default ShopInlineThumbnail;
theseushu/funong-web
app/modules/common/shop/inlineThumbnail.js
JavaScript
mit
555
#!/usr/bin/env ruby # coding: utf-8 bad = " " require "csv" require "mechanize" agent = Mechanize.new{ |agent| agent.history.max_size=0 } agent.user_agent = 'Mozilla/5.0' base = "http://www.basketball-reference.com/leagues" table_xpath = '//*[@id="games"]/tbody/tr' #league_id = "ABA" league_id = "NBA" first_year = 2016 last_year = 2016 #if (first_year==last_year) # stats = CSV.open("csv/games_#{first_year}.csv","w") #else # stats = CSV.open("csv/games_#{first_year}-#{last_year}.csv","w") #end (first_year..last_year).each do |year| # stats = CSV.open("csv/games_#{league_id}_#{year}.csv","w") stats = CSV.open("csv/games_#{year}.csv","w") url = "#{base}/#{league_id}_#{year}_games.html" print "Pulling year #{year}" begin page = agent.get(url) rescue retry end found = 0 page.parser.xpath(table_xpath).each do |r| row = [year] r.xpath("td").each_with_index do |e,i| text = e.text.strip rescue nil if (text==nil) or (text.size==0) text=nil end if ([0,2].include?(i)) if (e.xpath("a").first==nil) row += [text, nil] else href = e.xpath("a").first.attribute("href").to_s.strip rescue nil row += [text, href] end elsif ([3,5].include?(i)) if (e.xpath("a").first==nil) row += [text, nil, nil] else href = e.xpath("a").first.attribute("href").to_s.strip rescue nil id = href.split("/")[-2] row += [text, href, id] end else row += [text] end end if (row.size>1) found += 1 stats << row end end print " - found #{found}\n" stats.close end
octonion/basketball
bbref/scrapers/games.rb
Ruby
mit
1,722
// Copyright (c) 2015, Samvel Khalatyan #include "ch4/bipartile_factory.h" #include <cassert> #include <map> #include <sstream> #include "ch4/s1/depth_first_bipartile.h" using std::string; namespace { using BipartilePtr = algo::BipartileFactory::BipartilePtr; using Builder = BipartilePtr (*)(const algo::Graph& graph); using Builders = std::map<string, Builder>; static const Builders& GetBuilders() { static const Builders builders { {"dfbipartile", [](const algo::Graph& graph) -> BipartilePtr { return BipartilePtr {new algo::DepthFirstBipartile {graph}}; }} }; return builders; } static string GetHelp() { const Builders& builders {GetBuilders()}; std::ostringstream sout; if (not builders.empty()) { sout << "bipartile types:"; for (auto builder : builders) { sout << ' ' << builder.first; } } return sout.str(); } } // namespace namespace algo { bool BipartileFactory::Validate(const string& type) { const Builders& builders {GetBuilders()}; return builders.find(type) != builders.end(); } BipartilePtr BipartileFactory::Create(const string& type, const Graph& graph) { assert(Validate(type)); const Builders& builders {GetBuilders()}; const Builder& builder = builders.at(type); return builder(graph); } const char* BipartileFactory::Help() { static const string help {GetHelp()}; return help.c_str(); } } // namespace algo
ksamdev/algorithms
src/ch4/bipartile_factory.cc
C++
mit
1,481
import pageTitle from 'ember-page-title/helpers/page-title'; export default pageTitle;
tim-evans/ember-page-title
app/helpers/page-title.js
JavaScript
mit
88
'''Operating System Task ''' import types from systemCall import * class Task(object): taskId = 0 def __init__(self, target): self.tid = Task.taskId Task.taskId += 1 self.target = target self.sendVal = None self.name = target.__name__ self.stack = [] def run(self): while True: try: result = self.target.send(self.sendVal) if isinstance(result, SystemCall): return result if isinstance(result, types.GeneratorType): self.stack.append(self.target) self.sendVal = None self.target = result else: print(self.stack) if not self.stack: return self.sendVal = result self.target = self.stack.pop() except StopIteration: if not self.stack: raise self.sendVal = None self.target = self.stack.pop() def terminate(self): return self.target.close() def __str__(self): return '<Task name = %s %#x>' % (self.name, id(self)) if __name__ == '__main__': def simpleTask(): print('[SIMPLE TASK]step 1') yield print('[SIMPLE TASK]step 2') yield task = Task(simpleTask()) task.run() task.run()
JShadowMan/package
python/coroutine/operatingSystem/task.py
Python
mit
1,526
<?php echo $calendar; ?>
chloereimer/sleepy-me-hotel
application/views/calendar.php
PHP
mit
25
import { driver, By2 } from 'selenium-appium' import { until } from 'selenium-webdriver'; const setup = require('../jest-setups/jest.setup'); jest.setTimeout(60000); beforeAll(() => { return driver.startWithCapabilities(setup.capabilites); }); afterAll(() => { return driver.quit(); }); describe('Test App', () => { test('API_URL present', async () => { // Get the element by label, will fail if the element is not present // we use the API_URL from the .env file await driver.wait(until.elementLocated(By2.nativeName('API_URL=http://localhost'))); }); })
luggit/react-native-config
Example/__tests__/ShowEnv.test.js
JavaScript
mit
582
# See http://doc.gitlab.com/ce/development/migration_style_guide.html # for more information on how to write migrations for GitLab. # This migration generates missing routes for any projects and namespaces that # don't already have a route. # # On GitLab.com this would insert 611 project routes, and 0 namespace routes. # The exact number could vary per instance, so we take care of both just in # case. class GenerateMissingRoutes < ActiveRecord::Migration[4.2] include Gitlab::Database::MigrationHelpers DOWNTIME = false disable_ddl_transaction! class User < ActiveRecord::Base self.table_name = 'users' end class Route < ActiveRecord::Base self.table_name = 'routes' end module Routable def build_full_path if parent && path parent.build_full_path + '/' + path else path end end def build_full_name if parent && name parent.human_name + ' / ' + name else name end end def human_name build_full_name end def attributes_for_insert time = Time.zone.now { # We can't use "self.class.name" here as that would include the # migration namespace. source_type: source_type_for_route, source_id: id, created_at: time, updated_at: time, name: build_full_name, # The route path might already be taken. Instead of trying to generate a # new unique name on every conflict, we just append the row ID to the # route path. path: "#{build_full_path}-#{id}" } end end class Project < ActiveRecord::Base self.table_name = 'projects' include EachBatch include GenerateMissingRoutes::Routable belongs_to :namespace, class_name: 'GenerateMissingRoutes::Namespace' has_one :route, as: :source, inverse_of: :source, class_name: 'GenerateMissingRoutes::Route' alias_method :parent, :namespace alias_attribute :parent_id, :namespace_id def self.without_routes where( 'NOT EXISTS ( SELECT 1 FROM routes WHERE source_type = ? AND source_id = projects.id )', 'Project' ) end def source_type_for_route 'Project' end end class Namespace < ActiveRecord::Base self.table_name = 'namespaces' include EachBatch include GenerateMissingRoutes::Routable belongs_to :parent, class_name: 'GenerateMissingRoutes::Namespace' belongs_to :owner, class_name: 'GenerateMissingRoutes::User' has_one :route, as: :source, inverse_of: :source, class_name: 'GenerateMissingRoutes::Route' def self.without_routes where( 'NOT EXISTS ( SELECT 1 FROM routes WHERE source_type = ? AND source_id = namespaces.id )', 'Namespace' ) end def source_type_for_route 'Namespace' end end def up [Namespace, Project].each do |model| model.without_routes.each_batch(of: 100) do |batch| rows = batch.map(&:attributes_for_insert) Gitlab::Database.bulk_insert(:routes, rows) end end end def down # Removing routes we previously generated makes no sense. end end
axilleas/gitlabhq
db/migrate/20180702134423_generate_missing_routes.rb
Ruby
mit
3,300
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Podcasts { public class PlaylistState: Notifier { bool isPlaying; public bool IsPlaying { get { return isPlaying; } set { isPlaying = value; RaisePropertyChanged(nameof(IsPlaying)); } } bool isLoading = true; public bool IsLoading { get { return isLoading; } set { isLoading = value; RaisePropertyChanged(nameof(IsLoading)); } } bool isStreaming; public bool IsStreaming { get { return isStreaming; } set { isStreaming = value; RaisePropertyChanged(nameof(IsStreaming)); } } } }
deltakosh/Podcasts
Podcasts.Common/Models/PlaylistState.cs
C#
mit
1,079
require "helper" require "generators/minitest/mailer/mailer_generator" class TestMailerGenerator < GeneratorTest def test_mailer_generator assert_output(/create test\/mailers\/notification_mailer_test.rb/m) do Minitest::Generators::MailerGenerator.start ["notification", "--no-spec"] end assert File.exists? "test/mailers/notification_mailer_test.rb" contents = File.read "test/mailers/notification_mailer_test.rb" assert_match(/class NotificationMailerTest/m, contents) end def test_namespaced_mailer_generator assert_output(/create test\/mailers\/admin\/notification_mailer_test.rb/m) do Minitest::Generators::MailerGenerator.start ["admin/notification", "--no-spec"] end assert File.exists? "test/mailers/admin/notification_mailer_test.rb" contents = File.read "test/mailers/admin/notification_mailer_test.rb" assert_match(/class Admin::NotificationMailerTest/m, contents) end def test_mailer_generator_spec assert_output(/create test\/mailers\/notification_mailer_test.rb/m) do Minitest::Generators::MailerGenerator.start ["notification", "welcome"] end assert File.exists? "test/mailers/notification_mailer_test.rb" contents = File.read "test/mailers/notification_mailer_test.rb" assert_match(/describe NotificationMailer do/m, contents) end def test_namespaced_mailer_generator_spec assert_output(/create test\/mailers\/admin\/notification_mailer_test.rb/m) do Minitest::Generators::MailerGenerator.start ["admin/notification", "welcome"] end assert File.exists? "test/mailers/admin/notification_mailer_test.rb" contents = File.read "test/mailers/admin/notification_mailer_test.rb" assert_match(/describe Admin::NotificationMailer do/m, contents) end end
lrosskamp/makealist-public
vendor/cache/ruby/2.3.0/gems/minitest-rails-3.0.0/test/generators/test_mailer_generator.rb
Ruby
mit
1,791
describe "Spotify::API" do describe "#link_as_string" do let(:link) { double } it "reads the link as an UTF-8 encoded string" do expect(api).to receive(:sp_link_as_string).twice do |ptr, buffer, buffer_size| expect(ptr).to eq(link) buffer.write_bytes("spotify:user:burgestrandX") if buffer 24 end string = api.link_as_string(link) expect(string).to eq "spotify:user:burgestrand" expect(string.encoding).to eq(Encoding::UTF_8) end end describe "#link_as_track_and_offset" do let(:link) { double } let(:track) { double } it "reads the link as a track with offset information" do expect(api).to receive(:sp_link_as_track_and_offset) do |ptr, offset_pointer| expect(ptr).to eq(link) offset_pointer.write_int(6000) track end expect(api.link_as_track_and_offset(link)).to eq([track, 6000]) end it "returns nil if the link is not a track link" do expect(api).to receive(:sp_link_as_track_and_offset) do |ptr, offset_pointer| nil end expect(api.link_as_track_and_offset(link)).to be_nil end end end
fgbreel/spotify
spec/spotify/api/link_spec.rb
Ruby
mit
1,164