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
using System; namespace work.bacome.imapclient { public partial class cIMAPClient { private partial class cSession { public enum eGreetingType { ok, preauth, bye } public struct sGreeting { public readonly eGreetingType Type; public readonly cResponseText ResponseText; public sGreeting(eGreetingType pType, cResponseText pResponseText) { Type = pType; ResponseText = pResponseText; } } } } }
bacome/imapclient
imapclient/imapclient/session/support/greeting.cs
C#
mit
602
import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.*; public class ScoreCollectionTest { @Test public void answersArithmeticMeanOfTwoNumbers() { // arrange ScoreCollection collection = new ScoreCollection(); collection.add(() -> 5); collection.add(() -> 7); // act int actualResult = collection.arithmeticMean(); // assert assertThat(actualResult, equalTo(6)); } }
ordinary-developer/book_pragmatic_unit_testing_in_java_8_with_junit_j_langr
my_code/chapter_1_BUILDING_YOUR_FIRST_JUNIT_TEST/ScoreCollectionTest.java
Java
mit
488
export { Button, ButtonFactory } from './Button';
eldarlabs/cycle-ui
src/button/index.ts
TypeScript
mit
50
namespace System.Text.RegularExpressions { using System; using System.Globalization; internal sealed class RegexFC { internal bool _caseInsensitive; internal RegexCharClass _cc; internal bool _nullable; internal RegexFC(bool nullable) { this._cc = new RegexCharClass(); this._nullable = nullable; } internal RegexFC(string set, bool nullable, bool caseInsensitive) { this._cc = new RegexCharClass(); this._cc.AddSet(set); this._nullable = nullable; this._caseInsensitive = caseInsensitive; } internal RegexFC(char ch, bool not, bool nullable, bool caseInsensitive) { this._cc = new RegexCharClass(); if (not) { if (ch > '\0') { this._cc.AddRange('\0', (char) (ch - '\x0001')); } if (ch < 0xffff) { this._cc.AddRange((char) (ch + '\x0001'), (char)0xffff); } } else { this._cc.AddRange(ch, ch); } this._caseInsensitive = caseInsensitive; this._nullable = nullable; } internal void AddFC(RegexFC fc, bool concatenate) { if (concatenate) { if (!this._nullable) { return; } if (!fc._nullable) { this._nullable = false; } } else if (fc._nullable) { this._nullable = true; } this._caseInsensitive |= fc._caseInsensitive; this._cc.AddCharClass(fc._cc); } internal string GetFirstChars(CultureInfo culture) { return this._cc.ToSetCi(this._caseInsensitive, culture); } internal bool IsCaseInsensitive() { return this._caseInsensitive; } } }
wizzard0/dotNetAnywhere-wb
System/System.Text.RegularExpressions/RegexFC.cs
C#
mit
2,214
'use strict'; /** * Created by Alex Levshin on 26/11/16. */ var RootFolder = process.env.ROOT_FOLDER; if (!global.rootRequire) { global.rootRequire = function (name) { return require(RootFolder + '/' + name); }; } var restify = require('restify'); var _ = require('lodash'); var fs = require('fs'); var expect = require('chai').expect; var ApiPrefix = '/api/v1'; var Promise = require('promise'); var config = rootRequire('config'); var util = require('util'); var WorktyRepositoryCodePath = RootFolder + '/workties-repository'; var SubVersion = config.restapi.getLatestVersion().sub; // YYYY.M.D // Init the test client using supervisor account (all acl permissions) var adminClient = restify.createJsonClient({ version: SubVersion, url: config.restapi.getConnectionString(), headers: { 'Authorization': config.supervisor.getAuthorizationBasic() // supervisor }, rejectUnauthorized: false }); describe('Workflow Rest API', function () { var WorkflowsPerPage = 3; var Workflows = []; var WorktiesPerPage = 2; var Workties = []; var WorktiesInstances = []; var WORKTIES_FILENAMES = ['unsorted/nodejs/unit-tests/without-delay.zip']; console.log('Run Workflow API tests for version ' + ApiPrefix + '/' + SubVersion); function _createPromises(callback, count) { var promises = []; for (var idx = 0; idx < count; idx++) { promises.push(callback(idx)); } return promises; } function _createWorkty(idx) { return new Promise(function (resolve, reject) { try { var compressedCode = fs.readFileSync(WorktyRepositoryCodePath + '/' + WORKTIES_FILENAMES[0]); adminClient.post(ApiPrefix + '/workties', { name: 'myworkty' + idx, desc: 'worktydesc' + idx, compressedCode: compressedCode, template: true }, function (err, req, res, data) { var workty = data; adminClient.post(ApiPrefix + '/workties/' + data._id + '/properties', { property: { name: 'PropertyName', value: 'PropertyValue' } }, function (err, req, res, data) { workty.propertiesIds = [data]; resolve({res: res, data: workty}); }); }); } catch (ex) { reject(ex); } }); } function _createWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.post(ApiPrefix + '/workflows', { name: 'myworkflow' + idx, desc: 'workflowdesc' + idx }, function (err, req, res, data) { resolve({res: res, data: data}); }); } catch (ex) { reject(ex); } }); } function _createWorktyInstance(idx) { return new Promise(function (resolve, reject) { try { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { name: 'worktyinstance' + idx, desc: 'worktyinstance' + idx, worktyId: Workties[idx]._id, embed: 'properties' }, function (err, req, res, data) { resolve({res: res, data: data}); }); } catch (ex) { reject(ex); } }); } // Delete workflows and workties function _deleteWorkty(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workties/' + Workties[idx]._id, function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } function _deleteWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workflows/' + Workflows[idx]._id, function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } // Run once before the first test case before(function (done) { Promise.all(_createPromises(_createWorkty, WorktiesPerPage)).then(function (results) { // Create workties for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; Workties.push(data); } return Promise.all(_createPromises(_createWorkflow, WorkflowsPerPage)); }).then(function (results) { // Create workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; Workflows.push(data); } return Promise.all(_createPromises(_createWorktyInstance, WorktiesPerPage)); }).then(function (results) { // Create workties instances for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; WorktiesInstances.push(data); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); // Run once after the last test case after(function (done) { Promise.all(_createPromises(_deleteWorkty, WorktiesPerPage)).then(function (results) { // Delete workties for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } return Promise.all(_createPromises(_deleteWorkflow, WorkflowsPerPage)); }).then(function (results) { // Delete workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); describe('.getAll()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length.above(1); done(); }); }); it('should get 3', function (done) { adminClient.get(ApiPrefix + '/workflows?page_num=1&per_page=3', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); done(); }); }); it('should get 2', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=2', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('3'); done(); }); }); it('should get sorted', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&sort=_id', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { var currentValue = null; _.each(workflows, function (workflow) { if (!currentValue) { currentValue = workflow._id; } else { if (workflow._id <= currentValue) expect(true).to.be.false(); currentValue = workflow._id; } }); return true; }); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&fields=_id,name,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { _.each(workflows, function (workflow) { expect(workflow).to.have.keys(['_id', 'name', 'desc']); }); return true; }); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&embed=worktiesInstances,account', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { _.each(workflows, function (workflow) { expect(workflow).to.contain.keys('accountId', 'worktiesInstancesIds'); expect(workflow.accountId).to.contain.keys('_id'); if (workflow.worktiesInstancesIds.length > 0) { expect(workflow.worktiesInstancesIds[0]).to.contain.keys('_id'); } }); return true; }); done(); }); }); }); describe('.getById()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.get(ApiPrefix + '/workflows/' + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('1'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?fields=_id,name,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.have.keys(['_id', 'name', 'desc']); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?embed=worktiesInstances,account', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.contain.keys('accountId', 'worktiesInstancesIds'); expect(data.accountId).to.contain.keys('_id'); if (data.worktiesInstancesIds.length > 0) { expect(data.worktiesInstancesIds[0]).to.contain.keys('_id'); } done(); }); }); }); describe('.add()', function () { it('should get a 409 response', function (done) { adminClient.post(ApiPrefix + '/workflows', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); var error = JSON.parse(err.message).error; expect(error.message).to.equals("Validation Error"); expect(error.errors).to.have.length(1); expect(error.errors[0].message).to.equals("Path `name` is required."); done(); }); }); it('should get a 201 response', function (done) { // Create workflow adminClient.post(ApiPrefix + '/workflows', { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); expect(data.name).to.be.equal('mytestworkflow'); expect(data.desc).to.be.equal('testworkflow'); // Delete workflow adminClient.del(res.headers.location, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.update()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 409 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, {name: ''}, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); var error = JSON.parse(err.message).error; expect(error.errors).to.have.length(1); expect(error.errors[0].message).to.equals("Path `name` is required."); done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.null; var workflowId = data._id; expect(workflowId).to.equals(Workflows[0]._id); expect(data.name).to.be.equal('mytestworkflow'); expect(data.desc).to.be.equal('testworkflow'); done(); }); }); }); describe('.del()', function () { it('should get a 500 response not found', function (done) { // Delete workflow adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); done(); }); }); it('should get a 204 response', function (done) { // Create workflow adminClient.post(ApiPrefix + '/workflows', { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); // Delete workflow adminClient.del(ApiPrefix + '/workflows/' + workflowId, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.run()', function () { it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); describe('multiple workflows', function () { var WorkflowExtraPerPage = 2; var WorkflowExtraIds = []; function _deleteExtraWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workflows/' + WorkflowExtraIds[idx], function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } // Run once before the first test case before(function (done) { Promise.all(_createPromises(_createWorkflow, WorkflowExtraPerPage)).then(function (results) { // Create workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; WorkflowExtraIds.push(data._id); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); // Run once after the last test case after(function (done) { Promise.all(_createPromises(_deleteExtraWorkflow, WorkflowExtraPerPage)).then(function (results) { // Delete workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); }); }); describe('.stop()', function () { it('should get a 200 response', function (done) { // Run workflow adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); done(); }); }); it('should get a 500 response not found', function (done) { adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 200 response after two stops', function (done) { // Run workflow adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; // Stop workflow twice adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); done(); }); }); }); }); }); describe('.resume()', function () { it('should get a 200 response', function (done) { // Resume workflow adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); }); describe('Workties instances', function () { describe('.getAllWorktiesInstances()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length.above(0); expect(data[0].workflowId).to.equals(Workflows[0]._id); done(); }); }); it('should get 2', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('2'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&fields=_id,desc,created', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(data).to.satisfy(function (workflowInstances) { _.each(workflowInstances, function (workflowInstance) { expect(workflowInstance).to.have.keys(['_id', 'desc', 'created']); }); return true; }); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&embed=workflow,state', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(data).to.satisfy(function (workflowInstances) { _.each(workflowInstances, function (workflowInstance) { expect(workflowInstance).to.contain.keys('stateId', 'workflowId'); expect(workflowInstance.workflowId).to.contain.keys('_id'); if (workflowInstance.stateId.length > 0) { expect(workflowInstance.stateId[0]).to.contain.keys('_id'); } }); return true; }); done(); }); }); }); describe('.getWorktyInstanceById()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('1'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?fields=_id,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.have.keys(['_id', 'desc']); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?embed=workflow,state', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.contain.keys('stateId', 'workflowId'); expect(data.stateId).to.contain.keys('_id'); expect(data.workflowId).to.contain.keys('_id'); expect(data.workflowId._id).to.equals(Workflows[0]._id); done(); }); }); }); describe('.addWorktyInstance()', function () { it('should get a 201 response', function (done) { // Create workty instance adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { desc: 'descworktyinstance4', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; expect(data.worktyId).to.be.equal(Workties[0]._id); expect(data.desc).to.be.equal('descworktyinstance4'); // Delete workty instance adminClient.del(res.headers.location, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); it('should get a 500 response with code 12 position type is unknown', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=unknown', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(12); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 201 response for position type is last', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=last', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added in last position adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return worktyInstanceId === worktiesInstancesIds[worktiesInstancesIds.length - 1]; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 201 response for position type is first', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=first', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added in first position adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return worktyInstanceId === worktiesInstancesIds[0]; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 201 response for position index is 0 among 4 values', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 500 response with code 10 for position index is -1', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(10); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 500 response with code 11 for missing position id', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=N', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(11); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 201 response for position id', function (done) { // Insert workty by index 0 adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocationFirst = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Insert workty instance before worktyInstanceId adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=' + worktyInstanceId, { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 4) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Delete first workty instance adminClient.del(headerLocationFirst, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); // Delete second workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); }); }); }); it('should get a 500 response with code 1 for missing worktyId', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', {desc: 'testworkty'}, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'errors', 'inputParameters']); expect(data.error.code).is.empty; expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); }); describe('.updateWorktyInstance()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, {desc: 'updateddesc'}, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.null; expect(data.desc).to.be.equal('updateddesc'); done(); }); }); }); describe('.delWorktyInstance()', function () { it('should get a 500 response not found', function (done) { // Delete workty instance adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); done(); }); }); it('should get a 204 response', function (done) { // Create workty instance adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data.workflowId; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); // Delete workty instance adminClient.del(ApiPrefix + '/workflows/' + workflowId + '/worktiesInstances/' + worktyInstanceId, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.updateWorktyInstanceProperty()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, { name: 'NewPropertyName', value: 'NewPropertyValue' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data.name).to.be.equal('NewPropertyName'); expect(data.value).to.be.equal('NewPropertyValue'); done(); }); }); }); }); });
AlexLevshin/workty
tests/functional/v1/restapi/workflow-controller.spec.js
JavaScript
mit
50,622
using System; using System.Collections.Immutable; using System.IO; using System.Xml; using Xunit; namespace WarHub.ArmouryModel.Source.CodeGeneration.Tests { public class SerializationTests { [Fact] public void CheckEmptyDeserialization() { const string ContainerXml = "<container/>"; var serializer = new XmlFormat.ContainerCoreXmlSerializer(); using var reader = XmlReader.Create(new StringReader(ContainerXml)); var container = (ContainerCore)serializer.Deserialize(reader)!; Assert.Null(container.Id); Assert.Null(container.Name); Assert.Empty(container.Items); Assert.True(container.Items.IsEmpty); } [Fact] public void ContainerSerializesAndDeserializes() { var emptyGuid = Guid.Empty.ToString(); const string ContainerName = "Container0"; const string Item1Name = "Item1"; const string Item2Name = "Item2"; const string Item3Name = "Item3"; var profileType = new ContainerCore { Id = emptyGuid, Name = ContainerName, Items = ImmutableArray.Create( new ItemCore { Id = emptyGuid, Name = Item1Name }, new ItemCore { Id = emptyGuid, Name = Item2Name }, new ItemCore { Id = emptyGuid, Name = Item3Name }) }; var serializer = new XmlFormat.ContainerCoreXmlSerializer(); using var stream = new MemoryStream(); serializer.Serialize(stream, profileType); stream.Position = 0; using var reader = XmlReader.Create(stream); var deserialized = (ContainerCore)serializer.Deserialize(reader)!; Assert.NotNull(deserialized); Assert.Equal(ContainerName, deserialized.Name); Assert.Collection( deserialized.Items, x => Assert.Equal(Item1Name, x.Name), x => Assert.Equal(Item2Name, x.Name), x => Assert.Equal(Item3Name, x.Name)); } } }
WarHub/wham
tests/WarHub.ArmouryModel.Source.CodeGeneration.Tests/SerializationTests.cs
C#
mit
2,445
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Xml.Linq; using System.Windows.Forms; namespace NetOffice.DeveloperToolbox.ToolboxControls.OfficeCompatibility { /// <summary> /// Shows a detailed usage report for an analyzed assembly /// </summary> [ResourceTable("ToolboxControls.OfficeCompatibility.Report.txt")] public partial class ReportControl : UserControl { #region Fields private AnalyzerResult _report; #endregion #region Construction /// <summary> /// Creates an instance of the class /// </summary> public ReportControl() { InitializeComponent(); pictureBoxField.Image = imageList1.Images[3]; pictureBoxProperty.Image = imageList1.Images[7]; pictureBoxMethod.Image = imageList1.Images[5]; } /// <summary> /// Creates an instance of the class /// </summary> /// <param name="report">detailed report</param> public ReportControl(AnalyzerResult report) { InitializeComponent(); if (null == report.Report) return; _report = report; comboBoxFilter.SelectedIndex = 0; pictureBoxField.Image = imageList1.Images[3]; pictureBoxProperty.Image = imageList1.Images[7]; pictureBoxMethod.Image = imageList1.Images[5]; if (treeViewReport.Nodes.Count > 0) treeViewReport.SelectedNode = treeViewReport.Nodes[0]; } #endregion #region Methods private int GetPercent(int value, int percent) { return value / 100 * percent; } private int GetImageClassIndex(XElement itemClass) { if (itemClass.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 1; else return 2; } private int GetImageFieldIndex(XElement itemField) { if (itemField.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 3; else return 4; } private int GetImageMethodIndex(XElement itemMethod) { if (itemMethod.Attribute("IsProperty").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) { if (itemMethod.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 7; else return 8; } else { if (itemMethod.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 5; else return 6; } } private void ShowAssembly() { treeViewReport.Nodes.Clear(); foreach (XElement item in _report.Report.Document.Root.Elements("Assembly")) { string name = item.Attribute("Name").Value; if (name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase) > 0) name = name.Substring(0, name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase)); TreeNode node = treeViewReport.Nodes.Add(name); node.ImageIndex = 0; node.SelectedImageIndex = 0; node.Tag = item; foreach (XElement itemClass in item.Element("Classes").Elements("Class")) { TreeNode classNode = node.Nodes.Add(itemClass.Attribute("Name").Value); classNode.ImageIndex = GetImageClassIndex(itemClass); classNode.SelectedImageIndex = GetImageClassIndex(itemClass); classNode.Tag = itemClass; foreach (XElement itemField in itemClass.Element("Fields").Elements("Entity")) { if (FilterPassed(itemField.Element("SupportByLibrary"))) { TreeNode fieldNode = classNode.Nodes.Add(itemField.Attribute("Name").Value); fieldNode.ImageIndex = GetImageFieldIndex(itemField); fieldNode.SelectedImageIndex = GetImageFieldIndex(itemField); fieldNode.Tag = itemField; } } foreach (XElement itemMethod in itemClass.Element("Methods").Elements("Method")) { bool filterPassed = false; foreach (XElement itemFilterNode in itemMethod.Descendants("SupportByLibrary")) { if (FilterPassed(itemFilterNode)) { filterPassed = true; break; } } if (filterPassed) { string methodName = itemMethod.Attribute("Name").Value; if(methodName.StartsWith("get_")) { methodName = methodName.Substring(4); TreeNode methodNode = classNode.Nodes.Add(methodName, methodName); methodNode.ImageIndex = GetImageMethodIndex(itemMethod); methodNode.SelectedImageIndex = GetImageMethodIndex(itemMethod); methodNode.Tag = itemMethod; } else if( methodName.StartsWith("set_")) { methodName = methodName.Substring(4); List<XElement> list = new List<XElement>(); TreeNode getNode = classNode.Nodes[methodName]; list.Add(getNode.Tag as XElement); list.Add(itemMethod); getNode.Tag = list; } else { TreeNode methodNode = classNode.Nodes.Add(methodName); methodNode.ImageIndex = GetImageMethodIndex(itemMethod); methodNode.SelectedImageIndex = GetImageMethodIndex(itemMethod); methodNode.Tag = itemMethod; } } } } } panelView.Dock = DockStyle.Fill; panelNativeView.Dock = DockStyle.Fill; if (treeViewReport.Nodes.Count > 0) treeViewReport.Nodes[0].Expand(); } private void SetMethodCalls(XElement element) { XElement parametersNode = element.Element("Calls"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { string name = item.Attribute("Name").Value; if (name.IndexOf("::", StringComparison.InvariantCultureIgnoreCase) > -1) name = name.Substring(0,name.IndexOf("::", StringComparison.InvariantCultureIgnoreCase)); string type = item.Element("SupportByLibrary").Attribute("Name").Value; if (type.IndexOf("::", StringComparison.InvariantCultureIgnoreCase) > -1) type = type.Substring(type.IndexOf("::", StringComparison.InvariantCultureIgnoreCase) + 2); if (FilterPassed(item.Element("SupportByLibrary"))) { ListViewItem paramViewItem = listViewDetail.Items.Add("Call Method: " + name); paramViewItem.SubItems.Add(type); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } XElement itemParameters = item.Element("Parameters"); if (null != itemParameters) { foreach (XElement paramItem in itemParameters.Elements("Parameter")) { if (!FilterPassed(paramItem.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem2 = listViewDetail.Items.Add(" Parameter"); paramViewItem2.SubItems.Add(paramItem.Element("SupportByLibrary").Attribute("Name").Value); string supportText = paramItem.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersionParam in paramItem.Element("SupportByLibrary").Elements("Version")) supportText += itemVersionParam.Value + " "; paramViewItem2.SubItems.Add(supportText); } } } listViewDetail.Items.Add(""); } } private void SetMethodLocalFieldSets(XElement element) { XElement parametersNode = element.Element("LocalFieldSets"); if ((null != parametersNode) && (parametersNode.Elements("Field").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Field")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Set Local Variable " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Element("SupportByLibrary").Attribute("Name").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodFieldSets(XElement element) { XElement parametersNode = element.Element("FieldSets"); if ((null != parametersNode) && (parametersNode.Elements("Field").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Field")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Set Class Field " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Element("SupportByLibrary").Attribute("Name").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetNewObjects(XElement element) { XElement parametersNode = element.Element("NewObjects"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("new " + item.Attribute("Type").Value + "()"); paramViewItem.SubItems.Add(item.Attribute("Type").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodVariables(XElement element) { XElement parametersNode = element.Element("Variables"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Locale Variable " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Attribute("Type").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodParameters(XElement element) { XElement parametersNode = element.Element("Parameters"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Parameter " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Attribute("Type").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodReturnValue(XElement element) { XElement returnValueNode = element.Element("ReturnValue"); if (null != returnValueNode) { if (!FilterPassed(returnValueNode.Element("Entity").Element("SupportByLibrary"))) return; string valType = returnValueNode.Element("Entity").Attribute("FullType").Value; ListViewItem viewItem = listViewDetail.Items.Add("Return Value"); viewItem.SubItems.Add(valType); string supportText = returnValueNode.Element("Entity").Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement versionItem in returnValueNode.Element("Entity").Element("SupportByLibrary").Elements("Version")) supportText += versionItem.Value + " "; viewItem.SubItems.Add(supportText); listViewDetail.Items.Add(""); } } private bool FilterPassed(XElement supportNode) { if (0 == comboBoxFilter.SelectedIndex) return true; bool found09 = false; bool found10 = false; bool found11 = false; bool found12 = false; bool found14 = false; bool found15 = false; bool found16 = false; foreach (XElement itemVersion in supportNode.Elements("Version")) { switch (itemVersion.Value) { case "9": found09 = true; break; case "10": found10 = true; break; case "11": found11 = true; break; case "12": found12 = true; break; case "14": found14 = true; break; case "15": found15 = true; break; case "16": found16 = true; break; default: break; } } switch (comboBoxFilter.SelectedIndex) { case 1: // 09 if (found09) return false; break; case 2: // 10 if (found10) return false; break; case 3: // 11 if (found11) return false; break; case 4: // 12 if (found12) return false; break; case 5: // 14 if (found14) return false; break; case 6: // 15 if (found15) return false; break; case 7: // 16 if (found16) return false; break; } return true; } private string GetLogFileContent() { return _report.Report.ToString(); } #endregion #region Trigger private void buttonClose_Click(object sender, EventArgs e) { this.Hide(); } private void ShowDetails(List<XElement> elements) { listViewDetail.Items.Clear(); foreach (XElement element in elements) ShowDetails(element, false); } private void ShowDetails(XElement element, bool clearOldItems) { switch (element.Name.ToString()) { case "Assembly": listViewDetail.Columns.Clear(); listViewDetail.Columns.Add(""); listViewDetail.Columns[0].Width = listViewDetail.Width - 50; listViewDetail.Columns[0].Text = "Assenbly"; listViewDetail.Items.Add(element.Attribute("Name").Value); break; case "Class": listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); listViewDetail.Columns.Add(""); listViewDetail.Columns[0].Width = listViewDetail.Width - 50; listViewDetail.Columns[0].Text = "Class"; listViewDetail.Items.Add(element.Attribute("Name").Value); break; case "Entity": listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); listViewDetail.Columns.Add("Name"); listViewDetail.Columns.Add("Type"); listViewDetail.Columns.Add("Support"); listViewDetail.Columns[0].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[0].Tag = 25; listViewDetail.Columns[1].Width = GetPercent(listViewDetail.Width, 50); listViewDetail.Columns[1].Tag = 50; listViewDetail.Columns[2].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[2].Tag = 25; if (!FilterPassed(element.Element("SupportByLibrary"))) break; listViewDetail.Items.Add(element.Attribute("Name").Value); listViewDetail.Items[0].SubItems.Add(element.Attribute("Type").Value); string supportText = element.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement item in element.Element("SupportByLibrary").Elements("Version")) supportText += item.Value + " "; listViewDetail.Items[0].SubItems.Add(supportText); break; case "Method": if (clearOldItems) listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); listViewDetail.Columns.Add("Instance"); listViewDetail.Columns.Add("Target"); listViewDetail.Columns.Add("Support"); listViewDetail.Columns[0].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[0].Tag = 25; listViewDetail.Columns[1].Width = GetPercent(listViewDetail.Width, 50); listViewDetail.Columns[1].Tag = 50; listViewDetail.Columns[2].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[2].Tag = 25; SetMethodReturnValue(element); SetMethodParameters(element); SetMethodVariables(element); SetMethodLocalFieldSets(element); SetMethodFieldSets(element); SetNewObjects(element); SetMethodCalls(element); break; default: listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); break; } textBoxReport.Text = element.ToString(); } private void treeViewReport_AfterSelect(object sender, TreeViewEventArgs e) { if (null == treeViewReport.SelectedNode) { textBoxReport.Text = ""; return; } XElement element = treeViewReport.SelectedNode.Tag as XElement; if (null != element) { ShowDetails(element, true); } else { List<XElement> elements = treeViewReport.SelectedNode.Tag as List<XElement>; ShowDetails(elements); } } private void checkBoxNativeView_CheckedChanged(object sender, EventArgs e) { try { panelView.Visible = !checkBoxNativeView.Checked; panelNativeView.Visible = checkBoxNativeView.Checked; } catch (Exception exception) { Forms.ErrorForm.ShowError(this, exception,ErrorCategory.NonCritical); } } private void comboBoxFilter_SelectedIndexChanged(object sender, EventArgs e) { try { ShowAssembly(); } catch (Exception exception) { Forms.ErrorForm.ShowError(this, exception, ErrorCategory.NonCritical); } } private void listViewDetail_Resize(object sender, EventArgs e) { foreach (ColumnHeader item in listViewDetail.Columns) { if (item.Tag != null) { int percentValue = Convert.ToInt32(item.Tag); item.Width = GetPercent(listViewDetail.Width, percentValue); } } } private void buttonSaveReport_Click(object sender, EventArgs e) { try { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "*.txt|*.txt"; if(DialogResult.OK == dialog.ShowDialog(this)) { if (File.Exists(dialog.FileName)) File.Delete(dialog.FileName); string logFileContent = GetLogFileContent(); File.AppendAllText(dialog.FileName, logFileContent); } } catch (Exception exception) { Forms.ErrorForm.ShowError(this, exception, ErrorCategory.NonCritical); } } #endregion } }
NetOfficeFw/NetOfficeToolbox
DeveloperToolbox/ToolboxControls/OfficeCompatibility/ReportControl.cs
C#
mit
25,566
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Window { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // ƒ^ƒCƒgƒ‹‚̕ύX Window.Title = "Ookumaneko"; // ƒ}ƒEƒXƒJ[ƒ\ƒ‹‚ð•\ަ‚·‚é IsMouseVisible = true; // ‹N“®’†‚ɃTƒCƒY‚ð•ύX‚Å‚«‚邿‚¤‚É‚·‚é Window.AllowUserResizing = true; } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); base.Draw(gameTime); } } }
ookumaneko/Blog_XNA
Window/Window/Window/Game1.cs
C#
mit
1,692
require.register("scripts/product", function(exports, require, module) { var req = require('scripts/req'); AddStyleTagToItemVM = function(user, styletag_repo) { // this is very similar to AddItemToCollectionVM - yet different. var self = this; self.styletags = styletag_repo.create_filter(); self.styletags.load_until_entry(100); self.target_item = ko.observable(null); self.selected_styletag = ko.observable(); self.show_select_styletag = ko.computed(function() { return self.target_item(); }); self.show_must_login = ko.observable(false); var request_add_styletag_to_item = function(item, styletag, success, error) { req.post("/api/styletag-item/create/", JSON.stringify({'item': item.id, 'styletag': styletag.name}), success, error); }; self.confirmed_must_login = function() { self.show_must_login(false); }; self.confirmed_add_styletag = function() { if (!self.selected_styletag()) { // user selected "Choose..." in the drop-down return; } if (!_.contains(self.target_item().styletags(), self.selected_styletag())) { var success = function() { self.target_item().styletags.push(self.selected_styletag().name); self.target_item(null); }; var error = function() { self.target_item(null); /* TODO: display something to user. */ }; request_add_styletag_to_item(self.target_item(), self.selected_styletag(), success, error); }; }; self.add_to_item = function(item) { if (!user()) { self.show_must_login(true); return; } console.log("lets go add styletag"); self.target_item(item); }; }; ProductVM = function(template_name, item_repo, add_to_collection_vm, favorites_vm, add_styletag_to_item_vm) { var self = this; self.template_name = template_name; self.product = ko.observable(null); self.add_to_collection_vm = add_to_collection_vm; self.favorites_vm = favorites_vm; self.add_styletag_to_item_vm = add_styletag_to_item_vm self.load = function(params) { item_repo.fetch(params.product_id, self.product); } }; exports.ProductVM = ProductVM; exports.AddStyleTagToItemVM = AddStyleTagToItemVM; });
julienaubert/clothstream
frontend/app/scripts/apps/product.js
JavaScript
mit
2,625
module SifttterRedux # DropboxUploader Class # Wrapper class for the Dropbox Uploader project class DropboxUploader # Stores the local filepath. # @return [String] attr_accessor :local_target # Stores the remote filepath. # @return [String] attr_accessor :remote_target # Stores the message to display. # @return [String] attr_accessor :message # Stores the verbosity level. # @return [Boolean] attr_accessor :verbose # Loads the location of dropbox_uploader.sh. # @param [String] dbu_path The local filepath to the script # @param [Logger] A Logger to use # @return [void] def initialize(dbu_path, logger = nil) @dbu = dbu_path @logger = logger end # Downloads files from Dropbox (assumes that both # local_target and remote_target have been set). # @return [void] def download if !@local_target.nil? && !@remote_target.nil? if @verbose system "#{ @dbu } download #{ @remote_target } #{ @local_target }" else exec = `#{ @dbu } download #{ @remote_target } #{ @local_target }` end else error_msg = 'Local and remote targets cannot be nil' @logger.error(error_msg) if @logger fail StandardError, error_msg end end # Uploads files tro Dropbox (assumes that both # local_target and remote_target have been set). # @return [void] def upload if !@local_target.nil? && !@remote_target.nil? if @verbose system "#{ @dbu } upload #{ @local_target } #{ @remote_target }" else exec = `#{ @dbu } upload #{ @local_target } #{ @remote_target }` end else error_msg = 'Local and remote targets cannot be nil' @logger.error(error_msg) if @logger fail StandardError, error_msg end end end end
bachya/Sifttter-Redux
lib/sifttter-redux/dropbox-uploader.rb
Ruby
mit
1,884
using AppKit; using Foundation; namespace ChipmunkSharp.Example.Cocoa { [Register ("AppDelegate")] public class AppDelegate : NSApplicationDelegate { public AppDelegate () { } public override void DidFinishLaunching (NSNotification notification) { // Insert code here to initialize your application } public override void WillTerminate (NSNotification notification) { // Insert code here to tear down your application } } }
netonjm/ChipmunkSharp
samples/ChipmunkSharp.Example.Cocoa/AppDelegate.cs
C#
mit
458
<?php // Connection Component Binding Doctrine_Manager::getInstance()->bindComponent('Spdevalm', 'profit'); /** * BaseSpdevalm * * This class has been auto-generated by the Doctrine ORM Framework * * @property integer $dev_num * @property timestamp $fecha * @property string $alm_orig * @property string $alm_dest * @property string $motivo_glo * @property boolean $confirma * @property timestamp $fec_conf * @property boolean $inactivo * @property string $campo1 * @property string $campo2 * @property string $campo3 * @property string $campo4 * @property string $campo5 * @property string $campo6 * @property string $campo7 * @property string $campo8 * @property string $co_us_in * @property timestamp $fe_us_in * @property string $co_us_mo * @property timestamp $fe_us_mo * @property string $co_us_el * @property timestamp $fe_us_el * @property string $revisado * @property string $reqnfe * @property integer $seriales * @property string $co_sucu * @property boolean $anulada * @property string $dis_cen * @property timestamp $feccom * @property integer $numcom * @property integer $odp_num * @property string $comentario * @property integer $tras_num * @property string $rowguid * @property string $trasnfe * * @method integer getDevNum() Returns the current record's "dev_num" value * @method timestamp getFecha() Returns the current record's "fecha" value * @method string getAlmOrig() Returns the current record's "alm_orig" value * @method string getAlmDest() Returns the current record's "alm_dest" value * @method string getMotivoGlo() Returns the current record's "motivo_glo" value * @method boolean getConfirma() Returns the current record's "confirma" value * @method timestamp getFecConf() Returns the current record's "fec_conf" value * @method boolean getInactivo() Returns the current record's "inactivo" value * @method string getCampo1() Returns the current record's "campo1" value * @method string getCampo2() Returns the current record's "campo2" value * @method string getCampo3() Returns the current record's "campo3" value * @method string getCampo4() Returns the current record's "campo4" value * @method string getCampo5() Returns the current record's "campo5" value * @method string getCampo6() Returns the current record's "campo6" value * @method string getCampo7() Returns the current record's "campo7" value * @method string getCampo8() Returns the current record's "campo8" value * @method string getCoUsIn() Returns the current record's "co_us_in" value * @method timestamp getFeUsIn() Returns the current record's "fe_us_in" value * @method string getCoUsMo() Returns the current record's "co_us_mo" value * @method timestamp getFeUsMo() Returns the current record's "fe_us_mo" value * @method string getCoUsEl() Returns the current record's "co_us_el" value * @method timestamp getFeUsEl() Returns the current record's "fe_us_el" value * @method string getRevisado() Returns the current record's "revisado" value * @method string getReqnfe() Returns the current record's "reqnfe" value * @method integer getSeriales() Returns the current record's "seriales" value * @method string getCoSucu() Returns the current record's "co_sucu" value * @method boolean getAnulada() Returns the current record's "anulada" value * @method string getDisCen() Returns the current record's "dis_cen" value * @method timestamp getFeccom() Returns the current record's "feccom" value * @method integer getNumcom() Returns the current record's "numcom" value * @method integer getOdpNum() Returns the current record's "odp_num" value * @method string getComentario() Returns the current record's "comentario" value * @method integer getTrasNum() Returns the current record's "tras_num" value * @method string getRowguid() Returns the current record's "rowguid" value * @method string getTrasnfe() Returns the current record's "trasnfe" value * @method Spdevalm setDevNum() Sets the current record's "dev_num" value * @method Spdevalm setFecha() Sets the current record's "fecha" value * @method Spdevalm setAlmOrig() Sets the current record's "alm_orig" value * @method Spdevalm setAlmDest() Sets the current record's "alm_dest" value * @method Spdevalm setMotivoGlo() Sets the current record's "motivo_glo" value * @method Spdevalm setConfirma() Sets the current record's "confirma" value * @method Spdevalm setFecConf() Sets the current record's "fec_conf" value * @method Spdevalm setInactivo() Sets the current record's "inactivo" value * @method Spdevalm setCampo1() Sets the current record's "campo1" value * @method Spdevalm setCampo2() Sets the current record's "campo2" value * @method Spdevalm setCampo3() Sets the current record's "campo3" value * @method Spdevalm setCampo4() Sets the current record's "campo4" value * @method Spdevalm setCampo5() Sets the current record's "campo5" value * @method Spdevalm setCampo6() Sets the current record's "campo6" value * @method Spdevalm setCampo7() Sets the current record's "campo7" value * @method Spdevalm setCampo8() Sets the current record's "campo8" value * @method Spdevalm setCoUsIn() Sets the current record's "co_us_in" value * @method Spdevalm setFeUsIn() Sets the current record's "fe_us_in" value * @method Spdevalm setCoUsMo() Sets the current record's "co_us_mo" value * @method Spdevalm setFeUsMo() Sets the current record's "fe_us_mo" value * @method Spdevalm setCoUsEl() Sets the current record's "co_us_el" value * @method Spdevalm setFeUsEl() Sets the current record's "fe_us_el" value * @method Spdevalm setRevisado() Sets the current record's "revisado" value * @method Spdevalm setReqnfe() Sets the current record's "reqnfe" value * @method Spdevalm setSeriales() Sets the current record's "seriales" value * @method Spdevalm setCoSucu() Sets the current record's "co_sucu" value * @method Spdevalm setAnulada() Sets the current record's "anulada" value * @method Spdevalm setDisCen() Sets the current record's "dis_cen" value * @method Spdevalm setFeccom() Sets the current record's "feccom" value * @method Spdevalm setNumcom() Sets the current record's "numcom" value * @method Spdevalm setOdpNum() Sets the current record's "odp_num" value * @method Spdevalm setComentario() Sets the current record's "comentario" value * @method Spdevalm setTrasNum() Sets the current record's "tras_num" value * @method Spdevalm setRowguid() Sets the current record's "rowguid" value * @method Spdevalm setTrasnfe() Sets the current record's "trasnfe" value * * @package gesser * @subpackage model * @author Luis Hernández * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ abstract class BaseSpdevalm extends sfDoctrineRecord { public function setTableDefinition() { $this->setTableName('spdevalm'); $this->hasColumn('dev_num', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => true, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fecha', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(convert(varchar(10),getdate(),104))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('alm_orig', 'string', 6, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 6, )); $this->hasColumn('alm_dest', 'string', 6, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 6, )); $this->hasColumn('motivo_glo', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('confirma', 'boolean', 1, array( 'type' => 'boolean', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('fec_conf', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(convert(varchar(10),getdate(),104))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('inactivo', 'boolean', 1, array( 'type' => 'boolean', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('campo1', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo2', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo3', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo4', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo5', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo6', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo7', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo8', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('co_us_in', 'string', 4, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fe_us_in', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(dateadd(millisecond,(((-datepart(millisecond,getdate())))),getdate()))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('co_us_mo', 'string', 4, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fe_us_mo', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(dateadd(millisecond,(((-datepart(millisecond,getdate())))),getdate()))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('co_us_el', 'string', 4, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fe_us_el', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(dateadd(millisecond,(((-datepart(millisecond,getdate())))),getdate()))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('revisado', 'string', 1, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('reqnfe', 'string', 1, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('seriales', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('co_sucu', 'string', 6, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 6, )); $this->hasColumn('anulada', 'boolean', 1, array( 'type' => 'boolean', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('dis_cen', 'string', 2147483647, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 2147483647, )); $this->hasColumn('feccom', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(convert(varchar(10),getdate(),104))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('numcom', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('odp_num', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('comentario', 'string', 2147483647, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 2147483647, )); $this->hasColumn('tras_num', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('rowguid', 'string', 36, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(newid())', 'primary' => false, 'autoincrement' => false, 'length' => 36, )); $this->hasColumn('trasnfe', 'string', 1, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'primary' => false, 'autoincrement' => false, 'length' => 1, )); } public function setUp() { parent::setUp(); } }
luelher/gesser
lib/model/doctrine/base/BaseSpdevalm.class.php
PHP
mit
19,374
using System.Web; using System.Web.Optimization; namespace MvcOther { public class BundleConfig { // バンドルの詳細については、http://go.microsoft.com/fwlink/?LinkId=301862 を参照してください public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // 開発と学習には、Modernizr の開発バージョンを使用します。次に、実稼働の準備が // できたら、http://modernizr.com にあるビルド ツールを使用して、必要なテストのみを選択します。 bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); // デバッグを行うには EnableOptimizations を false に設定します。詳細については、 // http://go.microsoft.com/fwlink/?LinkId=301862 を参照してください BundleTable.EnableOptimizations = true; } } }
mono0926/ASPNETExercise
samples/MvcOther/MvcOther/App_Start/BundleConfig.cs
C#
mit
1,453
<?php /** * Class for performing HTTP requests * * PHP versions 4 and 5 * * LICENSE: * * Copyright (c) 2002-2007, Richard Heyes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * o 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. * o The names of the authors may not 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. * * @category HTTP * @package HTTP_Request * @author Richard Heyes <richard@phpguru.org> * @author Alexey Borzov <avb@php.net> * @copyright 2002-2007 Richard Heyes * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version CVS: $Id: Request.php,v 1.58 2007/10/26 13:45:56 avb Exp $ * @link http://pear.php.net/package/HTTP_Request/ */ /** * PEAR and PEAR_Error classes (for error handling) */ require_once 'PEAR.php'; /** * Socket class */ require_once 'Socket.php'; /** * URL handling class */ require_once 'URL.php'; /**#@+ * Constants for HTTP request methods */ define('HTTP_REQUEST_METHOD_GET', 'GET', true); define('HTTP_REQUEST_METHOD_HEAD', 'HEAD', true); define('HTTP_REQUEST_METHOD_POST', 'POST', true); define('HTTP_REQUEST_METHOD_PUT', 'PUT', true); define('HTTP_REQUEST_METHOD_DELETE', 'DELETE', true); define('HTTP_REQUEST_METHOD_OPTIONS', 'OPTIONS', true); define('HTTP_REQUEST_METHOD_TRACE', 'TRACE', true); /**#@-*/ /**#@+ * Constants for HTTP request error codes */ define('HTTP_REQUEST_ERROR_FILE', 1); define('HTTP_REQUEST_ERROR_URL', 2); define('HTTP_REQUEST_ERROR_PROXY', 4); define('HTTP_REQUEST_ERROR_REDIRECTS', 8); define('HTTP_REQUEST_ERROR_RESPONSE', 16); define('HTTP_REQUEST_ERROR_GZIP_METHOD', 32); define('HTTP_REQUEST_ERROR_GZIP_READ', 64); define('HTTP_REQUEST_ERROR_GZIP_DATA', 128); define('HTTP_REQUEST_ERROR_GZIP_CRC', 256); /**#@-*/ /**#@+ * Constants for HTTP protocol versions */ define('HTTP_REQUEST_HTTP_VER_1_0', '1.0', true); define('HTTP_REQUEST_HTTP_VER_1_1', '1.1', true); /**#@-*/ if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) { /** * Whether string functions are overloaded by their mbstring equivalents */ define('HTTP_REQUEST_MBSTRING', true); } else { /** * @ignore */ define('HTTP_REQUEST_MBSTRING', false); } /** * Class for performing HTTP requests * * Simple example (fetches yahoo.com and displays it): * <code> * $a = &new HTTP_Request('http://www.yahoo.com/'); * $a->sendRequest(); * echo $a->getResponseBody(); * </code> * * @category HTTP * @package HTTP_Request * @author Richard Heyes <richard@phpguru.org> * @author Alexey Borzov <avb@php.net> * @version Release: 1.4.2 */ class HTTP_Request { /**#@+ * @access private */ /** * Instance of Net_URL * @var Net_URL */ var $_url; /** * Type of request * @var string */ var $_method; /** * HTTP Version * @var string */ var $_http; /** * Request headers * @var array */ var $_requestHeaders; /** * Basic Auth Username * @var string */ var $_user; /** * Basic Auth Password * @var string */ var $_pass; /** * Socket object * @var Net_Socket */ var $_sock; /** * Proxy server * @var string */ var $_proxy_host; /** * Proxy port * @var integer */ var $_proxy_port; /** * Proxy username * @var string */ var $_proxy_user; /** * Proxy password * @var string */ var $_proxy_pass; /** * Post data * @var array */ var $_postData; /** * Request body * @var string */ var $_body; /** * A list of methods that MUST NOT have a request body, per RFC 2616 * @var array */ var $_bodyDisallowed = array('TRACE'); /** * Files to post * @var array */ var $_postFiles = array(); /** * Connection timeout. * @var float */ var $_timeout; /** * HTTP_Response object * @var HTTP_Response */ var $_response; /** * Whether to allow redirects * @var boolean */ var $_allowRedirects; /** * Maximum redirects allowed * @var integer */ var $_maxRedirects; /** * Current number of redirects * @var integer */ var $_redirects; /** * Whether to append brackets [] to array variables * @var bool */ var $_useBrackets = true; /** * Attached listeners * @var array */ var $_listeners = array(); /** * Whether to save response body in response object property * @var bool */ var $_saveBody = true; /** * Timeout for reading from socket (array(seconds, microseconds)) * @var array */ var $_readTimeout = null; /** * Options to pass to Net_Socket::connect. See stream_context_create * @var array */ var $_socketOptions = null; /**#@-*/ /** * Constructor * * Sets up the object * @param string The url to fetch/access * @param array Associative array of parameters which can have the following keys: * <ul> * <li>method - Method to use, GET, POST etc (string)</li> * <li>http - HTTP Version to use, 1.0 or 1.1 (string)</li> * <li>user - Basic Auth username (string)</li> * <li>pass - Basic Auth password (string)</li> * <li>proxy_host - Proxy server host (string)</li> * <li>proxy_port - Proxy server port (integer)</li> * <li>proxy_user - Proxy auth username (string)</li> * <li>proxy_pass - Proxy auth password (string)</li> * <li>timeout - Connection timeout in seconds (float)</li> * <li>allowRedirects - Whether to follow redirects or not (bool)</li> * <li>maxRedirects - Max number of redirects to follow (integer)</li> * <li>useBrackets - Whether to append [] to array variable names (bool)</li> * <li>saveBody - Whether to save response body in response object property (bool)</li> * <li>readTimeout - Timeout for reading / writing data over the socket (array (seconds, microseconds))</li> * <li>socketOptions - Options to pass to Net_Socket object (array)</li> * </ul> * @access public */ function HTTP_Request($url = '', $params = array()) { $this->_method = HTTP_REQUEST_METHOD_GET; $this->_http = HTTP_REQUEST_HTTP_VER_1_1; $this->_requestHeaders = array(); $this->_postData = array(); $this->_body = null; $this->_user = null; $this->_pass = null; $this->_proxy_host = null; $this->_proxy_port = null; $this->_proxy_user = null; $this->_proxy_pass = null; $this->_allowRedirects = false; $this->_maxRedirects = 3; $this->_redirects = 0; $this->_timeout = null; $this->_response = null; foreach ($params as $key => $value) { $this->{'_' . $key} = $value; } if (!empty($url)) { $this->setURL($url); } // Default useragent $this->addHeader('User-Agent', 'PEAR HTTP_Request class ( http://pear.php.net/ )'); // We don't do keep-alives by default $this->addHeader('Connection', 'close'); // Basic authentication if (!empty($this->_user)) { $this->addHeader('Authorization', 'Basic ' . base64_encode($this->_user . ':' . $this->_pass)); } // Proxy authentication (see bug #5913) if (!empty($this->_proxy_user)) { $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($this->_proxy_user . ':' . $this->_proxy_pass)); } // Use gzip encoding if possible if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && extension_loaded('zlib')) { $this->addHeader('Accept-Encoding', 'gzip'); } } /** * Generates a Host header for HTTP/1.1 requests * * @access private * @return string */ function _generateHostHeader() { if ($this->_url->port != 80 AND strcasecmp($this->_url->protocol, 'http') == 0) { $host = $this->_url->host . ':' . $this->_url->port; } elseif ($this->_url->port != 443 AND strcasecmp($this->_url->protocol, 'https') == 0) { $host = $this->_url->host . ':' . $this->_url->port; } elseif ($this->_url->port == 443 AND strcasecmp($this->_url->protocol, 'https') == 0 AND strpos($this->_url->url, ':443') !== false) { $host = $this->_url->host . ':' . $this->_url->port; } else { $host = $this->_url->host; } return $host; } /** * Resets the object to its initial state (DEPRECATED). * Takes the same parameters as the constructor. * * @param string $url The url to be requested * @param array $params Associative array of parameters * (see constructor for details) * @access public * @deprecated deprecated since 1.2, call the constructor if this is necessary */ function reset($url, $params = array()) { $this->HTTP_Request($url, $params); } /** * Sets the URL to be requested * * @param string The url to be requested * @access public */ function setURL($url) { $this->_url = &new Net_URL($url, $this->_useBrackets); if (!empty($this->_url->user) || !empty($this->_url->pass)) { $this->setBasicAuth($this->_url->user, $this->_url->pass); } if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http) { $this->addHeader('Host', $this->_generateHostHeader()); } // set '/' instead of empty path rather than check later (see bug #8662) if (empty($this->_url->path)) { $this->_url->path = '/'; } } /** * Returns the current request URL * * @return string Current request URL * @access public */ function getUrl() { return empty($this->_url)? '': $this->_url->getUrl(); } /** * Sets a proxy to be used * * @param string Proxy host * @param int Proxy port * @param string Proxy username * @param string Proxy password * @access public */ function setProxy($host, $port = 8080, $user = null, $pass = null) { $this->_proxy_host = $host; $this->_proxy_port = $port; $this->_proxy_user = $user; $this->_proxy_pass = $pass; if (!empty($user)) { $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($user . ':' . $pass)); } } /** * Sets basic authentication parameters * * @param string Username * @param string Password */ function setBasicAuth($user, $pass) { $this->_user = $user; $this->_pass = $pass; $this->addHeader('Authorization', 'Basic ' . base64_encode($user . ':' . $pass)); } /** * Sets the method to be used, GET, POST etc. * * @param string Method to use. Use the defined constants for this * @access public */ function setMethod($method) { $this->_method = $method; } /** * Sets the HTTP version to use, 1.0 or 1.1 * * @param string Version to use. Use the defined constants for this * @access public */ function setHttpVer($http) { $this->_http = $http; } /** * Adds a request header * * @param string Header name * @param string Header value * @access public */ function addHeader($name, $value) { $this->_requestHeaders[strtolower($name)] = $value; } /** * Removes a request header * * @param string Header name to remove * @access public */ function removeHeader($name) { if (isset($this->_requestHeaders[strtolower($name)])) { unset($this->_requestHeaders[strtolower($name)]); } } /** * Adds a querystring parameter * * @param string Querystring parameter name * @param string Querystring parameter value * @param bool Whether the value is already urlencoded or not, default = not * @access public */ function addQueryString($name, $value, $preencoded = false) { $this->_url->addQueryString($name, $value, $preencoded); } /** * Sets the querystring to literally what you supply * * @param string The querystring data. Should be of the format foo=bar&x=y etc * @param bool Whether data is already urlencoded or not, default = already encoded * @access public */ function addRawQueryString($querystring, $preencoded = true) { $this->_url->addRawQueryString($querystring, $preencoded); } /** * Adds postdata items * * @param string Post data name * @param string Post data value * @param bool Whether data is already urlencoded or not, default = not * @access public */ function addPostData($name, $value, $preencoded = false) { if ($preencoded) { $this->_postData[$name] = $value; } else { $this->_postData[$name] = $this->_arrayMapRecursive('urlencode', $value); } } /** * Recursively applies the callback function to the value * * @param mixed Callback function * @param mixed Value to process * @access private * @return mixed Processed value */ function _arrayMapRecursive($callback, $value) { if (!is_array($value)) { return call_user_func($callback, $value); } else { $map = array(); foreach ($value as $k => $v) { $map[$k] = $this->_arrayMapRecursive($callback, $v); } return $map; } } /** * Adds a file to upload * * This also changes content-type to 'multipart/form-data' for proper upload * * @access public * @param string name of file-upload field * @param mixed file name(s) * @param mixed content-type(s) of file(s) being uploaded * @return bool true on success * @throws PEAR_Error */ function addFile($inputName, $fileName, $contentType = 'application/octet-stream') { if (!is_array($fileName) && !is_readable($fileName)) { return PEAR::raiseError("File '{$fileName}' is not readable", HTTP_REQUEST_ERROR_FILE); } elseif (is_array($fileName)) { foreach ($fileName as $name) { if (!is_readable($name)) { return PEAR::raiseError("File '{$name}' is not readable", HTTP_REQUEST_ERROR_FILE); } } } $this->addHeader('Content-Type', 'multipart/form-data'); $this->_postFiles[$inputName] = array( 'name' => $fileName, 'type' => $contentType ); return true; } /** * Adds raw postdata (DEPRECATED) * * @param string The data * @param bool Whether data is preencoded or not, default = already encoded * @access public * @deprecated deprecated since 1.3.0, method setBody() should be used instead */ function addRawPostData($postdata, $preencoded = true) { $this->_body = $preencoded ? $postdata : urlencode($postdata); } /** * Sets the request body (for POST, PUT and similar requests) * * @param string Request body * @access public */ function setBody($body) { $this->_body = $body; } /** * Clears any postdata that has been added (DEPRECATED). * * Useful for multiple request scenarios. * * @access public * @deprecated deprecated since 1.2 */ function clearPostData() { $this->_postData = null; } /** * Appends a cookie to "Cookie:" header * * @param string $name cookie name * @param string $value cookie value * @access public */ function addCookie($name, $value) { $cookies = isset($this->_requestHeaders['cookie']) ? $this->_requestHeaders['cookie']. '; ' : ''; $this->addHeader('Cookie', $cookies . $name . '=' . $value); } /** * Clears any cookies that have been added (DEPRECATED). * * Useful for multiple request scenarios * * @access public * @deprecated deprecated since 1.2 */ function clearCookies() { $this->removeHeader('Cookie'); } /** * Sends the request * * @access public * @param bool Whether to store response body in Response object property, * set this to false if downloading a LARGE file and using a Listener * @return mixed PEAR error on error, true otherwise */ function sendRequest($saveBody = true) { if (!is_a($this->_url, 'Net_URL')) { return PEAR::raiseError('No URL given', HTTP_REQUEST_ERROR_URL); } $host = isset($this->_proxy_host) ? $this->_proxy_host : $this->_url->host; $port = isset($this->_proxy_port) ? $this->_proxy_port : $this->_url->port; // 4.3.0 supports SSL connections using OpenSSL. The function test determines // we running on at least 4.3.0 if (strcasecmp($this->_url->protocol, 'https') == 0 AND function_exists('file_get_contents') AND extension_loaded('openssl')) { if (isset($this->_proxy_host)) { return PEAR::raiseError('HTTPS proxies are not supported', HTTP_REQUEST_ERROR_PROXY); } $host = 'ssl://' . $host; } // magic quotes may fuck up file uploads and chunked response processing $magicQuotes = ini_get('magic_quotes_runtime'); ini_set('magic_quotes_runtime', false); // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive // connection token to a proxy server... if (isset($this->_proxy_host) && !empty($this->_requestHeaders['connection']) && 'Keep-Alive' == $this->_requestHeaders['connection']) { $this->removeHeader('connection'); } $keepAlive = (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && empty($this->_requestHeaders['connection'])) || (!empty($this->_requestHeaders['connection']) && 'Keep-Alive' == $this->_requestHeaders['connection']); $sockets = &PEAR::getStaticProperty('HTTP_Request', 'sockets'); $sockKey = $host . ':' . $port; unset($this->_sock); // There is a connected socket in the "static" property? if ($keepAlive && !empty($sockets[$sockKey]) && !empty($sockets[$sockKey]->fp)) { $this->_sock =& $sockets[$sockKey]; $err = null; } else { $this->_notify('connect'); $this->_sock =& new Net_Socket(); $err = $this->_sock->connect($host, $port, null, $this->_timeout, $this->_socketOptions); } PEAR::isError($err) or $err = $this->_sock->write($this->_buildRequest()); if (!PEAR::isError($err)) { if (!empty($this->_readTimeout)) { $this->_sock->setTimeout($this->_readTimeout[0], $this->_readTimeout[1]); } $this->_notify('sentRequest'); // Read the response $this->_response = &new HTTP_Response($this->_sock, $this->_listeners); $err = $this->_response->process( $this->_saveBody && $saveBody, HTTP_REQUEST_METHOD_HEAD != $this->_method ); if ($keepAlive) { $keepAlive = (isset($this->_response->_headers['content-length']) || (isset($this->_response->_headers['transfer-encoding']) && strtolower($this->_response->_headers['transfer-encoding']) == 'chunked')); if ($keepAlive) { if (isset($this->_response->_headers['connection'])) { $keepAlive = strtolower($this->_response->_headers['connection']) == 'keep-alive'; } else { $keepAlive = 'HTTP/'.HTTP_REQUEST_HTTP_VER_1_1 == $this->_response->_protocol; } } } } ini_set('magic_quotes_runtime', $magicQuotes); if (PEAR::isError($err)) { return $err; } if (!$keepAlive) { $this->disconnect(); // Store the connected socket in "static" property } elseif (empty($sockets[$sockKey]) || empty($sockets[$sockKey]->fp)) { $sockets[$sockKey] =& $this->_sock; } // Check for redirection if ( $this->_allowRedirects AND $this->_redirects <= $this->_maxRedirects AND $this->getResponseCode() > 300 AND $this->getResponseCode() < 399 AND !empty($this->_response->_headers['location'])) { $redirect = $this->_response->_headers['location']; // Absolute URL if (preg_match('/^https?:\/\//i', $redirect)) { $this->_url = &new Net_URL($redirect); $this->addHeader('Host', $this->_generateHostHeader()); // Absolute path } elseif ($redirect{0} == '/') { $this->_url->path = $redirect; // Relative path } elseif (substr($redirect, 0, 3) == '../' OR substr($redirect, 0, 2) == './') { if (substr($this->_url->path, -1) == '/') { $redirect = $this->_url->path . $redirect; } else { $redirect = dirname($this->_url->path) . '/' . $redirect; } $redirect = Net_URL::resolvePath($redirect); $this->_url->path = $redirect; // Filename, no path } else { if (substr($this->_url->path, -1) == '/') { $redirect = $this->_url->path . $redirect; } else { $redirect = dirname($this->_url->path) . '/' . $redirect; } $this->_url->path = $redirect; } $this->_redirects++; return $this->sendRequest($saveBody); // Too many redirects } elseif ($this->_allowRedirects AND $this->_redirects > $this->_maxRedirects) { return PEAR::raiseError('Too many redirects', HTTP_REQUEST_ERROR_REDIRECTS); } return true; } /** * Disconnect the socket, if connected. Only useful if using Keep-Alive. * * @access public */ function disconnect() { if (!empty($this->_sock) && !empty($this->_sock->fp)) { $this->_notify('disconnect'); $this->_sock->disconnect(); } } /** * Returns the response code * * @access public * @return mixed Response code, false if not set */ function getResponseCode() { return isset($this->_response->_code) ? $this->_response->_code : false; } /** * Returns either the named header or all if no name given * * @access public * @param string The header name to return, do not set to get all headers * @return mixed either the value of $headername (false if header is not present) * or an array of all headers */ function getResponseHeader($headername = null) { if (!isset($headername)) { return isset($this->_response->_headers)? $this->_response->_headers: array(); } else { $headername = strtolower($headername); return isset($this->_response->_headers[$headername]) ? $this->_response->_headers[$headername] : false; } } /** * Returns the body of the response * * @access public * @return mixed response body, false if not set */ function getResponseBody() { return isset($this->_response->_body) ? $this->_response->_body : false; } /** * Returns cookies set in response * * @access public * @return mixed array of response cookies, false if none are present */ function getResponseCookies() { return isset($this->_response->_cookies) ? $this->_response->_cookies : false; } /** * Builds the request string * * @access private * @return string The request string */ function _buildRequest() { $separator = ini_get('arg_separator.output'); ini_set('arg_separator.output', '&'); $querystring = ($querystring = $this->_url->getQueryString()) ? '?' . $querystring : ''; ini_set('arg_separator.output', $separator); $host = isset($this->_proxy_host) ? $this->_url->protocol . '://' . $this->_url->host : ''; $port = (isset($this->_proxy_host) AND $this->_url->port != 80) ? ':' . $this->_url->port : ''; $path = $this->_url->path . $querystring; $url = $host . $port . $path; if (!strlen($url)) { $url = '/'; } $request = $this->_method . ' ' . $url . ' HTTP/' . $this->_http . "\r\n"; if (in_array($this->_method, $this->_bodyDisallowed) || (0 == strlen($this->_body) && (HTTP_REQUEST_METHOD_POST != $this->_method || (empty($this->_postData) && empty($this->_postFiles))))) { $this->removeHeader('Content-Type'); } else { if (empty($this->_requestHeaders['content-type'])) { // Add default content-type $this->addHeader('Content-Type', 'application/x-www-form-urlencoded'); } elseif ('multipart/form-data' == $this->_requestHeaders['content-type']) { $boundary = 'HTTP_Request_' . md5(uniqid('request') . microtime()); $this->addHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary); } } // Request Headers if (!empty($this->_requestHeaders)) { foreach ($this->_requestHeaders as $name => $value) { $canonicalName = implode('-', array_map('ucfirst', explode('-', $name))); $request .= $canonicalName . ': ' . $value . "\r\n"; } } // No post data or wrong method, so simply add a final CRLF if (in_array($this->_method, $this->_bodyDisallowed) || (HTTP_REQUEST_METHOD_POST != $this->_method && 0 == strlen($this->_body))) { $request .= "\r\n"; // Post data if it's an array } elseif (HTTP_REQUEST_METHOD_POST == $this->_method && (!empty($this->_postData) || !empty($this->_postFiles))) { // "normal" POST request if (!isset($boundary)) { $postdata = implode('&', array_map( create_function('$a', 'return $a[0] . \'=\' . $a[1];'), $this->_flattenArray('', $this->_postData) )); // multipart request, probably with file uploads } else { $postdata = ''; if (!empty($this->_postData)) { $flatData = $this->_flattenArray('', $this->_postData); foreach ($flatData as $item) { $postdata .= '--' . $boundary . "\r\n"; $postdata .= 'Content-Disposition: form-data; name="' . $item[0] . '"'; $postdata .= "\r\n\r\n" . urldecode($item[1]) . "\r\n"; } } foreach ($this->_postFiles as $name => $value) { if (is_array($value['name'])) { $varname = $name . ($this->_useBrackets? '[]': ''); } else { $varname = $name; $value['name'] = array($value['name']); } foreach ($value['name'] as $key => $filename) { $fp = fopen($filename, 'r'); $data = fread($fp, filesize($filename)); fclose($fp); $basename = basename($filename); $type = is_array($value['type'])? @$value['type'][$key]: $value['type']; $postdata .= '--' . $boundary . "\r\n"; $postdata .= 'Content-Disposition: form-data; name="' . $varname . '"; filename="' . $basename . '"'; $postdata .= "\r\nContent-Type: " . $type; $postdata .= "\r\n\r\n" . $data . "\r\n"; } } $postdata .= '--' . $boundary . "--\r\n"; } $request .= 'Content-Length: ' . (HTTP_REQUEST_MBSTRING? mb_strlen($postdata, 'iso-8859-1'): strlen($postdata)) . "\r\n\r\n"; $request .= $postdata; // Explicitly set request body } elseif (0 < strlen($this->_body)) { $request .= 'Content-Length: ' . (HTTP_REQUEST_MBSTRING? mb_strlen($this->_body, 'iso-8859-1'): strlen($this->_body)) . "\r\n\r\n"; $request .= $this->_body; // Terminate headers with CRLF on POST request with no body, too } else { $request .= "\r\n"; } return $request; } /** * Helper function to change the (probably multidimensional) associative array * into the simple one. * * @param string name for item * @param mixed item's values * @return array array with the following items: array('item name', 'item value'); * @access private */ function _flattenArray($name, $values) { if (!is_array($values)) { return array(array($name, $values)); } else { $ret = array(); foreach ($values as $k => $v) { if (empty($name)) { $newName = $k; } elseif ($this->_useBrackets) { $newName = $name . '[' . $k . ']'; } else { $newName = $name; } $ret = array_merge($ret, $this->_flattenArray($newName, $v)); } return $ret; } } /** * Adds a Listener to the list of listeners that are notified of * the object's events * * Events sent by HTTP_Request object * - 'connect': on connection to server * - 'sentRequest': after the request was sent * - 'disconnect': on disconnection from server * * Events sent by HTTP_Response object * - 'gotHeaders': after receiving response headers (headers are passed in $data) * - 'tick': on receiving a part of response body (the part is passed in $data) * - 'gzTick': on receiving a gzip-encoded part of response body (ditto) * - 'gotBody': after receiving the response body (passes the decoded body in $data if it was gzipped) * * @param HTTP_Request_Listener listener to attach * @return boolean whether the listener was successfully attached * @access public */ function attach(&$listener) { if (!is_a($listener, 'HTTP_Request_Listener')) { return false; } $this->_listeners[$listener->getId()] =& $listener; return true; } /** * Removes a Listener from the list of listeners * * @param HTTP_Request_Listener listener to detach * @return boolean whether the listener was successfully detached * @access public */ function detach(&$listener) { if (!is_a($listener, 'HTTP_Request_Listener') || !isset($this->_listeners[$listener->getId()])) { return false; } unset($this->_listeners[$listener->getId()]); return true; } /** * Notifies all registered listeners of an event. * * @param string Event name * @param mixed Additional data * @access private * @see HTTP_Request::attach() */ function _notify($event, $data = null) { foreach (array_keys($this->_listeners) as $id) { $this->_listeners[$id]->update($this, $event, $data); } } } /** * Response class to complement the Request class * * @category HTTP * @package HTTP_Request * @author Richard Heyes <richard@phpguru.org> * @author Alexey Borzov <avb@php.net> * @version Release: 1.4.2 */ class HTTP_Response { /** * Socket object * @var Net_Socket */ var $_sock; /** * Protocol * @var string */ var $_protocol; /** * Return code * @var string */ var $_code; /** * Response headers * @var array */ var $_headers; /** * Cookies set in response * @var array */ var $_cookies; /** * Response body * @var string */ var $_body = ''; /** * Used by _readChunked(): remaining length of the current chunk * @var string */ var $_chunkLength = 0; /** * Attached listeners * @var array */ var $_listeners = array(); /** * Bytes left to read from message-body * @var null|int */ var $_toRead; /** * Constructor * * @param Net_Socket socket to read the response from * @param array listeners attached to request */ function HTTP_Response(&$sock, &$listeners) { $this->_sock =& $sock; $this->_listeners =& $listeners; } /** * Processes a HTTP response * * This extracts response code, headers, cookies and decodes body if it * was encoded in some way * * @access public * @param bool Whether to store response body in object property, set * this to false if downloading a LARGE file and using a Listener. * This is assumed to be true if body is gzip-encoded. * @param bool Whether the response can actually have a message-body. * Will be set to false for HEAD requests. * @throws PEAR_Error * @return mixed true on success, PEAR_Error in case of malformed response */ function process($saveBody = true, $canHaveBody = true) { do { $line = $this->_sock->readLine(); if (sscanf($line, 'HTTP/%s %s', $http_version, $returncode) != 2) { return PEAR::raiseError('Malformed response', HTTP_REQUEST_ERROR_RESPONSE); } else { $this->_protocol = 'HTTP/' . $http_version; $this->_code = intval($returncode); } while ('' !== ($header = $this->_sock->readLine())) { $this->_processHeader($header); } } while (100 == $this->_code); $this->_notify('gotHeaders', $this->_headers); // RFC 2616, section 4.4: // 1. Any response message which "MUST NOT" include a message-body ... // is always terminated by the first empty line after the header fields // 3. ... If a message is received with both a // Transfer-Encoding header field and a Content-Length header field, // the latter MUST be ignored. $canHaveBody = $canHaveBody && $this->_code >= 200 && $this->_code != 204 && $this->_code != 304; // If response body is present, read it and decode $chunked = isset($this->_headers['transfer-encoding']) && ('chunked' == $this->_headers['transfer-encoding']); $gzipped = isset($this->_headers['content-encoding']) && ('gzip' == $this->_headers['content-encoding']); $hasBody = false; if ($canHaveBody && ($chunked || !isset($this->_headers['content-length']) || 0 != $this->_headers['content-length'])) { if ($chunked || !isset($this->_headers['content-length'])) { $this->_toRead = null; } else { $this->_toRead = $this->_headers['content-length']; } while (!$this->_sock->eof() && (is_null($this->_toRead) || 0 < $this->_toRead)) { if ($chunked) { $data = $this->_readChunked(); } elseif (is_null($this->_toRead)) { $data = $this->_sock->read(4096); } else { $data = $this->_sock->read(min(4096, $this->_toRead)); $this->_toRead -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data); } if ('' == $data) { break; } else { $hasBody = true; if ($saveBody || $gzipped) { $this->_body .= $data; } $this->_notify($gzipped? 'gzTick': 'tick', $data); } } } if ($hasBody) { // Uncompress the body if needed if ($gzipped) { $body = $this->_decodeGzip($this->_body); if (PEAR::isError($body)) { return $body; } $this->_body = $body; $this->_notify('gotBody', $this->_body); } else { $this->_notify('gotBody'); } } return true; } /** * Processes the response header * * @access private * @param string HTTP header */ function _processHeader($header) { if (false === strpos($header, ':')) { return; } list($headername, $headervalue) = explode(':', $header, 2); $headername = strtolower($headername); $headervalue = ltrim($headervalue); if ('set-cookie' != $headername) { if (isset($this->_headers[$headername])) { $this->_headers[$headername] .= ',' . $headervalue; } else { $this->_headers[$headername] = $headervalue; } } else { $this->_parseCookie($headervalue); } } /** * Parse a Set-Cookie header to fill $_cookies array * * @access private * @param string value of Set-Cookie header */ function _parseCookie($headervalue) { $cookie = array( 'expires' => null, 'domain' => null, 'path' => null, 'secure' => false ); // Only a name=value pair if (!strpos($headervalue, ';')) { $pos = strpos($headervalue, '='); $cookie['name'] = trim(substr($headervalue, 0, $pos)); $cookie['value'] = trim(substr($headervalue, $pos + 1)); // Some optional parameters are supplied } else { $elements = explode(';', $headervalue); $pos = strpos($elements[0], '='); $cookie['name'] = trim(substr($elements[0], 0, $pos)); $cookie['value'] = trim(substr($elements[0], $pos + 1)); for ($i = 1; $i < count($elements); $i++) { if (false === strpos($elements[$i], '=')) { $elName = trim($elements[$i]); $elValue = null; } else { list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i])); } $elName = strtolower($elName); if ('secure' == $elName) { $cookie['secure'] = true; } elseif ('expires' == $elName) { $cookie['expires'] = str_replace('"', '', $elValue); } elseif ('path' == $elName || 'domain' == $elName) { $cookie[$elName] = urldecode($elValue); } else { $cookie[$elName] = $elValue; } } } $this->_cookies[] = $cookie; } /** * Read a part of response body encoded with chunked Transfer-Encoding * * @access private * @return string */ function _readChunked() { // at start of the next chunk? if (0 == $this->_chunkLength) { $line = $this->_sock->readLine(); if (preg_match('/^([0-9a-f]+)/i', $line, $matches)) { $this->_chunkLength = hexdec($matches[1]); // Chunk with zero length indicates the end if (0 == $this->_chunkLength) { $this->_sock->readLine(); // make this an eof() return ''; } } else { return ''; } } $data = $this->_sock->read($this->_chunkLength); $this->_chunkLength -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data); if (0 == $this->_chunkLength) { $this->_sock->readLine(); // Trailing CRLF } return $data; } /** * Notifies all registered listeners of an event. * * @param string Event name * @param mixed Additional data * @access private * @see HTTP_Request::_notify() */ function _notify($event, $data = null) { foreach (array_keys($this->_listeners) as $id) { $this->_listeners[$id]->update($this, $event, $data); } } /** * Decodes the message-body encoded by gzip * * The real decoding work is done by gzinflate() built-in function, this * method only parses the header and checks data for compliance with * RFC 1952 * * @access private * @param string gzip-encoded data * @return string decoded data */ function _decodeGzip($data) { if (HTTP_REQUEST_MBSTRING) { $oldEncoding = mb_internal_encoding(); mb_internal_encoding('iso-8859-1'); } $length = strlen($data); // If it doesn't look like gzip-encoded data, don't bother if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) { return $data; } $method = ord(substr($data, 2, 1)); if (8 != $method) { return PEAR::raiseError('_decodeGzip(): unknown compression method', HTTP_REQUEST_ERROR_GZIP_METHOD); } $flags = ord(substr($data, 3, 1)); if ($flags & 224) { return PEAR::raiseError('_decodeGzip(): reserved bits are set', HTTP_REQUEST_ERROR_GZIP_DATA); } // header is 10 bytes minimum. may be longer, though. $headerLength = 10; // extra fields, need to skip 'em if ($flags & 4) { if ($length - $headerLength - 2 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $extraLength = unpack('v', substr($data, 10, 2)); if ($length - $headerLength - 2 - $extraLength[1] < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $headerLength += $extraLength[1] + 2; } // file name, need to skip that if ($flags & 8) { if ($length - $headerLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $filenameLength = strpos(substr($data, $headerLength), chr(0)); if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $headerLength += $filenameLength + 1; } // comment, need to skip that also if ($flags & 16) { if ($length - $headerLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $commentLength = strpos(substr($data, $headerLength), chr(0)); if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $headerLength += $commentLength + 1; } // have a CRC for header. let's check if ($flags & 1) { if ($length - $headerLength - 2 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $crcReal = 0xffff & crc32(substr($data, 0, $headerLength)); $crcStored = unpack('v', substr($data, $headerLength, 2)); if ($crcReal != $crcStored[1]) { return PEAR::raiseError('_decodeGzip(): header CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC); } $headerLength += 2; } // unpacked data CRC and size at the end of encoded data $tmp = unpack('V2', substr($data, -8)); $dataCrc = $tmp[1]; $dataSize = $tmp[2]; // finally, call the gzinflate() function $unpacked = @gzinflate(substr($data, $headerLength, -8), $dataSize); if (false === $unpacked) { return PEAR::raiseError('_decodeGzip(): gzinflate() call failed', HTTP_REQUEST_ERROR_GZIP_READ); } elseif ($dataSize != strlen($unpacked)) { return PEAR::raiseError('_decodeGzip(): data size check failed', HTTP_REQUEST_ERROR_GZIP_READ); } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) { return PEAR::raiseError('_decodeGzip(): data CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC); } if (HTTP_REQUEST_MBSTRING) { mb_internal_encoding($oldEncoding); } return $unpacked; } } // End class HTTP_Response ?>
sharkhack/AmazonS3
PHP/s3uploader/HTTP/Request.php
PHP
mit
49,419
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _propTypes = require("prop-types"); var _propTypes2 = _interopRequireDefault(_propTypes); var _textInput = require("./text-input"); var _textInput2 = _interopRequireDefault(_textInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } var EmailInput = function (_TextInput) { _inherits(EmailInput, _TextInput); function EmailInput(props) { _classCallCheck(this, EmailInput); return _possibleConstructorReturn(this, (EmailInput.__proto__ || Object.getPrototypeOf(EmailInput)).call(this, props)); } _createClass(EmailInput, [{ key: "onValid", value: function onValid(e) { if (!!this.props.onValid) { this.props.onValid(validateEmail(e.target.value), e); } } }]); return EmailInput; }(_textInput2.default); exports.default = EmailInput; EmailInput.propTypes = { type: _propTypes2.default.string.isRequired }; EmailInput.defaultProps = { type: "email" };
njnest/rc-inputs
lib/email-input.js
JavaScript
mit
2,843
import React, { Component } from 'react'; import List from 'react-toolbox/lib/list/List'; import ListSubHeader from 'react-toolbox/lib/list/ListSubHeader'; import ListCheckbox from 'react-toolbox/lib/list/ListCheckbox'; import ListItem from 'react-toolbox/lib/list/ListItem'; import Dropdown from 'react-toolbox/lib/dropdown/Dropdown'; import ConnectedStoreHOC from '../utils/connect.store.hoc'; import * as Actions from '../utils/actions'; import { NEW_PHOTO_DURATIONS } from '../configs/constants'; const NEW_PHOTO_INTERVAL_OPTIONS = [ { value: NEW_PHOTO_DURATIONS.ALWAYS, label: 'Always' }, { value: NEW_PHOTO_DURATIONS.HOURLY, label: 'Hourly' }, { value: NEW_PHOTO_DURATIONS.DAILY, label: 'Daily' }, ]; const handleFetchFromServerChange = (value, ev) => Actions.setSetting({ fetchFromServer: value }); const handleNewPhotoIntervalChange = (value, ev) => Actions.setSetting({ newPhotoDuration: parseInt(value, 10) }); const NewPhotoIntervalDropdown = ({ refreshInterval, className }) => ( <Dropdown label="Duration" className={className} value={refreshInterval} source={NEW_PHOTO_INTERVAL_OPTIONS} onChange={handleNewPhotoIntervalChange} /> ); class SettingsContainer extends Component { componentDidMount() { // lazy initialize the state object setTimeout(() => Actions.refresh(false), 0); } render() { const { fetchFromServer, newPhotoDuration } = this.props; return ( <List selectable ripple> <ListSubHeader caption="Background Photos" /> <ListCheckbox caption="Load Fresh" legend="If disabled, it will cycle through a list of locally stored wallpapers only." checked={fetchFromServer} onChange={handleFetchFromServerChange} /> <ListItem itemContent={ <div> <p className="settings__inlineItem">Show new photo</p> <NewPhotoIntervalDropdown className="settings__inlineItem" refreshInterval={newPhotoDuration} /> </div> } ripple={false} selectable={false} /> </List>); } } export default ConnectedStoreHOC(SettingsContainer);
emadalam/mesmerized
src/modules/background/containers/Settings.js
JavaScript
mit
2,449
require "simple_selector/version" require "simple_selector/specificity" require "simple_selector/segment" class SimpleSelector def initialize(string=nil) @segments = [] @specificity = Specificity.new concat(string) unless string.nil? end attr_reader :specificity def concat(string) string.scan(/[\w.#]+/).map { |s| Segment.new(s) }.each do |segment| @segments << segment @specificity += segment.specificity end self end def +(string) duplicate.concat(string) end def match?(tag) return true if @segments.none? return false unless @segments.last.match?(tag) index = @segments.size - 2 current_tag = tag while index >= 0 && current_tag = current_tag.parent if @segments[index].match?(current_tag) index -= 1 next end end index == -1 end def empty? @segments.none? end def to_s @segments.map { |segment| segment.to_s }.join(" ") end def inspect "#<#{self.class} #{to_s.inspect}>" end def ==(other) to_s == other.to_s end def duplicate d = dup d.instance_variable_set( "@segments", @segments.dup) d.instance_variable_set("@specificity", @specificity.dup) d end end
jacekmikrut/simple_selector
lib/simple_selector.rb
Ruby
mit
1,247
<?php namespace thgs\Olographos; class Olographos { /* | Olographos class |-=-=-=-=-=-=-=-=-=- | | I wrote this a while ago, now went through it all wrapping it in a class. | Has some introspective comments :) | | | Limitations: max number is 999,999.99 | | Version: 0.1b - Improved comments and whitespace :) */ const STR_EURO = 'ΕΥΡΩ'; const STR_AND = 'ΚΑΙ'; const STR_CENTS = 'ΛΕΠΤΑ'; const STR_THOUSANDS = 'ΧΙΛΙΑΔΕΣ'; protected static $representations = [ '0' => '', '1' => 'ΕΝΑ', '2' => 'ΔΥΟ', '3' => 'ΤΡΙΑ', '4' => 'ΤΕΣΣΕΡΑ', '5' => 'ΠΕΝΤΕ', '6' => 'ΕΞΙ', '7' => 'ΕΠΤΑ', '8' => 'ΟΚΤΩ', '9' => 'ΕΝΝΙΑ', '10' => 'ΔΕΚΑ', '11' => 'ΕΝΤΕΚΑ', '12' => 'ΔΩΔΕΚΑ', '13' => 'ΔΕΚΑ ΤΡΙΑ', '14' => 'ΔΕΚΑ ΤΕΣΣΕΡΑ', '15' => 'ΔΕΚΑ ΠΕΝΤΕ', '16' => 'ΔΕΚΑ ΕΞΙ', '17' => 'ΔΕΚΑ ΕΠΤΑ', '18' => 'ΔΕΚΑ ΟΚΤΩ', '19' => 'ΔΕΚΑ ΕΝΝΙΑ', '20' => 'ΕΙΚΟΣΙ', '30' => 'ΤΡΙΑΝΤΑ', '40' => 'ΣΑΡΑΝΤΑ', '50' => 'ΠΕΝΗΝΤΑ', '60' => 'ΕΞΗΝΤΑ', '70' => 'ΕΒΔΟΜΗΝΤΑ', '80' => 'ΟΓΔΟΝΤΑ', '90' => 'ΕΝΕΝΗΝΤΑ', '100' => 'ΕΚΑΤΟ', '200' => 'ΔΙΑΚΟΣΙΑ', '300' => 'ΤΡΙΑΚΟΣΙΑ', '400' => 'ΤΕΤΡΑΚΟΣΙΑ', '500' => 'ΠΕΝΤΑΚΟΣΙΑ', '600' => 'ΕΞΑΚΟΣΙΑ', '700' => 'ΕΠΤΑΚΟΣΙΑ', '800' => 'ΟΚΤΑΚΟΣΙΑ', '900' => 'ΕΝΝΙΑΚΟΣΙΑ', '1000' => 'ΧΙΛΙΑ', ]; protected static $thousand_corrections = [ 'ΔΙΑΚΟΣΙΑ' => 'ΔΙΑΚΟΣΙΕΣ', 'ΤΡΙΑΚΟΣΙΑ' => 'ΤΡΙΑΚΟΣΙΕΣ', 'ΤΕΤΡΑΚΟΣΙΑ' => 'ΤΕΤΡΑΚΟΣΙΕΣ', 'ΠΕΝΤΑΚΟΣΙΑ' => 'ΠΕΝΤΑΚΟΣΙΕΣ', 'ΕΞΑΚΟΣΙΑ' => 'ΕΞΑΚΟΣΙΕΣ', 'ΕΠΤΑΚΟΣΙΑ' => 'ΕΠΤΑΚΟΣΙΕΣ', 'ΟΚΤΑΚΟΣΙΑ' => 'ΟΚΤΑΚΟΣΙΕΣ', 'ΕΝΝΙΑΚΟΣΙΑ' => 'ΕΝΝΙΑΚΟΣΙΕΣ', ]; protected static $grammar_corrections = [ 'ΕΝΑ ΧΙΛΙΑΔΕΣ' => 'ΧΙΛΙΑ', ' ΕΝΑ ΧΙΛΙΑΔΕΣ' => ' ΜΙΑ ΧΙΛΙΑΔΕΣ', 'ΕΚΑΤΟ ' => 'ΕΚΑΤΟΝ ', 'ΤΡΙΑ ΧΙΛΙΑΔΕΣ' => 'ΤΡΕΙΣ ΧΙΛΙΑΔΕΣ', 'ΤΕΣΣΕΡΑ ΧΙΛΙΑΔΕΣ' => 'ΤΕΣΣΕΡΙΣ ΧΙΛΙΑΔΕΣ', ]; public static function nt_prim($n, $append = false) { // if $n is not a number return false and exit function if (!is_numeric($n)) { return false; } // case $n contains thousands if ($n > 1000) { // process thousands recursively and correct any mistakes in representation // due to thousands word in greek (xiliades) $tnum = (int) ($n / 1000); $pretext = strtr( self::number_text($tnum).' '.self::STR_THOUSANDS.' ', self::$thousand_corrections ); // remove thousands from number // 0.1-old code: while ($n >= 1000) $n -= 1000; $n = $n % 1000; } // case $n is exactly 1000 if ($n == 1000) { $pretext = self::$representations['1000']; $n -= 1000; // not sure if we need this line // why not return here ? } $text = (isset($pretext)) ? $pretext : ''; // look for the closest representation, performing one iteration // over all representations $plimit = 0; foreach (self::$representations as $limit => $desc) { $ilimit = (int) $limit; if ($ilimit <= $n) { // store current limit, to be used as last found representation $plimit = $limit; continue; } else { // store last found representation $text .= self::$representations[$plimit]; // subtract the amount of last used representation from the number $n -= $plimit; break; } } // return return [$n, $text]; // that is a weird return value, regarding $n, which should be 0 ?? } /** * Returns a textual representation for a number $n in Greek. * * @param float $n * @returns string */ public static function number_text($n) { // dup $n to start getting textual representations $new = $n; // get all textual representations do { list($new, $txt) = self::nt_prim($new); $text[] = $txt; } while ($new > 0); // store into one string $ret = implode(' ', $text); // final grammar corrections $ret = strtr($ret, self::$grammar_corrections); // remove STR_AND from the end of the string, if there is there $length = (2 + strlen(self::STR_AND)) * (-1); if (substr($ret, $length) == ' '.self::STR_AND.' ') { $ret = substr($ret, 0, $length); } // return textual representation of $n return $ret; } /** * Returns the textual representation of an amount in Greek. * * @param float $amount * @returns string */ public static function str_greek_amount($amount) { // explode decimal part list($int, $dec) = explode('.', number_format($amount, 2, '.', '')); // get textual representation of integer part $txt = self::number_text($int).' '.self::STR_EURO; // add cents part if there is any if ($dec > 0) { $txt .= ' '.self::STR_AND.' ' .self::number_text($dec).' '.self::STR_CENTS; } // return return $txt; } }
thgs/olographos
src/Olographos/Olographos.php
PHP
mit
6,290
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LambdastylePrototype; using LambdastylePrototype.Interpreter; using LambdastylePrototype.Interpreter.Predicates; using LambdastylePrototype.Interpreter.Subjects; namespace Test.input5.json._5_remove_keys_with_values_containing_two_upper_letters { class Style { void Build(Builder builder) { builder.Add( new Sentence(new Subject(new Equals(new Any(), new RegExp("[A-Z].*[A-Z]"))), new Predicate()), Consts.CopyAny); } } }
PawelStroinski/LambdastylePrototype
Test/input5.json/5 remove keys with values containing two upper letters/Style.cs
C#
mit
650
using System; using System.Windows.Forms; using BizHawk.Emulation.Common; using BizHawk.Client.Common; using BizHawk.Common.NumberExtensions; namespace BizHawk.Client.EmuHawk { public partial class StateHistorySettingsForm : Form { public IStatable Statable { get; set; } private readonly TasStateManagerSettings _settings; private decimal _stateSizeMb; public StateHistorySettingsForm(TasStateManagerSettings settings) { _settings = settings; InitializeComponent(); } private void StateHistorySettings_Load(object sender, EventArgs e) { _stateSizeMb = Statable.SaveStateBinary().Length / (decimal)1024 / (decimal)1024; MemCapacityNumeric.Maximum = 1024 * 8; MemCapacityNumeric.Minimum = _stateSizeMb + 1; MemStateGapDividerNumeric.Maximum = Statable.SaveStateBinary().Length / 1024 / 2 + 1; MemStateGapDividerNumeric.Minimum = Math.Max(Statable.SaveStateBinary().Length / 1024 / 16, 1); MemCapacityNumeric.Value = NumberExtensions.Clamp(_settings.Capacitymb, MemCapacityNumeric.Minimum, MemCapacityNumeric.Maximum); DiskCapacityNumeric.Value = NumberExtensions.Clamp(_settings.DiskCapacitymb, MemCapacityNumeric.Minimum, MemCapacityNumeric.Maximum); FileCapacityNumeric.Value = NumberExtensions.Clamp(_settings.DiskSaveCapacitymb, MemCapacityNumeric.Minimum, MemCapacityNumeric.Maximum); MemStateGapDividerNumeric.Value = NumberExtensions.Clamp(_settings.MemStateGapDivider, MemStateGapDividerNumeric.Minimum, MemStateGapDividerNumeric.Maximum); FileStateGapNumeric.Value = _settings.FileStateGap; SavestateSizeLabel.Text = $"{Math.Round(_stateSizeMb, 2)} MB"; CapacityNumeric_ValueChanged(null, null); SaveCapacityNumeric_ValueChanged(null, null); } private int MaxStatesInCapacity => (int)Math.Floor(MemCapacityNumeric.Value / _stateSizeMb) + (int)Math.Floor(DiskCapacityNumeric.Value / _stateSizeMb); private void OkBtn_Click(object sender, EventArgs e) { _settings.Capacitymb = (int)MemCapacityNumeric.Value; _settings.DiskCapacitymb = (int)DiskCapacityNumeric.Value; _settings.DiskSaveCapacitymb = (int)FileCapacityNumeric.Value; _settings.MemStateGapDivider = (int)MemStateGapDividerNumeric.Value; _settings.FileStateGap = (int)FileStateGapNumeric.Value; DialogResult = DialogResult.OK; Close(); } private void CancelBtn_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void CapacityNumeric_ValueChanged(object sender, EventArgs e) { // TODO: Setting space for 2.6 (2) states in memory and 2.6 (2) on disk results in 5 total. // Easy to fix the display, but the way TasStateManager works the total used actually is 5. NumStatesLabel.Text = MaxStatesInCapacity.ToString(); } private void SaveCapacityNumeric_ValueChanged(object sender, EventArgs e) { NumSaveStatesLabel.Text = ((int)Math.Floor(FileCapacityNumeric.Value / _stateSizeMb)).ToString(); } private void FileStateGap_ValueChanged(object sender, EventArgs e) { FileNumFramesLabel.Text = FileStateGapNumeric.Value == 0 ? "frame" : $"{1 << (int)FileStateGapNumeric.Value} frames"; } private void MemStateGapDivider_ValueChanged(object sender, EventArgs e) { int val = (int)(Statable.SaveStateBinary().Length / MemStateGapDividerNumeric.Value / 1024); if (val <= 1) MemStateGapDividerNumeric.Maximum = MemStateGapDividerNumeric.Value; MemFramesLabel.Text = val <= 1 ? "frame" : $"{val} frames"; } } }
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs
C#
mit
3,504
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit54de4412c901abf97506a041edca18c7 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit54de4412c901abf97506a041edca18c7', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit54de4412c901abf97506a041edca18c7', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION'); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit54de4412c901abf97506a041edca18c7::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); return $loader; } }
yellowblackfish/io
themes/ybf-0.1.0/static/vendor/composer/autoload_real.php
PHP
mit
1,681
//----------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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; namespace PhotoSharingApp.Universal.Models { /// <summary> /// Represents an annotation for a photo. /// </summary> public class Annotation { /// <summary> /// Gets or sets the date and time when the /// notification was created. /// </summary> public DateTime CreatedTime { get; set; } /// <summary> /// Gets or sets the user who is the originator /// or the annotion. /// </summary> public User From { get; set; } /// <summary> /// Gets or sets the gold count which represents how /// much gold the annotation's originator gives to /// the photo. /// </summary> public int GoldCount { get; set; } /// <summary> /// Gets or sets the Id. /// </summary> public string Id { get; set; } /// <summary> /// Gets or sets the Photo Id. /// </summary> public string PhotoId { get; set; } /// <summary> /// Gets or sets the comment. /// </summary> public string Text { get; set; } } }
jackypham94/PetCareCenter
PhotoSharingApp/PhotoSharingApp.Universal/Models/Annotation.cs
C#
mit
2,503
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class OVRSceneLoader : MonoBehaviour { public const string externalStoragePath = "/sdcard/Android/data"; public const string sceneLoadDataName = "SceneLoadData.txt"; public const string resourceBundleName = "asset_resources"; public float sceneCheckIntervalSeconds = 1f; public float logCloseTime = 5.0f; public Canvas mainCanvas; public Text logTextBox; private AsyncOperation loadSceneOperation; private string formattedLogText; private float closeLogTimer; private bool closeLogDialogue; private bool canvasPosUpdated; private struct SceneInfo { public List<string> scenes; public long version; public SceneInfo(List<string> sceneList, long currentSceneEpochVersion) { scenes = sceneList; version = currentSceneEpochVersion; } } private string scenePath = ""; private string sceneLoadDataPath = ""; private List<AssetBundle> loadedAssetBundles = new List<AssetBundle>(); private SceneInfo currentSceneInfo; private void Awake() { // Make it presist across scene to continue checking for changes DontDestroyOnLoad(this.gameObject); } void Start() { string applicationPath = Path.Combine(externalStoragePath, Application.identifier); scenePath = Path.Combine(applicationPath, "cache/scenes"); sceneLoadDataPath = Path.Combine(scenePath, sceneLoadDataName); closeLogDialogue = false; StartCoroutine(DelayCanvasPosUpdate()); currentSceneInfo = GetSceneInfo(); // Check valid scene info has been fetched, and load the scenes if (currentSceneInfo.version != 0 && !string.IsNullOrEmpty(currentSceneInfo.scenes[0])) { LoadScene(currentSceneInfo); } } private void LoadScene(SceneInfo sceneInfo) { AssetBundle mainSceneBundle = null; Debug.Log("[OVRSceneLoader] Loading main scene: " + sceneInfo.scenes[0] + " with version " + sceneInfo.version.ToString()); logTextBox.text += "Target Scene: " + sceneInfo.scenes[0] + "\n"; logTextBox.text += "Version: " + sceneInfo.version.ToString() + "\n"; // Load main scene and dependent additive scenes (if any) Debug.Log("[OVRSceneLoader] Loading scene bundle files."); // Fetch all files under scene cache path, excluding unnecessary files such as scene metadata file string[] bundles = Directory.GetFiles(scenePath, "*_*"); logTextBox.text += "Loading " + bundles.Length + " bundle(s) . . . "; string mainSceneBundleFileName = "scene_" + sceneInfo.scenes[0].ToLower(); try { foreach (string b in bundles) { var assetBundle = AssetBundle.LoadFromFile(b); if (assetBundle != null) { Debug.Log("[OVRSceneLoader] Loading file bundle: " + assetBundle.name == null ? "null" : assetBundle.name); loadedAssetBundles.Add(assetBundle); } else { Debug.LogError("[OVRSceneLoader] Loading file bundle failed"); } if (assetBundle.name == mainSceneBundleFileName) { mainSceneBundle = assetBundle; } if (assetBundle.name == resourceBundleName) { OVRResources.SetResourceBundle(assetBundle); } } } catch(Exception e) { logTextBox.text += "<color=red>" + e.Message + "</color>"; return; } logTextBox.text += "<color=green>DONE\n</color>"; if (mainSceneBundle != null) { logTextBox.text += "Loading Scene: {0:P0}\n"; formattedLogText = logTextBox.text; string[] scenePaths = mainSceneBundle.GetAllScenePaths(); string sceneName = Path.GetFileNameWithoutExtension(scenePaths[0]); loadSceneOperation = SceneManager.LoadSceneAsync(sceneName); loadSceneOperation.completed += LoadSceneOperation_completed; } else { logTextBox.text += "<color=red>Failed to get main scene bundle.\n</color>"; } } private void LoadSceneOperation_completed(AsyncOperation obj) { StartCoroutine(onCheckSceneCoroutine()); StartCoroutine(DelayCanvasPosUpdate()); closeLogTimer = 0; closeLogDialogue = true; logTextBox.text += "Log closing in {0} seconds.\n"; formattedLogText = logTextBox.text; } public void Update() { // Display scene load percentage if (loadSceneOperation != null) { if (!loadSceneOperation.isDone) { logTextBox.text = string.Format(formattedLogText, loadSceneOperation.progress + 0.1f); if (loadSceneOperation.progress >= 0.9f) { logTextBox.text = formattedLogText.Replace("{0:P0}", "<color=green>DONE</color>"); logTextBox.text += "Transitioning to new scene.\nLoad times will vary depending on scene complexity.\n"; } } } UpdateCanvasPosition(); // Wait a certain time before closing the log dialogue after the scene has transitioned if (closeLogDialogue) { if (closeLogTimer < logCloseTime) { closeLogTimer += Time.deltaTime; logTextBox.text = string.Format(formattedLogText, (int)(logCloseTime - closeLogTimer)); } else { mainCanvas.gameObject.SetActive(false); closeLogDialogue = false; } } } private void UpdateCanvasPosition() { // Update canvas camera reference and position if the main camera has changed if (mainCanvas.worldCamera != Camera.main) { mainCanvas.worldCamera = Camera.main; if (Camera.main != null) { Vector3 newPosition = Camera.main.transform.position + Camera.main.transform.forward * 0.3f; gameObject.transform.position = newPosition; gameObject.transform.rotation = Camera.main.transform.rotation; } } } private SceneInfo GetSceneInfo() { SceneInfo sceneInfo = new SceneInfo(); try { StreamReader reader = new StreamReader(sceneLoadDataPath); sceneInfo.version = System.Convert.ToInt64(reader.ReadLine()); List<string> sceneList = new List<string>(); while (!reader.EndOfStream) { sceneList.Add(reader.ReadLine()); } sceneInfo.scenes = sceneList; } catch { logTextBox.text += "<color=red>Failed to get scene info data.\n</color>"; } return sceneInfo; } // Update canvas position after a slight delay to get accurate headset position after scene transitions IEnumerator DelayCanvasPosUpdate() { yield return new WaitForSeconds(0.1f); UpdateCanvasPosition(); } IEnumerator onCheckSceneCoroutine() { SceneInfo newSceneInfo; while (true) { newSceneInfo = GetSceneInfo(); if (newSceneInfo.version != currentSceneInfo.version) { Debug.Log("[OVRSceneLoader] Scene change detected."); // Unload all asset bundles foreach (var b in loadedAssetBundles) { if (b != null) { b.Unload(true); } } loadedAssetBundles.Clear(); // Unload all scenes in the hierarchy including main scene and // its dependent additive scenes. int activeScenes = SceneManager.sceneCount; for (int i = 0; i < activeScenes; i++) { SceneManager.UnloadSceneAsync(SceneManager.GetSceneAt(i)); } DestroyAllGameObjects(); SceneManager.LoadSceneAsync("OVRTransitionScene"); break; } yield return new WaitForSeconds(sceneCheckIntervalSeconds); } } void DestroyAllGameObjects() { foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[]) { Destroy(go); } } }
davidezordan/MixedRealitySamples
Oculus Demo/Assets/Oculus/VR/Scripts/OVRSceneLoader.cs
C#
mit
7,255
<?php /** * Store your app related helpers in this file. * You can access them in your Controllers, Views and Models. */
devfake/vume
app/helpers.php
PHP
mit
132
import { defaultAction, } from '../actions'; import { DEFAULT_ACTION, } from '../constants'; describe('Marginals actions', () => { describe('Default Action', () => { it('has a type of DEFAULT_ACTION', () => { const expected = { type: DEFAULT_ACTION, }; expect(defaultAction()).toEqual(expected); }); }); });
brainsandspace/ship
app/containers/Marginals/tests/actions.test.js
JavaScript
mit
352
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("thirdProblem")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("thirdProblem")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b4573fd0-d91b-4158-b943-1a7d4a343eac")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
velev1/HomeworkTA
High Quality Code - Part 1/NamingIdentifiersHomework/thirdProblem/Properties/AssemblyInfo.cs
C#
mit
1,400
/* * Fiahil * 12.05.2012 */ #if !defined(__Bomberman_Bonus_h) #define __Bomberman_Bonus_h #include <Model.hpp> #include "enum.hpp" #include "AObj.hpp" class Bonus : public AObj { public: Bonus(BonusType::eBonus t, Point const&, gdl::Model&); virtual ~Bonus(); private: BonusType::eBonus _type; gdl::Model& _model; public: BonusType::eBonus getType(void) const; void initialize(void); void draw(); void update(gdl::GameClock const&, gdl::Input&); }; #endif
fiahil/World-of-Bomberman
src/Bonus.hpp
C++
mit
486
//A simple build file using the tests directory for requirejs { baseUrl: "../../../requirejs/tests/text", paths: { text: "../../../requirejs/../text/text" }, dir: "builds/text", optimize: "none", optimizeAllPluginResources: true, modules: [ { name: "widget" } ] }
quantumlicht/collarbone
public/js/libs/rjs/build/tests/text.build.js
JavaScript
mit
349
#include "DirectFormOscillator.h" using namespace DSP; DirectFormOscillator::DirectFormOscillator(){ init = false; } void DirectFormOscillator::setFrequency(float frequency, float sampleRate){ if(fo != frequency){ flush(); fo = frequency; } fs = sampleRate; theta = 2 * PI * fo / fs; b1 = -2 * cosf(theta); b2 = 1.0f; if(!init){ yn1 = sinf(-1 * theta); yn2 = sinf(-2 * theta); init = true; } } float DirectFormOscillator::getNextSample(float input){ float output = - (b1 * yn1) - (b2 * yn2); yn2 = yn1; yn1 = output; return output; } void DirectFormOscillator::flush(){ yn1 = yn2 = 0; init = false; }
abaga129/lib_dsp
oscillators/DirectFormOscillator.cpp
C++
mit
736
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arc.Grammar.Tokens { public sealed class EndOfInputToken : IToken { } }
StephenCleary/ARC
src/Arc/Grammar/Tokens/EndOfInputToken.cs
C#
mit
214
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'stylescombo', 'no', { label: 'Stil', panelTitle: 'Stilformater', panelTitle1: 'Blokkstiler', panelTitle2: 'Inlinestiler', panelTitle3: 'Objektstiler' } );
otto-torino/gino
ckeditor/plugins/stylescombo/lang/no.js
JavaScript
mit
364
//Language: GNU C++ /** Be name Khoda **/ #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <map> #include <vector> #include <list> #include <set> #include <queue> #include <deque> #include <algorithm> #include <bitset> #include <cstring> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <climits> using namespace std; #define ll long long #define un unsigned #define pii pair<ll, ll> #define pb push_back #define mp make_pair #define VAL(x) #x << " = " << x << " " #define SQR(a) ((a) * (a)) #define SZ(x) ((int) x.size()) #define ALL(x) x.begin(), x.end() #define CLR(x, a) memset(x, a, sizeof x) #define FOREACH(i, x) for(__typeof((x).begin()) i = (x).begin(); i != (x).end(); i ++) #define X first #define Y second #define PI (3.141592654) //#define cout fout //#define cin fin //ifstream fin("problem.in"); //ofstream fout("problem.out"); const int MAXN = 100 * 1000 + 10, INF = INT_MAX, MOD = 1e9 + 7; ll a[MAXN]; int main () { ios::sync_with_stdio(false); ll n, m; cin >> n >> m; for (int i = 0, t; i < m; i ++) cin >> t >> a[i]; sort(a, a + m, greater<int>()); ll ans = 0; for (ll i = 0; i < m; i ++) { if (!(i % 2) && n - 1 < i * (i + 1) / 2) break; if ((i % 2) && n < SQR(i + 1) / 2) break; ans += a[i]; } cout << ans << endl; return 0; }
AmrARaouf/algorithm-detection
graph-source-code/368-E/5288513.cpp
C++
mit
1,368
using System; using System.Diagnostics; using System.IO; namespace Cogito.Diagnostics { /// <summary> /// Implements a <see cref="TraceListener"/> that writes to a file, rolling over for each day. /// </summary> public class RollingFileTraceListener : TraceListener { readonly string filePath; DateTime today; FileInfo output; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="fileName"></param> public RollingFileTraceListener(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); if (fileName.Length < 2) throw new ArgumentOutOfRangeException(nameof(fileName)); // resolve template FileInfo filePath = ResolveFilePath(fileName); } /// <summary> /// Gets the base directory of the current executable. /// </summary> /// <returns></returns> string GetBaseDirectory() { #if NET451 return AppDomain.CurrentDomain.BaseDirectory; #else return AppContext.BaseDirectory; #endif } /// <summary> /// Resolve the <see cref="FileInfo"/> given a relative or absolute file name. /// </summary> /// <param name="fileName"></param> /// <returns></returns> string ResolveFilePath(string fileName) { if (Path.IsPathRooted(fileName)) return fileName; // resolve base directory var baseDirectory = GetBaseDirectory(); if (baseDirectory != null) { var baseDirectoryUri = new Uri(baseDirectory); if (baseDirectoryUri.IsFile) baseDirectory = baseDirectoryUri.LocalPath; } // available base directory if (baseDirectory != null && baseDirectory.Length > 0) return Path.GetFullPath(Path.Combine(baseDirectory, fileName)); // fallback to full path of file return Path.GetFullPath(fileName); } /// <summary> /// Gets the current destination file name. /// </summary> /// <returns></returns> string GetCurrentFilePath() { today = DateTime.Today; return Path.Combine( Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + "_" + today.ToString("yyyyMMdd") + Path.GetExtension(filePath)); } void Rollover() { // ensure directory path exists var file = GetCurrentFilePath(); if (Directory.Exists(Path.GetDirectoryName(file)) == false) Directory.CreateDirectory(Path.GetDirectoryName(file)); // generate new writer output = new FileInfo(file); } /// <summary> /// Checks the current date and rolls the writer over if required. /// </summary> void CheckRollover() { if (output == null || today.CompareTo(DateTime.Today) != 0) { Rollover(); } } /// <summary> /// Writes a string to the stream. /// </summary> /// <param name="value"></param> public override void Write(string value) { CheckRollover(); using (var writer = output.AppendText()) writer.Write(value); } /// <summary> /// Writes a string followed by a line terminator to the text string or stream. /// </summary> /// <param name="value"></param> public override void WriteLine(string value) { CheckRollover(); using (var writer = output.AppendText()) writer.WriteLine(value); } /// <summary> /// Clears all buffers to the current output. /// </summary> public override void Flush() { } /// <summary> /// Disposes of the instance. /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing) { } } } }
wasabii/Cogito
Cogito.Core/Diagnostics/RollingFileTraceListener.cs
C#
mit
4,404
require 'rails/generators' require 'rails/generators/migration' require 'migration_assist/helper/file_name' module RailsAssist::Migration include Rails::Generators::Migration include FileNameHelper def reverse_migration_name name name.gsub(/^add_/, 'remove_').gsub(/^create_/, 'drop_') end def reverse_migration! migration_path reverse_class_names! migration_path reverse_up_down_methods! migration_path end def reverse_class_names! migration_path # Change class name gsub_file migration_path, /class Add/, 'class Remove' gsub_file migration_path, /class Create/, 'class Drop' end def reverse_up_down_methods! migration_path # swap up and down methods gsub_file migration_path, /up/, 'dwn' gsub_file migration_path, /down/, 'up' gsub_file migration_path, /dwn/, 'down' end def latest_migration_file dir, name self.class.latest_migration_file dir, name end def migration name, template_name=nil migration_template("#{template_name || name}.erb", migration_file_name(name)) end end
kristianmandrup/migration_assist
lib/migration_assist/implementation.rb
Ruby
mit
1,087
package a2ndrade.explore.data.model; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; public class Repo implements Parcelable { public static final int DEFAULT_COLOR = Color.DKGRAY; public final String name; public final String description; private boolean isStarred; // Avatar color private int color = DEFAULT_COLOR; public Repo(String name, String description, boolean isStarred) { this.name = name; this.description = description; this.isStarred = isStarred; } public boolean isStarred() { return isStarred; } public void setStarred(boolean isStarred) { this.isStarred = isStarred; } public void setColor(int color) { this.color = color; } public int getColor() { return color; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeString(this.description); dest.writeByte(this.isStarred ? (byte) 1 : (byte) 0); } protected Repo(Parcel in) { this.name = in.readString(); this.description = in.readString(); this.isStarred = in.readByte() != 0; } public static final Creator<Repo> CREATOR = new Creator<Repo>() { @Override public Repo createFromParcel(Parcel source) { return new Repo(source); } @Override public Repo[] newArray(int size) { return new Repo[size]; } }; }
amilcar-andrade/explore
app/src/main/java/a2ndrade/explore/data/model/Repo.java
Java
mit
1,618
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Resources::Mgmt::V2019_10_01 module Models # # Deployment operation parameters. # class ScopedDeployment include MsRestAzure # @return [String] The location to store the deployment data. attr_accessor :location # @return [DeploymentProperties] The deployment properties. attr_accessor :properties # @return [Hash{String => String}] Deployment tags attr_accessor :tags # # Mapper for ScopedDeployment class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ScopedDeployment', type: { name: 'Composite', class_name: 'ScopedDeployment', model_properties: { location: { client_side_validation: true, required: true, serialized_name: 'location', type: { name: 'String' } }, properties: { client_side_validation: true, required: true, serialized_name: 'properties', type: { name: 'Composite', class_name: 'DeploymentProperties' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_resources/lib/2019-10-01/generated/azure_mgmt_resources/models/scoped_deployment.rb
Ruby
mit
2,154
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Cosmosdb::Mgmt::V2020_06_01_preview module Models # # A private endpoint connection # class PrivateEndpointConnection < ProxyResource include MsRestAzure # @return [PrivateEndpointProperty] Private endpoint which the connection # belongs to. attr_accessor :private_endpoint # @return [PrivateLinkServiceConnectionStateProperty] Connection State of # the Private Endpoint Connection. attr_accessor :private_link_service_connection_state # # Mapper for PrivateEndpointConnection class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'PrivateEndpointConnection', type: { name: 'Composite', class_name: 'PrivateEndpointConnection', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, private_endpoint: { client_side_validation: true, required: false, serialized_name: 'properties.privateEndpoint', type: { name: 'Composite', class_name: 'PrivateEndpointProperty' } }, private_link_service_connection_state: { client_side_validation: true, required: false, serialized_name: 'properties.privateLinkServiceConnectionState', type: { name: 'Composite', class_name: 'PrivateLinkServiceConnectionStateProperty' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_cosmosdb/lib/2020-06-01-preview/generated/azure_mgmt_cosmosdb/models/private_endpoint_connection.rb
Ruby
mit
2,685
// // DialogueBoxSystem.cpp // Chilli Source // Created by Ian Copland on 04/03/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_ANDROID #include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxSystem.h> #include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxJavaInterface.h> #include <CSBackend/Platform/Android/Main/JNI/Core/JNI/JavaInterfaceManager.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Core/Base/PlatformSystem.h> namespace CSBackend { namespace Android { CS_DEFINE_NAMEDTYPE(DialogueBoxSystem); //---------------------------------------------------- //---------------------------------------------------- DialogueBoxSystem::DialogueBoxSystem() { m_dialogueBoxJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<DialogueBoxJavaInterface>(); if (m_dialogueBoxJI == nullptr) { m_dialogueBoxJI = std::make_shared<DialogueBoxJavaInterface>(); JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_dialogueBoxJI); } } //---------------------------------------------------- //---------------------------------------------------- bool DialogueBoxSystem::IsA(CSCore::InterfaceIDType in_interfaceId) const { return (DialogueBoxSystem::InterfaceID == in_interfaceId || CSCore::DialogueBoxSystem::InterfaceID == in_interfaceId); } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::ShowSystemDialogue(u32 in_id, const CSCore::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm) { m_dialogueBoxJI->ShowSystemDialogue(in_id, in_title, in_message, in_confirm); m_activeSysConfirmDelegate = in_delegate; } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::ShowSystemConfirmDialogue(u32 in_id, const CSCore::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm, const std::string& in_cancel) { m_dialogueBoxJI->ShowSystemConfirmDialogue(in_id, in_title, in_message, in_confirm, in_cancel); m_activeSysConfirmDelegate = in_delegate; } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::MakeToast(const std::string& in_text) { m_dialogueBoxJI->MakeToast(in_text); } //------------------------------------------------------ //------------------------------------------------------ void DialogueBoxSystem::OnSystemConfirmDialogueResult(u32 in_id, CSCore::DialogueBoxSystem::DialogueResult in_result) { if(m_activeSysConfirmDelegate) { m_activeSysConfirmDelegate(in_id, in_result); m_activeSysConfirmDelegate = nullptr; } } //----------------------------------------------------- //----------------------------------------------------- DialogueBoxSystem::~DialogueBoxSystem() { } } } #endif
fjpavm/ChilliSource
Source/CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxSystem.cpp
C++
mit
4,611
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013-2014 sagyf Yang. The Four Group. */ package goja.lang.util; import java.util.List; import java.util.Map; import java.util.Set; public interface Context extends Cloneable { Context set(String name, Object value); Set<String> keys(); Map<String, Object> getInnerMap(); Context putAll(Object obj); Context putAll(String prefix, Object obj); boolean has(String key); Context clear(); int size(); boolean isEmpty(); Object get(String name); Object get(String name, Object dft); <T> T getAs(Class<T> type, String name); <T> T getAs(Class<T> type, String name, T dft); int getInt(String name); int getInt(String name, int dft); String getString(String name); String getString(String name, String dft); boolean getBoolean(String name); boolean getBoolean(String name, boolean dft); float getFloat(String name); float getFloat(String name, float dft); double getDouble(String name); double getDouble(String name, double dft); Map<String, Object> getMap(String name); List<Object> getList(String name); <T> List<T> getList(Class<T> classOfT, String name); Context clone(); }
shootboss/goja
goja-core/src/main/java/goja/lang/util/Context.java
Java
mit
1,292
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.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 System.Runtime.Serialization; using ProtoBuf; using ZyGames.Framework.Game.Cache; using ZyGames.Framework.Common; using ZyGames.Framework.Collection; using ZyGames.Framework.Model; using ZyGames.Tianjiexing.Model.Config; using ZyGames.Framework.Cache.Generic; namespace ZyGames.Tianjiexing.Model.DataModel { /// <summary> /// 玩家大转盘奖励表 /// </summary> [Serializable, ProtoContract] [EntityTable(DbConfig.Data, "UserDial", DbConfig.PeriodTime, DbConfig.PersonalName)] public class UserDial : BaseEntity { public UserDial() : base(AccessLevel.ReadWrite) { PrizeInfo = new TreasureInfo(); Treasure = new CacheList<TreasureInfo>(); } //protected override void BindChangeEvent() //{ // PrizeInfo.BindParentChangeEvent(this); // Treasure.BindParentChangeEvent(this); //} public UserDial(String UserID) : this() { this.UserID = UserID; } #region 自动生成属性 private string _UserID; /// <summary> /// /// </summary> [ProtoMember(1)] [EntityField("UserID", IsKey = true)] public string UserID { get { return _UserID; } set { SetChange("UserID", value); } } private TreasureInfo _PrizeInfo; /// <summary> /// /// </summary> [ProtoMember(2)] [EntityField("PrizeInfo", IsJsonSerialize = true)] public TreasureInfo PrizeInfo { get { return _PrizeInfo; } set { SetChange("PrizeInfo", value); } } private decimal _ReturnRatio; /// <summary> /// /// </summary> [ProtoMember(3)] [EntityField("ReturnRatio")] public decimal ReturnRatio { get { return _ReturnRatio; } set { SetChange("ReturnRatio", value); } } private string _HeadID; /// <summary> /// /// </summary> [ProtoMember(4)] [EntityField("HeadID")] public string HeadID { get { return _HeadID; } set { SetChange("HeadID", value); } } private Int16 _DialNum; /// <summary> /// /// </summary> [ProtoMember(5)] [EntityField("DialNum")] public Int16 DialNum { get { return _DialNum; } set { SetChange("DialNum", value); } } private DateTime _RefreshDate; /// <summary> /// /// </summary> [ProtoMember(6)] [EntityField("RefreshDate")] public DateTime RefreshDate { get { return _RefreshDate; } set { SetChange("RefreshDate", value); } } private CacheList<TreasureInfo> _Treasure; /// <summary> /// /// </summary> [ProtoMember(7)] [EntityField("Treasure", IsJsonSerialize = true)] public CacheList<TreasureInfo> Treasure { get { return _Treasure; } set { SetChange("Treasure", value); } } private int _GroupID; /// <summary> /// /// </summary> [ProtoMember(8)] [EntityField("GroupID")] public int GroupID { get { return _GroupID; } set { SetChange("GroupID", value); } } [ProtoMember(9)] public string UserItemID { get; set; } protected override object this[string index] { get { #region switch (index) { case "UserID": return UserID; case "PrizeInfo": return PrizeInfo; case "ReturnRatio": return ReturnRatio; case "HeadID": return HeadID; case "DialNum": return DialNum; case "RefreshDate": return RefreshDate; case "Treasure": return Treasure; case "GroupID": return GroupID; default: throw new ArgumentException(string.Format("UserDial index[{0}] isn't exist.", index)); } #endregion } set { #region switch (index) { case "UserID": _UserID = value.ToNotNullString(); break; case "PrizeInfo": _PrizeInfo = ConvertCustomField<TreasureInfo>(value, index); break; case "ReturnRatio": _ReturnRatio = value.ToDecimal(); break; case "HeadID": _HeadID = value.ToNotNullString(); break; case "DialNum": _DialNum = value.ToShort(); break; case "RefreshDate": _RefreshDate = value.ToDateTime(); break; case "Treasure": _Treasure = ConvertCustomField<CacheList<TreasureInfo>>(value, index); break; case "GroupID": _GroupID = value.ToInt(); break; default: throw new ArgumentException(string.Format("UserDial index[{0}] isn't exist.", index)); } #endregion } } #endregion protected override int GetIdentityId() { return UserID.ToInt(); } } }
wenhulove333/ScutServer
Sample/Koudai/Server/src/ZyGames.Tianjiexing.Model/DataModel/UserDial.cs
C#
mit
7,951
<?php unset($where); if ($_GET['l'] == 'anfragen'){ $where['typ'] = 1; } elseif ($_GET['l'] == 'angebote'){ $where['typ'] = 0; } elseif ((($_GET['l'] == 'meinkonto') && !isset($_GET['a'])) || (($_GET['l'] == 'meinkonto') && ($_GET['a'] == 'angebote'))){ $where['typ'] = 0; $where['userid'] = $_SESSION['userid']; } elseif (($_GET['l'] == 'meinkonto') && ($_GET['a'] == 'anfragen')){ $where['userid'] = $_SESSION['userid']; $where['typ'] = 1; } $where['erledigt'] = 0; $stmt = $db->select("*", "nachhilfe", $where); while ($erg = $stmt->fetchObject()){ unset($where); $where['id'] = $erg->userid; $uisq = $db->select("nick", "user", $where); $uierg = $uisq->fetchObject(); echo '<div id="nachhilfecontainer"> <div id="nachhilfehead">'; echo 'Nachhilfe in: '; $link = ""; if (isset($_GET['a'])){ $link = '&a='.$_GET['a']; } echo '<a href="index.php?l='.$_GET['l'].$link.'&nachid='.$erg->id.'">'.$erg->fach.'</a></br>'; $datum = explode("-", $erg->datetime); echo 'Erstellt: '.$datum["2"].'.'.$datum["1"].'.'.$datum["0"].' '.$datum["3"].':'.$datum["4"].' '; echo 'von: '.$uierg->nick.'<br/>'; echo 'ab: '.$erg->zeitraum.'<br/>'; $tag = ''; $tage = explode(';', $erg->tage); for ($i = 0; $i < count($tage); $i++){ $tag .= ', '.$tage[$i]; } echo 'Tage: '.substr($tag, 2); echo '</div>'; if (isset($_GET["nachid"]) && ($_GET["nachid"] == $erg->id)){ echo '<br/><div id="nachhilfebody">'.$erg->text.'</div>'; if ($logedin){ echo '<br><div id="nachricht"> <form id="mesform" action="scripts/mess.php" method="post" class="formwiden"> Empfänger: '.$uierg->nick.'<input type="hidden" name="nick" value="'.$uierg->nick.'"/><br/> Betreff: '.$erg->fach.'<input type="hidden" name="betreff" value="Re: '.$erg->fach.'"/><br/> Nachricht: <br/><textarea name="text" cols="50" rows="10" class="textn"></textarea> <input type="hidden" name="token" value="'.csrf_token().'"><br/> <input type="submit" name="Abschicken" value="Abschicken" class="button"> </form> </div>'; } } echo '</div>'; } ?>
jeff84/studenthelper
content/nachhilfe-back.php
PHP
mit
2,309
using System.Collections.Generic; using System.Xml.Serialization; namespace Subsonic.Common.Classes { public class RandomSongs { [XmlElement("song")] public List<Child> Songs; } }
archrival/SubsonicSharp
Subsonic.Common/Classes/RandomSongs.cs
C#
mit
211
package es.infointernet.bean; import java.security.Principal; import java.util.List; public class User implements Principal { private String username; private List<String> roles; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String getName() { return username; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } }
mpecero/jaxrs-jwt-example
src/main/java/es/infointernet/bean/User.java
Java
mit
538
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using Xunit; namespace System.Abstract { public class ServiceLocatorResolutionExceptionTests { [Fact] public void Create_Instance_With_Type() { var exception = new ServiceLocatorResolutionException(typeof(string)); Assert.Equal(exception.ServiceType, typeof(string)); Assert.Equal(exception.Message, "Could not resolve serviceType 'System.String'"); Assert.Throws<ServiceLocatorResolutionException>(() => { throw exception; }); } [Fact] public void Create_Instance_With_Type_And_InnerException() { var operationException = new InvalidOperationException(); var exception = new ServiceLocatorResolutionException(typeof(string), operationException); Assert.Equal(exception.ServiceType, typeof(string)); Assert.Equal(exception.InnerException, operationException); Assert.Equal(exception.Message, "Could not resolve serviceType 'System.String'"); Assert.Throws<ServiceLocatorResolutionException>(() => { throw exception; }); } } }
BclEx/BclEx-Abstract
src/System.Abstract.Tests/Abstract+ServiceLocator/ServiceLocatorResolutionExceptionTests.cs
C#
mit
2,278
package org.sharedmq.primitives; import java.nio.ByteBuffer; /** * An adapter for the {@link MappedByteArrayStorageKey}. */ public class MappedByteArrayStorageKeyStorageAdapter implements StorageAdapter<MappedByteArrayStorageKey> { private static final MappedByteArrayStorageKeyStorageAdapter instance = new MappedByteArrayStorageKeyStorageAdapter(); public static MappedByteArrayStorageKeyStorageAdapter getInstance() { return instance; } @Override public int getRecordSize() { return 4 * 2 + 8; } @Override public void store(ByteBuffer buffer, MappedByteArrayStorageKey key) { if (key == null) { throw new IllegalArgumentException( "The MappedByteArrayStorageKeyStorageAdapter does not support null records."); } buffer.putInt(key.getSegmentNumber()); buffer.putInt(key.getRecordNumber()); buffer.putLong(key.getRecordId()); } @Override public MappedByteArrayStorageKey load(ByteBuffer buffer) { int segmentNumber = buffer.getInt(); int recordNumber = buffer.getInt(); long recordId = buffer.getLong(); return new MappedByteArrayStorageKey(segmentNumber, recordNumber, recordId); } }
yu-kopylov/shared-mq
src/main/java/org/sharedmq/primitives/MappedByteArrayStorageKeyStorageAdapter.java
Java
mit
1,277
package algorithms.imageProcessing.features; import algorithms.util.PairInt; import algorithms.util.PixelHelper; import gnu.trove.iterator.TIntIterator; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.HashSet; import java.util.Set; import algorithms.packing.Intersection2DPacking; /** * carries the current integrated histogram from a region of * HOGS, HCPT, or HGS data. * Note that orientation is not used. * Note that the user must restrict the arguments to * being the same origin data. * * @author nichole */ public class PatchUtil { private static float eps = 0.000001f; private final long[] h; private final TIntSet pixIdxs; private final int imgW; private final int imgH; private double err = 0; private double blockTotals = 0; public PatchUtil(int imageWidth, int imageHeight, int nBins) { this.h = new long[nBins]; this.imgW = imageWidth; this.imgH = imageHeight; this.pixIdxs = new TIntHashSet(); } public void add(TIntSet addPixelIndexes, HOGs hogs) { if (hogs.getNumberOfBins() != h.length) { throw new IllegalArgumentException( "hog number of bins differs the expected"); } if (hogs.getImageWidth() != imgW) { throw new IllegalArgumentException( "hog image width differs the expected"); } if (hogs.getImageHeight() != imgH) { throw new IllegalArgumentException( "hog image height differs the expected"); } if (addPixelIndexes.isEmpty()) { return; } int c0 = pixIdxs.size(); // to keep adding to block totals, square and factor by count again double tmpBlockTotals = blockTotals; if (blockTotals > 0) { double norm = 255.f/(blockTotals + eps); div(h, norm); } long tmpSum = 0; long tmpSumErrSq = 0; double maxValue; long[] tmp = new long[h.length]; int[] xy = new int[2]; PixelHelper ph = new PixelHelper(); //TODO: correct to use a scan by cell size pattern TIntIterator iter = addPixelIndexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); if (pixIdxs.contains(pixIdx)) { continue; } pixIdxs.add(pixIdx); ph.toPixelCoords(pixIdx, imgW, xy); hogs.extractBlock(xy[0], xy[1], tmp); HOGs.add(h, tmp); tmpSum = 0; maxValue = Double.NEGATIVE_INFINITY; for (int j = 0; j < tmp.length; ++j) { tmpSum += tmp[j]; if (tmp[j] > maxValue) { maxValue = tmp[j]; } } maxValue += eps; tmpBlockTotals += tmpSum; tmpSum /= tmp.length; tmpSumErrSq += ((tmpSum/maxValue)*(tmpSum/maxValue)); } int nAdded = pixIdxs.size() - c0; int c1 = pixIdxs.size(); if (c1 > 0) { this.blockTotals = tmpBlockTotals; } double norm = 1./(blockTotals + eps); float maxBlock = 255.f; norm *= maxBlock; mult(h, norm); //TODO: examine the order of divide by count and sqrt this.err *= this.err; this.err *= c0; this.err += tmpSumErrSq; this.err /= (double)c1; this.err = Math.sqrt(err); } public void add(TIntSet addPixelIndexes, HCPT hcpt) { if (hcpt.getNumberOfBins() != h.length) { throw new IllegalArgumentException( "hog number of bins differs the expected"); } if (hcpt.getImageWidth() != imgW) { throw new IllegalArgumentException( "hog image width differs the expected"); } if (hcpt.getImageHeight() != imgH) { throw new IllegalArgumentException( "hog image height differs the expected"); } if (addPixelIndexes.isEmpty()) { return; } int c0 = pixIdxs.size(); // to keep adding to block totals, square and factor by count again double tmpBlockTotals = blockTotals; if (blockTotals > 0) { double norm = 255.f/(blockTotals + eps); div(h, norm); } long tmpSum = 0; long tmpSumErrSq = 0; double maxValue; long[] tmp = new long[h.length]; int[] xy = new int[2]; PixelHelper ph = new PixelHelper(); //TODO: correct to use a scan by cell size pattern TIntIterator iter = addPixelIndexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); if (pixIdxs.contains(pixIdx)) { continue; } pixIdxs.add(pixIdx); ph.toPixelCoords(pixIdx, imgW, xy); hcpt.extractBlock(xy[0], xy[1], tmp); HOGs.add(h, tmp); tmpSum = 0; maxValue = Double.NEGATIVE_INFINITY; for (int j = 0; j < tmp.length; ++j) { tmpSum += tmp[j]; if (tmp[j] > maxValue) { maxValue = tmp[j]; } } maxValue += eps; tmpBlockTotals += tmpSum; tmpSum /= tmp.length; tmpSumErrSq += ((tmpSum/maxValue)*(tmpSum/maxValue)); } int nAdded = pixIdxs.size() - c0; int c1 = pixIdxs.size(); if (c1 > 0) { this.blockTotals = tmpBlockTotals; } double norm = 1./(blockTotals + eps); float maxBlock = 255.f; norm *= maxBlock; mult(h, norm); //TODO: examine the order of divide by count and sqrt this.err *= this.err; this.err *= c0; this.err += tmpSumErrSq; this.err /= (double)c1; this.err = Math.sqrt(err); } public void add(TIntSet addPixelIndexes, HGS hgs) { if (hgs.getNumberOfBins() != h.length) { throw new IllegalArgumentException( "hog number of bins differs the expected"); } if (hgs.getImageWidth() != imgW) { throw new IllegalArgumentException( "hog image width differs the expected"); } if (hgs.getImageHeight() != imgH) { throw new IllegalArgumentException( "hog image height differs the expected"); } if (addPixelIndexes.isEmpty()) { return; } int c0 = pixIdxs.size(); // to keep adding to block totals, square and factor by count again double tmpBlockTotals = blockTotals; if (blockTotals > 0) { double norm = 255.f/(blockTotals + eps); div(h, norm); } long tmpSum = 0; long tmpSumErrSq = 0; double maxValue; long[] tmp = new long[h.length]; int[] xy = new int[2]; PixelHelper ph = new PixelHelper(); //TODO: correct to use a scan by cell size pattern TIntIterator iter = addPixelIndexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); if (pixIdxs.contains(pixIdx)) { continue; } pixIdxs.add(pixIdx); ph.toPixelCoords(pixIdx, imgW, xy); hgs.extractBlock(xy[0], xy[1], tmp); HOGs.add(h, tmp); tmpSum = 0; maxValue = Double.NEGATIVE_INFINITY; for (int j = 0; j < tmp.length; ++j) { tmpSum += tmp[j]; if (tmp[j] > maxValue) { maxValue = tmp[j]; } } maxValue += eps; tmpBlockTotals += tmpSum; tmpSum /= tmp.length; tmpSumErrSq += ((tmpSum/maxValue)*(tmpSum/maxValue)); } int nAdded = pixIdxs.size() - c0; int c1 = pixIdxs.size(); if (c1 > 0) { this.blockTotals = tmpBlockTotals; } double norm = 1./(blockTotals + eps); float maxBlock = 255.f; norm *= maxBlock; mult(h, norm); //TODO: examine the order of divide by count and sqrt this.err *= this.err; this.err *= c0; this.err += tmpSumErrSq; this.err /= (double)c1; this.err = Math.sqrt(err); } /** * returns the set of points that is a subset of the intersection, scanned * from center to perimeter by interval of size hog cell. * @param other * @param nCellSize * @return */ public TIntSet calculateDetectorWindow(PatchUtil other, int nCellSize) { Intersection2DPacking ip = new Intersection2DPacking(); TIntSet seeds = ip.naiveStripPacking(pixIdxs, other.pixIdxs, imgW, nCellSize); return seeds; } /** * calculate the intersection of the histograms. histograms that are * identical have a result of 1.0 and histograms that are completely * different have a result of 0. * * @param other * @return */ public double intersection(PatchUtil other) { if ((h.length != other.h.length)) { throw new IllegalArgumentException( "h and other.h must be same dimensions"); } int nBins = h.length; double sum = 0; double sumA = 0; double sumB = 0; for (int j = 0; j < nBins; ++j) { long yA = h[j]; long yB = other.h[j]; sum += Math.min(yA, yB); sumA += yA; sumB += yB; //System.out.println(" " + yA + " -- " + yB + " sum="+sum + ", " + sumA + "," + sumB); } double d = eps + Math.min(sumA, sumB); double sim = sum/d; return sim; } /** * calculate the difference of the histograms. histograms that are * identical have a result of 0.0 and histograms that are completely * different have a result of 1. * * @param other * @return */ public double[] diff(PatchUtil other) { if ((h.length != other.h.length)) { throw new IllegalArgumentException( "h and other.h must be same dimensions"); } int nBins = h.length; double tmpSumDiff = 0; double tmpErr = 0; for (int j = 0; j < nBins; ++j) { long yA = h[j]; long yB = other.h[j]; float maxValue = Math.max(yA, yB) + eps; float diff = Math.abs((yA - yB)/maxValue); tmpSumDiff += diff; // already squared tmpErr += (diff/maxValue); } tmpSumDiff /= (double)nBins; tmpErr /= (double)nBins; tmpErr = Math.sqrt(tmpErr); return new double[]{tmpSumDiff, tmpErr}; } private void mult(long[] a, double factor) { double t; for (int j = 0; j < a.length; ++j) { t = factor * a[j]; a[j] = (long)t; } } private void div(long[] a, double factor) { if (factor == 0) { throw new IllegalArgumentException("factor cannot be 0"); } double t; for (int j = 0; j < a.length; ++j) { t = a[j] / factor; a[j] = (long)t; } } public double getAvgErr() { return Math.sqrt(err); } public long[] getHistogram() { return h; } public TIntSet getPixelIndexes() { return pixIdxs; } public Set<PairInt> getPixelSet() { PixelHelper ph = new PixelHelper(); int[] xy = new int[2]; Set<PairInt> set = new HashSet<PairInt>(); TIntIterator iter = pixIdxs.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); ph.toPixelCoords(pixIdx, imgW, xy); set.add(new PairInt(xy[0], xy[1])); } return set; } }
nking/curvature-scale-space-corners-and-transformations
src/algorithms/imageProcessing/features/PatchUtil.java
Java
mit
12,845
using Microsoft.WindowsAzure.ServiceRuntime; namespace SFA.DAS.EmployerUsers.Web { public class WebRole : RoleEntryPoint { public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. return base.OnStart(); } } }
SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Web/WebRole.cs
C#
mit
399
// Package services provides Github Integration. package services import ( "encoding/json" ) // Git structs type User struct { Name string Email string Username string Display_name string } type GitRepository struct { Id int Name string Full_name string Url string AbsoluteUrl string Owner User Pusher User } type GitCommit struct { Id string Message string Timestamp string Url string Author User Committer User Modified []string } type GitUser struct { Login string Id int Avatar_url string Type string Site_admin bool } type GitPullRequest struct { Url string Html_url string Id int State string Title string User GitUser Body string Repo GitRepository Merged bool Merged_by GitUser } type GitPayload struct { Zen string Ref string Compare string Repository GitRepository Commits []GitCommit Action string Number int Pull_request GitPullRequest Pusher User } // Return github data. func getGithubData(decoder *json.Decoder, header string) (string, string) { var gEvent GitPayload decoder.Decode(&gEvent) var event, desc string if header == "push" { event = gEvent.Repository.Name + " --> " + header + " event" repo := gEvent.Repository desc = repo.Name + ": \n" + "\nName: " + repo.Name + "\nUrl: " + repo.Url + "\nOwner: " + repo.Owner.Email + "\nCompare: " + gEvent.Compare + "\nRef: " + gEvent.Ref + "\nModified files\n" for i := 0; i < len(gEvent.Commits); i++ { commit := gEvent.Commits[i] desc += "\n* " + commit.Message + " (" + commit.Timestamp + ")" for j := 0; j < len(commit.Modified); j++ { desc += "\n * " + commit.Modified[j] } } } else if header == "pull_request" { pr := gEvent.Pull_request if gEvent.Action == "opened" { event = "New pull request for " + gEvent.Repository.Full_name + " from " + pr.User.Login } else if gEvent.Action == "closed" && pr.Merged { event = "Pull request merged by " + pr.Merged_by.Login } desc = "Title: " + pr.Title if pr.Body != "" { desc += "\nDescription: " + pr.Body } desc += "\nReview at " + pr.Html_url } else if gEvent.Zen != "" { event = "Ping! from " + gEvent.Repository.Name } return event, desc }
PredictionGuru/webhook
services/git.go
GO
mit
2,755
"use strict" var writeIEEE754 = require('../float_parser').writeIEEE754 , readIEEE754 = require('../float_parser').readIEEE754 , Long = require('../long').Long , Double = require('../double').Double , Timestamp = require('../timestamp').Timestamp , ObjectID = require('../objectid').ObjectID , Symbol = require('../symbol').Symbol , BSONRegExp = require('../regexp').BSONRegExp , Code = require('../code').Code , Decimal128 = require('../decimal128') , MinKey = require('../min_key').MinKey , MaxKey = require('../max_key').MaxKey , DBRef = require('../db_ref').DBRef , Binary = require('../binary').Binary; // To ensure that 0.4 of node works correctly var isDate = function isDate(d) { return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; } var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { var totalLength = (4 + 1); if(Array.isArray(object)) { for(var i = 0; i < object.length; i++) { totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) } } else { // If we have toBSON defined, override the current object if(object.toBSON) { object = object.toBSON(); } // Calculate size for(var key in object) { totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) } } return totalLength; } /** * @ignore * @api private */ function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { // If we have toBSON defined, override the current object if(value && value.toBSON){ value = value.toBSON(); } switch(typeof value) { case 'string': return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; case 'number': if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } } else { // 64 bit return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } case 'undefined': if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); return 0; case 'boolean': return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); case 'object': if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); } else if(value instanceof Date || isDate(value)) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } else if(value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (16 + 1); } else if(value instanceof Code || value['_bsontype'] == 'Code') { // Calculate size depending on the availability of a scope if(value.scope != null && Object.keys(value.scope).length > 0) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; } } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { // Check what kind of subtype we have if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); } } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { // Set up correct object for serialization var ordered_values = { '$ref': value.namespace , '$id' : value.oid }; // Add db reference if it exists if(null != value.db) { ordered_values['$db'] = value.db; } return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1 } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; } case 'function': // WTF for 0.4.X where typeof /someregexp/ === 'function' if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 } else { if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); } else if(serializeFunctions) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; } } } return 0; } var BSON = {}; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7FFFFFFF; BSON.BSON_INT32_MIN = -0x80000000; // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. module.exports = calculateObjectSize;
PLfW/lab-5-BabalaV
node_modules/bson/lib/bson/parser/calculate_size.js
JavaScript
mit
7,823
<?php namespace Nht\Http\Requests; use Nht\Http\Requests\Request; class AdminCategoryRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'type' => 'integer|min:1' ]; } public function messages() { return [ 'name.required' => 'Vui lòng nhập tên danh mục', 'type.min' => 'Vui lòng chọn loại danh mục', 'type.integer' => 'Vui lòng chọn loại danh mục' ]; } }
alvintran/rapian-document
app/Http/Requests/AdminCategoryRequest.php
PHP
mit
687
/** * DocumentController * * @description :: Server-side logic for managing documents * @help :: See http://links.sailsjs.org/docs/controllers */ var exec = require('child_process').exec; var path = require('path'); var fs = require('fs'); var UPLOADFOLDER = __dirname+'/../../.tmp/uploads'; module.exports = { /** * `OdfController.create()` */ upload: function (req, res) { req.file("documents").upload(function (err, files) { if (err) { sails.log.error(err); return res.serverError(err); } for (var i = 0; i < files.length; i++) { files[i].uploadedAs = path.basename(files[i].fd); }; // EmailService.send(from, subject, text, html); return res.json({ message: files.length + ' file(s) uploaded successfully!', files: files }); }); }, // filters source: http://listarchives.libreoffice.org/global/users/msg15151.html // org.openoffice.da.writer2xhtml.epub // org.openoffice.da.calc2xhtml11 // Text - txt - csv (StarCalc) // impress_svg_Export // math8 // EPS - Encapsulated PostScript // StarOffice XML (Base) Report Chart // org.openoffice.da.writer2xhtml.mathml.xsl // impress_svm_Export // MS Excel 95 (StarWriter) // impress_pdf_addstream_import // JPG - JPEG // placeware_Export // StarOffice XML (Math) // T602Document // impress_jpg_Export // writer_globaldocument_StarOffice_XML_Writer // draw_emf_Export // MS Word 2003 XML // WMF - MS Windows Metafile // GIF - Graphics Interchange // writer_pdf_import // calc8 // writer_globaldocument_StarOffice_XML_Writer_GlobalDocument // MS Word 97 Vorlage // impress_tif_Export // draw_xpm_Export // Calc MS Excel 2007 XML // Text (encoded) // MathML XML (Math) // MET - OS/2 Metafile // MS PowerPoint 97 AutoPlay // impress8 // StarOffice XML (Calc) // calc_HTML_WebQuery // RAS - Sun Rasterfile // MS Excel 5.0 (StarWriter) // impress_png_Export // DXF - AutoCAD Interchange // impress_pct_Export // impress_met_Export // SGF - StarOffice Writer SGF // draw_eps_Export // Calc MS Excel 2007 Binary // calc8_template // Calc MS Excel 2007 XML Template // impress_pbm_Export // draw_pdf_import // Calc Office Open XML // math_pdf_Export // Rich Text Format (StarCalc) // MS PowerPoint 97 Vorlage // StarOffice XML (Base) // DIF // Impress MS PowerPoint 2007 XML Template // MS Excel 2003 XML // impress_ras_Export // draw_PCD_Photo_CD_Base16 // draw_bmp_Export // WordPerfect Graphics // StarOffice XML (Writer) // PGM - Portable Graymap // Office Open XML Text Template // MS Excel 5.0/95 // draw_svg_Export // draw_PCD_Photo_CD_Base4 // TGA - Truevision TARGA // Quattro Pro 6.0 // writer_globaldocument_pdf_Export // calc_pdf_addstream_import // writerglobal8_HTML // draw_svm_Export // HTML // EMF - MS Windows Metafile // PPM - Portable Pixelmap // Lotus // impress_ppm_Export // draw_jpg_Export // Text // TIF - Tag Image File // Impress Office Open XML AutoPlay // StarOffice XML (Base) Report // PNG - Portable Network Graphic // draw8 // Rich Text Format // writer_web_StarOffice_XML_Writer_Web_Template // org.openoffice.da.writer2xhtml // MS_Works // Office Open XML Text // SVG - Scalable Vector Graphics // org.openoffice.da.writer2xhtml11 // draw_tif_Export // impress_gif_Export // StarOffice XML (Draw) // StarOffice XML (Impress) // Text (encoded) (StarWriter/Web) // writer_web_pdf_Export // MediaWiki_Web // impress_pdf_Export // draw_pdf_addstream_import // draw_png_Export // HTML (StarCalc) // HTML (StarWriter) // impress_StarOffice_XML_Impress_Template // draw_pct_Export // calc_StarOffice_XML_Calc_Template // MS Excel 95 Vorlage/Template // writerglobal8_writer // MS Excel 95 // draw_met_Export // dBase // MS Excel 97 // MS Excel 4.0 // draw_pbm_Export // impress_StarOffice_XML_Draw // Impress Office Open XML // writerweb8_writer // chart8 // MediaWiki // MS Excel 4.0 Vorlage/Template // impress_wmf_Export // draw_ras_Export // writer_StarOffice_XML_Writer_Template // BMP - MS Windows // impress8_template // LotusWordPro // impress_pgm_Export // SGV - StarDraw 2.0 // draw_PCD_Photo_CD_Base // draw_html_Export // writer8_template // Calc Office Open XML Template // writerglobal8 // draw_flash_Export // MS Word 2007 XML Template // impress8_draw // CGM - Computer Graphics Metafile // MS PowerPoint 97 // WordPerfect // impress_emf_Export // writer_pdf_Export // PSD - Adobe Photoshop // PBM - Portable Bitmap // draw_ppm_Export // writer_pdf_addstream_import // PCX - Zsoft Paintbrush // writer_web_HTML_help // MS Excel 4.0 (StarWriter) // Impress Office Open XML Template // org.openoffice.da.writer2xhtml.mathml // MathType 3.x // impress_xpm_Export // writer_web_StarOffice_XML_Writer // writerweb8_writer_template // MS Word 95 // impress_html_Export // MS Word 97 // draw_gif_Export // writer8 // MS Excel 5.0/95 Vorlage/Template // draw8_template // StarOffice XML (Chart) // XPM // draw_pdf_Export // calc_pdf_Export // impress_eps_Export // XBM - X-Consortium // Text (encoded) (StarWriter/GlobalDocument) // writer_MIZI_Hwp_97 // MS WinWord 6.0 // Lotus 1-2-3 1.0 (WIN) (StarWriter) // SYLK // MS Word 2007 XML // Text (StarWriter/Web) // impress_pdf_import // MS Excel 97 Vorlage/Template // Impress MS PowerPoint 2007 XML AutoPlay // Impress MS PowerPoint 2007 XML // draw_wmf_Export // Unifa Adressbuch // org.openoffice.da.calc2xhtml // impress_bmp_Export // Lotus 1-2-3 1.0 (DOS) (StarWriter) // MS Word 95 Vorlage // MS WinWord 5 // PCT - Mac Pict // SVM - StarView Metafile // draw_StarOffice_XML_Draw_Template // impress_flash_Export // draw_pgm_Export convert: function (req, res) { var stdout = ''; var stderr = ''; sails.log.info('convert'); if(!req.param('filename')) res.badRequest('filename is required'); var source = req.param('filename'); var inputDir = UPLOADFOLDER +'/'+source; var outputFileExtension = req.param('extension') ? req.param('extension') : 'pdf'; // example 'pdf'; var outputFilterName = req.param('filter') ? ':'+req.param('filter') : ''; //(optinal) example ':'+'MS Excel 95'; var outputDir = UPLOADFOLDER; if(req.param('dir')) { outputDir += '/'+req.param('dir'); } outputDir = path.normalize(outputDir); inputDir = path.normalize(inputDir); var target = outputDir+"/"+path.basename(source, '.odt')+"."+outputFileExtension; var command = 'soffice --headless --invisible --convert-to '+outputFileExtension+outputFilterName+' --outdir '+outputDir+' '+inputDir; sails.log.info(command); var child = exec(command, function (code, stdout, stderr) { if(code) { sails.log.error(code); } if(stderr) { sails.log.error(stderr); } if(stdout) { sails.log.info(stdout); } res.json({target:target, code: code, stdout: stdout, stderr: stderr}); // res.download(target); // not working over socket.io }); } };
JumpLink/mwp-maps
src/api/controllers/DocumentController.js
JavaScript
mit
7,286
class ItemMarkersCountCache < ActiveRecord::Migration def self.up add_column :items, :markers_count, :integer, {:default => 0} end def self.down remove_column :items, :markers_count end end
nazar/DarkFallSage
db/migrate/20090702194132_item_markers_count_cache.rb
Ruby
mit
207
using System; namespace SoCreate.ServiceFabric.PubSubDemo.SampleEvents { public class SampleEvent { public Guid Id { get; set; } public string Message { get; set; } public SampleEvent() { Id = Guid.NewGuid(); } } public class SampleUnorderedEvent { public Guid Id { get; set; } public string Message { get; set; } public SampleUnorderedEvent() { Id = Guid.NewGuid(); } } }
loekd/ServiceFabric.PubSubActors
examples/SoCreate.ServiceFabric.PubSubDemo.SampleEvents/SampleEvent.cs
C#
mit
513
'use strict'; var assert = require('assert'), mongoose = require('mongoose'), mobgoose = require('../')(mongoose); var Foo = mongoose.model('Foo', new mongoose.Schema({}), 'foo_collection_name'); it('accepts configuration without url', function() { return mobgoose({ host: 'localhost', database: 'test123' }) .then(function(connection) { var model = connection.model('Foo'); assert(model.db.name === 'test123'); }); }); it('supports a simple conection string', function() { return mobgoose('mongodb://localhost:27017/test') .then(function(connection) { var model = connection.model('Foo'); assert(model.db.name === 'test'); }); }); it('keeps the model collection name', function() { return mobgoose('mongodb://localhost:27017/test') .then(function(connection) { var model = connection.model('Foo'); assert(model.collection.name === 'foo_collection_name'); }); }); describe('different databases on the same server', function(done) { var connection1, connection2; before(function() { return mobgoose({ host: 'localhost', database: 'test1' }) .then(function(connection) { connection1 = connection; }); }); before(function() { return mobgoose({ host: 'localhost', database: 'test2' }) .then(function(connection) { connection2 = connection; }); }); it('use one actual connection', function() { assert(Object.keys(mobgoose.connections).length === 1); }); it('produce connections in the connected readyState', function() { assert(connection1.readyState === mongoose.STATES.connected); assert(connection2.readyState === mongoose.STATES.connected); }); it('register their own models', function() { assert(connection1.model('Foo') !== undefined); assert(connection1.model('Foo').modelName === Foo.modelName); assert(connection1.model('Foo').db.name === 'test1'); assert(connection2.model('Foo') !== undefined); assert(connection2.model('Foo').modelName === Foo.modelName); assert(connection2.model('Foo').db.name === 'test2'); }); }); describe('multiple hosts', function() { it('work with a bunch of databases', function() { return Promise.all(['localhost', '127.0.0.1'].map((host) => { return Promise.all(['foo', 'bar', 'baz'].map((database) => { return mobgoose({ host: host, database: database }); })); })) .then(function() { assert(Object.keys(mobgoose.connections).length == 2); }); }); });
dougmoscrop/mobgoose
test/spec.js
JavaScript
mit
2,576
using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NBitcoin; using Newtonsoft.Json; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Controllers; using Stratis.Bitcoin.Features.BlockStore; using Stratis.Bitcoin.Features.RPC; using Stratis.Bitcoin.Features.RPC.Exceptions; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Features.Wallet.Models; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.Primitives; using Stratis.Bitcoin.Utilities; using TracerAttributes; namespace Stratis.Bitcoin.Features.Wallet { [ApiVersion("1")] public class WalletRPCController : FeatureController { /// <summary>Provides access to the block store database.</summary> private readonly IBlockStore blockStore; /// <summary>Wallet broadcast manager.</summary> private readonly IBroadcasterManager broadcasterManager; /// <summary>Instance logger.</summary> private readonly ILogger logger; /// <summary>A reader for extracting an address from a <see cref="Script"/>.</summary> private readonly IScriptAddressReader scriptAddressReader; /// <summary>Node related configuration.</summary> private readonly StoreSettings storeSettings; /// <summary>Wallet manager.</summary> private readonly IWalletManager walletManager; /// <summary>Wallet transaction handler.</summary> private readonly IWalletTransactionHandler walletTransactionHandler; /// <summary>Wallet related configuration.</summary> private readonly WalletSettings walletSettings; public WalletRPCController( IBlockStore blockStore, IBroadcasterManager broadcasterManager, ChainIndexer chainIndexer, IConsensusManager consensusManager, IFullNode fullNode, ILoggerFactory loggerFactory, Network network, IScriptAddressReader scriptAddressReader, StoreSettings storeSettings, IWalletManager walletManager, WalletSettings walletSettings, IWalletTransactionHandler walletTransactionHandler) : base(fullNode: fullNode, consensusManager: consensusManager, chainIndexer: chainIndexer, network: network) { this.blockStore = blockStore; this.broadcasterManager = broadcasterManager; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.scriptAddressReader = scriptAddressReader; this.storeSettings = storeSettings; this.walletManager = walletManager; this.walletSettings = walletSettings; this.walletTransactionHandler = walletTransactionHandler; } [ActionName("walletpassphrase")] [ActionDescription("Stores the wallet decryption key in memory for the indicated number of seconds. Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock time that overrides the old one.")] [NoTrace] public bool UnlockWallet(string passphrase, int timeout) { Guard.NotEmpty(passphrase, nameof(passphrase)); WalletAccountReference account = this.GetWalletAccountReference(); try { this.walletManager.UnlockWallet(passphrase, account.WalletName, timeout); } catch (SecurityException exception) { throw new RPCServerException(RPCErrorCode.RPC_INVALID_REQUEST, exception.Message); } return true; // NOTE: Have to return a value or else RPC middleware doesn't serialize properly. } [ActionName("walletlock")] [ActionDescription("Removes the wallet encryption key from memory, locking the wallet. After calling this method, you will need to call walletpassphrase again before being able to call any methods which require the wallet to be unlocked.")] public bool LockWallet() { WalletAccountReference account = this.GetWalletAccountReference(); this.walletManager.LockWallet(account.WalletName); return true; // NOTE: Have to return a value or else RPC middleware doesn't serialize properly. } [ActionName("sendtoaddress")] [ActionDescription("Sends money to an address. Requires wallet to be unlocked using walletpassphrase.")] public async Task<uint256> SendToAddressAsync(BitcoinAddress address, decimal amount, string commentTx, string commentDest) { WalletAccountReference account = this.GetWalletAccountReference(); TransactionBuildContext context = new TransactionBuildContext(this.FullNode.Network) { AccountReference = this.GetWalletAccountReference(), Recipients = new[] { new Recipient { Amount = Money.Coins(amount), ScriptPubKey = address.ScriptPubKey } }.ToList(), CacheSecret = false }; try { Transaction transaction = this.walletTransactionHandler.BuildTransaction(context); await this.broadcasterManager.BroadcastTransactionAsync(transaction); uint256 hash = transaction.GetHash(); return hash; } catch (SecurityException) { throw new RPCServerException(RPCErrorCode.RPC_WALLET_UNLOCK_NEEDED, "Wallet unlock needed"); } catch (WalletException exception) { throw new RPCServerException(RPCErrorCode.RPC_WALLET_ERROR, exception.Message); } } /// <summary> /// Broadcasts a raw transaction from hex to local node and network. /// </summary> /// <param name="hex">Raw transaction in hex.</param> /// <returns>The transaction hash.</returns> [ActionName("sendrawtransaction")] [ActionDescription("Submits raw transaction (serialized, hex-encoded) to local node and network.")] public async Task<uint256> SendTransactionAsync(string hex) { Transaction transaction = this.FullNode.Network.CreateTransaction(hex); await this.broadcasterManager.BroadcastTransactionAsync(transaction); uint256 hash = transaction.GetHash(); return hash; } /// <summary> /// RPC method that gets a new address for receiving payments. /// Uses the first wallet and account. /// </summary> /// <param name="account">Parameter is deprecated.</param> /// <param name="addressType">Address type, currently only 'legacy' is supported.</param> /// <returns>The new address.</returns> [ActionName("getnewaddress")] [ActionDescription("Returns a new wallet address for receiving payments.")] public NewAddressModel GetNewAddress(string account, string addressType) { if (!string.IsNullOrEmpty(account)) throw new RPCServerException(RPCErrorCode.RPC_METHOD_DEPRECATED, "Use of 'account' parameter has been deprecated"); if (!string.IsNullOrEmpty(addressType)) { // Currently segwit and bech32 addresses are not supported. if (!addressType.Equals("legacy", StringComparison.InvariantCultureIgnoreCase)) throw new RPCServerException(RPCErrorCode.RPC_METHOD_NOT_FOUND, "Only address type 'legacy' is currently supported."); } HdAddress hdAddress = this.walletManager.GetUnusedAddress(this.GetWalletAccountReference()); string base58Address = hdAddress.Address; return new NewAddressModel(base58Address); } /// <summary> /// RPC method that returns the total available balance. /// The available balance is what the wallet considers currently spendable. /// /// Uses the first wallet and account. /// </summary> /// <param name="accountName">Remains for backward compatibility. Must be excluded or set to "*" or "". Deprecated in latest bitcoin core (0.17.0).</param> /// <param name="minConfirmations">Only include transactions confirmed at least this many times. (default=0)</param> /// <returns>Total spendable balance of the wallet.</returns> [ActionName("getbalance")] [ActionDescription("Gets wallets spendable balance.")] public decimal GetBalance(string accountName, int minConfirmations = 0) { if (!string.IsNullOrEmpty(accountName) && !accountName.Equals("*")) throw new RPCServerException(RPCErrorCode.RPC_METHOD_DEPRECATED, "Account has been deprecated, must be excluded or set to \"*\""); WalletAccountReference account = this.GetWalletAccountReference(); Money balance = this.walletManager.GetSpendableTransactionsInAccount(account, minConfirmations).Sum(x => x.Transaction.Amount); return balance?.ToUnit(MoneyUnit.BTC) ?? 0; } /// <summary> /// RPC method to return transaction info from the wallet. Will only work fully if 'txindex' is set. /// Uses the default wallet if specified, or the first wallet found. /// </summary> /// <param name="txid">Identifier of the transaction to find.</param> /// <returns>Transaction information.</returns> [ActionName("gettransaction")] [ActionDescription("Get detailed information about an in-wallet transaction.")] public GetTransactionModel GetTransaction(string txid) { if (!uint256.TryParse(txid, out uint256 trxid)) throw new ArgumentException(nameof(txid)); WalletAccountReference accountReference = this.GetWalletAccountReference(); HdAccount account = this.walletManager.GetAccounts(accountReference.WalletName).Single(a => a.Name == accountReference.AccountName); // Get the transaction from the wallet by looking into received and send transactions. List<HdAddress> addresses = account.GetCombinedAddresses().ToList(); List<TransactionData> receivedTransactions = addresses.Where(r => !r.IsChangeAddress() && r.Transactions != null).SelectMany(a => a.Transactions.Where(t => t.Id == trxid)).ToList(); List<TransactionData> sendTransactions = addresses.Where(r => r.Transactions != null).SelectMany(a => a.Transactions.Where(t => t.SpendingDetails != null && t.SpendingDetails.TransactionId == trxid)).ToList(); if (!receivedTransactions.Any() && !sendTransactions.Any()) throw new RPCServerException(RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id."); // Get the block hash from the transaction in the wallet. TransactionData transactionFromWallet = null; uint256 blockHash = null; int? blockHeight, blockIndex; if (receivedTransactions.Any()) { blockHeight = receivedTransactions.First().BlockHeight; blockIndex = receivedTransactions.First().BlockIndex; blockHash = receivedTransactions.First().BlockHash; transactionFromWallet = receivedTransactions.First(); } else { blockHeight = sendTransactions.First().SpendingDetails.BlockHeight; blockIndex = sendTransactions.First().SpendingDetails.BlockIndex; blockHash = blockHeight != null ? this.ChainIndexer.GetHeader(blockHeight.Value).HashBlock : null; } // Get the block containing the transaction (if it has been confirmed). ChainedHeaderBlock chainedHeaderBlock = null; if (blockHash != null) this.ConsensusManager.GetOrDownloadBlocks(new List<uint256> { blockHash }, b => { chainedHeaderBlock = b; }); Block block = null; Transaction transactionFromStore = null; if (chainedHeaderBlock != null) { block = chainedHeaderBlock.Block; transactionFromStore = block.Transactions.Single(t => t.GetHash() == trxid); } DateTimeOffset transactionTime; bool isGenerated; string hex; if (transactionFromStore != null) { transactionTime = Utils.UnixTimeToDateTime(transactionFromStore.Time); isGenerated = transactionFromStore.IsCoinBase || transactionFromStore.IsCoinStake; hex = transactionFromStore.ToHex(); } else if (transactionFromWallet != null) { transactionTime = transactionFromWallet.CreationTime; isGenerated = transactionFromWallet.IsCoinBase == true || transactionFromWallet.IsCoinStake == true; hex = transactionFromWallet.Hex; } else { transactionTime = sendTransactions.First().SpendingDetails.CreationTime; isGenerated = false; hex = null; // TODO get from mempool } var model = new GetTransactionModel { Confirmations = blockHeight != null ? this.ConsensusManager.Tip.Height - blockHeight.Value + 1 : 0, Isgenerated = isGenerated ? true : (bool?)null, BlockHash = blockHash, BlockIndex = blockIndex ?? block?.Transactions.FindIndex(t => t.GetHash() == trxid), BlockTime = block?.Header.BlockTime.ToUnixTimeSeconds(), TransactionId = uint256.Parse(txid), TransactionTime = transactionTime.ToUnixTimeSeconds(), TimeReceived = transactionTime.ToUnixTimeSeconds(), Details = new List<GetTransactionDetailsModel>(), Hex = hex }; Money feeSent = Money.Zero; if (sendTransactions.Any()) { Wallet wallet = this.walletManager.GetWallet(accountReference.WalletName); feeSent = wallet.GetSentTransactionFee(trxid); } // Send transactions details. foreach (PaymentDetails paymentDetail in sendTransactions.Select(s => s.SpendingDetails).SelectMany(sd => sd.Payments)) { // Only a single item should appear per destination address. if (model.Details.SingleOrDefault(d => d.Address == paymentDetail.DestinationAddress) == null) { model.Details.Add(new GetTransactionDetailsModel { Address = paymentDetail.DestinationAddress, Category = GetTransactionDetailsCategoryModel.Send, Amount = -paymentDetail.Amount.ToDecimal(MoneyUnit.BTC), Fee = -feeSent.ToDecimal(MoneyUnit.BTC), OutputIndex = paymentDetail.OutputIndex }); } } // Receive transactions details. foreach (TransactionData trxInWallet in receivedTransactions) { GetTransactionDetailsCategoryModel category; if (isGenerated) { category = model.Confirmations > this.FullNode.Network.Consensus.CoinbaseMaturity ? GetTransactionDetailsCategoryModel.Generate : GetTransactionDetailsCategoryModel.Immature; } else { category = GetTransactionDetailsCategoryModel.Receive; } model.Details.Add(new GetTransactionDetailsModel { Address = addresses.First(a => a.Transactions.Contains(trxInWallet)).Address, Category = category, Amount = trxInWallet.Amount.ToDecimal(MoneyUnit.BTC), OutputIndex = trxInWallet.Index }); } model.Amount = model.Details.Sum(d => d.Amount); model.Fee = model.Details.FirstOrDefault(d => d.Category == GetTransactionDetailsCategoryModel.Send)?.Fee; return model; } [ActionName("listaddressgroupings")] [ActionDescription("Returns a list of grouped addresses which have had their common ownership made public by common use as inputs or as the resulting change in past transactions.")] public AddressGroupingModel[] ListAddressGroupings() { if (!this.storeSettings.TxIndex) throw new RPCServerException(RPCErrorCode.RPC_INVALID_REQUEST, $"{nameof(ListAddressGroupings)} is incompatible with transaction indexing turned off (i.e. -txIndex=0)."); var walletReference = this.GetWalletAccountReference(); var addressGroupings = this.GetAddressGroupings(walletReference.WalletName); var addressGroupingModels = new List<AddressGroupingModel>(); foreach (var addressGrouping in addressGroupings) { var addressGroupingModel = new AddressGroupingModel(); foreach (var address in addressGrouping) { var balance = this.walletManager.GetAddressBalance(address); addressGroupingModel.AddressGroups.Add(new AddressGroupModel() { Address = address, Amount = balance.AmountConfirmed }); } addressGroupingModels.Add(addressGroupingModel); } return addressGroupingModels.ToArray(); } /// <summary> /// Returns a list of grouped addresses which have had their common ownership made public by common use as inputs or as the resulting change in past transactions. /// </summary /// <remarks> /// Please see https://github.com/bitcoin/bitcoin/blob/726d0668ff780acb59ab0200359488ce700f6ae6/src/wallet/wallet.cpp#L3641 /// </remarks> /// <param name="walletName">The wallet in question.</param> /// <returns>The grouped list of base58 addresses.</returns> private List<List<string>> GetAddressGroupings(string walletName) { // Get the wallet to check. var wallet = this.walletManager.GetWallet(walletName); // Cache all the addresses in the wallet. var addresses = wallet.GetAllAddresses(); // Get the transaction data for this wallet. var txs = wallet.GetAllTransactions(); // Create a transaction dictionary for performant lookups. var txDictionary = new Dictionary<uint256, TransactionData>(txs.Count()); foreach (var item in txs) { txDictionary.TryAdd(item.Id, item); } // Cache the wallet's set of internal (change addresses). var internalAddresses = wallet.GetAccounts().SelectMany(a => a.InternalAddresses); var addressGroupings = new List<List<string>>(); foreach (var transaction in txDictionary) { var tx = this.blockStore.GetTransactionById(transaction.Value.Id); if (tx.Inputs.Count > 0) { var addressGroupBase58 = new List<string>(); // Group all input addresses with each other. foreach (var txIn in tx.Inputs) { if (!IsTxInMine(addresses, txDictionary, txIn)) continue; // Get the txIn's previous transaction address. var prevTransactionData = txs.FirstOrDefault(t => t.Id == txIn.PrevOut.Hash); var prevTransaction = this.blockStore.GetTransactionById(prevTransactionData.Id); var prevTransactionScriptPubkey = prevTransaction.Outputs[txIn.PrevOut.N].ScriptPubKey; var addressBase58 = this.scriptAddressReader.GetAddressFromScriptPubKey(this.Network, prevTransactionScriptPubkey); if (string.IsNullOrEmpty(addressBase58)) continue; addressGroupBase58.Add(addressBase58); } // If any of the inputs were "mine", also include any change addresses associated to the transaction. if (addressGroupBase58.Any()) { foreach (var txOut in tx.Outputs) { if (IsChange(internalAddresses, txOut.ScriptPubKey)) { var txOutAddressBase58 = this.scriptAddressReader.GetAddressFromScriptPubKey(this.Network, txOut.ScriptPubKey); if (!string.IsNullOrEmpty(txOutAddressBase58)) addressGroupBase58.Add(txOutAddressBase58); } } addressGroupings.Add(addressGroupBase58); } } // Group lone addresses by themselves. foreach (var txOut in tx.Outputs) { if (IsAddressMine(addresses, txOut.ScriptPubKey)) { var grouping = new List<string>(); string addressBase58 = this.scriptAddressReader.GetAddressFromScriptPubKey(this.Network, txOut.ScriptPubKey); if (string.IsNullOrEmpty(addressBase58)) continue; grouping.Add(addressBase58); addressGroupings.Add(grouping); } } } // Merge the results into a distinct set of grouped addresses. var uniqueGroupings = new List<List<string>>(); foreach (var addressGroup in addressGroupings) { var addressGroupDistinct = addressGroup.Distinct(); List<string> existing = null; foreach (var address in addressGroupDistinct) { // If the address was found to be apart of an existing group add it here. // The assumption here is that if we have a grouping of [a,b], finding [a] would have returned // the existing set and we can just add the address to that set. if (existing != null) { var existingAddress = existing.FirstOrDefault(a => a == address); if (existingAddress == null) existing.Add(address); continue; } // Check if the address already exists in a group. // If it does not, add the distinct set into the unique groupings list, // thereby creating a new "grouping". existing = uniqueGroupings.FirstOrDefault(g => g.Contains(address)); if (existing == null) uniqueGroupings.Add(new List<string>(addressGroupDistinct)); } } return uniqueGroupings.ToList(); } /// <summary> /// This will check the wallet's list of <see cref="HdAccount.InternalAddress"/>es to see if this address is /// an address that received change. /// </summary> /// <param name="internalAddresses">The wallet's set of internal addresses.</param> /// <param name="txOutScriptPubkey">The base58 address to verify from the <see cref="TxOut"/>.</param> /// <returns><c>true</c> if the <paramref name="txOutScriptPubkey"/> is a change address.</returns> private bool IsChange(IEnumerable<HdAddress> internalAddresses, Script txOutScriptPubkey) { return internalAddresses.FirstOrDefault(ia => ia.ScriptPubKey == txOutScriptPubkey) != null; } /// <summary> /// Determines whether or not the input's address exists in the wallet's set of addresses. /// </summary> /// <param name="addresses">The wallet's external and internal addresses.</param> /// <param name="txDictionary">The set of transactions to check against.</param> /// <param name="txIn">The input to check.</param> /// <returns><c>true</c>if the input's address exist in the wallet.</returns> private bool IsTxInMine(IEnumerable<HdAddress> addresses, Dictionary<uint256, TransactionData> txDictionary, TxIn txIn) { TransactionData previousTransaction = null; txDictionary.TryGetValue(txIn.PrevOut.Hash, out previousTransaction); if (previousTransaction == null) return false; var previousTx = this.blockStore.GetTransactionById(previousTransaction.Id); if (txIn.PrevOut.N >= previousTx.Outputs.Count) return false; // We now need to check if the scriptPubkey is in our wallet. // See https://github.com/bitcoin/bitcoin/blob/011c39c2969420d7ca8b40fbf6f3364fe72da2d0/src/script/ismine.cpp return IsAddressMine(addresses, previousTx.Outputs[txIn.PrevOut.N].ScriptPubKey); } /// <summary> /// Determines whether the script translates to an address that exists in the given wallet. /// </summary> /// <param name="addresses">All the addresses from the wallet.</param> /// <param name="scriptPubKey">The script to check.</param> /// <returns><c>true</c> if the <paramref name="scriptPubKey"/> is an address in the given wallet.</returns> private bool IsAddressMine(IEnumerable<HdAddress> addresses, Script scriptPubKey) { return addresses.FirstOrDefault(a => a.ScriptPubKey == scriptPubKey) != null; } [ActionName("listunspent")] [ActionDescription("Returns an array of unspent transaction outputs belonging to this wallet.")] public UnspentCoinModel[] ListUnspent(int minConfirmations = 1, int maxConfirmations = 9999999, string addressesJson = null) { List<BitcoinAddress> addresses = new List<BitcoinAddress>(); if (!string.IsNullOrEmpty(addressesJson)) { JsonConvert.DeserializeObject<List<string>>(addressesJson).ForEach(i => addresses.Add(BitcoinAddress.Create(i, this.FullNode.Network))); } WalletAccountReference accountReference = this.GetWalletAccountReference(); IEnumerable<UnspentOutputReference> spendableTransactions = this.walletManager.GetSpendableTransactionsInAccount(accountReference, minConfirmations); var unspentCoins = new List<UnspentCoinModel>(); foreach (var spendableTx in spendableTransactions) { if (spendableTx.Confirmations <= maxConfirmations) { if (!addresses.Any() || addresses.Contains(BitcoinAddress.Create(spendableTx.Address.Address, this.FullNode.Network))) { unspentCoins.Add(new UnspentCoinModel() { Account = accountReference.AccountName, Address = spendableTx.Address.Address, Id = spendableTx.Transaction.Id, Index = spendableTx.Transaction.Index, Amount = spendableTx.Transaction.Amount, ScriptPubKeyHex = spendableTx.Transaction.ScriptPubKey.ToHex(), RedeemScriptHex = null, // TODO: Currently don't support P2SH wallet addresses, review if we do. Confirmations = spendableTx.Confirmations, IsSpendable = !spendableTx.Transaction.IsSpent(), IsSolvable = !spendableTx.Transaction.IsSpent() // If it's spendable we assume it's solvable. }); } } } return unspentCoins.ToArray(); } [ActionName("sendmany")] [ActionDescription("Creates and broadcasts a transaction which sends outputs to multiple addresses.")] public async Task<uint256> SendManyAsync(string fromAccount, string addressesJson, int minConf = 1, string comment = null, string subtractFeeFromJson = null, bool isReplaceable = false, int? confTarget = null, string estimateMode = "UNSET") { if (string.IsNullOrEmpty(addressesJson)) throw new RPCServerException(RPCErrorCode.RPC_INVALID_PARAMETER, "No valid output addresses specified."); var addresses = new Dictionary<string, decimal>(); try { // Outputs addresses are key-value pairs of address, amount. Translate to Receipient list. addresses = JsonConvert.DeserializeObject<Dictionary<string, decimal>>(addressesJson); } catch (JsonSerializationException ex) { throw new RPCServerException(RPCErrorCode.RPC_PARSE_ERROR, ex.Message); } if (addresses.Count == 0) throw new RPCServerException(RPCErrorCode.RPC_INVALID_PARAMETER, "No valid output addresses specified."); // Optional list of addresses to subtract fees from. IEnumerable<BitcoinAddress> subtractFeeFromAddresses = null; if (!string.IsNullOrEmpty(subtractFeeFromJson)) { try { subtractFeeFromAddresses = JsonConvert.DeserializeObject<List<string>>(subtractFeeFromJson).Select(i => BitcoinAddress.Create(i, this.FullNode.Network)); } catch (JsonSerializationException ex) { throw new RPCServerException(RPCErrorCode.RPC_PARSE_ERROR, ex.Message); } } var recipients = new List<Recipient>(); foreach (var address in addresses) { // Check for duplicate recipients var recipientAddress = BitcoinAddress.Create(address.Key, this.FullNode.Network).ScriptPubKey; if (recipients.Any(r => r.ScriptPubKey == recipientAddress)) throw new RPCServerException(RPCErrorCode.RPC_INVALID_PARAMETER, string.Format("Invalid parameter, duplicated address: {0}.", recipientAddress)); var recipient = new Recipient { ScriptPubKey = recipientAddress, Amount = Money.Coins(address.Value), SubtractFeeFromAmount = subtractFeeFromAddresses == null ? false : subtractFeeFromAddresses.Contains(BitcoinAddress.Create(address.Key, this.FullNode.Network)) }; recipients.Add(recipient); } WalletAccountReference accountReference = this.GetWalletAccountReference(); var context = new TransactionBuildContext(this.FullNode.Network) { AccountReference = accountReference, MinConfirmations = minConf, Shuffle = true, // We shuffle transaction outputs by default as it's better for anonymity. Recipients = recipients, CacheSecret = false }; // Set fee type for transaction build context. context.FeeType = FeeType.Medium; if (estimateMode.Equals("ECONOMICAL", StringComparison.InvariantCultureIgnoreCase)) context.FeeType = FeeType.Low; else if (estimateMode.Equals("CONSERVATIVE", StringComparison.InvariantCultureIgnoreCase)) context.FeeType = FeeType.High; try { // Log warnings for currently unsupported parameters. if (!string.IsNullOrEmpty(comment)) this.logger.LogWarning("'comment' parameter is currently unsupported. Ignored."); if (isReplaceable) this.logger.LogWarning("'replaceable' parameter is currently unsupported. Ignored."); if (confTarget != null) this.logger.LogWarning("'conf_target' parameter is currently unsupported. Ignored."); Transaction transaction = this.walletTransactionHandler.BuildTransaction(context); await this.broadcasterManager.BroadcastTransactionAsync(transaction); return transaction.GetHash(); } catch (SecurityException) { throw new RPCServerException(RPCErrorCode.RPC_WALLET_UNLOCK_NEEDED, "Wallet unlock needed"); } catch (WalletException exception) { throw new RPCServerException(RPCErrorCode.RPC_WALLET_ERROR, exception.Message); } catch (NotImplementedException exception) { throw new RPCServerException(RPCErrorCode.RPC_MISC_ERROR, exception.Message); } } /// <summary> /// Gets the first account from the "default" wallet if it specified, /// otherwise returns the first available account in the existing wallets. /// </summary> /// <returns>Reference to the default wallet account, or the first available if no default wallet is specified.</returns> private WalletAccountReference GetWalletAccountReference() { string walletName = null; if (this.walletSettings.IsDefaultWalletEnabled()) walletName = this.walletManager.GetWalletsNames().FirstOrDefault(w => w == this.walletSettings.DefaultWalletName); else { //TODO: Support multi wallet like core by mapping passed RPC credentials to a wallet/account walletName = this.walletManager.GetWalletsNames().FirstOrDefault(); } if (walletName == null) throw new RPCServerException(RPCErrorCode.RPC_INVALID_REQUEST, "No wallet found"); HdAccount account = this.walletManager.GetAccounts(walletName).First(); return new WalletAccountReference(walletName, account.Name); } } }
quantumagi/StratisBitcoinFullNode
src/Stratis.Bitcoin.Features.Wallet/WalletRPCController.cs
C#
mit
34,892
package be.tjoener.editor.model; public interface Movable { Point getPosition(); void moveTo(Point position); }
jandk/editor
src/main/java/be/tjoener/editor/model/Movable.java
Java
mit
124
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; public class Point { public double X { get; set; } public double Y { get; set; } } class Program { static void Main() { var pointOne = ReadPointCoordinates(); var pointTwo = ReadPointCoordinates(); Console.WriteLine(CalculateDistance(pointOne, pointTwo)); } public static Point ReadPointCoordinates() { var coordinates = Console.ReadLine().Split().Select(double.Parse).ToArray(); var p = new Point() { X = coordinates[0], Y = coordinates[1] }; return p; } public static double CalculateDistance(Point pointOne, Point pointTwo) { var a = pointOne.X - pointTwo.X; var b = pointOne.Y - pointTwo.Y; var sum2 = a * a + b * b; var distance = Math.Sqrt(sum2); return distance; } }
kalinmarkov/SoftUni
Programming Fundamentals/13.ObjectsAndClassesLab/04.V2.DistanceBetweenTwoPoints/V2DistanceBetweenTwoPoints.cs
C#
mit
925
/* * Copyright (c) 2019 Handywedge Co.,Ltd. * * This software is released under the MIT License. * * http://opensource.org/licenses/mit-license.php */ package com.handywedge.context; import java.util.Date; import javax.enterprise.context.RequestScoped; import com.handywedge.context.FWRequestContext; import lombok.Data; @Data @RequestScoped public class FWRequestContextImpl implements FWRequestContext { private String requestId; private String contextPath; private Date requestStartTime; private boolean rest; private String token; private String requestUrl; private String preToken; }
cstudioteam/csFrame
handywedge-master/handywedge-core/src/main/java/com/handywedge/context/FWRequestContextImpl.java
Java
mit
616
"use strict"; const setupTask = require('utils').setupTask; const calcTasks = require("calcTasks"); module.exports = { run : function(creep){ if(!creep.task){ var room = creep.room; var creepsByTask = _(Game.creeps).filter( (c) => c.task && c.task.roomName == room.name).groupBy('task.type').value(); var upgradeList = calcTasks.calcUpgradeTasks(room,creepsByTask); var myIndex = _.findIndex(upgradeList, (t) => true); if(myIndex != -1){ var upgradeContainer = room.controller.pos.findInRange(FIND_STRUCTURES,1,{filter: (s) => s.structureType == STRUCTURE_CONTAINER})[0]; creep.task=upgradeList[myIndex]; if(upgradeContainer != undefined){ creep.task.containerId = upgradeContainer.id; } return OK; } } } }
Eijolend/screeps
creep.roleUpgrader.js
JavaScript
mit
899
namespace CampusSystem.Services.Data.Contracts { using System.Linq; using CampusSystem.Data.Models; public interface IFloorService { IQueryable<Floor> GetFloorByBuildingId(int buildingId); IQueryable<Room> GetRoomsByFloorId(int floorId); int GetFloorNameById(int floorId); } }
vlad-sp/CampusSystem
CampusSystemAsp.NetMvc/Services/CampusSystem.Services.Data/Contracts/IFloorService.cs
C#
mit
326
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace AspxCommerce.ServiceItem { [Serializable] [DataContract] public class ServiceItemsDetailsInfo { [DataMember] private int _itemID; [DataMember] private string _itemName; [DataMember] private decimal _price; [DataMember] private string _shortdescription; [DataMember] private string _description; [DataMember] private string _imagePath; [DataMember] private int _categoryID; [DataMember] private int _serviceDuration; public int ItemID { get { return this._itemID; } set { if (this._itemID != value) { this._itemID = value; } } } public string ItemName { get { return this._itemName; } set { if (this._itemName != value) { this._itemName = value; } } } public decimal Price { get { return this._price; } set { if (this._price != value) { this._price = value; } } } public string ShortDescription { get { return this._shortdescription; } set { if (this._shortdescription != value) { this._shortdescription = value; } } } public string Description { get { return this._description; } set { if (this._description != value) { this._description = value; } } } public string ImagePath { get { return this._imagePath; } set { if (this._imagePath != value) { this._imagePath = value; } } } public int CategoryID { get { return this._categoryID; } set { if (this._categoryID != value) { this._categoryID = value; } } } public int ServiceDuration { get { return this._serviceDuration; } set { if ((this._serviceDuration != value)) { this._serviceDuration = value; } } } } }
AspxCommerce/AspxCommerce2.7
AspxCommerce.ServiceItem/Entity/ServiceItemsDetailsInfo.cs
C#
mit
2,885
<?php /* @Framework/Form/search_widget.html.php */ class __TwigTemplate_1e27897cdf53745818839e0426e315ba62e8c6dc797e62f5556e82b242f48ae4 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<?php echo \$view['form']->block(\$form, 'form_widget_simple', array('type' => isset(\$type) ? \$type : 'search')) ?> "; } public function getTemplateName() { return "@Framework/Form/search_widget.html.php"; } public function getDebugInfo() { return array ( 19 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("", "@Framework/Form/search_widget.html.php", "C:\\wamp64\\www\\serveurDeVoeuxOmar\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\FrameworkBundle\\Resources\\views\\Form\\search_widget.html.php"); } }
youcefboukersi/serveurdevoeux
app/cache/prod/twig/ce/ce45fd5017f3759799c3c6de030876e2d9ecdf7fec1bb9e4dbdf5a086758c464.php
PHP
mit
1,407
<?php namespace App\Http\Controllers; use Greg\View\Viewer; class HomeController { public function index(Viewer $viewer) { return $viewer->render('home'); } }
greg-md/php-app
app/Http/Controllers/HomeController.php
PHP
mit
182
package lcf.clock.prefs; import java.util.List; import lcf.clock.R; import lcf.weather.CitiesCallback; import lcf.weather.City; import lcf.weather.WeatherMain; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class CityDialog extends PrefsDialog implements OnEditorActionListener, OnClickListener, OnItemClickListener { private TextView mSearchStatus; private ListView mCitiesList; private EditText mSearchLine; private Button mSearchButton; private CityListAdapter mCitiesListAdapter; private SharedPreferences mSharedPreferences; private static final String CITY_NOT_SET = " "; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city_dialog); setTitle(R.string.cat1_city); applySize(R.id.dcityroot); mSearchStatus = (TextView) findViewById(R.id.searchStatus); mCitiesList = (ListView) findViewById(R.id.citieslist); mSearchLine = (EditText) findViewById(R.id.citysearch); mSearchLine.setOnEditorActionListener(this); mSearchButton = ((Button) findViewById(R.id.buttonSearch)); mSearchButton.setOnClickListener(this); ((Button) findViewById(R.id.button3)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); mCitiesListAdapter = new CityListAdapter(this); mCitiesList.setAdapter(mCitiesListAdapter); mCitiesList.setOnItemClickListener(this); mSharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); } @Override public void onClick(View v) { search(false); } @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { if (event != null && event.isShiftPressed()) { return false; } search(false); return true; } return false; } @Override protected void onResume() { super.onResume(); String c = getCityName(mSharedPreferences, this); if (c.length() != 0 && !c.equals(CITY_NOT_SET)) { int p = c.lastIndexOf(","); if (p > 0) { mSearchLine.setText(c.substring(0, p)); } } else { search(true); } } private void search(boolean byIp) { mCitiesListAdapter.clear(); mCitiesList.setVisibility(View.GONE); mSearchStatus.setVisibility(View.VISIBLE); mSearchLine.setEnabled(false); mSearchButton.setEnabled(false); mSearchStatus.setText(R.string.search_process); CitiesCallback cc = new CitiesCallback() { @Override public void ready(List<City> result) { if (result == null || result.size() == 0) { if (getPattern() != null) { mSearchStatus.setText(R.string.notfound); } else { mSearchStatus.setText(""); } } else { mSearchStatus.setText(""); mSearchStatus.setVisibility(View.GONE); mCitiesList.setVisibility(View.VISIBLE); for (int i = 0; i < result.size(); i++) { mCitiesListAdapter.add(result.get(i)); } } mSearchLine.setEnabled(true); mSearchButton.setEnabled(true); } }; if (byIp) { WeatherMain.findNearestCitiesByCurrentIP(cc); } else { String s = mSearchLine.getText().toString(); if (s.length() == 0) { WeatherMain.findNearestCitiesByCurrentIP(cc); } else { WeatherMain.findCities(s, cc); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { City c = mCitiesListAdapter.getItem(position); mSharedPreferences .edit() .putString(getString(R.string.key_city), CityListAdapter.getCityReadable(c, this)) .putInt(getString(R.string.key_city_id), c.getId()).commit(); finish(); } public static boolean checkFirstTime(SharedPreferences sharedPreferences, Context context) { if (getCityName(sharedPreferences, context).length() == 0) { sharedPreferences .edit() .putString(context.getString(R.string.key_city), CITY_NOT_SET).commit(); return true; } return false; } public static String getCityName(SharedPreferences sharedPreferences, Context context) { return sharedPreferences.getString( context.getString(R.string.key_city), ""); } public static int getCityId(SharedPreferences sharedPreferences, Context context) { return sharedPreferences.getInt( context.getString(R.string.key_city_id), 0); } }
Nikolay-Kha/TabletClock
app/src/main/java/lcf/clock/prefs/CityDialog.java
Java
mit
4,834
// GET /api/v1/nowplaying/groovesalad { "stationId": "groovesalad", "time": 1425871720000, "artist": "Panorama", "title": "Selene", "album": "Panorama", "trackCorrected": false, "artistCorrected": false, "albumCorrected": false, "corrected": false, "duration": 335000, "durationEstimated": false }
maxkueng/somascrobbler-api
static/sample-nowplaying.js
JavaScript
mit
320
/** * Using Rails-like standard naming convention for endpoints. * GET /api/bridges -> index * POST /api/bridges -> create * GET /api/bridges/:id -> show * PUT /api/bridges/:id -> upsert * PATCH /api/bridges/:id -> patch * DELETE /api/bridges/:id -> destroy */ 'use strict'; import jsonpatch from 'fast-json-patch'; import Bridge from './bridge.model'; function respondWithResult(res, statusCode) { statusCode = statusCode || 200; return function(entity) { if (entity) { return res.status(statusCode).json(entity); } return null; }; } function patchUpdates(patches) { return function(entity) { try { // eslint-disable-next-line prefer-reflect jsonpatch.apply(entity, patches, /*validate*/ true); } catch(err) { return Promise.reject(err); } return entity.save(); }; } function removeEntity(res) { return function(entity) { if (entity) { return entity.remove() .then(() => { res.status(204).end(); }); } }; } function handleEntityNotFound(res) { return function(entity) { if (!entity) { res.status(404).end(); return null; } return entity; }; } function handleError(res, statusCode) { statusCode = statusCode || 500; return function(err) { res.status(statusCode).send(err); }; } // Gets a list of Bridges export function index(req, res) { return Bridge.find().exec() .then(respondWithResult(res)) .catch(handleError(res)); } // Gets a single Bridge from the DB export function show(req, res) { return Bridge.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(respondWithResult(res)) .catch(handleError(res)); } // Creates a new Bridge in the DB export function create(req, res) { return Bridge.create(req.body) .then(respondWithResult(res, 201)) .catch(handleError(res)); } // Upserts the given Bridge in the DB at the specified ID export function upsert(req, res) { if (req.body._id) { Reflect.deleteProperty(req.body, '_id'); } return Bridge.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true}).exec() .then(respondWithResult(res)) .catch(handleError(res)); } // Updates an existing Bridge in the DB export function patch(req, res) { if (req.body._id) { Reflect.deleteProperty(req.body, '_id'); } return Bridge.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(patchUpdates(req.body)) .then(respondWithResult(res)) .catch(handleError(res)); } // Deletes a Bridge from the DB export function destroy(req, res) { return Bridge.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(removeEntity(res)) .catch(handleError(res)); }
sunshouxing/bshm
server/api/bridge/bridge.controller.js
JavaScript
mit
2,898
<?php class Jobs extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('job_get'); $this->load->helper('url_helper'); $this->load->library('session'); } public function index() { $data['jobs'] = $this->job_get->get_jobs($this->session->userdata['logged_in']['user_id']); $data['title'] = 'Jobs'; $data['Type']=$this->session->userdata['logged_in']['type']; $this->load->view('jobs/joblist', $data); } public function view($slug = NULL) { $data['jobs_item'] = $this->Jobs_model->get_jobs($slug); } public function insert_applied() { $this->load->model->insert_desc(); } public function insert_jobposted() { $this->load->model->insert_job(); } }
Skchoudhary/Challenge
Jobs.php
PHP
mit
1,017
/* jQuery UI Sortable plugin wrapper @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config */ angular.module('ui.sortable', []) .value('uiSortableConfig',{}) .directive('uiSortable', [ 'uiSortableConfig', function(uiSortableConfig) { return { require: '?ngModel', link: function(scope, element, attrs, ngModel) { function combineCallbacks(first,second){ if( second && (typeof second === "function") ){ return function(e,ui){ first(e,ui); second(e,ui); }; } return first; } var opts = {}; var callbacks = { receive: null, remove:null, start:null, stop:null, update:null }; var apply = function(e, ui) { if (ui.item.sortable.resort || ui.item.sortable.relocate) { scope.$apply(); } }; angular.extend(opts, uiSortableConfig); if (ngModel) { ngModel.$render = function() { element.sortable( "refresh" ); }; callbacks.start = function(e, ui) { // Save position of dragged item ui.item.sortable = { index: ui.item.index() }; }; callbacks.update = function(e, ui) { // For some reason the reference to ngModel in stop() is wrong ui.item.sortable.resort = ngModel; }; callbacks.receive = function(e, ui) { ui.item.sortable.relocate = true; // added item to array into correct position and set up flag ngModel.$modelValue.splice(ui.item.index(), 0, ui.item.sortable.moved); }; callbacks.remove = function(e, ui) { // copy data into item if (ngModel.$modelValue.length === 1) { ui.item.sortable.moved = ngModel.$modelValue.splice(0, 1)[0]; } else { ui.item.sortable.moved = ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]; } }; callbacks.stop = function(e, ui) { // digest all prepared changes if (ui.item.sortable.resort && !ui.item.sortable.relocate) { // Fetch saved and current position of dropped element var end, start; start = ui.item.sortable.index; end = ui.item.index(); // Reorder array and apply change to scope ui.item.sortable.resort.$modelValue.splice(end, 0, ui.item.sortable.resort.$modelValue.splice(start, 1)[0]); } }; } scope.$watch(attrs.uiSortable, function(newVal, oldVal){ angular.forEach(newVal, function(value, key){ if( callbacks[key] ){ // wrap the callback value = combineCallbacks( callbacks[key], value ); if ( key === 'stop' ){ // call apply after stop value = combineCallbacks( value, apply ); } } element.sortable('option', key, value); }); }, true); angular.forEach(callbacks, function(value, key ){ opts[key] = combineCallbacks(value, opts[key]); }); // call apply after stop opts.stop = combineCallbacks( opts.stop, apply ); // Create sortable element.sortable(opts); } }; } ]);
kdisneur/wish_list
javascripts/angular-sortable.js
JavaScript
mit
4,272
<?xml version="1.0" ?><!DOCTYPE TS><TS language="et" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/aboutdialog.ui" line="97"/> <source>Copyright © 2009-2012 Bitcoin 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 type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="36"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="63"/> <source>Create a new address</source> <translation>Loo uus aadress</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="77"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="102"/> <source>Sign a message to prove you own this address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="105"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="119"/> <source>&amp;Delete</source> <translation>&amp;Kustuta</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 type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="293"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Error exporting</source> <translation>Viga eksportimisel</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Label</source> <translation>Silt</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Address</source> <translation>Aadress</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="178"/> <source>(no label)</source> <translation>(silti pole)</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 type="unfinished"/> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="61"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="75"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="37"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="42"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="45"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="50"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="53"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="100"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="110"/> <location filename="../askpassphrasedialog.cpp" line="159"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <source>Bitcoin 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 type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="207"/> <location filename="../askpassphrasedialog.cpp" line="231"/> <source>Warning: The Caps Lock key is on.</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="135"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="146"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet passphrase was succesfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="73"/> <source>Bitcoin Wallet</source> <translation type="unfinished"/> </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;Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="515"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="185"/> <source>&amp;Overview</source> <translation>&amp;Ülevaade</translation> </message> <message> <location filename="../bitcoingui.cpp" line="186"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="191"/> <source>&amp;Transactions</source> <translation>&amp;Tehingud</translation> </message> <message> <location filename="../bitcoingui.cpp" line="192"/> <source>Browse transaction history</source> <translation>Sirvi tehingute ajalugu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="197"/> <source>&amp;Address Book</source> <translation>&amp;Aadressiraamat</translation> </message> <message> <location filename="../bitcoingui.cpp" line="198"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="203"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="204"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="209"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="216"/> <source>Prove you control an address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="235"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>&amp;About %1</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show information about Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="245"/> <source>&amp;Options...</source> <translation>&amp;Valikud...</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></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;Ekspordi...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="210"/> <source>Send coins to a Bitcoin address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>Modify configuration options for Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Show or hide the Bitcoin 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 type="unfinished"/> </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 type="unfinished"/> </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;Fail</translation> </message> <message> <location filename="../bitcoingui.cpp" line="296"/> <source>&amp;Settings</source> <translation>&amp;Seaded</translation> </message> <message> <location filename="../bitcoingui.cpp" line="302"/> <source>&amp;Help</source> <translation>&amp;Abiinfo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="311"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="322"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="334"/> <location filename="../bitcoingui.cpp" line="343"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="343"/> <location filename="../bitcoingui.cpp" line="399"/> <source>Bitcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="492"/> <source>%n active connection(s) to Bitcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="540"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="555"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="559"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="563"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="567"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="573"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="580"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="590"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="682"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="683"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </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. Bitcoin 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 type="unfinished"/> </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 Bitcoin.</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 type="unfinished"/> </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 Bitcoin 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 Bitcoin.</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Muuda aadressi</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>Si&amp;lt</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageBox</name> <message> <location filename="../bitcoin.cpp" line="133"/> <location filename="../bitcoin.cpp" line="143"/> <source>Bitcoin-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 type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="204"/> <source>Main</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="222"/> <source>&amp;Start Bitcoin on system login</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Automatically start Bitcoin 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 type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="114"/> <source>Sign a message to prove you own this address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="30"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="83"/> <source>%1 is not a valid address.</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="117"/> <source>Sign failed</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="348"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="351"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="372"/> <source>Port of the proxy (e.g. 1234)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="135"/> <source>Options</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location 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 Bitcoin 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 type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="147"/> <source>Number of transactions:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="118"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="105"/> <source>Your current balance</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="154"/> <source>Total number of transactions in wallet</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="55"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="70"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="105"/> <source>NOBL</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="121"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="144"/> <source>Message:</source> <translation>Sõnum:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="186"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </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>Bitcoin 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 Bitcoin 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 Bitcoin 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 type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 NOBL</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="21"/> <source>Open for %1 blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="23"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="29"/> <source>%1/offline?</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="31"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="33"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="51"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="58"/> <source>, broadcast through %1 node</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>, broadcast through %1 nodes</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="64"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="71"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="77"/> <location filename="../transactiondesc.cpp" line="94"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source>unknown</source> <translation>tundmatu</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 type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="98"/> <source> (yours, label: </source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="100"/> <source> (yours)</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="138"/> <source>(%1 matures in %2 more blocks)</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="142"/> <source>(not accepted)</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="200"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="216"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="222"/> <source>Message:</source> <translation>Sõnum:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Comment:</source> <translation>Kommentaar:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="226"/> <source>Transaction ID:</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Date</source> <translation>Kuupäev</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Type</source> <translation>Tüüp</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Address</source> <translation>Aadress</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Amount</source> <translation>Kogus</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="281"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="284"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="287"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="290"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="293"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="301"/> <source>Mined balance will be available in %n more blocks</source> <translation type="unfinished"><numerusform></numerusform><numerusform></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 type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="310"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="353"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="355"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="358"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="360"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="362"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="400"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="603"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="605"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="607"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="85"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="92"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="129"/> <source>Edit label</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="271"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Date</source> <translation>Kuupäev</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Type</source> <translation>Tüüp</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Label</source> <translation>Silt</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>Address</source> <translation>Aadress</translation> </message> <message> <location filename="../transactionview.cpp" line="284"/> <source>Amount</source> <translation>Kogus</translation> </message> <message> <location filename="../transactionview.cpp" line="285"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Error exporting</source> <translation>Viga eksportimisel</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="384"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="392"/> <source>to</source> <translation type="unfinished"/> </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 Bitcoin 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 Bitcoin 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 type="unfinished"/> </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 Bitcoin 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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="317"/> <source>Show only a tray icon after minimizing the window</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Bitcoin version</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Send command to -server or bitcoind</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="49"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Generate coins</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Don&apos;t generate coins</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="54"/> <source>Specify data directory</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Connect only to the specified node</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="79"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="80"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="87"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="88"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="89"/> <source>Output extra debugging information</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="90"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="91"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="92"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="93"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="94"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="95"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="96"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="103"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </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 Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="111"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="112"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="113"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="114"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="121"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="48"/> <source>Bitcoin</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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="132"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="134"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="135"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="136"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="137"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Sending...</source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </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. Bitcoin 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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="144"/> <source>Done loading</source> <translation type="unfinished"/> </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 Bitcoin will not work properly.</source> <translation type="unfinished"/> </message> </context> </TS>
jlcurby/NobleCoin
src/qt/locale/bitcoin_et.ts
TypeScript
mit
98,093
load("build/jslint.js"); var src = readFile("dist/jquery.ImageColorPicker.js"); JSLINT(src, { evil: true, forin: true }); // All of the following are known issues that we think are 'ok' // (in contradiction with JSLint) more information here: // http://docs.jquery.com/JQuery_Core_Style_Guidelines var ok = { "Expected an identifier and instead saw 'undefined' (a reserved word).": true, "Use '===' to compare with 'null'.": true, "Use '!==' to compare with 'null'.": true, "Expected an assignment or function call and instead saw an expression.": true, "Expected a 'break' statement before 'case'.": true }; var e = JSLINT.errors, found = 0, w; for ( var i = 0; i < e.length; i++ ) { w = e[i]; if ( !ok[ w.reason ] ) { found++; print( "\n" + w.evidence + "\n" ); print( " Problem at line " + w.line + " character " + w.character + ": " + w.reason ); } } if ( found > 0 ) { print( "\n" + found + " Error(s) found." ); } else { print( "JSLint check passed." ); }
Skarabaeus/ImageColorPicker
build/jslint-check.js
JavaScript
mit
990
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class VirtualNetworkPeering(SubResource): """Peerings in a virtual network resource. :param id: Resource ID. :type id: str :param allow_virtual_network_access: Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virtual network space. :type allow_virtual_network_access: bool :param allow_forwarded_traffic: Whether the forwarded traffic from the VMs in the remote virtual network will be allowed/disallowed. :type allow_forwarded_traffic: bool :param allow_gateway_transit: If gateway links can be used in remote virtual networking to link to this virtual network. :type allow_gateway_transit: bool :param use_remote_gateways: If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. :type use_remote_gateways: bool :param remote_virtual_network: The reference of the remote virtual network. The remote virtual network can be in the same or different region (preview). See here to register for the preview and learn more (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering). :type remote_virtual_network: ~azure.mgmt.network.v2017_11_01.models.SubResource :param remote_address_space: The reference of the remote virtual network address space. :type remote_address_space: ~azure.mgmt.network.v2017_11_01.models.AddressSpace :param peering_state: The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and 'Disconnected'. Possible values include: 'Initiated', 'Connected', 'Disconnected' :type peering_state: str or ~azure.mgmt.network.v2017_11_01.models.VirtualNetworkPeeringState :param provisioning_state: The provisioning state of the resource. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 'type': 'bool'}, 'allow_forwarded_traffic': {'key': 'properties.allowForwardedTraffic', 'type': 'bool'}, 'allow_gateway_transit': {'key': 'properties.allowGatewayTransit', 'type': 'bool'}, 'use_remote_gateways': {'key': 'properties.useRemoteGateways', 'type': 'bool'}, 'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'}, 'remote_address_space': {'key': 'properties.remoteAddressSpace', 'type': 'AddressSpace'}, 'peering_state': {'key': 'properties.peeringState', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, id=None, allow_virtual_network_access=None, allow_forwarded_traffic=None, allow_gateway_transit=None, use_remote_gateways=None, remote_virtual_network=None, remote_address_space=None, peering_state=None, provisioning_state=None, name=None, etag=None): super(VirtualNetworkPeering, self).__init__(id=id) self.allow_virtual_network_access = allow_virtual_network_access self.allow_forwarded_traffic = allow_forwarded_traffic self.allow_gateway_transit = allow_gateway_transit self.use_remote_gateways = use_remote_gateways self.remote_virtual_network = remote_virtual_network self.remote_address_space = remote_address_space self.peering_state = peering_state self.provisioning_state = provisioning_state self.name = name self.etag = etag
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/virtual_network_peering.py
Python
mit
4,677
// ----------------------------------------------------------------------- // <copyright file="SubscriptionDailyUsageRecordCollectionOperations.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.usage; import java.text.MessageFormat; import java.util.Locale; import com.fasterxml.jackson.core.type.TypeReference; import com.microsoft.store.partnercenter.BasePartnerComponent; import com.microsoft.store.partnercenter.IPartner; import com.microsoft.store.partnercenter.PartnerService; import com.microsoft.store.partnercenter.models.ResourceCollection; import com.microsoft.store.partnercenter.models.usage.SubscriptionDailyUsageRecord; import com.microsoft.store.partnercenter.models.utils.Tuple; import com.microsoft.store.partnercenter.network.PartnerServiceProxy; import com.microsoft.store.partnercenter.utils.StringHelper; /** * Implements operations related to a single subscription daily usage records. */ public class SubscriptionDailyUsageRecordCollectionOperations extends BasePartnerComponent<Tuple<String, String>> implements ISubscriptionDailyUsageRecordCollection { /** * Initializes a new instance of the {@link #SubscriptionDailyUsageRecordCollectionOperations} class. * * @param rootPartnerOperations The root partner operations instance. * @param customerId The customer Id. * @param subscriptionId The subscription id. */ public SubscriptionDailyUsageRecordCollectionOperations( IPartner rootPartnerOperations, String customerId, String subscriptionId ) { super( rootPartnerOperations, new Tuple<String, String>( customerId, subscriptionId ) ); if ( StringHelper.isNullOrWhiteSpace( customerId ) ) { throw new IllegalArgumentException( "customerId should be set." ); } if ( StringHelper.isNullOrWhiteSpace( subscriptionId ) ) { throw new IllegalArgumentException( "subscriptionId should be set." ); } } /** * Retrieves the subscription daily usage records. * * @return Collection of subscription daily usage records. */ @Override public ResourceCollection<SubscriptionDailyUsageRecord> get() { PartnerServiceProxy<SubscriptionDailyUsageRecord, ResourceCollection<SubscriptionDailyUsageRecord>> partnerServiceProxy = new PartnerServiceProxy<SubscriptionDailyUsageRecord, ResourceCollection<SubscriptionDailyUsageRecord>>( new TypeReference<ResourceCollection<SubscriptionDailyUsageRecord>>() { }, this.getPartner(), MessageFormat.format( PartnerService.getInstance().getConfiguration().getApis().get( "GetSubscriptionDailyUsageRecords" ).getPath(), this.getContext().getItem1(), this.getContext().getItem2(), Locale.US ) ); return partnerServiceProxy.get(); } }
iogav/Partner-Center-Java-SDK
PartnerSdk/src/main/java/com/microsoft/store/partnercenter/usage/SubscriptionDailyUsageRecordCollectionOperations.java
Java
mit
3,167
Noodles.http_app.routes do end
DamirSvrtan/noodles
cli/template/config/router.rb
Ruby
mit
30
public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello, World"); } }
spearsandshields/RecJ
HelloWorld/HelloWorld.java
Java
mit
110
# # rb_main.rb # Croak # # Created by Brian Cooke on 8/21/08. # Copyright (c) 2008 roobasoft, LLC. All rights reserved. # require 'osx/cocoa' require 'rubygems' include OSX Thread.abort_on_exception = true %w(EMKeychainProxy EMKeyChainItem).each do |class_name| OSX.ns_import class_name.to_sym end gemdir = OSX::NSBundle.mainBundle.resourcePath.stringByAppendingPathComponent("gems").fileSystemRepresentation Dir.glob(File.join("#{gemdir}/**/lib")).each do |path| $:.unshift(gemdir, path) end def rb_main_init path = OSX::NSBundle.mainBundle.resourcePath.fileSystemRepresentation rbfiles = Dir.entries(path).select {|x| /\.rb\z/ =~ x} rbfiles -= [ File.basename(__FILE__) ] rbfiles.each do |path| next if File.basename(path) == "Error.rb" # save that guy for later (takes too long to load) require( File.basename(path) ) end end if $0 == __FILE__ then rb_main_init OSX.NSApplicationMain(0, nil) end
bricooke/croak-app
rb_main.rb
Ruby
mit
938
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ParkAppTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ParkAppTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("186008d1-1820-49ff-8c59-5ea06b7f25c9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
xamarin-com-br/ParkForms
src/ParkApp/ParkAppTest/Properties/AssemblyInfo.cs
C#
mit
1,434
// The MIT License (MIT) // // Copyright (c) 2015-2016 Rasmus Mikkelsen // Copyright (c) 2015-2016 eBay Software Foundation // https://github.com/rasmus/EventFlow // // 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.Linq; using System.Threading; using System.Threading.Tasks; using EventFlow.Examples.Shipping.Domain.Model.CargoModel; using EventFlow.Examples.Shipping.Domain.Model.CargoModel.Commands; using EventFlow.Examples.Shipping.Domain.Model.CargoModel.ValueObjects; using EventFlow.Examples.Shipping.ExternalServices.Routing; using EventFlow.Exceptions; namespace EventFlow.Examples.Shipping.Application { public class BookingApplicationService : IBookingApplicationService { private readonly ICommandBus _commandBus; private readonly IRoutingService _routingService; public BookingApplicationService( ICommandBus commandBus, IRoutingService routingService) { _commandBus = commandBus; _routingService = routingService; } public async Task<CargoId> BookCargoAsync(Route route, CancellationToken cancellationToken) { var cargoId = CargoId.New; await _commandBus.PublishAsync(new CargoBookCommand(cargoId, route), cancellationToken).ConfigureAwait(false); var itineraries = await _routingService.CalculateItinerariesAsync(route, cancellationToken).ConfigureAwait(false); var itinerary = itineraries.FirstOrDefault(); if (itinerary == null) { throw DomainError.With("Could not find itinerary"); } await _commandBus.PublishAsync(new CargoSetItineraryCommand(cargoId, itinerary), cancellationToken).ConfigureAwait(false); return cargoId; } } }
AntoineGa/EventFlow
Source/EventFlow.Examples.Shipping/Application/BookingApplicationService.cs
C#
mit
2,845
/* * The MIT License * * Copyright 2015 Paul. * * 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. */ package org.grouchotools.jsrules.config; /** * * @author Paul */ public interface Config { }
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/config/Config.java
Java
mit
1,230
import { jMask } from '@mask-j/jMask'; import { parser_parse, mask_stringify } from '@core/parser/exports'; import { listeners_on, listeners_off } from '@core/util/listeners'; UTest({ 'should parse name' () { var ast = jMask(` define Foo { h4 > 'Hello' } `); var def = ast.filter('define').get(0); eq_(def.name, 'Foo'); }, 'should parse extends' () { var ast = parser_parse(` define Foo extends Baz, $qu_x { h4 > 'Hello' } `); var def = jMask(ast).filter('define').get(0); eq_(def.name, 'Foo'); deepEq_(def.extends, [ { compo: 'Baz' }, { compo: '$qu_x'} ]); var back = mask_stringify(ast, 4); has_(back, 'define Foo extends Baz, $qu_x {'); }, 'should parse mask head in "as" ' () { var ast = parser_parse(` define Foo as ( .some data-id='name') { h4 > 'Hello' } `); var def = jMask(ast).filter('define').get(0); eq_(def.name, 'Foo'); eq_(def.as, " .some data-id='name'"); var back = mask_stringify(ast, 4); has_(back, `define Foo as ( .some data-id='name') {`); }, 'should parse arguments ' () { var ast = parser_parse(` define Foo ( foo, $qu_x ) { h4 > 'Hello' } `); var def = jMask(ast).filter('define').get(0); deepEq_(def.arguments, [ { name: 'foo'}, { name: '$qu_x'} ]); var back = mask_stringify(ast, 4); has_(back, "define Foo (foo, $qu_x)"); }, 'should parse arguments with types' () { var ast = parser_parse(` define Foo (store: IStore) { h4 > 'Hello' } `); var def = jMask(ast).filter('define').get(0); deepEq_(def.arguments, [ { name: 'store', type: 'IStore'}]); var back = mask_stringify(ast, 4); has_(back, "define Foo (store: IStore)"); }, 'should parse arguments and extends' () { listeners_on('error', assert.avoid()); var ast = parser_parse(` define Foo (a, b) extends Bar { span > 'Hello' } `); var def = jMask(ast).filter('define').get(0); deepEq_(def.arguments, [ { name: 'a'}, { name: 'b'} ]); deepEq_(def.extends, [ { compo:'Bar' } ]); listeners_off('error'); }, 'should parse arguments, extends and as' () { listeners_on('error', assert.avoid()); var ast = parser_parse(` define Foo (a, b ) as (div) extends Xy, Bar { span > 'Hello' } `); var def = jMask(ast).filter('define').get(0); deepEq_(def.arguments, [ { name: 'a'}, { name: 'b'} ]); deepEq_(def.extends, [ { compo:'Xy' }, { compo:'Bar' } ]); deepEq_(def.as, 'div'); listeners_off('error'); var back = mask_stringify(ast, 4); has_(back, "define Foo (a, b) as (div) extends Xy, Bar {"); }, 'should parse minified' () { listeners_on('error', assert.avoid()); var ast = parser_parse(`define Foo{span>'Hello'}`); var def = jMask(ast).filter('define').get(0); deepEq_(def.name, 'Foo'); listeners_off('error'); } }) // vim: set ft=js:
atmajs/MaskJS
test/node/parser/define.spec.ts
TypeScript
mit
2,850
var fs = require('fs'); var os=require('os'); var express = require('express'), // wine = require('./routes/wines'); user = require('./services/user'); contact = require('./services/contact'); inbox = require('./services/inbox'); outbox = require('./services/outbox'); device = require('./services/device'); audio = require('./services/audio'); GLOBAL.GCMessage = require('./lib/GCMessage.js'); GLOBAL.Sound = require('./lib/Sound.js'); GLOBAL.PORT = 3000; GLOBAL.IP = "54.214.9.117"; GLOBAL.HOSTNAME = "vivu.uni.me"; //GLOBAL.IP = "127.0.0.1"; GLOBAL.__dirname = __dirname; var app = express(); app.configure(function () { app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */ app.use(express.bodyParser()); app.use(express.static(__dirname + '/public/html')); }); app.set('views', __dirname + '/views'); app.engine('html', require('ejs').renderFile); app.get('/$',function (req, res){ res.render('homepage.html'); }); app.get('/audio/flash',function (req, res){ try{ var filePath = __dirname + "/public/flash/dewplayer.swf"; var audioFile = fs.statSync(filePath); res.setHeader('Content-Type', 'application/x-shockwave-flash'); res.setHeader('Content-Length',audioFile.size); var readStream = fs.createReadStream(filePath); readStream.on('data', function(data) { res.write(data); }); readStream.on('end', function() { res.end(); }); } catch(e){ console.log("Error when process get /audio/:id, error: "+ e); res.send("Error from server"); } }); app.get('/cfs/audio/:id',function (req, res){ try{ var audioId = req.params.id; var ip = GLOBAL.IP; var host = ip+":8888"; var source = "http://"+host+"/public/audio/"+audioId+".mp3"; res.render('index1.html', { sourceurl:source, sourceid: audioId }); } catch(e){ console.log("Error when process get cfs/audio/:id, error: "+ e); res.send("Error from server"); } }); /* app.get('/cfs/audio/:id',function (req, res) { console.log("hostname:"+os.hostname()); try{ var audioId = req.params.id; var ip = GLOBAL.IP; var host = ip+":8888"; var source = "http://"+host+"/public/audio/"+audioId+".mp3"; //var source = "http://s91.stream.nixcdn.com/3ce626c71801e67a340ef3b7997001be/51828581/NhacCuaTui025/RingBackTone-SunnyHill_4g6z.mp3"; res.render(__dirname + '/public/template/index.jade', {sourceurl:source, sourceid: audioId}); } catch(e){ console.log("Error when process get cfs/audio/:id, error: "+ e); res.send("Error from server"); } }); */ /* app.get('/audio/:id',function (req, res) { try{ var audioId = req.params.id; var filePath = __dirname + "/public/audio/"+audioId+".mp3"; var audioFile = fs.statSync(filePath); res.setHeader('Content-Type', 'audio/mpeg'); res.setHeader('Content-Length',audioFile.size); var readStream = fs.createReadStream(filePath); readStream.on('data', function(data) { res.write(data); }); readStream.on('end', function() { res.end(); }); } catch(e){ console.log("Error when process get /audio/:id, error: "+ e); res.send("Error from server"); } }); */ /* app.get('/wines', wine.findAll); app.get('/wines/:id', wine.findById); app.post('/wines', wine.addWine); app.put('/wines', wine.updateWine); app.delete('/wines/:id', wine.deleteWine); */ //gcm service //app.get('/services/gcm', bllUsers); // user service app.get('/services/users', user.findAllUsers); //app.get('/services/users/:id', user.findUserByUserId); app.get('/services/users/:facebookid',user.findUserByFacebookID); app.post('/services/users/searchname', user.findUserByUserName); app.post('/services/users', user.addUser); app.put('/services/users/:id', user.updateUser); app.delete('/services/users/:id', user.deleteUserByUserId); app.delete('/services/users', user.deleteAllUsers); //contact service app.get('/services/contacts', contact.findAllContacts); app.get('/services/contacts/byuserid/:id', contact.getAllContactByUserId); app.post('/services/contacts', contact.addContact); app.delete('/services/contacts', contact.deleteAllContacts); /* app.post('/services/contacts', user.addUser); app.put('/services/contacts/:id', user.updateUser); app.delete('/services/contacts/:id', user.deleteUserByUserId); */ //inbox service app.post('/services/inboxs/delete', inbox.deleteInboxs); app.post('/services/inboxs', inbox.addInbox); app.get('/services/inboxs', inbox.findAllInboxs); app.get('/services/inboxs/byuserid/:id', inbox.findInboxByUserId); app.delete('/services/inboxs', inbox.deleteAllInboxs); app.put('/services/inboxs', inbox.updateInboxs); //app.put('/services/inbox', inbox.updateInbox); //outbox service app.post('/services/outboxs/delete', outbox.deleteOutboxs); app.post('/services/outboxs', outbox.addOutbox); app.get('/services/outboxs', outbox.findAllInboxs); app.get('/services/outboxs/byuserid/:id', outbox.findOutboxByUserId); app.delete('/services/outboxs', outbox.deleteAllOutboxs); //device service app.post('/services/devices', device.addDevice); app.get('/services/devices', device.getAllDevices); app.get('/services/devices/byuserid/:id', device.getAllDevicesByUserId); app.delete('/services/devices', device.deleteAllDevices); //audio service app.post('/upload', audio.uploadAudio); app.get('/upload/view', function(req, res){ res.send( '<form action="/upload" method="post" enctype="multipart/form-data">'+ '<input type="file" name="source">'+ '<input type="submit" value="Upload">'+ '</form>' ); }); /************************test******************************************/ app.get('/convert', function(req, res){ function removeSubstring(str,strrm){ var newstr = str.replace(strrm,""); return newstr; } GLOBAL.__staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk"); var audioDir = GLOBAL.__staticDir + "/staticserver/public/audio/"; var soundlib = new GLOBAL.Sound; soundlib.convertWavToMp3(audioDir + "24.wav",audioDir + "testout1.mp3"); res.send("Ok"); }); /************************end test******************************************/ app.listen(GLOBAL.PORT); console.log('Listening on port 3000...');
tonycaovn/vivuserver
server.js
JavaScript
mit
6,443
package cc.hughes.droidchatty; public class SearchResult { private int _postId; private String _author; private String _content; private String _posted; public SearchResult(int postId, String author, String content, String posted) { _postId = postId; _author = author; _content = content; _posted = posted; } public int getPostId() { return _postId; } public String getAuthor() { return _author; } public String getContent() { return _content; } public String getPosted() { return _posted; } }
arhughes/droidchatty
src/cc/hughes/droidchatty/SearchResult.java
Java
mit
661
using CSC.Common.Infrastructure.GitHub; using CSC.CSClassroom.Model.Projects; namespace CSC.CSClassroom.Service.Projects.PushEvents { /// <summary> /// A commit that we were notified of through a push event. /// </summary> public class PushEventCommit { /// <summary> /// The push event that notified us of the commit. /// </summary> public GitHubPushEvent PushEvent { get; } /// <summary> /// The commit that needs to be processed. /// </summary> public Commit Commit { get; } /// <summary> /// Constructor. /// </summary> public PushEventCommit(GitHubPushEvent pushEvent, Commit commit) { PushEvent = pushEvent; Commit = commit; } } }
CSClassroom/CSClassroom
Services/src/CSClassroom/CSClassroom.Service/Projects/PushEvents/PushEventCommit.cs
C#
mit
683
# -*- coding: utf-8 -*- import sys sys.path.append('../browser_interface/browser') class BrowserFactory(object): def create(self, type, *args, **kwargs): return getattr(__import__(type), type)(*args, **kwargs)
xtuyaowu/jtyd_python_spider
browser_interface/browser/BrowserFactory.py
Python
mit
225
using System.Collections.Generic; using ChessOk.ModelFramework.Messages; namespace ChessOk.ModelFramework.Commands.Messages { /// <summary> /// Обработчик сообщения <see cref="ICommandInvokedMessage{T}"/>, которое /// посылается в шину после выполнения команды с типом <typeparamref name="T"/> /// (наследник <see cref="CommandBase"/>). /// </summary> /// /// <remarks> /// Так как в сообщении <see cref="ICommandInvokedMessage{T}"/> параметр <typeparamref name="T"/> /// объявлен ковариантным, то обработчик будет вызван после выполнения всех команд, /// являющихся наследниками типа <typeparamref name="T"/>. /// </remarks> /// /// <typeparam name="T">Тип выполненной команды, наследник <see cref="CommandBase"/></typeparam> public abstract class CommandInvokedHandler<T> : ApplicationBusMessageHandler<ICommandInvokedMessage<T>> { public sealed override IEnumerable<string> MessageNames { get { yield return CommandInvokedMessage<object>.GetMessageName(); } } protected abstract void Handle(T command); protected sealed override void Handle(ICommandInvokedMessage<T> message) { Handle(message.Command); } } }
ChessOK/ModelFramework
ModelFramework/Commands/Messages/CommandInvokedHandler.cs
C#
mit
1,525
# -*- coding: utf-8 -*- import sqlite3 VERBOSE = 0 CTABLE_DOMAIN = ''' CREATE TABLE IF NOT EXISTS Domains( did INTEGER PRIMARY KEY AUTOINCREMENT, domain VARCHAR(64) UNIQUE, indegree INTEGER, outdegree INTEGER )''' CTABLE_WEBSITE = ''' CREATE TABLE IF NOT EXISTS Websites( wid INTEGER PRIMARY KEY AUTOINCREMENT, did INTEGER, url VARCHAR(256) NOT NULL UNIQUE, title VARCHAR(100), visited bit, FOREIGN KEY (did) REFERENCES Domains(did) )''' CTABLE_RULESETS = ''' CREATE TABLE IF NOT EXISTS Rulesets( rid INTEGER PRIMARY KEY AUTOINCREMENT, did INTEGER, rules VARCHAR(512), FOREIGN KEY (did) REFERENCES Domains(did) )''' class DatabaseHelper(object): def __init__(self): '''创建表''' self.conn = sqlite3.connect("./items.db") if VERBOSE: print 'Database connection OPEN.' # Domain 表 self.conn.execute(CTABLE_DOMAIN) # Website 表 self.conn.execute(CTABLE_WEBSITE) # Rule 表 self.conn.execute(CTABLE_RULESETS) self.conn.commit() if VERBOSE: cur = self.conn.cursor() print 'Tables:',cur.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall() def close(self): '''关闭与数据库的连接''' if VERBOSE: print 'Database connection CLOSE.' self.conn.close() def insertDomain(self, domain, indegree=0, outdegree=0): '''增加一个域名''' cur = self.conn.cursor() cur.execute("INSERT INTO Domains VALUES (NULL,?,?,?)", (domain, indegree, outdegree)) # 写入到文件中 self.conn.commit() def insertRuleset(self, ruleset, domain): '''增加一个robots.txt规则集''' cur = self.conn.cursor() cur.execute("SELECT did FROM Domains WHERE domain=?", (domain,)) did = cur.fetchone()[0] cur.execute("INSERT INTO Rulesets VALUES (NULL,?,?)",(did, ruleset)) # 写入到文件 self.conn.commit() def insertWebsite(self, url, domain): '''增加一个网页,标记为未访问,并对相应的domain增加其入度''' cur = self.conn.cursor() cur.execute("SELECT 1 FROM Domains WHERE domain=?", (domain,)) result = cur.fetchone() if not result: # 未有对应domain记录, 先创建domain, 把入度设为1 if VERBOSE: print 'Spot Domain:',domain self.insertDomain(domain, indegree=1) cur.execute("SELECT did FROM Domains WHERE domain=?", (domain,)) did = cur.fetchone()[0] else: did = result[0] # 对应的domain记录已经存在, 对其入度+1 cur.execute("UPDATE Domains SET outdegree=outdegree+1 WHERE domain=?", (domain,)) cur.execute("INSERT INTO Websites VALUES (NULL,?,?,NULL,0)", (did, url,)) # 写入到文件 self.conn.commit() def updateInfo(self, item, newlinks, oldlinks): '''爬虫爬完之后对数据库内容进行更新''' cur = self.conn.cursor() cur.execute("SELECT wid,did FROM Websites WHERE url=?", (item['url'],)) wid, did = cur.fetchone() # website记录更新 cur.execute("UPDATE Websites SET title=?,visited=1 WHERE wid=?", (item['title'], wid,)) # 对应的domain记录中出度也需要更新 cur.execute("UPDATE Domains SET outdegree=outdegree+? WHERE did=?", (len(item['links']), did,)) # 对该网页中所有链接涉及的记录进行更新 # 外部判断未出现过的链接 for link,domain in newlinks: self.insertWebsite(link, domain) # 外部判断出现过的链接 for link,domain in oldlinks: # 对对应的domain记录入度增加 cur.execute("UPDATE Domains SET outdegree=outdegree+1 WHERE domain=?", (domain,)) # 写入到文件 self.conn.commit() def robotsrulesetOfDomain(self, domain): '''检查domain是否在数据库中, 否 --> (False, None) 是 --> (True, 数据库中存储的robots.txt内容) ''' exist = False cur = self.conn.cursor() # 是否存在 cur.execute("SELECT 1 FROM Domains WHERE domain=?", (domain,)) if cur.fetchone() : exist = True # 存在的话,结果是什么 cur.execute("SELECT rules FROM Domains,Rulesets " "WHERE domain=? AND Domains.did=Rulesets.did" ,(domain,) ) ruleset = cur.fetchone() return (exist, ruleset) def rollback(self): self.conn.rollback() def showAll(self): self.conn.commit() cur = self.conn.cursor() cur.execute("SELECT * FROM Domains") print cur.fetchall() cur.execute("SELECT * FROM Websites") print cur.fetchall() _dbcli = None def getCliInstance(): global _dbcli if not _dbcli: _dbcli = DatabaseHelper() return _dbcli def test(): dbcli = getCliInstance() # dbcli.insertDomain('jaysonhwang.com') # dbcli.insertRuleset('test','jaysonhwang.com') print dbcli.robotsrulesetOfDomain('www.zol.com') print dbcli.robotsrulesetOfDomain('jayson.com') dbcli.showAll() dbcli.close() if __name__ == '__main__': test()
JaySon-Huang/WebModel
WebModel/database/databasehelper.py
Python
mit
4,676
package com.muller.wikimagesearch.volley; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.muller.wikimagesearch.model.Query; import java.io.UnsupportedEncodingException; import java.util.Map; public class GsonRequest<T> extends Request<T> { private final Gson gson; private final Class<T> clazz; private final Response.Listener<T> listener; /** * Make a GET request and return a parsed object from JSON. * * @param url URL of the request to make * @param clazz Relevant class object, for Gson's reflection */ public GsonRequest(String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(Method.GET, url, errorListener); this.gson = new GsonBuilder().registerTypeAdapter(Query.class, new Query.GsonDeserializer()).create(); this.clazz = clazz; this.listener = listener; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return super.getHeaders(); } @Override protected void deliverResponse(T response) { listener.onResponse(response); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } }
lauw/mustached-octo-happiness
app/src/main/java/com/muller/wikimagesearch/volley/GsonRequest.java
Java
mit
1,897
# coding: utf-8 import re from crossword import * class Crossword2(Crossword): def __init__(self): self.grid = OpenGrid() self.connected = {} self.used_words = [] def copy(self): copied = Crossword2() copied.grid = self.grid.copy() copied.connected = self.connected.copy() copied.used_words = self.used_words[:] return copied def embed(self, pos, direction, word): assert word not in self.used_words super(Crossword2, self).embed(pos, direction, word) self.used_words.append(word) def all_disconnected_sequences(self): ''' >>> c = Crossword2() >>> c.embed((0, 0), HORIZONTAL, 'ANT') >>> c.embed((0, 0), VERTICAL, 'ATOM') >>> c.embed((1, 2), HORIZONTAL, 'IT') >>> c.embed((3, 0), HORIZONTAL, 'MEET') >>> c.dump() _#____ #ANT#_ _T#IT# _O____ #MEET# _#____ >>> c.all_disconnected_sequences() [((0, 2), 2, 'T'), ((1, 0), 2, 'T'), ((2, 0), 2, 'O'), ((0, 1), 1, 'N'), ((3, 1), 1, 'E'), ((0, 2), 1, 'TI'), ((0, 2), 1, 'TI.E'), ((3, 2), 1, 'E'), ((1, 3), 1, 'T'), ((1, 3), 1, 'T.T'), ((3, 3), 1, 'T')] ''' sequences = [] for pos, direction, length in [((r, self.grid.colmin), HORIZONTAL, self.grid.width) for r in range(self.grid.rowmin, self.grid.rowmax + 1)] + [((self.grid.rowmin, c), VERTICAL, self.grid.height) for c in range(self.grid.colmin, self.grid.colmax + 1)]: line = self.grid.get_word(pos, direction, length) poslist = self.grid.poslist(pos, direction, length) sequences += self.extract_sequences(line, poslist, direction) return [(p, d, w) for (p, d, w) in sequences if not w.endswith('.')] def extract_sequences(self, line, poslist, direction, idx=0, current_seq=None): ''' >>> c = Crossword2() >>> c.extract_sequences('ABC', [(0, 0), (0, 1), (0, 2)], HORIZONTAL) [((0, 0), 2, 'ABC')] >>> c.extract_sequences('_A_', [(0, 0), (0, 1), (0, 2)], HORIZONTAL) [((0, 1), 2, 'A'), ((0, 1), 2, 'A.')] >>> c.extract_sequences('A_C', [(0, 0), (0, 1), (0, 2)], HORIZONTAL) [((0, 0), 2, 'A'), ((0, 0), 2, 'A.C'), ((0, 2), 2, 'C')] >>> c.extract_sequences('A#C', [(0, 0), (0, 1), (0, 2)], HORIZONTAL) [((0, 0), 2, 'A'), ((0, 2), 2, 'C')] >>> c.extract_sequences('A_#B_C', [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0,5)], HORIZONTAL) [((0, 0), 2, 'A'), ((0, 0), 2, 'A.'), ((0, 3), 2, 'B'), ((0, 3), 2, 'B.C'), ((0, 5), 2, 'C')] >>> c.extract_sequences('A_B__C', [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0,5)], HORIZONTAL) [((0, 0), 2, 'A'), ((0, 0), 2, 'A.B'), ((0, 2), 2, 'B'), ((0, 0), 2, 'A.B.'), ((0, 2), 2, 'B.'), ((0, 0), 2, 'A.B..C'), ((0, 2), 2, 'B..C'), ((0, 5), 2, 'C')] ''' if not current_seq: current_seq = [] if idx >= len(line): return current_seq c = line[idx] pos = poslist[idx] if c == FILLED: return current_seq + self.extract_sequences(line, poslist, direction, idx + 1, []) if c == EMPTY: new_current_seq = [(p, d, s + '.') for (p, d, s) in current_seq] return current_seq + self.extract_sequences(line, poslist, direction, idx + 1, new_current_seq) if current_seq: new_current_seq = [(p, d, s + c) for (p, d, s) in current_seq if not self.is_connected(poslist[idx - 1], pos)] if any([s.endswith('.') for (p, d, s) in current_seq]): new_current_seq.append((pos, direction, c)) return self.extract_sequences(line, poslist, direction, idx + 1, new_current_seq) else: new_current_seq = [(pos, direction, c)] return self.extract_sequences(line, poslist, direction, idx + 1, new_current_seq) def build_crossword2(words, monitor=False): ''' >>> ans = list(build_crossword2(['ANT', 'ART', 'RAT'])) >>> ans[0].dump() #ANT# >>> ans[1].dump() _#___ #ANT# _R___ _T___ _#___ >>> ans[2].dump() ___#___ __#ANT# ___R___ #RAT#__ ___#___ >>> ans[3].dump() ___#_ ___R_ _#_A_ #ANT# _R_#_ _T___ _#___ >>> ans[4].dump() _#___ _R___ #ANT# _T___ _#___ >>> ans[5].dump() ___#_ _#_A_ _R_R_ #ANT# _T_#_ _#___ >>> ans[6].dump() ___#___ ___R___ __#ANT# #ART#__ ___#___ >>> ans[7].dump() ___#_ ___A_ ___R_ #ANT# ___#_ >>> ans[8].dump() ___#__ _#RAT# ___R__ #ANT#_ ___#__ >>> ans[9].dump() ___#_ _#_A_ _R_R_ #ANT# _T_#_ _#___ >>> ans[10].dump() ___#___ ___A___ __#RAT# #ANT#__ ___#___ >>> ans[11].dump() ___#_ ___R_ ___A_ #ANT# ___#_ >>> ans[12].dump() ___#__ _#ART# ___A__ #ANT#_ ___#__ >>> ans[13].dump() ___#___ ___R___ __#ART# #ANT#__ ___#___ >>> ans[14].dump() ___#_ ___R_ _#_A_ #ANT# _R_#_ _T___ _#___ >>> len(ans) 15 ''' crosswords = [Crossword2()] crosswords[0].embed((0, 0), HORIZONTAL, words[0]) while True: if not crosswords: break crosswords = sorted(crosswords, key=lambda c: evaluate_crossword(c)) base = crosswords.pop(0) if monitor: print ('%d candidates...'%(len(crosswords))) if isinstance(monitor, dict): base.dump(empty=monitor['EMPTY'], filled=monitor['FILLED']) else: base.dump() print ('') try: sequences = base.all_disconnected_sequences() if is_valid_crossword(sequences): yield base candidates = generate_candidates(words, base, sequences) crosswords += candidates except ValueError: # discard this base pass def is_valid_crossword(sequences): return all([len(s) <= 1 or s.find('.') > -1 for _, _, s in sequences]) def generate_candidates(words, base, sequences): fit_words = [] for sequence in sequences: available_words = [w for w in words if w not in base.used_words] fit_words_for_seq = [(p, d, w) for (p, d, w) in propose_words(sequence, available_words) if base.is_fit(p, d, w)] _, _, s = sequence if not fit_words_for_seq and len(s) > 1 and s.find('.') == -1: # dead end; discard this base raise ValueError('no candidates found') fit_words += fit_words_for_seq candidates = [] for p, d, w in fit_words: copy = base.copy() copy.embed(p, d, w) candidates.append(copy) return candidates def propose_words(sequence, words): (p, d, seq) = sequence proposed_words = [] for word in words: idx = 0 while True: m = re.search(seq, word[idx:]) if not m: break proposed_words.append((OpenGrid.pos_inc(p, -(m.start() + idx), d), d, word)) idx += m.start() + 1 return proposed_words def evaluate_crossword(c): # return -len(c.used_words) return (c.grid.width + c.grid.height) * 1.0 / len(c.used_words) ** 2 # return (c.grid.width * c.grid.height) * 1.0 / sum([len(w) for w in c.used_words]) def pickup_crosswords(words, dump_option=None, monitor=False): best = 9999 for c in build_crossword2(words, monitor=monitor): if evaluate_crossword(c) < best: if dump_option: c.dump(empty=dump_option['EMPTY'], filled=dump_option['FILLED']) else: c.dump() best = evaluate_crossword(c) print ('score: %f'%(best)) print ('') if __name__ == '__main__': import doctest doctest.testmod()
yattom/crossword
crossword2.py
Python
mit
7,931
// Javascript helper functions for parsing and displaying UUIDs in the MongoDB shell. // This is a temporary solution until SERVER-3153 is implemented. // To create BinData values corresponding to the various driver encodings use: // var s = "{00112233-4455-6677-8899-aabbccddeeff}"; // var uuid = UUID(s); // new Standard encoding // var juuid = JUUID(s); // JavaLegacy encoding // var csuuid = CSUUID(s); // CSharpLegacy encoding // var pyuuid = PYUUID(s); // PythonLegacy encoding // To convert the various BinData values back to human readable UUIDs use: // uuid.toUUID() => 'UUID("00112233-4455-6677-8899-aabbccddeeff")' // juuid.ToJUUID() => 'JUUID("00112233-4455-6677-8899-aabbccddeeff")' // csuuid.ToCSUUID() => 'CSUUID("00112233-4455-6677-8899-aabbccddeeff")' // pyuuid.ToPYUUID() => 'PYUUID("00112233-4455-6677-8899-aabbccddeeff")' // With any of the UUID variants you can use toHexUUID to echo the raw BinData with subtype and hex string: // uuid.toHexUUID() => 'HexData(4, "00112233-4455-6677-8899-aabbccddeeff")' // juuid.toHexUUID() => 'HexData(3, "77665544-3322-1100-ffee-ddccbbaa9988")' // csuuid.toHexUUID() => 'HexData(3, "33221100-5544-7766-8899-aabbccddeeff")' // pyuuid.toHexUUID() => 'HexData(3, "00112233-4455-6677-8899-aabbccddeeff")' function HexToBase64(hex) { var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var base64 = ""; var group; for (var i = 0; i < 30; i += 6) { group = parseInt(hex.substr(i, 6), 16); base64 += base64Digits[(group >> 18) & 0x3f]; base64 += base64Digits[(group >> 12) & 0x3f]; base64 += base64Digits[(group >> 6) & 0x3f]; base64 += base64Digits[group & 0x3f]; } group = parseInt(hex.substr(30, 2), 16); base64 += base64Digits[(group >> 2) & 0x3f]; base64 += base64Digits[(group << 4) & 0x3f]; base64 += "=="; return base64; } function Base64ToHex(base64) { var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var hexDigits = "0123456789abcdef"; var hex = ""; for (var i = 0; i < 24; ) { var e1 = base64Digits.indexOf(base64[i++]); var e2 = base64Digits.indexOf(base64[i++]); var e3 = base64Digits.indexOf(base64[i++]); var e4 = base64Digits.indexOf(base64[i++]); var c1 = (e1 << 2) | (e2 >> 4); var c2 = ((e2 & 15) << 4) | (e3 >> 2); var c3 = ((e3 & 3) << 6) | e4; hex += hexDigits[c1 >> 4]; hex += hexDigits[c1 & 15]; if (e3 != 64) { hex += hexDigits[c2 >> 4]; hex += hexDigits[c2 & 15]; } if (e4 != 64) { hex += hexDigits[c3 >> 4]; hex += hexDigits[c3 & 15]; } } return hex; } function UUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var base64 = HexToBase64(hex); return new BinData(4, base64); // new subtype 4 } function JUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var msb = hex.substr(0, 16); var lsb = hex.substr(16, 16); msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2); lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2); hex = msb + lsb; var base64 = HexToBase64(hex); return new BinData(3, base64); } function CSUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2); var b = hex.substr(10, 2) + hex.substr(8, 2); var c = hex.substr(14, 2) + hex.substr(12, 2); var d = hex.substr(16, 16); hex = a + b + c + d; var base64 = HexToBase64(hex); return new BinData(3, base64); } function PYUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var base64 = HexToBase64(hex); return new BinData(3, base64); } BinData.prototype.toUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'UUID("' + uuid + '")'; } BinData.prototype.toJUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var msb = hex.substr(0, 16); var lsb = hex.substr(16, 16); msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2); lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2); hex = msb + lsb; var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'JUUID("' + uuid + '")'; } BinData.prototype.toCSUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2); var b = hex.substr(10, 2) + hex.substr(8, 2); var c = hex.substr(14, 2) + hex.substr(12, 2); var d = hex.substr(16, 16); hex = a + b + c + d; var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'CSUUID("' + uuid + '")'; } BinData.prototype.toPYUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'PYUUID("' + uuid + '")'; } BinData.prototype.toHexUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'HexData(' + this.subtype() + ', "' + uuid + '")'; } function TestUUIDHelperFunctions() { var s = "{00112233-4455-6677-8899-aabbccddeeff}"; var uuid = UUID(s); var juuid = JUUID(s); var csuuid = CSUUID(s); var pyuuid = PYUUID(s); print(uuid.toUUID()); print(juuid.toJUUID()); print(csuuid.toCSUUID()); print(pyuuid.toPYUUID()); print(uuid.toHexUUID()); print(juuid.toHexUUID()); print(csuuid.toHexUUID()); print(pyuuid.toHexUUID()); }
sragu/mongo-uuid
lib/uuidhelpers.js
JavaScript
mit
6,977
var assert = require('assert'); var RequestBuilder = require('../lib/rest-builder'); describe('REST Request Builder', function () { describe('Request templating', function () { var server = null; before(function (done) { var express = require('express'); var app = express(); app.configure(function () { app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); }); app.all('*', function (req, res, next) { res.setHeader('Content-Type', 'application/json'); var payload = { method: req.method, url: req.url, headers: req.headers, query: req.query, body: req.body }; res.json(200, payload); }); server = app.listen(app.get('port'), function (err, data) { // console.log('Server listening on ', app.get('port')); done(err, data); }); }); after(function(done) { server && server.close(done); }); it('should substitute the variables', function (done) { var builder = new RequestBuilder('GET', 'http://localhost:3000/{p}').query({x: '{x}', y: 2}); builder.invoke({p: 1, x: 'X'}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(body.query.x, 'X'); assert.equal(body.query.y, 2); done(err, body); }); }); it('should support default variables', function (done) { var builder = new RequestBuilder('GET', 'http://localhost:3000/{p=100}').query({x: '{x=ME}', y: 2}); builder.invoke({p: 1}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal('ME', body.query.x); assert.equal(2, body.query.y); done(err, body); }); }); it('should support typed variables', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{p=100}').query({x: '{x=100:number}', y: 2}) .body({a: '{a=1:number}', b: '{b=true:boolean}'}); builder.invoke({p: 1, a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal(100, body.query.x); assert.equal(2, body.query.y); assert.equal(100, body.body.a); assert.equal(false, body.body.b); done(err, body); }); }); it('should report missing required variables', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{!p}').query({x: '{x=100:number}', y: 2}) .body({a: '{^a:number}', b: '{!b=true:boolean}'}); try { builder.invoke({a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); done(err, body); }); assert.fail(); } catch(err) { // This is expected done(null, null); } }); it('should support required variables', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{!p}').query({x: '{x=100:number}', y: 2}) .body({a: '{^a:number}', b: '{!b=true:boolean}'}); builder.invoke({p: 1, a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal(100, body.query.x); assert.equal(2, body.query.y); assert.equal(100, body.body.a); assert.equal(false, body.body.b); done(err, body); }); }); it('should build an operation with the parameter names', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{p}').query({x: '{x}', y: 2}); var fn = builder.operation(['p', 'x']); fn(1, 'X', function (err, body, response) { assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal('X', body.query.x); assert.equal(2, body.query.y); // console.log(body); done(err, body); }); }); it('should build an operation with the parameter names as args', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{p}').query({x: '{x}', y: 2}); var fn = builder.operation('p', 'x'); fn(1, 'X', function (err, body, response) { assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal('X', body.query.x); assert.equal(2, body.query.y); // console.log(body); done(err, body); }); }); it('should build from a json doc', function (done) { var builder = new RequestBuilder(require('./request-template.json')); // console.log(builder.parse()); builder.invoke({p: 1, a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal(100, body.query.x); assert.equal(2, body.query.y); assert.equal(100, body.body.a); assert.equal(false, body.body.b); done(err, body); }); }); }); });
sunyardtc/git
node_modules/loopback-connector-rest/test/rest-builder.test.js
JavaScript
mit
8,351
using System.Xml; namespace Anycmd.Xacml.Policy.TargetItems { /// <summary> /// Represents a read-only Action element in the Policy document. This class is a specialization of TargetItem class /// which contains the information needed for all the items that can be part of the target. /// </summary> public class ActionElement : TargetItemBase { #region Constructor /// <summary> /// Creates a new instance of Action using the specified arguments. /// </summary> /// <param name="match">The target item match collection.</param> /// <param name="version">The version of the schema that was used to validate.</param> public ActionElement( TargetMatchReadWriteCollection match, XacmlVersion version ) : base( match, version ) { } /// <summary> /// Creates an instance of the Action item and calls the base constructor specifying the names of the nodes /// that defines this target item. /// </summary> /// <param name="reader">The XmlReader positioned at the Action node.</param> /// <param name="version">The version of the schema that was used to validate.</param> public ActionElement( XmlReader reader, XacmlVersion version ) : base( reader, Consts.Schema1.ActionElement.Action, Consts.Schema1.ActionElement.ActionMatch, version ) { } #endregion #region Protected Methods /// <summary> /// Overrided method that is called when the xxxMatch element is found in the target item definition. /// </summary> /// <param name="reader">The XmlReader positioned at the start of the Match element found.</param> /// <returns>The instance of the ActionMatch which is a class extending the abstract Match class</returns> protected override TargetMatchBaseReadWrite CreateMatch(XmlReader reader) { return new ActionMatchElement( reader, SchemaVersion ); } #endregion #region Public properties /// <summary> /// Whether the instance is a read only version. /// </summary> public override bool IsReadOnly { get{ return true; } } #endregion } }
anycmd/anycmd
src/Anycmd.Xacml/Policy/TargetItems/ActionElement.cs
C#
mit
2,034
using System; namespace libmapgen { [Serializable()] public class FlatHeightmap : IInitialMapGenerator { public int width { get; set; } public int height { get; set; } public FlatHeightmap (int width, int height) { this.width = width; this.height = height; } public MapArea generate () { return new MapArea (width, height); } } }
tmsbrg/libmapgen
libmapgen/FlatHeightmap.cs
C#
mit
362
<?php /** * Filesystem Access Object interface. * * PHP Version 5.3 * * @package Lunr\Gravity\Filesystem * @author Heinz Wiesinger <heinz@m2mobi.com> * @copyright 2013-2018, M2Mobi BV, Amsterdam, The Netherlands * @license http://lunr.nl/LICENSE MIT License */ namespace Lunr\Gravity\Filesystem; /** * Filesystem Access Object interface. */ interface FilesystemAccessObjectInterface { /** * Get a list of all non-dot directories in a given directory. * * @param string $directory Base directory * * @return array $contents List of directory in that directory */ public function get_list_of_directories($directory); /** * Get a list of all non-dot files in a given directory. * * @param string $directory Base directory * * @return array $contents List of files in that directory */ public function get_list_of_files($directory); /** * Get a listing of the contents of a given directory. * * @param string $directory Base directory * * @return array $contents List of contents of that directory */ public function get_directory_listing($directory); /** * Find a file in a given directory. * * @param string $needle Filename to look for * @param string $haystack Base directory to search in * * @return mixed $return Path of the file if found, * FALSE on failure */ public function find_matches($needle, $haystack); /** * Get the contents of a given file. * * @param string $file Filepath * * @return mixed $contents Contents of the given file as String on success, * FALSE on failure */ public function get_file_content($file); /** * Write contents into file. * * @param string $file Filepath * @param string $contents Contents to write * * @return mixed $return Written bytes as integer on success, * FALSE on failure */ public function put_file_content($file, $contents); /** * Recursively removes a directory and its contents. * * @param string $dir_path The directory path to be removed * * @return boolean TRUE when directory is removed and FALSE in a failure. */ public function rmdir($dir_path); /** * Turns the values of an array into csv and writes them in a given file. * * @param string $file The filepath to write the file * @param array $data An array with the data to be turned into csv * @param string $delimiter The delimiter for the csv (optional) * @param string $enclosure The enclosure for the csv (option) * * @return boolean TRUE when file is created and FALSE in failure. */ public function put_csv_file_content($file, $data, $delimiter = ',', $enclosure = '"'); /** * Creates a directory with the given name, if it does not exist. * * This method is a wrapper of the php mkdir. * * @param string $pathname The directory path/name * @param integer $mode The access mode (0755 by default) * @param boolean $recursive Allows the creation of nested directories specified in the pathname * * @return boolean TRUE when directory is created or FALSE in failure. */ public function mkdir($pathname, $mode = 0755, $recursive = FALSE); /** * Generate a temporary file and return the path. * * @param string|null $prefix The prefix to the temp file * * @return bool|string */ public function get_tmp_file($prefix = NULL); /** * Remove a file. * * @param string $file Filepath * * @return bool */ public function rm($file); } ?>
pprkut/lunr
src/Lunr/Gravity/Filesystem/FilesystemAccessObjectInterface.php
PHP
mit
3,852
using UnityEngine; using System; public struct SpriteInfo { public string SpriteSheetName; public Vector2 SpritePosition; public Vector3 SpriteSize; }
NickABoen/Dungeon-Explorer
Dungeon Explorer/Assets/Scripts/Structures/SpriteInfo.cs
C#
mit
156
using System; namespace Oragon.Architecture.MessageQueuing { public interface IQueueConsumerWorker : IDisposable { bool ModelIsClosed { get; } void DoConsume(); void Ack(ulong deliveryTag); void Nack(ulong deliveryTag, bool requeue = false); } }
luizcarlosfaria/Oragon.Architecture
[source]/Oragon.Architecture.MQ/MessageQueuing/IQueueConsumerWorker.cs
C#
mit
263
<?php class Input { public static $is_parsed = false; public static $params = []; /** * Парсит и сохраняет все параметры в переменной self::$params * * @access protected * @return $this */ protected static function parse() { if (filter_input(INPUT_SERVER, 'argc')) { $argv = filter_input(INPUT_SERVER, 'argv'); array_shift($argv); // file static::$params['ACTION'] = array_shift($argv); static::$params += $argv; } elseif ((0 === strpos(filter_input(INPUT_SERVER, 'CONTENT_TYPE'), 'application/json'))) { static::$params = (array) filter_input_array(INPUT_GET) + (array) json_decode(file_get_contents('php://input'), true); } else { static::$params = (array) filter_input_array(INPUT_POST) + (array) filter_input_array(INPUT_GET); } static::$is_parsed = true; } public static function set(string $key, $value) { static::$is_parsed || static::parse(); static::$params[$key] = $value; } /** * Получение переменной запроса * * <code> * $test = Input::get('test'); * * $params = Input::get(['test:int=1']); * </code> */ public static function get(...$args) { static::$is_parsed || static::parse(); if (!isset($args[0])) { return static::$params; } // String key? if (is_string($args[0])) { return isset(static::$params[$args[0]]) ? static::$params[$args[0]] : (isset($args[1]) ? $args[1] : null); } if (is_array($args[0])) { return static::extractTypified($args[0], function ($key, $default = null) { return static::get($key, $default); }); } // Exctract typifie var by mnemonic rules as array trigger_error('Error while fetch key from input'); } /** * Извлекает и типизирует параметры из массива args с помощью функции $fetcher, которая * принимает на вход ключ из массива args и значение по умолчанию, если его там нет * * @param array $args * @param Closure $fetcher ($key, $default) */ public static function extractTypified(array $args, Closure $fetcher) { $params = []; foreach ($args as $arg) { preg_match('#^([a-zA-Z0-9_]+)(?:\:([a-z]+))?(?:\=(.+))?$#', $arg, $m); $params[$m[1]] = $fetcher($m[1], isset($m[3]) ? $m[3] : ''); // Нужно ли типизировать if (isset($m[2])) { typify($params[$m[1]], $m[2]); } } return $params; } }
dmitrykuzmenkov/kisscore
core/Input.php
PHP
mit
2,636
#include "pch.hpp" #include "default_log.hpp" #include "service_log.hpp" #include "service_helpers.hpp" namespace be { /////////////////////////////////////////////////////////////////////////////// bool default_log_available() { return check_service<Log>(); } /////////////////////////////////////////////////////////////////////////////// Log& default_log() { return service<Log>(); } } // be
magicmoremagic/bengine-core
src/default_log.cpp
C++
mit
405
// // VariableValueReference.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2009 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.Debugging.Evaluation; using Mono.Debugging.Client; using Mono.Debugger.Soft; namespace Mono.Debugging.Soft { public class VariableValueReference : ValueReference { readonly LocalVariable variable; LocalVariableBatch batch; Value value; string name; public VariableValueReference (EvaluationContext ctx, string name, LocalVariable variable, LocalVariableBatch batch) : base (ctx) { this.variable = variable; this.batch = batch; this.name = name; } public VariableValueReference (EvaluationContext ctx, string name, LocalVariable variable, Value value) : base (ctx) { this.variable = variable; this.value = value; this.name = name; } public VariableValueReference (EvaluationContext ctx, string name, LocalVariable variable) : base (ctx) { this.variable = variable; this.name = name; } public override ObjectValueFlags Flags { get { return ObjectValueFlags.Variable; } } public override string Name { get { return name; } } public override object Type { get { return variable.Type; } } Value NormalizeValue (EvaluationContext ctx, Value value) { if (variable.Type.IsPointer) { long addr = (long) ((PrimitiveValue) value).Value; return new PointerValue (value.VirtualMachine, variable.Type, addr); } return ctx.Adapter.IsNull (ctx, value) ? null : value; } public override object Value { get { var ctx = (SoftEvaluationContext) Context; try { if (value == null) value = batch != null ? batch.GetValue (variable) : ctx.Frame.GetValue (variable); return NormalizeValue (ctx, value); } catch (AbsentInformationException) { throw new EvaluatorException ("Value not available"); } catch (ArgumentException ex) { throw new EvaluatorException (ex.Message); } } set { ((SoftEvaluationContext) Context).Frame.SetValue (variable, (Value) value); this.value = (Value) value; } } } }
joj/debugger-libs
Mono.Debugging.Soft/VariableValueReference.cs
C#
mit
3,237
<?php return array( /* |-------------------------------------------------------------------------- | Module Language Lines |-------------------------------------------------------------------------- | | This file keeps the language lines of the related module. | */ 'receiver' => 'Destinataire', 'message_sent' => 'Votre message a été envoyé.', 're' => 'Re: ', 'system_info' => 'Ce message a été créé automatiquement.', );
Contentify/Contentify
app/Modules/Messages/Resources/Lang/fr/main.php
PHP
mit
505
/** * Copyright 2015 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ require( [ 'laxar', 'laxar-application/var/flows/embed/dependencies', 'json!laxar-application/var/flows/embed/resources.json' ], function( ax, mainDependencies, mainResources ) { 'use strict'; window.laxar.fileListings = { application: mainResources, bower_components: mainResources, includes: mainResources }; ax.bootstrap( mainDependencies ); } );
jpommerening/release-station
init-embed.js
JavaScript
mit
490
=begin #The Plaid API #The Plaid REST API. Please see https://plaid.com/docs/api for more details. The version of the OpenAPI document: 2020-09-14_1.79.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.1.0 =end require 'date' require 'time' module Plaid # An object containing liability accounts class LiabilitiesObject # The credit accounts returned. attr_accessor :credit # The mortgage accounts returned. attr_accessor :mortgage # The student loan accounts returned. attr_accessor :student # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'credit' => :'credit', :'mortgage' => :'mortgage', :'student' => :'student' } end # Returns all the JSON keys this model knows about def self.acceptable_attributes attribute_map.values end # Attribute type mapping. def self.openapi_types { :'credit' => :'Array<CreditCardLiability>', :'mortgage' => :'Array<MortgageLiability>', :'student' => :'Array<StudentLoan>' } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ :'credit', :'mortgage', :'student' ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::LiabilitiesObject` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::LiabilitiesObject`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'credit') if (value = attributes[:'credit']).is_a?(Array) self.credit = value end end if attributes.key?(:'mortgage') if (value = attributes[:'mortgage']).is_a?(Array) self.mortgage = value end end if attributes.key?(:'student') if (value = attributes[:'student']).is_a?(Array) self.student = value end end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && credit == o.credit && mortgage == o.mortgage && student == o.student end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [credit, mortgage, student].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) elsif type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :Time Time.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model # models (e.g. Pet) or oneOf klass = Plaid.const_get(type) klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
plaid/plaid-ruby
lib/plaid/models/liabilities_object.rb
Ruby
mit
7,316