code stringlengths 4 991k | repo_name stringlengths 6 116 | path stringlengths 4 249 | language stringclasses 30 values | license stringclasses 15 values | size int64 4 991k | input_ids listlengths 502 502 | token_type_ids listlengths 502 502 | attention_mask listlengths 502 502 | labels listlengths 502 502 |
|---|---|---|---|---|---|---|---|---|---|
#!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier',
'msn',
'newyorktimes',
'stackoverflow',
'wikipedia',
'es6'
];
fileNames = fileNames.sort().reverse();
var table = new Table({
head: ['File', 'Before', 'After', 'Savings', 'Time'],
colWidths: [20, 25, 25, 20, 20]
});
function toKb(size) {
return (size / 1024).toFixed(2);
}
function redSize(size) {
return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function greenSize(size) {
return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function blueSavings(oldSize, newSize) {
var savingsPercent = (1 - newSize / oldSize) * 100;
var savings = (oldSize - newSize) / 1024;
return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)');
}
function blueTime(time) {
return chalk.cyan.bold(time) + chalk.white(' ms');
}
function test(fileName, done) {
if (!fileName) {
console.log('\n' + table.toString());
return;
}
console.log('Processing...', fileName);
var filePath = path.join('benchmarks/', fileName + '.html');
var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html');
var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz');
var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz');
var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath;
// Open and read the size of the original input
fs.stat(filePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + filePath);
}
var originalSize = stats.size;
exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () {
// Open and read the size of the gzipped original
fs.stat(gzFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + gzFilePath);
}
var gzOriginalSize = stats.size;
// Begin timing after gzipped fixtures have been created
var startTime = new Date();
exec('node ' + command, function () {
// Open and read the size of the minified output
fs.stat(minifiedFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + minifiedFilePath);
}
var minifiedSize = stats.size;
var minifiedTime = new Date() - startTime;
// Gzip the minified output
exec('gzip --keep --force --best --stdout ' + minifiedFilePath + ' > ' + gzMinifiedFilePath, function () {
// Open and read the size of the minified+gzipped output
fs.stat(gzMinifiedFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + gzMinifiedFilePath);
}
var gzMinifiedSize = stats.size;
var gzMinifiedTime = new Date() - startTime;
table.push([
[fileName, '+ gzipped'].join('\n'),
[redSize(originalSize), redSize(gzOriginalSize)].join('\n'),
[greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'),
[blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'),
[blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n')
]);
done();
});
});
});
});
});
});
});
}
(function run() {
test(fileNames.pop(), run);
})();
| psychoss/html-minifier | benchmark.js | JavaScript | mit | 3,946 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
13045,
1005,
2224,
9384,
1005,
1025,
13075,
1042,
2015,
1027,
5478,
1006,
1005,
1042,
2015,
1005,
1007,
1010,
4130,
1027,
5478,
1006,
1005,
4130,
1005,
1007,
1010,
4654,
85... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright 2017, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const config = require('./config');
// TODO: Load the trace-agent and start it
// Trace must be started before any other code in the
// application.
require('@google-cloud/trace-agent').start({
projectId: config.get('GCLOUD_PROJECT')
});
// END TODO
require('@google-cloud/debug-agent').start({
allowExpressions: true,
projectId: config.get('GCLOUD_PROJECT')
});
const path = require('path');
const express = require('express');
const scores = require('./gcp/spanner');
const {ErrorReporting} = require('@google-cloud/error-reporting');
const errorReporting = new ErrorReporting({
projectId: config.get('GCLOUD_PROJECT')
});
const app = express();
// Static files
app.use(express.static('frontend/public/'));
app.disable('etag');
app.set('views', path.join(__dirname, 'web-app/views'));
app.set('view engine', 'pug');
app.set('trust proxy', true);
app.set('json spaces', 2);
// Questions
app.use('/questions', require('./web-app/questions'));
// Quizzes API
app.use('/api/quizzes', require('./api'));
// Display the home page
app.get('/', (req, res) => {
res.render('home.pug');
});
// Display the Leaderboard
app.get('/leaderboard', (req, res) => {
scores.getLeaderboard().then(scores => {
res.render('leaderboard.pug', {
scores
});
});
});
// Use Stackdriver Error Reporting with Express
app.use(errorReporting.express);
// Basic 404 handler
app.use((req, res) => {
res.status(404).send('Not Found');
});
// Basic error handler
app.use((err, req, res, next) => {
/* jshint unused:false */
console.error(err);
// If our routes specified a specific response, then send that. Otherwise,
// send a generic message so as not to leak anything.
res.status(500).send(err.response || 'Something broke!');
});
if (module === require.main) {
// Start the server
const server = app.listen(config.get('PORT'), () => {
const port = server.address().port;
console.log(`App listening on port ${port}`);
});
}
module.exports = app;
| GoogleCloudPlatform/training-data-analyst | courses/developingapps/v1.3/nodejs/stackdriver-trace-monitoring/end/frontend/app.js | JavaScript | apache-2.0 | 2,594 | [
30522,
1013,
1013,
9385,
2418,
1010,
8224,
1010,
4297,
1012,
1013,
1013,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1013,
1013,
2017,
2089,
2025,
2224,
2023,
5371,
3272,
1999,
12... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "changefileurlcommand.h"
namespace QmlDesigner {
ChangeFileUrlCommand::ChangeFileUrlCommand()
{
}
ChangeFileUrlCommand::ChangeFileUrlCommand(const QUrl &fileUrl)
: m_fileUrl(fileUrl)
{
}
QUrl ChangeFileUrlCommand::fileUrl() const
{
return m_fileUrl;
}
QDataStream &operator<<(QDataStream &out, const ChangeFileUrlCommand &command)
{
out << command.fileUrl();
return out;
}
QDataStream &operator>>(QDataStream &in, ChangeFileUrlCommand &command)
{
in >> command.m_fileUrl;
return in;
}
} // namespace QmlDesigner
| yinyunqiao/qtcreator | src/plugins/qmldesigner/designercore/instances/changefileurlcommand.cpp | C++ | lgpl-2.1 | 1,932 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require 'package'
class Gdb < Package
description 'GDB, the GNU Project debugger, allows you to see what is going on \'inside\' another program while it executes -- or what another program was doing at the moment it crashed.'
homepage 'https://www.gnu.org/software/gdb/'
version '8.0'
source_url 'http://ftp.gnu.org/gnu/gdb/gdb-8.0.tar.xz'
source_sha256 'f6a24ffe4917e67014ef9273eb8b547cb96a13e5ca74895b06d683b391f3f4ee'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/gdb-8.0-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/gdb-8.0-chromeos-armv7l.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/gdb-8.0-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/gdb-8.0-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: '8612b39c8041b7ca574f0689f74a733c0ed168227495bcbc7ef2588dde5e314b',
armv7l: '8612b39c8041b7ca574f0689f74a733c0ed168227495bcbc7ef2588dde5e314b',
i686: 'fcaac403d13015720d0ef469545041a2bcff0b4d0f3bdba48380acfd8ac17385',
x86_64: 'f58b46880dd963748d604bca3cb9db9e108c64142e45d7df42b389acc0a085f2',
})
depends_on "buildessential"
depends_on "ncurses"
depends_on "texinfo"
def self.build
system "./configure", "--prefix=/usr/local"
system "make"
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end
| jam7/chromebrew | packages/gdb.rb | Ruby | gpl-3.0 | 1,422 | [
30522,
5478,
1005,
7427,
1005,
2465,
1043,
18939,
1026,
7427,
6412,
1005,
1043,
18939,
1010,
1996,
27004,
2622,
2139,
8569,
13327,
1010,
4473,
2017,
2000,
2156,
2054,
2003,
2183,
2006,
1032,
1005,
2503,
1032,
1005,
2178,
2565,
2096,
2009,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#ifndef _ZANavFilterArray_h
#define _ZANavFilterArray_h
#if _MSC_VER >= 1000
#pragma once
#endif
#pragma warning(push)
#pragma warning(disable : 4275)
class ANAV_PORT CNavFilterArray : public CNavArray<CNavFilter> {
public:
CNavFilterArray ();
virtual ~CNavFilterArray ();
public:
void SetFrom (LPCTSTR str, BOOL bUseFullDescrition = FALSE);
int Find (LPCTSTR str);
int FindExact (LPCTSTR str);
};
#pragma warning(pop)
#endif
| kevinzhwl/ZWCAD.DK | ZRXSDK/inc/zanavfilterarray.h | C | gpl-2.0 | 532 | [
30522,
1001,
2065,
13629,
2546,
1035,
23564,
2532,
2615,
8873,
21928,
2906,
9447,
1035,
1044,
1001,
9375,
1035,
23564,
2532,
2615,
8873,
21928,
2906,
9447,
1035,
1044,
1001,
2065,
1035,
23794,
1035,
2310,
2099,
1028,
1027,
6694,
1001,
10975... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
function SignupController()
{
// redirect to homepage when cancel button is clicked //
$('#account-form-btn1').click(function(){ window.location.href = '/#section-3';});
// redirect to homepage on new account creation, add short delay so user can read alert window //
$('.modal-alert #ok').click(function(){ setTimeout(function(){window.location.href = '/#';}, 300)});
} | lucianoportela/hiverbook | app/public/js/controllers/signupController.js | JavaScript | mit | 374 | [
30522,
3853,
3696,
6279,
8663,
13181,
10820,
1006,
1007,
1063,
1013,
1013,
2417,
7442,
6593,
2000,
2188,
13704,
2043,
17542,
6462,
2003,
13886,
1013,
1013,
1002,
1006,
1005,
1001,
4070,
1011,
2433,
1011,
18411,
2078,
2487,
1005,
1007,
1012,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Add a new language stack
Each language stack has its own Docker image used to execute code inside
a Docker container.
These images can be found inside the `dockerfiles` directory:
```
dockerfiles
│
├─── ruby.docker
│
└─── golang.docker
|
└─── ruby
| |
| └─── sync.rb
|
└─── shared
|
└─── run.sh
```
Each image has:
- A `Dockerfile` following the naming convention:
$LANGUAGE_CODE.docker
e.g.
php.docker
- A shell script `run.sh` (in `shared` directory).
Images are following this naming convention:
$REPOSITORY/exec-$LANGUAGE
Images are built has an executable Docker image. This allow us to do:
$ docker run grounds/exec-ruby "puts 42"
42
## run.sh
This script writes into a file the content of the first argument into a file
specified by environment variable `FILE`, compile with `COMPILE`command if specified
and then execute the command specified by environment variable `EXEC`.
e.g.
FILE='prog.rb' \
EXEC='ruby prog.rb' ./run.sh '<some ruby code>'
FILE='prog.cpp' \
COMPILE='gcc -o prog prog.c' \
EXEC='./prog' ./run.sh '<some c code>'
## Create an image
Creating an image for a new language is really trivial.
Take a look at this example for the C language:
Add a `Dockerfile` inside images directory:
touch dockerfiles/c.docker
### Inside the Dockerfile:
Checkout first [here](https://github.com/docker-library).
If there is an official image for the language stack you are trying to add,
just inherit from the latest tag of the official image and skip to step 4:
FROM python:latest
If there is no official image for this language stack:
1. Base the image on the official ubuntu image:
FROM ubuntu:14.04
2. Add yourself as a maintainer of this image:
MAINTAINER Adrien Folie <folie.adrien@gmail.com>
3. Update ubuntu package manager:
RUN apt-get update -qq
>Use apt-get update quiet mode level 2 (with `--qq`)
4. Install dependencies required to compile C code (e.g `gcc`)
RUN apt-get -qy install \
build-essential \
gcc
5. Specify file format:
ENV FILE prog.c
6. Specify compiler/interpreter command:
* If you need to compile the program:
ENV COMPILE gcc -o prog $FILE
* Run the interpreter or the program:
ENV EXEC ./prog
7. Set development directory in env:
ENV DEV /home/dev
8. Copy the shared files inside the development directory:
COPY shared/* $DEV/
9. Add a user and give him access to the development directory:
RUN useradd dev
RUN chown -R dev: $DEV
10. Switch to this user:
USER dev
11. Set working directory:
WORKDIR $DEV
12. Configure this image as an executable:
ENTRYPOINT ["./run.sh"]
When you run a Docker container with this image:
- The default `pwd` of this container will be `/home/dev`.
- The user of this container will be `dev`
- This container will run `run.sh` and takes as parameter a string whith arbitrary code inside.
**N.B. If you have some custom files that should be in the image:**
1. Create a directory for this image:
mkdir dockerfiles/ruby
2. Add your files inside this directory.
3. Copy this directory inside the image:
e.g. For ruby, add in `dockerfiles/ruby.docker`:
COPY ruby /custom
### Build this image:
$ LANGUAGE="c" rake build
### Tests
To add this language to the test suite:
1. Create a directory with the language code inside `examples/code`
e.g. For PHP:
mkdir examples/code/php
2. In this directory add two files with the appropriate file extension:
* A code example who writes `"Hello world\n"` on `stdout`.
* A code example who writes `"Hello stderr\n"` on `stderr`.
You can find great examples on
[Rosetta code](http://rosettacode.org/wiki/Hello_world).
3. Run the examples test suite
rake test
4. If you want to test only a specific language
LANGUAGE="ruby" rake test
**Thanks for your contribution!**
| grounds/grounds-images | docs/NEW_LANGUAGE.md | Markdown | mit | 4,108 | [
30522,
1001,
5587,
1037,
2047,
2653,
9991,
2169,
2653,
9991,
2038,
2049,
2219,
8946,
2121,
3746,
2109,
2000,
15389,
3642,
2503,
1037,
8946,
2121,
11661,
1012,
2122,
4871,
2064,
2022,
2179,
2503,
1996,
1036,
8946,
2121,
8873,
4244,
1036,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
//
// Data-forge enumerator for iterating a standard JavaScript array.
//
var TakeIterator = function (iterator, takeAmount) {
var self = this;
self._iterator = iterator;
self._takeAmount = takeAmount;
};
module.exports = TakeIterator;
TakeIterator.prototype.moveNext = function () {
var self = this;
if (--self._takeAmount >= 0) {
return self._iterator.moveNext();
}
return false;
};
TakeIterator.prototype.getCurrent = function () {
var self = this;
return self._iterator.getCurrent();
};
| data-forge/data-forge-js | src/iterators/take.js | JavaScript | mit | 524 | [
30522,
1005,
2224,
9384,
1005,
1025,
1013,
1013,
1013,
1013,
2951,
1011,
15681,
4372,
17897,
16259,
2005,
2009,
6906,
3436,
1037,
3115,
9262,
22483,
9140,
1012,
1013,
1013,
13075,
2202,
21646,
8844,
1027,
3853,
1006,
2009,
6906,
4263,
1010,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package math;
import util.IReplicable;
public class Vector3 implements IReplicable<Vector3> {
private static final float MIN_TOLERANCE = (float) 1E-9;
public float x;
public float y;
public float z;
public static Vector3 of(float x, float y, float z) {
Vector3 vector = new Vector3();
vector.x = x;
vector.y = y;
vector.z = z;
return vector;
}
public static Vector3 getUnitX() {
Vector3 vector = new Vector3();
vector.x = 1;
return vector;
}
public static Vector3 getUnitY() {
Vector3 vector = new Vector3();
vector.y = 1;
return vector;
}
public static Vector3 getUnitZ() {
Vector3 vector = new Vector3();
vector.z = 1;
return vector;
}
public static Vector3 getUnit() {
Vector3 vector = new Vector3();
vector.x = 1;
vector.y = 1;
vector.z = 1;
return vector;
}
public boolean isUnitX() {
return (x == 1) && (y == 0) && (z == 0);
}
public boolean isUnitY() {
return (x == 0) && (y == 1) && (z == 0);
}
public boolean isUnitZ() {
return (x == 0) && (y == 0) && (z == 1);
}
public boolean isUnit() {
return (x == 1) && (y == 1) && (z == 1);
}
public float lengthSquared() {
return (x * x) + (y * y) + (z * z);
}
public float length() {
return (float) Math.sqrt(lengthSquared());
}
public float inverseLength() {
return 1f / length();
}
public static Vector3 add(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
add(result, a, b);
return result;
}
public static void add(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x + b.x;
result.y = a.y + b.y;
result.z = a.z + b.z;
}
public static Vector3 subtract(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
subtract(result, a, b);
return result;
}
public static void subtract(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x - b.x;
result.y = a.y - b.y;
result.z = a.z - b.z;
}
public static Vector3 multiply(Vector3 a, float scalar) {
Vector3 result = new Vector3();
multiply(result, a, scalar);
return result;
}
public static void multiply(Vector3 result, Vector3 a, float scalar) {
result.x = a.x * scalar;
result.y = a.y * scalar;
result.z = a.z * scalar;
}
public static Vector3 divide(Vector3 a, float scalar) {
Vector3 result = new Vector3();
divide(result, a, scalar);
return result;
}
public static void divide(Vector3 result, Vector3 a, float scalar) {
float multiplier = (scalar <= MIN_TOLERANCE)
? 0
: 1f / scalar;
multiply(result, a, multiplier);
}
public static float dot(Vector3 a, Vector3 b) {
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
public static Vector3 cross(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
cross(result, a, b);
return result;
}
public static void cross(Vector3 result, Vector3 a, Vector3 b) {
float x = (a.y * b.z) - (a.z * b.y);
float y = (a.z * b.x) - (a.x * b.z);
float z = (a.x * b.y) - (a.y * b.x);
result.x = x;
result.y = y;
result.z = z;
}
public static Vector3 negate(Vector3 a) {
Vector3 result = new Vector3();
negate(result, a);
return result;
}
public static void negate(Vector3 result, Vector3 a) {
result.x = -a.x;
result.y = -a.y;
result.z = -a.z;
}
public static Vector3 normalise(Vector3 a) {
Vector3 result = new Vector3();
normalise(result, a);
return result;
}
public static void normalise(Vector3 result, Vector3 a) {
float sumSq = (a.x * a.x) + (a.y * a.y) + (a.z * a.z);
if (sumSq <= MIN_TOLERANCE) {
result.x = 0;
result.y = 1;
result.z = 0;
} else {
double sum = Math.sqrt(sumSq);
multiply(result, a, (float) (1.0 / sum));
}
}
@Override
public Vector3 createBlank() {
return new Vector3();
}
@Override
public void copyFrom(Vector3 master) {
this.x = master.x;
this.y = master.y;
this.z = master.z;
}
}
| NathanJAdams/verJ | src/math/Vector3.java | Java | mit | 4,539 | [
30522,
7427,
8785,
1025,
12324,
21183,
30524,
2270,
14257,
1062,
1025,
2270,
10763,
9207,
2509,
1997,
1006,
14257,
1060,
1010,
14257,
1061,
1010,
14257,
1062,
1007,
1063,
9207,
2509,
9207,
1027,
2047,
9207,
2509,
1006,
1007,
1025,
9207,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- Content Stylesheet for Site -->
<!-- start the processing -->
<!-- ====================================================================== -->
<!-- GENERATED FILE, DO NOT EDIT, EDIT THE XML FILE IN xdocs INSTEAD! -->
<!-- Main Page Section -->
<!-- ====================================================================== -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<meta name="author" value="Ceki Gülcü">
<meta name="email" value="not@disclosed">
<link href="./css/site.css" rel="stylesheet" type="text/css"/>
<title>Log4j project - Project history</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#525D76">
<!-- START Header table -->
<table class="banner" border="0">
<tr>
<td valign="top">
<a href="http://logging.apache.org/">
<img src="http://logging.apache.org/images/ls-logo.jpg" border="0"/>
</a>
<td align="right">
<a href="http://logging.apache.org/log4j/docs/">
<img src="./images/logo.jpg" alt="The log4j project" border="0"/>
</a>
</td>
</tr>
</table>
<!-- END Header table -->
<div class="centercol">
<hr noshade="" size="1"/>
<h1>Project history</strong></h1>
<p>The <a href="HISTORY"><b>project history</b></a> gives a
brief summary of changes and additions. Users frequently
report bugs that are solved in newer versions of log4j. Please
have a look at the history file before asking for help.
</p>
<p>The project's official URL is <a href="http://logging.apache.org/log4j">http://logging.apache.org/log4j</a>.
</p>
<p>Many thanks to all the log4j users who keep sending us input
and sometimes even praise for our collective effort. The first
ancestor of log4j was written for the E.U. sponsored <a href="http://www.semper.org">SEMPER</a> project. N. Asokan,
Ceki Gülcü and Michael Steiner came up with the idea
of hierarchical loggers back in 1996. Their idea is still at the
heart of log4j. The package was considerably improved over the
years at the <a href="http://www.zurich.ibm.com">IBM Zurich
Research Laboratory</a>. However, log4j is no longer associated
nor supported by IBM.
</p>
<p>Special thanks to M. Niksch from ZRL for his assistance on
many large and small matters. The Apache members, Pier
Fumagalli and Sam Ruby in particular, have been extremely
helpful in easing the move to Apache.
</p>
<p>The log4j logo was designed and kindly donated by Cyberlab SA of Switzerland.
</p>
<hr/>
<!-- FOOTER -->
<div align="center"><font color="#525D76" size="-1"><em>
Copyright © 1999-2006, Apache Software Foundation.<br />
Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.
</em></font></div>
<!-- END main table -->
<!-- LEFT SIDE NAVIGATION -->
<!-- ============================================================ -->
<div class="leftcol">
<div class="menu_header">Log4j Project</div>
<div class="menu_item"> <a href="./index.html">Introduction</a>
</div>
<div class="menu_item"> <a href="./download.html">Download</a>
</div>
<div class="menu_item"> <a href="./documentation.html">Documentation</a>
</div>
<div class="menu_item"> <a href="./plan.html">Roadmap</a>
</div>
<div class="menu_item"> <a href="http://wiki.apache.org/logging-log4j/Log4JProjectPages">Wiki</a>
</div>
<div class="menu_item"> <a href="./contactUs.html">Contact us</a>
</div>
<div class="menu_item"> <a href="./contributors.html">Contributors</a>
</div>
<div class="menu_item"> <a href="./history.html">History</a>
</div>
<div class="menu_header">Logging Services</div>
<div class="menu_item"> <a href="http://logging.apache.org/">Home page</a>
</div>
<div class="menu_item"> <a href="http://logging.apache.org/site/news.html">News</a>
</div>
<div class="menu_item"> <a href="http://logging.apache.org/site/mission-statement.html">Mission</a>
</div>
<div class="menu_item"> <a href="http://logging.apache.org/site/bylaws.html">Guidelines</a>
</div>
<div class="menu_header">Translations</div>
<div class="menu_item"> <a href="http://jakarta.apache-korea.org/log4j/index.html">Korean</a>
</div>
<div class="menu_item"> <a href="http://www.ingrid.org/jajakarta/log4j/">Japanese</a>
</div>
</div>
</body>
</html>
<!-- end the processing -->
| nologic/nabs | client/trunk/shared/libraries/logging-log4j-1.2.14/docs/history.html | HTML | gpl-2.0 | 5,840 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Created by PhpStorm.
* User: Niels
* Date: 18/10/2014
* Time: 18:00
*/
namespace Repositories;
use Utilities\Utilities;
/**
* The repository contains all methods for interacting with the database for the TalkTag model
*
* Class TalkTagRepository
* @package Repositories
*/
class TalkTagRepository {
/**
* @return array Returns all talktags
*/
public static function getTalkTags()
{
$sql_query = "SELECT * FROM talk_tag";
$con=Utilities::getConnection();
$stmt = $con->query($sql_query);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* @param $talkId int The talkid of the TalkTag
* @param $tagId int The tagid of the TalkTag
* @return bool Returns true if successful
*/
public static function insertTalkTag($talkId, $tagId)
{
try {
$sql_query = "INSERT INTO talk_tag (talk_id, tag_id) VALUES (:talk_id,:tag_id);";
$con = Utilities::getConnection();
$stmt = $con->prepare($sql_query);
return $stmt->execute(array(':talk_id' => $talkId, ':tag_id' => $tagId));
}catch (\Exception $ex){
return false;
}
}
} | SNiels/Multi-Mania-app | backend/Repositories/TalkTagRepository.php | PHP | mit | 1,214 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
2580,
2011,
25718,
19718,
1012,
1008,
5310,
1024,
9152,
9050,
1008,
3058,
1024,
2324,
1013,
2184,
1013,
2297,
1008,
2051,
1024,
2324,
1024,
4002,
1008,
1013,
3415,
15327,
16360,
20049,
29469... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.coact.kochzap.book;
/**
* The underlying data for a SBC result.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
final class SearchBookContentsResult {
private static String query = null;
private final String pageId;
private final String pageNumber;
private final String snippet;
private final boolean validSnippet;
SearchBookContentsResult(String pageId,
String pageNumber,
String snippet,
boolean validSnippet) {
this.pageId = pageId;
this.pageNumber = pageNumber;
this.snippet = snippet;
this.validSnippet = validSnippet;
}
public static void setQuery(String query) {
SearchBookContentsResult.query = query;
}
public String getPageId() {
return pageId;
}
public String getPageNumber() {
return pageNumber;
}
public String getSnippet() {
return snippet;
}
public boolean getValidSnippet() {
return validSnippet;
}
public static String getQuery() {
return query;
}
}
| DavidLDawes/zxing | android/app/src/main/java/com/coact/kochzap/book/SearchBookContentsResult.java | Java | apache-2.0 | 1,667 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2263,
1062,
19612,
6048,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2025,
2224,
2023,
5371,
3272,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
function(doc) {
if(doc.tags.length > 0) {
for(var idx in doc.tags) {
emit(doc.tags[idx], null);
}
}
} | Arcticwolf/Ektorp | org.ektorp/src/test/resources/org/ektorp/support/map.js | JavaScript | apache-2.0 | 119 | [
30522,
3853,
1006,
9986,
1007,
1063,
2065,
1006,
9986,
1012,
22073,
1012,
3091,
1028,
1014,
1007,
1063,
2005,
1006,
13075,
8909,
2595,
1999,
9986,
1012,
22073,
1007,
1063,
12495,
2102,
1006,
9986,
1012,
22073,
1031,
8909,
2595,
1033,
1010,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
@charset 'UTF-8';
@font-face {
font-family: 'LigatureSymbols';
src: url('LigatureSymbols-2.07.eot');
src: url('LigatureSymbols-2.07.eot?#iefix') format('embedded-opentype'),
url('LigatureSymbols-2.07.woff') format('woff'),
url('LigatureSymbols-2.07.ttf') format('truetype'),
url('LigatureSymbols-2.07.svg#LigatureSymbols') format('svg');
font-weight: normal;
font-style: normal;
}
.lsf {
font-family: 'LigatureSymbols';
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
-webkit-font-feature-settings: "liga" 1, "dlig" 1;
-moz-font-feature-settings: "liga=1, dlig=1";
-ms-font-feature-settings: "liga" 1, "dlig" 1;
-o-font-feature-settings: "liga" 1, "dlig" 1;
font-feature-settings: "liga" 1, "dlig" 1;
}
.lsf-icon:before {
content:attr(title);
margin-right:0.3em;
font-size:130%;
font-family: 'LigatureSymbols';
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
-webkit-font-feature-settings: "liga" 1, "dlig" 1;
-moz-font-feature-settings: "liga=1, dlig=1";
-ms-font-feature-settings: "liga" 1, "dlig" 1;
-o-font-feature-settings: "liga" 1, "dlig" 1;
font-feature-settings: "liga" 1, "dlig" 1;
}
/* RESET */
html, body,
div,
ul, ol, li,
dl, dt, dd, td, th,
h1, h2, h3, h4, h5, h6,
p, pre, blockquote, fieldset,
form, input, button, textarea {
margin: 0;
padding: 0;
}
h1, h2, h3, h4, h5, h6,
pre, code, address, caption, cite, code,
em, strong, th {
font-size: 1.0em;
font-weight: normal;
font-style: normal;
}
ul, ol, li {
list-style: none;
}
fieldset, img {
border: none;
}
img {
-ms-interpolation-mode: bicubic;
}
caption, th {
text-align: left;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
input,textarea,select {
font-family: inherit;
font-size: inherit;
font-weight: inherit;
}
input,textarea,select {
*font-size: 100%;
}
button {
background-color: transparent;
text-decoration: none;
}
label {
cursor: pointer;
}
/* IEPNGFIX */
img { behavior: url(lib/iepngfix.htc); }
.main-image {
position:absolute;
top:-1000px;
width:400px;
}
/* ELEMENT */
body {
clear: both;
background-color: #ffffff;
text-align: center;
color: #333;
font-size: 16px;
font-weight: normal;
font-style: normal;
line-height: 1.5;
font-family :
Meiryo,
'メイリオ',
'Lucida Grande',
Verdana,
'Hiragino Kaku Gothic Pro',
'ヒラギノ角ゴ Pro W3',
'MS Pゴシック',
'MS P Gothic',
sans-serif;
}
a {
color: #006DBE;
font-weight: normal;
font-style: normal;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
html{
font-size:100%;
-webkit-text-size-adjust:100%;
-ms-text-size-adjust:100%;
-webkit-font-smoothing:antialiased;
text-align:center;
}
#body {
width:900px;
margin:0 auto;
}
#copyright {
margin:60px 0 20px;
text-align:center;
font-size:14px;
}
#copyright,
#copyright a {
color:#ccc;
}
h1 {
margin:60px 0 0px;
font-size:48px;
}
h2 {
clear:both;
padding:60px 7px 2px;
margin-bottom:30px;
border-bottom:1px solid #ccc;
text-align:left;
font-size:20px;
font-weight:bold;
}
p {
margin:10px 0;
color:#999;
text-align:left;
}
.lsf-input {
margin:60px 0 40px;
font-size:48px;
text-align:center;
}
.lsf-input input {
width:860px;
padding:10px 20px;
border:1px solid #ccc;
-webkit-border-radius:5px;
-moz-border-radius:5px;
-ms-border-radius:5px;
-o-border-radius:5px;
border-radius:5px;
text-align:center;
-webkit-box-shadow:inset 0 2px 6px rgba(0,0,0,0.1);
-moz-box-shadow:inset 0 2px 6px rgba(0,0,0,0.1);
-ms-box-shadow:inset 0 2px 6px rgba(0,0,0,0.1);
-o-box-shadow:inset 0 2px 6px rgba(0,0,0,0.1);
box-shadow:inset 0 2px 6px rgba(0,0,0,0.1);
}
.lsf-input::-webkit-input-placeholder {
text-align:center;
}
.table {
float:left;
width:420px;
}
.table:nth-child(2n-1) {
float:right;
}
.table table {
width:100%;
}
.table td,
.table th {
vertical-align:middle;
}
.table tr:nth-child(2n) th,
.table tr:nth-child(2n) td {
background:#f0f0f0;
}
.table th {
padding-bottom:5px;
text-align:center;
font-size:12px;
color:#999;
}
.table td.symbol {
width:60px;
font-size:36px;
text-align:center;
}
.table td.ligature {
text-align:left;
padding-left:10px;
}
.table td.unicode {
width:100px;
border-left:2px solid #fff;
}
.lsf-html,
.lsf-css {
overflow:auto;
width:860px;
min-height:170px;
padding:20px;
border:1px solid #ddd;
font-size:14px;
text-align:left;
background:#f9f9f9;
-webkit-border-radius:5px;
-moz-border-radius:5px;
-ms-border-radius:5px;
-o-border-radius:5px;
border-radius:5px;
-webkit-overflow-scrolling:touch;
}
.lsf-css {
min-height:940px;
margin-top:10px;
}
.download {
min-height:170px;
}
.download-button {
display:inline-block;
padding:2px 30px 10px;
font-size:25px;
color: #666;
-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.3);
-moz-box-shadow:0 1px 3px rgba(0,0,0,0.3);
-ms-box-shadow:0 1px 3px rgba(0,0,0,0.3);
-o-box-shadow:0 1px 3px rgba(0,0,0,0.3);
box-shadow:0 1px 3px rgba(0,0,0,0.3);
-webkit-border-radius:10px;
-moz-border-radius:10px;
-ms-border-radius:10px;
-o-border-radius:10px;
border-radius:10px;
-webkit-transition:0.2s;
-moz-transition:0.2s;
-ms-transition:0.2s;
-o-transition:0.2s;
transition:0.2s;
background: #f6f6f6;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f6f6f6));
background: linear-gradient(top, #fff #f6f6f6);
background: -webkit-linear-gradient(top, #fff #f6f6f6);
background: -moz-linear-gradient(top, #fff #f6f6f6);
background: -ms-linear-gradient(top, #fff #f6f6f6);
background: -o-linear-gradient(top, #fff #f6f6f6);
}
.download-button:hover {
color: #006DBE;
text-decoration:none;
-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.3);
-moz-box-shadow:0 3px 9px rgba(0,0,0,0.3);
-ms-box-shadow:0 3px 9px rgba(0,0,0,0.3);
-o-box-shadow:0 3px 9px rgba(0,0,0,0.3);
box-shadow:0 3px 9px rgba(0,0,0,0.3);
}
.download-button:active {
margin-top:3px;
color: #333;
-webkit-transition:0s;
-moz-transition:0s;
transition:0s;
-webkit-box-shadow:0 0px 2px rgba(0,0,0,0.5), inset 0 2px 2px rgba(0,0,0,0.2);
-moz-box-shadow:0 0px 2px rgba(0,0,0,0.5), inset 0 2px 2px rgba(0,0,0,0.2);
-ms-box-shadow:0 0px 2px rgba(0,0,0,0.5), inset 0 2px 2px rgba(0,0,0,0.2);
-o-box-shadow:0 0px 2px rgba(0,0,0,0.5), inset 0 2px 2px rgba(0,0,0,0.2);
box-shadow:0 0px 2px rgba(0,0,0,0.5), inset 0 2px 2px rgba(0,0,0,0.2);
background: #f0f0f0;
background: -webkit-gradient(linear, left top, left bottom, from(#fcfcfc), to(#f0f0f0));
background: linear-gradient(top, #fcfcfc #f0f0f0);
background: -webkit-linear-gradient(top, #fcfcfc #f0f0f0);
background: -moz-linear-gradient(top, #fcfcfc #f0f0f0);
background: -ms-linear-gradient(top, #fcfcfc #f0f0f0);
background: -o-linear-gradient(top, #fcfcfc #f0f0f0);
}
.download-button span {
display:block;
font-size:13px;
}
.profile {
overflow:hidden;
}
.profile-image {
float:left;
width:120px;
-webkit-border-radius:5px;
-moz-border-radius:5px;
-ms-border-radius:5px;
-o-border-radius:5px;
border-radius:5px;
opacity:0.8;
-webkit-transition:0.2s;
-moz-transition:0.2s;
-ms-transition:0.2s;
-o-transition:0.2s;
transition:0.2s;
}
.profile-image:hover {
opacity:1;
}
.profile-text {
float:left;
width:400px;
margin-top:5px;
margin-left:40px;
}
.profile-text h3 {
font-size:24px;
text-align:left;
}
.profile-text h3 span {
font-size:18px;
color:#999;
}
.profile-acount {
float:left;
padding-left:80px;
margin-left:60px;
border-left:1px solid #eee;
text-align:left;
}
.profile-acount li {
padding:1px 0;
}
.profile-acount li a {
font-size:16px;
}
@media (max-width: 900px){
#body {
width:100%;
margin:0 auto 20px;
font-size:14px;
}
h1 {
margin-top:15px;
font-size:24px;
}
h2 {
padding:50px 10px 2px;
margin-bottom:10px;
}
p {
margin-left:10px;
margin-right:10px;
}
.name {
font-size:12px;
}
.lsf-input {
margin:15px 0 25px;
font-size:22px;
}
.lsf-input input {
width:80%;
margin:0 5%;
padding-left:5%;
padding-right:5%;
}
.table {
float:none !important;
width:100%;
}
.table th {
font-size:8px;
}
.table td.symbol {
width:60px;
font-size:32px;
}
.table td.ligature {
padding-left:5px;
}
.table td.unicode {
width:70px;
font-size:11px;
}
.lsf-html, .lsf-css {
width:80%;
min-height:80px;
max-height:80px;
margin:5px 5%;
padding-left:5%;
padding-right:5%;
}
.profile-image {
width:48px;
margin:0 10px;
}
.profile-text {
float:none;
width:auto;
margin:0 10px 0 0;
}
.profile-text h3 {
font-size:18px;
}
.profile-text h3 span {
display:block;
font-size:12px;
}
.profile-acount {
width:100%;
padding:0;
margin:20px 0 0;
border:0;
border-top:1px solid #ddd;
}
.profile-acount li {
border-bottom:1px solid #ddd;
}
.profile-acount li a {
display:block;
padding:10px 20px;
color:#555;
font-size:20px;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f0f0f0));
background: linear-gradient(top, #fff #f0f0f0);
background: -webkit-linear-gradient(top, #fff #f0f0f0);
background: -moz-linear-gradient(top, #fff #f0f0f0);
background: -ms-linear-gradient(top, #fff #f0f0f0);
background: -o-linear-gradient(top, #fff #f0f0f0);
}
.profile-acount li a:after {
content:"right";
float:right;
color:#999;
line-height:1.7;
font-size:120%;
font-family: 'LigatureSymbols';
text-shadow:0 2px 0 #fff;
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
-webkit-font-feature-settings: "liga" 1, "dlig" 1;
-moz-font-feature-settings: "liga=1, dlig=1";
-ms-font-feature-settings: "liga" 1, "dlig" 1;
-o-font-feature-settings: "liga" 1, "dlig" 1;
font-feature-settings: "liga" 1, "dlig" 1;
}
#copyright {
margin:20px 0;
font-size:10px;
}
}
| adrianquirozf0/omsa | webroot/LigatureSymbols/style.css | CSS | gpl-2.0 | 11,081 | [
30522,
1030,
25869,
13462,
1005,
21183,
2546,
1011,
1022,
1005,
1025,
1030,
15489,
1011,
2227,
1063,
15489,
1011,
2155,
1024,
1005,
8018,
22662,
24335,
14956,
2015,
1005,
1025,
5034,
2278,
1024,
24471,
2140,
1006,
1005,
8018,
22662,
24335,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.analytics.function.mapping;
import org.apache.solr.analytics.ExpressionFactory.CreatorFunction;
import org.apache.solr.analytics.value.AnalyticsValueStream;
import org.apache.solr.analytics.value.BooleanValueStream;
import org.apache.solr.analytics.value.DoubleValueStream;
import org.apache.solr.analytics.value.FloatValueStream;
import org.apache.solr.analytics.value.IntValueStream;
import org.apache.solr.analytics.value.LongValueStream;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
/**
* A negation mapping function.
*
* <p>Takes a numeric or boolean ValueStream or Value and returns a ValueStream or Value of the same
* numeric type.
*/
public class NegateFunction {
public static final String name = "neg";
public static final CreatorFunction creatorFunction =
(params -> {
if (params.length != 1) {
throw new SolrException(
ErrorCode.BAD_REQUEST,
"The " + name + " function requires 1 paramaters, " + params.length + " found.");
}
AnalyticsValueStream param = params[0];
if (param instanceof BooleanValueStream) {
return LambdaFunction.createBooleanLambdaFunction(
name, x -> !x, (BooleanValueStream) param);
}
if (param instanceof IntValueStream) {
return LambdaFunction.createIntLambdaFunction(name, x -> x * -1, (IntValueStream) param);
}
if (param instanceof LongValueStream) {
return LambdaFunction.createLongLambdaFunction(
name, x -> x * -1, (LongValueStream) param);
}
if (param instanceof FloatValueStream) {
return LambdaFunction.createFloatLambdaFunction(
name, x -> x * -1, (FloatValueStream) param);
}
if (param instanceof DoubleValueStream) {
return LambdaFunction.createDoubleLambdaFunction(
name, x -> x * -1, (DoubleValueStream) param);
}
throw new SolrException(
ErrorCode.BAD_REQUEST,
"The "
+ name
+ " function requires a boolean or numeric parameter, "
+ param.getExpressionStr()
+ " found.");
});
}
| apache/solr | solr/modules/analytics/src/java/org/apache/solr/analytics/function/mapping/NegateFunction.java | Java | apache-2.0 | 3,077 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
1008,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
5500,
2007,
1008,
2023,
2147,
2005,
3176,
2592,
4953,
9385,
6095,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
Copyright (c) 2011 Mellanox Technologies. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
*/
#ifndef MCA_COLL_FCA_DEBUG_H
#define MCA_COLL_FCA_DEBUG_H
#pragma GCC system_header
#ifdef __BASE_FILE__
#define __FCA_FILE__ __BASE_FILE__
#else
#define __FCA_FILE__ __FILE__
#endif
#define FCA_VERBOSE(level, format, ...) \
opal_output_verbose(level, mca_coll_fca_output, "%s:%d - %s() " format, \
__FCA_FILE__, __LINE__, __FUNCTION__, ## __VA_ARGS__)
#define FCA_ERROR(format, ... ) \
opal_output_verbose(0, mca_coll_fca_output, "Error: %s:%d - %s() " format, \
__FCA_FILE__, __LINE__, __FUNCTION__, ## __VA_ARGS__)
#define FCA_MODULE_VERBOSE(fca_module, level, format, ...) \
FCA_VERBOSE(level, "[%p:%d] " format, (void*)(fca_module)->comm, (fca_module)->rank, ## __VA_ARGS__)
extern int mca_coll_fca_output;
#endif
| ClaudioNahmad/Servicio-Social | Parametros/CosmoMC/prerrequisitos/openmpi-2.0.2/ompi/mca/coll/fca/coll_fca_debug.h | C | gpl-3.0 | 926 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2249,
11463,
5802,
11636,
6786,
1012,
2035,
2916,
9235,
1012,
1002,
9385,
1002,
3176,
9385,
2015,
2089,
3582,
1002,
20346,
1002,
1008,
1013,
1001,
2065,
13629,
2546,
22432,
1035,
8902,
2140,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
function Boot() {
}
Boot.prototype = {
preload: function () {
this.load.image('preloader', 'assets/preloader.gif');
},
create: function () {
this.game.input.maxPointers = 1;
this.game.state.start('preload');
}
};
module.exports = Boot;
| robomatix/one-minute-shoot-em-up-v2 | game/states/boot.js | JavaScript | gpl-3.0 | 273 | [
30522,
1005,
2224,
9384,
1005,
1025,
3853,
9573,
1006,
1007,
1063,
1065,
9573,
1012,
8773,
1027,
1063,
3653,
11066,
1024,
3853,
1006,
1007,
1063,
2023,
1012,
7170,
1012,
3746,
1006,
1005,
3653,
11066,
2121,
1005,
1010,
1005,
7045,
1013,
3... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
namespace ContaLibre.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | seranfuen/contalibre | ContaLibre/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | C# | gpl-3.0 | 242 | [
30522,
3415,
15327,
9530,
9080,
12322,
2890,
1012,
2752,
1012,
2393,
13704,
1012,
2944,
6155,
23235,
8496,
1063,
2270,
2465,
4372,
2819,
10175,
5657,
6155,
23235,
3258,
1063,
2270,
5164,
12653,
1063,
2131,
1025,
2275,
1025,
1065,
2270,
5164... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>unicoq: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.6 / unicoq - 1.3+8.8</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
unicoq
<small>
1.3+8.8
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-01-01 06:30:20 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-01 06:30:20 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 1 Virtual package relying on perl
coq 8.6 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
authors: [ "Matthieu Sozeau <matthieu.sozeau@inria.fr>" "Beta Ziliani <beta@mpi-sws.org>" ]
dev-repo: "git+https://github.com/unicoq/unicoq.git"
homepage: "https://github.com/unicoq/unicoq"
bug-reports: "https://github.com/unicoq/unicoq/issues"
license: "MIT"
build: [
["coq_makefile" "-f" "Make" "-o" "Makefile"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"ocaml"
"coq" {>= "8.8.0" & < "8.9~"}
]
synopsis: "An enhanced unification algorithm for Coq"
url {
src: "https://github.com/unicoq/unicoq/archive/v1.3-8.8.tar.gz"
checksum: "md5=9879651098175dd7bb1b8768d29dae62"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-unicoq.1.3+8.8 coq.8.6</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.6).
The following dependencies couldn't be met:
- coq-unicoq -> coq >= 8.8.0 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-unicoq.1.3+8.8</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.03.0-2.0.5/released/8.6/unicoq/1.3+8.8.html | HTML | mit | 6,753 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
11374,
1027,
1000,
4372,
1000,
1028,
1026,
2132,
1028,
1026,
18804,
25869,
13462,
1027,
1000,
21183,
2546,
1011,
1022,
1000,
1028,
1026,
18804,
2171,
1027,
1000,
3193,
6442,
1000,
418... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\Order */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Orders', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="col-xs-12">
<div class="row">
<div class="col-md-2">
<div class="row">
<?php echo $this->render('@vendor/kirillantv/yii2-swap/views/management/_menu'); ?>
</div>
</div>
<div class="col-md-10">
<div class="order-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'item_id',
'catcher_id',
'status',
],
]) ?>
</div>
</div>
</div>
</div>
| kirillantv/yii2-swap | views/management/orders/view.php | PHP | mit | 1,263 | [
30522,
1026,
1029,
25718,
2224,
12316,
2072,
1032,
2393,
2545,
1032,
16129,
1025,
2224,
12316,
2072,
1032,
15536,
28682,
1032,
6987,
8584,
1025,
1013,
1008,
1030,
13075,
1002,
2023,
12316,
2072,
1032,
4773,
1032,
3193,
1008,
1013,
1013,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<html>
<title>代客訂位訂餐</title>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<div><form>
姓名 : <input type="text" id="name"> <br>
電話:<input type="text" id="phonenum"> <br>
日期:<select name="date_" id="date_">
<?php for($i=0; $i<7; $i++){
$temp = $dates[$i];
echo "<option value=\"".$temp."\">".$temp."</option>";
} ?>
</select> <br>
時段:<select name="time_" id="time_">
<option value="0">11:00~13:00</option>
<option value="1">13:00~15:00</option>
<option value="2">17:00~19:00</option>
<option value="3">19:00~21:00</option>
</select> <br>
人數:<select name="quantity" id="quantity">
<?php for($i=1; $i<11; $i++){
echo "<option value=\"".$i."\">".$i."</option>";
} ?>
</select> <br>
<button class="myButton" id="submit">確認</button>
<button class="myButton" type="button" onclick="window.location.replace('/CI/index.php/reservation');">回到大廳</button> <br>
</form></div>
<script>
$(document).ready(function(){
$("#submit").click(function() {
var order_confirm = confirm("是否訂菜?");
$.ajax({
url : "upload_seat_reservation_by_manager",
type : "POST",
dataType : "text",
data : {"date_" : $('#date_').val(), "time_" : $('#time_').val(), "quantity" : $('#quantity').val(), "name" : $('#name').val(), "phonenum" : $('#phonenum').val()},
success : function(response){
var check = response;
if(check == "c"){
if(!order_confirm){
window.location.replace("/CI/index.php/reservation/create_reservation");
}else{
window.location.replace("/CI/index.php/reservation/menu");
}
}
else if(check == "n"){
alert("no enough seat");
}
else{
alert("invalid value");
}
}
});
});
});
</script>
</body>
</html>
<style>
body {
background: url("http://127.0.0.1/CI/image/index_back.jpg");
background-size: cover;
background-repeat: no-repeat;
font-style: oblique;
font-size: 18px;
font-weight: bold;
}
div {
background-color: #DDDDDD;
width: 350px;
height: 280px;
margin-top: 150px;
margin:0px auto;
border-radius: 10px;
box-shadow: 10px 10px 5px #111111;
text-align:center;
line-height:40px;
}
input {
border: 1px solid #BBBBBB; //改變外框
background: #fff; // 背景色
/* 邊角圓弧化,不同瀏器覧設定不同 */
-moz-border-radius:3px; // Firefox
-webkit-border-radius: 3px; // Safari 和 Chrome
border-radius: 3px; // Opera 10.5+
}
a{
text-decoration:none;
color: #666666;
}
.myButton {
margin-top: 15px;
-moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
-webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
box-shadow:inset 0px 1px 0px 0px #ffffff;
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9));
background:-moz-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background:-webkit-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background:-o-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background:-ms-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background:linear-gradient(to bottom, #f9f9f9 5%, #e9e9e9 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9',GradientType=0);
background-color:#f9f9f9;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1px solid #807480;
display:inline-block;
cursor:pointer;
color:#666666;
font-family:Arial;
font-size:15px;
font-weight:bold;
padding:11px 24px;
text-decoration:none;
text-shadow:0px 1px 0px #ffffff;
}
.myButton:hover {
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #e9e9e9), color-stop(1, #f9f9f9));
background:-moz-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background:-webkit-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background:-o-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background:-ms-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background:linear-gradient(to bottom, #e9e9e9 5%, #f9f9f9 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#e9e9e9', endColorstr='#f9f9f9',GradientType=0);
background-color:#e9e9e9;
}
.myButton:active {
position:relative;
top:1px;
}
</style> | floydxiu/Restaurant-reservation-system | application/views/seat_reservation_by_manager.php | PHP | mit | 4,390 | [
30522,
1026,
16129,
1028,
1026,
2516,
1028,
1760,
100,
100,
100,
100,
100,
1026,
1013,
2516,
1028,
1026,
2132,
1028,
1026,
5896,
5034,
2278,
1027,
1000,
8299,
1024,
1013,
1013,
18176,
1012,
8224,
9331,
2483,
1012,
4012,
1013,
18176,
1013,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# O'Sullivan: A Ruby API for working with IIIF Presentation manifests
[](https://travis-ci.org/iiif-prezi/osullivan)
[](https://coveralls.io/github/iiif-prezi/osullivan?branch=development)
## Installation
From the source code do `rake install`, or get the latest release [from RubyGems](https://rubygems.org/gems/iiif-presentation).
## Building New Objects
There is (or will be) a class for all types in [IIIF Presentation API Spec](http://iiif.io/api/presentation/2.0/).
```ruby
require 'iiif/presentation'
seed = {
'@id' => 'http://example.com/manifest',
'label' => 'My Manifest'
}
# Any options you add are added to the object
manifest = IIIF::Presentation::Manifest.new(seed)
canvas = IIIF::Presentation::Canvas.new()
# All classes act like `ActiveSupport::OrderedHash`es, for the most part.
# Use `[]=` to set JSON-LD properties...
canvas['@id'] = 'http://example.com/canvas'
# ...but there are also accessors and mutators for the properties mentioned in
# the spec
canvas.width = 10
canvas.height = 20
canvas.label = 'My Canvas'
oc = IIIF::Presentation::Resource.new('@id' => 'http://example.com/content')
canvas.other_content << oc
manifest.sequences << canvas
puts manifest.to_json(pretty: true)
```
Methods are generated dynamically, which means `#methods` is your friend:
```ruby
manifest = IIIF::Presentation::Manifest.new()
puts manifest.methods(false)
> label=
> label
> description=
> description
> thumbnail=
> thumbnail
> attribution=
> attribution
> viewing_hint=
> viewingHint=
> viewing_hint
> viewingHint
[...]
```
Note that multi-word properties are implemented as snake_case (because this is
Ruby), but is serialized as camelCase. There are camelCase aliases for these.
```ruby
manifest = IIIF::Presentation::Manifest.new()
manifest.viewing_hint = 'paged'
puts manifest.to_json(pretty: true, force: true) # force: true skips validations
> {
> "@context": "http://iiif.io/api/presentation/2/context.json",
> "@type": "sc:Manifest",
> "viewingHint": "paged"
> }
```
## Parsing Existing Objects
Use `IIIF::Service#parse`. It will figure out what the object
should be, based on `@type`, and fall back to `Hash` when
it can't e.g.:
```ruby
seed = '{
"@context": "http://iiif.io/api/presentation/2/context.json",
"@id": "http://example.com/manifest",
"@type": "sc:Manifest",
"label": "My Manifest",
"service": {
"@context": "http://iiif.io/api/image/2/context.json",
"@id":"http://www.example.org/images/book1-page1",
"profile":"http://iiif.io/api/image/2/profiles/level2.json"
},
"seeAlso": {
"@id": "http://www.example.org/library/catalog/book1.marc",
"format": "application/marc"
},
"sequences": [
{
"@id":"http://www.example.org/iiif/book1/sequence/normal",
"@type":"sc:Sequence",
"label":"Current Page Order",
"viewingDirection":"left-to-right",
"viewingHint":"paged",
"startCanvas": "http://www.example.org/iiif/book1/canvas/p2",
"canvases": [
{
"@id": "http://example.com/canvas",
"@type": "sc:Canvas",
"width": 10,
"height": 20,
"label": "My Canvas",
"otherContent": [
{
"@id": "http://example.com/content",
"@type":"sc:AnnotationList",
"motivation": "sc:painting"
}
]
}
]
}
]
}'
obj = IIIF::Service.parse(seed) # can also be a file path or a Hash
puts obj.class
puts obj.see_also.class
> IIIF::Presentation::Manifest
> Hash
```
## Validation and Exceptions
This is work in progress. Right now exceptions are generally raised when you
try to set something to a type it should never be:
```ruby
manifest = IIIF::Presentation::Manifest.new
manifest.sequences = 'quux'
> [...] sequences must be an Array. (IIIF::Presentation::IllegalValueError)
```
and also if any required properties are missing when calling `to_json`
```ruby
canvas = IIIF::Presentation::Canvas.new('@id' => 'http://example.com/canvas')
puts canvas.to_json(pretty: true)
> A(n) width is required for each IIIF::Presentation::Canvas (IIIF::Presentation::MissingRequiredKeyError)
```
but you can skip this validation by adding `force: true`:
```ruby
canvas = IIIF::Presentation::Canvas.new('@id' => 'http://example.com/canvas')
puts canvas.to_json(pretty: true, force: true)
> {
> "@context": "http://iiif.io/api/presentation/2/context.json",
> "@id": "http://example.com/canvas",
> "@type": "sc:Canvas"
> }
```
This all needs a bit of tidying up, finishing, and refactoring, so expect it to
change.
| iiif-prezi/osullivan | README.md | Markdown | bsd-2-clause | 4,780 | [
30522,
1001,
1051,
1005,
7624,
1024,
1037,
10090,
17928,
2005,
2551,
2007,
3523,
2546,
8312,
19676,
2015,
1031,
999,
1031,
3857,
3570,
1033,
1006,
16770,
1024,
1013,
1013,
10001,
1011,
25022,
1012,
8917,
1013,
3523,
2546,
1011,
3653,
5831,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
////////////////////////////////////////////////////////////////////////////
// Created : 04.03.2010
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2010
////////////////////////////////////////////////////////////////////////////
#ifndef N_ARY_TREE_WEIGHT_NODE_H_INCLUDED
#define N_ARY_TREE_WEIGHT_NODE_H_INCLUDED
#include "mixing_n_ary_tree_base_node.h"
#include "base_interpolator.h"
namespace xray {
namespace animation {
namespace mixing {
class n_ary_tree_weight_node : public n_ary_tree_base_node {
public:
inline n_ary_tree_weight_node ( base_interpolator const& interpolator, float const weight );
inline n_ary_tree_weight_node ( n_ary_tree_weight_node const& other );
inline base_interpolator const& interpolator ( ) const;
inline float weight ( ) const;
inline bool operator == ( n_ary_tree_weight_node const& other ) const;
inline bool operator != ( n_ary_tree_weight_node const& other ) const;
private:
n_ary_tree_weight_node& operator= ( n_ary_tree_weight_node const& other);
virtual void accept ( n_ary_tree_visitor& visitor );
virtual void accept ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_base_node& node );
virtual void visit ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_animation_node& node );
virtual void visit ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_weight_node& node );
virtual void visit ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_addition_node& node );
virtual void visit ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_subtraction_node& node );
virtual void visit ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_multiplication_node& node );
virtual void visit ( n_ary_tree_double_dispatcher& dispatcher, n_ary_tree_transition_node& node );
private:
base_interpolator const& m_interpolator;
float const m_weight;
}; // class n_ary_tree_weight_node
inline bool operator < (
n_ary_tree_weight_node const& left,
n_ary_tree_weight_node const& right
);
} // namespace mixing
} // namespace animation
} // namespace xray
#include "mixing_n_ary_tree_weight_node_inline.h"
#endif // #ifndef N_ARY_TREE_WEIGHT_NODE_H_INCLUDED | hpl1nk/nonamegame | xray/animation/sources/mixing_n_ary_tree_weight_node.h | C | gpl-3.0 | 2,250 | [
30522,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.pm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fxch_ST0_ST2 extends Executable
{
public fxch_ST0_ST2(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double tmp = cpu.fpu.ST(0);
cpu.fpu.setST(0, cpu.fpu.ST(2));
cpu.fpu.setST(2, tmp);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/fxch_ST0_ST2.java | Java | gpl-2.0 | 1,856 | [
30522,
1013,
1008,
16545,
2278,
1024,
2019,
1060,
20842,
7473,
8051,
7861,
20350,
2005,
1037,
5760,
9262,
7484,
3698,
9385,
1006,
1039,
1007,
2262,
1011,
2286,
4775,
8475,
2023,
2565,
2003,
2489,
4007,
1025,
2017,
2064,
2417,
2923,
3089,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7-b41
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.03.30 at 03:47:44 PM EDT
//
package helloworld.sample.ibm.helloworld;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for helloResponseType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="helloResponseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="response" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "helloResponseType", propOrder = {
"response"
})
public class HelloResponseType {
@XmlElement(required = true, nillable = true)
protected String response;
/**
* Gets the value of the response property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getResponse() {
return response;
}
/**
* Sets the value of the response property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setResponse(String value) {
this.response = value;
}
}
| jacobono/gradle-jaxb-plugin | examples/hello-world-bindings-schema/src/main/java/helloworld/sample/ibm/helloworld/HelloResponseType.java | Java | gpl-2.0 | 1,801 | [
30522,
1013,
1013,
1013,
1013,
2023,
5371,
2001,
7013,
2011,
1996,
9262,
21246,
4294,
2005,
20950,
8031,
1006,
13118,
2497,
1007,
4431,
7375,
1010,
1058,
2475,
1012,
1016,
1012,
1021,
1011,
1038,
30524,
1028,
1013,
1013,
2151,
12719,
2000,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Copyright 2015 Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fastfood Chef Cookbook manager."""
from __future__ import print_function
import os
from fastfood import utils
class CookBook(object):
"""Chef Cookbook object.
Understands metadata.rb, Berksfile and how to parse them.
"""
def __init__(self, path):
"""Initialize CookBook wrapper at 'path'."""
self.path = utils.normalize_path(path)
self._metadata = None
if not os.path.isdir(path):
raise ValueError("Cookbook dir %s does not exist."
% self.path)
self._berksfile = None
@property
def name(self):
"""Cookbook name property."""
try:
return self.metadata.to_dict()['name']
except KeyError:
raise LookupError("%s is missing 'name' attribute'."
% self.metadata)
@property
def metadata(self):
"""Return dict representation of this cookbook's metadata.rb ."""
self.metadata_path = os.path.join(self.path, 'metadata.rb')
if not os.path.isfile(self.metadata_path):
raise ValueError("Cookbook needs metadata.rb, %s"
% self.metadata_path)
if not self._metadata:
self._metadata = MetadataRb(open(self.metadata_path, 'r+'))
return self._metadata
@property
def berksfile(self):
"""Return this cookbook's Berksfile instance."""
self.berks_path = os.path.join(self.path, 'Berksfile')
if not self._berksfile:
if not os.path.isfile(self.berks_path):
raise ValueError("No Berksfile found at %s"
% self.berks_path)
self._berksfile = Berksfile(open(self.berks_path, 'r+'))
return self._berksfile
class MetadataRb(utils.FileWrapper):
"""Wrapper for a metadata.rb file."""
@classmethod
def from_dict(cls, dictionary):
"""Create a MetadataRb instance from a dict."""
cookbooks = set()
# put these in order
groups = [cookbooks]
for key, val in dictionary.items():
if key == 'depends':
cookbooks.update({cls.depends_statement(cbn, meta)
for cbn, meta in val.items()})
body = ''
for group in groups:
if group:
body += '\n'
body += '\n'.join(group)
return cls.from_string(body)
@staticmethod
def depends_statement(cookbook_name, metadata=None):
"""Return a valid Ruby 'depends' statement for the metadata.rb file."""
line = "depends '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Stencil dependency options for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadata))
if metadata:
line = "%s '%s'" % (line, "', '".join(metadata))
return line
def to_dict(self):
"""Return a dictionary representation of this metadata.rb file."""
return self.parse()
def parse(self):
"""Parse the metadata.rb into a dict."""
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
depends = {}
for line in data:
if not len(line) == 2:
continue
key, value = line
if key == 'depends':
value = value.split(',')
lib = utils.ruby_strip(value[0])
detail = [utils.ruby_strip(j) for j in value[1:]]
depends[lib] = detail
datamap = {key: utils.ruby_strip(val) for key, val in data}
if depends:
datamap['depends'] = depends
self.seek(0)
return datamap
def merge(self, other):
"""Add requirements from 'other' metadata.rb into this one."""
if not isinstance(other, MetadataRb):
raise TypeError("MetadataRb to merge should be a 'MetadataRb' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
meta_writelines = ['%s\n' % self.depends_statement(cbn, meta)
for cbn, meta in new.get('depends', {}).items()
if cbn not in current.get('depends', {})]
self.write_statements(meta_writelines)
return self.to_dict()
class Berksfile(utils.FileWrapper):
"""Wrapper for a Berksfile."""
berks_options = [
'branch',
'git',
'path',
'ref',
'revision',
'tag',
]
def to_dict(self):
"""Return a dictionary representation of this Berksfile."""
return self.parse()
def parse(self):
"""Parse this Berksfile into a dict."""
self.flush()
self.seek(0)
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
datamap = {}
for line in data:
if len(line) == 1:
datamap[line[0]] = True
elif len(line) == 2:
key, value = line
if key == 'cookbook':
datamap.setdefault('cookbook', {})
value = [utils.ruby_strip(v) for v in value.split(',')]
lib, detail = value[0], value[1:]
datamap['cookbook'].setdefault(lib, {})
# if there is additional dependency data but its
# not the ruby hash, its the version constraint
if detail and not any("".join(detail).startswith(o)
for o in self.berks_options):
constraint, detail = detail[0], detail[1:]
datamap['cookbook'][lib]['constraint'] = constraint
if detail:
for deet in detail:
opt, val = [
utils.ruby_strip(i)
for i in deet.split(':', 1)
]
if not any(opt == o for o in self.berks_options):
raise ValueError(
"Cookbook detail '%s' does not specify "
"one of '%s'" % (opt, self.berks_options))
else:
datamap['cookbook'][lib][opt.strip(':')] = (
utils.ruby_strip(val))
elif key == 'source':
datamap.setdefault(key, [])
datamap[key].append(utils.ruby_strip(value))
elif key:
datamap[key] = utils.ruby_strip(value)
self.seek(0)
return datamap
@classmethod
def from_dict(cls, dictionary):
"""Create a Berksfile instance from a dict."""
cookbooks = set()
sources = set()
other = set()
# put these in order
groups = [sources, cookbooks, other]
for key, val in dictionary.items():
if key == 'cookbook':
cookbooks.update({cls.cookbook_statement(cbn, meta)
for cbn, meta in val.items()})
elif key == 'source':
sources.update({"source '%s'" % src for src in val})
elif key == 'metadata':
other.add('metadata')
body = ''
for group in groups:
if group:
body += '\n'
body += '\n'.join(group)
return cls.from_string(body)
@staticmethod
def cookbook_statement(cookbook_name, metadata=None):
"""Return a valid Ruby 'cookbook' statement for the Berksfile."""
line = "cookbook '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Berksfile dependency hash for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadata))
# not like the others...
if 'constraint' in metadata:
line += ", '%s'" % metadata.pop('constraint')
for opt, spec in metadata.items():
line += ", %s: '%s'" % (opt, spec)
return line
def merge(self, other):
"""Add requirements from 'other' Berksfile into this one."""
if not isinstance(other, Berksfile):
raise TypeError("Berksfile to merge should be a 'Berksfile' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
berks_writelines = ['%s\n' % self.cookbook_statement(cbn, meta)
for cbn, meta in new.get('cookbook', {}).items()
if cbn not in current.get('cookbook', {})]
# compare and gather 'source' requirements
berks_writelines.extend(["source '%s'\n" % src for src
in new.get('source', [])
if src not in current.get('source', [])])
self.write_statements(berks_writelines)
return self.to_dict()
| samstav/fastfood | fastfood/book.py | Python | apache-2.0 | 10,125 | [
30522,
1001,
9385,
2325,
27259,
15327,
2149,
1010,
4297,
1012,
1001,
1001,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1001,
2017,
2089,
2025,
2224,
2023,
5371,
3272,
1999,
12646,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#ifndef RT_CONFIG_H__
#define RT_CONFIG_H__
/* Automatically generated file; DO NOT EDIT. */
/* RT-Thread Configuration */
/* RT-Thread Kernel */
#define RT_NAME_MAX 8
#define RT_ALIGN_SIZE 4
#define RT_THREAD_PRIORITY_32
#define RT_THREAD_PRIORITY_MAX 32
#define RT_TICK_PER_SECOND 100
#define RT_USING_OVERFLOW_CHECK
#define RT_USING_HOOK
#define RT_USING_IDLE_HOOK
#define RT_IDEL_HOOK_LIST_SIZE 4
#define IDLE_THREAD_STACK_SIZE 256
#define RT_DEBUG
#define RT_DEBUG_COLOR
/* Inter-Thread communication */
#define RT_USING_SEMAPHORE
#define RT_USING_MUTEX
#define RT_USING_EVENT
#define RT_USING_MAILBOX
#define RT_USING_MESSAGEQUEUE
/* Memory Management */
#define RT_USING_MEMPOOL
#define RT_USING_MEMHEAP
#define RT_USING_MEMHEAP_AS_HEAP
#define RT_USING_HEAP
/* Kernel Device Object */
#define RT_USING_DEVICE
#define RT_USING_CONSOLE
#define RT_CONSOLEBUF_SIZE 128
#define RT_CONSOLE_DEVICE_NAME "uart1"
#define RT_VER_NUM 0x40001
/* RT-Thread Components */
#define RT_USING_COMPONENTS_INIT
#define RT_USING_USER_MAIN
#define RT_MAIN_THREAD_STACK_SIZE 2048
#define RT_MAIN_THREAD_PRIORITY 10
/* C++ features */
/* Command shell */
#define RT_USING_FINSH
#define FINSH_THREAD_NAME "tshell"
#define FINSH_USING_HISTORY
#define FINSH_HISTORY_LINES 5
#define FINSH_USING_SYMTAB
#define FINSH_USING_DESCRIPTION
#define FINSH_THREAD_PRIORITY 20
#define FINSH_THREAD_STACK_SIZE 4096
#define FINSH_CMD_SIZE 80
#define FINSH_USING_MSH
#define FINSH_USING_MSH_DEFAULT
#define FINSH_USING_MSH_ONLY
#define FINSH_ARG_MAX 10
/* Device virtual file system */
/* Device Drivers */
#define RT_USING_DEVICE_IPC
#define RT_PIPE_BUFSZ 512
#define RT_USING_SERIAL
#define RT_SERIAL_RB_BUFSZ 64
#define RT_USING_CPUTIME
#define RT_USING_PIN
/* Using WiFi */
/* Using USB */
/* POSIX layer and C standard library */
#define RT_USING_LIBC
/* Network */
/* Socket abstraction layer */
/* light weight TCP/IP stack */
/* Modbus master and slave stack */
/* AT commands */
/* VBUS(Virtual Software BUS) */
/* Utilities */
/* RT-Thread online packages */
/* IoT - internet of things */
/* Wi-Fi */
/* Marvell WiFi */
/* Wiced WiFi */
/* IoT Cloud */
/* security packages */
/* language packages */
/* multimedia packages */
/* tools packages */
/* system packages */
/* peripheral libraries and drivers */
/* miscellaneous packages */
/* samples: kernel and components samples */
/* Hardware Drivers Config */
#define BSP_USING_4MFLASH
#define SOC_MIMXRT1064DVL6A
/* On-chip Peripheral Drivers */
#define BSP_USING_GPIO
#define BSP_USING_LPUART
#define BSP_USING_LPUART1
/* Onboard Peripheral Drivers */
/* Board extended module Drivers */
#endif
| FlyLu/rt-thread | bsp/imxrt/libraries/templates/imxrt1064xxx/rtconfig.h | C | apache-2.0 | 2,700 | [
30522,
1001,
2065,
13629,
2546,
19387,
1035,
9530,
8873,
2290,
1035,
1044,
1035,
1035,
1001,
9375,
19387,
1035,
9530,
8873,
2290,
1035,
1044,
1035,
1035,
1013,
1008,
8073,
7013,
5371,
1025,
2079,
2025,
10086,
1012,
1008,
1013,
1013,
1008,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import Ember from 'ember-metal/core';
import { get } from 'ember-metal/property_get';
import { internal } from 'htmlbars-runtime';
import { read } from 'ember-metal/streams/utils';
export default {
setupState(state, env, scope, params, hash) {
var controller = hash.controller;
if (controller) {
if (!state.controller) {
var context = params[0];
var controllerFactory = env.container.lookupFactory('controller:' + controller);
var parentController = null;
if (scope.locals.controller) {
parentController = read(scope.locals.controller);
} else if (scope.locals.view) {
parentController = get(read(scope.locals.view), 'context');
}
var controllerInstance = controllerFactory.create({
model: env.hooks.getValue(context),
parentController: parentController,
target: parentController
});
params[0] = controllerInstance;
return { controller: controllerInstance };
}
return state;
}
return { controller: null };
},
isStable() {
return true;
},
isEmpty(state) {
return false;
},
render(morph, env, scope, params, hash, template, inverse, visitor) {
if (morph.state.controller) {
morph.addDestruction(morph.state.controller);
hash.controller = morph.state.controller;
}
Ember.assert(
'{{#with foo}} must be called with a single argument or the use the ' +
'{{#with foo as |bar|}} syntax',
params.length === 1
);
Ember.assert(
'The {{#with}} helper must be called with a block',
!!template
);
internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor);
},
rerender(morph, env, scope, params, hash, template, inverse, visitor) {
internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor);
}
};
| cjc343/ember.js | packages/ember-htmlbars/lib/keywords/with.js | JavaScript | mit | 1,930 | [
30522,
12324,
7861,
5677,
2013,
1005,
7861,
5677,
1011,
3384,
1013,
4563,
1005,
1025,
12324,
1063,
2131,
1065,
2013,
1005,
7861,
5677,
1011,
3384,
1013,
3200,
1035,
2131,
1005,
1025,
12324,
1063,
4722,
1065,
2013,
1005,
16129,
8237,
2015,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Makefile.in generated by automake 1.8.5 from Makefile.am.
# win32/VS2003/libspeex/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# Disable automatic dependency tracking if using other tools than gcc and gmake
#AUTOMAKE_OPTIONS = no-dependencies
srcdir = .
top_srcdir = ../../..
pkgdatadir = $(datadir)/speex
pkglibdir = $(libdir)/speex
pkgincludedir = $(includedir)/speex
top_builddir = ../../..
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
INSTALL = /usr/bin/install -c
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
host_triplet = arm-apple-darwin
subdir = win32/VS2003/libspeex
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(mkdir_p)
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
SOURCES =
DIST_SOURCES =
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /Users/cxjwin/Desktop/speex-1.2rc1/missing --run aclocal-1.8
AMDEP_FALSE = #
AMDEP_TRUE =
AMTAR = ${SHELL} /Users/cxjwin/Desktop/speex-1.2rc1/missing --run tar
AR = ar
AS = as
AUTOCONF = ${SHELL} /Users/cxjwin/Desktop/speex-1.2rc1/missing --run autoconf
AUTOHEADER = ${SHELL} /Users/cxjwin/Desktop/speex-1.2rc1/missing --run autoheader
AUTOMAKE = ${SHELL} /Users/cxjwin/Desktop/speex-1.2rc1/missing --run automake-1.8
AWK = awk
BUILD_KISS_FFT_FALSE =
BUILD_KISS_FFT_TRUE = #
BUILD_SMALLFT_FALSE = #
BUILD_SMALLFT_TRUE =
CC = xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=7.0 --sysroot=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk -isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include
CCDEPMODE = depmode=gcc3
CFLAGS = -g -O2 -fvisibility=hidden
CPP = xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=7.0 --sysroot=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk -isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include -E
CPPFLAGS =
CXX = xcrun --sdk iphoneos clang++ -arch arm64 -miphoneos-version-min=7.0 --sysroot=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk -isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include
CXXCPP = xcrun --sdk iphoneos clang++ -arch arm64 -miphoneos-version-min=7.0 --sysroot=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk -isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include -E
CXXDEPMODE = depmode=gcc3
CXXFLAGS = -g -O2
CYGPATH_W = echo
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = dlltool
DSYMUTIL = dsymutil
ECHO = /bin/echo
ECHO_C = \c
ECHO_N =
ECHO_T =
EGREP = /usr/bin/grep -E
EXEEXT =
F77 =
FFLAGS =
FFT_CFLAGS =
FFT_LIBS =
FFT_PKGCONFIG =
GREP = /usr/bin/grep
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
LDFLAGS = -Wl,-syslibroot,/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk
LIBOBJS =
LIBS = -lm
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LN_S = ln -s
LTLIBOBJS =
MAINT = #
MAINTAINER_MODE_FALSE =
MAINTAINER_MODE_TRUE = #
MAKEINFO = ${SHELL} /Users/cxjwin/Desktop/speex-1.2rc1/missing --run makeinfo
NMEDIT = nmedit
OBJDUMP = objdump
OBJEXT = o
OGG_CFLAGS = -I/Users/cxjwin/Desktop/speexLibrary/libogg-1.3.0/arm64/include
OGG_LIBS = -L/Users/cxjwin/Desktop/speexLibrary/libogg-1.3.0/arm64/lib -logg
PACKAGE = speex
PACKAGE_BUGREPORT =
PACKAGE_NAME =
PACKAGE_STRING =
PACKAGE_TARNAME =
PACKAGE_VERSION =
PATH_SEPARATOR = :
PKG_CONFIG =
RANLIB = ranlib
SED = /usr/bin/sed
SET_MAKE =
SHELL = /bin/sh
SIZE16 = short
SIZE32 = int
SPEEX_LT_AGE = 5
SPEEX_LT_CURRENT = 6
SPEEX_LT_REVISION = 0
SPEEX_VERSION = 1.2rc1
STRIP = strip
VERSION = 1.2rc1
ac_ct_CC =
ac_ct_CXX =
ac_ct_F77 =
am__fastdepCC_FALSE = #
am__fastdepCC_TRUE =
am__fastdepCXX_FALSE = #
am__fastdepCXX_TRUE =
am__include = include
am__leading_dot = .
am__quote =
bindir = ${exec_prefix}/bin
build = i386-apple-darwin12.5.0
build_alias =
build_cpu = i386
build_os = darwin12.5.0
build_vendor = apple
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = arm-apple-darwin
host_alias = arm-apple-darwin
host_cpu = arm
host_os = darwin
host_vendor = apple
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = /Users/cxjwin/Desktop/speex-1.2rc1/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = $(install_sh) -d
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /Users/cxjwin/Desktop/speexLibrary/speex-1.2rc1/arm64
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
src = src
sysconfdir = ${prefix}/etc
target_alias =
EXTRA_DIST = libspeex.vcproj
all: all-am
.SUFFIXES:
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/VS2003/libspeex/Makefile'; \
cd $(top_srcdir) && \
$(AUTOMAKE) --gnu win32/VS2003/libspeex/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
distclean-libtool:
-rm -f libtool
uninstall-info-am:
tags: TAGS
TAGS:
ctags: CTAGS
CTAGS:
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
list='$(DISTFILES)'; for file in $$list; do \
case $$file in \
$(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
$(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
esac; \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
if test "$$dir" != "$$file" && test "$$dir" != "."; then \
dir="/$$dir"; \
$(mkdir_p) "$(distdir)$$dir"; \
else \
dir=''; \
fi; \
if test -d $$d/$$file; then \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
fi; \
cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
else \
test -f $(distdir)/$$file \
|| cp -p $$d/$$file $(distdir)/$$file \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile
installdirs:
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-rm -f $(CONFIG_CLEAN_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-libtool
dvi: dvi-am
dvi-am:
html: html-am
info: info-am
info-am:
install-data-am:
install-exec-am:
install-info: install-info-am
install-man:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-info-am
.PHONY: all all-am check check-am clean clean-generic clean-libtool \
distclean distclean-generic distclean-libtool distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-exec install-exec-am \
install-info install-info-am install-man install-strip \
installcheck installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \
uninstall-info-am
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
| cxjwin/speex-1.2rc1 | win32/VS2003/libspeex/Makefile | Makefile | bsd-3-clause | 10,615 | [
30522,
1001,
2191,
8873,
2571,
1012,
1999,
7013,
2011,
8285,
2863,
3489,
1015,
1012,
1022,
1012,
1019,
2013,
2191,
8873,
2571,
1012,
2572,
1012,
1001,
2663,
16703,
1013,
5443,
28332,
2509,
1013,
5622,
5910,
28084,
2595,
1013,
2191,
8873,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* fallback */
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: local('Material Icons'), local('MaterialIcons-Regular'), url(http://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5UEw0lE80llgEseQY3FEmqw.woff2) format('woff2');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-webkit-font-feature-settings: 'liga';
-webkit-font-smoothing: antialiased;
}
/* cyrillic-ext */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v16/sTdaA6j0Psb920Vjv-mrzH-_kf6ByYO6CLYdB4HQE-Y.woff2) format('woff2');
}
/* cyrillic */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v16/uYECMKoHcO9x1wdmbyHIm3-_kf6ByYO6CLYdB4HQE-Y.woff2) format('woff2');
}
/* cyrillic-ext */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 500;
src: local('Roboto Medium'), local('Roboto-Medium'), url(https://fonts.gstatic.com/s/roboto/v16/ZLqKeelYbATG60EpZBSDy4X0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2');
}
/* cyrillic */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 500;
src: local('Roboto Medium'), local('Roboto-Medium'), url(https://fonts.gstatic.com/s/roboto/v16/oHi30kwQWvpCWqAhzHcCSIX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2');
}
/* cyrillic-ext */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 900;
src: local('Roboto Black'), local('Roboto-Black'), url(https://fonts.gstatic.com/s/roboto/v16/s7gftie1JANC-QmDJvMWZoX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2');
}
/* cyrillic */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 900;
src: local('Roboto Black'), local('Roboto-Black'), url(https://fonts.gstatic.com/s/roboto/v16/3Y_xCyt7TNunMGg0Et2pnoX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2');
} | adikari/todo-ee | Todo-web/src/main/webapp/resources/css/fonts.css | CSS | apache-2.0 | 2,216 | [
30522,
1013,
1008,
2991,
5963,
1008,
1013,
1030,
15489,
1011,
2227,
1063,
15489,
1011,
2155,
1024,
1005,
3430,
18407,
1005,
1025,
15489,
1011,
2806,
1024,
3671,
1025,
15489,
1011,
3635,
1024,
4278,
1025,
5034,
2278,
1024,
2334,
1006,
1005,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
local questSystemOld = Action()
function questSystemOld.onUse(player, item, fromPosition, target, toPosition, isHotkey)
if item.uid <= 100 or item.uid >= 41560 then
return false
end
local itemType = ItemType(item.uid)
if itemType:getId() == 0 then
return false
end
local itemWeight = itemType:getWeight()
local playerCap = player:getFreeCapacity()
if player:getStorageValue(item.uid) == -1 then
if playerCap >= itemWeight then
player:sendTextMessage(MESSAGE_INFO_DESCR, 'You have found a ' .. itemType:getName() .. '.')
player:addItem(item.uid, 1)
player:setStorageValue(item.uid, 1)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, 'You have found a ' .. itemType:getName() .. ' weighing ' .. itemWeight .. ' oz it\'s too heavy.')
end
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.")
end
return true
end
questSystemOld:id(2472, 2478, 2480, 2481, 2482, 7160, 7161)
questSystemOld:register()
| mattyx14/otxserver | data/scripts/actions/system/questSystemOld.lua | Lua | gpl-2.0 | 944 | [
30522,
2334,
8795,
6508,
13473,
5302,
6392,
1027,
2895,
1006,
1007,
3853,
8795,
6508,
13473,
5302,
6392,
1012,
2006,
8557,
1006,
2447,
1010,
8875,
1010,
2013,
26994,
1010,
4539,
1010,
2327,
19234,
1010,
2003,
12326,
14839,
1007,
2065,
8875,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework.autoproxy;
import java.util.ArrayList;
import java.util.List;
import org.springframework.aop.TargetSource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.Assert;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
/**
* Auto proxy creator that identifies beans to proxy via a list of names.
* Checks for direct, "xxx*", and "*xxx" matches.
*
* <p>For configuration details, see the javadoc of the parent class
* AbstractAutoProxyCreator. Typically, you will specify a list of
* interceptor names to apply to all identified beans, via the
* "interceptorNames" property.
*
* @author Juergen Hoeller
* @since 10.10.2003
* @see #setBeanNames
* @see #isMatch
* @see #setInterceptorNames
* @see AbstractAutoProxyCreator
*/
@SuppressWarnings("serial")
public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
private List<String> beanNames;
/**
* Set the names of the beans that should automatically get wrapped with proxies.
* A name can specify a prefix to match by ending with "*", e.g. "myBean,tx*"
* will match the bean named "myBean" and all beans whose name start with "tx".
* <p><b>NOTE:</b> In case of a FactoryBean, only the objects created by the
* FactoryBean will get proxied. This default behavior applies as of Spring 2.0.
* If you intend to proxy a FactoryBean instance itself (a rare use case, but
* Spring 1.2's default behavior), specify the bean name of the FactoryBean
* including the factory-bean prefix "&": e.g. "&myFactoryBean".
* @see org.springframework.beans.factory.FactoryBean
* @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX
*/
public void setBeanNames(String... beanNames) {
Assert.notEmpty(beanNames, "'beanNames' must not be empty");
this.beanNames = new ArrayList<>(beanNames.length);
for (String mappedName : beanNames) {
this.beanNames.add(StringUtils.trimWhitespace(mappedName));
}
}
/**
* Identify as bean to proxy if the bean name is in the configured list of names.
*/
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
if (this.beanNames != null) {
for (String mappedName : this.beanNames) {
if (FactoryBean.class.isAssignableFrom(beanClass)) {
if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
continue;
}
mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
if (isMatch(beanName, mappedName)) {
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
BeanFactory beanFactory = getBeanFactory();
if (beanFactory != null) {
String[] aliases = beanFactory.getAliases(beanName);
for (String alias : aliases) {
if (isMatch(alias, mappedName)) {
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
}
}
}
}
return DO_NOT_PROXY;
}
/**
* Return if the given bean name matches the mapped name.
* <p>The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
* as well as direct equality. Can be overridden in subclasses.
* @param beanName the bean name to check
* @param mappedName the name in the configured list of names
* @return if the names match
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected boolean isMatch(String beanName, String mappedName) {
return PatternMatchUtils.simpleMatch(mappedName, beanName);
}
}
| boggad/jdk9-sample | sample-catalog/spring-jdk9/src/spring.aop/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java | Java | mit | 4,235 | [
30522,
1013,
1008,
1008,
9385,
2526,
1011,
2355,
1996,
2434,
3166,
2030,
6048,
1012,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2025,
2224,
2023,
53... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/bin/bash
#===========================
# WATOBO-Installer for Linux
#---------------------------
# Tested on BackTrack 5R2
#===========================
# Date: 06.08.2012
# Author: Andreas Schmidt
Version=1.1
#---
# Version 1.1
# added libnetfilter-queue-dev package & gem
# added platform detection
#---
info() {
printf "\033[36m$*\033[0m\n"
}
head() {
printf "\033[31m$*\033[0m\n"
}
head "##############################################"
head "# W A T O B O - I N S T A L L E R #"
head "##############################################"
info "Version: $Version"
gem_opts=""
platform="Generic"
file=/etc/issue
if grep -q "BackTrack" $file
then
platform="BackTrack"
gem_opts="--user-install"
fi
info "Platform: $platform"
if [ "$platform" == "BackTrack" ]
then
echo "Adding /root/.gem/ruby/1.9.2/bin/ to your PATH .."
echo 'export PATH=$PATH:/root/.gem/ruby/1.9.2/bin' >> /root/.bashrc
export PATH=$PATH:/root/.gem/ruby/1.9.2/bin
#. /root/.bashrc
fi
echo "Installing required gems ..."
for G in ffi multi_json childprocess selenium-webdriver mechanize fxruby net-http-digest_auth net-http-persistent nokogiri domain_name unf webrobots ntlm-http net-http-pipeline nfqueue watobo
do
info ">> $G"
gem install $gem_opts $G
done
echo "Install libnetfilter for transparent proxy mode"
apt-get install libnetfilter-queue-dev
info "Installation finished."
echo "Open a new shell and type watobo_gui.rb to start WATOBO."
echo "For manuals/videos and general information about WATOBO please check:"
echo "* http://watobo.sourceforge.net/"
| larskanis/watobo | extras/watobo-installer.sh | Shell | gpl-2.0 | 1,558 | [
30522,
1001,
999,
1013,
8026,
1013,
24234,
1001,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1001,
28194,
16429,
2080,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# pakey
自己用的一些类库
| pakey/tool | README.md | Markdown | mit | 33 | [
30522,
1001,
22190,
3240,
100,
100,
100,
1916,
1740,
100,
100,
100,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp
{
public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData);
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions);
#region Quick Action
private async Task TestQuickActionNotProvidedAsync(
string initialMarkup,
TestParameters parameters = default)
{
using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters);
var (actions, _) = await GetCodeActionsAsync(workspace, parameters);
if (actions.Length == 1)
{
// The dialog shows up, not quick action
Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type);
}
else if (actions.Length > 1)
{
Assert.True(false, "Pull Members Up is provided via quick action");
}
else
{
Assert.True(true);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public interface ITestInterface
{
}
public class TestClass : ITestInterface
{
public int yo[||]u = 10086;
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction()
{
var methodTest = @"
namespace PushUpTest
{
public interface ITestInterface
{
void TestMethod();
}
public class TestClass : ITestInterface
{
public void TestM[||]ethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestQuickActionNotProvidedAsync(methodTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction()
{
var propertyTest1 = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { get; }
}
public class TestClass : IInterface
{
public int TestPr[||]operty { get; private set; }
}
}";
await TestQuickActionNotProvidedAsync(propertyTest1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction()
{
var eventTest = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
await TestQuickActionNotProvidedAsync(eventTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction()
{
var input = @"
namespace PushUpTest
{
public interface ITestInterface
{
void Foobar();
}
public class TestClass : ITestInterface
{
public class N[||]estedClass
{
}
}
}";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public void TestM[||]ethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
void TestMethod();
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullAbstractMethodToInterfaceViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public interface IInterface
{
}
public abstract class TestClass : IInterface
{
public abstract void TestMeth[||]od();
}
}";
var expected = @"
namespace PushUpTest
{
public interface IInterface
{
void TestMethod();
}
public abstract class TestClass : IInterface
{
public abstract void TestMethod();
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullGenericsUpToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface IInterface
{
}
public class TestClass : IInterface
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface IInterface
{
void TestMethod<T>() where T : IDisposable;
}
public class TestClass : IInterface
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullSingleEventToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
}
public class TestClass : IInterface
{
public event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event1, Event2, Event3;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Eve[||]nt2
{
add
{
System.Console.Writeln(""This is add in event1"");
}
remove
{
System.Console.Writeln(""This is remove in event2"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event2
{
add
{
System.Console.Writeln(""This is add in event1"");
}
remove
{
System.Console.Writeln(""This is remove in event2"");
}
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public int TestPr[||]operty { get; private set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { get; }
}
public class TestClass : IInterface
{
public int TestProperty { get; private set; }
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public int TestProperty[||]{ private get; set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { set; }
}
public class TestClass : IInterface
{
public int TestProperty{ private get; set; }
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
interface FooInterface : IInterface
{
int TestPr[||]operty { set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { set; }
}
interface FooInterface : IInterface
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private int j;
public int th[||]is[int i]
{
set => j = value;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int this[int i] { set; }
}
public class TestClass : IInterface
{
private int j;
public int this[int i]
{
set => j = value;
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private int j;
public int th[||]is[int i]
{
get => j = value;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int this[int i] { get; }
}
public class TestClass : IInterface
{
private int j;
public int this[int i]
{
get => j = value;
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction()
{
var methodTest = @"
namespace PushUpTest
{
public class Base
{
public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo"");
}
public class TestClass : Base
{
public override void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestQuickActionNotProvidedAsync(methodTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction()
{
var propertyTest = @"
using System;
namespace PushUpTest
{
public class Base
{
public virtual int TestProperty { get => 111; private set; }
}
public class TestClass : Base
{
public override int TestPr[||]operty { get; private set; }
}
}";
await TestQuickActionNotProvidedAsync(propertyTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction()
{
var eventTest = @"
using System;
namespace PushUpTest
{
public class Base2
{
protected virtual event EventHandler Event3
{
add
{
System.Console.WriteLine(""Hello"");
}
remove
{
System.Console.WriteLine(""World"");
}
};
}
public class TestClass2 : Base2
{
protected override event EventHandler E[||]vent3
{
add
{
System.Console.WriteLine(""foo"");
}
remove
{
System.Console.WriteLine(""bar"");
}
};
}
}";
await TestQuickActionNotProvidedAsync(eventTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction()
{
// Fields share the same name will be thought as 'override', since it will cause error
// if two same name fields exist in one class
var fieldTest = @"
namespace PushUpTest
{
public class Base
{
public int you = -100000;
}
public class TestClass : Base
{
public int y[||]ou = 10086;
}
}";
await TestQuickActionNotProvidedAsync(fieldTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodToOrdinaryClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneFieldsToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you[||]= 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int you = 10086;
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullGenericsUpToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
}
public class TestClass : BaseClass
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
public void TestMethod<T>() where T : IDisposable
{
}
}
public class TestClass : BaseClass
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you, a[||]nd, someone = 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int and;
}
public class TestClass : Base
{
public int you, someone = 10086;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMiddleFieldWithValueToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you, a[||]nd = 4000, someone = 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int and = 4000;
}
public class TestClass : Base
{
public int you, someone = 10086;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneEventFromMultipleToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3;
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Event4;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class TestClass2 : Base2
{
private static event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3;
}
public class TestClass2 : Base2
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventWithBodyToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class TestClass2 : Base2
{
private static event EventHandler Eve[||]nt3
{
add
{
System.Console.Writeln(""Hello"");
}
remove
{
System.Console.Writeln(""World"");
}
};
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3
{
add
{
System.Console.Writeln(""Hello"");
}
remove
{
System.Console.Writeln(""World"");
}
};
}
public class TestClass2 : Base2
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int TestPr[||]operty { get; private set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base
{
public int TestProperty { get; private set; }
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
private int j;
public int th[||]is[int i]
{
get => j;
set => j = value;
}
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int this[int i]
{
get => j;
set => j = value;
}
}
public class TestClass : Base
{
private int j;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Bar[||]Bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Bar[||]Bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
int BarBar();
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int F[||]oo
{
get;
set;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Foo
{
get;
set;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
int Foo { get; set; }
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullFieldUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : BaseClass
{
private int i, j, [||]k = 10;
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public class BaseClass
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : BaseClass
{
private int i, j;
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public class BaseClass
{
private int k = 10;
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToVBClassViaQuickAction()
{
// Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in
// AbstractCodeGenerationService will return null.
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int Bar[||]bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToVBInterfaceViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
public class TestClass : VBInterface
{
public int Bar[||]bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>
";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullFieldUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int fo[||]obar = 0;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int foo[||]bar
{
get;
set;
}
}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>
";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpToVBInterfaceViaQuickAction()
{
var input = @"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBInterface
{
public int foo[||]bar
{
get;
set;
}
}
</Document>
</Project>
<Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public event EventHandler BarEve[||]nt;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventUpToVBInterfaceViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBInterface
{
public event EventHandler BarEve[||]nt;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
#endregion Quick Action
#region Dialog
internal Task TestWithPullMemberDialogAsync(
string initialMarkUp,
string expectedResult,
IEnumerable<(string name, bool makeAbstract)> selection = null,
string destinationName = null,
int index = 0,
TestParameters parameters = default)
{
var service = new TestPullMemberUpService(selection, destinationName);
return TestInRegularAndScript1Async(
initialMarkUp, expectedResult,
index,
parameters.WithFixProviderData(service));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullPartialMethodUpToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public partial class TestClass : IInterface
{
partial void Bar[||]Bar()
}
public partial class TestClass
{
partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
void BarBar();
}
public partial class TestClass : IInterface
{
void BarBar()
}
public partial class TestClass
{
partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
protected void F[||]oo(int i)
{
// do awesome things
}
private static string Bar(string x)
{}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
string Bar(string x);
void Foo(int i);
void TestMethod();
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
public void Foo(int i)
{
// do awesome things
}
public string Bar(string x)
{}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleNonPublicEventsToInterface()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
event EventHandler Event2;
event EventHandler Event3;
}
public class TestClass : IInterface
{
public event EventHandler Event1;
public event EventHandler Event2;
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMethodToInnerInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class TestClass : TestClass.IInterface
{
private void Bar[||]Bar()
{
}
interface IInterface
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class TestClass : TestClass.IInterface
{
public void BarBar()
{
}
interface IInterface
{
void BarBar();
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public class TestClass : IInterface
{
public int th[||]is[int i]
{
get => j = value;
}
private static void BarBar()
{}
protected static event EventHandler event1, event2;
internal static int Foo
{
get; set;
}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
int this[int i] { get; }
int Foo { get; set; }
event EventHandler event1;
event EventHandler event2;
void BarBar();
}
public class TestClass : IInterface
{
public int this[int i]
{
get => j = value;
}
public void BarBar()
{}
public event EventHandler event1;
public event EventHandler event2;
public int Foo
{
get; set;
}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMethodWithAbstractOptionToClassViaDialog()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
namespace PushUpTest
{
public abstract class Base
{
public abstract void TestMethod();
}
public class TestClass : Base
{
public override void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullAbstractMethodToClassViaDialog()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public abstract class TestClass : Base
{
public abstract void TestMeth[||]od();
}
}";
var expected = @"
namespace PushUpTest
{
public abstract class Base
{
public abstract void TestMethod();
}
public abstract class TestClass : Base
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleEventsToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event1;
private static event EventHandler Event3;
private static event EventHandler Event4;
}
public class Testclass2 : Base2
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleAbstractEventsToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public abstract class Testclass2 : ITest
{
protected abstract event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event1;
event EventHandler Event3;
event EventHandler Event4;
}
public abstract class Testclass2 : ITest
{
public abstract event EventHandler Event1;
public abstract event EventHandler Event3;
public abstract event EventHandler Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullAbstractEventToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public abstract class Testclass2 : Base2
{
private static abstract event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class Base2
{
private static abstract event EventHandler Event3;
}
public abstract class Testclass2 : Base2
{
private static abstract event EventHandler Event1, Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicEventToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event3;
}
public class Testclass2 : ITest
{
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullSingleNonPublicEventToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public abstract class TestClass2 : ITest
{
protected event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event3;
}
public abstract class TestClass2 : ITest
{
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
}
public class TestClass : IInterface
{
public event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullFieldsToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
public int i, [||]j = 10, k = 100;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
public int i;
public int j = 10;
public int k = 100;
}
public class Testclass2 : Base2
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private double Test[||]Property => 2.717;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { get; }
}
public class Testclass2 : ITest
{
public readonly double TestProperty => 2.717;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private double Test[||]Property
{
get;
set;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { get; set; }
}
public class Testclass2 : ITest
{
public double TestProperty
{
get;
set;
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private static double Test[||]Property
{
set;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { set; }
}
public class Testclass2 : ITest
{
public double Test[||]Property
{
set;
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption()
{
var testText = @"
abstract class B
{
}
class D : B
{
int [||]X => 7;
}";
var expected = @"
abstract class B
{
private abstract int X { get; }
}
class D : B
{
override int X => 7;
}";
await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class Base2
{
private abstract event EventHandler Event3;
}
public class Testclass2 : Base2
{
private event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption()
{
var testText = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
}
public class TestClass : BaseClass
{
public event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class BaseClass
{
public abstract event EventHandler Event1;
}
public class TestClass : BaseClass
{
public override event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1);
}
#endregion Dialog
#region Selections and caret position
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestArgsIsPartOfHeader()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[Test2]
void C([||])
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
[Test2]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretBeforeAttributes()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[||][Test]
[Test2]
void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
[Test2]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretBetweenAttributes()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||][Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes1()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[|void C()
{
}|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]
void C()
{
}|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes3()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test][|
void C()
{
}
|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringInAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[[||]Test]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectionAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]
[Test2]|]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretInAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[[||]Test]
[Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretBetweenAttributeLists()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||][Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectionAttributeList2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]|]
[Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]|]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLocAfterAttributes1()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||]void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLocAfterAttributes2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
// Comment1
[Test2]
// Comment2
[||]void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
// Comment1
[Test2]
// Comment2
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLoc1()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[||]void C()
{
}
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelection()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[|void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{ [|
// Comment1
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
// Comment1
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments2()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[|/// <summary>
/// Test
/// </summary>
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
/// <summary>
/// Test
/// </summary>
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments3()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
/// <summary>
[|/// Test
/// </summary>
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
/// <summary>
/// Test
/// </summary>
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
#endregion
}
}
| davkean/roslyn | src/EditorFeatures/CSharpTest/PullMemberUp/CSharpPullMemberUpTests.cs | C# | apache-2.0 | 65,448 | [
30522,
1013,
1013,
7000,
2000,
1996,
1012,
5658,
3192,
2104,
2028,
2030,
2062,
10540,
1012,
1013,
1013,
1996,
1012,
5658,
3192,
15943,
2023,
5371,
2000,
2017,
2104,
1996,
10210,
6105,
1012,
1013,
1013,
2156,
1996,
6105,
5371,
1999,
1996,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package com.wabbit.libraries;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
} | DobrinAlexandru/Wabbit-Messenger---android-client | Wabbit/src/com/wabbit/libraries/Installation.java | Java | mit | 1,373 | [
30522,
7427,
4012,
1012,
11333,
10322,
4183,
1012,
8860,
1025,
12324,
11924,
1012,
4180,
1012,
6123,
1025,
12324,
9262,
1012,
22834,
1012,
5371,
1025,
12324,
9262,
1012,
22834,
1012,
5371,
5833,
18780,
21422,
1025,
12324,
9262,
1012,
22834,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript (c) Chris Veness 2002-2014 / MIT Licence */
/* */
/* - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html */
/* http://csrc.nist.gov/groups/ST/toolkit/examples.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* jshint node:true *//* global define, escape, unescape */
'use strict';
/**
* SHA-1 hash function reference implementation.
*
* @namespace
*/
var Sha1 = {};
/**
* Generates SHA-1 hash of string.
*
* @param {string} msg - (Unicode) string to be hashed.
* @returns {string} Hash of msg as hex character string.
*/
Sha1.hash = function(msg) {
// convert string to UTF-8, as SHA only deals with byte-streams
msg = msg.utf8Encode();
// constants [§4.2.1]
var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 ];
// PREPROCESSING
msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
// convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
var N = Math.ceil(l/16); // number of 16-integer-blocks required to hold 'l' ints
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) { // encode 4 chars per integer, big-endian encoding
M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
(msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
} // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
}
// add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
// note: most significant word would be (len-1)*8 >>> 32, but since JS converts
// bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]);
M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;
// set initial hash value [§5.3.1]
var H0 = 0x67452301;
var H1 = 0xefcdab89;
var H2 = 0x98badcfe;
var H3 = 0x10325476;
var H4 = 0xc3d2e1f0;
// HASH COMPUTATION [§6.1.2]
var W = new Array(80); var a, b, c, d, e;
for (var i=0; i<N; i++) {
// 1 - prepare message schedule 'W'
for (var t=0; t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) W[t] = Sha1.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
// 2 - initialise five working variables a, b, c, d, e with previous hash value
a = H0; b = H1; c = H2; d = H3; e = H4;
// 3 - main loop
for (var t=0; t<80; t++) {
var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
var T = (Sha1.ROTL(a,5) + Sha1.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
e = d;
d = c;
c = Sha1.ROTL(b, 30);
b = a;
a = T;
}
// 4 - compute the new intermediate hash value (note 'addition modulo 2^32')
H0 = (H0+a) & 0xffffffff;
H1 = (H1+b) & 0xffffffff;
H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}
return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) + Sha1.toHexStr(H2) +
Sha1.toHexStr(H3) + Sha1.toHexStr(H4);
};
/**
* Function 'f' [§4.1.1].
* @private
*/
Sha1.f = function(s, x, y, z) {
switch (s) {
case 0: return (x & y) ^ (~x & z); // Ch()
case 1: return x ^ y ^ z; // Parity()
case 2: return (x & y) ^ (x & z) ^ (y & z); // Maj()
case 3: return x ^ y ^ z; // Parity()
}
};
/**
* Rotates left (circular left shift) value x by n positions [§3.2.5].
* @private
*/
Sha1.ROTL = function(x, n) {
return (x<<n) | (x>>>(32-n));
};
/**
* Hexadecimal representation of a number.
* @private
*/
Sha1.toHexStr = function(n) {
// note can't use toString(16) as it is implementation-dependant,
// and in IE returns signed numbers when used on full words
var s="", v;
for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); }
return s;
};
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/** Extend String object with method to encode multi-byte string to utf8
* - monsur.hossa.in/2012/07/20/utf-8-in-javascript.html */
if (typeof String.prototype.utf8Encode == 'undefined') {
String.prototype.utf8Encode = function() {
return unescape( encodeURIComponent( this ) );
};
}
/** Extend String object with method to decode utf8 string to multi-byte */
if (typeof String.prototype.utf8Decode == 'undefined') {
String.prototype.utf8Decode = function() {
try {
return decodeURIComponent( escape( this ) );
} catch (e) {
return this; // invalid UTF-8? return as-is
}
};
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
if (typeof module != 'undefined' && module.exports) module.exports = Sha1; // CommonJs export
if (typeof define == 'function' && define.amd) define([], function() { return Sha1; }); // AMD | vinaymayar/maygh | src/client/util-sha1.js | JavaScript | mit | 5,625 | [
30522,
1013,
1008,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
30524,
1011,
1011,
1008,
1013,
1013,
1008,
21146,
1011,
1015,
7375,
1999,
9262,
22483,
1006,
1039,
1007,
3782,
2310,
2791,
2526,
1011,
2297,
1013,
10210,
11172,
1008,
1013,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* grid */
.mdr-columns {
display: block;
@media (--lmd) {
display: flex;
}
&.is-responsive {
@media (--md) {
display: flex;
}
}
&.is-multiline {
flex-wrap: wrap;
}
}
.mdr-column,
.mdr-tile {
flex-grow: 1;
flex-shrink: 1;
@media (--md) {
&.is-2, &.is-3, &.is-4, &.is-5, &.is-6, &.is-7, &.is-8, &.is-9, &.is-10, &.is-11 {
display: block;
width: 100%;
}
}
@media (--lmd) {
&.is-2, &.is-3, &.is-4, &.is-5, &.is-6, &.is-7, &.is-8, &.is-9, &.is-10, &.is-11 {
flex: none;
}
&.is-2 {
width: 16.66667%;
}
&.is-3 {
width: 25%;
}
&.is-4 {
width: 33.33333%;
}
&.is-5 {
width: 41.66667%;
}
&.is-6 {
width: 50%;
}
&.is-7 {
width: 58.33333%;
}
&.is-8 {
width: 66.66667%;
}
&.is-9 {
width: 75%;
}
&.is-10 {
width: 83.33333%;
}
&.is-11 {
width: 91.66667%;
}
}
}
.mdr-column {
display: block;
flex-basis: 0;
padding: 10px;
}
.mdr-tile {
display: block;
@media (--lmd) {
display: flex;
align-items: stretch;
flex-basis: auto;
min-height: min-content;
}
&.is-vertical {
flex-direction: column;
}
}
| mismith0227/wp-theme-modernize | src/css/layout/grid.css | CSS | gpl-2.0 | 1,241 | [
30522,
1013,
1008,
8370,
1008,
1013,
1012,
9108,
2099,
1011,
7753,
1063,
4653,
1024,
3796,
1025,
1030,
2865,
1006,
1011,
1011,
1048,
26876,
1007,
1063,
4653,
1024,
23951,
1025,
1065,
1004,
1012,
2003,
1011,
26651,
1063,
1030,
2865,
1006,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
---
layout: post
title: iOS Localization
date: 2014-10-25
categories: iOS
---
This post contains some of my thoughts and experiences from localizing iOS applications.
##Format specifiers
After many mistakes when localizing and having to change stuff later I've arrived at the conclusion that you should use the string format specifier (`%@`) for *everything*.
The following example should give you an idea of why.
{% highlight objc %}
NSString *format = NSLocalizedString(@"I have %d red candies.", nil);
NSString *result = [NSString stringWithFormat:format, 5];
// "I have 5 red candies".
{% endhighlight %}
There are two problems with using integer format (`%d`) here:
1. Sooner or later we might want to put something other than an integer in there, like spelling out "five" or using a fractional number like 5.5.
2. Some languages don't use decimal integers like we do. A language could theoretically use base 4, or use [different characters](http://en.wikipedia.org/wiki/Eastern_Arabic_numerals) for numbers. I'll explain how to deal with the number formatting in a second.
Had we used `%@` instead of `%d`, both of the above problems could be solved without ordering new, specific translations.
##Combining strings
Combining different localized strings is something I've seen happen every now and then.
For instance, if we already have localizations for the strings `@"Eat"` and `@"Candy"`, it could be very tempting to do something like this to reduce translation costs:
{% highlight objc %}
NSString *eat = NSLocalizedString(@"Eat", nil);
NSString *candy = NSLocalizedString(@"Candy", nil);
NSString *consumeButtonText = [NSString stringWithFormat:@"%@ %@", eat, candy];
// "Eat Candy"
{% endhighlight %}
The problem is that in some languages, the order of words will be inverted. It only gets worse if we combine several words or sentences. I recommend that you spend some more resources on adding all the possible sentences to your localization files, and the translations will be more correct.
##Formatting numbers
Each and every number presented in the UI should be formatted. This guarantees that the application displays numbers correctly even if different locales use different characters or number systems.
{% highlight objc %}
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSInteger aNumber = 74679;
NSString *formattedNumber = [formatter stringFromNumber:@(aNumber)];
{% endhighlight %}
`formattedNumber` will differ depending on the current locale:
{% highlight objc %}
// en
"74,679"
// sv
"74 679"
// ar
"٧٤٬٦٧٩"
{% endhighlight %}
Since `NSNumberFormatter` is heavy to initialize, I usually keep a few static formatters in a utility class configured for different format styles.
Formatting numbers also have other benefits, for example, not having to write code to round floats or display percentages. If you give a formatter with `NSNumberFormatterPercentageStyle` a float like `0.53467`, it will nicely output `53%`for you. (Or whatever a percentage number should look like in the current locale).
`NSNumberFormatter` really is an amazing class, and I recommend everyone to at least skim through its documentation.
##Autolayout
Autolayout is a great tool to aid us in our quests for perfect localizations. Different languages use different amount of characters to express the same things, and having UI elements automatically make room for text is a real time saver.
It's especially helpful for supporting right-to-left (RTL) languages. Every view that layouts using leading or trailing attributes will be properly laid out together with labels containing right-to-left text.
Most of the time, Autolayout takes care of everything we need for supporting RTL languages. But when something comes up that needs to be done manually (or if we don't use Autolayout at all), we can always branch code like this:
{% highlight objc %}
UIUserInterfaceLayoutDirection layoutDirection = [UIApplication sharedApplication].userInterfaceLayoutDirection;
if (layoutDirection == UIUserInterfaceLayoutDirectionRightToLeft) {
// Code to handle RTL language
}
{% endhighlight %}
| accatyyc/accatyyc.github.io | _posts/2014-10-25-ios-localization.md | Markdown | mit | 4,201 | [
30522,
1011,
1011,
1011,
9621,
1024,
2695,
2516,
1024,
16380,
2334,
3989,
3058,
1024,
2297,
1011,
2184,
1011,
2423,
7236,
1024,
16380,
1011,
1011,
1011,
2023,
2695,
3397,
2070,
1997,
2026,
4301,
1998,
6322,
2013,
2334,
6026,
16380,
5097,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*************************************************************************
Copyright (C) 2009 Grandite
This file is part of Open ModelSphere.
Open ModelSphere is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/.
You can redistribute and/or modify this particular file even under the
terms of the GNU Lesser General Public License (LGPL) as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
You should have received a copy of the GNU Lesser General Public License
(LGPL) along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/.
You can reach Grandite at:
20-1220 Lebourgneuf Blvd.
Quebec, QC
Canada G2K 2G4
or
open-modelsphere@grandite.com
**********************************************************************/
package org.modelsphere.jack.baseDb.assistant;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyVetoException;
import java.net.URL;
import java.util.*;
import javax.swing.*;
import javax.swing.border.SoftBevelBorder;
import javax.swing.event.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;
import org.modelsphere.jack.debug.Debug;
import org.modelsphere.jack.international.LocaleMgr;
public abstract class JHtmlBallonHelp extends JInternalFrame implements MouseListener,
ListSelectionListener {
private static final String kShowHelpExplorer = LocaleMgr.screen.getString("ShowHelpExplorer");
private static final String kHideHelpExplorer = LocaleMgr.screen.getString("HideHelpExplorer");
protected Vector indexList;
protected Vector indexPages;
protected Vector categoryList;
protected Vector bookList;
protected Vector htmlPagesTocList;
protected Vector vec;
protected Vector searchVector;
protected Vector titles;
protected JButton backButton = null;
protected JButton exitButton = null;
protected JButton refreshButton = null;
protected JButton forwardButton = null;
protected JButton printButton = null;
protected JButton showHideButton = null;
// protected JButton findButton = null;
protected JEditorPane baloonHelpPane;
protected JScrollPane baloonHelpView;
protected JScrollPane listScrollPane;
protected JScrollPane findListScrollPane;
protected JList list;
protected JList findList;
protected JTabbedPane tabbedPane = new JTabbedPane();
protected JTextField indexField;
protected JPanel indexPane;
protected JPanel findPane;
// protected JTextField findTextField;
protected JTextField searchTextField;
protected String keyWord = "";
protected String findTextFieldEntry = "";
protected URL helpURL;
protected URL startURL;
protected URL link;
protected URL[] historyUrl = new URL[10];
protected URL currentURL;
protected int i = 0;
protected int numberOfEntries = 0;
protected int[] pos = new int[400];
protected int select = 0;
protected int x = 0;
protected int j = 0;
protected String helpRootDirectory;
public JHtmlBallonHelp(String helpRootDirectory) {
super(LocaleMgr.screen.getString("help"), true, true, true, true); // resizable,
// closable,
// maximizable,
// iconifiable
this.helpRootDirectory = helpRootDirectory;
getIndexPages();
getIndexEntries();
// //////Table Of Contents
// Create the nodes.
DefaultMutableTreeNode top = new DefaultMutableTreeNode(getRootNodeName());
createNodes(top);
// Create a tree that allows one selection at a time.
JTree tree = new JTree(top);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer
.setClosedIcon(new ImageIcon(LocaleMgr.class.getResource("resources/booknode.gif")));
renderer.setOpenIcon(new ImageIcon(LocaleMgr.class.getResource("resources/opennode.gif")));
renderer.setLeafIcon(new ImageIcon(LocaleMgr.class.getResource("resources/leafnode.gif")));
tree.setCellRenderer(renderer);
// Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) (e.getPath()
.getLastPathComponent());
Object nodeInfo = node.getUserObject();
if (node.isLeaf()) {
BookInfo book = (BookInfo) nodeInfo;
displayURL(book.bookURL, true);
} else {
displayURL(helpURL, false);
}
}
});
// Create the scroll pane and add the tree to it.
JScrollPane treeView = new JScrollPane(tree);
// //end of TOC
// ///INDEX PANE START
// /Index TextField
indexField = new JTextField(20);
indexField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
synchIndexFieldList();
}
});
// List
list = new JList(indexList);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
listScrollPane = new JScrollPane(list);
listScrollPane.setMinimumSize(new Dimension(100, 50));
// Index Panel
indexPane = new JPanel(new BorderLayout());
indexPane.add(indexField, BorderLayout.NORTH);
indexPane.add(listScrollPane, BorderLayout.CENTER);
// /////INDEX PANE STOP
// Find Pane
// ///Find TextField
// findTextField = new JTextField();
// findTextField.setMaximumSize (new Dimension(100, 20));
// findTextField.setAlignmentY (-45);
// findTextField.setToolTipText("Find in Document"); // NOT LOCALIZABLE
// /Search TextField
searchTextField = new JTextField();
searchTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
JSearch search = new JSearch(searchTextField.getText(),
JHtmlBallonHelp.this.helpRootDirectory);
searchVector = search.getSearchResultVector();
titles = search.getTitle();
findList.setListData(titles);
Debug.trace(titles);
}
});
// find result list
findList = new JList();
findList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
findList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
JList theList = (JList) e.getSource();
if (theList.isSelectionEmpty()) {
helpURL = getHtmlFile("welcome.html"); // NOT LOCALIZABLE -
// link
} else {
int index = theList.getSelectedIndex();
helpURL = ((URL) searchVector.elementAt(index));
displayURL(helpURL, true);
}
}
});
findListScrollPane = new JScrollPane(findList);
findListScrollPane.setMinimumSize(new Dimension(100, 50));
// find panel
findPane = new JPanel(new BorderLayout());
findPane.add(findListScrollPane, BorderLayout.CENTER);
findPane.add(searchTextField, BorderLayout.NORTH);
// Find Pane
// /CONSTRUCTING HELP FRAME
// THE Toolbar
JToolBar toolBar = new JToolBar();
addButtons(toolBar);
// toolBar.add (findTextField);
toolBar.setFloatable(false);
// THE Tab Pane
tabbedPane.setBorder(BorderFactory.createEmptyBorder(6, 8, 6, 8));
tabbedPane.addTab(LocaleMgr.screen.getString("TOC"), treeView);
tabbedPane.addTab(LocaleMgr.screen.getString("Index"), indexPane);
tabbedPane.addTab(LocaleMgr.screen.getString("Find"), findPane);
tabbedPane.setSelectedIndex(0);
// THE HTML Viewer
baloonHelpPane = new JEditorPane();
baloonHelpPane.setBorder(BorderFactory.createEmptyBorder(6, 8, 6, 8));
baloonHelpPane.setEditable(false);
baloonHelpPane.addHyperlinkListener(new HyperlinkListener() {
public final void hyperlinkUpdate(HyperlinkEvent e) {
HyperlinkEvent.EventType type = e.getEventType();
if (type == HyperlinkEvent.EventType.ENTERED)
baloonHelpPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
else if (type == HyperlinkEvent.EventType.EXITED)
baloonHelpPane.setCursor(Cursor.getDefaultCursor());
else if (type == HyperlinkEvent.EventType.ACTIVATED) {
link = e.getURL();
displayURL(link, true);
}
}
});
baloonHelpView = new JScrollPane(baloonHelpPane);
baloonHelpView.setPreferredSize(new Dimension(400, 500));
initBaloonHelp();
Container contentPane = getContentPane();
contentPane.add(toolBar, BorderLayout.NORTH);
contentPane.add(tabbedPane, BorderLayout.WEST);
contentPane.add(baloonHelpView, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
/**
* To close the window, you must call this method (do not call dispose).
*/
public final void close() {
try {
setClosed(true);
} catch (PropertyVetoException e) {
} // should not happen
}
// /CONSTRUCTING HELP FRAME END
private URL getHtmlFile(String fileName) {
URL helpURL;
String pattern;
if (fileName.endsWith(".html")) // NOT LOCALIZABLE
pattern = "File:{0}/{1}"; // NOT LOCALIZABLE
else
pattern = "File:{0}/{1}.html"; // NOT LOCALIZABLE
String file = java.text.MessageFormat.format(pattern, new Object[] { helpRootDirectory,
fileName });
try {
helpURL = new URL(file);
} catch (java.net.MalformedURLException e) {
org.modelsphere.jack.debug.Debug.trace("getHtmlFile bad URL:" + file); // NOT LOCALIZABLE
helpURL = null;
}
return helpURL;
}
// public URL getResource(String resName){
// return classForGetResource.getResource(resName);
// }
// /INDEX PROPERTIES
public void synchIndexFieldList() {
int j = 0;
j = numberOfEntries / 2;
String s = indexField.getText();
for (int h = 0; h < j; h++) {
String indexEntry = ((String) indexList.elementAt(h));
String indexURL = ((String) indexPages.elementAt(h));
if (indexEntry.equals(s)) {
list.setSelectedIndex(h);
helpURL = getHtmlFile(indexURL);
displayURL(helpURL, false);
break;
}
}
}
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
JList theList = (JList) e.getSource();
if (theList.isSelectionEmpty()) {
helpURL = getHtmlFile("welcome"); // NOT LOCALIZABLE
} else {
int index = theList.getSelectedIndex();
String page = ((String) indexPages.elementAt(index));
helpURL = getHtmlFile(page);
displayURL(helpURL, true);
}
}
protected Vector parseList(String indexList) {
Vector v = new Vector(10);
StringTokenizer tokenizer = new StringTokenizer(indexList, ","); // NOT
// LOCALIZABLE
while (tokenizer.hasMoreTokens()) {
String index = tokenizer.nextToken();
v.addElement(index);
numberOfEntries++;
}
return v;
}
public void getIndexEntries() {
// getting the list for the index
ResourceBundle indexResource;
try {
indexResource = ResourceBundle.getBundle(getHelpPackageName() + "index"); // NOT LOCALIZABLE
String indexEntry = indexResource.getString("index"); // NOT
// LOCALIZABLE
indexList = parseList(indexEntry);
} catch (MissingResourceException e) {
Debug.trace("Unable to parse properties file.");
return;
}
}
public void getIndexPages() {
// getting the corresponding html page for the selected index
ResourceBundle indexPagesResource;
try {
indexPagesResource = ResourceBundle.getBundle(getHelpPackageName() + "html"); // NOT LOCALIZABLE
String indexPage = indexPagesResource.getString("html"); // NOT
// LOCALIZABLE
indexPages = parseList(indexPage);
} catch (MissingResourceException e) {
Debug.trace("Unable to parse properties file.");
return;
}
}
// ///INDEX PROPERTIES END
protected final void addButtons(JToolBar toolBar) {
// Exit button
exitButton = new JButton(new ImageIcon(LocaleMgr.class
.getResource("resources/exitover.gif")));
exitButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/exitover.gif")));
exitButton.setRolloverEnabled(true);
exitButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/exitover.gif")));
exitButton.setToolTipText(LocaleMgr.screen.getString("ExitHelp"));
exitButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
exitButton.setBorderPainted(false);
exitButton.setFocusPainted(false);
exitButton.addMouseListener(this);
exitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
toolBar.add(exitButton);
// Back button
backButton = new JButton(new ImageIcon(LocaleMgr.class
.getResource("resources/backover.gif")));
backButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/backover.gif")));
backButton.setRolloverEnabled(true);
backButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/backover.gif")));
backButton.setToolTipText(LocaleMgr.screen.getString("Back"));
backButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
backButton.setBorderPainted(false);
backButton.setFocusPainted(false);
backButton.setEnabled(false);
backButton.addMouseListener(this);
backButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
goBack();
}
});
toolBar.add(backButton);
// forward button
forwardButton = new JButton(new ImageIcon(LocaleMgr.class
.getResource("resources/forwardover.gif")));
forwardButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/forwardover.gif")));
forwardButton.setRolloverEnabled(true);
forwardButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/forwardover.gif")));
forwardButton.setToolTipText(LocaleMgr.screen.getString("Forward"));
forwardButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
forwardButton.setBorderPainted(false);
forwardButton.setFocusPainted(false);
forwardButton.setEnabled(false);
forwardButton.addMouseListener(this);
forwardButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
goNext();
}
});
toolBar.add(forwardButton);
// refresh button
refreshButton = new JButton(new ImageIcon(LocaleMgr.class
.getResource("resources/refresh.gif")));
refreshButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/refresh.gif")));
refreshButton.setRolloverEnabled(true);
refreshButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/refresh.gif")));
refreshButton.setToolTipText(LocaleMgr.screen.getString("ReloadCurrentDoc"));
refreshButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
refreshButton.setBorderPainted(false);
refreshButton.setFocusPainted(false);
refreshButton.addMouseListener(this);
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
reload();
}
});
toolBar.add(refreshButton);
// Print button
printButton = new JButton(new ImageIcon(LocaleMgr.class.getResource("resources/print.gif")));
printButton
.setPressedIcon(new ImageIcon(LocaleMgr.class.getResource("resources/print.gif")));
printButton.setRolloverEnabled(true);
printButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/print.gif")));
printButton.setToolTipText(LocaleMgr.screen.getString("PrintCurrentDocument"));
printButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
printButton.setBorderPainted(false);
printButton.setFocusPainted(false);
printButton.addMouseListener(this);
printButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
print();
}
});
toolBar.add(printButton);
// Show button
showHideButton = new JButton(new ImageIcon(LocaleMgr.class
.getResource("resources/hide.gif")));
showHideButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/hide.gif")));
showHideButton.setRolloverEnabled(true);
showHideButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/hide.gif")));
showHideButton.setToolTipText(kHideHelpExplorer);
showHideButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
showHideButton.setBorderPainted(false);
showHideButton.setFocusPainted(false);
showHideButton.addMouseListener(this);
showHideButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
if (tabbedPane.isVisible()) {
showHideToc(true);
} else {
showHideToc(false);
}
}
});
toolBar.add(showHideButton);
/*
* toolBar.addSeparator(new Dimension(65,0));
*
* //Find button findButton = new JButton(new
* ImageIcon(Application.class.getResource("resources/find.gif"))); // NOT LOCALIZABLE
* findButton.setPressedIcon(new
* ImageIcon(Application.class.getResource("resources/find.gif"))); // NOT LOCALIZABLE
* findButton.setRolloverEnabled(true); findButton.setRolloverIcon(new
* ImageIcon(Application.class.getResource("resources/find.gif"))); // NOT LOCALIZABLE
* findButton.setToolTipText("Show Next Occurence"); // NOT LOCALIZABLE
* findButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
* findButton.setBorderPainted(false); findButton.setFocusPainted(false);
* findButton.addMouseListener(this); findButton.addActionListener(new
* java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) {
* selectOccurence(); } }); toolBar.add(findButton);
*/
}
// //////////////////////////////////////////////
// MouseListener Support
//
public void mouseClicked(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
JButton button = ((JButton) e.getSource());
if (!button.isEnabled()) {
button.setBorderPainted(false);
}
}
}
public void mousePressed(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
JButton button = ((JButton) e.getSource());
if (button.isEnabled()) {
button.setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED));
}
}
}
public void mouseReleased(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
JButton button = ((JButton) e.getSource());
button.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
}
}
public void mouseEntered(MouseEvent e) {
JButton button = ((JButton) e.getSource());
if (button.isEnabled()) {
button.setBorderPainted(true);
}
}
public void mouseExited(MouseEvent e) {
JButton button = ((JButton) e.getSource());
button.setBorderPainted(false);
}
// //////////////////////////////////////////////
// MouseListener Support END
//
// ////Navigation Methods
// contructing url array for Back and Forward buttons
protected final void addStack(URL u) {
i++;
historyUrl[i] = u;
backButton.setEnabled(true);
if (i == 9) {
for (int j = 0; j <= 8; j++) {
historyUrl[j] = historyUrl[j + 1];
}
i--;
}
}
// reload
protected final void reload() {
helpURL = getHtmlFile("empty"); // NOT LOCALIZABLE
URL reloadURL = currentURL;
displayURL(helpURL, false);
displayURL(reloadURL, false);
}
// print
protected final void print() {
PrintJob job = Toolkit.getDefaultToolkit().getPrintJob(
(Frame) SwingUtilities.getAncestorOfClass(Frame.class, this),
LocaleMgr.misc.getString("Help"), null);
if (job != null) {
Graphics pg = job.getGraphics();
pg.setFont(new Font("arial", Font.PLAIN, 10)); // NOT LOCALIZABLE
baloonHelpPane.print(pg);
pg.dispose();
job.end();
}
}
// forward
public final void goNext() {
try {
i++;
displayURL(historyUrl[i], false);
backButton.setEnabled(true);
if (historyUrl[i + 1] == null) {
forwardButton.setEnabled(false);
}
if (i == 8) {
forwardButton.setEnabled(false);
}
} catch (ArrayIndexOutOfBoundsException o) {
i = i - 1;
}
}
// back
public final void goBack() {
try {
i--;
displayURL(historyUrl[i], false);
forwardButton.setEnabled(true);
if (i == 0) {
backButton.setEnabled(false);
} else {
}
} catch (ArrayIndexOutOfBoundsException o) {
i = i + 1;
}
}
// Showing or Hiding the TabPane (for the show/hide button)
public final void showHideToc(boolean visible) {
if (visible == true) {
tabbedPane.setVisible(false);
showHideButton
.setIcon(new ImageIcon(LocaleMgr.class.getResource("resources/show.gif")));
showHideButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/show.gif")));
showHideButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/show.gif")));
showHideButton.setToolTipText(kShowHelpExplorer);
}
if (visible == false) {
tabbedPane.setVisible(true);
showHideButton
.setIcon(new ImageIcon(LocaleMgr.class.getResource("resources/hide.gif")));
showHideButton.setPressedIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/hide.gif")));
showHideButton.setRolloverIcon(new ImageIcon(LocaleMgr.class
.getResource("resources/hide.gif")));
showHideButton.setToolTipText(kHideHelpExplorer);
}
}
// ////Navigation Methods END
// //TOC PROPERTIES
protected Vector parseToc(String tocList) {
Vector v = new Vector(10);
StringTokenizer tokenizer = new StringTokenizer(tocList, ","); // NOT
// LOCALIZABLE
while (tokenizer.hasMoreTokens()) {
String index = tokenizer.nextToken();
v.addElement(index);
}
return v;
}
// populating the TOC via properties files
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode book = null;
ResourceBundle TocCategoryResource;
ResourceBundle TocBookResource;
ResourceBundle TocHtmlPagesResource;
// properties for the nodes
TocCategoryResource = ResourceBundle.getBundle(getHelpPackageName() + "category"); // NOT LOCALIZABLE
// properties for the entries for each nodes
TocBookResource = ResourceBundle.getBundle(getHelpPackageName() + "book"); // NOT LOCALIZABLE
// properties for the html pages corresponding to each node entries
TocHtmlPagesResource = ResourceBundle.getBundle(getHelpPackageName() + "htmlPagesToc"); // NOT LOCALIZABLE
for (int c = 0; c < 30; c++)
try {
String bookNode = ("book" + c); // NOT LOCALIZABLE
String bookCategory = ("category" + c); // NOT LOCALIZABLE
String bookHtmlPage = ("html" + c); // NOT LOCALIZABLE
String tocCategory = TocCategoryResource.getString(bookCategory);
String tocBook = TocBookResource.getString(bookNode);
String tocHtmlPage = TocHtmlPagesResource.getString(bookHtmlPage);
categoryList = parseToc(tocCategory);
// adding nodes
category = new DefaultMutableTreeNode(tocCategory);
top.add(category);
// adding entries for each nodes
bookList = parseToc(tocBook);
htmlPagesTocList = parseToc(tocHtmlPage);
for (int b = 0; b < bookList.size(); b++) {
String bookEntry = ((String) bookList.elementAt(b));
String bookHtml = ((String) htmlPagesTocList.elementAt(b));
book = new DefaultMutableTreeNode(
new BookInfo(bookEntry, getHtmlFile(bookHtml)));
category.add(book);
}
if (bookCategory == null)
break;
} catch (MissingResourceException e) {
break;
}
}
// Find methods
// Parsing the EditorPane
protected Vector parseText(String input) {
Vector v = new Vector(10);
StringTokenizer tokenizer = new StringTokenizer(input, " "); // NOT
// LOCALIZABLE
while (tokenizer.hasMoreTokens()) {
String index = tokenizer.nextToken();
v.addElement(index);
}
return v;
}
// Returns the position of the first letter of
// the word specified in the FindTextField.
public final void getPosition(String entry) {
try {
Document doc = baloonHelpPane.getDocument();
String docString = doc.getText(0, doc.getLength());
vec = parseText(docString);
for (int v = 0; v < vec.size(); v++) {
String pageEntry = ((String) vec.elementAt(v));
if (pageEntry.equalsIgnoreCase(entry)) {
pos[j] = docString.indexOf(pageEntry, select + entry.length());
j++;
select = pos[j - 1];
}
}
j = 0;
} catch (BadLocationException b) {
}
}
/*
* //Select the occurence from the word //specified in the FindTextField protected final void
* selectOccurence(){ findTextFieldEntry = findTextField.getText (); if
* (keyWord.equals(findTextFieldEntry)){ baloonHelpPane.select (pos[x], pos[x] +
* findTextFieldEntry.length()); x++; } else{ keyWord = findTextFieldEntry; for (int a=0;
* a<pos.length; a++) pos[a]=0; getPosition(keyWord); baloonHelpPane.select (pos[0], pos[0] +
* findTextFieldEntry.length()); x=1; } if (pos[x]==0){ x=0; } }
*/
private void initBaloonHelp() {
try {
helpURL = getHtmlFile("welcome"); // NOT LOCALIZABLE
baloonHelpPane.setPage(helpURL);
historyUrl[i] = helpURL;
currentURL = helpURL;
} catch (Exception e) {
}
}
public final void display(Object helpObjectKey) {
displayURL(getHtmlFile(getURLForObjectKey(helpObjectKey)), true);
}
private void displayURL(URL nUrl, boolean stack) {
try {
baloonHelpPane.setPage(nUrl);
currentURL = nUrl;
if (stack)
addStack(nUrl);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, LocaleMgr.message.getString("helpnotfound"));
}
}
// //////////////////////////////////////
// Abstract Methods
//
public abstract String getHelpPackageName();
public abstract String getRootNodeName();
public abstract String getURLForObjectKey(Object helpObjectKey);
//
// End of Abstract Method
// //////////////////////////////////////
}
| DarioGT/OMS-PluginXML | org.modelsphere.jack/src/org/modelsphere/jack/baseDb/assistant/JHtmlBallonHelp.java | Java | gpl-3.0 | 31,986 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Pennisetum aureum Link SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Pennisetum/Pennisetum glaucum/ Syn. Pennisetum aureum/README.md | Markdown | apache-2.0 | 179 | [
30522,
1001,
9502,
5562,
11667,
8740,
2890,
2819,
4957,
2427,
1001,
1001,
1001,
1001,
3570,
10675,
1001,
1001,
1001,
1001,
2429,
2000,
1996,
10161,
1997,
2166,
1010,
3822,
2254,
2249,
1001,
1001,
1001,
1001,
2405,
1999,
19701,
1001,
1001,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace tronpon.Pages {
public partial class registreren {
/// <summary>
/// tbUname control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbUname;
/// <summary>
/// reqFieldValidUname control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator reqFieldValidUname;
/// <summary>
/// RegexValidUname control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RegularExpressionValidator RegexValidUname;
/// <summary>
/// tbMail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbMail;
/// <summary>
/// reqFieldValidMail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator reqFieldValidMail;
/// <summary>
/// RegexValidMail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RegularExpressionValidator RegexValidMail;
/// <summary>
/// tbPass control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbPass;
/// <summary>
/// reqFieldValidPass control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator reqFieldValidPass;
/// <summary>
/// tbPassRepeat control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbPassRepeat;
/// <summary>
/// reqFieldValidPassRepeat control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator reqFieldValidPassRepeat;
/// <summary>
/// ComparePass control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator ComparePass;
/// <summary>
/// btnRegister control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnRegister;
}
}
| chaoskie/Project_SE22 | tronpon/tronpon/Pages/registreren.aspx.designer.cs | C# | mit | 4,489 | [
30522,
1013,
1013,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
---
copyright:
years: 2016
lastupdated: "2016-10-10"
---
{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}
# 빌드팩 지원 구문
{: #buildpack_support_statement}
## 기본 제공 IBM 빌드팩
{: #built-in_ibm_buildpacks}
[Liberty for Java](/docs/runtimes/liberty/index.html), [SDK for Node.js](/docs/runtimes/nodejs/index.html) 및 [ASP.NET Core](/docs/runtimes/dotnet/index.html)의 경우, IBM은 두 버전(n 및 n - 1)을 지원합니다(예: IBM Liberty Buildpack v1.22 및 IBM Liberty Buildpack v1.21).
각 빌드팩은 그에 해당하는 런타임의 주 버전을 필요에 따라 하나 이상 제공하고 지원합니다(예: IBM SDK, Java Technology Edition 버전 7 릴리스 1 및 버전 8). 빌드팩은 일반적으로 한 달에 한 번 사용 가능한 런타임의 최신 부 버전으로 새로 고쳐집니다.
[IBM Bluemix Runtime for Swift](/docs/runtimes/swift/index.html)의 경우 IBM은 [Swift.org](http://swift.org)에서 사용 가능한 Swift의 최신 버전과 일치하는 빌드팩에 대한 지원을 제공합니다. 빌드팩에 대한 업데이트는 사용 가능한 최신 Swift 릴리스 버전과 일치합니다.
{{site.data.keyword.Bluemix_notm}}에서 현재 지원되는 기본 제공 IBM 빌드팩의 어느 버전에 대해서든 문제점을 보고할 수 있지만, 최신 버전에 대해 해당 문제점을 확인해야 합니다. 결함이 발견되면 IBM은 이후 레벨의 런타임 및 해당 빌드팩에서 수정사항을 제공합니다. IBM은 이전 주 버전 및 부 버전(N-1, n-1)에 대해서는 수정사항을 제공하지 않습니다. IBM은 IBM 빌드팩을 사용하는 경우에도(예를 들어, Liberty 빌드팩이 있는 Open JDK를 사용하는 경우) 커뮤니티 런타임에 대한 지원은 제공하지 않습니다. 이러한 커뮤니티 런타임은 아래의 "기본 제공 커뮤니티 빌드팩"과 동일한 지원 정책을 따릅니다.
## 기본 제공 커뮤니티 빌드팩
{: #built-in_community_buildpacks}
Cloud Foundry 커뮤니티에서는 다음 기본 제공 커뮤니티 빌드팩을 제공합니다.
* [Java](/docs/runtimes/tomcat/index.html)
* [Node.js](https://github.com/cloudfoundry/nodejs-buildpack)
* [PHP](/docs/runtimes/php/index.html)
* [Ruby](/docs/runtimes/ruby/index.html)
* [Python](/docs/runtimes/python/index.html)
* [Go](/docs/runtimes/go/index.html)
{{site.data.keyword.Bluemix_notm}}를 새 버전의 Cloud Foundry로 업그레이드하면 이러한 빌드팩이 업데이트됩니다. {{site.data.keyword.Bluemix_notm}}에서 발생하는 이러한 런타임 관련 문제점을 IBM에 보고할 수 있으며 IBM에서는 {{site.data.keyword.Bluemix_notm}}가 문제점의 원인인지 판별하는 데 도움을 줍니다. {{site.data.keyword.Bluemix_notm}} 관련 문제점인 경우 IBM은 수정사항을 제공하지만, 빌드팩 또는 런타임 자체의 결함인 경우 IBM은 적절한 커뮤니티에 결함을 보고하는 데 도움을 줍니다. IBM은 이러한 빌드팩 및 런타임에 대한 수정사항은 제공하지 않습니다.
## 외부 빌드팩
{: #external_buildpacks}
외부 빌드팩에 대해서는 IBM에서 지원을 제공하지 않습니다. 지원을 원하는 경우 Cloud Foundry 커뮤니티에 문의해야 합니다.
| patsmith-ibm/docs | manageapps/nl/ko/buildpackSupport.md | Markdown | apache-2.0 | 3,353 | [
30522,
1011,
1011,
1011,
9385,
1024,
2086,
1024,
2355,
2197,
6279,
13701,
2094,
1024,
1000,
2355,
1011,
2184,
1011,
2184,
1000,
1011,
1011,
1011,
1063,
1024,
2460,
6155,
2278,
1024,
1012,
2460,
6155,
2278,
1065,
1063,
1024,
2047,
1035,
33... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# frozen_string_literal: true
require 'spec_helper'
describe Tsubaki::MyNumber do
describe '.rand' do
it 'generates valid random my number' do
n = Tsubaki::MyNumber.rand
expect(Tsubaki::MyNumber.new(n, strict: true).valid?).to be_truthy
end
end
describe '.calc_check_digit' do
context 'given invalid digits' do
[
nil,
'12345678901X',
'5678-1111-9018'
].each do |n|
describe n.to_s do
it 'raises RuntimeError' do
expect {
Tsubaki::MyNumber.calc_check_digit(n)
}.to raise_error(RuntimeError)
end
end
end
end
context 'given valid digits' do
subject { Tsubaki::MyNumber.calc_check_digit(digits) }
describe '37296774233' do
let(:digits) { '37296774233' }
it { is_expected.to eq 8 }
end
describe '29217589598' do
let(:digits) { '29217589598' }
it { is_expected.to eq 2 }
end
end
end
describe '#valid?' do
subject { Tsubaki::MyNumber.new(digits, options).valid? }
context 'when digits no options are specified' do
let(:options) { {} }
context 'given the valid my numbers' do
%w[
123456789012
987654321098
112233445566
].each do |n|
describe n.to_s do
let(:digits) { n }
it { is_expected.to be_truthy }
end
end
end
context 'given the invalid my numbers' do
[
nil,
'12345678901X',
'5678-1111-9018'
].each do |n|
describe n.to_s do
let(:digits) { n }
it { is_expected.to be_falsy }
end
end
end
end
context 'when digits contains divider & not strict mode' do
let(:options) { { divider: '-', strict: false } }
context 'given the valid my numbers' do
%w[
123456789012
9876-5432-1098
112233--445566
].each do |n|
describe n.to_s do
let(:digits) { n }
it { is_expected.to be_truthy }
end
end
end
context 'given the invalid my numbers' do
[
nil,
'0234-5678-XXXX',
'5678-9018'
].each do |n|
describe n.to_s do
let(:digits) { n }
it { is_expected.to be_falsy }
end
end
end
end
context 'when digits contains divider & strict mode' do
let(:options) { { divider: '-', strict: true } }
context 'given the valid my numbers' do
%w[
873321641958
2633-4829-1158
491131--223718
].each do |n|
describe n.to_s do
let(:digits) { n }
it { is_expected.to be_truthy }
end
end
end
context 'given the invalid my numbers' do
[
nil,
'0234-5678-XXXX',
'5678-9018',
'123456789012',
'9876-5432-1098',
'112233--445566'
].each do |n|
describe n.to_s do
let(:digits) { n }
it { is_expected.to be_falsy }
end
end
end
end
end
describe '#valid_pattern?' do
subject { Tsubaki::MyNumber.new(digits, {}).valid_pattern? }
context 'given the valid pattern my numbers' do
%w[
023456789013
123456789018
333333333333
].each do |n|
describe n.to_s do
let(:digits) { n }
it 'should be valid' do
is_expected.to be_truthy
end
end
end
end
context 'given the invalid my numbers' do
%w[
12345678901
12345678901X
1234567890123
].each do |n|
describe n.to_s do
let(:digits) { n }
it 'should be invalid' do
is_expected.to be_falsy
end
end
end
end
end
describe '#valid_check_digit?' do
subject { Tsubaki::MyNumber.new(digits, {}).valid_check_digit? }
context 'given the valid my numbers' do
%w[
185672239885
176521275740
654629853731
].each do |n|
describe n.to_s do
let(:digits) { n }
it 'should be valid' do
is_expected.to be_truthy
end
end
end
end
context 'given the invalid my numbers' do
%w[
185672239886
176521275741
654629853732
].each do |n|
describe n.to_s do
let(:digits) { n }
it 'should be invalid' do
is_expected.to be_falsy
end
end
end
end
end
end
| kakipo/tsubaki | spec/tsubaki/my_number_spec.rb | Ruby | mit | 4,714 | [
30522,
1001,
7708,
1035,
5164,
1035,
18204,
1024,
2995,
5478,
1005,
28699,
1035,
2393,
2121,
1005,
6235,
24529,
19761,
3211,
1024,
1024,
2026,
19172,
5677,
2079,
6235,
1005,
1012,
14566,
1005,
2079,
2009,
1005,
19421,
9398,
6721,
2026,
2193... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
.configuration-root {
flex: 1;
padding: 20px;
}
.configuration-section {
margin-bottom: 40px;
}
| earaujoassis/watchman | web/components/Configuration/style.css | CSS | mit | 103 | [
30522,
1012,
9563,
1011,
7117,
1063,
23951,
1024,
1015,
1025,
11687,
4667,
1024,
2322,
2361,
2595,
1025,
1065,
1012,
9563,
1011,
2930,
1063,
7785,
1011,
3953,
1024,
2871,
2361,
2595,
1025,
1065,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#--
# Copyleft meh. [http://meh.paranoid.pk | meh@paranoici.org]
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
# of conditions and the following disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY meh ''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 meh 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.
#
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied.
#++
module FFI
typedef :ushort, :Rotation
typedef :ushort, :SizeID
typedef :ushort, :SubpixelOrder
typedef :ushort, :Connection
typedef :ushort, :XRandrRotation
typedef :ushort, :XRandrSizeID
typedef :ushort, :XRandrSubpixelOrder
typedef :ulong, :XRandrModeFlags
end
| meh/ruby-x11 | lib/X11/extensions/randr/c.rb | Ruby | lgpl-3.0 | 1,786 | [
30522,
1001,
1011,
1011,
1001,
6100,
2571,
6199,
2033,
2232,
1012,
1031,
8299,
1024,
1013,
1013,
2033,
2232,
1012,
19810,
1012,
1052,
2243,
1064,
2033,
2232,
1030,
11498,
3630,
28775,
1012,
8917,
1033,
1001,
1001,
25707,
1998,
2224,
1999,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# -*- coding:utf-8 -*-
import unittest, sys, os
sys.path[:0] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from saklient.cloud.enums.eserverinstancestatus import EServerInstanceStatus
class TestEnum(unittest.TestCase):
def test_should_be_defined(self):
self.assertEqual(EServerInstanceStatus.UP, "up");
self.assertEqual(EServerInstanceStatus.DOWN, "down");
def test_should_be_compared(self):
self.assertEqual(EServerInstanceStatus.compare("up", "up"), 0);
self.assertEqual(EServerInstanceStatus.compare("up", "down"), 1);
self.assertEqual(EServerInstanceStatus.compare("down", "up"), -1);
self.assertEqual(EServerInstanceStatus.compare("UNDEFINED-SYMBOL", "up"), None);
self.assertEqual(EServerInstanceStatus.compare("up", "UNDEFINED-SYMBOL"), None);
self.assertEqual(EServerInstanceStatus.compare(None, "up"), None);
self.assertEqual(EServerInstanceStatus.compare("up", None), None);
self.assertEqual(EServerInstanceStatus.compare(None, None), None);
if __name__ == '__main__':
unittest.main()
| sakura-internet/saklient.python | tests/test_enum.py | Python | mit | 1,117 | [
30522,
1001,
1011,
1008,
1011,
16861,
30524,
1033,
1027,
9808,
1012,
4130,
1012,
16101,
18442,
1006,
9808,
1012,
4130,
1012,
16101,
18442,
1006,
9808,
1012,
4130,
1012,
14689,
15069,
1006,
1035,
1035,
5371,
1035,
1035,
1007,
1007,
1007,
201... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#-*- encoding: utf-8 -*-
import csv, math, time, re, threading, sys
try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
class ErAPI():
# Metodo constructor, seteos basicos necesarios de configuracion, instancia objetos utiles
def __init__(self):
self.data = {}
# Data format: {'XXCiro|BNC': {'id': 123456, 'nick': 'XXCiro', 'level': 49, 'strength': 532.5, 'rank_points': 1233354, 'citizenship': 'Argentina'}}
# Diccionario de puntos/rango
self.rank_required_points = {
"Recruit": 0,
"Private": 15,
"Private*": 45,
"Private**": 80,
"Private***": 120,
"Corporal": 170,
"Corporal*": 250,
"Corporal**": 350,
"Corporal***": 450,
"Sergeant": 600,
"Sergeant*": 800,
"Sergeant**": 1000,
"Sergeant***": 1400,
"Lieutenant": 1850,
"Lieutenant*": 2350,
"Lieutenant**": 3000,
"Lieutenant***": 3750,
"Captain": 5000,
"Captain*": 6500,
"Captain**": 9000,
"Captain***": 12000,
"Major": 15500,
"Major*": 20000,
"Major**": 25000,
"Major***": 31000,
"Commander": 40000,
"Commander*": 52000,
"Commander**": 67000,
"Commander***": 85000,
"Lt Colonel": 110000,
"Lt Colonel*": 140000,
"Lt Colonel**": 180000,
"Lt Colonel***": 225000,
"Colonel": 285000,
"Colonel*": 355000,
"Colonel**": 435000,
"Colonel***": 540000,
"General": 660000,
"General*": 800000,
"General**": 950000,
"General***": 1140000,
"Field Marshal": 1350000,
"Field Marshal*": 1600000,
"Field Marshal**": 1875000,
"Field Marshal***": 2185000,
"Supreme Marshal": 2550000,
"Supreme Marshal*": 3000000,
"Supreme Marshal**": 3500000,
"Supreme Marshal***": 4150000,
"National Force": 4900000,
"National Force*": 5800000,
"National Force**": 7000000,
"National Force***": 9000000,
"World Class Force": 11500000,
"World Class Force*": 14500000,
"World Class Force**": 18000000,
"World Class Force***": 22000000,
"Legendary Force": 26500000,
"Legendary Force*": 31500000,
"Legendary Force**": 37000000,
"Legendary Force***": 42000000,
"God of War": 50000000,
"God of War*": 100000000 ,
"God of War**": 200000000,
"God of War***": 500000000,
"Titan": 1000000000,
"Titan*": 2000000000,
"Titan**": 4000000000,
"Titan***": 10000000000}
# Lista ordenada de rangos segun importancia
self.rank_to_pos = [
"Recruit",
"Private",
"Private*",
"Private**",
"Private***",
"Corporal",
"Corporal*",
"Corporal**",
"Corporal***",
"Sergeant",
"Sergeant*",
"Sergeant**",
"Sergeant***",
"Lieutenant",
"Lieutenant*",
"Lieutenant**",
"Lieutenant***",
"Captain",
"Captain*",
"Captain**",
"Captain***",
"Major",
"Major*",
"Major**",
"Major***",
"Commander",
"Commander*",
"Commander**",
"Commander***",
"Lt Colonel",
"Lt Colonel*",
"Lt Colonel**",
"Lt Colonel***",
"Colonel",
"Colonel*",
"Colonel**",
"Colonel***",
"General",
"General*",
"General**",
"General***",
"Field Marshal",
"Field Marshal*",
"Field Marshal**",
"Field Marshal***",
"Supreme Marshal",
"Supreme Marshal*",
"Supreme Marshal**",
"Supreme Marshal***",
"National Force",
"National Force*",
"National Force**",
"National Force***",
"World Class Force",
"World Class Force*",
"World Class Force**",
"World Class Force***",
"Legendary Force",
"Legendary Force*",
"Legendary Force**",
"Legendary Force***",
"God of War",
"God of War*",
"God of War**",
"God of War***",
"Titan",
"Titan*",
"Titan**",
"Titan***",]
# Bandera de ejecucion, util en caso de que se decida matar de forma manual los threads para actualizar y guardar los datos
self.run = True
# Se paraleliza la carga de datos en un hilo nuevo, el cual es demonio del invocador en caso de "muerte prematura"
th = threading.Thread(target=self.data_loader)
th.daemon = True
th.start()
# Metodo invocador, carga datos y crea threads para guardar y actualizar informacion, solo llamado desde constructor
def data_loader(self):
self.load_data()
self.data_saver_th = threading.Thread(target=self.data_saver)
self.data_saver_th.daemon = True
self.data_saver_th.start()
self.data_updater_th = threading.Thread(target=self.data_updater)
self.data_updater_th.daemon = True
self.data_updater_th.start()
# Metodo para volcar informacion a archivo fisico, solo llamado de metodo data_loader
def data_saver(self):
while self.run:
self.save_data()
time.sleep(60)
# Metodo para actualizar informacion, solo llamado de metodo data_loader
def data_updater(self):
while self.run:
for irc_nick in self.data:
self.update_data(irc_nick)
time.sleep(30)
time.sleep(600)
# ---------------------------------------------------------------------------------- #
# @ PUBLIC METHODS #
# ---------------------------------------------------------------------------------- #
# Metodo para actualizar informacion local del objeto desde archivo
def load_data(self):
try:
f = open('data/er_nick-data.csv', 'rt')
reader = csv.reader(f)
for nick_irc,id,nick_er,level,strength,rank_points,citizenship in reader:
self.data[nick_irc] = {'id': int(id), 'nick': nick_er, 'level': int(level), 'strength': float(strength), 'rank_points': int(rank_points), 'citizenship': citizenship}
f.close()
except:
pass
# Metodo para guardar informacion local del objeto en archivo
def save_data(self):
try:
f = open('data/er_nick-data.csv', 'wt')
writer = csv.writer(f)
for u in self.data:
writer.writerow([u, self.data[u]['id'], self.data[u]['nick'], self.data[u]['level'], self.data[u]['strength'], self.data[u]['rank_points'], self.data[u]['citizenship']])
f.close()
except:
pass
# Metodo scraper para actualizar informacion local del objeto del nick de irc especificado
def update_data(self, irc_nick):
try:
id = self.data[irc_nick]['id']
c = urlopen('http://www.erepublik.com/es/citizen/profile/%d' % id)
page = c.read()
c.close()
self.data[irc_nick]['nick'] = re.search('<meta name="title" content="(.+?) - Ciudadano del Nuevo Mundo" \/>', page.decode('utf-8')).group(1)
self.data[irc_nick]['level'] = int(re.search('<strong class="citizen_level">(.+?)<\/strong>', page.decode('utf-8'), re.DOTALL).group(1))
self.data[irc_nick]['strength'] = float(re.search('<span class="military_box_info mb_bottom">(.+?)</span>', page.decode('utf-8'), re.DOTALL).group(1).strip('\r\n\t ').replace(',',''))
self.data[irc_nick]['rank_points'] = int(re.search('<span class="rank_numbers">(.+?) \/', page.decode('utf-8'), re.DOTALL).group(1).replace(',',''))
self.data[irc_nick]['citizenship'] = re.search('<a href="http\:\/\/www.erepublik.com\/es\/country\/society\/([^ \t\n\x0B\f\r]+?)">', page.decode('utf-8')).group(1)
except:
pass
# Metodo para actualizar informacion local del objeto con nick de irc e id especificados, fuerza actualizacion del mismo
def reg_nick_write(self, nick, id):
if(nick.lower() in self.data.keys()):
self.data[nick.lower()]['id'] = int(id)
else:
self.data[nick.lower()] = {'id': int(id), 'nick': nick, 'level': 1, 'strength': 0, 'rank_points': 0, 'citizenship': ''}
self.update_data(nick.lower())
# Metodo para obtener ID del nick de irc especificado
def get_id(self, nick):
return self.data[nick.lower()]['id']
# Metodo para obtener LEVEL del nick de irc especificado
def get_level(self, nick):
return self.data[nick.lower()]['level']
# Metodo para obtener STRENGTH del nick de irc especificado
def get_strength(self, nick):
return self.data[nick.lower()]['strength']
# Metodo para obtener RANK POINTS del nick de irc especificado
def get_rank_points(self, nick):
return self.data[nick.lower()]['rank_points']
# Metodo para obtener CITIZENSHIP del nick de irc especificado
def get_citizenship(self, nick):
return self.data[nick.lower()]['citizenship']
# Metodo para obtener NICK INGAME del nick de irc especificado
def get_nick(self, nick):
return self.data[nick.lower()]['nick']
# Metodo para obtener RANK NAME del nick de irc especificado
def calculate_rank_name(self, rank_points):
index = 0
for k in [key for key in self.rank_required_points.keys() if self.rank_required_points[key] < rank_points]:
if(self.rank_to_pos.index(k) > index):
index = self.rank_to_pos.index(k)
return self.rank_to_pos[index]
# Metodo para calcular DAÑO del nick de irc especificado segun datos adicionales
def calculate_damage(self, rank_points, strength, weapon_power, level, bonus):
index = 0
for k in [key for key in self.rank_required_points.keys() if self.rank_required_points[key] < rank_points]:
if(self.rank_to_pos.index(k) > index):
index = self.rank_to_pos.index(k)
return(math.trunc(((index / 20) + 0.3) * ((strength / 10) + 40) * (1 + (weapon_power / 100)) * (1.1 if level > 99 else 1) * bonus)) | CPedrini/TateTRES | erapi.py | Python | apache-2.0 | 11,009 | [
30522,
1001,
30524,
2015,
3046,
1024,
2013,
24471,
6894,
2497,
1012,
5227,
12324,
24471,
4135,
11837,
3272,
12324,
2121,
29165,
1024,
2013,
24471,
6894,
2497,
12324,
24471,
4135,
11837,
2465,
3690,
8197,
1006,
1007,
1024,
1001,
2777,
7716,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<html><body>
<h4>Windows 10 x64 (19042.610)</h4><br>
<h2>_WHEA_TIMESTAMP</h2>
<font face="arial"> +0x000 Seconds : Pos 0, 8 Bits<br>
+0x000 Minutes : Pos 8, 8 Bits<br>
+0x000 Hours : Pos 16, 8 Bits<br>
+0x000 Precise : Pos 24, 1 Bit<br>
+0x000 Reserved : Pos 25, 7 Bits<br>
+0x000 Day : Pos 32, 8 Bits<br>
+0x000 Month : Pos 40, 8 Bits<br>
+0x000 Year : Pos 48, 8 Bits<br>
+0x000 Century : Pos 56, 8 Bits<br>
+0x000 AsLARGE_INTEGER : <a href="./_LARGE_INTEGER.html">_LARGE_INTEGER</a><br>
</font></body></html> | epikcraw/ggool | public/Windows 10 x64 (19042.610)/_WHEA_TIMESTAMP.html | HTML | mit | 644 | [
30522,
1026,
16129,
1028,
1026,
2303,
1028,
1026,
1044,
2549,
1028,
3645,
2184,
1060,
21084,
1006,
5692,
2475,
1012,
19827,
1007,
1026,
1013,
1044,
2549,
1028,
1026,
7987,
1028,
1026,
1044,
2475,
1028,
1035,
1059,
20192,
1035,
2335,
15464,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/bin/bash
# Luke Shannon
# Source this script to set Java home, the path will need to be updated accordingly
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
echo "Java home is set to: $JAVA_HOME" | Pivotal-Open-Source-Hub/geode-demo-application | demo/geode-server-package/setJDK.sh | Shell | apache-2.0 | 199 | [
30522,
1001,
999,
1013,
8026,
1013,
24234,
1001,
5355,
10881,
1001,
3120,
2023,
5896,
2000,
2275,
9262,
2188,
1010,
1996,
4130,
2097,
2342,
2000,
2022,
7172,
11914,
9167,
9262,
1035,
2188,
1027,
1002,
1006,
1013,
2149,
2099,
1013,
5622,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
using System.Drawing;
using CanmanSharp.Core;
namespace CanmanSharp.BuiltIn.Filters
{
public class Brightness : FilterBase
{
private readonly int _adjust;
public Brightness(double Adjust)
{
_adjust = (int) Math.Floor(255*(Adjust/100));
}
public override Color Process(Color layerColor)
{
int r = layerColor.R + _adjust;
int g = layerColor.G + _adjust;
int b = layerColor.B + _adjust;
return Color.FromArgb(layerColor.A, Utils.ClampRGB(r), Utils.ClampRGB(g), Utils.ClampRGB(b));
}
}
} | sangcu/camansharp | CanmanSharp.BuiltIn/Filters/Brightness.cs | C# | mit | 631 | [
30522,
2478,
2291,
1025,
2478,
2291,
1012,
5059,
1025,
2478,
2064,
15154,
8167,
2361,
1012,
4563,
1025,
3415,
15327,
2064,
15154,
8167,
2361,
1012,
2328,
2378,
1012,
17736,
1063,
2270,
2465,
18295,
1024,
11307,
15058,
1063,
2797,
3191,
2239... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Fishcoin</source>
<translation>Fishcoin hakkında</translation>
</message>
<message>
<location line="+39"/>
<source><b>Fishcoin</b> version</source>
<translation><b>Fishcoin</b> sürüm</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Bu yazılım deneme safhasındadır.
MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, COPYING dosyasına ya da http://www.opensource.org/licenses/mit-license.php sayfasına bakınız.
Bu ürün OpenSSL projesi tarafından OpenSSL araç takımı (http://www.openssl.org/) için geliştirilen yazılımlar, Eric Young (eay@cryptsoft.com) tarafından hazırlanmış şifreleme yazılımları ve Thomas Bernard tarafından programlanmış UPnP yazılımı içerir.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Telif hakkı</translation>
</message>
<message>
<location line="+0"/>
<source>The Fishcoin developers</source>
<translation>Fishcoin geliştiricileri</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adres defteri</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Yeni bir adres oluştur</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Şu anda seçili olan adresi panoya kopyala</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Yeni adres</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Fishcoin 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>Bunlar, ödeme almak için Fishcoin adresleridir. Kimin ödeme yaptığını izleyebilmek için her ödeme yollaması gereken kişiye değişik bir adres verebilirsiniz.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>Adresi &kopyala</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>&QR kodunu göster</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Fishcoin address</source>
<translation>Bir Fishcoin adresinin sizin olduğunu ispatlamak için mesaj imzalayın</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Mesaj imzala</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Seçili adresi listeden sil</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Güncel sekmedeki verileri bir dosyaya aktar</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Dışa aktar</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Fishcoin address</source>
<translation>Belirtilen Fishcoin adresi ile imzalandığını doğrulamak için bir mesajı kontrol et</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Mesaj &kontrol et</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Sil</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Fishcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Bunlar ödeme yapmak için kullanacağınız Fishcoin adreslerinizdir. Fishcoin yollamadan önce meblağı ve alıcı adresini daima kontrol ediniz.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>&Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Düzenle</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Bit&coin Gönder</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Adres defteri verilerini dışa aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Dışa aktarımda hata oluştu</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Parola diyaloğu</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Parolayı giriniz</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Yeni parola</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Yeni parolayı tekrarlayınız</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Cüzdanınız için yeni parolayı giriniz.<br/>Lütfen <b>10 ya da daha fazla rastgele karakter</b> veya <b>sekiz ya da daha fazla kelime</b> içeren bir parola seçiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Cüzdanı şifrele</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Cüzdan kilidini aç</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Cüzdan şifresini aç</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Parolayı değiştir</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Cüzdan için eski ve yeni parolaları giriniz.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Cüzdan şifrelenmesini teyit eder</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR FISHCOINS</b>!</source>
<translation>Uyarı: Eğer cüzdanınızı şifrelerseniz ve parolanızı kaybederseniz, <b>TÜM BİTCOİNLERİNİZİ KAYBEDERSİNİZ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Cüzdanınızı şifrelemek istediğinizden emin misiniz?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ÖNEMLİ: Önceden yapmış olduğunuz cüzdan dosyası yedeklemelerinin yeni oluşturulan şifrelenmiş cüzdan dosyası ile değiştirilmeleri gerekir. Güvenlik nedenleriyle yeni, şifrelenmiş cüzdanı kullanmaya başladığınızda eski şifrelenmemiş cüzdan dosyaları işe yaramaz hale gelecektir.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Uyarı: Caps Lock tuşu faal durumda!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Cüzdan şifrelendi</translation>
</message>
<message>
<location line="-56"/>
<source>Fishcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your fishcoins from being stolen by malware infecting your computer.</source>
<translation>Şifreleme işlemini tamamlamak için Fishcoin şimdi kapanacaktır. Cüzdanınızı şifrelemenin, Fishcoinlerinizin bilgisayara bulaşan kötücül bir yazılım tarafından çalınmaya karşı tamamen koruyamayacağını unutmayınız.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Cüzdan şifrelemesi başarısız oldu</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Girilen parolalar birbirleriyle uyumlu değil.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Cüzdan kilidinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Cüzdan şifresinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>&Mesaj imzala...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Şebeke ile senkronizasyon...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Genel bakış</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Cüzdana genel bakışı göster</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Muameleler</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Muamele tarihçesini tara</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Saklanan adres ve etiket listesini düzenle</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Ödeme alma adreslerinin listesini göster</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Çık</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Uygulamadan çık</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Fishcoin</source>
<translation>Fishcoin hakkında bilgi göster</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>&Qt hakkında</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Qt hakkında bilgi görüntü</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Seçenekler...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>Cüzdanı &şifrele...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Cüzdanı &yedekle...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Parolayı &değiştir...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Bloklar diskten içe aktarılıyor...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Diskteki bloklar yeniden endeksleniyor...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Fishcoin address</source>
<translation>Bir Fishcoin adresine Fishcoin yolla</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Fishcoin</source>
<translation>Fishcoin seçeneklerinin yapılandırmasını değiştir</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Cüzdanı diğer bir konumda yedekle</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cüzdan şifrelemesi için kullanılan parolayı değiştir</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Hata ayıklama ve teşhis penceresini aç</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>Mesaj &kontrol et...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Fishcoin</source>
<translation>Fishcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Gönder</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Al</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adresler</translation>
</message>
<message>
<location line="+22"/>
<source>&About Fishcoin</source>
<translation>Fishcoin &Hakkında</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Göster / Sakla</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Ana pencereyi görüntüle ya da sakla</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Cüzdanınızın özel anahtarlarını şifrele</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Fishcoin addresses to prove you own them</source>
<translation>Mesajları adreslerin size ait olduğunu ispatlamak için Fishcoin adresleri ile imzala</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Fishcoin addresses</source>
<translation>Belirtilen Fishcoin adresleri ile imzalandıklarından emin olmak için mesajları kontrol et</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Dosya</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Ayarlar</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Yardım</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Sekme araç çubuğu</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Fishcoin client</source>
<translation>Fishcoin istemcisi</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Fishcoin network</source>
<translation><numerusform>Fishcoin şebekesine %n faal bağlantı</numerusform><numerusform>Fishcoin şebekesine %n faal bağlantı</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Hiçbir blok kaynağı mevcut değil...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Muamele tarihçesinin toplam (tahmini) %2 blokundan %1 blok işlendi.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Muamele tarihçesinde %1 blok işlendi.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n saat</numerusform><numerusform>%n saat</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n gün</numerusform><numerusform>%n gün</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n hafta</numerusform><numerusform>%n hafta</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 geride</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Son alınan blok %1 evvel oluşturulmuştu.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Bundan sonraki muameleler henüz görüntülenemez.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Bilgi</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Bu muamele boyut sınırlarını aşmıştır. Gene de %1 ücret ödeyerek gönderebilirsiniz, ki bu ücret muamelenizi işleyen ve şebekeye yardım eden düğümlere ödenecektir. Ücreti ödemek istiyor musunuz?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Güncel</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Aralık kapatılıyor...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Muamele ücretini teyit et</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Muamele yollandı</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Gelen muamele</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tarih: %1
Miktar: %2
Tür: %3
Adres: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI yönetimi</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Fishcoin address or malformed URI parameters.</source>
<translation>URI okunamadı! Sebebi geçersiz bir Fishcoin adresi veya hatalı URI parametreleri olabilir.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilidi açıktır</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilitlidir</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Fishcoin can no longer continue safely and will quit.</source>
<translation>Ciddi bir hata oluştu. Fishcoin artık güvenli bir şekilde işlemeye devam edemez ve kapanacaktır.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Şebeke hakkında uyarı</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Adresi düzenle</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Bu adres defteri unsuru ile ilişkili etiket</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Bu adres defteri unsuru ile ilişkili adres. Bu, sadece gönderi adresi için değiştirilebilir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Yeni alım adresi</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Yeni gönderi adresi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Alım adresini düzenle</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Gönderi adresini düzenle</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Girilen "%1" adresi hâlihazırda adres defterinde mevcuttur.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Fishcoin address.</source>
<translation>Girilen "%1" adresi geçerli bir Fishcoin adresi değildir.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Cüzdan kilidi açılamadı.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Yeni anahtar oluşturulması başarısız oldu.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Fishcoin-Qt</source>
<translation>Fishcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>sürüm</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komut satırı seçenekleri</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Kullanıcı arayüzü seçenekleri</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Lisan belirt, mesela "de_De" (varsayılan: sistem dili)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Küçültülmüş olarak başlat</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Başlatıldığında başlangıç ekranını göster (varsayılan: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Seçenekler</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Esas ayarlar</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Muamelelerin hızlı işlenmesini garantilemeye yardım eden, seçime dayalı kB başı muamele ücreti. Muamelelerin çoğunluğunun boyutu 1 kB'dir.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Muamele ücreti &öde</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Fishcoin after logging in to the system.</source>
<translation>Sistemde oturum açıldığında Fishcoin'i otomatik olarak başlat.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Fishcoin on system login</source>
<translation>Fishcoin'i sistem oturumuyla &başlat</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>İstemcinin tüm seçeneklerini varsayılan değerlere geri al.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Seçenekleri &sıfırla</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Şebeke</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Fishcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Yönlendiricide Fishcoin istemci portlarını otomatik olarak açar. Bu, sadece yönlendiricinizin UPnP desteği bulunuyorsa ve etkinse çalışabilir.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portları &UPnP kullanarak haritala</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Fishcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Fishcoin şebekesine SOCKS vekil sunucusu vasıtasıyla bağlan (mesela Tor ile bağlanıldığında).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>SOCKS vekil sunucusu vasıtasıyla ba&ğlan:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Vekil &İP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Vekil sunucunun İP adresi (mesela 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Vekil sunucunun portu (mesela 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &sürümü:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Vekil sunucunun SOCKS sürümü (mesela 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Pencere</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Küçültüldükten sonra sadece çekmece ikonu göster.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>İşlem çubuğu yerine sistem çekmecesine &küçült</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Kapatma sırasında k&üçült</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Görünüm</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Kullanıcı arayüzü &lisanı:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Fishcoin.</source>
<translation>Kullanıcı arayüzünün dili burada belirtilebilir. Bu ayar Fishcoin tekrar başlatıldığında etkinleşecektir.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Miktarı göstermek için &birim:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Fishcoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Fishcoin addresses in the transaction list or not.</source>
<translation>Muamele listesinde Fishcoin adreslerinin gösterilip gösterilmeyeceklerini belirler.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Muamele listesinde adresleri &göster</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Tamam</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&İptal</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Uygula</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>varsayılan</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Seçeneklerin sıfırlanmasını teyit et</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Bazı ayarların dikkate alınması istemcinin tekrar başlatılmasını gerektirebilir.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Devam etmek istiyor musunuz?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Fishcoin.</source>
<translation>Bu ayarlar Fishcoin tekrar başlatıldığında etkinleşecektir.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Girilen vekil sunucu adresi geçersizdir.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Fishcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Görüntülenen veriler zaman aşımına uğramış olabilir. Bağlantı kurulduğunda cüzdanınız otomatik olarak şebeke ile eşleşir ancak bu işlem henüz tamamlanmamıştır.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Doğrulanmamış:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Olgunlaşmamış:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Oluşturulan bakiye henüz olgunlaşmamıştır</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Son muameleler</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Güncel bakiyeniz</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Doğrulanması beklenen ve henüz güncel bakiyeye ilâve edilmemiş muamelelerin toplamı</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>eşleşme dışı</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start fishcoin: click-to-pay handler</source>
<translation>Fishcoin başlatılamadı: tıkla-ve-öde yöneticisi</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR kodu diyaloğu</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Ödeme talebi</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiket:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Farklı kaydet...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>URI'nin QR koduna kodlanmasında hata oluştu.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Girilen miktar geçersizdir, kontrol ediniz.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Sonuç URI çok uzun, etiket ya da mesaj metnini kısaltmayı deneyiniz.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>QR kodu kaydet</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG resimleri (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>İstemci ismi</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>Mevcut değil</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>İstemci sürümü</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Malumat</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Kullanılan OpenSSL sürümü</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Başlama zamanı</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Bağlantı sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testnet üzerinde</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blok zinciri</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Güncel blok sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Tahmini toplam blok sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Son blok zamanı</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Aç</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komut satırı seçenekleri</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Fishcoin-Qt help message to get a list with possible Fishcoin command-line options.</source>
<translation>Mevcut Fishcoin komut satırı seçeneklerinin listesini içeren Fishcoin-Qt yardımını göster.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Göster</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Derleme tarihi</translation>
</message>
<message>
<location line="-104"/>
<source>Fishcoin - Debug window</source>
<translation>Fishcoin - Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+25"/>
<source>Fishcoin Core</source>
<translation>Fishcoin Çekirdeği</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Hata ayıklama kütük dosyası</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Fishcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Güncel veri klasöründen Fishcoin hata ayıklama kütük dosyasını açar. Büyük kütük dosyaları için bu birkaç saniye alabilir.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Konsolu temizle</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Fishcoin RPC console.</source>
<translation>Fishcoin RPC konsoluna hoş geldiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Tarihçede gezinmek için imleç tuşlarını kullanınız, <b>Ctrl-L</b> ile de ekranı temizleyebilirsiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Mevcut komutların listesi için <b>help</b> yazınız.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Fishcoin yolla</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Birçok alıcıya aynı anda gönder</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Alıcı ekle</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Bütün muamele alanlarını kaldır</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Yollama etkinliğini teyit ediniz</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>G&önder</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> şu adrese: %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Gönderiyi teyit ediniz</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>%1 göndermek istediğinizden emin misiniz?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> ve </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Tutar bakiyenizden yüksektir.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Toplam, %1 muamele ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Hata: Muamele oluşturması başarısız oldu!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: Muamele reddedildi. Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>M&iktar:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Şu kişiye öde:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Ödemenin gönderileceği adres (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Bu alıcıyı kaldır</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Fishcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Fishcoin adresi giriniz (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>İmzalar - Mesaj İmzala / Kontrol et</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>Mesaj &imzala</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayınız.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Mesajın imzalanmasında kullanılacak adres (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Adres defterinden bir adres seç</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>İmzalamak istediğiniz mesajı burada giriniz</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>İmza</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Güncel imzayı sistem panosuna kopyala</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Fishcoin address</source>
<translation>Bu Fishcoin adresinin sizin olduğunu ispatlamak için mesajı imzalayın</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Mesajı imzala</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Tüm mesaj alanlarını sıfırla</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>Mesaj &kontrol et</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>İmza için kullanılan adresi, mesajı (satır sonları, boşluklar, sekmeler vs. karakterleri tam olarak kopyaladığınızdan emin olunuz) ve imzayı aşağıda giriniz. Bir ortadaki adam saldırısı tarafından kandırılmaya mâni olmak için imzadan, imzalı mesajın içeriğini aşan bir anlam çıkarmamaya dikkat ediniz.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Mesajı imzalamak için kullanılmış olan adres (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Fishcoin address</source>
<translation>Belirtilen Fishcoin adresi ile imzalandığını doğrulamak için mesajı kontrol et</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>&Mesaj kontrol et</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Tüm mesaj kontrolü alanlarını sıfırla</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Fishcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Fishcoin adresi giriniz (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>İmzayı oluşturmak için "Mesaj İmzala" unsurunu tıklayın</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Fishcoin signature</source>
<translation>Fishcoin imzası gir</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Girilen adres geçersizdir.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Adresi kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Girilen adres herhangi bir anahtara işaret etmemektedir.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Cüzdan kilidinin açılması iptal edildi.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Girilen adres için özel anahtar mevcut değildir.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Mesajın imzalanması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mesaj imzalandı.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>İmzanın kodu çözülemedi.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>İmza mesajın hash değeri ile eşleşmedi.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Mesaj doğrulaması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mesaj doğrulandı.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Fishcoin developers</source>
<translation>Fishcoin geliştiricileri</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/çevrim dışı</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/doğrulanmadı</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 teyit</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Durum</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, %n düğüm vasıtasıyla yayınlandı</numerusform><numerusform>, %n düğüm vasıtasıyla yayınlandı</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kaynak</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Oluşturuldu</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Gönderen</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Alıcı</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>kendi adresiniz</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Gider</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>%n ek blok sonrasında olgunlaşacak</numerusform><numerusform>%n ek blok sonrasında olgunlaşacak</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>kabul edilmedi</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Gelir</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Muamele ücreti</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net miktar</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Yorum</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Muamele tanımlayıcı</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Oluşturulan Fishcoin'lerin harcanabilmelerinden önce 120 blok beklemeleri gerekmektedir. Bu blok, oluşturduğunuzda blok zincirine eklenmesi için ağda yayınlandı. Zincire eklenmesi başarısız olursa, durumu "kabul edilmedi" olarak değiştirilecek ve harcanamayacaktır. Bu, bazen başka bir düğüm sizden birkaç saniye önce ya da sonra blok oluşturursa meydana gelebilir.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Hata ayıklama verileri</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Muamele</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Girdiler</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>doğru</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>yanlış</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, henüz başarılı bir şekilde yayınlanmadı</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>%n ilâve blok için açık</numerusform><numerusform>%n ilâve blok için açık</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>bilinmiyor</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Muamele detayları</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Bu pano muamelenin ayrıntılı açıklamasını gösterir</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>%n ilâve blok için açık</numerusform><numerusform>%n ilâve blok için açık</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Çevrimdışı (%1 teyit)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Doğrulanmadı (%1 (toplam %2 üzerinden) teyit)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Doğrulandı (%1 teyit)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Madenden çıkarılan bakiye %n ek blok sonrasında olgunlaştığında kullanılabilecektir</numerusform><numerusform>Madenden çıkarılan bakiye %n ek blok sonrasında olgunlaştığında kullanılabilecektir</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Oluşturuldu ama kabul edilmedi</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Şununla alındı</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Alındığı kişi</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Kendinize ödeme</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Madenden çıkarılan</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(mevcut değil)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Muamele durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Muamelenin alındığı tarih ve zaman.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Muamele türü.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Muamelenin alıcı adresi.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bakiyeden alınan ya da bakiyeye eklenen miktar.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Hepsi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Bugün</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Bu hafta</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Bu ay</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Geçen ay</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Bu sene</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Aralık...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Şununla alınan</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Kendinize</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Oluşturulan</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Aranacak adres ya da etiket giriniz</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Asgari miktar</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Muamele kimliğini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Etiketi düzenle</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Muamele detaylarını göster</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Muamele verilerini dışa aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Doğrulandı</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>Tanımlayıcı</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Dışa aktarımda hata oluştu</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Aralık:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ilâ</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Fishcoin yolla</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Dışa aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Güncel sekmedeki verileri bir dosyaya aktar</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Cüzdanı yedekle</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Cüzdan verileri (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Yedekleme başarısız oldu</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Cüzdanı değişik bir konuma kaydetmek denenirken bir hata meydana geldi.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Yedekleme başarılı</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Cüzdan verileri başarılı bir şekilde yeni konuma kaydedildi.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Fishcoin version</source>
<translation>Fishcoin sürümü</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or fishcoind</source>
<translation>-server ya da fishcoind'ye komut gönder</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komutları listele</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Bir komut için yardım al</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Seçenekler:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: fishcoin.conf)</source>
<translation>Yapılandırma dosyası belirt (varsayılan: fishcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: fishcoind.pid)</source>
<translation>Pid dosyası belirt (varsayılan: fishcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Veri dizinini belirt</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Bağlantılar için dinlenecek <port> (varsayılan: 9333 ya da testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Eşler ile en çok <n> adet bağlantı kur (varsayılan: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Kendi genel adresinizi tanımlayın</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>IPv4 üzerinde dinlemek için %u numaralı RPC portunun kurulumu sırasında hata meydana geldi: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>JSON-RPC bağlantılarını <port> üzerinde dinle (varsayılan: 9332 veya tesnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Deneme şebekesini kullan</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: -proxy veya -connect yoksa 1)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=fishcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Fishcoin Alert" admin@foo.com
</source>
<translation>%s, şu yapılandırma dosyasında rpc parolası belirtmeniz gerekir:
%s
Aşağıdaki rastgele oluşturulan parolayı kullanmanız tavsiye edilir:
rpcuser=fishcoinrpc
rpcpassword=%s
(bu parolayı hatırlamanız gerekli değildir)
Kullanıcı ismi ile parolanın FARKLI olmaları gerekir.
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.
Sorunlar hakkında bildiri almak için alertnotify unsurunu ayarlamanız tavsiye edilir;
mesela: alertnotify=echo %%s | mail -s "Fishcoin Alert" admin@foo.com
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>IPv6 üzerinde dinlemek için %u numaralı RPC portu kurulurken bir hata meydana geldi, IPv4'e dönülüyor: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Belirtilen adrese bağlan ve daima ondan dinle. IPv6 için [makine]:port yazımını kullanınız</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Fishcoin is probably already running.</source>
<translation>%s veri dizininde kilit elde edilemedi. Fishcoin muhtemelen hâlihazırda çalışmaktadır.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: Muamele reddedildi! Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Hata: Muamelenin miktarı, karmaşıklığı ya da yakın geçmişte alınan fonların kullanılması nedeniyle bu muamele en az %s tutarında ücret gerektirmektedir!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>İlgili bir uyarı alındığında komut çalıştır (komuttaki %s mesaj ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Bir cüzdan muamelesi değiştiğinde komutu çalıştır (komuttaki %s TxID ile değiştirilecektir)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Yüksek öncelikli/düşük ücretli muamelelerin boyutunu bayt olarak tanımla (varsayılan: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Bu yayın öncesi bir deneme sürümüdür - tüm riski siz üstlenmiş olursunuz - fishcoin oluşturmak ya da ticari uygulamalar için kullanmayınız</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış! Bu, muamele gönderirseniz ödeyeceğiniz muamele ücretidir.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Uyarı: Görüntülenen muameleler doğru olmayabilir! Sizin ya da diğer düğümlerin güncelleme yapması gerekebilir.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Fishcoin will not work properly.</source>
<translation>Uyarı: Lütfen bilgisayarınızın tarih ve saatinin doğru olup olmadığını kontrol ediniz! Saatiniz doğru değilse Fishcoin gerektiği gibi çalışamaz.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Uyarı: wallet.dat dosyasının okunması sırasında bir hata meydana geldi! Tüm anahtarlar doğru bir şekilde okundu, ancak muamele verileri ya da adres defteri unsurları hatalı veya eksik olabilir.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Uyarı: wallet.dat bozuk, veriler geri kazanıldı! Özgün wallet.dat, wallet.{zamandamgası}.bak olarak %s klasörüne kaydedildi; bakiyeniz ya da muameleleriniz yanlışsa bir yedeklemeden tekrar yüklemeniz gerekir.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Bozuk bir wallet.dat dosyasından özel anahtarları geri kazanmayı dene</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Blok oluşturma seçenekleri:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Sadece belirtilen düğüme veya düğümlere bağlan</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Bozuk blok veritabanı tespit edildi</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Kendi IP adresini keşfet (varsayılan: dinlenildiğinde ve -externalip yoksa 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Blok veritabanını şimdi yeniden inşa etmek istiyor musunuz?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Blok veritabanını başlatılırken bir hata meydana geldi</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>%s cüzdan veritabanı ortamının başlatılmasında hata meydana geldi!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Blok veritabanının yüklenmesinde hata</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Blok veritabanının açılışı sırasında hata</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Hata: Disk alanı düşük!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Hata: Cüzdan kilitli, muamele oluşturulamadı!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Hata: sistem hatası:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Herhangi bir portun dinlenmesi başarısız oldu. Bunu istiyorsanız -listen=0 seçeneğini kullanınız.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Blok verileri okunamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Blok okunamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Blok indeksi eşleştirilemedi</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Blok indeksi yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Blok verileri yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Blok yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Dosya verileri yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Madenî para veritabanına yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Muamele indeksi yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Geri alma verilerinin yazılamadı</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Eşleri DNS araması vasıtasıyla bul (varsayılan: 1, eğer -connect kullanılmadıysa)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Fishcoin oluştur (varsayılan: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Başlangıçta kontrol edilecek blok sayısı (varsayılan: 288, 0 = hepsi)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Blok kontrolünün ne kadar derin olacağı (0 ilâ 4, varsayılan: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Kafi derecede dosya tanımlayıcıları mevcut değil.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Blok zinciri indeksini güncel blk000??.dat dosyalarından tekrar inşa et</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>RPC aramaları için iş parçacığı sayısını belirle (varsayılan: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Bloklar kontrol ediliyor...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Cüzdan kontrol ediliyor...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Harici blk000??.dat dosyasından blokları içe aktarır</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Betik kontrolü iş parçacığı sayısını belirt (azami 16, 0 = otomatik, <0 = bu sayıda çekirdeği boş bırak, varsayılan: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Bilgi</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Geçersiz -tor adresi: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>-minrelaytxfee=<amount> için geçersiz meblağ: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>-mintxfee=<amount> için geçersiz meblağ: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Muamelelerin tamamının indeksini tut (varsayılan: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Bağlantı başına azami alım tamponu, <n>*1000 bayt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Bağlantı başına azami yollama tamponu, <n>*1000 bayt (varsayılan: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Sadece yerleşik kontrol noktalarıyla eşleşen blok zincirini kabul et (varsayılan: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Sadece <net> şebekesindeki düğümlere bağlan (IPv4, IPv6 ya da Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>İlâve hata ayıklama verileri çıkart. Diğer tüm -debug* seçeneklerini ima eder</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>İlâve şebeke hata ayıklama verileri çıkart</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Hata ayıklama çıktısına tarih ön ekleri ilâve et</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Fishcoin Wiki for SSL setup instructions)</source>
<translation> SSL seçenekleri: (SSL kurulum bilgisi için Fishcoin vikisine bakınız)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Kullanılacak socks vekil sunucu sürümünü seç (4-5, varsayılan: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Hata ayıklayıcıya -debugger- trace/hata ayıklama verileri gönder</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Bayt olarak azami blok boyutunu tanımla (varsayılan: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Bayt olarak asgari blok boyutunu tanımla (varsayılan: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>İstemci başlatıldığında debug.log dosyasını küçült (varsayılan: -debug bulunmadığında 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Muamelenin imzalanması başarısız oldu</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Bağlantı zaman aşım süresini milisaniye olarak belirt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Sistem hatası:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Muamele meblağı çok düşük</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Muamele tutarının pozitif olması lazımdır</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Muamele çok büyük</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: dinlenildiğinde 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Gizli tor servislerine erişmek için vekil sunucu kullan (varsayılan: -proxy ile aynısı)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için kullanıcı ismi</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Uyarı: Bu sürüm çok eskidir, güncellemeniz gerekir!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>-txindex'i değiştirmek için veritabanlarını -reindex kullanarak yeniden inşa etmeniz gerekir.</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat bozuk, geri kazanım başarısız oldu</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için parola</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Şu <ip> adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>En iyi blok değiştiğinde komutu çalıştır (komut için %s parametresi blok hash değeri ile değiştirilecektir)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Cüzdanı en yeni biçime güncelle</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Anahtar alan boyutunu <n> değerine ayarla (varsayılan: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blok zincirini eksik cüzdan muameleleri için tekrar tara</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Kabul edilebilir şifreler (varsayılan: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Bu yardım mesajı</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Socks vekil sunucusu vasıtasıyla bağlan</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Adresler yükleniyor...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Fishcoin</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: cüzdanın daha yeni bir Fishcoin sürümüne ihtiyacı var</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Fishcoin to complete</source>
<translation>Cüzdanın tekrar yazılması gerekiyordu: işlemi tamamlamak için Fishcoin'i yeniden başlatınız</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Geçersiz -proxy adresi: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet için bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Bilinmeyen bir -socks vekil sürümü talep edildi: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<miktar> için geçersiz miktar: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Geçersiz miktar</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Yetersiz bakiye</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Blok indeksi yükleniyor...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Fishcoin is probably already running.</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. Fishcoin muhtemelen hâlihazırda çalışmaktadır.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Yolladığınız muameleler için eklenecek KB başı ücret</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Cüzdan yükleniyor...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Cüzdan eski biçime geri alınamaz</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Varsayılan adres yazılamadı</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Yeniden tarama...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Yükleme tamamlandı</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>%s seçeneğini kullanmak için</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>rpcpassword=<parola> şu yapılandırma dosyasında belirtilmelidir:
%s
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation>
</message>
</context>
</TS> | fishcoin/fishcoin | src/qt/locale/bitcoin_tr.ts | TypeScript | mit | 119,207 | [
30522,
1026,
1029,
20950,
2544,
1027,
1000,
1015,
1012,
1014,
1000,
1029,
1028,
1026,
999,
9986,
13874,
24529,
1028,
1026,
24529,
2653,
1027,
1000,
19817,
1000,
2544,
1027,
1000,
1016,
1012,
1014,
1000,
1028,
1026,
12398,
16044,
2278,
1028,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* K&R2 1-23: Write a program to remove all comments from a C program.
Don't forget to handle quoted strings and character constants
properly. C comments do not nest.
This solution does not deal with other special cases, such as
trigraphs, line continuation with \, or <> quoting on #include,
since these aren't mentioned up 'til then in K&R2. Perhaps this is
cheating.
Note that this program contains both comments and quoted strings of
text that looks like comments, so running it on itself is a
reasonable test. It also contains examples of a comment that ends
in a star and a comment preceded by a slash. Note that the latter
will break C99 compilers and C89 compilers with // comment
extensions.
Interface: The C source file is read from stdin and the
comment-less output is written to stdout. **/
#include <stdio.h>
int
main(void)
{
#define PROGRAM 0
#define SLASH 1
#define COMMENT 2
#define STAR 3
#define QUOTE 4
#define LITERAL 5
/* State machine's current state, one of the above values. */
int state;
/* If state == QUOTE, then ' or ". Otherwise, undefined. */
int quote;
/* Input character. */
int c;
state = PROGRAM;
while ((c = getchar()) != EOF) {
/* The following cases are in guesstimated order from most common
to least common. */
if (state == PROGRAM || state == SLASH) {
if (state == SLASH) {
/* Program text following a slash. */
if (c == '*')
state = COMMENT;
else {
putchar('/');
state = PROGRAM;
}
}
if (state == PROGRAM) {
/* Program text. */
if (c == '\'' || c == '"') {
quote = c;
state = QUOTE;
putchar(c);
}
else if (c == "/*"[0])
state = SLASH;
else
putchar(c);
}
}
else if (state == COMMENT) {
/* Comment. */
if (c == "/*"[1])
state = STAR;
}
else if (state == QUOTE) {
/* Within quoted string or character constant. */
putchar(c);
if (c == '\\')
state = LITERAL;
else if (c == quote)
state = PROGRAM;
}
else if (state == SLASH) {
}
else if (state == STAR) {
/* Comment following a star. */
if (c == '/')
state = PROGRAM;
else if (c != '*')
state = COMMENT;
}
else /* state == LITERAL */ {
/* Within quoted string or character constant, following \. */
putchar(c);
state = QUOTE;
}
}
if (state == SLASH)
putchar('/' //**/
1);
return 0;
}
/*
Local variables:
compile-command: "checkergcc -W -Wall -ansi -pedantic knr123-0.c -o knr123-0"
End:
*/
| mikephp/basic_data_struct | example/C Programming Code/krx12301.c | C | gpl-2.0 | 3,109 | [
30522,
1013,
1008,
1047,
1004,
1054,
2475,
1015,
1011,
2603,
1024,
4339,
1037,
2565,
2000,
6366,
2035,
7928,
2013,
1037,
1039,
2565,
1012,
2123,
1005,
1056,
5293,
2000,
5047,
9339,
7817,
1998,
2839,
5377,
2015,
7919,
1012,
1039,
7928,
207... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Linux有问必答:如何检查Linux上的glibc版本
================================================================================
> **问题**:我需要找出我的Linux系统上的GNU C库(glibc)的版本,我怎样才能检查Linux上的glibc版本呢?
GNU C库(glibc)是标准C库的GNU实现。glibc是GNU工具链的关键组件,用于和二进制工具和编译器一起使用,为目标架构生成用户空间应用程序。
当从源码进行构建时,一些Linux程序可能需要链接到某个特定版本的glibc。在这种情况下,你可能想要检查已安装的glibc信息以查看是否满足依赖关系。
这里介绍几种简单的方法,方便你检查Linux上的glibc版本。
### 方法一 ###
下面给出了命令行下检查GNU C库的简单命令。
$ ldd --version

在本例中,**glibc**版本是**2.19**。
### 方法二 ###
另一个方法是在命令行“输入”**glibc 库的名称**(如,libc.so.6),就像命令一样执行。
输出结果会显示更多关于**glibc库**的详细信息,包括glibc的版本以及使用的GNU编译器,也提供了glibc扩展的信息。glibc变量的位置取决于Linux版本和处理器架构。
在基于Debian的64位系统上:
$ /lib/x86_64-linux-gnu/libc.so.6
在基于Debian的32位系统上:
$ /lib/i386-linux-gnu/libc.so.6
在基于Red Hat的64位系统上:
$ /lib64/libc.so.6
在基于Red Hat的32位系统上:
$ /lib/libc.so.6
下图中是输入glibc库后的输出结果样例。

--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/check-glibc-version-linux.html
译者:[GOLinux](https://github.com/GOLinux)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
| geekpi/TranslateProject | published/201411/20141125 Linux FAQs with Answers--How to check glibc version on Linux.md | Markdown | apache-2.0 | 2,047 | [
30522,
11603,
1873,
100,
100,
100,
1993,
100,
100,
100,
100,
11603,
1742,
1916,
1043,
29521,
2278,
1907,
1876,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?PHP // $Id$
// message.php - created with Moodle 1.9.3+ (Build: 20081126) (2007101532)
$string['addcontact'] = 'Añadir contacto';
$string['addsomecontacts'] = 'Para enviar un mensaje a alguien, o para añadir un atajo en esta página, utilice la pestaña <a href=\"$a\">Buscar</a> de más arriba.';
$string['addsomecontactsincoming'] = 'Estos mensajes provienen de personas que no están en su lista de contactos. Para agregarlos a sus contactos, haga clic en el icono \"Agregar contacto\" al lado de su nombre.';
$string['ago'] = 'hace $a';
$string['ajax_gui'] = 'Sala de chat Ajax';
$string['allmine'] = 'Todos los mensajes';
$string['allstudents'] = 'Todos los mensajes entre los estudiantes del curso';
$string['allusers'] = 'Todos los mensajes de todos los usuarios';
$string['backupmessageshelp'] = 'Si se activa, los mensajes instantáneos serán incluídos en las copias automatizadas del SITIO';
$string['beepnewmessage'] = '\'Beep\' cuando llegue un mensaje nuevo';
$string['blockcontact'] = 'Bloquear contacto';
$string['blockedmessages'] = '$a mensaje(s) hacia/de usuarios bloqueados';
$string['blocknoncontacts'] = 'Bloquear todos los mensajes nuevos de las personas que no están en mi lista de contactos';
$string['cannotsavemessageprefs'] = 'No se pudieron guardar sus preferencias de mensajería';
$string['contactlistempty'] = 'Su lista de contactos está vacía';
$string['contacts'] = 'Contactos';
$string['context'] = 'contexto';
$string['deletemessagesdays'] = 'Número de días antes de eliminar automáticamente los mensajes antiguos';
$string['disabled'] = 'La mensajería está deshabilitada en este sitio';
$string['discussion'] = 'Discusión';
$string['editmymessage'] = 'Mensajería';
$string['emailmessages'] = 'Mensajes por email cuando no estoy en línea';
$string['emailtagline'] = 'Este email es copia de un mensaje enviado a usted en \"$a\"';
$string['emptysearchstring'] = 'Debe buscar algo';
$string['errorcallingprocessor'] = 'Error al llamar al procesador definido';
$string['formorethan'] = 'Durante más de';
$string['guestnoeditmessage'] = 'Los invitados no pueden editar las opciones de mensajería';
$string['guestnoeditmessageother'] = 'Los invitados no pueden editar las opciones de mensajería de otro usuario';
$string['includeblockedusers'] = 'Incluir usuarios bloqueados';
$string['incomingcontacts'] = 'Contactos Entrantes ($a)';
$string['keywords'] = 'Palabras-clave';
$string['keywordssearchresults'] = 'Resultados de la búsqueda: $a mensajes encontrados';
$string['loggedin'] = 'En línea';
$string['loggedoff'] = 'No en línea';
$string['mailsent'] = 'Su mensaje se ha enviado por email.';
$string['maxmessages'] = 'Número máximo de mensajes para mostrar en la historia de la discusión';
$string['message'] = 'Mensaje';
$string['messagehistory'] = 'Historia de mensajes';
$string['messageprovider:instantmessage'] = 'Mensaje Instantáneo de un Usuario a otro Usuario';
$string['messages'] = 'Mensajes';
$string['messaging'] = 'Mensajes';
$string['messagingdisabled'] = 'El servicio de mensajería está deshabilitado en este sitio: se enviarán correos electrónicos en lugar de mensajes';
$string['mycontacts'] = 'Mis contactos';
$string['newonlymsg'] = 'Mostrar sólo nuevos';
$string['newsearch'] = 'Nueva búsqueda';
$string['noframesjs'] = 'Versión sin marcos ni JavaScript';
$string['nomessages'] = 'No hay mensajes en espera';
$string['nomessagesfound'] = 'No se encontraron mensajes';
$string['nosearchresults'] = 'La búsqueda no produjo resultados';
$string['offline'] = 'Fuera de línea';
$string['offlinecontacts'] = 'Contactos fuera de línea ($a)';
$string['online'] = 'En línea';
$string['onlinecontacts'] = 'Contactos en línea ($a)';
$string['onlyfromme'] = 'Sólo mensajes enviados por mí';
$string['onlymycourses'] = 'Sólo en mis cursos';
$string['onlytome'] = 'Sólo mensajes dirigidos a mí';
$string['pagerefreshes'] = 'Esta página se actualiza automáticamente cada $a segundos';
$string['private_config'] = 'Opciones de Mensajería Privada';
$string['processortag'] = 'Destino:';
$string['providers_config'] = 'Fuentes de Mensajes';
$string['providerstag'] = 'Fuente:';
$string['readmessages'] = '$a mensajes leídos';
$string['removecontact'] = 'Eliminar contacto';
$string['savemysettings'] = 'Guardar mis ajustes';
$string['search'] = 'Buscar';
$string['searchforperson'] = 'Buscar una persona';
$string['searchmessages'] = 'Buscar mensajes';
$string['sendmessage'] = 'Enviar mensaje';
$string['sendmessageto'] = 'Enviar mensaje a $a';
$string['sendmessagetopopup'] = 'Enviar mensaje a $a - ventana nueva';
$string['settings'] = 'Ajustes';
$string['settingssaved'] = 'Sus ajustes han sido guardados';
$string['showmessagewindow'] = 'Mostrar automáticamente la ventana de Mensajes cuando me llegan mensajes nuevos (el navegador debe estar configurado para permitir ventanas emergentes en el sitio)';
$string['strftimedaydatetime'] = '%%A, %%d %%B %%Y, %%I:%%M %%p';
$string['timenosee'] = 'Minutos desde que estuve en línea por última vez';
$string['timesent'] = 'Hora de envío';
$string['unblockcontact'] = 'Desbloquear contacto';
$string['unreadmessages'] = '$a mensajes sin leer';
$string['userisblockingyou'] = 'Este usuario le ha bloqueado y no puede enviarle mensajes';
$string['userisblockingyounoncontact'] = 'Este usuario sólo acepta mensajes de las personas que están en su lista de contactos, y usted no figura de momento en dicha lista.';
$string['userssearchresults'] = 'Resultados de la búsqueda: $a usuarios encontrados';
$string['processor_config'] = 'Configuración de Destinos'; // ORPHANED
?>
| carpe-diem/conectar-igualdad-server-apps | apps/src/intranet/moodle/lang/es_utf8/message.php | PHP | gpl-3.0 | 5,622 | [
30522,
1026,
1029,
25718,
1013,
1013,
1002,
8909,
1002,
1013,
1013,
4471,
1012,
25718,
1011,
2580,
2007,
6888,
2571,
1015,
1012,
1023,
1012,
1017,
1009,
1006,
3857,
1024,
2263,
14526,
23833,
1007,
1006,
2289,
10790,
16068,
16703,
1007,
1002... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (c) 2020 Embedded Planet
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
#include <bootutil/sign_key.h>
#include <mcuboot_config/mcuboot_config.h>
#if defined(MCUBOOT_SIGN_RSA)
#define HAVE_KEYS
extern const unsigned char rsa_pub_key[];
extern unsigned int rsa_pub_key_len;
#elif defined(MCUBOOT_SIGN_EC256)
#define HAVE_KEYS
extern const unsigned char ecdsa_pub_key[];
extern unsigned int ecdsa_pub_key_len;
#elif defined(MCUBOOT_SIGN_ED25519)
#define HAVE_KEYS
extern const unsigned char ed25519_pub_key[];
extern unsigned int ed25519_pub_key_len;
#else
#error "No public key available for given signing algorithm."
#endif
/*
* Note: Keys for both signing and encryption must be provided by the application.
* mcuboot's imgtool utility can be used to generate these keys and convert them into compatible C code.
* See imgtool's documentation, specifically the section: "Incorporating the public key into the code" which can be found here:
* https://github.com/JuulLabs-OSS/mcuboot/blob/master/docs/imgtool.md#incorporating-the-public-key-into-the-code
*/
#if defined(HAVE_KEYS)
const struct bootutil_key bootutil_keys[] = {
{
#if defined(MCUBOOT_SIGN_RSA)
.key = rsa_pub_key,
.len = &rsa_pub_key_len,
#elif defined(MCUBOOT_SIGN_EC256)
.key = ecdsa_pub_key,
.len = &ecdsa_pub_key_len,
#elif defined(MCUBOOT_SIGN_ED25519)
.key = ed25519_pub_key,
.len = &ed25519_pub_key_len,
#endif
},
};
const int bootutil_key_cnt = 1;
#if defined(MCUBOOT_ENCRYPT_RSA)
extern const unsigned char enc_priv_key[];
extern const unsigned int enc_priv_key_len;
const struct bootutil_key bootutil_enc_key = {
.key = enc_priv_key,
.len = &enc_priv_key_len,
};
#elif defined(MCUBOOT_ENCRYPT_KW)
#error "Encrypted images with AES-KW is not implemented yet."
#endif
#endif
| utzig/mcuboot | boot/mbed/app_enc_keys.c | C | apache-2.0 | 2,391 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
12609,
11157,
4774,
1008,
23772,
2595,
1011,
6105,
1011,
8909,
4765,
18095,
1024,
15895,
1011,
1016,
1012,
1014,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
# $Id: memory_storage.h 1754 2006-05-05 12:43:18Z nlehuen $
# Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __MEMORY_STORAGE__H_INCLUDED__
#define __MEMORY_STORAGE__H_INCLUDED__
#include <vector>
#include <map>
#include <algorithm>
template <typename charT,typename valueT>
class memory_storage {
public:
typedef typename std::vector< tst_node<charT,valueT> > array_type;
typedef typename array_type::iterator iterator_type;
typedef typename array_type::reverse_iterator reverse_iterator_type;
typedef typename array_type::size_type size_type;
memory_storage(int initial_size) : array(), empty(UNDEFINED_INDEX) {
array.reserve(initial_size);
}
~memory_storage() {
}
inline tst_node<charT,valueT>* get(int index) {
return &(array[index]);
}
inline void delete_node(int index) {
get(index)->next = empty;
empty = index;
}
void new_node(node_info<charT,valueT>* info);
void pack(int& root);
void erase() {
array_type().swap(array);
};
typename array_type::size_type size() {
return array.size();
}
protected:
array_type array;
int empty;
};
template <typename charT,typename valueT>
void memory_storage<charT,valueT>::new_node(node_info<charT,valueT>* info) {
if(empty!=UNDEFINED_INDEX) {
// si on a un noeud vide on l'utilise.
info->index=empty;
info->node=get(empty);
info->node->reset();
// on passe au noeud vide suivant.
empty = get(empty)->next;
}
else {
// on construit un noeud supplémentaire dans le tableau.
info->index = (int)array.size();
array.resize(array.size()+1);
// array.push_back(tst_node<charT,valueT>()); // Plus ou moins rapide ?
info->node=get(info->index);
}
}
template <typename charT,typename valueT>
void memory_storage<charT,valueT>::pack(int& root) {
if(empty == UNDEFINED_INDEX) {
return;
}
// Etape 1 : on construit un vector des numéros de noeuds vide
std::vector<int> empty_nodes;
while(empty!=UNDEFINED_INDEX) {
empty_nodes.push_back(empty);
empty = get(empty)->next;
}
// Etape 2 : on trie ce vecteur
std::sort(empty_nodes.begin(),empty_nodes.end());
// Etape 3 : on remplit les noeuds vides avec des noeuds pleins pris en
// fin du storage
std::map<int,int> mapping; // sera utile en étape 4
int current_empty_node=0, last_empty_node = static_cast<int>(empty_nodes.size())-1;
int last_node_index = static_cast<int>(array.size())-1 ;
while(current_empty_node<=last_empty_node) {
int last_empty_node_index = empty_nodes[last_empty_node];
if(last_empty_node_index<last_node_index) {
// le dernier noeud est plein
// on l'échange avec le premier noeud vide
int current_empty_node_index = empty_nodes[current_empty_node];
mapping[last_node_index] = current_empty_node_index;
array[current_empty_node_index] = array[last_node_index];
--last_node_index;
++current_empty_node;
}
else {
// le dernier noeud est vide
// on le supprime
--last_node_index;
--last_empty_node;
}
}
// Etape 4 : on réécrit les indices
std::map<int,int>::const_iterator item,end(mapping.end());
// La racine a peut-être bougé ?
item = mapping.find(root);
if(item!=end) {
root = item->second;
}
last_empty_node = 0;
while(last_empty_node <= last_node_index) {
tst_node<charT,valueT>* node = get(last_empty_node);
if(node->left!=UNDEFINED_INDEX) {
item = mapping.find(node->left);
if(item!=end) {
node->left = item->second;
}
}
if(node->right!=UNDEFINED_INDEX) {
item = mapping.find(node->right);
if(item!=end) {
node->right = item->second;
}
}
if(node->next!=UNDEFINED_INDEX) {
item = mapping.find(node->next);
if(item!=end) {
node->next = item->second;
}
}
++last_empty_node;
}
// Etape 5 : on redimensionne le tableau
array.resize(last_node_index+1);
array_type(array).swap(array);
}
#endif
| yatsu/ruby-pytst | include/memory_storage.h | C | lgpl-2.1 | 5,325 | [
30522,
1013,
1008,
1001,
1002,
8909,
1024,
3638,
1035,
5527,
1012,
1044,
22593,
2294,
1011,
5709,
1011,
5709,
2260,
1024,
4724,
1024,
2324,
2480,
17953,
11106,
24997,
1002,
1001,
9385,
1006,
1039,
1007,
2432,
1011,
2384,
9473,
3393,
20169,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link href="../../../../../src/css/29tree.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tree" id="c1">
<div class="root open">
<div class="tag">
<div class="text">XLib</div>
</div>
<div class="childs">
<div class="folder normal open">
<div class="tag">
<div class="text">base</div>
</div>
<div class="childs">
<div class="txt normal close">
<div class="tag">
<div class="text">basis</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">extend</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">core</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">out</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">dom</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">css</div>
</div>
<div class="childs"></div>
</div>
<div class="txt last close">
<div class="tag">
<div class="text">createdom</div>
</div>
<div class="childs"></div>
</div>
</div>
</div>
<div class="folder normal close">
<div class="tag">
<div class="text">ui</div>
</div>
<div class="childs">
<div class="txt normal close">
<div class="tag">
<div class="text">basis</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">extend</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">core</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">out</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">dom</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">css</div>
</div>
<div class="childs"></div>
</div>
<div class="txt last close">
<div class="tag">
<div class="text">createdom</div>
</div>
<div class="childs"></div>
</div>
</div>
</div>
<div class="folder last close">
<div class="tag">
<div class="text">grid</div>
</div>
<div class="childs">
<div class="txt normal close">
<div class="tag">
<div class="text">basis</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">extend</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">core</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">out</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">dom</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">css</div>
</div>
<div class="childs"></div>
</div>
<div class="txt last close">
<div class="tag">
<div class="text">createdom</div>
</div>
<div class="childs"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| ldjking/sharegrid | web/examples/xlib/5tree/50old/51tree/tree_design_0.8.html | HTML | apache-2.0 | 4,959 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
20950,
3619,
1027,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
2639,
1013,
1060,
11039,
19968,
1000,
1028,
1026,
2132,
1028,
1026,
18804,
8299,
1011,
1041,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# encoding: utf-8
# (c) 2011 Martin Kozák (martinkozak@martinkozak.net)
require "abstract"
##
# Base +Unified Queues+ module.
#
module UnifiedQueues
##
# Universal single queue interface.
#
class Single
##
# Abstract single driver class.
# @abstract
#
class Driver
##
# Holds native object.
# @return [Object]
#
attr_accessor :native
@native
##
# Constructor.
#
def initialize(cls, *args, &block)
if self.instance_of? UnifiedQueues::Single::Driver
not_implemented
end
if cls.kind_of? Class
@native = cls::new(*args, &block)
else
@native = cls
end
end
##
# Pushes the value into the queue.
#
# @param [Object] value value for push
# @param [Object] key key for priority queues
# @abstract
#
def push(value, key = value, &block)
not_implemented
end
alias :<< :push
##
# Pops value out of the queue.
#
# @param [Boolean|Integer] blocking +true+ or timeout if it should block, +false+ otherwise
# @param [Object] queue value
# @abstract
#
def pop(blocking = false, &block)
not_implemented
end
##
# Indicates queue is empty.
#
# @param [Boolean] +true+ if it's, +false+ otherwise
# @abstract
#
def empty?(&block)
not_implemented
end
##
# Clears the queue.
# @abstract
#
def clear!(&block)
while not self.pop.nil?
end
end
alias :clear :clear!
##
# Returns length of the queue.
#
# @return [Integer]
# @abstract
#
def length(&block)
not_implemented
end
alias :size :length
##
# Returs type of the queue. Queue can be +:linear+ which means,
# calls values are returned using +return+ or +:evented+
# which indicates necessity of callbacks.
#
# @return [:linear, :evented]
# @abstract
#
def type
not_implemented
end
##
# Indicates, driver is evented so expexts callbacks.
# @return [Boolean] +true+ if it is, +false+ otherwise
#
def evented?
self.type == :evented
end
##
# Indicates, driver is evented so expexts callbacks.
# @return [Boolean] +true+ if it is, +false+ otherwise
#
def linear?
self.type == :linear
end
end
end
end | martinkozak/unified-queues | lib/unified-queues/single/driver.rb | Ruby | mit | 3,560 | [
30522,
1001,
17181,
1024,
21183,
2546,
1011,
1022,
1001,
1006,
1039,
1007,
2249,
3235,
12849,
20685,
1006,
3235,
3683,
20685,
1030,
3235,
3683,
20685,
1012,
5658,
1007,
5478,
1000,
10061,
1000,
1001,
1001,
1001,
2918,
1009,
10562,
24240,
20... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
.navbar-brand {
font-family: javloFont, Verdana;
} | Javlo/javlo | src/main/webapp/WEB-INF/template-plugin/javlo_design/css/javlo_design.css | CSS | lgpl-3.0 | 51 | [
30522,
1012,
6583,
26493,
2906,
1011,
4435,
1063,
15489,
1011,
2155,
1024,
14855,
2615,
4135,
14876,
3372,
1010,
2310,
26992,
2050,
1025,
1065,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
task :after_symlink do
%w{ database.yml}.each do |c|
run "ln -nsf #{shared_path}/system/config/#{c} #{current_path}/config/#{c}"
end
end
| anildigital/planet | config/database.rb | Ruby | mit | 151 | [
30522,
4708,
1024,
2044,
1035,
25353,
19968,
19839,
2079,
1003,
1059,
1063,
7809,
1012,
1061,
19968,
1065,
1012,
2169,
2079,
1064,
1039,
1064,
2448,
1000,
1048,
2078,
1011,
24978,
2546,
1001,
1063,
4207,
1035,
4130,
1065,
1013,
2291,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package scala
package object macros
extends scala.macros.config.Api
with scala.macros.config.Aliases
with scala.macros.inputs.Api
with scala.macros.inputs.Aliases
with scala.macros.prettyprinters.Api
with scala.macros.prettyprinters.Aliases
with scala.macros.trees.Api
with scala.macros.trees.Aliases
with scala.macros.semantic.Api
with scala.macros.semantic.Aliases
with scala.macros.Universe {
private[macros] val universe = new ThreadLocal[scala.macros.Universe]
private[macros] def abstracts = {
if (universe.get == null) sys.error("this API can only be called in a macro expansion")
universe.get.abstracts.asInstanceOf[Abstracts]
}
}
| xeno-by/scalamacros | core/src/main/scala/scala/macros/package.scala | Scala | bsd-3-clause | 699 | [
30522,
7427,
26743,
7427,
4874,
26632,
2015,
8908,
26743,
1012,
26632,
2015,
1012,
9530,
8873,
2290,
1012,
17928,
2007,
26743,
1012,
26632,
2015,
1012,
9530,
8873,
2290,
1012,
14593,
2229,
2007,
26743,
1012,
26632,
2015,
1012,
20407,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*-
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* -Changed package name
* -Removed Android dependencies
* -Removed/replaced Java SE dependencies
* -Removed/replaced annotations
*/
package com.google.authenticator.blackberry;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.ByteArrayOutputStream;
import java.util.Vector;
/**
* Immutable URI reference. A URI reference includes a URI and a fragment, the
* component of the URI following a '#'. Builds and parses URI references
* which conform to
* <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>.
*
* <p>In the interest of performance, this class performs little to no
* validation. Behavior is undefined for invalid input. This class is very
* forgiving--in the face of invalid input, it will return garbage
* rather than throw an exception unless otherwise specified.
*/
public abstract class Uri {
/*
This class aims to do as little up front work as possible. To accomplish
that, we vary the implementation dependending on what the user passes in.
For example, we have one implementation if the user passes in a
URI string (StringUri) and another if the user passes in the
individual components (OpaqueUri).
*Concurrency notes*: Like any truly immutable object, this class is safe
for concurrent use. This class uses a caching pattern in some places where
it doesn't use volatile or synchronized. This is safe to do with ints
because getting or setting an int is atomic. It's safe to do with a String
because the internal fields are final and the memory model guarantees other
threads won't see a partially initialized instance. We are not guaranteed
that some threads will immediately see changes from other threads on
certain platforms, but we don't mind if those threads reconstruct the
cached result. As a result, we get thread safe caching with no concurrency
overhead, which means the most common case, access from a single thread,
is as fast as possible.
From the Java Language spec.:
"17.5 Final Field Semantics
... when the object is seen by another thread, that thread will always
see the correctly constructed version of that object's final fields.
It will also see versions of any object or array referenced by
those final fields that are at least as up-to-date as the final fields
are."
In that same vein, all non-transient fields within Uri
implementations should be final and immutable so as to ensure true
immutability for clients even when they don't use proper concurrency
control.
For reference, from RFC 2396:
"4.3. Parsing a URI Reference
A URI reference is typically parsed according to the four main
components and fragment identifier in order to determine what
components are present and whether the reference is relative or
absolute. The individual components are then parsed for their
subparts and, if not opaque, to verify their validity.
Although the BNF defines what is allowed in each component, it is
ambiguous in terms of differentiating between an authority component
and a path component that begins with two slash characters. The
greedy algorithm is used for disambiguation: the left-most matching
rule soaks up as much of the URI reference string as it is capable of
matching. In other words, the authority component wins."
The "four main components" of a hierarchical URI consist of
<scheme>://<authority><path>?<query>
*/
/**
* NOTE: EMPTY accesses this field during its own initialization, so this
* field *must* be initialized first, or else EMPTY will see a null value!
*
* Placeholder for strings which haven't been cached. This enables us
* to cache null. We intentionally create a new String instance so we can
* compare its identity and there is no chance we will confuse it with
* user data.
*/
private static final String NOT_CACHED = new String("NOT CACHED");
/**
* The empty URI, equivalent to "".
*/
public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL,
PathPart.EMPTY, Part.NULL, Part.NULL);
/**
* Prevents external subclassing.
*/
private Uri() {}
/**
* Returns true if this URI is hierarchical like "http://google.com".
* Absolute URIs are hierarchical if the scheme-specific part starts with
* a '/'. Relative URIs are always hierarchical.
*/
public abstract boolean isHierarchical();
/**
* Returns true if this URI is opaque like "mailto:nobody@google.com". The
* scheme-specific part of an opaque URI cannot start with a '/'.
*/
public boolean isOpaque() {
return !isHierarchical();
}
/**
* Returns true if this URI is relative, i.e. if it doesn't contain an
* explicit scheme.
*
* @return true if this URI is relative, false if it's absolute
*/
public abstract boolean isRelative();
/**
* Returns true if this URI is absolute, i.e. if it contains an
* explicit scheme.
*
* @return true if this URI is absolute, false if it's relative
*/
public boolean isAbsolute() {
return !isRelative();
}
/**
* Gets the scheme of this URI. Example: "http"
*
* @return the scheme or null if this is a relative URI
*/
public abstract String getScheme();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Decodes escaped octets.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getSchemeSpecificPart();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Leaves escaped octets
* intact.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getEncodedSchemeSpecificPart();
/**
* Gets the decoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "bob@google.com:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getAuthority();
/**
* Gets the encoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "bob@google.com:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getEncodedAuthority();
/**
* Gets the decoded user information from the authority.
* For example, if the authority is "nobody@google.com", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getUserInfo();
/**
* Gets the encoded user information from the authority.
* For example, if the authority is "nobody@google.com", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getEncodedUserInfo();
/**
* Gets the encoded host from the authority for this URI. For example,
* if the authority is "bob@google.com", this method will return
* "google.com".
*
* @return the host for this URI or null if not present
*/
public abstract String getHost();
/**
* Gets the port from the authority for this URI. For example,
* if the authority is "google.com:80", this method will return 80.
*
* @return the port for this URI or -1 if invalid or not present
*/
public abstract int getPort();
/**
* Gets the decoded path.
*
* @return the decoded path, or null if this is not a hierarchical URI
* (like "mailto:nobody@google.com") or the URI is invalid
*/
public abstract String getPath();
/**
* Gets the encoded path.
*
* @return the encoded path, or null if this is not a hierarchical URI
* (like "mailto:nobody@google.com") or the URI is invalid
*/
public abstract String getEncodedPath();
/**
* Gets the decoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the decoded query or null if there isn't one
*/
public abstract String getQuery();
/**
* Gets the encoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the encoded query or null if there isn't one
*/
public abstract String getEncodedQuery();
/**
* Gets the decoded fragment part of this URI, everything after the '#'.
*
* @return the decoded fragment or null if there isn't one
*/
public abstract String getFragment();
/**
* Gets the encoded fragment part of this URI, everything after the '#'.
*
* @return the encoded fragment or null if there isn't one
*/
public abstract String getEncodedFragment();
/**
* Gets the decoded path segments.
*
* @return decoded path segments, each without a leading or trailing '/'
*/
public abstract String[] getPathSegments();
/**
* Gets the decoded last segment in the path.
*
* @return the decoded last segment or null if the path is empty
*/
public abstract String getLastPathSegment();
/**
* Compares this Uri to another object for equality. Returns true if the
* encoded string representations of this Uri and the given Uri are
* equal. Case counts. Paths are not normalized. If one Uri specifies a
* default port explicitly and the other leaves it implicit, they will not
* be considered equal.
*/
public boolean equals(Object o) {
if (!(o instanceof Uri)) {
return false;
}
Uri other = (Uri) o;
return toString().equals(other.toString());
}
/**
* Hashes the encoded string represention of this Uri consistently with
* {@link #equals(Object)}.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Compares the string representation of this Uri with that of
* another.
*/
public int compareTo(Uri other) {
return toString().compareTo(other.toString());
}
/**
* Returns the encoded string representation of this URI.
* Example: "http://google.com/"
*/
public abstract String toString();
/**
* Constructs a new builder, copying the attributes from this Uri.
*/
public abstract Builder buildUpon();
/** Index of a component which was not found. */
private final static int NOT_FOUND = -1;
/** Placeholder value for an index which hasn't been calculated yet. */
private final static int NOT_CALCULATED = -2;
/**
* Error message presented when a user tries to treat an opaque URI as
* hierarchical.
*/
private static final String NOT_HIERARCHICAL
= "This isn't a hierarchical URI.";
/** Default encoding. */
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* Creates a Uri which parses the given encoded URI string.
*
* @param uriString an RFC 2396-compliant, encoded URI
* @throws NullPointerException if uriString is null
* @return Uri for this given uri string
*/
public static Uri parse(String uriString) {
return new StringUri(uriString);
}
/**
* An implementation which wraps a String URI. This URI can be opaque or
* hierarchical, but we extend AbstractHierarchicalUri in case we need
* the hierarchical functionality.
*/
private static class StringUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 1;
/** URI string representation. */
private final String uriString;
private StringUri(String uriString) {
if (uriString == null) {
throw new NullPointerException("uriString");
}
this.uriString = uriString;
}
/** Cached scheme separator index. */
private volatile int cachedSsi = NOT_CALCULATED;
/** Finds the first ':'. Returns -1 if none found. */
private int findSchemeSeparator() {
return cachedSsi == NOT_CALCULATED
? cachedSsi = uriString.indexOf(':')
: cachedSsi;
}
/** Cached fragment separator index. */
private volatile int cachedFsi = NOT_CALCULATED;
/** Finds the first '#'. Returns -1 if none found. */
private int findFragmentSeparator() {
return cachedFsi == NOT_CALCULATED
? cachedFsi = uriString.indexOf('#', findSchemeSeparator())
: cachedFsi;
}
public boolean isHierarchical() {
int ssi = findSchemeSeparator();
if (ssi == NOT_FOUND) {
// All relative URIs are hierarchical.
return true;
}
if (uriString.length() == ssi + 1) {
// No ssp.
return false;
}
// If the ssp starts with a '/', this is hierarchical.
return uriString.charAt(ssi + 1) == '/';
}
public boolean isRelative() {
// Note: We return true if the index is 0
return findSchemeSeparator() == NOT_FOUND;
}
private volatile String scheme = NOT_CACHED;
public String getScheme() {
boolean cached = (scheme != NOT_CACHED);
return cached ? scheme : (scheme = parseScheme());
}
private String parseScheme() {
int ssi = findSchemeSeparator();
return ssi == NOT_FOUND ? null : uriString.substring(0, ssi);
}
private Part ssp;
private Part getSsp() {
return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
private String parseSsp() {
int ssi = findSchemeSeparator();
int fsi = findFragmentSeparator();
// Return everything between ssi and fsi.
return fsi == NOT_FOUND
? uriString.substring(ssi + 1)
: uriString.substring(ssi + 1, fsi);
}
private Part authority;
private Part getAuthorityPart() {
if (authority == null) {
String encodedAuthority
= parseAuthority(this.uriString, findSchemeSeparator());
return authority = Part.fromEncoded(encodedAuthority);
}
return authority;
}
public String getEncodedAuthority() {
return getAuthorityPart().getEncoded();
}
public String getAuthority() {
return getAuthorityPart().getDecoded();
}
private PathPart path;
private PathPart getPathPart() {
return path == null
? path = PathPart.fromEncoded(parsePath())
: path;
}
public String getPath() {
return getPathPart().getDecoded();
}
public String getEncodedPath() {
return getPathPart().getEncoded();
}
public String[] getPathSegments() {
return getPathPart().getPathSegments().segments;
}
private String parsePath() {
String uriString = this.uriString;
int ssi = findSchemeSeparator();
// If the URI is absolute.
if (ssi > -1) {
// Is there anything after the ':'?
boolean schemeOnly = ssi + 1 == uriString.length();
if (schemeOnly) {
// Opaque URI.
return null;
}
// A '/' after the ':' means this is hierarchical.
if (uriString.charAt(ssi + 1) != '/') {
// Opaque URI.
return null;
}
} else {
// All relative URIs are hierarchical.
}
return parsePath(uriString, ssi);
}
private Part query;
private Part getQueryPart() {
return query == null
? query = Part.fromEncoded(parseQuery()) : query;
}
public String getEncodedQuery() {
return getQueryPart().getEncoded();
}
private String parseQuery() {
// It doesn't make sense to cache this index. We only ever
// calculate it once.
int qsi = uriString.indexOf('?', findSchemeSeparator());
if (qsi == NOT_FOUND) {
return null;
}
int fsi = findFragmentSeparator();
if (fsi == NOT_FOUND) {
return uriString.substring(qsi + 1);
}
if (fsi < qsi) {
// Invalid.
return null;
}
return uriString.substring(qsi + 1, fsi);
}
public String getQuery() {
return getQueryPart().getDecoded();
}
private Part fragment;
private Part getFragmentPart() {
return fragment == null
? fragment = Part.fromEncoded(parseFragment()) : fragment;
}
public String getEncodedFragment() {
return getFragmentPart().getEncoded();
}
private String parseFragment() {
int fsi = findFragmentSeparator();
return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1);
}
public String getFragment() {
return getFragmentPart().getDecoded();
}
public String toString() {
return uriString;
}
/**
* Parses an authority out of the given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the authority or null if none is found
*/
static String parseAuthority(String uriString, int ssi) {
int length = uriString.length();
// If "//" follows the scheme separator, we have an authority.
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// We have an authority.
// Look for the start of the path, query, or fragment, or the
// end of the string.
int end = ssi + 3;
LOOP: while (end < length) {
switch (uriString.charAt(end)) {
case '/': // Start of path
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
end++;
}
return uriString.substring(ssi + 3, end);
} else {
return null;
}
}
/**
* Parses a path out of this given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the path
*/
static String parsePath(String uriString, int ssi) {
int length = uriString.length();
// Find start of path.
int pathStart;
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// Skip over authority to path.
pathStart = ssi + 3;
LOOP: while (pathStart < length) {
switch (uriString.charAt(pathStart)) {
case '?': // Start of query
case '#': // Start of fragment
return ""; // Empty path.
case '/': // Start of path!
break LOOP;
}
pathStart++;
}
} else {
// Path starts immediately after scheme separator.
pathStart = ssi + 1;
}
// Find end of path.
int pathEnd = pathStart;
LOOP: while (pathEnd < length) {
switch (uriString.charAt(pathEnd)) {
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
pathEnd++;
}
return uriString.substring(pathStart, pathEnd);
}
public Builder buildUpon() {
if (isHierarchical()) {
return new Builder()
.scheme(getScheme())
.authority(getAuthorityPart())
.path(getPathPart())
.query(getQueryPart())
.fragment(getFragmentPart());
} else {
return new Builder()
.scheme(getScheme())
.opaquePart(getSsp())
.fragment(getFragmentPart());
}
}
}
/**
* Creates an opaque Uri from the given components. Encodes the ssp
* which means this method cannot be used to create hierarchical URIs.
*
* @param scheme of the URI
* @param ssp scheme-specific-part, everything between the
* scheme separator (':') and the fragment separator ('#'), which will
* get encoded
* @param fragment fragment, everything after the '#', null if undefined,
* will get encoded
*
* @throws NullPointerException if scheme or ssp is null
* @return Uri composed of the given scheme, ssp, and fragment
*
* @see Builder if you don't want the ssp and fragment to be encoded
*/
public static Uri fromParts(String scheme, String ssp,
String fragment) {
if (scheme == null) {
throw new NullPointerException("scheme");
}
if (ssp == null) {
throw new NullPointerException("ssp");
}
return new OpaqueUri(scheme, Part.fromDecoded(ssp),
Part.fromDecoded(fragment));
}
/**
* Opaque URI.
*/
private static class OpaqueUri extends Uri {
/** Used in parcelling. */
static final int TYPE_ID = 2;
private final String scheme;
private final Part ssp;
private final Part fragment;
private OpaqueUri(String scheme, Part ssp, Part fragment) {
this.scheme = scheme;
this.ssp = ssp;
this.fragment = fragment == null ? Part.NULL : fragment;
}
public boolean isHierarchical() {
return false;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return this.scheme;
}
public String getEncodedSchemeSpecificPart() {
return ssp.getEncoded();
}
public String getSchemeSpecificPart() {
return ssp.getDecoded();
}
public String getAuthority() {
return null;
}
public String getEncodedAuthority() {
return null;
}
public String getPath() {
return null;
}
public String getEncodedPath() {
return null;
}
public String getQuery() {
return null;
}
public String getEncodedQuery() {
return null;
}
public String getFragment() {
return fragment.getDecoded();
}
public String getEncodedFragment() {
return fragment.getEncoded();
}
public String[] getPathSegments() {
return new String[0];
}
public String getLastPathSegment() {
return null;
}
public String getUserInfo() {
return null;
}
public String getEncodedUserInfo() {
return null;
}
public String getHost() {
return null;
}
public int getPort() {
return -1;
}
private volatile String cachedString = NOT_CACHED;
public String toString() {
boolean cached = cachedString != NOT_CACHED;
if (cached) {
return cachedString;
}
StringBuffer sb = new StringBuffer();
sb.append(scheme).append(':');
sb.append(getEncodedSchemeSpecificPart());
if (!fragment.isEmpty()) {
sb.append('#').append(fragment.getEncoded());
}
return cachedString = sb.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(this.scheme)
.opaquePart(this.ssp)
.fragment(this.fragment);
}
}
/**
* Wrapper for path segment array.
*/
static class PathSegments {
static final PathSegments EMPTY = new PathSegments(null, 0);
final String[] segments;
final int size;
PathSegments(String[] segments, int size) {
this.segments = segments;
this.size = size;
}
public String get(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
return segments[index];
}
public int size() {
return this.size;
}
}
/**
* Builds PathSegments.
*/
static class PathSegmentsBuilder {
String[] segments;
int size = 0;
void add(String segment) {
if (segments == null) {
segments = new String[4];
} else if (size + 1 == segments.length) {
String[] expanded = new String[segments.length * 2];
System.arraycopy(segments, 0, expanded, 0, segments.length);
segments = expanded;
}
segments[size++] = segment;
}
PathSegments build() {
if (segments == null) {
return PathSegments.EMPTY;
}
try {
return new PathSegments(segments, size);
} finally {
// Makes sure this doesn't get reused.
segments = null;
}
}
}
/**
* Support for hierarchical URIs.
*/
private abstract static class AbstractHierarchicalUri extends Uri {
public String getLastPathSegment() {
// TODO: If we haven't parsed all of the segments already, just
// grab the last one directly so we only allocate one string.
String[] segments = getPathSegments();
int size = segments.length;
if (size == 0) {
return null;
}
return segments[size - 1];
}
private Part userInfo;
private Part getUserInfoPart() {
return userInfo == null
? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo;
}
public final String getEncodedUserInfo() {
return getUserInfoPart().getEncoded();
}
private String parseUserInfo() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
int end = authority.indexOf('@');
return end == NOT_FOUND ? null : authority.substring(0, end);
}
public String getUserInfo() {
return getUserInfoPart().getDecoded();
}
private volatile String host = NOT_CACHED;
public String getHost() {
boolean cached = (host != NOT_CACHED);
return cached ? host
: (host = parseHost());
}
private String parseHost() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
// Parse out user info and then port.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
String encodedHost = portSeparator == NOT_FOUND
? authority.substring(userInfoSeparator + 1)
: authority.substring(userInfoSeparator + 1, portSeparator);
return decode(encodedHost);
}
private volatile int port = NOT_CALCULATED;
public int getPort() {
return port == NOT_CALCULATED
? port = parsePort()
: port;
}
private int parsePort() {
String authority = getEncodedAuthority();
if (authority == null) {
return -1;
}
// Make sure we look for the port separtor *after* the user info
// separator. We have URLs with a ':' in the user info.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
if (portSeparator == NOT_FOUND) {
return -1;
}
String portString = decode(authority.substring(portSeparator + 1));
try {
return Integer.parseInt(portString);
} catch (NumberFormatException e) {
return -1;
}
}
}
/**
* Hierarchical Uri.
*/
private static class HierarchicalUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 3;
private final String scheme; // can be null
private final Part authority;
private final PathPart path;
private final Part query;
private final Part fragment;
private HierarchicalUri(String scheme, Part authority, PathPart path,
Part query, Part fragment) {
this.scheme = scheme;
this.authority = Part.nonNull(authority);
this.path = path == null ? PathPart.NULL : path;
this.query = Part.nonNull(query);
this.fragment = Part.nonNull(fragment);
}
public boolean isHierarchical() {
return true;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return scheme;
}
private Part ssp;
private Part getSsp() {
return ssp == null
? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
/**
* Creates the encoded scheme-specific part from its sub parts.
*/
private String makeSchemeSpecificPart() {
StringBuffer builder = new StringBuffer();
appendSspTo(builder);
return builder.toString();
}
private void appendSspTo(StringBuffer builder) {
String encodedAuthority = authority.getEncoded();
if (encodedAuthority != null) {
// Even if the authority is "", we still want to append "//".
builder.append("//").append(encodedAuthority);
}
String encodedPath = path.getEncoded();
if (encodedPath != null) {
builder.append(encodedPath);
}
if (!query.isEmpty()) {
builder.append('?').append(query.getEncoded());
}
}
public String getAuthority() {
return this.authority.getDecoded();
}
public String getEncodedAuthority() {
return this.authority.getEncoded();
}
public String getEncodedPath() {
return this.path.getEncoded();
}
public String getPath() {
return this.path.getDecoded();
}
public String getQuery() {
return this.query.getDecoded();
}
public String getEncodedQuery() {
return this.query.getEncoded();
}
public String getFragment() {
return this.fragment.getDecoded();
}
public String getEncodedFragment() {
return this.fragment.getEncoded();
}
public String[] getPathSegments() {
return this.path.getPathSegments().segments;
}
private volatile String uriString = NOT_CACHED;
/**
* {@inheritDoc}
*/
public String toString() {
boolean cached = (uriString != NOT_CACHED);
return cached ? uriString
: (uriString = makeUriString());
}
private String makeUriString() {
StringBuffer builder = new StringBuffer();
if (scheme != null) {
builder.append(scheme).append(':');
}
appendSspTo(builder);
if (!fragment.isEmpty()) {
builder.append('#').append(fragment.getEncoded());
}
return builder.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(scheme)
.authority(authority)
.path(path)
.query(query)
.fragment(fragment);
}
}
/**
* Helper class for building or manipulating URI references. Not safe for
* concurrent use.
*
* <p>An absolute hierarchical URI reference follows the pattern:
* {@code <scheme>://<authority><absolute path>?<query>#<fragment>}
*
* <p>Relative URI references (which are always hierarchical) follow one
* of two patterns: {@code <relative or absolute path>?<query>#<fragment>}
* or {@code //<authority><absolute path>?<query>#<fragment>}
*
* <p>An opaque URI follows this pattern:
* {@code <scheme>:<opaque part>#<fragment>}
*/
public static final class Builder {
private String scheme;
private Part opaquePart;
private Part authority;
private PathPart path;
private Part query;
private Part fragment;
/**
* Constructs a new Builder.
*/
public Builder() {}
/**
* Sets the scheme.
*
* @param scheme name or {@code null} if this is a relative Uri
*/
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
Builder opaquePart(Part opaquePart) {
this.opaquePart = opaquePart;
return this;
}
/**
* Encodes and sets the given opaque scheme-specific-part.
*
* @param opaquePart decoded opaque part
*/
public Builder opaquePart(String opaquePart) {
return opaquePart(Part.fromDecoded(opaquePart));
}
/**
* Sets the previously encoded opaque scheme-specific-part.
*
* @param opaquePart encoded opaque part
*/
public Builder encodedOpaquePart(String opaquePart) {
return opaquePart(Part.fromEncoded(opaquePart));
}
Builder authority(Part authority) {
// This URI will be hierarchical.
this.opaquePart = null;
this.authority = authority;
return this;
}
/**
* Encodes and sets the authority.
*/
public Builder authority(String authority) {
return authority(Part.fromDecoded(authority));
}
/**
* Sets the previously encoded authority.
*/
public Builder encodedAuthority(String authority) {
return authority(Part.fromEncoded(authority));
}
Builder path(PathPart path) {
// This URI will be hierarchical.
this.opaquePart = null;
this.path = path;
return this;
}
/**
* Sets the path. Leaves '/' characters intact but encodes others as
* necessary.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder path(String path) {
return path(PathPart.fromDecoded(path));
}
/**
* Sets the previously encoded path.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder encodedPath(String path) {
return path(PathPart.fromEncoded(path));
}
/**
* Encodes the given segment and appends it to the path.
*/
public Builder appendPath(String newSegment) {
return path(PathPart.appendDecodedSegment(path, newSegment));
}
/**
* Appends the given segment to the path.
*/
public Builder appendEncodedPath(String newSegment) {
return path(PathPart.appendEncodedSegment(path, newSegment));
}
Builder query(Part query) {
// This URI will be hierarchical.
this.opaquePart = null;
this.query = query;
return this;
}
/**
* Encodes and sets the query.
*/
public Builder query(String query) {
return query(Part.fromDecoded(query));
}
/**
* Sets the previously encoded query.
*/
public Builder encodedQuery(String query) {
return query(Part.fromEncoded(query));
}
Builder fragment(Part fragment) {
this.fragment = fragment;
return this;
}
/**
* Encodes and sets the fragment.
*/
public Builder fragment(String fragment) {
return fragment(Part.fromDecoded(fragment));
}
/**
* Sets the previously encoded fragment.
*/
public Builder encodedFragment(String fragment) {
return fragment(Part.fromEncoded(fragment));
}
/**
* Encodes the key and value and then appends the parameter to the
* query string.
*
* @param key which will be encoded
* @param value which will be encoded
*/
public Builder appendQueryParameter(String key, String value) {
// This URI will be hierarchical.
this.opaquePart = null;
String encodedParameter = encode(key, null) + "="
+ encode(value, null);
if (query == null) {
query = Part.fromEncoded(encodedParameter);
return this;
}
String oldQuery = query.getEncoded();
if (oldQuery == null || oldQuery.length() == 0) {
query = Part.fromEncoded(encodedParameter);
} else {
query = Part.fromEncoded(oldQuery + "&" + encodedParameter);
}
return this;
}
/**
* Constructs a Uri with the current attributes.
*
* @throws UnsupportedOperationException if the URI is opaque and the
* scheme is null
*/
public Uri build() {
if (opaquePart != null) {
if (this.scheme == null) {
throw new UnsupportedOperationException(
"An opaque URI must have a scheme.");
}
return new OpaqueUri(scheme, opaquePart, fragment);
} else {
// Hierarchical URIs should not return null for getPath().
PathPart path = this.path;
if (path == null || path == PathPart.NULL) {
path = PathPart.EMPTY;
} else {
// If we have a scheme and/or authority, the path must
// be absolute. Prepend it with a '/' if necessary.
if (hasSchemeOrAuthority()) {
path = PathPart.makeAbsolute(path);
}
}
return new HierarchicalUri(
scheme, authority, path, query, fragment);
}
}
private boolean hasSchemeOrAuthority() {
return scheme != null
|| (authority != null && authority != Part.NULL);
}
/**
* {@inheritDoc}
*/
public String toString() {
return build().toString();
}
}
/**
* Searches the query string for parameter values with the given key.
*
* @param key which will be encoded
*
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return a list of decoded values
*/
public String[] getQueryParameters(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return new String[0];
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
// Prepend query with "&" making the first parameter the same as the
// rest.
query = "&" + query;
// Parameter prefix.
String prefix = "&" + encodedKey + "=";
Vector values = new Vector();
int start = 0;
int length = query.length();
while (start < length) {
start = query.indexOf(prefix, start);
if (start == -1) {
// No more values.
break;
}
// Move start to start of value.
start += prefix.length();
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
values.addElement(decode(value));
start = end;
}
int size = values.size();
String[] result = new String[size];
values.copyInto(result);
return result;
}
/**
* Searches the query string for the first value with the given key.
*
* @param key which will be encoded
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return the decoded value or null if no parameter is found
*/
public String getQueryParameter(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return null;
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
String prefix = encodedKey + "=";
if (query.length() < prefix.length()) {
return null;
}
int start;
if (query.startsWith(prefix)) {
// It's the first parameter.
start = prefix.length();
} else {
// It must be later in the query string.
prefix = "&" + prefix;
start = query.indexOf(prefix);
if (start == -1) {
// Not found.
return null;
}
start += prefix.length();
}
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
return decode(value);
}
private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters.
*
* @param s string to encode
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s) {
return encode(s, null);
}
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters with the exception of those specified in the
* allow argument.
*
* @param s string to encode
* @param allow set of additional characters to allow in the encoded form,
* null if no characters should be skipped
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s, String allow) {
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer encoded = null;
int oldLength = s.length();
// This loop alternates between copying over allowed characters and
// encoding in chunks. This results in fewer method calls and
// allocations than encoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over allowed chars.
// Find the next character which needs to be encoded.
int nextToEncode = current;
while (nextToEncode < oldLength
&& isAllowed(s.charAt(nextToEncode), allow)) {
nextToEncode++;
}
// If there's nothing more to encode...
if (nextToEncode == oldLength) {
if (current == 0) {
// We didn't need to encode anything!
return s;
} else {
// Presumably, we've already done some encoding.
encoded.append(s.substring(current, oldLength));
return encoded.toString();
}
}
if (encoded == null) {
encoded = new StringBuffer();
}
if (nextToEncode > current) {
// Append allowed characters leading up to this point.
encoded.append(s.substring(current, nextToEncode));
} else {
// assert nextToEncode == current
}
// Switch to "encoding" mode.
// Find the next allowed character.
current = nextToEncode;
int nextAllowed = current + 1;
while (nextAllowed < oldLength
&& !isAllowed(s.charAt(nextAllowed), allow)) {
nextAllowed++;
}
// Convert the substring to bytes and encode the bytes as
// '%'-escaped octets.
String toEncode = s.substring(current, nextAllowed);
try {
byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING);
int bytesLength = bytes.length;
for (int i = 0; i < bytesLength; i++) {
encoded.append('%');
encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
encoded.append(HEX_DIGITS[bytes[i] & 0xf]);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
current = nextAllowed;
}
// Encoded could still be null at this point if s is empty.
return encoded == null ? s : encoded.toString();
}
/**
* Returns true if the given character is allowed.
*
* @param c character to check
* @param allow characters to allow
* @return true if the character is allowed or false if it should be
* encoded
*/
private static boolean isAllowed(char c, String allow) {
return (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| "_-!.~'()*".indexOf(c) != NOT_FOUND
|| (allow != null && allow.indexOf(c) != NOT_FOUND);
}
/** Unicode replacement character: \\uFFFD. */
private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD };
/**
* Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
* Replaces invalid octets with the unicode replacement character
* ("\\uFFFD").
*
* @param s encoded string to decode
* @return the given string with escaped octets decoded, or null if
* s is null
*/
public static String decode(String s) {
/*
Compared to java.net.URLEncoderDecoder.decode(), this method decodes a
chunk at a time instead of one character at a time, and it doesn't
throw exceptions. It also only allocates memory when necessary--if
there's nothing to decode, this method won't do much.
*/
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer decoded = null;
ByteArrayOutputStream out = null;
int oldLength = s.length();
// This loop alternates between copying over normal characters and
// escaping in chunks. This results in fewer method calls and
// allocations than decoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over normal characters.
// Find the next escape sequence.
int nextEscape = s.indexOf('%', current);
if (nextEscape == NOT_FOUND) {
if (decoded == null) {
// We didn't actually decode anything.
return s;
} else {
// Append the remainder and return the decoded string.
decoded.append(s.substring(current, oldLength));
return decoded.toString();
}
}
// Prepare buffers.
if (decoded == null) {
// Looks like we're going to need the buffers...
// We know the new string will be shorter. Using the old length
// may overshoot a bit, but it will save us from resizing the
// buffer.
decoded = new StringBuffer(oldLength);
out = new ByteArrayOutputStream(4);
} else {
// Clear decoding buffer.
out.reset();
}
// Append characters leading up to the escape.
if (nextEscape > current) {
decoded.append(s.substring(current, nextEscape));
current = nextEscape;
} else {
// assert current == nextEscape
}
// Switch to "decoding" mode where we decode a string of escape
// sequences.
// Decode and append escape sequences. Escape sequences look like
// "%ab" where % is literal and a and b are hex digits.
try {
do {
if (current + 2 >= oldLength) {
// Truncated escape sequence.
out.write(REPLACEMENT);
} else {
int a = Character.digit(s.charAt(current + 1), 16);
int b = Character.digit(s.charAt(current + 2), 16);
if (a == -1 || b == -1) {
// Non hex digits.
out.write(REPLACEMENT);
} else {
// Combine the hex digits into one byte and write.
out.write((a << 4) + b);
}
}
// Move passed the escape sequence.
current += 3;
} while (current < oldLength && s.charAt(current) == '%');
// Decode UTF-8 bytes into a string and append it.
decoded.append(new String(out.toByteArray(), DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
} catch (IOException e) {
throw new RuntimeException("AssertionError: " + e);
}
}
// If we don't have a buffer, we didn't have to decode anything.
return decoded == null ? s : decoded.toString();
}
/**
* Support for part implementations.
*/
static abstract class AbstractPart {
/**
* Enum which indicates which representation of a given part we have.
*/
static class Representation {
static final int BOTH = 0;
static final int ENCODED = 1;
static final int DECODED = 2;
}
volatile String encoded;
volatile String decoded;
AbstractPart(String encoded, String decoded) {
this.encoded = encoded;
this.decoded = decoded;
}
abstract String getEncoded();
final String getDecoded() {
boolean hasDecoded = decoded != NOT_CACHED;
return hasDecoded ? decoded : (decoded = decode(encoded));
}
}
/**
* Immutable wrapper of encoded and decoded versions of a URI part. Lazily
* creates the encoded or decoded version from the other.
*/
static class Part extends AbstractPart {
/** A part with null values. */
static final Part NULL = new EmptyPart(null);
/** A part with empty strings for values. */
static final Part EMPTY = new EmptyPart("");
private Part(String encoded, String decoded) {
super(encoded, decoded);
}
boolean isEmpty() {
return false;
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
return hasEncoded ? encoded : (encoded = encode(decoded));
}
/**
* Returns given part or {@link #NULL} if the given part is null.
*/
static Part nonNull(Part part) {
return part == null ? NULL : part;
}
/**
* Creates a part from the encoded string.
*
* @param encoded part string
*/
static Part fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a part from the decoded string.
*
* @param decoded part string
*/
static Part fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a part from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static Part from(String encoded, String decoded) {
// We have to check both encoded and decoded in case one is
// NOT_CACHED.
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
if (decoded == null) {
return NULL;
}
if (decoded .length() == 0) {
return EMPTY;
}
return new Part(encoded, decoded);
}
private static class EmptyPart extends Part {
public EmptyPart(String value) {
super(value, value);
}
/**
* {@inheritDoc}
*/
boolean isEmpty() {
return true;
}
}
}
/**
* Immutable wrapper of encoded and decoded versions of a path part. Lazily
* creates the encoded or decoded version from the other.
*/
static class PathPart extends AbstractPart {
/** A part with null values. */
static final PathPart NULL = new PathPart(null, null);
/** A part with empty strings for values. */
static final PathPart EMPTY = new PathPart("", "");
private PathPart(String encoded, String decoded) {
super(encoded, decoded);
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
// Don't encode '/'.
return hasEncoded ? encoded : (encoded = encode(decoded, "/"));
}
/**
* Cached path segments. This doesn't need to be volatile--we don't
* care if other threads see the result.
*/
private PathSegments pathSegments;
/**
* Gets the individual path segments. Parses them if necessary.
*
* @return parsed path segments or null if this isn't a hierarchical
* URI
*/
PathSegments getPathSegments() {
if (pathSegments != null) {
return pathSegments;
}
String path = getEncoded();
if (path == null) {
return pathSegments = PathSegments.EMPTY;
}
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();
int previous = 0;
int current;
while ((current = path.indexOf('/', previous)) > -1) {
// This check keeps us from adding a segment if the path starts
// '/' and an empty segment for "//".
if (previous < current) {
String decodedSegment
= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);
}
previous = current + 1;
}
// Add in the final path segment.
if (previous < path.length()) {
segmentBuilder.add(decode(path.substring(previous)));
}
return pathSegments = segmentBuilder.build();
}
static PathPart appendEncodedSegment(PathPart oldPart,
String newSegment) {
// If there is no old path, should we make the new path relative
// or absolute? I pick absolute.
if (oldPart == null) {
// No old path.
return fromEncoded("/" + newSegment);
}
String oldPath = oldPart.getEncoded();
if (oldPath == null) {
oldPath = "";
}
int oldPathLength = oldPath.length();
String newPath;
if (oldPathLength == 0) {
// No old path.
newPath = "/" + newSegment;
} else if (oldPath.charAt(oldPathLength - 1) == '/') {
newPath = oldPath + newSegment;
} else {
newPath = oldPath + "/" + newSegment;
}
return fromEncoded(newPath);
}
static PathPart appendDecodedSegment(PathPart oldPart, String decoded) {
String encoded = encode(decoded);
// TODO: Should we reuse old PathSegments? Probably not.
return appendEncodedSegment(oldPart, encoded);
}
/**
* Creates a path from the encoded string.
*
* @param encoded part string
*/
static PathPart fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a path from the decoded string.
*
* @param decoded part string
*/
static PathPart fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a path from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static PathPart from(String encoded, String decoded) {
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
return new PathPart(encoded, decoded);
}
/**
* Prepends path values with "/" if they're present, not empty, and
* they don't already start with "/".
*/
static PathPart makeAbsolute(PathPart oldPart) {
boolean encodedCached = oldPart.encoded != NOT_CACHED;
// We don't care which version we use, and we don't want to force
// unneccessary encoding/decoding.
String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded;
if (oldPath == null || oldPath.length() == 0
|| oldPath.startsWith("/")) {
return oldPart;
}
// Prepend encoded string if present.
String newEncoded = encodedCached
? "/" + oldPart.encoded : NOT_CACHED;
// Prepend decoded string if present.
boolean decodedCached = oldPart.decoded != NOT_CACHED;
String newDecoded = decodedCached
? "/" + oldPart.decoded
: NOT_CACHED;
return new PathPart(newEncoded, newDecoded);
}
}
/**
* Creates a new Uri by appending an already-encoded path segment to a
* base Uri.
*
* @param baseUri Uri to append path segment to
* @param pathSegment encoded path segment to append
* @return a new Uri based on baseUri with the given segment appended to
* the path
* @throws NullPointerException if baseUri is null
*/
public static Uri withAppendedPath(Uri baseUri, String pathSegment) {
Builder builder = baseUri.buildUpon();
builder = builder.appendEncodedPath(pathSegment);
return builder.build();
}
}
| google/google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/Uri.java | Java | apache-2.0 | 65,026 | [
30522,
1013,
1008,
1011,
1008,
9385,
1006,
1039,
1007,
2289,
1996,
11924,
2330,
3120,
2622,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2025,
2224,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.Organizing
{
internal static partial class OrganizingService
{
/// <summary>
/// Organize the whole document.
///
/// Optionally you can provide your own organizers. otherwise, default will be used.
/// </summary>
public static Task<Document> OrganizeAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers = null, CancellationToken cancellationToken = default)
{
var service = document.Project.LanguageServices.GetService<IOrganizingService>();
return service.OrganizeAsync(document, organizers, cancellationToken);
}
}
}
| mmitche/roslyn | src/Features/Core/Portable/Organizing/OrganizingService.cs | C# | apache-2.0 | 973 | [
30522,
1013,
1013,
9385,
1006,
1039,
1007,
7513,
1012,
2035,
2916,
9235,
1012,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1012,
2156,
6105,
1012,
19067,
2102,
1999,
1996,
2622,
7117,
2005,
6105,
2592,
1012,
2478,
2291,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include "script_component.hpp"
class CfgPatches {
class ADDON {
units[] = {};
weapons[] = {};
requiredVersion = REQUIRED_VERSION;
requiredAddons[] = {"ace_interaction"};
author = ECSTRING(common,ACETeam);
authors[] = {"KoffeinFlummi", "BaerMitUmlaut"};
url = ECSTRING(main,URL);
VERSION_CONFIG;
};
};
#include "CfgEventHandlers.hpp"
#include "CfgMoves.hpp"
#include "CfgSounds.hpp"
#include "CfgVehicles.hpp"
#include "CfgWaypoints.hpp"
| voiperr/ACE3 | addons/fastroping/config.cpp | C++ | gpl-2.0 | 512 | [
30522,
1001,
2421,
1000,
5896,
1035,
6922,
1012,
6522,
2361,
1000,
2465,
12935,
21600,
4017,
8376,
1063,
2465,
5587,
2239,
1063,
3197,
1031,
1033,
1027,
1063,
1065,
1025,
4255,
1031,
1033,
1027,
1063,
1065,
1025,
3223,
27774,
1027,
3223,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Subclass for performing query and update operations on the 'cctipana' table.
*
*
*
* @package lib.model
*/
class CctipanaPeer extends BaseCctipanaPeer
{
public static function getTipanabyPk($eId)
{
$c = new Criteria();
$c->add(CctipanaPeer::CCGERENC_ID,$eId);
$m = CctipanaPeer::doSelect($c);
if($m){
$resp = array();
foreach($m as $dato){
$resp[$dato->getId()] = $dato->getNomtipana();
}
return $resp;
}else return array();
}
}
| cidesa/siga-universitario | lib/model/creditos/CctipanaPeer.php | PHP | gpl-2.0 | 506 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
4942,
26266,
2005,
4488,
23032,
1998,
10651,
3136,
2006,
1996,
1005,
10507,
25101,
5162,
1005,
2795,
1012,
1008,
1008,
1008,
1008,
1030,
7427,
5622,
2497,
1012,
2944,
1008,
1013,
2465,
10507... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.thrift.model;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Maps;
import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.model.AbstractColumnList;
import com.netflix.astyanax.model.Column;
public class ThriftCounterColumnListImpl<C> extends AbstractColumnList<C> {
private final List<org.apache.cassandra.thrift.CounterColumn> columns;
private Map<C, org.apache.cassandra.thrift.CounterColumn> lookup;
private final Serializer<C> colSer;
public ThriftCounterColumnListImpl(List<org.apache.cassandra.thrift.CounterColumn> columns, Serializer<C> colSer) {
this.columns = columns;
this.colSer = colSer;
}
@Override
public Iterator<Column<C>> iterator() {
class IteratorImpl implements Iterator<Column<C>> {
Iterator<org.apache.cassandra.thrift.CounterColumn> base;
public IteratorImpl(Iterator<org.apache.cassandra.thrift.CounterColumn> base) {
this.base = base;
}
@Override
public boolean hasNext() {
return base.hasNext();
}
@Override
public Column<C> next() {
org.apache.cassandra.thrift.CounterColumn c = base.next();
return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Iterator is immutable");
}
}
return new IteratorImpl(columns.iterator());
}
@Override
public Column<C> getColumnByName(C columnName) {
constructMap();
org.apache.cassandra.thrift.CounterColumn c = lookup.get(columnName);
if (c == null) {
return null;
}
return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c);
}
@Override
public Column<C> getColumnByIndex(int idx) {
org.apache.cassandra.thrift.CounterColumn c = columns.get(idx);
return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c);
}
@Override
public <C2> Column<C2> getSuperColumn(C columnName, Serializer<C2> colSer) {
throw new UnsupportedOperationException("Call getCounter");
}
@Override
public <C2> Column<C2> getSuperColumn(int idx, Serializer<C2> colSer) {
throw new UnsupportedOperationException("Call getCounter");
}
@Override
public boolean isEmpty() {
return columns.isEmpty();
}
@Override
public int size() {
return columns.size();
}
@Override
public boolean isSuperColumn() {
return false;
}
@Override
public Collection<C> getColumnNames() {
constructMap();
return lookup.keySet();
}
private void constructMap() {
if (lookup == null) {
lookup = Maps.newHashMap();
for (org.apache.cassandra.thrift.CounterColumn column : columns) {
lookup.put(colSer.fromBytes(column.getName()), column);
}
}
}
}
| 0x6e6562/astyanax | src/main/java/com/netflix/astyanax/thrift/model/ThriftCounterColumnListImpl.java | Java | apache-2.0 | 3,953 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Crypto module for Geierlein.
*
* @author Stefan Siegl
*
* Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function() {
var geierlein = {};
var gzipjs = {};
var forge = {};
if(typeof(window) !== 'undefined') {
geierlein = window.geierlein = window.geierlein || {};
gzipjs = window.gzipjs;
forge = window.forge;
}
// define node.js module
else if(typeof(module) !== 'undefined' && module.exports) {
geierlein = {
};
module.exports = geierlein.crypto = {};
gzipjs = require('../gzip-js/lib/gzip.js');
forge = require('../forge/js/forge.js');
}
var crypto = geierlein.crypto = geierlein.crypto || {};
/**
* The X.509 certificate with the Elster project's public key.
*
* The public key is used to encrypt the tax case.
*/
var elsterPem = '-----BEGIN CERTIFICATE-----\n' +
'MIIDKjCCAhICAQAwDQYJKoZIhvcNAQEEBQAwWTELMAkGA1UEBhMCREUxDzANBgNV\n' +
'BAoTBkVMU1RFUjEMMAoGA1UECxMDRUJBMQ8wDQYDVQQDEwZDb2RpbmcxGjAYBgNV\n' +
'BAUTETIwMDMwOTMwMTQzMzIzeDAwMCIYDzIwMDMwMTAxMDAwMDAwWhgPMjAwOTEy\n' +
'MzEyMzU5NTlaMFkxCzAJBgNVBAYTAkRFMQ8wDQYDVQQKEwZFTFNURVIxDDAKBgNV\n' +
'BAsTA0VCQTEPMA0GA1UEAxMGQ29kaW5nMRowGAYDVQQFExEyMDAzMDkzMDE0MzMy\n' +
'M3gwMDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIKjQAK3+1WlW6Az\n' +
'bp5C0UISN7+H7KFydsH3xvmvtVHV2XpAlQJxpMt3APH1NzSAmsz7FQlsVPYcTqgd\n' +
'tzwd6s/2bINLm/owNXTjCNRjmf2NLI2cTe9Gq+ovcujFVxVLO1IYjEpj6K09KJc4\n' +
'e9F+LTyJujaRg/W/cSY7aBwPhv/+1o49IoG7nXSwmpMp6CyRZwCVT26RbVAuTJ2R\n' +
'fmDgSmcc5Tostd/gQGSwVcreElrrN2LJM2MP5xDzP5tTQGmB8tMFwEYa7otPuhjF\n' +
'eV5ry3GSlgrFqUdt8JaZ03WQD2dbPZYbNGUvuzb4GebuEdnKCwRrOiGG6bUCx8Qk\n' +
'xXy6sMsCAwEAATANBgkqhkiG9w0BAQQFAAOCAQEABu72l9QUIng2n08p5uzffJA2\n' +
'Zx04ZfKWC+dBJB6an03ax8YqxUPm+e83D341NQtLlgJ4qKn9ShNZW85YoL/I02mU\n' +
'/sj50O4NAX72RwzHe/rPi+sS5BU5p4fi8YL+xN00r8R+Mbqctg8QJXleMmvuS/JF\n' +
'qB8F9m72Ud9kmZsV1Letl/qog0El4QHNnU9rSoI+MpchfDaoGvdqoVa+729SEBlc\n' +
'agWaHE8RNF43+aaVZQScvuwQZBrTJq2kqKmPm4Kg7GYuIGMqrm2/g0ldRrm8KfI2\n' +
'vxZIknBdmDknjnQHGMuLXmV3HKZTeN1F6I9BgmBXXqzTJu4gEDpY5n/h7mM+bA==\n' +
'-----END CERTIFICATE-----';
/**
* The Elster project's X.509 certificate as a Forge PKI instance.
*/
var elsterCert = forge.pki.certificateFromPem(elsterPem);
/**
* Perform whole encoding process of one XML piece as required by Elster specs.
*
* This is, take the provided data, GZIP it, encrypt it with DES3-EDE & RSA,
* encode the DER encoding of the resulting PKCS#7 enveloped document with
* Base64 and return it.
*
* @param {string} data The data block to encode.
* @param {object} key The key to use to encrypt the data (as a Forge buffer)
* @return {string} Base64-encoded result.
*/
crypto.encryptBlock = function(data, key) {
// gzip data
var out = gzipjs.zip(data, { level: 9 });
out = gzipjs.charArrayToString(out);
out = forge.util.createBuffer(out);
// encrypt data
var p7 = forge.pkcs7.createEnvelopedData();
p7.addRecipient(elsterCert);
p7.content = out;
p7.encrypt(key.copy(), forge.pki.oids['des-EDE3-CBC']);
// convert to base64
out = forge.asn1.toDer(p7.toAsn1());
return forge.util.encode64(out.getBytes(), 0);
};
/**
* Decrypt all the encoded parts of a response document from Elster the servers.
*
* This function performs the full decoding process, i.e. it decrypts the
* PKCS#7 encrypted data blocks and unzips them.
*
* @param {string} data The XML document.
* @param {object} key A Forge buffer containing the decryption key.
*/
crypto.decryptDocument = function(data, key) {
function decryptBlock(regex) {
var pieces = data.split(regex);
if(pieces.length !== 5) {
return;
}
var encBlock = pieces[2].replace(/[\r\n]*/g, '');
if(encBlock === '') {
/* On error <DatenTeil> is in some cases returned empty. */
return;
}
/* Base64-decode block, result is DER-encoded PKCS#7 encrypted data. */
encBlock = forge.util.decode64(encBlock);
/* Convert to Forge ASN.1 object. */
encBlock = forge.asn1.fromDer(encBlock);
/* Convert to Forge PKCS#7 object. */
var p7 = forge.pkcs7.messageFromAsn1(encBlock);
p7.decrypt(key.copy());
/* Covert Forge buffer to gzipJS buffer (array of bytes). */
var gzippedData = [];
while(!p7.content.isEmpty()) {
gzippedData.push(p7.content.getByte());
}
/* Gunzip and replace back into pieces. */
pieces[2] = gzipjs.charArrayToString(gzipjs.unzip(gzippedData));
/* Join pieces together again. */
data = pieces.join('');
}
decryptBlock(/(<\/?DatenLieferant>)/);
decryptBlock(/(<\/?DatenTeil>)/);
return data;
};
/**
* Generate a key suitable for encryptBlock function.
*
* @return {object} A new random DES3 key as a Forge buffer.
*/
crypto.generateKey = function() {
return forge.util.createBuffer(forge.random.getBytes(24));
};
})();
| vog/geierlein | chrome/content/lib/geierlein/crypto.js | JavaScript | agpl-3.0 | 5,912 | [
30522,
1013,
1008,
1008,
1008,
19888,
2080,
11336,
2005,
16216,
3771,
19856,
1012,
1008,
1008,
1030,
3166,
8852,
9033,
13910,
2140,
1008,
1008,
9385,
1006,
1039,
1007,
2262,
8852,
9033,
13910,
2140,
1026,
26261,
11741,
1030,
3714,
24548,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package railo.commons.io.res.type.http;
import java.io.IOException;
import java.util.Map;
import railo.commons.io.res.Resource;
import railo.commons.io.res.ResourceProvider;
import railo.commons.io.res.Resources;
import railo.commons.io.res.util.ResourceLockImpl;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.StringUtil;
import railo.runtime.op.Caster;
public class HTTPResourceProvider implements ResourceProvider {
private int lockTimeout=20000;
private final ResourceLockImpl lock=new ResourceLockImpl(lockTimeout,false);
private String scheme="http";
private int clientTimeout=30000;
private int socketTimeout=20000;
private Map arguments;
public String getScheme() {
return scheme;
}
public String getProtocol() {
return scheme;
}
public void setScheme(String scheme) {
if(!StringUtil.isEmpty(scheme))this.scheme=scheme;
}
public ResourceProvider init(String scheme, Map arguments) {
setScheme(scheme);
if(arguments!=null) {
this.arguments=arguments;
// client-timeout
String strTimeout=(String) arguments.get("client-timeout");
if(strTimeout!=null) {
clientTimeout = Caster.toIntValue(strTimeout,clientTimeout);
}
// socket-timeout
strTimeout=(String) arguments.get("socket-timeout");
if(strTimeout!=null) {
socketTimeout=Caster.toIntValue(strTimeout,socketTimeout);
}
// lock-timeout
strTimeout = (String) arguments.get("lock-timeout");
if(strTimeout!=null) {
lockTimeout=Caster.toIntValue(strTimeout,lockTimeout);
}
}
lock.setLockTimeout(lockTimeout);
return this;
}
@Override
public Resource getResource(String path) {
int indexQ=path.indexOf('?');
if(indexQ!=-1){
int indexS=path.lastIndexOf('/');
while((indexS=path.lastIndexOf('/'))>indexQ){
path=path.substring(0,indexS)+"%2F"+path.substring(indexS+1);
}
}
path=ResourceUtil.translatePath(ResourceUtil.removeScheme(scheme,path),false,false);
return new HTTPResource(this,new HTTPConnectionData(path,getSocketTimeout()));
}
public boolean isAttributesSupported() {
return false;
}
public boolean isCaseSensitive() {
return false;
}
public boolean isModeSupported() {
return false;
}
public void setResources(Resources resources) {
}
@Override
public void lock(Resource res) throws IOException {
lock.lock(res);
}
@Override
public void unlock(Resource res) {
lock.unlock(res);
}
@Override
public void read(Resource res) throws IOException {
lock.read(res);
}
/**
* @return the clientTimeout
*/
public int getClientTimeout() {
return clientTimeout;
}
/**
* @return the lockTimeout
*/
public int getLockTimeout() {
return lockTimeout;
}
/**
* @return the socketTimeout
*/
public int getSocketTimeout() {
return socketTimeout;
}
@Override
public Map getArguments() {
return arguments;
}
}
| JordanReiter/railo | railo-java/railo-core/src/railo/commons/io/res/type/http/HTTPResourceProvider.java | Java | lgpl-2.1 | 2,880 | [
30522,
7427,
4334,
2080,
1012,
7674,
1012,
22834,
1012,
24501,
1012,
2828,
1012,
8299,
1025,
12324,
9262,
1012,
22834,
1012,
22834,
10288,
24422,
1025,
12324,
9262,
1012,
21183,
4014,
1012,
4949,
1025,
12324,
4334,
2080,
1012,
7674,
1012,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package utils.remote.amazon.operation
import play.api.test._
import utils.remote.amazon.stackable.CartRG
import scala.concurrent.duration.FiniteDuration
import utils.remote.amazon.AmazonSpecification
/**
* @author alari (name.alari@gmail.com)
* @since 24.10.13 13:59
*/
class CartCreateSpec extends AmazonSpecification {
import main.Implicits.amazonOp
"cart create operation" should {
"create a cart" in new WithApplication {
maybeUnavailable {
CartCreate.byAsins("1476745374" -> 2) must beLike[Seq[CartRG]] {
case cart =>
cart.head.id.length must be_>=(1)
cart.head.purchaseUrl.length must be_>=(10)
}.await(2, FiniteDuration(2, "seconds"))
}
}
}
}
| alari/amazon-scala-ecommerce | src/test/scala/amazon/operation/CartCreateSpec.scala | Scala | apache-2.0 | 734 | [
30522,
7427,
21183,
12146,
1012,
6556,
1012,
9733,
1012,
3169,
12324,
2377,
1012,
17928,
1012,
3231,
1012,
1035,
12324,
21183,
12146,
1012,
6556,
1012,
9733,
1012,
9991,
3085,
1012,
11122,
10623,
12324,
26743,
1012,
16483,
1012,
9367,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package ru.lanbilling.webservice.wsdl;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="isInsert" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="val" type="{urn:api3}soapInstallmentsPlan"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"isInsert",
"val"
})
@XmlRootElement(name = "insupdInstallmentsPlan")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class InsupdInstallmentsPlan {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected long isInsert;
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected SoapInstallmentsPlan val;
/**
* Gets the value of the isInsert property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public long getIsInsert() {
return isInsert;
}
/**
* Sets the value of the isInsert property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setIsInsert(long value) {
this.isInsert = value;
}
/**
* Gets the value of the val property.
*
* @return
* possible object is
* {@link SoapInstallmentsPlan }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public SoapInstallmentsPlan getVal() {
return val;
}
/**
* Sets the value of the val property.
*
* @param value
* allowed object is
* {@link SoapInstallmentsPlan }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setVal(SoapInstallmentsPlan value) {
this.val = value;
}
}
| kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/InsupdInstallmentsPlan.java | Java | mit | 2,811 | [
30522,
7427,
21766,
1012,
17595,
24457,
2075,
1012,
4773,
8043,
7903,
2063,
1012,
1059,
16150,
2140,
1025,
12324,
9262,
2595,
1012,
5754,
17287,
3508,
1012,
7013,
1025,
12324,
9262,
2595,
1012,
20950,
1012,
14187,
1012,
5754,
17287,
3508,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.spring;
import java.util.HashMap;
import java.util.Map;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
public class SequenceDao extends SqlMapClientDaoSupport implements ISequenceDao {
public boolean compareAndSet(String name, int value, int expect) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", name);
parameters.put("value", value);
parameters.put("expect", expect);
int updateCount = getSqlMapClientTemplate().update("Sequence.compareAndSet", parameters);
return updateCount == 1;
}
public int getValue(String name) {
return (Integer) getSqlMapClientTemplate().queryForObject("Sequence.getValue", name);
}
public int getValueForUpdate(String name) {
return (Integer) getSqlMapClientTemplate().queryForObject("Sequence.getValueForUpdate", name);
}
}
| xiaomozhang/druid | druid-1.0.9/src/test/java/com/alibaba/druid/spring/SequenceDao.java | Java | apache-2.0 | 1,557 | [
30522,
1013,
1008,
1008,
9385,
2639,
1011,
2249,
4862,
3676,
3676,
2177,
3173,
5183,
1012,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2025,
2224,
20... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
jsonp({"cep":"41640070","logradouro":"Rua Ministro Carlos Coqueijo","bairro":"Itapu\u00e3","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/41640070.jsonp.js | JavaScript | cc0-1.0 | 141 | [
30522,
1046,
3385,
2361,
1006,
1063,
1000,
8292,
2361,
1000,
1024,
1000,
4601,
21084,
8889,
19841,
1000,
1010,
1000,
8833,
12173,
8162,
2080,
1000,
1024,
1000,
21766,
2050,
7163,
3367,
3217,
5828,
2522,
4226,
28418,
2080,
1000,
1010,
1000,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/////////////////////////////////////////////////////////////////////////////
// Name: exec.cpp
// Purpose: exec sample demonstrates wxExecute and related functions
// Author: Vadim Zeitlin
// Modified by:
// Created: 15.01.00
// RCS-ID: $Id: exec.cpp 54352 2008-06-25 07:51:09Z JS $
// Copyright: (c) Vadim Zeitlin
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/log.h"
#include "wx/frame.h"
#include "wx/panel.h"
#include "wx/timer.h"
#include "wx/utils.h"
#include "wx/menu.h"
#include "wx/msgdlg.h"
#include "wx/textdlg.h"
#include "wx/filedlg.h"
#include "wx/choicdlg.h"
#include "wx/button.h"
#include "wx/textctrl.h"
#include "wx/listbox.h"
#include "wx/sizer.h"
#endif
#include "wx/txtstrm.h"
#include "wx/numdlg.h"
#include "wx/textdlg.h"
#include "wx/ffile.h"
#include "wx/process.h"
#include "wx/mimetype.h"
#ifdef __WINDOWS__
#include "wx/dde.h"
#endif // __WINDOWS__
// ----------------------------------------------------------------------------
// the usual application and main frame classes
// ----------------------------------------------------------------------------
// Define a new application type, each program should derive a class from wxApp
class MyApp : public wxApp
{
public:
// override base class virtuals
// ----------------------------
// this one is called on application startup and is a good place for the app
// initialization (doing it here and not in the ctor allows to have an error
// return: if OnInit() returns false, the application terminates)
virtual bool OnInit();
};
// Define an array of process pointers used by MyFrame
class MyPipedProcess;
WX_DEFINE_ARRAY_PTR(MyPipedProcess *, MyProcessesArray);
// Define a new frame type: this is going to be our main frame
class MyFrame : public wxFrame
{
public:
// ctor(s)
MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
// event handlers (these functions should _not_ be virtual)
void OnQuit(wxCommandEvent& event);
void OnKill(wxCommandEvent& event);
void OnClear(wxCommandEvent& event);
void OnSyncExec(wxCommandEvent& event);
void OnAsyncExec(wxCommandEvent& event);
void OnShell(wxCommandEvent& event);
void OnExecWithRedirect(wxCommandEvent& event);
void OnExecWithPipe(wxCommandEvent& event);
void OnPOpen(wxCommandEvent& event);
void OnFileExec(wxCommandEvent& event);
void OnOpenURL(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
// polling output of async processes
void OnTimer(wxTimerEvent& event);
void OnIdle(wxIdleEvent& event);
// for MyPipedProcess
void OnProcessTerminated(MyPipedProcess *process);
wxListBox *GetLogListBox() const { return m_lbox; }
private:
void ShowOutput(const wxString& cmd,
const wxArrayString& output,
const wxString& title);
void DoAsyncExec(const wxString& cmd);
void AddAsyncProcess(MyPipedProcess *process)
{
if ( m_running.IsEmpty() )
{
// we want to start getting the timer events to ensure that a
// steady stream of idle events comes in -- otherwise we
// wouldn't be able to poll the child process input
m_timerIdleWakeUp.Start(100);
}
//else: the timer is already running
m_running.Add(process);
}
void RemoveAsyncProcess(MyPipedProcess *process)
{
m_running.Remove(process);
if ( m_running.IsEmpty() )
{
// we don't need to get idle events all the time any more
m_timerIdleWakeUp.Stop();
}
}
// the PID of the last process we launched asynchronously
long m_pidLast;
// last command we executed
wxString m_cmdLast;
#ifdef __WINDOWS__
void OnDDEExec(wxCommandEvent& event);
void OnDDERequest(wxCommandEvent& event);
bool GetDDEServer();
// last params of a DDE transaction
wxString m_server,
m_topic,
m_cmdDde;
#endif // __WINDOWS__
wxListBox *m_lbox;
MyProcessesArray m_running;
// the idle event wake up timer
wxTimer m_timerIdleWakeUp;
// any class wishing to process wxWidgets events must use this macro
DECLARE_EVENT_TABLE()
};
// ----------------------------------------------------------------------------
// MyPipeFrame: allows the user to communicate with the child process
// ----------------------------------------------------------------------------
class MyPipeFrame : public wxFrame
{
public:
MyPipeFrame(wxFrame *parent,
const wxString& cmd,
wxProcess *process);
protected:
void OnTextEnter(wxCommandEvent& WXUNUSED(event)) { DoSend(); }
void OnBtnSend(wxCommandEvent& WXUNUSED(event)) { DoSend(); }
void OnBtnSendFile(wxCommandEvent& WXUNUSED(event));
void OnBtnGet(wxCommandEvent& WXUNUSED(event)) { DoGet(); }
void OnBtnClose(wxCommandEvent& WXUNUSED(event)) { DoClose(); }
void OnClose(wxCloseEvent& event);
void OnProcessTerm(wxProcessEvent& event);
void DoSend()
{
wxString s(m_textOut->GetValue());
s += _T('\n');
m_out.Write(s.c_str(), s.length());
m_textOut->Clear();
DoGet();
}
void DoGet();
void DoClose();
private:
void DoGetFromStream(wxTextCtrl *text, wxInputStream& in);
void DisableInput();
void DisableOutput();
wxProcess *m_process;
wxOutputStream &m_out;
wxInputStream &m_in,
&m_err;
wxTextCtrl *m_textOut,
*m_textIn,
*m_textErr;
DECLARE_EVENT_TABLE()
};
// ----------------------------------------------------------------------------
// wxProcess-derived classes
// ----------------------------------------------------------------------------
// This is the handler for process termination events
class MyProcess : public wxProcess
{
public:
MyProcess(MyFrame *parent, const wxString& cmd)
: wxProcess(parent), m_cmd(cmd)
{
m_parent = parent;
}
// instead of overriding this virtual function we might as well process the
// event from it in the frame class - this might be more convenient in some
// cases
virtual void OnTerminate(int pid, int status);
protected:
MyFrame *m_parent;
wxString m_cmd;
};
// A specialization of MyProcess for redirecting the output
class MyPipedProcess : public MyProcess
{
public:
MyPipedProcess(MyFrame *parent, const wxString& cmd)
: MyProcess(parent, cmd)
{
Redirect();
}
virtual void OnTerminate(int pid, int status);
virtual bool HasInput();
};
// A version of MyPipedProcess which also sends input to the stdin of the
// child process
class MyPipedProcess2 : public MyPipedProcess
{
public:
MyPipedProcess2(MyFrame *parent, const wxString& cmd, const wxString& input)
: MyPipedProcess(parent, cmd), m_input(input)
{
}
virtual bool HasInput();
private:
wxString m_input;
};
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// IDs for the controls and the menu commands
enum
{
// menu items
Exec_Quit = 100,
Exec_Kill,
Exec_ClearLog,
Exec_SyncExec = 200,
Exec_AsyncExec,
Exec_Shell,
Exec_POpen,
Exec_OpenFile,
Exec_OpenURL,
Exec_DDEExec,
Exec_DDERequest,
Exec_Redirect,
Exec_Pipe,
Exec_About = 300,
// control ids
Exec_Btn_Send = 1000,
Exec_Btn_SendFile,
Exec_Btn_Get,
Exec_Btn_Close
};
static const wxChar *DIALOG_TITLE = _T("Exec sample");
// ----------------------------------------------------------------------------
// event tables and other macros for wxWidgets
// ----------------------------------------------------------------------------
// the event tables connect the wxWidgets events with the functions (event
// handlers) which process them. It can be also done at run-time, but for the
// simple menu events like this the static method is much simpler.
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(Exec_Quit, MyFrame::OnQuit)
EVT_MENU(Exec_Kill, MyFrame::OnKill)
EVT_MENU(Exec_ClearLog, MyFrame::OnClear)
EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec)
EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec)
EVT_MENU(Exec_Shell, MyFrame::OnShell)
EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect)
EVT_MENU(Exec_Pipe, MyFrame::OnExecWithPipe)
EVT_MENU(Exec_POpen, MyFrame::OnPOpen)
EVT_MENU(Exec_OpenFile, MyFrame::OnFileExec)
EVT_MENU(Exec_OpenURL, MyFrame::OnOpenURL)
#ifdef __WINDOWS__
EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
EVT_MENU(Exec_DDERequest, MyFrame::OnDDERequest)
#endif // __WINDOWS__
EVT_MENU(Exec_About, MyFrame::OnAbout)
EVT_IDLE(MyFrame::OnIdle)
EVT_TIMER(wxID_ANY, MyFrame::OnTimer)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(MyPipeFrame, wxFrame)
EVT_BUTTON(Exec_Btn_Send, MyPipeFrame::OnBtnSend)
EVT_BUTTON(Exec_Btn_SendFile, MyPipeFrame::OnBtnSendFile)
EVT_BUTTON(Exec_Btn_Get, MyPipeFrame::OnBtnGet)
EVT_BUTTON(Exec_Btn_Close, MyPipeFrame::OnBtnClose)
EVT_TEXT_ENTER(wxID_ANY, MyPipeFrame::OnTextEnter)
EVT_CLOSE(MyPipeFrame::OnClose)
EVT_END_PROCESS(wxID_ANY, MyPipeFrame::OnProcessTerm)
END_EVENT_TABLE()
// Create a new application object: this macro will allow wxWidgets to create
// the application object during program execution (it's better than using a
// static object for many reasons) and also declares the accessor function
// wxGetApp() which will return the reference of the right type (i.e. MyApp and
// not wxApp)
IMPLEMENT_APP(MyApp)
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// the application class
// ----------------------------------------------------------------------------
// `Main program' equivalent: the program execution "starts" here
bool MyApp::OnInit()
{
// Create the main application window
MyFrame *frame = new MyFrame(_T("Exec wxWidgets sample"),
wxDefaultPosition, wxSize(500, 140));
// Show it and tell the application that it's our main window
frame->Show(true);
SetTopWindow(frame);
// success: wxApp::OnRun() will be called which will enter the main message
// loop and the application will run. If we returned false here, the
// application would exit immediately.
return true;
}
// ----------------------------------------------------------------------------
// main frame
// ----------------------------------------------------------------------------
#ifdef __VISUALC__
#pragma warning(disable: 4355) // this used in base member initializer list
#endif
// frame constructor
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size),
m_timerIdleWakeUp(this)
{
m_pidLast = 0;
#ifdef __WXMAC__
// we need this in order to allow the about menu relocation, since ABOUT is
// not the default id of the about menu
wxApp::s_macAboutMenuItemId = Exec_About;
#endif
// create a menu bar
wxMenu *menuFile = new wxMenu(wxEmptyString, wxMENU_TEAROFF);
menuFile->Append(Exec_Kill, _T("&Kill process...\tCtrl-K"),
_T("Kill a process by PID"));
menuFile->AppendSeparator();
menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
_T("Clear the log window"));
menuFile->AppendSeparator();
menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
wxMenu *execMenu = new wxMenu;
execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
_T("Launch a program and return when it terminates"));
execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
_T("Launch a program and return immediately"));
execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
_T("Launch a shell and execute a command in it"));
execMenu->AppendSeparator();
execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
_T("Launch a program and capture its output"));
execMenu->Append(Exec_Pipe, _T("&Pipe through command..."),
_T("Pipe a string through a filter"));
execMenu->Append(Exec_POpen, _T("&Open a pipe to a command...\tCtrl-P"),
_T("Open a pipe to and from another program"));
execMenu->AppendSeparator();
execMenu->Append(Exec_OpenFile, _T("Open &file...\tCtrl-F"),
_T("Launch the command to open this kind of files"));
execMenu->Append(Exec_OpenURL, _T("Open &URL...\tCtrl-U"),
_T("Launch the default browser with the given URL"));
#ifdef __WINDOWS__
execMenu->AppendSeparator();
execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
execMenu->Append(Exec_DDERequest, _T("Send DDE &request...\tCtrl-R"));
#endif
wxMenu *helpMenu = new wxMenu(wxEmptyString, wxMENU_TEAROFF);
helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
// now append the freshly created menu to the menu bar...
wxMenuBar *menuBar = new wxMenuBar();
menuBar->Append(menuFile, _T("&File"));
menuBar->Append(execMenu, _T("&Exec"));
menuBar->Append(helpMenu, _T("&Help"));
// ... and attach this menu bar to the frame
SetMenuBar(menuBar);
// create the listbox in which we will show misc messages as they come
m_lbox = new wxListBox(this, wxID_ANY);
wxFont font(12, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
wxFONTWEIGHT_NORMAL);
if ( font.Ok() )
m_lbox->SetFont(font);
#if wxUSE_STATUSBAR
// create a status bar just for fun (by default with 1 pane only)
CreateStatusBar();
SetStatusText(_T("Welcome to wxWidgets exec sample!"));
#endif // wxUSE_STATUSBAR
}
// ----------------------------------------------------------------------------
// event handlers: file and help menu
// ----------------------------------------------------------------------------
void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
// true is to force the frame to close
Close(true);
}
void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
{
m_lbox->Clear();
}
void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
_T("About Exec"), wxOK | wxICON_INFORMATION, this);
}
void MyFrame::OnKill(wxCommandEvent& WXUNUSED(event))
{
long pid = wxGetNumberFromUser(_T("Please specify the process to kill"),
_T("Enter PID:"),
_T("Exec question"),
m_pidLast,
// we need the full unsigned int range
-INT_MAX, INT_MAX,
this);
if ( pid == -1 )
{
// cancelled
return;
}
static const wxString signalNames[] =
{
_T("Just test (SIGNONE)"),
_T("Hangup (SIGHUP)"),
_T("Interrupt (SIGINT)"),
_T("Quit (SIGQUIT)"),
_T("Illegal instruction (SIGILL)"),
_T("Trap (SIGTRAP)"),
_T("Abort (SIGABRT)"),
_T("Emulated trap (SIGEMT)"),
_T("FP exception (SIGFPE)"),
_T("Kill (SIGKILL)"),
_T("Bus (SIGBUS)"),
_T("Segment violation (SIGSEGV)"),
_T("System (SIGSYS)"),
_T("Broken pipe (SIGPIPE)"),
_T("Alarm (SIGALRM)"),
_T("Terminate (SIGTERM)"),
};
int sig = wxGetSingleChoiceIndex(_T("How to kill the process?"),
_T("Exec question"),
WXSIZEOF(signalNames), signalNames,
this);
switch ( sig )
{
default:
wxFAIL_MSG( _T("unexpected return value") );
// fall through
case -1:
// cancelled
return;
case wxSIGNONE:
case wxSIGHUP:
case wxSIGINT:
case wxSIGQUIT:
case wxSIGILL:
case wxSIGTRAP:
case wxSIGABRT:
case wxSIGEMT:
case wxSIGFPE:
case wxSIGKILL:
case wxSIGBUS:
case wxSIGSEGV:
case wxSIGSYS:
case wxSIGPIPE:
case wxSIGALRM:
case wxSIGTERM:
break;
}
if ( sig == 0 )
{
if ( wxProcess::Exists(pid) )
wxLogStatus(_T("Process %ld is running."), pid);
else
wxLogStatus(_T("No process with pid = %ld."), pid);
}
else // not SIGNONE
{
wxKillError rc = wxProcess::Kill(pid, (wxSignal)sig);
if ( rc == wxKILL_OK )
{
wxLogStatus(_T("Process %ld killed with signal %d."), pid, sig);
}
else
{
static const wxChar *errorText[] =
{
_T(""), // no error
_T("signal not supported"),
_T("permission denied"),
_T("no such process"),
_T("unspecified error"),
};
wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
pid, sig, errorText[rc]);
}
}
}
// ----------------------------------------------------------------------------
// event handlers: exec menu
// ----------------------------------------------------------------------------
void MyFrame::DoAsyncExec(const wxString& cmd)
{
wxProcess *process = new MyProcess(this, cmd);
m_pidLast = wxExecute(cmd, wxEXEC_ASYNC, process);
if ( !m_pidLast )
{
wxLogError( _T("Execution of '%s' failed."), cmd.c_str() );
delete process;
}
else
{
wxLogStatus( _T("Process %ld (%s) launched."),
m_pidLast, cmd.c_str() );
m_cmdLast = cmd;
}
}
void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
{
wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
DIALOG_TITLE,
m_cmdLast);
if ( !cmd )
return;
wxLogStatus( _T("'%s' is running please wait..."), cmd.c_str() );
int code = wxExecute(cmd, wxEXEC_SYNC);
wxLogStatus(_T("Process '%s' terminated with exit code %d."),
cmd.c_str(), code);
m_cmdLast = cmd;
}
void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
{
wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
DIALOG_TITLE,
m_cmdLast);
if ( !cmd )
return;
DoAsyncExec(cmd);
}
void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
{
wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
DIALOG_TITLE,
m_cmdLast);
if ( !cmd )
return;
int code = wxShell(cmd);
wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
cmd.c_str(), code);
m_cmdLast = cmd;
}
void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
{
wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
DIALOG_TITLE,
m_cmdLast);
if ( !cmd )
return;
bool sync;
switch ( wxMessageBox(_T("Execute it synchronously?"),
_T("Exec question"),
wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
{
case wxYES:
sync = true;
break;
case wxNO:
sync = false;
break;
default:
return;
}
if ( sync )
{
wxArrayString output, errors;
int code = wxExecute(cmd, output, errors);
wxLogStatus(_T("command '%s' terminated with exit code %d."),
cmd.c_str(), code);
if ( code != -1 )
{
ShowOutput(cmd, output, _T("Output"));
ShowOutput(cmd, errors, _T("Errors"));
}
}
else // async exec
{
MyPipedProcess *process = new MyPipedProcess(this, cmd);
if ( !wxExecute(cmd, wxEXEC_ASYNC, process) )
{
wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
delete process;
}
else
{
AddAsyncProcess(process);
}
}
m_cmdLast = cmd;
}
void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
{
if ( !m_cmdLast )
m_cmdLast = _T("tr [a-z] [A-Z]");
wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
DIALOG_TITLE,
m_cmdLast);
if ( !cmd )
return;
wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
DIALOG_TITLE);
if ( !input )
return;
// always execute the filter asynchronously
MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
long pid = wxExecute(cmd, wxEXEC_ASYNC, process);
if ( pid )
{
wxLogStatus( _T("Process %ld (%s) launched."), pid, cmd.c_str() );
AddAsyncProcess(process);
}
else
{
wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
delete process;
}
m_cmdLast = cmd;
}
void MyFrame::OnPOpen(wxCommandEvent& WXUNUSED(event))
{
wxString cmd = wxGetTextFromUser(_T("Enter the command to launch: "),
DIALOG_TITLE,
m_cmdLast);
if ( cmd.empty() )
return;
wxProcess *process = wxProcess::Open(cmd);
if ( !process )
{
wxLogError(_T("Failed to launch the command."));
return;
}
wxLogVerbose(_T("PID of the new process: %ld"), process->GetPid());
wxOutputStream *out = process->GetOutputStream();
if ( !out )
{
wxLogError(_T("Failed to connect to child stdin"));
return;
}
wxInputStream *in = process->GetInputStream();
if ( !in )
{
wxLogError(_T("Failed to connect to child stdout"));
return;
}
new MyPipeFrame(this, cmd, process);
}
void MyFrame::OnFileExec(wxCommandEvent& WXUNUSED(event))
{
static wxString s_filename;
wxString filename;
#if wxUSE_FILEDLG
filename = wxLoadFileSelector(_T("any file"), NULL, s_filename, this);
#else // !wxUSE_FILEDLG
filename = wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
s_filename, this);
#endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
if ( filename.empty() )
return;
s_filename = filename;
wxString ext = filename.AfterLast(_T('.'));
wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
if ( !ft )
{
wxLogError(_T("Impossible to determine the file type for extension '%s'"),
ext.c_str());
return;
}
wxString cmd;
bool ok = ft->GetOpenCommand(&cmd,
wxFileType::MessageParameters(filename));
delete ft;
if ( !ok )
{
wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
ext.c_str());
return;
}
DoAsyncExec(cmd);
}
void MyFrame::OnOpenURL(wxCommandEvent& WXUNUSED(event))
{
static wxString s_filename;
wxString filename = wxGetTextFromUser
(
_T("Enter the URL"),
_T("exec sample"),
s_filename,
this
);
if ( filename.empty() )
return;
s_filename = filename;
if ( !wxLaunchDefaultBrowser(s_filename) )
wxLogError(_T("Failed to open URL \"%s\""), s_filename.c_str());
}
// ----------------------------------------------------------------------------
// DDE stuff
// ----------------------------------------------------------------------------
#ifdef __WINDOWS__
bool MyFrame::GetDDEServer()
{
wxString server = wxGetTextFromUser(_T("Server to connect to:"),
DIALOG_TITLE, m_server);
if ( !server )
return false;
m_server = server;
wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic);
if ( !topic )
return false;
m_topic = topic;
wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde);
if ( !cmd )
return false;
m_cmdDde = cmd;
return true;
}
void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
{
if ( !GetDDEServer() )
return;
wxDDEClient client;
wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
if ( !conn )
{
wxLogError(_T("Failed to connect to the DDE server '%s'."),
m_server.c_str());
}
else
{
if ( !conn->Execute(m_cmdDde) )
{
wxLogError(_T("Failed to execute command '%s' via DDE."),
m_cmdDde.c_str());
}
else
{
wxLogStatus(_T("Successfully executed DDE command"));
}
}
}
void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event))
{
if ( !GetDDEServer() )
return;
wxDDEClient client;
wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
if ( !conn )
{
wxLogError(_T("Failed to connect to the DDE server '%s'."),
m_server.c_str());
}
else
{
if ( !conn->Request(m_cmdDde) )
{
wxLogError(_T("Failed to send request '%s' via DDE."),
m_cmdDde.c_str());
}
else
{
wxLogStatus(_T("Successfully sent DDE request."));
}
}
}
#endif // __WINDOWS__
// ----------------------------------------------------------------------------
// various helpers
// ----------------------------------------------------------------------------
// input polling
void MyFrame::OnIdle(wxIdleEvent& event)
{
size_t count = m_running.GetCount();
for ( size_t n = 0; n < count; n++ )
{
if ( m_running[n]->HasInput() )
{
event.RequestMore();
}
}
}
void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
{
wxWakeUpIdle();
}
void MyFrame::OnProcessTerminated(MyPipedProcess *process)
{
RemoveAsyncProcess(process);
}
void MyFrame::ShowOutput(const wxString& cmd,
const wxArrayString& output,
const wxString& title)
{
size_t count = output.GetCount();
if ( !count )
return;
m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
title.c_str(), cmd.c_str()));
for ( size_t n = 0; n < count; n++ )
{
m_lbox->Append(output[n]);
}
m_lbox->Append(wxString::Format(_T("--- End of %s ---"),
title.Lower().c_str()));
}
// ----------------------------------------------------------------------------
// MyProcess
// ----------------------------------------------------------------------------
void MyProcess::OnTerminate(int pid, int status)
{
wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
pid, m_cmd.c_str(), status);
// we're not needed any more
delete this;
}
// ----------------------------------------------------------------------------
// MyPipedProcess
// ----------------------------------------------------------------------------
bool MyPipedProcess::HasInput()
{
bool hasInput = false;
if ( IsInputAvailable() )
{
wxTextInputStream tis(*GetInputStream());
// this assumes that the output is always line buffered
wxString msg;
msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
m_parent->GetLogListBox()->Append(msg);
hasInput = true;
}
if ( IsErrorAvailable() )
{
wxTextInputStream tis(*GetErrorStream());
// this assumes that the output is always line buffered
wxString msg;
msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
m_parent->GetLogListBox()->Append(msg);
hasInput = true;
}
return hasInput;
}
void MyPipedProcess::OnTerminate(int pid, int status)
{
// show the rest of the output
while ( HasInput() )
;
m_parent->OnProcessTerminated(this);
MyProcess::OnTerminate(pid, status);
}
// ----------------------------------------------------------------------------
// MyPipedProcess2
// ----------------------------------------------------------------------------
bool MyPipedProcess2::HasInput()
{
if ( !m_input.empty() )
{
wxTextOutputStream os(*GetOutputStream());
os.WriteString(m_input);
CloseOutput();
m_input.clear();
// call us once again - may be we'll have output
return true;
}
return MyPipedProcess::HasInput();
}
// ============================================================================
// MyPipeFrame implementation
// ============================================================================
MyPipeFrame::MyPipeFrame(wxFrame *parent,
const wxString& cmd,
wxProcess *process)
: wxFrame(parent, wxID_ANY, cmd),
m_process(process),
// in a real program we'd check that the streams are !NULL here
m_out(*process->GetOutputStream()),
m_in(*process->GetInputStream()),
m_err(*process->GetErrorStream())
{
m_process->SetNextHandler(this);
wxPanel *panel = new wxPanel(this, wxID_ANY);
m_textOut = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
wxDefaultPosition, wxDefaultSize,
wxTE_PROCESS_ENTER);
m_textIn = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE | wxTE_RICH);
m_textIn->SetEditable(false);
m_textErr = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE | wxTE_RICH);
m_textErr->SetEditable(false);
wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
sizerTop->Add(m_textOut, 0, wxGROW | wxALL, 5);
wxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL);
sizerBtns->
Add(new wxButton(panel, Exec_Btn_Send, _T("&Send")), 0, wxALL, 5);
sizerBtns->
Add(new wxButton(panel, Exec_Btn_SendFile, _T("&File...")), 0, wxALL, 5);
sizerBtns->
Add(new wxButton(panel, Exec_Btn_Get, _T("&Get")), 0, wxALL, 5);
sizerBtns->
Add(new wxButton(panel, Exec_Btn_Close, _T("&Close")), 0, wxALL, 5);
sizerTop->Add(sizerBtns, 0, wxCENTRE | wxALL, 5);
sizerTop->Add(m_textIn, 1, wxGROW | wxALL, 5);
sizerTop->Add(m_textErr, 1, wxGROW | wxALL, 5);
panel->SetSizer(sizerTop);
sizerTop->Fit(this);
Show();
}
void MyPipeFrame::OnBtnSendFile(wxCommandEvent& WXUNUSED(event))
{
#if wxUSE_FILEDLG
wxFileDialog filedlg(this, _T("Select file to send"));
if ( filedlg.ShowModal() != wxID_OK )
return;
wxFFile file(filedlg.GetFilename(), _T("r"));
wxString data;
if ( !file.IsOpened() || !file.ReadAll(&data) )
return;
// can't write the entire string at once, this risk overflowing the pipe
// and we would dead lock
size_t len = data.length();
const wxChar *pc = data.c_str();
while ( len )
{
const size_t CHUNK_SIZE = 4096;
m_out.Write(pc, len > CHUNK_SIZE ? CHUNK_SIZE : len);
// note that not all data could have been written as we don't block on
// the write end of the pipe
const size_t lenChunk = m_out.LastWrite();
pc += lenChunk;
len -= lenChunk;
DoGet();
}
#endif // wxUSE_FILEDLG
}
void MyPipeFrame::DoGet()
{
// we don't have any way to be notified when any input appears on the
// stream so we have to poll it :-(
DoGetFromStream(m_textIn, m_in);
DoGetFromStream(m_textErr, m_err);
}
void MyPipeFrame::DoGetFromStream(wxTextCtrl *text, wxInputStream& in)
{
while ( in.CanRead() )
{
wxChar buffer[4096];
buffer[in.Read(buffer, WXSIZEOF(buffer) - 1).LastRead()] = _T('\0');
text->AppendText(buffer);
}
}
void MyPipeFrame::DoClose()
{
m_process->CloseOutput();
DisableInput();
}
void MyPipeFrame::DisableInput()
{
m_textOut->SetEditable(false);
FindWindow(Exec_Btn_Send)->Disable();
FindWindow(Exec_Btn_SendFile)->Disable();
FindWindow(Exec_Btn_Close)->Disable();
}
void MyPipeFrame::DisableOutput()
{
FindWindow(Exec_Btn_Get)->Disable();
}
void MyPipeFrame::OnClose(wxCloseEvent& event)
{
if ( m_process )
{
// we're not interested in getting the process termination notification
// if we are closing it ourselves
wxProcess *process = m_process;
m_process = NULL;
process->SetNextHandler(NULL);
process->CloseOutput();
}
event.Skip();
}
void MyPipeFrame::OnProcessTerm(wxProcessEvent& WXUNUSED(event))
{
DoGet();
delete m_process;
m_process = NULL;
wxLogWarning(_T("The other process has terminated, closing"));
DisableInput();
DisableOutput();
}
| hajuuk/R7000 | ap/gpl/amule/wxWidgets-2.8.12/samples/exec/exec.cpp | C++ | gpl-2.0 | 34,871 | [
30522,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* @author mr.v
*/
class MY_Input extends CI_Input {
function __construct() {
parent::__construct();
}// __construct
function ip_address() {
if ( $this->ip_address !== false ) {
return $this->ip_address;
}
// IMPROVED!! CI ip address cannot detect through http_x_forwarded_for. this one can do.
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
// //check ip from share internet
$this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//to check ip is pass from proxy
$this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$this->ip_address = $_SERVER['REMOTE_ADDR'];
}
//
if ( $this->ip_address === false ) {
$this->ip_address = "0.0.0.0";
return $this->ip_address;
}
//
if (strpos($this->ip_address, ',') !== FALSE)
{
$x = explode(',', $this->ip_address);
$this->ip_address = trim(end($x));
}
//
if ( ! $this->valid_ip($this->ip_address)){
$this->ip_address = '0.0.0.0';
}
//
return $this->ip_address;
}
}
/* end of file */ | OkveeNet/vee-manga-reader-pro | application/core/MY_Input.php | PHP | gpl-2.0 | 1,068 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
1030,
3166,
2720,
1012,
1058,
1008,
1013,
2465,
2026,
1035,
7953,
8908,
25022,
1035,
7953,
1063,
3853,
1035,
1035,
9570,
1006,
1007,
1063,
6687,
1024,
1024,
1035,
1035,
9570,
1006,
1007,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
document.head.appendChild(rscript);
return;
}
require.config({
baseUrl: 'js/',
paths: {
// the left side is the module ID,
// the right side is the path to
// the jQuery file, relative to baseUrl.
// Also, the path should NOT include
// the '.js' file extension. This example
// is using jQuery 1.8.2 located at
// js/jquery-1.8.2.js, relative to
// the HTML page.
jquery: 'lib/jquery-2.1.3.min',
namedwebsockets: 'lib/namedwebsockets',
qrcode: 'lib/qrcode.min',
webcodecam:'lib/WebCodeCam.min',
qrcodelib:'lib/qrcodelib',
socketio: '/socket.io/socket.io',
shake: 'lib/shake'
}
});
// Start the main app logic.
define("mediascape", ["mediascape/Agentcontext/agentcontext",
"mediascape/Association/association",
"mediascape/Discovery/discovery",
"mediascape/DiscoveryAgentContext/discoveryagentcontext",
"mediascape/Sharedstate/sharedstate",
"mediascape/Mappingservice/mappingservice",
"mediascape/Applicationcontext/applicationcontext"], function ($, Modules) {
//jQuery, modules and the discovery/modules module are all.
//loaded and can be used here now.
//creation of mediascape and discovery objects.
var mediascape = {};
var moduleList = Array.prototype.slice.apply(arguments);
mediascape.init = function (options) {
mediascapeOptions = {};
_this = Object.create(mediascape);
for (var i = 0; i < moduleList.length; i++) {
var name = moduleList[i].__moduleName;
var dontCall = ['sharedState', 'mappingService', 'applicationContext'];
if (dontCall.indexOf(name) === -1) {
mediascape[name] = new moduleList[i](mediascape, "gq" + i, mediascape);
} else {
mediascape[name] = moduleList[i];
}
}
return _this;
};
mediascape.version = "0.0.1";
// See if we have any waiting init calls that happened before we loaded require.
if (window.mediascape) {
var args = window.mediascape.__waiting;
delete window.mediascape;
if (args) {
mediascape.init.apply(this, args);
}
}
window.mediascape = mediascape;
//return of mediascape object with discovery and features objects and its functions
return mediascape;
});
require(["mediascape"], function (mediascape) {
mediascape.init();
/**
*
* Polyfill for custonevents
*/
(function () {
function CustomEvent(event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
var event = new CustomEvent("mediascape-ready", {
"detail": {
"loaded": true
}
});
document.dispatchEvent(event);
});
}());
| martinangel/association | helloworld/Triggers/js/mediascape/mediascape.js | JavaScript | apache-2.0 | 3,983 | [
30522,
1013,
1013,
2364,
9262,
22483,
1006,
3853,
1999,
4183,
1006,
1007,
1063,
1013,
1013,
2065,
2057,
2342,
2000,
7170,
5478,
22578,
2077,
10578,
12136,
1010,
2191,
2009,
2061,
2065,
1006,
2828,
11253,
9375,
1027,
1027,
1027,
1000,
6151,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/local/bin/perl
# Normal is the
# md5_block_x86(MD5_CTX *c, ULONG *X);
# version, non-normal is the
# md5_block_x86(MD5_CTX *c, ULONG *X,int blocks);
$normal=0;
push(@INC,"perlasm","../../perlasm");
require "x86asm.pl";
&asm_init($ARGV[0],$0);
$A="eax";
$B="ebx";
$C="ecx";
$D="edx";
$tmp1="edi";
$tmp2="ebp";
$X="esi";
# What we need to load into $tmp for the next round
%Ltmp1=("R0",&Np($C), "R1",&Np($C), "R2",&Np($C), "R3",&Np($D));
@xo=(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, # R0
1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, # R1
5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, # R2
0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9, # R3
);
&md5_block("md5_block_asm_data_order");
&asm_finish();
sub Np
{
local($p)=@_;
local(%n)=($A,$D,$B,$A,$C,$B,$D,$C);
return($n{$p});
}
sub R0
{
local($pos,$a,$b,$c,$d,$K,$ki,$s,$t)=@_;
&mov($tmp1,$C) if $pos < 0;
&mov($tmp2,&DWP($xo[$ki]*4,$K,"",0)) if $pos < 0; # very first one
# body proper
&comment("R0 $ki");
&xor($tmp1,$d); # F function - part 2
&and($tmp1,$b); # F function - part 3
&lea($a,&DWP($t,$a,$tmp2,1));
&xor($tmp1,$d); # F function - part 4
&add($a,$tmp1);
&mov($tmp1,&Np($c)) if $pos < 1; # next tmp1 for R0
&mov($tmp1,&Np($c)) if $pos == 1; # next tmp1 for R1
&rotl($a,$s);
&mov($tmp2,&DWP($xo[$ki+1]*4,$K,"",0)) if ($pos != 2);
&add($a,$b);
}
sub R1
{
local($pos,$a,$b,$c,$d,$K,$ki,$s,$t)=@_;
&comment("R1 $ki");
&lea($a,&DWP($t,$a,$tmp2,1));
&xor($tmp1,$b); # G function - part 2
&and($tmp1,$d); # G function - part 3
&mov($tmp2,&DWP($xo[$ki+1]*4,$K,"",0)) if ($pos != 2);
&xor($tmp1,$c); # G function - part 4
&add($a,$tmp1);
&mov($tmp1,&Np($c)) if $pos < 1; # G function - part 1
&mov($tmp1,&Np($c)) if $pos == 1; # G function - part 1
&rotl($a,$s);
&add($a,$b);
}
sub R2
{
local($n,$pos,$a,$b,$c,$d,$K,$ki,$s,$t)=@_;
# This one is different, only 3 logical operations
if (($n & 1) == 0)
{
&comment("R2 $ki");
# make sure to do 'D' first, not 'B', else we clash with
# the last add from the previous round.
&xor($tmp1,$d); # H function - part 2
&xor($tmp1,$b); # H function - part 3
&lea($a,&DWP($t,$a,$tmp2,1));
&add($a,$tmp1);
&rotl($a,$s);
&mov($tmp2,&DWP($xo[$ki+1]*4,$K,"",0));
&mov($tmp1,&Np($c));
}
else
{
&comment("R2 $ki");
# make sure to do 'D' first, not 'B', else we clash with
# the last add from the previous round.
&lea($a,&DWP($t,$a,$tmp2,1));
&add($b,$c); # MOVED FORWARD
&xor($tmp1,$d); # H function - part 2
&xor($tmp1,$b); # H function - part 3
&mov($tmp2,&DWP($xo[$ki+1]*4,$K,"",0)) if ($pos != 2);
&add($a,$tmp1);
&mov($tmp1,&Np($c)) if $pos < 1; # H function - part 1
&mov($tmp1,-1) if $pos == 1; # I function - part 1
&rotl($a,$s);
&add($a,$b);
}
}
sub R3
{
local($pos,$a,$b,$c,$d,$K,$ki,$s,$t)=@_;
&comment("R3 $ki");
# ¬($tmp1)
&xor($tmp1,$d) if $pos < 0; # I function - part 2
&or($tmp1,$b); # I function - part 3
&lea($a,&DWP($t,$a,$tmp2,1));
&xor($tmp1,$c); # I function - part 4
&mov($tmp2,&DWP($xo[$ki+1]*4,$K,"",0)) if $pos != 2; # load X/k value
&mov($tmp2,&wparam(0)) if $pos == 2;
&add($a,$tmp1);
&mov($tmp1,-1) if $pos < 1; # H function - part 1
&add($K,64) if $pos >=1 && !$normal;
&rotl($a,$s);
&xor($tmp1,&Np($d)) if $pos <= 0; # I function - part = first time
&mov($tmp1,&DWP( 0,$tmp2,"",0)) if $pos > 0;
&add($a,$b);
}
sub md5_block
{
local($name)=@_;
&function_begin_B($name,"",3);
# parameter 1 is the MD5_CTX structure.
# A 0
# B 4
# C 8
# D 12
&push("esi");
&push("edi");
&mov($tmp1, &wparam(0)); # edi
&mov($X, &wparam(1)); # esi
&mov($C, &wparam(2));
&push("ebp");
&shl($C, 6);
&push("ebx");
&add($C, $X); # offset we end at
&sub($C, 64);
&mov($A, &DWP( 0,$tmp1,"",0));
&push($C); # Put on the TOS
&mov($B, &DWP( 4,$tmp1,"",0));
&mov($C, &DWP( 8,$tmp1,"",0));
&mov($D, &DWP(12,$tmp1,"",0));
&set_label("start") unless $normal;
&comment("");
&comment("R0 section");
&R0(-2,$A,$B,$C,$D,$X, 0, 7,0xd76aa478);
&R0( 0,$D,$A,$B,$C,$X, 1,12,0xe8c7b756);
&R0( 0,$C,$D,$A,$B,$X, 2,17,0x242070db);
&R0( 0,$B,$C,$D,$A,$X, 3,22,0xc1bdceee);
&R0( 0,$A,$B,$C,$D,$X, 4, 7,0xf57c0faf);
&R0( 0,$D,$A,$B,$C,$X, 5,12,0x4787c62a);
&R0( 0,$C,$D,$A,$B,$X, 6,17,0xa8304613);
&R0( 0,$B,$C,$D,$A,$X, 7,22,0xfd469501);
&R0( 0,$A,$B,$C,$D,$X, 8, 7,0x698098d8);
&R0( 0,$D,$A,$B,$C,$X, 9,12,0x8b44f7af);
&R0( 0,$C,$D,$A,$B,$X,10,17,0xffff5bb1);
&R0( 0,$B,$C,$D,$A,$X,11,22,0x895cd7be);
&R0( 0,$A,$B,$C,$D,$X,12, 7,0x6b901122);
&R0( 0,$D,$A,$B,$C,$X,13,12,0xfd987193);
&R0( 0,$C,$D,$A,$B,$X,14,17,0xa679438e);
&R0( 1,$B,$C,$D,$A,$X,15,22,0x49b40821);
&comment("");
&comment("R1 section");
&R1(-1,$A,$B,$C,$D,$X,16, 5,0xf61e2562);
&R1( 0,$D,$A,$B,$C,$X,17, 9,0xc040b340);
&R1( 0,$C,$D,$A,$B,$X,18,14,0x265e5a51);
&R1( 0,$B,$C,$D,$A,$X,19,20,0xe9b6c7aa);
&R1( 0,$A,$B,$C,$D,$X,20, 5,0xd62f105d);
&R1( 0,$D,$A,$B,$C,$X,21, 9,0x02441453);
&R1( 0,$C,$D,$A,$B,$X,22,14,0xd8a1e681);
&R1( 0,$B,$C,$D,$A,$X,23,20,0xe7d3fbc8);
&R1( 0,$A,$B,$C,$D,$X,24, 5,0x21e1cde6);
&R1( 0,$D,$A,$B,$C,$X,25, 9,0xc33707d6);
&R1( 0,$C,$D,$A,$B,$X,26,14,0xf4d50d87);
&R1( 0,$B,$C,$D,$A,$X,27,20,0x455a14ed);
&R1( 0,$A,$B,$C,$D,$X,28, 5,0xa9e3e905);
&R1( 0,$D,$A,$B,$C,$X,29, 9,0xfcefa3f8);
&R1( 0,$C,$D,$A,$B,$X,30,14,0x676f02d9);
&R1( 1,$B,$C,$D,$A,$X,31,20,0x8d2a4c8a);
&comment("");
&comment("R2 section");
&R2( 0,-1,$A,$B,$C,$D,$X,32, 4,0xfffa3942);
&R2( 1, 0,$D,$A,$B,$C,$X,33,11,0x8771f681);
&R2( 2, 0,$C,$D,$A,$B,$X,34,16,0x6d9d6122);
&R2( 3, 0,$B,$C,$D,$A,$X,35,23,0xfde5380c);
&R2( 4, 0,$A,$B,$C,$D,$X,36, 4,0xa4beea44);
&R2( 5, 0,$D,$A,$B,$C,$X,37,11,0x4bdecfa9);
&R2( 6, 0,$C,$D,$A,$B,$X,38,16,0xf6bb4b60);
&R2( 7, 0,$B,$C,$D,$A,$X,39,23,0xbebfbc70);
&R2( 8, 0,$A,$B,$C,$D,$X,40, 4,0x289b7ec6);
&R2( 9, 0,$D,$A,$B,$C,$X,41,11,0xeaa127fa);
&R2(10, 0,$C,$D,$A,$B,$X,42,16,0xd4ef3085);
&R2(11, 0,$B,$C,$D,$A,$X,43,23,0x04881d05);
&R2(12, 0,$A,$B,$C,$D,$X,44, 4,0xd9d4d039);
&R2(13, 0,$D,$A,$B,$C,$X,45,11,0xe6db99e5);
&R2(14, 0,$C,$D,$A,$B,$X,46,16,0x1fa27cf8);
&R2(15, 1,$B,$C,$D,$A,$X,47,23,0xc4ac5665);
&comment("");
&comment("R3 section");
&R3(-1,$A,$B,$C,$D,$X,48, 6,0xf4292244);
&R3( 0,$D,$A,$B,$C,$X,49,10,0x432aff97);
&R3( 0,$C,$D,$A,$B,$X,50,15,0xab9423a7);
&R3( 0,$B,$C,$D,$A,$X,51,21,0xfc93a039);
&R3( 0,$A,$B,$C,$D,$X,52, 6,0x655b59c3);
&R3( 0,$D,$A,$B,$C,$X,53,10,0x8f0ccc92);
&R3( 0,$C,$D,$A,$B,$X,54,15,0xffeff47d);
&R3( 0,$B,$C,$D,$A,$X,55,21,0x85845dd1);
&R3( 0,$A,$B,$C,$D,$X,56, 6,0x6fa87e4f);
&R3( 0,$D,$A,$B,$C,$X,57,10,0xfe2ce6e0);
&R3( 0,$C,$D,$A,$B,$X,58,15,0xa3014314);
&R3( 0,$B,$C,$D,$A,$X,59,21,0x4e0811a1);
&R3( 0,$A,$B,$C,$D,$X,60, 6,0xf7537e82);
&R3( 0,$D,$A,$B,$C,$X,61,10,0xbd3af235);
&R3( 0,$C,$D,$A,$B,$X,62,15,0x2ad7d2bb);
&R3( 2,$B,$C,$D,$A,$X,63,21,0xeb86d391);
# &mov($tmp2,&wparam(0)); # done in the last R3
# &mov($tmp1, &DWP( 0,$tmp2,"",0)); # done is the last R3
&add($A,$tmp1);
&mov($tmp1, &DWP( 4,$tmp2,"",0));
&add($B,$tmp1);
&mov($tmp1, &DWP( 8,$tmp2,"",0));
&add($C,$tmp1);
&mov($tmp1, &DWP(12,$tmp2,"",0));
&add($D,$tmp1);
&mov(&DWP( 0,$tmp2,"",0),$A);
&mov(&DWP( 4,$tmp2,"",0),$B);
&mov($tmp1,&swtmp(0)) unless $normal;
&mov(&DWP( 8,$tmp2,"",0),$C);
&mov(&DWP(12,$tmp2,"",0),$D);
&cmp($tmp1,$X) unless $normal; # check count
&jae(&label("start")) unless $normal;
&pop("eax"); # pop the temp variable off the stack
&pop("ebx");
&pop("ebp");
&pop("edi");
&pop("esi");
&ret();
&function_end_B($name);
}
| zarboz/XBMC-PVR-mac | tools/darwin/depends/openssl/crypto/md5/asm/md5-586.pl | Perl | gpl-2.0 | 7,568 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
2334,
1013,
8026,
1013,
2566,
2140,
1001,
3671,
2003,
1996,
1001,
9108,
2629,
1035,
3796,
1035,
1060,
20842,
1006,
9108,
2629,
1035,
14931,
2595,
1008,
1039,
1010,
17359,
5063,
1008,
1060,
1007,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectGridLoader.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Creature.h"
#include "Vehicle.h"
#include "GameObject.h"
#include "DynamicObject.h"
#include "Corpse.h"
#include "World.h"
#include "CellImpl.h"
#include "CreatureAI.h"
class ObjectGridRespawnMover
{
public:
ObjectGridRespawnMover() {}
void Move(GridType &grid);
template<class T> void Visit(GridRefManager<T> &) {}
void Visit(CreatureMapType &m);
};
void
ObjectGridRespawnMover::Move(GridType &grid)
{
TypeContainerVisitor<ObjectGridRespawnMover, GridTypeMapContainer > mover(*this);
grid.Visit(mover);
}
void
ObjectGridRespawnMover::Visit(CreatureMapType &m)
{
// creature in unloading grid can have respawn point in another grid
// if it will be unloaded then it will not respawn in original grid until unload/load original grid
// move to respawn point to prevent this case. For player view in respawn grid this will be normal respawn.
for (CreatureMapType::iterator iter = m.begin(); iter != m.end();)
{
Creature* c = iter->getSource();
++iter;
ASSERT(!c->isPet() && "ObjectGridRespawnMover don't must be called for pets");
Cell const& cur_cell = c->GetCurrentCell();
float resp_x, resp_y, resp_z;
c->GetRespawnCoord(resp_x, resp_y, resp_z);
CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
Cell resp_cell(resp_val);
if (cur_cell.DiffGrid(resp_cell))
{
c->GetMap()->CreatureRespawnRelocation(c);
// false result ignored: will be unload with other creatures at grid
}
}
}
// for loading world object at grid loading (Corpses)
class ObjectWorldLoader
{
public:
explicit ObjectWorldLoader(ObjectGridLoader& gloader)
: i_cell(gloader.i_cell), i_grid(gloader.i_grid), i_map(gloader.i_map), i_corpses (0)
{}
void Visit(CorpseMapType &m);
template<class T> void Visit(GridRefManager<T>&) {}
private:
Cell i_cell;
NGridType &i_grid;
Map* i_map;
public:
uint32 i_corpses;
};
template<class T> void AddUnitState(T* /*obj*/, CellPair const& /*cell_pair*/)
{
}
template<> void AddUnitState(Creature *obj, CellPair const& cell_pair)
{
Cell cell(cell_pair);
obj->SetCurrentCell(cell);
}
template <class T>
void AddObjectHelper(CellPair &cell, GridRefManager<T> &m, uint32 &count, Map* map, T *obj)
{
obj->GetGridRef().link(&m, obj);
AddUnitState(obj, cell);
obj->AddToWorld();
if (obj->isActiveObject())
map->AddToActive(obj);
++count;
}
template <class T>
void LoadHelper(CellGuidSet const& guid_set, CellPair &cell, GridRefManager<T> &m, uint32 &count, Map* map)
{
for (CellGuidSet::const_iterator i_guid = guid_set.begin(); i_guid != guid_set.end(); ++i_guid)
{
T* obj = new T;
uint32 guid = *i_guid;
//sLog->outString("DEBUG: LoadHelper from table: %s for (guid: %u) Loading", table, guid);
if (!obj->LoadFromDB(guid, map))
{
delete obj;
continue;
}
AddObjectHelper(cell, m, count, map, obj);
}
}
void LoadHelper(CellCorpseSet const& cell_corpses, CellPair &cell, CorpseMapType &m, uint32 &count, Map* map)
{
if (cell_corpses.empty())
return;
for (CellCorpseSet::const_iterator itr = cell_corpses.begin(); itr != cell_corpses.end(); ++itr)
{
if (itr->second != map->GetInstanceId())
continue;
uint32 player_guid = itr->first;
Corpse *obj = sObjectAccessor->GetCorpseForPlayerGUID(player_guid);
if (!obj)
continue;
// TODO: this is a hack
// corpse's map should be reset when the map is unloaded
// but it may still exist when the grid is unloaded but map is not
// in that case map == currMap
obj->SetMap(map);
AddObjectHelper(cell, m, count, map, obj);
}
}
void
ObjectGridLoader::Visit(GameObjectMapType &m)
{
uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
CellPair cell_pair(x, y);
uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
CellObjectGuids const& cell_guids = sObjectMgr->GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cell_id);
LoadHelper(cell_guids.gameobjects, cell_pair, m, i_gameObjects, i_map);
}
void
ObjectGridLoader::Visit(CreatureMapType &m)
{
uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
CellPair cell_pair(x, y);
uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
CellObjectGuids const& cell_guids = sObjectMgr->GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cell_id);
LoadHelper(cell_guids.creatures, cell_pair, m, i_creatures, i_map);
}
void
ObjectWorldLoader::Visit(CorpseMapType &m)
{
uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
CellPair cell_pair(x, y);
uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
// corpses are always added to spawn mode 0 and they are spawned by their instance id
CellObjectGuids const& cell_guids = sObjectMgr->GetCellObjectGuids(i_map->GetId(), 0, cell_id);
LoadHelper(cell_guids.corpses, cell_pair, m, i_corpses, i_map);
}
void
ObjectGridLoader::Load(GridType &grid)
{
{
TypeContainerVisitor<ObjectGridLoader, GridTypeMapContainer > loader(*this);
grid.Visit(loader);
}
{
ObjectWorldLoader wloader(*this);
TypeContainerVisitor<ObjectWorldLoader, WorldTypeMapContainer > loader(wloader);
grid.Visit(loader);
i_corpses = wloader.i_corpses;
}
}
void ObjectGridLoader::LoadN(void)
{
i_gameObjects = 0; i_creatures = 0; i_corpses = 0;
i_cell.data.Part.cell_y = 0;
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
i_cell.data.Part.cell_x = x;
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
i_cell.data.Part.cell_y = y;
GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
loader.Load(i_grid(x, y), *this);
}
}
sLog->outDebug(LOG_FILTER_MAPS, "%u GameObjects, %u Creatures, and %u Corpses/Bones loaded for grid %u on map %u", i_gameObjects, i_creatures, i_corpses, i_grid.GetGridId(), i_map->GetId());
}
void ObjectGridUnloader::MoveToRespawnN()
{
for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
{
for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
{
ObjectGridRespawnMover mover;
mover.Move(i_grid(x, y));
}
}
}
void
ObjectGridUnloader::Unload(GridType &grid)
{
TypeContainerVisitor<ObjectGridUnloader, GridTypeMapContainer > unloader(*this);
grid.Visit(unloader);
}
template<class T>
void
ObjectGridUnloader::Visit(GridRefManager<T> &m)
{
while (!m.isEmpty())
{
T *obj = m.getFirst()->getSource();
// if option set then object already saved at this moment
if (!sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
obj->SaveRespawnTime();
///- object will get delinked from the manager when deleted
delete obj;
}
}
void
ObjectGridStoper::Stop(GridType &grid)
{
TypeContainerVisitor<ObjectGridStoper, GridTypeMapContainer > stoper(*this);
grid.Visit(stoper);
}
void
ObjectGridStoper::Visit(CreatureMapType &m)
{
// stop any fights at grid de-activation and remove dynobjects created at cast by creatures
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
{
iter->getSource()->RemoveAllDynObjects();
if (iter->getSource()->isInCombat())
{
iter->getSource()->CombatStop();
iter->getSource()->DeleteThreatList();
iter->getSource()->AI()->EnterEvadeMode();
}
}
}
void
ObjectGridCleaner::Stop(GridType &grid)
{
TypeContainerVisitor<ObjectGridCleaner, GridTypeMapContainer > stoper(*this);
grid.Visit(stoper);
}
void
ObjectGridCleaner::Visit(CreatureMapType &m)
{
for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
iter->getSource()->CleanupsBeforeDelete();
}
template<class T>
void
ObjectGridCleaner::Visit(GridRefManager<T> &m)
{
for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
iter->getSource()->RemoveFromWorld();
}
template void ObjectGridUnloader::Visit(CreatureMapType &);
template void ObjectGridUnloader::Visit(GameObjectMapType &);
template void ObjectGridUnloader::Visit(DynamicObjectMapType &);
template void ObjectGridUnloader::Visit(CorpseMapType &);
template void ObjectGridCleaner::Visit<GameObject>(GameObjectMapType &);
template void ObjectGridCleaner::Visit<DynamicObject>(DynamicObjectMapType &);
template void ObjectGridCleaner::Visit<Corpse>(CorpseMapType &);
| SeTM/MythCore | src/server/game/Grids/ObjectGridLoader.cpp | C++ | gpl-2.0 | 9,987 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
30524,
24792,
2015,
1026,
8299,
1024,
1013,
1013,
2131,
2386,
12333,
1012,
4012,
1013,
1028,
1008,
1008,
2023,
2565,
2003,
2489,
4007,
1025,
2017,
2064,
2417,
2923,
3089,
8569,
2618,
2009,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env python
# Copyright 2017 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import os
from pprint import pprint as pp
from f5_cccl.resource.ltm.pool import *
from mock import MagicMock
import pytest
bigip_pools_cfg = [
{'description': None,
'partition': 'Common',
'loadBalancingMode': 'round-robin',
'monitor': '/Common/http ',
'membersReference': {
'isSubcollection': True,
'items': [
{'ratio': 1,
'name': '172.16.0.100:8080',
'partition': 'Common',
'session': 'monitor-enabled',
'priorityGroup': 0,
'connectionLimit': 0,
'description': None},
{'ratio': 1,
'name': '172.16.0.101:8080',
'partition': 'Common',
'session': 'monitor-enabled',
'priorityGroup': 0,
'connectionLimit': 0,
'description': None}
]
},
'name': u'pool1'
},
{'description': None,
'partition': 'Common',
'loadBalancingMode': 'round-robin',
'monitor': '/Common/http ',
'name': u'pool1'
}
]
cccl_pools_cfg = [
{ "name": "pool0" },
{ "name": "pool1",
"members": [
{"address": "172.16.0.100", "port": 8080, "routeDomain": {"id": 0}},
{"address": "172.16.0.101", "port": 8080, "routeDomain": {"id": 0}}
],
"monitors": ["/Common/http"]
},
{ "name": "pool2",
"members": [
{"address": "192.168.0.100", "port": 80, "routeDomain": {"id": 2}},
{"address": "192.168.0.101", "port": 80, "routeDomain": {"id": 2}}
],
"monitors": []
},
{ "name": "pool3",
"members": [],
"description": "This is test pool 3",
"monitors": []
},
{ "name": "pool4",
"members": [],
"description": "This is test pool 4",
"monitors": ["/Common/http"]
},
{ "name": "pool1",
"members": [
{"address": "172.16.0.100", "port": 8080, "routeDomain": {"id": 0}},
{"address": "172.16.0.102", "port": 8080, "routeDomain": {"id": 0}}
],
"monitors": ["/Common/http"]
}
]
@pytest.fixture
def bigip():
bigip = MagicMock()
return bigip
@pytest.fixture
def bigip_pool0():
return bigip_pools_cfg[0]
@pytest.fixture
def bigip_pool1():
return bigip_pools_cfg[1]
@pytest.fixture
def cccl_pool0():
return cccl_pools_cfg[0]
@pytest.fixture
def cccl_pool1():
return cccl_pools_cfg[1]
@pytest.fixture
def cccl_pool2():
return cccl_pools_cfg[2]
@pytest.fixture
def cccl_pool3():
return cccl_pools_cfg[3]
@pytest.fixture
def cccl_pool5():
return cccl_pools_cfg[5]
@pytest.fixture
def bigip_members():
members_filename = (
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'./bigip-members.json'))
with open(members_filename) as fp:
json_data = fp.read()
json_data = json.loads(json_data)
members = [m for m in json_data['members']]
pp(json_data)
return members
def test_create_pool_minconfig(cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert pool.name == "pool0"
assert pool.partition == "Common"
assert pool.data['loadBalancingMode'] == "round-robin"
assert not pool.data['description']
assert len(pool) == 0
assert pool.data['monitor'] == "default"
def test_create_pool(cccl_pool1):
pool = ApiPool(partition="Common", **cccl_pool1)
assert pool.name == "pool1"
assert pool.partition == "Common"
assert pool.data['loadBalancingMode'] == "round-robin"
assert not pool.data['description']
assert pool.data['monitor'] == "/Common/http"
assert len(pool) == 2
def test_create_pool_empty_lists(cccl_pool3):
pool = ApiPool(partition="Common", **cccl_pool3)
assert pool.name == "pool3"
assert pool.partition == "Common"
assert pool.data['loadBalancingMode'] == "round-robin"
assert pool.data['description'] == "This is test pool 3"
assert pool.data['monitor'] == "default"
assert len(pool) == 0
def test_compare_equal_pools(cccl_pool0):
p1 = ApiPool(partition="Common", **cccl_pool0)
p2 = ApiPool(partition="Common", **cccl_pool0)
assert id(p1) != id(p2)
assert p1 == p2
def test_compare_pool_and_dict(cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert not pool == cccl_pool0
def test_get_uri_path(bigip, cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert pool._uri_path(bigip) == bigip.tm.ltm.pools.pool
def test_pool_hash(bigip, cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert hash(pool) == hash((pool.name, pool.partition))
def test_compare_bigip_cccl_pools(cccl_pool1, bigip_pool0):
bigip_pool = IcrPool(**bigip_pool0)
cccl_pool = ApiPool(partition="Common", **cccl_pool1)
assert bigip_pool == cccl_pool
def test_create_bigip_pool_no_members(bigip_pool1):
bigip_pool = IcrPool(**bigip_pool1)
assert bigip_pool.data['membersReference']
assert bigip_pool.data['membersReference']['items'] == []
def test_compare_pools_unequal_members(bigip, cccl_pool1, cccl_pool2, cccl_pool5):
pool1 = ApiPool(partition="Common", **cccl_pool1)
pool2 = ApiPool(partition="Common", **cccl_pool2)
pool5 = ApiPool(partition="Common", **cccl_pool5)
pool1_one_member_cfg = { "name": "pool1",
"members": [
{"address": "172.16.0.100", "port": 8080, "routeDomain": {"id": 0}},
],
"monitors": ["/Common/http"]
}
pool1_one_member = ApiPool(partition="Common",
**pool1_one_member_cfg)
pool2_with_monitor = { "name": "pool2",
"members": [
{"address": "192.168.0.100", "port": 80, "routeDomain": {"id": 2}},
{"address": "192.168.0.101", "port": 80, "routeDomain": {"id": 2}}
],
"monitors": ["/Common/http"]
}
pool2_with_monitor = ApiPool(partition="Common",
**pool2_with_monitor)
assert not pool1 == pool2
assert pool1 != pool2
assert not pool1_one_member == pool1
assert not pool2_with_monitor == pool2
assert not pool1 == pool5
assert pool1 != pool5
assert pool5 != pool1
def test_get_monitors(bigip):
pool = ApiPool(name="pool1", partition="Common")
assert pool._get_monitors(None) == "default"
assert pool._get_monitors([]) == "default"
monitors = ["/Common/http", "/Common/my_tcp"]
assert pool._get_monitors(monitors) == "/Common/http and /Common/my_tcp"
monitors = ["", ""]
assert pool._get_monitors(monitors) == " and "
monitors = ["/Common/my_tcp", "/Common/http"]
assert pool._get_monitors(monitors) == "/Common/http and /Common/my_tcp"
| richbrowne/f5-cccl | f5_cccl/resource/ltm/test/test_pool.py | Python | apache-2.0 | 7,378 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
18750,
1001,
9385,
2418,
1042,
2629,
6125,
4297,
1012,
1001,
1001,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Behavior
***
## What is behavior
the works is same as model but it has different function, behavior is used to organized "behavior" for application
into logic method. For example
class Behavior(Behavior):
def __init__(self):
super(Behavior, self).__init__()
def changeLabelText(self, parameter = None):
'''
Behavior function is used to change the label text on welcome.
'''
if self.widget.Welcome_Label.text == 'stigma':
self.widget.Welcome_Label.text = 'Welcome, Build what you want fix what you need'
else:
self.widget.Welcome_Label.text = 'stigma'
@property
def alias(self):
alias_map = CollectMap(
change_label_text=eventAttach(self.changeLabelText, 'on_touch_down')
)
return alias_map.transform
as we see, we create an behavior called `changeLabelText` with parameter *None*, because the method is converted into
event *on_touch_down* with [eventAttach](#) helper, so when the widget called this method it will convert widget
`Welcome_Label` text
### alias property
this property is also had same function with [layer model property](#) but you can return the value with your own liking. | Kzulfazriawan/stigma-game-demo | docs/english/behavior.md | Markdown | mit | 1,324 | [
30522,
1001,
5248,
1008,
1008,
1008,
1001,
1001,
2054,
2003,
5248,
1996,
2573,
2003,
2168,
2004,
2944,
2021,
2009,
2038,
2367,
3853,
1010,
5248,
2003,
2109,
2000,
4114,
1000,
5248,
1000,
2005,
4646,
2046,
7961,
4118,
1012,
2005,
2742,
246... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SPCtoMML
{
public partial class Form2 : Form
{
/// <summary>
/// Callback for updating progress
/// </summary>
private Func<double> updateProgressHandler;
/// <summary>
/// Initializes the form.
/// </summary>
/// <param name="updateProgress">The callback for updating progress bar ratio.</param>
public Form2(Func<double> updateProgress)
{
InitializeComponent();
this.Text = Program.GetProgramName();
this.updateProgressHandler = updateProgress;
}
public void UpdateHandler(Func<double> updateProgress)
{
this.updateProgressHandler = updateProgress;
}
/// <summary>
/// Updates the progress dialog status.
/// </summary>
/// <param name="status">The new status to use.</param>
public void UpdateStatus(string status)
{
this.label1.Text = status;
}
/// <summary>
/// Updates the progress bar.
/// </summary>
/// <param name="ratio">The progress ratio.</param>
public void UpdateProgress(double ratio)
{
try
{
this.progressBar1.Value = (int)Math.Round(ratio * 1000);
}
catch
{
this.progressBar1.Value = 0;
}
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (updateProgressHandler != null)
{
UpdateProgress(updateProgressHandler());
}
}
}
}
| VitorVilela7/SPCtoMML | SPCtoMML/Form2.cs | C# | gpl-3.0 | 1,633 | [
30522,
2478,
2291,
1025,
2478,
2291,
1012,
6407,
1012,
12391,
1025,
2478,
2291,
1012,
6922,
5302,
9247,
1025,
2478,
2291,
1012,
2951,
1025,
2478,
2291,
1012,
5059,
1025,
2478,
2291,
1012,
11409,
4160,
1025,
2478,
2291,
1012,
3793,
1025,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// SPDX-License-Identifier: GPL-2.0
#ifndef SMRTK2SSRFC_WINDOW_H
#define SMRTK2SSRFC_WINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QFileInfo>
extern "C" void smartrak_import(const char *file, struct dive_table *divetable);
namespace Ui {
class Smrtk2ssrfcWindow;
}
class Smrtk2ssrfcWindow : public QMainWindow
{
Q_OBJECT
public:
explicit Smrtk2ssrfcWindow(QWidget *parent = 0);
~Smrtk2ssrfcWindow();
private:
Ui::Smrtk2ssrfcWindow *ui;
QString filter();
void updateLastUsedDir(const QString &s);
void closeCurrentFile();
private
slots:
void on_inputFilesButton_clicked();
void on_outputFileButton_clicked();
void on_importButton_clicked();
void on_exitButton_clicked();
void on_outputLine_textEdited();
void on_inputLine_textEdited();
};
#endif // SMRTK2SSRFC_WINDOW_H
| mturkia/subsurface | smtk-import/smrtk2ssrfc_window.h | C | gpl-2.0 | 809 | [
30522,
1013,
1013,
23772,
2595,
1011,
6105,
1011,
8909,
4765,
18095,
1024,
14246,
2140,
1011,
1016,
1012,
1014,
1001,
2065,
13629,
2546,
15488,
5339,
2243,
2475,
4757,
12881,
2278,
1035,
3332,
1035,
1044,
1001,
9375,
15488,
5339,
2243,
2475... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
.work {
min-height: 520px;
}
.work > div > p {
margin-bottom: 5px;
}
| EcutDavid/EcutDavid.github.io | src/styles/Work.css | CSS | mit | 74 | [
30522,
1012,
2147,
1063,
8117,
1011,
4578,
1024,
19611,
2361,
2595,
1025,
1065,
1012,
2147,
1028,
4487,
2615,
1028,
1052,
1063,
7785,
1011,
3953,
1024,
1019,
2361,
2595,
1025,
1065,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Gdata_Media_Feed
*/
require_once 'Zend/Gdata/Media/Feed.php';
/**
* @see Zend_Gdata_YouTube_SubscriptionEntry
*/
require_once 'Zend/Gdata/YouTube/SubscriptionEntry.php';
/**
* The YouTube video subscription list flavor of an Atom Feed with media support
* Represents a list of individual subscriptions, where each contained entry is
* a subscription.
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_YouTube_SubscriptionFeed extends Zend_Gdata_Media_Feed
{
/**
* The classname for individual feed elements.
*
* @var string
*/
protected $_entryClassName = 'Zend_Gdata_YouTube_SubscriptionEntry';
/**
* Creates a Subscription feed, representing a list of subscriptions,
* usually associated with an individual user.
*
* @param DOMElement $element (optional) DOMElement from which this
* object should be constructed.
*/
public function __construct($element = null)
{
$this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
parent::__construct($element);
}
}
| EvanDotPro/zf1-mirror | library/Zend/Gdata/YouTube/SubscriptionFeed.php | PHP | bsd-3-clause | 2,022 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
16729,
2094,
7705,
1008,
1008,
6105,
1008,
1008,
2023,
3120,
5371,
2003,
3395,
2000,
1996,
2047,
18667,
2094,
6105,
2008,
2003,
24378,
1008,
2007,
2023,
7427,
1999,
1996,
5371,
6105,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/model/pdata"
)
func Test_loadMetadata(t *testing.T) {
tests := []struct {
name string
yml string
want metadata
wantErr string
}{
{
name: "all options",
yml: "all_options.yaml",
want: metadata{
Name: "metricreceiver",
Attributes: map[attributeName]attribute{
"enumAttribute": {
Description: "Attribute with a known set of values.",
Value: "",
Enum: []string{"red", "green", "blue"}},
"freeFormAttribute": {
Description: "Attribute that can take on any value.",
Value: ""},
"freeFormAttributeWithValue": {
Description: "Attribute that has alternate value set.",
Value: "state"}},
Metrics: map[metricName]metric{
"system.cpu.time": {
Enabled: (func() *bool { t := true; return &t })(),
Description: "Total CPU seconds broken down by different states.",
ExtendedDocumentation: "Additional information on CPU Time can be found [here](https://en.wikipedia.org/wiki/CPU_time).",
Unit: "s",
Sum: &sum{
MetricValueType: MetricValueType{pdata.MetricValueTypeDouble},
Aggregated: Aggregated{Aggregation: "cumulative"},
Mono: Mono{Monotonic: true},
},
Attributes: []attributeName{"freeFormAttribute", "freeFormAttributeWithValue", "enumAttribute"},
},
"system.cpu.utilization": {
Enabled: (func() *bool { f := false; return &f })(),
Description: "Percentage of CPU time broken down by different states.",
Unit: "1",
Gauge: &gauge{
MetricValueType: MetricValueType{pdata.MetricValueTypeDouble},
},
Attributes: []attributeName{"enumAttribute"},
},
},
},
},
{
name: "unknown metric attribute",
yml: "unknown_metric_attribute.yaml",
want: metadata{},
wantErr: "error validating struct:\n\tmetadata.Metrics[system.cpu.time]." +
"Attributes[missing]: unknown attribute value\n",
},
{
name: "no metric type",
yml: "no_metric_type.yaml",
want: metadata{},
wantErr: "metric system.cpu.time doesn't have a metric type key, " +
"one of the following has to be specified: sum, gauge, histogram",
},
{
name: "no enabled",
yml: "no_enabled.yaml",
want: metadata{},
wantErr: "error validating struct:\n\tmetadata.Metrics[system.cpu.time].Enabled: Enabled is a required field\n",
},
{
name: "two metric types",
yml: "two_metric_types.yaml",
want: metadata{},
wantErr: "metric system.cpu.time has more than one metric type keys, " +
"only one of the following has to be specified: sum, gauge, histogram",
},
{
name: "no number types",
yml: "no_value_type.yaml",
want: metadata{},
wantErr: "error validating struct:\n\tmetadata.Metrics[system.cpu.time].Sum.MetricValueType.ValueType: " +
"ValueType is a required field\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := loadMetadata(filepath.Join("testdata", tt.yml))
if tt.wantErr != "" {
require.Error(t, err)
require.EqualError(t, err, tt.wantErr)
} else {
require.NoError(t, err)
require.Equal(t, tt.want, got)
}
})
}
}
| open-telemetry/opentelemetry-collector-contrib | cmd/mdatagen/loader_test.go | GO | apache-2.0 | 3,973 | [
30522,
1013,
1013,
9385,
1996,
2330,
9834,
21382,
11129,
6048,
1013,
1013,
1013,
1013,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1013,
1013,
2017,
2089,
2025,
2224,
2023,
5371,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":4,"../lib/Shim.IE8":27}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = pathSolver.parseArr(this._index, {
verbose: true
});
queryArr = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":23,"./Shared":26}],3:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatch[joinMatchIndex].query;
joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]);
}
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = new Path(query.substr(3, query.length - 3)).value(item);
} else {
pathResult = new Path(query).value(item);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":23,"./Shared":26}],8:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":23,"./Shared":26}],9:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":26}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":21,"./Shared":26}],11:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],12:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],13:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":22,"./Serialiser":25}],14:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":22}],16:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check we have a database object to work from
if (!this.db()) {
throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!');
}
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
}
};
module.exports = Matching;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],19:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":22}],20:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":23,"./Shared":26}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
Path.prototype.valueOne = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.valueOne(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":26}],24:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":26}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.505',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
| AMoo-Miki/cdnjs | ajax/libs/forerunnerdb/1.3.505/fdb-core.js | JavaScript | mit | 240,356 | [
30522,
1006,
3853,
1041,
1006,
1056,
1010,
1050,
1010,
1054,
1007,
1063,
3853,
1055,
1006,
1051,
1010,
1057,
1007,
1063,
2065,
1006,
999,
1050,
1031,
1051,
1033,
1007,
1063,
2065,
1006,
999,
1056,
1031,
1051,
1033,
1007,
1063,
13075,
1037... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native middle-level C interface to LAPACK function ssycon_3
* Author: Intel Corporation
* Generated December 2016
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_ssycon_3_work( int matrix_layout, char uplo, lapack_int n,
const float* a, lapack_int lda,
const float* e, const lapack_int* ipiv, float anorm,
float* rcond, float* work, lapack_int* iwork )
{
lapack_int info = 0;
if( matrix_layout == LAPACK_COL_MAJOR ) {
/* Call LAPACK function and adjust info */
LAPACK_ssycon_3( &uplo, &n, a, &lda, e, ipiv, &anorm, rcond, work, iwork,
&info );
if( info < 0 ) {
info = info - 1;
}
} else if( matrix_layout == LAPACK_ROW_MAJOR ) {
lapack_int lda_t = MAX(1,n);
float* a_t = NULL;
/* Check leading dimension(s) */
if( lda < n ) {
info = -5;
LAPACKE_xerbla( "LAPACKE_ssycon_3_work", info );
return info;
}
/* Allocate memory for temporary array(s) */
a_t = (float*)LAPACKE_malloc( sizeof(float) * lda_t * MAX(1,n) );
if( a_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_0;
}
/* Transpose input matrices */
LAPACKE_ssy_trans( matrix_layout, uplo, n, a, lda, a_t, lda_t );
/* Call LAPACK function and adjust info */
LAPACK_ssycon_3( &uplo, &n, a_t, &lda_t, e, ipiv, &anorm, rcond, work, iwork,
&info );
if( info < 0 ) {
info = info - 1;
}
/* Release memory and exit */
LAPACKE_free( a_t );
exit_level_0:
if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_ssycon_3_work", info );
}
} else {
info = -1;
LAPACKE_xerbla( "LAPACKE_ssycon_3_work", info );
}
return info;
}
| grisuthedragon/OpenBLAS | lapack-netlib/LAPACKE/src/lapacke_ssycon_3_work.c | C | bsd-3-clause | 3,756 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*!
*Pratham Canada website
*Author: Danna Aphayavong
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
overflow-x: hidden;
background: url(../img/blackboard.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
}
p {
font-size: 20px;
}
p.small {
font-size: 16px;
}
a,
a:hover,
a:focus,
a:active,
a.active {
outline: 0;
color: #18bc9c;
}
h1,
h3,
h4,
h2,
h6 {
text-transform: uppercase;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 700;
}
h5{
font-weight: 400;
}
.img-centered {
margin: 0 auto;
}
header {
text-align: center;
color: #fff;
background-size: cover;
}
header .container {
padding-top: 100px;
padding-bottom: 50px;
}
header img {
display: block;
margin: 0 auto 20px;
}
header .intro-text .name {
display: block;
text-transform: uppercase;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-size: 2em;
font-weight: 700;
}
header .intro-text .skills {
font-size: 1.25em;
font-weight: 300;
}
@media(min-width:768px) {
header .container {
padding-top: 100px;
padding-bottom: 100px;
}
header .intro-text .name {
font-size: 4.75em;
}
header .intro-text .skills {
font-size: 1.75em;
}
}
@media(min-width:768px) {
.navbar-fixed-top {
padding: 0;
-webkit-transition: padding .3s;
-moz-transition: padding .3s;
transition: padding .3s;
background-image: url(../img/footer.png);
background-size:100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.navbar-fixed-top .navbar-brand {
font-size: 2em;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
padding-top: 0;
padding-bottom: 10px;
}
.navbar-fixed-top.navbar-shrink {
padding: 0;
}
.navbar-fixed-top.navbar-shrink .navbar-brand {
font-size: 1.5em;
}
}
.navbar {
text-transform: uppercase;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 900;
}
.navbar a:focus {
outline: 0;
}
.navbar .navbar-nav {
letter-spacing: 1px;
}
.navbar .navbar-nav li a:focus {
outline: 0;
}
.navbar-default,
.navbar-inverse {
border: 0;
}
section {
padding: 100px 0;
}
section h2 {
margin: 0;
font-size: 3em;
}
section.about {
color: #FFFFFF;
}
section.info {
color: #FFFFFF;
}
section.blue {
color: #FFFFFF;
}
section.red {
color: #FFFFFF;
}
section.purple {
color: #FFFFFF;
}
@media(max-width:767px) {
section {
padding: 75px 0;
}
section.first {
padding-top: 75px;
}
}
/* #portfolio .portfolio-item {
right: 0;
margin: 0 0 15px;
}
#portfolio .portfolio-item .portfolio-link {
display: block;
position: relative;
margin: 0 auto;
max-width: 400px;
}
#portfolio .portfolio-item .portfolio-link .caption {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
background: rgba(24,188,156,.9);
-webkit-transition: all ease .5s;
-moz-transition: all ease .5s;
transition: all ease .5s;
}
#portfolio .portfolio-item .portfolio-link .caption:hover {
opacity: 1;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content {
position: absolute;
top: 50%;
width: 100%;
height: 20px;
margin-top: -12px;
text-align: center;
font-size: 20px;
color: #fff;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content i {
margin-top: -12px;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content h3,
#portfolio .portfolio-item .portfolio-link .caption .caption-content h4 {
margin: 0;
}
#portfolio * {
z-index: 2;
} */
@media(min-width:767px) {
#portfolio .portfolio-item {
margin: 0 0 30px;
}
}
.btn-outline {
margin-top: 15px;
border: solid 2px #fff;
font-size: 20px;
color: #fff;
background: 0 0;
transition: all .3s ease-in-out;
}
.btn-outline:hover,
.btn-outline:focus,
.btn-outline:active,
.btn-outline.active {
border: solid 2px #fff;
color: #18bc9c;
background: #fff;
}
.floating-label-form-group {
position: relative;
margin-bottom: 0;
padding-bottom: .5em;
border-bottom: 1px solid #eee;
}
.floating-label-form-group input,
.floating-label-form-group textarea {
z-index: 1;
position: relative;
padding-right: 0;
padding-left: 0;
border: 0;
border-radius: 0;
font-size: 1.5em;
background: 0 0;
box-shadow: none!important;
resize: none;
}
.floating-label-form-group label {
display: block;
z-index: 0;
position: relative;
top: 2em;
margin: 0;
font-size: .85em;
line-height: 1.764705882em;
vertical-align: middle;
vertical-align: baseline;
opacity: 0;
-webkit-transition: top .3s ease,opacity .3s ease;
-moz-transition: top .3s ease,opacity .3s ease;
-ms-transition: top .3s ease,opacity .3s ease;
transition: top .3s ease,opacity .3s ease;
}
.floating-label-form-group::not(:first-child) {
padding-left: 14px;
border-left: 1px solid #eee;
}
.floating-label-form-group-with-value label {
top: 0;
opacity: 1;
}
.floating-label-form-group-with-focus label {
color: #18bc9c;
}
form .row:first-child .floating-label-form-group {
border-top: 1px solid #eee;
}
footer {
color: #fff;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 400;
}
footer h3 {
margin-bottom: 30px;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 400;
}
footer .footer-above {
padding-top: 10px;
background-image: url(../img/footer.png);
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 400;
}
footer .footer-col {
margin-bottom: 0px;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 400;
}
footer .footer-below {
padding: 25px 0;
}
.btn-social {
display: inline-block;
width: 50px;
height: 50px;
border: 2px solid #fff;
border-radius: 100%;
text-align: center;
font-size: 20px;
line-height: 45px;
}
.btn:focus,
.btn:active,
.btn.active {
outline: 0;
}
.scroll-top {
z-index: 1049;
position: fixed;
right: 2%;
bottom: 2%;
width: 50px;
height: 50px;
}
.scroll-top .btn {
width: 50px;
height: 50px;
border-radius: 100%;
font-size: 20px;
line-height: 28px;
}
.scroll-top .btn:focus {
outline: 0;
}
.portfolio-modal .modal-content {
padding: 100px 0;
min-height: 100%;
border: 0;
border-radius: 0;
text-align: center;
background-clip: border-box;
-webkit-box-shadow: none;
box-shadow: none;
}
.portfolio-modal .modal-content h2 {
margin: 0;
font-size: 3em;
}
.portfolio-modal .modal-content img {
margin-bottom: 30px;
}
.portfolio-modal .modal-content .item-details {
margin: 30px 0;
}
.portfolio-modal .close-modal {
position: absolute;
top: 25px;
right: 25px;
width: 75px;
height: 75px;
background-color: transparent;
cursor: pointer;
}
.portfolio-modal .close-modal:hover {
opacity: .3;
}
.portfolio-modal .close-modal .lr {
z-index: 1051;
width: 1px;
height: 75px;
margin-left: 35px;
background-color: #FFFF66;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.portfolio-modal .close-modal .lr .rl {
z-index: 1052;
width: 1px;
height: 75px;
background-color: #FFFF66;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.portfolio-modal .modal-backdrop {
display: none;
opacity: 0;
}
| DannaAphayavong/prathamcanada | css/style.css | CSS | apache-2.0 | 8,258 | [
30522,
1013,
1008,
999,
1008,
10975,
8988,
3286,
2710,
4037,
1008,
3166,
1024,
4907,
2532,
9706,
26115,
17789,
2290,
1008,
3642,
7000,
2104,
1996,
15895,
6105,
1058,
2475,
1012,
1014,
1012,
1008,
2005,
4751,
1010,
2156,
8299,
1024,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Kyaroikeus Sniezek, Coats & Small, 1995 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
J Eukaryot Microbiol 42 (3), May-June: 261.
#### Original name
null
### Remarks
null | mdoering/backbone | life/Protozoa/Ciliophora/Cyrtophoria/Dysteriida/Kyaroikeidae/Kyaroikeus/README.md | Markdown | apache-2.0 | 242 | [
30522,
1001,
18712,
10464,
17339,
2271,
1055,
8034,
24506,
1010,
15695,
1004,
2235,
1010,
2786,
3562,
1001,
1001,
1001,
1001,
3570,
3970,
1001,
1001,
1001,
1001,
2429,
2000,
9455,
4236,
1997,
3884,
1998,
2512,
21966,
11416,
1001,
1001,
1001... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
### 2020-09-14
diff between today and yesterday
#### python
* [ytdl-org/youtube-dl](https://github.com/ytdl-org/youtube-dl): Command-line program to download videos from YouTube.com and other video sites
* [baowenbo/DAIN](https://github.com/baowenbo/DAIN): Depth-Aware Video Frame Interpolation (CVPR 2019)
* [intelowlproject/IntelOwl](https://github.com/intelowlproject/IntelOwl): Intel Owl: analyze files, domains, IPs in multiple ways from a single API at scale
* [espressif/esptool](https://github.com/espressif/esptool): ESP8266 and ESP32 serial bootloader utility
* [openai/gym](https://github.com/openai/gym): A toolkit for developing and comparing reinforcement learning algorithms.
* [zhzyker/exphub](https://github.com/zhzyker/exphub): Exphub[] WebloigcStruts2TomcatNexusSolrJbossDrupalCVE-2020-5902CVE-2020-11444CVE-2020-10204CVE-2020-10199CVE-2020-1938CVE-2020-2551CVE-2020-2555CVE-2020-2883CVE-2019-17558CVE-2019-6340
* [gnebbia/kb](https://github.com/gnebbia/kb): A minimalist knowledge base manager
* [powerline/powerline](https://github.com/powerline/powerline): Powerline is a statusline plugin for vim, and provides statuslines and prompts for several other applications, including zsh, bash, tmux, IPython, Awesome and Qtile.
* [pyca/cryptography](https://github.com/pyca/cryptography): cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.
* [anandpawara/Real_Time_Image_Animation](https://github.com/anandpawara/Real_Time_Image_Animation): The Project is real time application in opencv using first order model
* [lyft/l5kit](https://github.com/lyft/l5kit): L5Kit - level5.lyft.com
* [timgrossmann/InstaPy](https://github.com/timgrossmann/InstaPy): Instagram Bot - Tool for automated Instagram interactions
* [zhan-xu/RigNet](https://github.com/zhan-xu/RigNet): Code for SIGGRAPH 2020 paper "RigNet: Neural Rigging for Articulated Characters"
* [domlysz/BlenderGIS](https://github.com/domlysz/BlenderGIS): Blender addons to make the bridge between Blender and geographic data
* [KurtBestor/Hitomi-Downloader](https://github.com/KurtBestor/Hitomi-Downloader): Desktop application to download images/videos/music/text from Hitomi.la and other sites, and more.
* [ZimoLoveShuang/auto-submit](https://github.com/ZimoLoveShuang/auto-submit):
#### go
* [golang-design/history](https://github.com/golang-design/history): Go: A Documentary | golang.design/history
* [kubernetes/enhancements](https://github.com/kubernetes/enhancements): Enhancements tracking repo for Kubernetes
* [rclone/rclone](https://github.com/rclone/rclone): "rsync for cloud storage" - Google Drive, Amazon Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Cloudfiles, Google Cloud Storage, Yandex Files
* [DNSCrypt/dnscrypt-proxy](https://github.com/DNSCrypt/dnscrypt-proxy): dnscrypt-proxy 2 - A flexible DNS proxy, with support for encrypted DNS protocols.
* [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go): Algorithms Implemented in GoLang
* [mattermost/mattermost-server](https://github.com/mattermost/mattermost-server): Open source Slack-alternative in Golang and React - Mattermost
* [p4gefau1t/trojan-go](https://github.com/p4gefau1t/trojan-go): GoTrojan//CDN/ShadowsocksA Trojan proxy written in Go. An unidentifiable mechanism that helps you bypass GFW. https://p4gefau1t.github.io/trojan-go/
* [mmcdole/gofeed](https://github.com/mmcdole/gofeed): Parse RSS, Atom and JSON feeds in Go
* [0xsha/CloudBrute](https://github.com/0xsha/CloudBrute): Awesome cloud enumerator
* [dapr/dapr](https://github.com/dapr/dapr): Dapr is a portable, event-driven, runtime for building distributed applications across cloud and edge.
* [docker/distribution](https://github.com/docker/distribution): The Docker toolset to pack, ship, store, and deliver content
* [hashicorp/terraform](https://github.com/hashicorp/terraform): Terraform enables you to safely and predictably create, change, and improve infrastructure. It is an open source tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
* [docker/docker-ce](https://github.com/docker/docker-ce): Docker CE
* [geph-official/geph2](https://github.com/geph-official/geph2): Geph () is a modular Internet censorship circumvention system designed specifically to deal with national filtering.
* [open-policy-agent/conftest](https://github.com/open-policy-agent/conftest): Write tests against structured configuration data using the Open Policy Agent Rego query language
* [FairwindsOps/polaris](https://github.com/FairwindsOps/polaris): Validation of best practices in your Kubernetes clusters
#### cpp
* [TheCherno/Hazel](https://github.com/TheCherno/Hazel): Hazel Engine
* [TheAlgorithms/C-Plus-Plus](https://github.com/TheAlgorithms/C-Plus-Plus): Collection of various algorithms in mathematics, machine learning, computer science and physics implemented in C++ for educational purposes.
* [Aircoookie/WLED](https://github.com/Aircoookie/WLED): Control WS2812B and many more types of digital RGB LEDs with an ESP8266 or ESP32 over WiFi!
* [mostafa-saad/ArabicCompetitiveProgramming](https://github.com/mostafa-saad/ArabicCompetitiveProgramming): The repository contains the ENGLISH description files attached to the video series in my ARABIC algorithms channel.
* [taichi-dev/taichi](https://github.com/taichi-dev/taichi): Productive & portable programming language for high-performance, sparse & differentiable computing on GPUs
* [hrydgard/ppsspp](https://github.com/hrydgard/ppsspp): A PSP emulator for Android, Windows, Mac and Linux, written in C++. Want to contribute? Join us on Discord at https://discord.gg/5NJB6dD or in #ppsspp on freenode (IRC) or just send pull requests / issues. For discussion use the forums on ppsspp.org.
* [LMMS/lmms](https://github.com/LMMS/lmms): Cross-platform music production software
* [topjohnwu/Magisk](https://github.com/topjohnwu/Magisk): The Magic Mask for Android
* [microsoft/react-native-windows](https://github.com/microsoft/react-native-windows): A framework for building native Windows apps with React.
* [FreeCAD/FreeCAD](https://github.com/FreeCAD/FreeCAD): This is the official source code of FreeCAD, a free and opensource multiplatform 3D parametric modeler. Issues are managed on our own bug tracker at https://www.freecadweb.org/tracker
* [gzc/CLRS](https://github.com/gzc/CLRS): Solutions to Introduction to Algorithms
* [Z3Prover/z3](https://github.com/Z3Prover/z3): The Z3 Theorem Prover
* [FastLED/FastLED](https://github.com/FastLED/FastLED): The FastLED library for colored LED animation on Arduino. Please direct questions/requests for help to the FastLED Reddit community: http://fastled.io/r We'd like to use github "issues" just for tracking library bugs / enhancements.
* [DrKLO/Telegram](https://github.com/DrKLO/Telegram): Telegram for Android source
* [zhedahht/CodingInterviewChinese2](https://github.com/zhedahht/CodingInterviewChinese2): Offer
#### javascript
* [gothinkster/realworld](https://github.com/gothinkster/realworld): "The mother of all demo apps" Exemplary fullstack Medium.com clone powered by React, Angular, Node, Django, and many more
* [justdjango/django-ecommerce](https://github.com/justdjango/django-ecommerce): An e-commerce website built with Django
* [tailwindlabs/heroicons](https://github.com/tailwindlabs/heroicons): A set of free MIT-licensed high-quality SVG icons for UI development.
* [node-fetch/node-fetch](https://github.com/node-fetch/node-fetch): A light-weight module that brings Fetch API to Node.js
* [firebase/functions-samples](https://github.com/firebase/functions-samples): Collection of sample apps showcasing popular use cases using Cloud Functions for Firebase
* [qianguyihao/Web](https://github.com/qianguyihao/Web): Web
* [Zettlr/Zettlr](https://github.com/Zettlr/Zettlr): A Markdown Editor for the 21st century.
* [feross/simple-peer](https://github.com/feross/simple-peer): Simple WebRTC video, voice, and data channels
* [yarnpkg/yarn](https://github.com/yarnpkg/yarn): Fast, reliable, and secure dependency management.
* [js-org/js.org](https://github.com/js-org/js.org): Dedicated to JavaScript and its awesome community since 2015
* [rolling-scopes-school/tasks](https://github.com/rolling-scopes-school/tasks):
* [emberjs/ember.js](https://github.com/emberjs/ember.js): Ember.js - A JavaScript framework for creating ambitious web applications
* [typescript-cheatsheets/react](https://github.com/typescript-cheatsheets/react): Cheatsheets for experienced React developers getting started with TypeScript
* [nextauthjs/next-auth](https://github.com/nextauthjs/next-auth): Authentication for Next.js
* [iamadamdev/bypass-paywalls-chrome](https://github.com/iamadamdev/bypass-paywalls-chrome): Bypass Paywalls web browser extension for Chrome and Firefox.
#### coffeescript
* [Qix-/node-error-ex](https://github.com/Qix-/node-error-ex): Easy error subclassing and stack customization
| larsbijl/trending_archive | 2020-09/2020-09-14_short.md | Markdown | mit | 9,023 | [
30522,
1001,
1001,
1001,
12609,
1011,
5641,
1011,
2403,
4487,
4246,
2090,
2651,
1998,
7483,
1001,
1001,
1001,
1001,
18750,
1008,
1031,
1061,
2102,
19422,
1011,
8917,
1013,
7858,
1011,
21469,
1033,
1006,
16770,
1024,
1013,
1013,
21025,
2705,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
!=====================================================================
!
! S p e c f e m 3 D G l o b e V e r s i o n 7 . 0
! --------------------------------------------------
!
! Main historical authors: Dimitri Komatitsch and Jeroen Tromp
! Princeton University, USA
! and CNRS / University of Marseille, France
! (there are currently many more authors!)
! (c) Princeton University and CNRS / University of Marseille, April 2014
!
! This program is free software; you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation; either version 2 of the License, or
! (at your option) any later version.
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License along
! with this program; if not, write to the Free Software Foundation, Inc.,
! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
!
!=====================================================================
subroutine read_topography_bathymetry()
use specfem_par
use specfem_par_crustmantle
use specfem_par_innercore
use specfem_par_outercore
implicit none
! local parameters
integer :: ier
! timing
double precision :: tCPU
double precision, external :: wtime
character(len=MAX_STRING_LEN) :: topo_path
! get MPI starting time
time_start = wtime()
! make ellipticity
if (ELLIPTICITY_VAL) then
! splines used for locating exact source/receivers positions
! in locate_sources() and locate_receivers() routines
call make_ellipticity(nspl,rspl,espl,espl2,ONE_CRUST)
endif
! read topography and bathymetry file
if (TOPOGRAPHY) then
! allocates topography array
allocate(ibathy_topo(NX_BATHY,NY_BATHY),stat=ier)
if (ier /= 0 ) call exit_mpi(myrank,'Error allocating ibathy_topo array')
! initializes
ibathy_topo(:,:) = 0
if (I_should_read_the_database) then
! master reads file
if (myrank == 0) then
! user output
write(IMAIN,*) 'topography:'
call flush_IMAIN()
topo_path = LOCAL_PATH
! reads topo file
call read_topo_bathy_database(ibathy_topo, topo_path)
endif
! broadcast the information read on the master to the nodes
call bcast_all_i(ibathy_topo,NX_BATHY*NY_BATHY)
endif
call bcast_ibathy_topo()
endif
! user output
call synchronize_all()
if (myrank == 0 .and. (TOPOGRAPHY .or. OCEANS_VAL .or. ELLIPTICITY_VAL)) then
! elapsed time since beginning of mesh generation
tCPU = wtime() - time_start
write(IMAIN,*)
write(IMAIN,*) 'Elapsed time for reading topo/bathy in seconds = ',sngl(tCPU)
write(IMAIN,*)
call flush_IMAIN()
endif
end subroutine read_topography_bathymetry
!
!-------------------------------------------------------------------------------------------------
!
subroutine bcast_ibathy_topo()
use specfem_par
use specfem_par_crustmantle
use specfem_par_innercore
use specfem_par_outercore
implicit none
call bcast_all_i_for_database(ibathy_topo(1,1), size(ibathy_topo))
end subroutine bcast_ibathy_topo
| QuLogic/specfem3d_globe | src/specfem3D/read_topography_bathymetry.f90 | FORTRAN | gpl-2.0 | 3,428 | [
30522,
999,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//===--- CallerAnalysis.cpp - Determine callsites to a function ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-caller-analysis"
#include "swift/SILOptimizer/Analysis/CallerAnalysis.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/YAMLTraits.h"
using namespace swift;
namespace {
using FunctionInfo = CallerAnalysis::FunctionInfo;
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// CallerAnalysis::FunctionInfo
//===----------------------------------------------------------------------===//
CallerAnalysis::FunctionInfo::FunctionInfo(SILFunction *f)
: callerStates(),
// TODO: Make this more aggressive by considering
// final/visibility/etc.
mayHaveIndirectCallers(f->getDynamicallyReplacedFunction() ||
canBeCalledIndirectly(f->getRepresentation())),
mayHaveExternalCallers(f->isPossiblyUsedExternally() ||
f->isAvailableExternally()) {}
//===----------------------------------------------------------------------===//
// CallerAnalysis::ApplySiteFinderVisitor
//===----------------------------------------------------------------------===//
struct CallerAnalysis::ApplySiteFinderVisitor
: SILInstructionVisitor<ApplySiteFinderVisitor, bool> {
CallerAnalysis *analysis;
SILFunction *callerFn;
FunctionInfo &callerInfo;
#ifndef NDEBUG
SmallPtrSet<SILInstruction *, 8> visitedCallSites;
SmallSetVector<SILInstruction *, 8> callSitesThatMustBeVisited;
#endif
ApplySiteFinderVisitor(CallerAnalysis *analysis, SILFunction *callerFn)
: analysis(analysis), callerFn(callerFn),
callerInfo(analysis->unsafeGetFunctionInfo(callerFn)) {}
~ApplySiteFinderVisitor();
bool visitSILInstruction(SILInstruction *) { return false; }
bool visitFunctionRefInst(FunctionRefInst *fri) {
return visitFunctionRefBaseInst(fri);
}
bool visitDynamicFunctionRefInst(DynamicFunctionRefInst *fri) {
return visitFunctionRefBaseInst(fri);
}
bool
visitPreviousDynamicFunctionRefInst(PreviousDynamicFunctionRefInst *fri) {
return visitFunctionRefBaseInst(fri);
}
bool visitFunctionRefBaseInst(FunctionRefBaseInst *fri);
void process();
void processApplySites(ArrayRef<ApplySite> applySites);
void processApplySites(ArrayRef<FullApplySite> applySites);
void checkCallSiteInvariants(SILInstruction &i);
};
void CallerAnalysis::ApplySiteFinderVisitor::processApplySites(
ArrayRef<ApplySite> applySites) {
// For now we just verify our invariants. If we need to update other
// non-NDEBUG state related to apply sites, this should be updated.
#ifndef NDEBUG
for (auto applySite : applySites) {
visitedCallSites.insert(applySite.getInstruction());
callSitesThatMustBeVisited.remove(applySite.getInstruction());
}
#endif
}
void CallerAnalysis::ApplySiteFinderVisitor::processApplySites(
ArrayRef<FullApplySite> applySites) {
// For now we just verify our invariants. If we need to update other
// non-NDEBUG state related to apply sites, this should be updated.
#ifndef NDEBUG
for (auto applySite : applySites) {
visitedCallSites.insert(applySite.getInstruction());
callSitesThatMustBeVisited.remove(applySite.getInstruction());
}
#endif
}
CallerAnalysis::ApplySiteFinderVisitor::~ApplySiteFinderVisitor() {
#ifndef NDEBUG
if (callSitesThatMustBeVisited.empty())
return;
llvm::errs() << "Found unhandled call sites!\n";
while (callSitesThatMustBeVisited.size()) {
auto *i = callSitesThatMustBeVisited.pop_back_val();
llvm::errs() << "Inst: " << *i;
}
assert(false && "Unhandled call site?!");
#endif
}
bool CallerAnalysis::ApplySiteFinderVisitor::visitFunctionRefBaseInst(
FunctionRefBaseInst *fri) {
auto optResult = findLocalApplySites(fri);
auto *calleeFn = fri->getInitiallyReferencedFunction();
FunctionInfo &calleeInfo = analysis->unsafeGetFunctionInfo(calleeFn);
// First make an edge from our callerInfo to our calleeState for invalidation
// purposes.
callerInfo.calleeStates.insert(calleeFn);
// Then grab our callee state and update it with state for this caller.
auto iter = calleeInfo.callerStates.insert({callerFn, {}});
// If we succeeded in inserting a new value, put in an optimistic
// value for escaping.
if (iter.second) {
iter.first->second.isDirectCallerSetComplete = true;
}
// Then check if we found any information at all from our result. If we
// didn't, then mark this as escaping and bail.
if (!optResult.hasValue()) {
iter.first->second.isDirectCallerSetComplete = false;
return true;
}
auto &result = optResult.getValue();
// Ok. We know that we have some sort of information. Merge that information
// into our information.
iter.first->second.isDirectCallerSetComplete &= !result.isEscaping();
if (result.fullApplySites.size()) {
iter.first->second.hasFullApply = true;
processApplySites(llvm::makeArrayRef(result.fullApplySites));
}
if (result.partialApplySites.size()) {
auto optMin = iter.first->second.getNumPartiallyAppliedArguments();
unsigned min = optMin.getValueOr(UINT_MAX);
for (ApplySite partialSite : result.partialApplySites) {
min = std::min(min, partialSite.getNumArguments());
}
iter.first->second.setNumPartiallyAppliedArguments(min);
processApplySites(result.partialApplySites);
}
return true;
}
void CallerAnalysis::ApplySiteFinderVisitor::checkCallSiteInvariants(
SILInstruction &i) {
#ifndef NDEBUG
if (auto apply = FullApplySite::isa(&i)) {
if (apply.getCalleeFunction() && !visitedCallSites.count(&i)) {
callSitesThatMustBeVisited.insert(&i);
}
return;
}
// Make sure that we are in sync with looking for partial apply callees.
if (auto *pai = dyn_cast<PartialApplyInst>(&i)) {
if (pai->getCalleeFunction() && !visitedCallSites.count(&i)) {
callSitesThatMustBeVisited.insert(pai);
}
return;
}
#endif
}
void CallerAnalysis::ApplySiteFinderVisitor::process() {
for (auto &block : *callerFn) {
for (auto &i : block) {
#ifndef NDEBUG
// If this is a call site that we visited as part of seeing a different
// function_ref, skip it. We know that it has been processed correctly.
//
// NOTE: This is only used in NDEBUG builds since we only use this as part
// of the verification that we can find all callees going forward along
// def-use edges that FullApplySite is able to track backwards along
// def-use edges.
if (visitedCallSites.count(&i))
continue;
#endif
// Try to find the apply sites for this specific FRI.
if (visit(&i))
continue;
#ifndef NDEBUG
checkCallSiteInvariants(i);
#endif
}
}
}
//===----------------------------------------------------------------------===//
// CallerAnalysis
//===----------------------------------------------------------------------===//
// NOTE: This is only meant to be used by external users of CallerAnalysis since
// it recomputes our invalidated results. For internal uses, please instead use
// getOrInsertFunctionInfo or unsafeGetFunctionInfo.
const FunctionInfo &CallerAnalysis::getFunctionInfo(SILFunction *f) const {
// Recompute every function in the invalidated function list and empty the
// list.
auto &self = const_cast<CallerAnalysis &>(*this);
self.processRecomputeFunctionList();
return self.unsafeGetFunctionInfo(f);
}
// Private only version of this function for mutable callers that tries to
// initialize a new f.
FunctionInfo &CallerAnalysis::getOrInsertFunctionInfo(SILFunction *f) {
LLVM_DEBUG(llvm::dbgs() << "CallerAnalysis: Creating caller info for: "
<< f->getName() << "\n");
return funcInfos.try_emplace(f, f).first->second;
}
FunctionInfo &CallerAnalysis::unsafeGetFunctionInfo(SILFunction *f) {
auto r = funcInfos.find(f);
assert(r != funcInfos.end() && "Function does not have functionInfo!");
return r->second;
}
const FunctionInfo &
CallerAnalysis::unsafeGetFunctionInfo(SILFunction *f) const {
auto r = funcInfos.find(f);
assert(r != funcInfos.end() && "Function does not have functionInfo!");
return r->second;
}
CallerAnalysis::CallerAnalysis(SILModule *m)
: SILAnalysis(SILAnalysisKind::Caller), mod(*m) {
// When we start we create a function info for each f and add all f to the
// recompute function list.
for (auto &f : mod) {
getOrInsertFunctionInfo(&f);
recomputeFunctionList.insert(&f);
}
}
void CallerAnalysis::processFunctionCallSites(SILFunction *callerFn) {
ApplySiteFinderVisitor visitor(this, callerFn);
visitor.process();
}
void CallerAnalysis::invalidateAllInfo(SILFunction *f) {
// Look up the callees that our caller refers to and invalidate any
// values that point back at the caller.
FunctionInfo &fInfo = unsafeGetFunctionInfo(f);
// Then we first eliminate any callees that we point at.
invalidateKnownCallees(f, fInfo);
// And then eliminate any caller edges that we need.
while (fInfo.callerStates.size()) {
auto back = fInfo.callerStates.back();
SILFunction *caller = back.first;
auto &callerInfo = unsafeGetFunctionInfo(caller);
LLVM_DEBUG(llvm::dbgs()
<< " caller-backedge: " << caller->getName() << "\n");
bool foundF = callerInfo.calleeStates.remove(f);
(void)foundF;
assert(foundF && "Bad caller edge pointing at f?");
fInfo.callerStates.pop_back();
}
}
void CallerAnalysis::invalidateKnownCallees(SILFunction *caller,
FunctionInfo &callerInfo) {
LLVM_DEBUG(llvm::dbgs() << "Invalidating caller: " << caller->getName()
<< "\n");
while (callerInfo.calleeStates.size()) {
auto *callee = callerInfo.calleeStates.pop_back_val();
FunctionInfo &calleeInfo = unsafeGetFunctionInfo(callee);
LLVM_DEBUG(llvm::dbgs() << " callee: " << callee->getName() << "\n");
assert(calleeInfo.callerStates.count(caller) &&
"Referenced callee is not fully/partially applied in the caller?!");
// Then remove the caller from this specific callee's info struct
// and to be conservative mark the callee as potentially having an
// escaping use that we do not understand.
calleeInfo.callerStates.erase(caller);
}
}
void CallerAnalysis::invalidateKnownCallees(SILFunction *caller) {
// Look up the callees that our caller refers to and invalidate any
// values that point back at the caller.
invalidateKnownCallees(caller, unsafeGetFunctionInfo(caller));
}
void CallerAnalysis::verify(SILFunction *caller) const {
#ifndef NDEBUG
const FunctionInfo &callerInfo = unsafeGetFunctionInfo(caller);
verify(caller, callerInfo);
#endif
}
void CallerAnalysis::verify(SILFunction *function,
const FunctionInfo &functionInfo) const {
#ifndef NDEBUG
LLVM_DEBUG(llvm::dbgs() << "Validating function: " << function->getName()
<< "\n");
for (auto *callee : functionInfo.calleeStates) {
LLVM_DEBUG(llvm::dbgs() << " callee: " << callee->getName() << "\n");
const FunctionInfo &calleeInfo = unsafeGetFunctionInfo(callee);
assert(calleeInfo.callerStates.count(function) &&
"Referenced callee is not fully/partially applied in the caller");
}
// Make sure all caller edges are valid.
for (auto callerPair : functionInfo.callerStates) {
auto *caller = callerPair.first;
LLVM_DEBUG(llvm::dbgs() << " caller: " << caller->getName() << "\n");
const FunctionInfo &callerInfo = unsafeGetFunctionInfo(caller);
assert(callerInfo.calleeStates.count(function) &&
"Referencing caller does not have a callee edge for function");
}
#endif
}
void CallerAnalysis::verify() const {
#ifndef NDEBUG
std::vector<SILFunction *> seenFunctions;
for (auto &fn : mod) {
bool found = funcInfos.count(&fn);
if (!found) {
llvm::errs() << "Missing notification for added function: '"
<< fn.getName() << "'\n";
llvm_unreachable("standard error assertion");
}
seenFunctions.push_back(&fn);
}
sortUnique(seenFunctions);
for (auto &pair : funcInfos) {
bool found = std::binary_search(seenFunctions.begin(), seenFunctions.end(),
pair.first);
if (!found) {
llvm::errs() << "Notification not sent for deleted function: '"
<< pair.first->getName() << "'.";
llvm_unreachable("standard error assertion");
}
verify(pair.first, pair.second);
}
#endif
}
void CallerAnalysis::invalidate() {
for (auto &f : mod) {
// Since we are going over all functions in the module
// invalidateKnownCallees should be sufficient.
invalidateKnownCallees(&f);
// We do not need to clear recompute function list since we know that it can
// at most contain a subset of the functions in the module so the SetVector
// will unique for us.
recomputeFunctionList.insert(&f);
}
}
//===----------------------------------------------------------------------===//
// CallerAnalysis YAML Dumper
//===----------------------------------------------------------------------===//
namespace {
using llvm::yaml::IO;
using llvm::yaml::MappingTraits;
using llvm::yaml::Output;
using llvm::yaml::ScalarEnumerationTraits;
using llvm::yaml::SequenceTraits;
/// A special struct that marshals call graph state into a form that
/// is easy for llvm's yaml i/o to dump. Its structure is meant to
/// correspond to how the data should be shown by the printer, so
/// naturally it is slightly redundant.
struct YAMLCallGraphNode {
StringRef calleeName;
bool hasCaller;
unsigned minPartialAppliedArgs;
bool hasOnlyCompleteDirectCallerSets;
bool hasAllCallers;
std::vector<StringRef> partialAppliers;
std::vector<StringRef> fullAppliers;
YAMLCallGraphNode() = delete;
~YAMLCallGraphNode() = default;
YAMLCallGraphNode(const YAMLCallGraphNode &) = delete;
YAMLCallGraphNode(YAMLCallGraphNode &&) = delete;
YAMLCallGraphNode &operator=(const YAMLCallGraphNode &) = delete;
YAMLCallGraphNode &operator=(YAMLCallGraphNode &&) = delete;
YAMLCallGraphNode(StringRef calleeName, bool hasCaller,
unsigned minPartialAppliedArgs,
bool hasOnlyCompleteDirectCallerSets, bool hasAllCallers,
std::vector<StringRef> &&partialAppliers,
std::vector<StringRef> &&fullAppliers)
: calleeName(calleeName), hasCaller(hasCaller),
minPartialAppliedArgs(minPartialAppliedArgs),
hasOnlyCompleteDirectCallerSets(hasOnlyCompleteDirectCallerSets),
hasAllCallers(hasAllCallers),
partialAppliers(std::move(partialAppliers)),
fullAppliers(std::move(fullAppliers)) {}
};
} // end anonymous namespace
namespace llvm {
namespace yaml {
template <> struct MappingTraits<YAMLCallGraphNode> {
static void mapping(IO &io, YAMLCallGraphNode &func) {
io.mapRequired("calleeName", func.calleeName);
io.mapRequired("hasCaller", func.hasCaller);
io.mapRequired("minPartialAppliedArgs", func.minPartialAppliedArgs);
io.mapRequired("hasOnlyCompleteDirectCallerSets",
func.hasOnlyCompleteDirectCallerSets);
io.mapRequired("hasAllCallers", func.hasAllCallers);
io.mapRequired("partialAppliers", func.partialAppliers);
io.mapRequired("fullAppliers", func.fullAppliers);
}
};
} // namespace yaml
} // namespace llvm
void CallerAnalysis::dump() const { print(llvm::errs()); }
void CallerAnalysis::print(const char *filePath) const {
using namespace llvm::sys;
std::error_code error;
llvm::raw_fd_ostream fileOutputStream(filePath, error, fs::OF_Text);
if (error) {
llvm::errs() << "Failed to open path \"" << filePath << "\" for writing.!";
llvm_unreachable("default error handler");
}
print(fileOutputStream);
}
void CallerAnalysis::print(llvm::raw_ostream &os) const {
llvm::yaml::Output yout(os);
// NOTE: We purposely do not iterate over our internal state here to ensure
// that we dump for all functions and that we dump the state we have stored
// with the functions in module order.
for (auto &f : mod) {
const auto &fi = getFunctionInfo(&f);
std::vector<StringRef> partialAppliers;
std::vector<StringRef> fullAppliers;
for (auto &apply : fi.getAllReferencingCallers()) {
if (apply.second.hasFullApply) {
fullAppliers.push_back(apply.first->getName());
}
if (apply.second.getNumPartiallyAppliedArguments().hasValue()) {
partialAppliers.push_back(apply.first->getName());
}
}
YAMLCallGraphNode node(
f.getName(), fi.hasDirectCaller(), fi.getMinPartialAppliedArgs(),
fi.hasOnlyCompleteDirectCallerSets(), fi.foundAllCallers(),
std::move(partialAppliers), std::move(fullAppliers));
yout << node;
}
}
//===----------------------------------------------------------------------===//
// Main Entry Point
//===----------------------------------------------------------------------===//
SILAnalysis *swift::createCallerAnalysis(SILModule *mod) {
return new CallerAnalysis(mod);
}
| rudkx/swift | lib/SILOptimizer/Analysis/CallerAnalysis.cpp | C++ | apache-2.0 | 17,945 | [
30522,
1013,
1013,
1027,
1027,
1027,
1011,
1011,
1011,
20587,
25902,
1012,
18133,
2361,
1011,
5646,
4455,
7616,
2000,
1037,
3853,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1027,
1027,
1027,
1013,
1013,
1013,
1013,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Sublime Text
[Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code)
## Packager
[Sublime Package Control](https://sublime.wbond.net/)
[Sublime Package Control Install](https://sublime.wbond.net/installation)
Install a Package
/preferences/package control/install package
List Install Packages
/preferences/package control/list packages
### Base Packages
[Sidebar Enhancements](https://sublime.wbond.net/packages/SideBarEnhancements)
Browser Refresh (not needed for hugo or compass)
[Markdown Editing](https://sublime.wbond.net/packages/MarkdownEditing)
might have to set view/syntax/opens all with current extensions as/markdownediting/??? to get nice formatting
Delete Blank Lines
FileDiffs
rsub (for editing locally files on remote server)
https://github.com/Drarok/rsub
[Dependents](dependents.md)
ssh to the server and wget this
```
sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
sudo chmod +x /usr/local/bin/rsub
```
original post here.
http://www.lleess.com/2013/05/how-to-edit-remote-files-with-sublime.html
Possible sh file or put it in the config.
```
#!/bin/bash
ssh -R 52698:localhost:52698
ssh -o IdentitiesOnly=yes -i /home/david/.ssh/EC2Server.pem ubuntu@54.191.214.51
```
```
~/.ssh/config
Host 54.191.214.51
RemoteForward 52698 localhost:52698
```
Windows/Linux:
Ctrl+Alt+Backspace --> Delete Blank Lines
Ctrl+Alt+Shift+Backspace --> Delete Surplus Blank Lines
OSX:
Ctrl+Alt+Delete --> Delete Blank Lines
Ctrl+Alt+Shift+Delete --> Delete Blank Lines
### Misc
ctnrl-j join lines (http://sublimetexttips.com/7-handy-text-manipulation-tricks-sublime-text-2/)
### User Settings
For not saving state
```
"hot_exit": false,
"remember_open_files": false
```
### Languages
download a raw .dic file from there to the packages directory
(you can find out by doing preferences browse packages)
https://github.com/SublimeText/Dictionaries
click on the .dic file right click on the raw button and download
### My Snippets
fmt<tab> {{% format xxxxx %}}
cfmt<tab> {{% /format %}}
img<tab> {{% image filename="" caption="" position="" %}}
ibr<tab> {{% imagebreak %}}
lno<tab> {{% linkout text="" url="" %}} (not finished??)
For notes use NOTE-xx: where xx is initials of person for that note. use no initial for a generic note. Could us bold-italics for notes. Example
***NOTE-dk:this is example note***
to use the note snippet. type nt then the <tab> key
## Find and Replace
### Regular Expressions - Regex
Finds a paragraph
^(.+?)\n\s*\n
Put something before and after the paragraph
{test}\n\1\n{end test}\n\n
find paragaraphs
```
^(.+?)\n\s*\n
```
find paragraph starting with {{% image
```
^(\{\{% image.*$)
```
wrap the english class format shortcode around it
```
{{% format english %}}\n\1\n{{% /format %}}
```
find paragraphs except those that start with {{% which is a shortcode
```
^(?!\{\{\%)(.*$)\n\s*\n
```
put format shortcoded around paragraph
```
{{% format english %}}\n\1\n{{% /format %}}\n\n
```
| dkebler/hackingnotes | sublime.md | Markdown | mit | 3,079 | [
30522,
1001,
28341,
3793,
1031,
2928,
7698,
21910,
4095,
15558,
1033,
1006,
16770,
1024,
1013,
1013,
21025,
2705,
12083,
1012,
4012,
1013,
4205,
1011,
1052,
1013,
2928,
7698,
1011,
2182,
1013,
15536,
3211,
1013,
2928,
7698,
1011,
21910,
409... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* @file
* Default simple view template to display a list of rows.
*
* @ingroup views_templates
*/
?>
<?php if (!empty($title)): ?>
<h3><?php print $title; ?></h3>
<?php endif; ?>
<div class="our-works-slider"><?php foreach ($rows as $id => $row): ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>
<?php print $row; ?>
</div>
<?php endforeach; ?></div>
| farruhmirisoev/mir | sites/all/themes/mytheme/templates/views-view-unformatted--view-our-work--block.tpl.php | PHP | gpl-2.0 | 439 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
1030,
5371,
1008,
12398,
3722,
3193,
23561,
2000,
4653,
1037,
2862,
1997,
10281,
1012,
1008,
1008,
1030,
13749,
22107,
5328,
1035,
23561,
2015,
1008,
1013,
1029,
1028,
1026,
1029,
25718,
206... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
const Sites = require('./reducers/sites-list');
const Site = require('./reducers/site-form');
const User = require('./reducers/user');
const Delete = require('./reducers/delete');
const Count = require('./reducers/count');
const Redux = require('redux');
module.exports = Redux.createStore(
Redux.combineReducers({
delete: Delete,
sites: Sites,
site: Site,
count: Count,
user: User
})
);
| interra/data-admin | client/pages/sites/store.js | JavaScript | mit | 453 | [
30522,
1005,
2224,
9384,
1005,
1025,
9530,
3367,
4573,
1027,
5478,
1006,
1005,
1012,
1013,
5547,
2869,
1013,
4573,
1011,
2862,
1005,
1007,
1025,
9530,
3367,
2609,
1027,
5478,
1006,
1005,
1012,
1013,
5547,
2869,
1013,
2609,
1011,
2433,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.parsing;
import java.util.EnumSet;
import java.util.Set;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nullable;
import com.intellij.lang.ITokenTypeRemapper;
import com.intellij.lang.PsiBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.text.CharArrayUtil;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.LanguageLevel;
import com.jetbrains.python.psi.PyElementType;
/**
* @author yole
*/
public class StatementParsing extends Parsing implements ITokenTypeRemapper
{
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.parsing.StatementParsing");
@NonNls
protected static final String TOK_FUTURE_IMPORT = "__future__";
@NonNls
protected static final String TOK_WITH_STATEMENT = "with_statement";
@NonNls
protected static final String TOK_NESTED_SCOPES = "nested_scopes";
@NonNls
protected static final String TOK_PRINT_FUNCTION = "print_function";
@NonNls
protected static final String TOK_WITH = "with";
@NonNls
protected static final String TOK_AS = "as";
@NonNls
protected static final String TOK_PRINT = "print";
@NonNls
protected static final String TOK_NONE = "None";
@NonNls
protected static final String TOK_TRUE = "True";
@NonNls
protected static final String TOK_DEBUG = "__debug__";
@NonNls
protected static final String TOK_FALSE = "False";
@NonNls
protected static final String TOK_NONLOCAL = "nonlocal";
@NonNls
protected static final String TOK_EXEC = "exec";
@NonNls
protected static final String TOK_ASYNC = "async";
@NonNls
protected static final String TOK_AWAIT = "await";
private static final String EXPRESSION_EXPECTED = "Expression expected";
public static final String IDENTIFIER_EXPECTED = "Identifier expected";
protected enum Phase
{
NONE, FROM, FUTURE, IMPORT
} // 'from __future__ import' phase
private Phase myFutureImportPhase = Phase.NONE;
private boolean myExpectAsKeyword = false;
public enum FUTURE
{
ABSOLUTE_IMPORT, DIVISION, GENERATORS, NESTED_SCOPES, WITH_STATEMENT, PRINT_FUNCTION
}
protected Set<FUTURE> myFutureFlags = EnumSet.noneOf(FUTURE.class);
public static class ImportTypes
{
public final IElementType statement;
public final IElementType element;
public IElementType starElement;
public ImportTypes(IElementType statement, IElementType element, IElementType starElement)
{
this.statement = statement;
this.element = element;
this.starElement = starElement;
}
}
public StatementParsing(ParsingContext context, @Nullable FUTURE futureFlag)
{
super(context);
if(futureFlag != null)
{
myFutureFlags.add(futureFlag);
}
}
private void setExpectAsKeyword(boolean expectAsKeyword)
{
myExpectAsKeyword = expectAsKeyword;
myBuilder.setTokenTypeRemapper(this); // clear cached token type
}
public void parseStatement()
{
while(myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
myBuilder.advanceLexer();
}
final IElementType firstToken;
firstToken = myBuilder.getTokenType();
if(firstToken == null)
{
return;
}
if(firstToken == PyTokenTypes.WHILE_KEYWORD)
{
parseWhileStatement();
return;
}
if(firstToken == PyTokenTypes.IF_KEYWORD)
{
parseIfStatement(PyTokenTypes.IF_KEYWORD, PyTokenTypes.ELIF_KEYWORD, PyTokenTypes.ELSE_KEYWORD, PyElementTypes.IF_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.FOR_KEYWORD)
{
parseForStatement(myBuilder.mark());
return;
}
if(firstToken == PyTokenTypes.TRY_KEYWORD)
{
parseTryStatement();
return;
}
if(firstToken == PyTokenTypes.DEF_KEYWORD)
{
getFunctionParser().parseFunctionDeclaration(myBuilder.mark(), false);
return;
}
if(firstToken == PyTokenTypes.AT)
{
getFunctionParser().parseDecoratedDeclaration();
return;
}
if(firstToken == PyTokenTypes.CLASS_KEYWORD)
{
parseClassDeclaration();
return;
}
if(firstToken == PyTokenTypes.WITH_KEYWORD)
{
parseWithStatement(myBuilder.mark());
return;
}
if(firstToken == PyTokenTypes.ASYNC_KEYWORD)
{
parseAsyncStatement();
return;
}
parseSimpleStatement();
}
protected void parseSimpleStatement()
{
PsiBuilder builder = myContext.getBuilder();
final IElementType firstToken = builder.getTokenType();
if(firstToken == null)
{
return;
}
if(firstToken == PyTokenTypes.PRINT_KEYWORD && hasPrintStatement())
{
parsePrintStatement(builder);
return;
}
if(firstToken == PyTokenTypes.ASSERT_KEYWORD)
{
parseAssertStatement();
return;
}
if(firstToken == PyTokenTypes.BREAK_KEYWORD)
{
parseKeywordStatement(builder, PyElementTypes.BREAK_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.CONTINUE_KEYWORD)
{
parseKeywordStatement(builder, PyElementTypes.CONTINUE_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.DEL_KEYWORD)
{
parseDelStatement();
return;
}
if(firstToken == PyTokenTypes.EXEC_KEYWORD)
{
parseExecStatement();
return;
}
if(firstToken == PyTokenTypes.GLOBAL_KEYWORD)
{
parseNameDefiningStatement(PyElementTypes.GLOBAL_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.NONLOCAL_KEYWORD)
{
parseNameDefiningStatement(PyElementTypes.NONLOCAL_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.IMPORT_KEYWORD)
{
parseImportStatement(PyElementTypes.IMPORT_STATEMENT, PyElementTypes.IMPORT_ELEMENT);
return;
}
if(firstToken == PyTokenTypes.FROM_KEYWORD)
{
parseFromImportStatement();
return;
}
if(firstToken == PyTokenTypes.PASS_KEYWORD)
{
parseKeywordStatement(builder, PyElementTypes.PASS_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.RETURN_KEYWORD)
{
parseReturnStatement(builder);
return;
}
if(firstToken == PyTokenTypes.RAISE_KEYWORD)
{
parseRaiseStatement();
return;
}
PsiBuilder.Marker exprStatement = builder.mark();
if(builder.getTokenType() == PyTokenTypes.YIELD_KEYWORD)
{
getExpressionParser().parseYieldOrTupleExpression(false);
checkEndOfStatement();
exprStatement.done(PyElementTypes.EXPRESSION_STATEMENT);
return;
}
else if(getExpressionParser().parseExpressionOptional())
{
IElementType statementType = PyElementTypes.EXPRESSION_STATEMENT;
if(PyTokenTypes.AUG_ASSIGN_OPERATIONS.contains(builder.getTokenType()))
{
statementType = PyElementTypes.AUG_ASSIGNMENT_STATEMENT;
builder.advanceLexer();
if(!getExpressionParser().parseYieldOrTupleExpression(false))
{
builder.error(EXPRESSION_EXPECTED);
}
}
else if(atToken(PyTokenTypes.EQ) || (atToken(PyTokenTypes.COLON) && myContext.getLanguageLevel().isPy3K()))
{
exprStatement.rollbackTo();
exprStatement = builder.mark();
getExpressionParser().parseExpression(false, true);
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.EQ || builder.getTokenType() == PyTokenTypes.COLON, builder.getTokenType());
if(builder.getTokenType() == PyTokenTypes.COLON)
{
statementType = PyElementTypes.TYPE_DECLARATION_STATEMENT;
getFunctionParser().parseParameterAnnotation();
}
if(builder.getTokenType() == PyTokenTypes.EQ)
{
statementType = PyElementTypes.ASSIGNMENT_STATEMENT;
builder.advanceLexer();
while(true)
{
PsiBuilder.Marker maybeExprMarker = builder.mark();
final boolean isYieldExpr = builder.getTokenType() == PyTokenTypes.YIELD_KEYWORD;
if(!getExpressionParser().parseYieldOrTupleExpression(false))
{
maybeExprMarker.drop();
builder.error(EXPRESSION_EXPECTED);
break;
}
if(builder.getTokenType() == PyTokenTypes.EQ)
{
if(isYieldExpr)
{
maybeExprMarker.drop();
builder.error("Cannot assign to 'yield' expression");
}
else
{
maybeExprMarker.rollbackTo();
getExpressionParser().parseExpression(false, true);
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.EQ, builder.getTokenType());
}
builder.advanceLexer();
}
else
{
maybeExprMarker.drop();
break;
}
}
}
}
checkEndOfStatement();
exprStatement.done(statementType);
return;
}
else
{
exprStatement.drop();
}
builder.advanceLexer();
reportParseStatementError(builder, firstToken);
}
protected void reportParseStatementError(PsiBuilder builder, IElementType firstToken)
{
if(firstToken == PyTokenTypes.INCONSISTENT_DEDENT)
{
builder.error("Unindent does not match any outer indentation level");
}
else if(firstToken == PyTokenTypes.INDENT)
{
builder.error("Unexpected indent");
}
else
{
builder.error("Statement expected, found " + firstToken.toString());
}
}
private boolean hasPrintStatement()
{
return myContext.getLanguageLevel().hasPrintStatement() && !myFutureFlags.contains(FUTURE.PRINT_FUNCTION);
}
protected void checkEndOfStatement()
{
PsiBuilder builder = myContext.getBuilder();
final ParsingScope scope = getParsingContext().getScope();
if(builder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
builder.advanceLexer();
scope.setAfterSemicolon(false);
}
else if(builder.getTokenType() == PyTokenTypes.SEMICOLON)
{
if(!scope.isSuite())
{
builder.advanceLexer();
scope.setAfterSemicolon(true);
if(builder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
builder.advanceLexer();
scope.setAfterSemicolon(false);
}
}
}
else if(!builder.eof())
{
builder.error("End of statement expected");
}
}
private void parsePrintStatement(final PsiBuilder builder)
{
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.PRINT_KEYWORD);
final PsiBuilder.Marker statement = builder.mark();
builder.advanceLexer();
if(builder.getTokenType() == PyTokenTypes.GTGT)
{
final PsiBuilder.Marker target = builder.mark();
builder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
target.done(PyElementTypes.PRINT_TARGET);
}
else
{
getExpressionParser().parseSingleExpression(false);
}
while(builder.getTokenType() == PyTokenTypes.COMMA)
{
builder.advanceLexer();
if(getEndOfStatementsTokens().contains(builder.getTokenType()))
{
break;
}
getExpressionParser().parseSingleExpression(false);
}
checkEndOfStatement();
statement.done(PyElementTypes.PRINT_STATEMENT);
}
protected void parseKeywordStatement(PsiBuilder builder, IElementType statementType)
{
final PsiBuilder.Marker statement = builder.mark();
builder.advanceLexer();
checkEndOfStatement();
statement.done(statementType);
}
private void parseReturnStatement(PsiBuilder builder)
{
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.RETURN_KEYWORD);
final PsiBuilder.Marker returnStatement = builder.mark();
builder.advanceLexer();
if(builder.getTokenType() != null && !getEndOfStatementsTokens().contains(builder.getTokenType()))
{
getExpressionParser().parseExpression();
}
checkEndOfStatement();
returnStatement.done(PyElementTypes.RETURN_STATEMENT);
}
private void parseDelStatement()
{
assertCurrentToken(PyTokenTypes.DEL_KEYWORD);
final PsiBuilder.Marker delStatement = myBuilder.mark();
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("Expression expected");
}
while(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
if(!getEndOfStatementsTokens().contains(myBuilder.getTokenType()))
{
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("Expression expected");
}
}
}
checkEndOfStatement();
delStatement.done(PyElementTypes.DEL_STATEMENT);
}
private void parseRaiseStatement()
{
assertCurrentToken(PyTokenTypes.RAISE_KEYWORD);
final PsiBuilder.Marker raiseStatement = myBuilder.mark();
myBuilder.advanceLexer();
if(!getEndOfStatementsTokens().contains(myBuilder.getTokenType()))
{
getExpressionParser().parseSingleExpression(false);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
}
}
else if(myBuilder.getTokenType() == PyTokenTypes.FROM_KEYWORD)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("Expression expected");
}
}
}
checkEndOfStatement();
raiseStatement.done(PyElementTypes.RAISE_STATEMENT);
}
private void parseAssertStatement()
{
assertCurrentToken(PyTokenTypes.ASSERT_KEYWORD);
final PsiBuilder.Marker assertStatement = myBuilder.mark();
myBuilder.advanceLexer();
if(getExpressionParser().parseSingleExpression(false))
{
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myContext.getBuilder().error(EXPRESSION_EXPECTED);
}
}
checkEndOfStatement();
}
else
{
myContext.getBuilder().error(EXPRESSION_EXPECTED);
}
assertStatement.done(PyElementTypes.ASSERT_STATEMENT);
}
protected void parseImportStatement(IElementType statementType, IElementType elementType)
{
final PsiBuilder builder = myContext.getBuilder();
final PsiBuilder.Marker importStatement = builder.mark();
builder.advanceLexer();
parseImportElements(elementType, true, false, false);
checkEndOfStatement();
importStatement.done(statementType);
}
/*
Really parses two forms:
from identifier import id, id... -- may be either relative or absolute
from . import identifier -- only relative
*/
private void parseFromImportStatement()
{
PsiBuilder builder = myContext.getBuilder();
assertCurrentToken(PyTokenTypes.FROM_KEYWORD);
myFutureImportPhase = Phase.FROM;
final PsiBuilder.Marker fromImportStatement = builder.mark();
builder.advanceLexer();
boolean from_future = false;
boolean had_dots = parseRelativeImportDots();
IElementType statementType = PyElementTypes.FROM_IMPORT_STATEMENT;
if(had_dots && parseOptionalDottedName() || parseDottedName())
{
final ImportTypes types = checkFromImportKeyword();
statementType = types.statement;
final IElementType elementType = types.element;
if(myFutureImportPhase == Phase.FUTURE)
{
myFutureImportPhase = Phase.IMPORT;
from_future = true;
}
if(builder.getTokenType() == PyTokenTypes.MULT)
{
final PsiBuilder.Marker star_import_mark = builder.mark();
builder.advanceLexer();
star_import_mark.done(types.starElement);
}
else if(builder.getTokenType() == PyTokenTypes.LPAR)
{
builder.advanceLexer();
parseImportElements(elementType, false, true, from_future);
checkMatches(PyTokenTypes.RPAR, ") expected");
}
else
{
parseImportElements(elementType, false, false, from_future);
}
}
else if(had_dots)
{ // from . import ...
final ImportTypes types = checkFromImportKeyword();
statementType = types.statement;
parseImportElements(types.element, false, false, from_future);
}
checkEndOfStatement();
fromImportStatement.done(statementType);
myFutureImportPhase = Phase.NONE;
}
protected ImportTypes checkFromImportKeyword()
{
checkMatches(PyTokenTypes.IMPORT_KEYWORD, "'import' expected");
return new ImportTypes(PyElementTypes.FROM_IMPORT_STATEMENT, PyElementTypes.IMPORT_ELEMENT, PyElementTypes.STAR_IMPORT_ELEMENT);
}
/**
* Parses option dots before imported name.
*
* @return true iff there were dots.
*/
private boolean parseRelativeImportDots()
{
PsiBuilder builder = myContext.getBuilder();
boolean had_dots = false;
while(builder.getTokenType() == PyTokenTypes.DOT)
{
had_dots = true;
builder.advanceLexer();
}
return had_dots;
}
private void parseImportElements(IElementType elementType, boolean is_module_import, boolean in_parens, final boolean from_future)
{
PsiBuilder builder = myContext.getBuilder();
while(true)
{
final PsiBuilder.Marker asMarker = builder.mark();
if(is_module_import)
{ // import _
if(!parseDottedNameAsAware(true, false))
{
asMarker.drop();
break;
}
}
else
{ // from X import _
String token_text = parseIdentifier(getReferenceType());
if(from_future)
{
// TODO: mark all known future feature names
if(TOK_WITH_STATEMENT.equals(token_text))
{
myFutureFlags.add(FUTURE.WITH_STATEMENT);
}
else if(TOK_NESTED_SCOPES.equals(token_text))
{
myFutureFlags.add(FUTURE.NESTED_SCOPES);
}
else if(TOK_PRINT_FUNCTION.equals(token_text))
{
myFutureFlags.add(FUTURE.PRINT_FUNCTION);
}
}
}
setExpectAsKeyword(true); // possible 'as' comes as an ident; reparse it as keyword if found
if(builder.getTokenType() == PyTokenTypes.AS_KEYWORD)
{
builder.advanceLexer();
setExpectAsKeyword(false);
parseIdentifier(PyElementTypes.TARGET_EXPRESSION);
}
asMarker.done(elementType);
setExpectAsKeyword(false);
if(builder.getTokenType() == PyTokenTypes.COMMA)
{
builder.advanceLexer();
if(in_parens && builder.getTokenType() == PyTokenTypes.RPAR)
{
break;
}
}
else
{
break;
}
}
}
@Nullable
private String parseIdentifier(final IElementType elementType)
{
final PsiBuilder.Marker idMarker = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.IDENTIFIER)
{
String id_text = myBuilder.getTokenText();
myBuilder.advanceLexer();
idMarker.done(elementType);
return id_text;
}
else
{
myBuilder.error(IDENTIFIER_EXPECTED);
idMarker.drop();
}
return null;
}
public boolean parseOptionalDottedName()
{
return parseDottedNameAsAware(false, true);
}
public boolean parseDottedName()
{
return parseDottedNameAsAware(false, false);
}
// true if identifier was parsed or skipped as optional, false on error
protected boolean parseDottedNameAsAware(boolean expect_as, boolean optional)
{
if(myBuilder.getTokenType() != PyTokenTypes.IDENTIFIER)
{
if(optional)
{
return true;
}
myBuilder.error(IDENTIFIER_EXPECTED);
return false;
}
PsiBuilder.Marker marker = myBuilder.mark();
myBuilder.advanceLexer();
marker.done(getReferenceType());
boolean old_expect_AS_kwd = myExpectAsKeyword;
setExpectAsKeyword(expect_as);
while(myBuilder.getTokenType() == PyTokenTypes.DOT)
{
marker = marker.precede();
myBuilder.advanceLexer();
checkMatches(PyTokenTypes.IDENTIFIER, IDENTIFIER_EXPECTED);
marker.done(getReferenceType());
}
setExpectAsKeyword(old_expect_AS_kwd);
return true;
}
private void parseNameDefiningStatement(final PyElementType elementType)
{
final PsiBuilder.Marker globalStatement = myBuilder.mark();
myBuilder.advanceLexer();
parseIdentifier(PyElementTypes.TARGET_EXPRESSION);
while(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
parseIdentifier(PyElementTypes.TARGET_EXPRESSION);
}
checkEndOfStatement();
globalStatement.done(elementType);
}
private void parseExecStatement()
{
assertCurrentToken(PyTokenTypes.EXEC_KEYWORD);
final PsiBuilder.Marker execStatement = myBuilder.mark();
myBuilder.advanceLexer();
getExpressionParser().parseExpression(true, false);
if(myBuilder.getTokenType() == PyTokenTypes.IN_KEYWORD)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
}
}
checkEndOfStatement();
execStatement.done(PyElementTypes.EXEC_STATEMENT);
}
protected void parseIfStatement(PyElementType ifKeyword, PyElementType elifKeyword, PyElementType elseKeyword, PyElementType elementType)
{
assertCurrentToken(ifKeyword);
final PsiBuilder.Marker ifStatement = myBuilder.mark();
final PsiBuilder.Marker ifPart = myBuilder.mark();
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("expression expected");
}
parseColonAndSuite();
ifPart.done(PyElementTypes.IF_PART_IF);
PsiBuilder.Marker elifPart = myBuilder.mark();
while(myBuilder.getTokenType() == elifKeyword)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("expression expected");
}
parseColonAndSuite();
elifPart.done(PyElementTypes.IF_PART_ELIF);
elifPart = myBuilder.mark();
}
elifPart.drop(); // we always kept an open extra elif
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == elseKeyword)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
ifStatement.done(elementType);
}
private boolean expectColon()
{
if(myBuilder.getTokenType() == PyTokenTypes.COLON)
{
myBuilder.advanceLexer();
return true;
}
else if(myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
myBuilder.error("Colon expected");
return true;
}
final PsiBuilder.Marker marker = myBuilder.mark();
while(!atAnyOfTokens(null, PyTokenTypes.DEDENT, PyTokenTypes.STATEMENT_BREAK, PyTokenTypes.COLON))
{
myBuilder.advanceLexer();
}
boolean result = matchToken(PyTokenTypes.COLON);
if(!result && atToken(PyTokenTypes.STATEMENT_BREAK))
{
myBuilder.advanceLexer();
}
marker.error("Colon expected");
return result;
}
private void parseForStatement(PsiBuilder.Marker endMarker)
{
assertCurrentToken(PyTokenTypes.FOR_KEYWORD);
parseForPart();
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.ELSE_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
endMarker.done(PyElementTypes.FOR_STATEMENT);
}
protected void parseForPart()
{
final PsiBuilder.Marker forPart = myBuilder.mark();
myBuilder.advanceLexer();
getExpressionParser().parseExpression(true, true);
checkMatches(PyTokenTypes.IN_KEYWORD, "'in' expected");
getExpressionParser().parseExpression();
parseColonAndSuite();
forPart.done(PyElementTypes.FOR_PART);
}
private void parseWhileStatement()
{
assertCurrentToken(PyTokenTypes.WHILE_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
final PsiBuilder.Marker whilePart = myBuilder.mark();
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error(EXPRESSION_EXPECTED);
}
parseColonAndSuite();
whilePart.done(PyElementTypes.WHILE_PART);
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.ELSE_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
statement.done(PyElementTypes.WHILE_STATEMENT);
}
private void parseTryStatement()
{
assertCurrentToken(PyTokenTypes.TRY_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
final PsiBuilder.Marker tryPart = myBuilder.mark();
myBuilder.advanceLexer();
parseColonAndSuite();
tryPart.done(PyElementTypes.TRY_PART);
boolean haveExceptClause = false;
if(myBuilder.getTokenType() == PyTokenTypes.EXCEPT_KEYWORD)
{
haveExceptClause = true;
while(myBuilder.getTokenType() == PyTokenTypes.EXCEPT_KEYWORD)
{
final PsiBuilder.Marker exceptBlock = myBuilder.mark();
myBuilder.advanceLexer();
if(myBuilder.getTokenType() != PyTokenTypes.COLON)
{
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error(EXPRESSION_EXPECTED);
}
setExpectAsKeyword(true);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA || myBuilder.getTokenType() == PyTokenTypes.AS_KEYWORD)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(true))
{
myBuilder.error(EXPRESSION_EXPECTED);
}
}
}
parseColonAndSuite();
exceptBlock.done(PyElementTypes.EXCEPT_PART);
}
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.ELSE_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
}
final PsiBuilder.Marker finallyPart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.FINALLY_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
finallyPart.done(PyElementTypes.FINALLY_PART);
}
else
{
finallyPart.drop();
if(!haveExceptClause)
{
myBuilder.error("'except' or 'finally' expected");
// much better to have a statement of incorrectly determined type
// than "TRY" and "COLON" tokens attached to nothing
}
}
statement.done(PyElementTypes.TRY_EXCEPT_STATEMENT);
}
private void parseColonAndSuite()
{
if(expectColon())
{
parseSuite();
}
else
{
final PsiBuilder.Marker mark = myBuilder.mark();
mark.done(PyElementTypes.STATEMENT_LIST);
}
}
private void parseWithStatement(PsiBuilder.Marker endMarker)
{
assertCurrentToken(PyTokenTypes.WITH_KEYWORD);
myBuilder.advanceLexer();
while(true)
{
PsiBuilder.Marker withItem = myBuilder.mark();
getExpressionParser().parseExpression();
setExpectAsKeyword(true);
if(myBuilder.getTokenType() == PyTokenTypes.AS_KEYWORD)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(true))
{
myBuilder.error("Identifier expected");
// 'as' is followed by a target
}
}
withItem.done(PyElementTypes.WITH_ITEM);
if(!matchToken(PyTokenTypes.COMMA))
{
break;
}
}
parseColonAndSuite();
endMarker.done(PyElementTypes.WITH_STATEMENT);
}
private void parseClassDeclaration()
{
final PsiBuilder.Marker classMarker = myBuilder.mark();
parseClassDeclaration(classMarker);
}
public void parseClassDeclaration(PsiBuilder.Marker classMarker)
{
assertCurrentToken(PyTokenTypes.CLASS_KEYWORD);
myBuilder.advanceLexer();
parseIdentifierOrSkip(PyTokenTypes.LPAR, PyTokenTypes.COLON);
if(myBuilder.getTokenType() == PyTokenTypes.LPAR)
{
getExpressionParser().parseArgumentList();
}
else
{
final PsiBuilder.Marker inheritMarker = myBuilder.mark();
inheritMarker.done(PyElementTypes.ARGUMENT_LIST);
}
final ParsingContext context = getParsingContext();
context.pushScope(context.getScope().withClass());
parseColonAndSuite();
context.popScope();
classMarker.done(PyElementTypes.CLASS_DECLARATION);
}
private void parseAsyncStatement()
{
assertCurrentToken(PyTokenTypes.ASYNC_KEYWORD);
final PsiBuilder.Marker marker = myBuilder.mark();
myBuilder.advanceLexer();
final IElementType token = myBuilder.getTokenType();
if(token == PyTokenTypes.DEF_KEYWORD)
{
getFunctionParser().parseFunctionDeclaration(marker, true);
}
else if(token == PyTokenTypes.WITH_KEYWORD)
{
parseWithStatement(marker);
}
else if(token == PyTokenTypes.FOR_KEYWORD)
{
parseForStatement(marker);
}
else
{
marker.drop();
myBuilder.error("'def' or 'with' or 'for' expected");
}
}
public void parseSuite()
{
parseSuite(null, null);
}
public void parseSuite(@Nullable PsiBuilder.Marker endMarker, @Nullable IElementType elType)
{
if(myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
myBuilder.advanceLexer();
final PsiBuilder.Marker marker = myBuilder.mark();
final boolean indentFound = myBuilder.getTokenType() == PyTokenTypes.INDENT;
if(indentFound)
{
myBuilder.advanceLexer();
if(myBuilder.eof())
{
myBuilder.error("Indented block expected");
}
else
{
while(!myBuilder.eof() && myBuilder.getTokenType() != PyTokenTypes.DEDENT)
{
parseStatement();
}
}
}
else
{
myBuilder.error("Indent expected");
}
marker.done(PyElementTypes.STATEMENT_LIST);
marker.setCustomEdgeTokenBinders(LeadingCommentsBinder.INSTANCE, FollowingCommentBinder.INSTANCE);
if(endMarker != null)
{
endMarker.done(elType);
}
if(indentFound && !myBuilder.eof())
{
checkMatches(PyTokenTypes.DEDENT, "Dedent expected");
}
}
else
{
final PsiBuilder.Marker marker = myBuilder.mark();
if(myBuilder.eof())
{
myBuilder.error("Statement expected");
}
else
{
final ParsingContext context = getParsingContext();
context.pushScope(context.getScope().withSuite());
parseSimpleStatement();
context.popScope();
while(matchToken(PyTokenTypes.SEMICOLON))
{
if(matchToken(PyTokenTypes.STATEMENT_BREAK))
{
break;
}
context.pushScope(context.getScope().withSuite());
parseSimpleStatement();
context.popScope();
}
}
marker.done(PyElementTypes.STATEMENT_LIST);
if(endMarker != null)
{
endMarker.done(elType);
}
}
}
public IElementType filter(final IElementType source, final int start, final int end, final CharSequence text)
{
if((myExpectAsKeyword || myContext.getLanguageLevel().hasWithStatement()) &&
source == PyTokenTypes.IDENTIFIER && isWordAtPosition(text, start, end, TOK_AS))
{
return PyTokenTypes.AS_KEYWORD;
}
else if( // filter
(myFutureImportPhase == Phase.FROM) &&
source == PyTokenTypes.IDENTIFIER &&
isWordAtPosition(text, start, end, TOK_FUTURE_IMPORT))
{
myFutureImportPhase = Phase.FUTURE;
return source;
}
else if(hasWithStatement() &&
source == PyTokenTypes.IDENTIFIER &&
isWordAtPosition(text, start, end, TOK_WITH))
{
return PyTokenTypes.WITH_KEYWORD;
}
else if(hasPrintStatement() && source == PyTokenTypes.IDENTIFIER &&
isWordAtPosition(text, start, end, TOK_PRINT))
{
return PyTokenTypes.PRINT_KEYWORD;
}
else if(myContext.getLanguageLevel().isPy3K() && source == PyTokenTypes.IDENTIFIER)
{
if(isWordAtPosition(text, start, end, TOK_NONE))
{
return PyTokenTypes.NONE_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_TRUE))
{
return PyTokenTypes.TRUE_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_FALSE))
{
return PyTokenTypes.FALSE_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_DEBUG))
{
return PyTokenTypes.DEBUG_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_NONLOCAL))
{
return PyTokenTypes.NONLOCAL_KEYWORD;
}
if(myContext.getLanguageLevel().isAtLeast(LanguageLevel.PYTHON35))
{
if(isWordAtPosition(text, start, end, TOK_ASYNC))
{
if(myContext.getScope().isAsync() || myBuilder.lookAhead(1) == PyTokenTypes.DEF_KEYWORD)
{
return PyTokenTypes.ASYNC_KEYWORD;
}
}
if(isWordAtPosition(text, start, end, TOK_AWAIT))
{
if(myContext.getScope().isAsync())
{
return PyTokenTypes.AWAIT_KEYWORD;
}
}
}
}
else if(!myContext.getLanguageLevel().isPy3K() && source == PyTokenTypes.IDENTIFIER)
{
if(isWordAtPosition(text, start, end, TOK_EXEC))
{
return PyTokenTypes.EXEC_KEYWORD;
}
}
return source;
}
protected TokenSet getEndOfStatementsTokens()
{
return PyTokenTypes.END_OF_STATEMENT;
}
private static boolean isWordAtPosition(CharSequence text, int start, int end, final String tokenText)
{
return CharArrayUtil.regionMatches(text, start, end, tokenText) && end - start == tokenText.length();
}
private boolean hasWithStatement()
{
return myContext.getLanguageLevel().hasWithStatement() || myFutureFlags.contains(FUTURE.WITH_STATEMENT);
}
}
| consulo/consulo-python | python-impl/src/main/java/com/jetbrains/python/parsing/StatementParsing.java | Java | apache-2.0 | 32,571 | [
30522,
1013,
1008,
1008,
9385,
2456,
1011,
2355,
6892,
10024,
7076,
1055,
1012,
1054,
1012,
1051,
1012,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Walsura lanceolata Wall. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Meliaceae/Walsura/Walsura lanceolata/README.md | Markdown | apache-2.0 | 174 | [
30522,
1001,
24547,
26210,
2050,
9993,
6030,
2696,
2813,
1012,
2427,
1001,
1001,
1001,
1001,
3570,
3970,
1001,
1001,
1001,
1001,
2429,
2000,
2248,
3269,
3415,
5950,
1001,
1001,
1001,
1001,
2405,
1999,
19701,
1001,
1001,
1001,
1001,
2434,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Pluralsight React Components
A library of React components created in "Creating Reusable React Components" on Pluralsight.
## Install
```
npm install ps-react-dr
```
## Issues
I'll add tips for common problems and address any known course issues here.
## Docs
[Component documentation](http://dryzhkov.github.io/ps-react-dr) | dryzhkov/ps-react-dr | README.md | Markdown | mit | 330 | [
30522,
1001,
13994,
25807,
10509,
6177,
1037,
3075,
1997,
10509,
6177,
2580,
1999,
1000,
4526,
2128,
10383,
3468,
10509,
6177,
1000,
2006,
13994,
25807,
1012,
1001,
1001,
16500,
1036,
1036,
1036,
27937,
2213,
16500,
8827,
1011,
10509,
1011,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
class Shopware_Controllers_Api_Translations extends Shopware_Controllers_Api_Rest
{
/**
* @var \Shopware\Components\Api\Resource\Translation
*/
protected $resource = null;
public function init()
{
$this->resource = \Shopware\Components\Api\Manager::getResource('translation');
}
public function preDispatch()
{
parent::preDispatch();
// We still support the old behavior
$request = $this->Request();
$localeId = $request->getPost('localeId');
if ($localeId !== null) {
$request->setPost('shopId', $localeId);
$request->setPost('localeId', null);
}
}
/**
* Get list of translations
*
* GET /api/translations/
*/
public function indexAction()
{
$limit = (int) $this->Request()->getParam('limit', 1000);
$offset = (int) $this->Request()->getParam('start', 0);
$sort = $this->Request()->getParam('sort', []);
$filter = $this->Request()->getParam('filter', []);
$result = $this->resource->getList($offset, $limit, $filter, $sort);
$this->View()->assign($result);
$this->View()->assign('success', true);
}
/**
* Create new translation
*
* POST /api/translations
*/
public function postAction()
{
$useNumberAsId = (bool) $this->Request()->getParam('useNumberAsId', 0);
$params = $this->Request()->getPost();
if ($useNumberAsId) {
$translation = $this->resource->createByNumber($params);
} else {
$translation = $this->resource->create($params);
}
$location = $this->apiBaseUrl . 'translations/' . $translation->getId();
$data = [
'id' => $translation->getId(),
'location' => $location,
];
$this->View()->assign(['success' => true, 'data' => $data]);
$this->Response()->setHeader('Location', $location);
}
/**
* Update translation
*
* PUT /api/translations/{id}
*/
public function putAction()
{
$useNumberAsId = (bool) $this->Request()->getParam('useNumberAsId', 0);
$id = $this->Request()->getParam('id');
$params = $this->Request()->getPost();
if ($useNumberAsId) {
$translation = $this->resource->updateByNumber($id, $params);
} else {
$translation = $this->resource->update($id, $params);
}
$location = $this->apiBaseUrl . 'translations/' . $translation->getId();
$data = [
'id' => $translation->getId(),
'location' => $location,
];
$this->View()->assign(['success' => true, 'data' => $data]);
}
/**
* Delete translation
*
* DELETE /api/translation/{id}
*/
public function deleteAction()
{
$id = $this->Request()->getParam('id');
$data = $this->Request()->getParams();
$useNumberAsId = (bool) $this->Request()->getParam('useNumberAsId', 0);
if ($useNumberAsId) {
$this->resource->deleteByNumber($id, $data);
} else {
$this->resource->delete($id, $data);
}
$this->View()->assign(['success' => true]);
}
}
| wlwwt/shopware | engine/Shopware/Controllers/Api/Translations.php | PHP | agpl-3.0 | 4,215 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
4497,
8059,
1019,
1008,
9385,
1006,
1039,
1007,
4497,
8059,
12943,
1008,
1008,
2429,
2000,
2256,
7037,
13202,
2944,
1010,
2023,
2565,
2064,
2022,
2109,
2593,
1008,
2104,
1996,
3408,
1997,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html data-require="math">
<head>
<title>Algorithm Analysis Exercise: Big Theta</title>
<script src="../../lib/jquery.min.js"></script>
<script src="../../lib/jquery-ui.min.js"></script>
<script src="../../ODSAkhan-exercises/khan-exercise.js"></script>
</head>
<body>
<div class="exercise">
<div class="problems">
<div id="problem-type-or-description">
<p class="problem">Answer TRUE or FALSE.</p>
<p class="question">
It is correct to say that, the upper bound and lower bounds of the sequencial search algorithm is in
<code>O(n)</code> and <code>\Theta(n)</code> respectively.
</p>
<div class="solution"><var>"False"</var></div>
<ul class="choices" data-category="true">
<li><var>"True"</var></li>
<li><var>"False"</var></li>
</ul>
<div class="hints">
<p>Is this statement complete?</p>
<p>To make this statement correct, you need to add in which case you are measuring the lower and upper bounds</p>
</div>
</div>
</div>
</div>
</body>
</html>
| hosamshahin/OpenDSA | Exercises/AlgAnalTest/MisunderstandingsTF2.html | HTML | mit | 1,108 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
2951,
1011,
5478,
1027,
1000,
8785,
1000,
1028,
1026,
2132,
1028,
1026,
2516,
1028,
9896,
4106,
6912,
1024,
2502,
23963,
1026,
1013,
2516,
1028,
1026,
5896,
5034,
2278,
1027,
1000,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.