code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
var MockServer = require('../../../lib/mockserver.js');
var assert = require('assert');
var Nightwatch = require('../../../lib/nightwatch.js');
var MochaTest = require('../../../lib/mochatest.js');
module.exports = MochaTest.add('waitForElementNotVisible', {
afterEach : function() {
MockServer.removeMock({
url : '/wd/hub/session/1352110219202/element/0/displayed',
method:'GET'
});
},
'client.waitForElementNotVisible() success' : function(done) {
var client = Nightwatch.client();
var api = Nightwatch.api();
var assertion = [];
MockServer.addMock({
url : '/wd/hub/session/1352110219202/element/0/displayed',
method:'GET',
response : JSON.stringify({
sessionId: '1352110219202',
status:0,
value : false
})
});
client.assertion = function(result, actual, expected, msg, abortObFailure) {
Array.prototype.unshift.apply(assertion, arguments);
};
api.globals.abortOnAssertionFailure = false;
api.waitForElementNotVisible('#weblogin', 110, 50, function callback(result, instance) {
assert.equal(assertion[0], true);
assert.equal(assertion[4], false);
done();
});
Nightwatch.start();
},
'client.waitForElementNotVisible() failure' : function(done) {
var client = Nightwatch.client();
var api = Nightwatch.api();
var assertion = [];
MockServer.addMock({
url : '/wd/hub/session/1352110219202/element/0/displayed',
method:'GET',
response : JSON.stringify({
sessionId: '1352110219202',
status:0,
value : true
})
});
api.globals.abortOnAssertionFailure = true;
client.assertion = function(result, actual, expected, msg, abortObFailure) {
Array.prototype.unshift.apply(assertion, arguments);
};
api.waitForElementNotVisible('#weblogin', 15, 10, function callback(result) {
assert.equal(assertion[0], false);
assert.equal(assertion[1], 'visible');
assert.equal(assertion[2], 'not visible');
assert.equal(assertion[3], 'Timed out while waiting for element <#weblogin> to not be visible for 15 milliseconds.');
assert.equal(assertion[4], true); // abortOnFailure
assert.equal(result.status, 0);
done();
});
Nightwatch.start();
}
});
| varmasingh/Night-watch | test/src/api/commands/testWaitForElementNotVisible.js | JavaScript | mit | 2,402 |
from pyswagger import App
from ..utils import get_test_data_folder
import unittest
class BitBucketTestCase(unittest.TestCase):
""" test for bitbucket related """
@classmethod
def setUpClass(kls):
kls.app = App.load(get_test_data_folder(
version='2.0',
which='bitbucket'
))
# bypass cyclic testing
kls.app.prepare(strict=False)
def test_load(self):
# make sure loading is fine,
# this test case could be removed when something else exists in this suite.
pass
| mission-liao/pyswagger | pyswagger/tests/v2_0/test_bitbucket.py | Python | mit | 559 |
Normalize for stylus
| exdeniz/normalize-stylus | readme.md | Markdown | mit | 21 |
#! /bin/bash
SYSTEMCTL="`which systemctl`"
IPERF_VERSION="2.0.9"
if [ -n "`which yum`" ]
then
sudo yum -y install docker
elif [ -n "`which apt-get`" ]
then
sudo apt-get update
sudo apt-get install docker
fi
if [ ! -f "/usr/local/bin/docker-compose" ]
then
curl -L https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m` -o docker-compose
sudo mv -f docker-compose /usr/local/bin/docker-compose
sudo chmod 755 /usr/local/bin/docker-compose
fi
if [ ! -d "/data" ]
then
sudo mkdir -p /data
sudo chown `whoami` /data
fi
for i in tcp udp
do
for p in `seq 5001 5005`
do
mkdir -p /data/iperf-server-${i}-${p}
curl -o /data/iperf-server-${i}-${p}/docker-compose.yml https://raw.githubusercontent.com/iitggithub/iperf-server/master/docker-compose.yml.single-use || {
echo "Failed to download single use service file. Installation halted..."
rm -f /data/iperf-server-${i}-${p}/docker-compose.yml
exit 1
}
sed -i -e "s/ - \".*/ - \"${p}:${p}\/${i}\"/" \
-e "s/latest/${IPERF_VERSION}/" /data/iperf-server-${i}-${p}/docker-compose.yml
done
done
mkdir -p /data/iperf-web
curl -o /data/iperf-web/docker-compose.yml https://raw.githubusercontent.com/iitggithub/iperf-web/master/docker-compose.yml
if [ -n "${SYSTEMCTL}" ]
then
sudo ${SYSTEMCTL} start docker
sudo ${SYSTEMCTL} enable docker
for i in tcp udp
do
for p in `seq 5001 5005`
do
sudo curl -o /usr/lib/systemd/system/docker-iperf-server-${i}-${p}.service https://raw.githubusercontent.com/iitggithub/iperf-server/${IPERF_VERSION}/docker-iperf-server.service
sudo sed -i "s/iperf-server/iperf-server-${i}-${p}/" /usr/lib/systemd/system/docker-iperf-server-${i}-${p}.service
done
done
sudo ${SYSTEMCTL} daemon-reload
for i in tcp udp
do
for p in `seq 5001 5005`
do
sudo ${SYSTEMCTL} start docker-iperf-server-${i}-${p}
sudo ${SYSTEMCTL} enable docker-iperf-server-${i}-${p}
done
done
curl -o /usr/lib/systemd/system/docker-iperf-web.service https://raw.githubusercontent.com/iitggithub/iperf-web/master/docker-iperf-web.service
sudo ${SYSTEMCTL} daemon-reload
sudo ${SYSTEMCTL} start docker-iperf-web
sudo ${SYSTEMCTL} enable docker-iperf-web
else
sudo /etc/init.d/docker start
sudo chkconfig docker on
echo "for i in tcp udp; do for p in `seq 5001 5005`; do cd /data/iperf-server-${i}-${p} && /usr/local/bin/docker-compose up -d; done; done" >>/etc/rc.local
echo "cd /data/iperf-web && /usr/local/bin/docker-compose up -d" >>/etc/rc.local
for i in tcp udp; do for p in `seq 5001 5005`; do cd /data/iperf-server-${i}-${p} && sudo /usr/local/bin/docker-compose up -d; done; done
cd /data/iperf-web && sudo /usr/local/bin/docker-compose up -d
fi
| iitggithub/iperf-web | install.sh | Shell | mit | 2,815 |
using System;
using System.Collections.Concurrent;
namespace Ritter.Infra.Crosscutting.Validations
{
public class ValidationContextCache : IValidationContextCache
{
private static IValidationContextCache current = null;
private readonly ConcurrentDictionary<CacheKey, ValidationContext> cache = new();
public static IValidationContextCache Current()
{
return (current = current ?? new ValidationContextCache());
}
public virtual ValidationContext GetOrAdd(Type type, Func<Type, ValidationContext> factory)
{
Ensure.NotNull(type, nameof(type));
return cache.GetOrAdd(new CacheKey(type, factory), ck => ck.Factory(ck.EntityType));
}
private readonly struct CacheKey
{
public CacheKey(Type entityType, Func<Type, ValidationContext> factory)
{
EntityType = entityType;
Factory = factory;
}
public Type EntityType { get; }
public Func<Type, ValidationContext> Factory { get; }
private bool Equals(CacheKey other)
{
return EntityType.Equals(other.EntityType);
}
public override bool Equals(object obj)
{
if (obj is null)
{
return false;
}
return (obj is CacheKey cacheKey) && Equals(cacheKey);
}
public override int GetHashCode()
{
unchecked
{
return EntityType.GetHashCode() * 397;
}
}
}
}
}
| arsouza/Aritter | src/Infra.Crosscutting/Validations/ValidationContextCache.cs | C# | mit | 1,702 |
var Page = (function() {
var config = {
$bookBlock : $( '#bb-bookblock' ),
$navNext : $( '#bb-nav-next' ),
$navPrev : $( '#bb-nav-prev' ),
$navFirst : $( '#bb-nav-first' ),
$navLast : $( '#bb-nav-last' )
},
init = function() {
config.$bookBlock.bookblock( {
speed : 1000,
shadowSides : 0.8,
shadowFlip : 0.4
} );
initEvents();
},
initEvents = function() {
var $slides = config.$bookBlock.children();
// add navigation events
config.$navNext.on( 'click touchstart', function() {
config.$bookBlock.bookblock( 'next' );
return false;
} );
config.$navPrev.on( 'click touchstart', function() {
config.$bookBlock.bookblock( 'prev' );
return false;
} );
config.$navFirst.on( 'click touchstart', function() {
config.$bookBlock.bookblock( 'first' );
return false;
} );
config.$navLast.on( 'click touchstart', function() {
config.$bookBlock.bookblock( 'last' );
return false;
} );
// add swipe events
$slides.on( {
'swipeleft' : function( event ) {
config.$bookBlock.bookblock( 'next' );
return false;
},
'swiperight' : function( event ) {
config.$bookBlock.bookblock( 'prev' );
return false;
}
} );
// add keyboard events
$( document ).keydown( function(e) {
var keyCode = e.keyCode || e.which,
arrow = {
left : 37,
up : 38,
right : 39,
down : 40
};
switch (keyCode) {
case arrow.left:
config.$bookBlock.bookblock( 'prev' );
break;
case arrow.right:
config.$bookBlock.bookblock( 'next' );
break;
}
} );
};
return { init : init };
})();
Page.init(); | ManishKrVerma/fejro | assets/js/vendor/jquery.bookblock.trigger.js | JavaScript | mit | 1,706 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import getopt
import codecs
import collections
import pulp
from . import tools
def summarize(text, char_limit, sentence_filter=None, debug=False):
'''
select sentences in terms of maximum coverage problem
Args:
text: text to be summarized (unicode string)
char_limit: summary length (the number of characters)
Returns:
list of extracted sentences
Reference:
Hiroya Takamura, Manabu Okumura.
Text summarization model based on maximum coverage problem and its
variant. (section 3)
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.222.6945
'''
debug_info = {}
sents = list(tools.sent_splitter_ja(text))
words_list = [
# pulp variables should be utf-8 encoded
w.encode('utf-8') for s in sents for w in tools.word_segmenter_ja(s)
]
tf = collections.Counter()
for words in words_list:
for w in words:
tf[w] += 1.0
if sentence_filter is not None:
valid_indices = [i for i, s in enumerate(sents) if sentence_filter(s)]
sents = [sents[i] for i in valid_indices]
words_list = [words_list[i] for i in valid_indices]
sent_ids = [str(i) for i in range(len(sents))] # sentence id
sent_id2len = dict((id_, len(s)) for id_, s in zip(sent_ids, sents)) # c
word_contain = dict() # a
for id_, words in zip(sent_ids, words_list):
word_contain[id_] = collections.defaultdict(lambda: 0)
for w in words:
word_contain[id_][w] = 1
prob = pulp.LpProblem('summarize', pulp.LpMaximize)
# x
sent_vars = pulp.LpVariable.dicts('sents', sent_ids, 0, 1, pulp.LpBinary)
# z
word_vars = pulp.LpVariable.dicts('words', tf.keys(), 0, 1, pulp.LpBinary)
# first, set objective function: sum(w*z)
prob += pulp.lpSum([tf[w] * word_vars[w] for w in tf])
# next, add constraints
# limit summary length: sum(c*x) <= K
prob += pulp.lpSum(
[sent_id2len[id_] * sent_vars[id_] for id_ in sent_ids]
) <= char_limit, 'lengthRequirement'
# for each term, sum(a*x) <= z
for w in tf:
prob += pulp.lpSum(
[word_contain[id_][w] * sent_vars[id_] for id_ in sent_ids]
) >= word_vars[w], 'z:{}'.format(w)
prob.solve()
# print("Status:", pulp.LpStatus[prob.status])
sent_indices = []
for v in prob.variables():
# print v.name, "=", v.varValue
if v.name.startswith('sents') and v.varValue == 1:
sent_indices.append(int(v.name.split('_')[-1]))
return [sents[i] for i in sent_indices], debug_info
if __name__ == '__main__':
_usage = '''
Usage:
python mcp_summ.py -f <file_name> [ -e <encoding> ] -c <char_limit>
Args:
file_name: plain text file to be summarized
encoding: input and output encoding (default: utf-8)
char_limit: summary length (the number of charactors)
'''.strip()
options, args = getopt.getopt(sys.argv[1:], 'f:c:')
options = dict(options)
if len(options) < 2:
print _usage
sys.exit(0)
fname = options['-f']
encoding = optoin['-e'] if '-e' in options else 'utf-8'
char_limit = int(options['-c']) if '-c' in options else None
if fname == 'stdin':
text = '\n'.join(
line for line in sys.stdin.readlines()
).decode(encoding)
else:
text = codecs.open(fname, encoding=encoding).read()
# example sentence filter
#not_too_short = lambda s: True if len(s) > 20 else False
sentences, debug_info = summarize(text, char_limit=char_limit)
#sentence_filter=not_too_short)
for sent in sentences:
print sent.strip().encode(encoding)
| iinm/summpy | summpy/mcp_summ.py | Python | mit | 3,773 |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using SitecoreCognitiveServices.Foundation.IBMSDK.Http;
using SitecoreCognitiveServices.Foundation.IBMSDK.Http.Filters;
namespace SitecoreCognitiveServices.Foundation.IBMSDK.Http
{
public interface IIBMWatsonRepositoryClient : IDisposable
{
HttpClient BaseClient { get; }
MediaTypeFormatterCollection Formatters { get; }
List<IHttpFilter> Filters { get; }
IIBMWatsonRepositoryClient WithAuthentication(string username, string password);
IRequest DeleteAsync(string url);
IRequest GetAsync(string url);
IRequest PostAsync(string url);
IRequest PostAsync<TBody>(string url, TBody body);
IRequest PutAsync(string url);
IRequest PutAsync<TBody>(string url, TBody body);
IRequest SendAsync(string url, HttpMethod method);
IRequest SendAsync(string url, HttpRequestMessage message);
}
} | markstiles/SitecoreCognitiveServices | src/Foundation/IBMSDK/code/Http/IIBMWatsonRepositoryClient.cs | C# | mit | 1,055 |
/*
CrossNet - Copyright (c) 2007 Olivier Nallet
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "CrossNetRuntime/System/Collections/IEnumerable.h"
void * * System::Collections::IEnumerable::s__InterfaceMap__ = NULL;
| KonajuGames/CrossNet | sources/System/Collections/IEnumerable.cpp | C++ | mit | 1,242 |
package chrome.idle
package object bindings {
type State = String
object State {
val ACTIVE: State = "active"
val IDLE: State = "idle"
val LOCKED: State = "locked"
}
}
| amsayk/scala-js-chrome | bindings/src/main/scala/chrome/idle/bindings/package.scala | Scala | mit | 191 |
//
// LMStartViewController.h
// LoveMatch
//
// Created by Wolfgang Kluth on 02.12.12.
// Copyright (c) 2012 nerdburgers. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#import "User.h"
#import "Friend.h"
#import "ATMHudDelegate.h"
@interface LMStartViewController : UIViewController <ATMHudDelegate>
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error;
- (void)calculationSuccessful;
- (void)startHud;
@end
| pheiniz/LoveMatch | LoveMatch/LMStartViewController.h | C | mit | 545 |
'use strict'; // Node 4.x workaround
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const socketio_jwt = require('../../lib');
const jwt = require('jsonwebtoken');
const xtend = require('xtend');
const bodyParser = require('body-parser');
const enableDestroy = require('server-destroy');
let sio;
exports.start = (options, callback) => {
const SECRETS = {
123: 'aaafoo super sercret',
555: 'other'
};
if (typeof options == 'function') {
callback = options;
options = {};
}
options = xtend({
secret: (request, decodedToken, callback) => {
callback(null, SECRETS[decodedToken.id]);
},
timeout: 1000,
handshake: true
}, options);
const app = express();
const server = http.createServer(app);
sio = socketIo.listen(server);
app.use(bodyParser.json());
app.post('/login', (req, res) => {
const profile = {
first_name: 'John',
last_name: 'Doe',
email: '[email protected]',
id: req.body.username === 'valid_signature' ? 123 : 555
};
// We are sending the profile inside the token
const token = jwt.sign(profile, SECRETS[123], { expiresIn: 60*60*5 });
res.json({token: token});
});
if (options.handshake) {
sio.use(socketio_jwt.authorize(options));
sio.sockets.on('echo', (m) => {
sio.sockets.emit('echo-response', m);
});
} else {
sio.sockets
.on('connection', socketio_jwt.authorize(options))
.on('authenticated', (socket) => {
socket.on('echo', (m) => {
socket.emit('echo-response', m);
});
});
}
server.__sockets = [];
server.on('connection', (c) => {
server.__sockets.push(c);
});
server.listen(9000, callback);
enableDestroy(server);
};
exports.stop = (callback) => {
sio.close();
try {
server.destroy();
} catch (er) {}
callback();
};
| auth0/socketio-jwt | test/fixture/secret_function.js | JavaScript | mit | 1,907 |
#ifndef GINGER_TEST_GSEARCH_GPOSTPROCESSMATCHES_H_
#define GINGER_TEST_GSEARCH_GPOSTPROCESSMATCHES_H_
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/GSearch.h>
using namespace seqan;
using namespace std;
SEQAN_DEFINE_TEST(test_GPostProcessMatches_dummy)
{
String<GMatch<int> > unsortetResults;
unsortetResults[0].score=2;
unsortetResults[1].score=3;
unsortetResults[2].score=7;
unsortetResults[3].score=13;
unsortetResults[4].score=5;
int res=GPostProcessMatches(unsortetResults);
SEQAN_ASSERT_EQ(unsortetResults[0].score,2);
SEQAN_ASSERT_EQ(unsortetResults[1].score,3);
SEQAN_ASSERT_EQ(unsortetResults[2].score,5);
SEQAN_ASSERT_EQ(unsortetResults[3].score,7);
SEQAN_ASSERT_EQ(unsortetResults[4].score,13);
SEQAN_ASSERT_EQ(res,0);
}
#endif // GINGER_TEST_GPOSTPROCESSMATCHES_H_
| bkahlert/seqan-research | raw/pmsb13/pmsb13-data-20130530/sources/zsrreplh0s7rggp4/2013-05-16T21-03-39.291+0200/sandbox/PSMB_group6/tests/GSearch/test_GPostProcessMatches.h | C | mit | 828 |
=begin
Escribe un programa que [mientras] no le ingresemos una linea vacia, te siga pidiendo que le ingreses un color
hasta que no le ingreses una linea vacia te va a dejar de pedir
luego imprime todos los colores ingresados
=end
puts "Escribe un color"
colores = []
color = gets.chomp
colores << color
while color != ""
puts "Ingresa un color"
color= gets.chomp
colores << color if color != ""
end
puts colores.join (", ")
n = colores.count - 1
begin
intercambio = false
color = 1
while color <= n
if colores[color - 1] > colores[color]
# si esta condicion se cumple que se haga el intercambio
colores[color - 1], colores[color] = colores[color], colores[color-1]
intercambio = true
end
puts colores.join (", ")
color += 1
end
end while intercambio == true
puts colores.join (", ")
puts color
| anxhe/ejercicios-ruby | color.rb | Ruby | mit | 885 |
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// cocos2d
#include "2d/CCTextureAtlas.h"
#include "CCTextureCache.h"
#include "2d/ccMacros.h"
#include "2d/CCGLProgram.h"
#include "2d/ccGLStateCache.h"
#include "2d/CCEventType.h"
#include "2d/CCDirector.h"
#include "CCGL.h"
#include "CCConfiguration.h"
#include "2d/renderer/CCRenderer.h"
// support
#include "2d/CCTexture2D.h"
#include "deprecated/CCString.h"
#include <stdlib.h>
#include "2d/CCEventDispatcher.h"
#include "2d/CCEventListenerCustom.h"
//According to some tests GL_TRIANGLE_STRIP is slower, MUCH slower. Probably I'm doing something very wrong
// implementation TextureAtlas
NS_CC_BEGIN
TextureAtlas::TextureAtlas()
:_indices(nullptr)
,_dirty(false)
,_texture(nullptr)
,_quads(nullptr)
#if CC_ENABLE_CACHE_TEXTURE_DATA
,_backToForegroundlistener(nullptr)
#endif
{}
TextureAtlas::~TextureAtlas()
{
CCLOGINFO("deallocing TextureAtlas: %p", this);
CC_SAFE_FREE(_quads);
CC_SAFE_FREE(_indices);
glDeleteBuffers(2, _buffersVBO);
if (Configuration::getInstance()->supportsShareableVAO())
{
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
}
CC_SAFE_RELEASE(_texture);
#if CC_ENABLE_CACHE_TEXTURE_DATA
Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundlistener);
#endif
}
ssize_t TextureAtlas::getTotalQuads() const
{
return _totalQuads;
}
ssize_t TextureAtlas::getCapacity() const
{
return _capacity;
}
Texture2D* TextureAtlas::getTexture() const
{
return _texture;
}
void TextureAtlas::setTexture(Texture2D * var)
{
CC_SAFE_RETAIN(var);
CC_SAFE_RELEASE(_texture);
_texture = var;
}
V3F_C4B_T2F_Quad* TextureAtlas::getQuads()
{
//if someone accesses the quads directly, presume that changes will be made
_dirty = true;
return _quads;
}
void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads)
{
_quads = quads;
}
// TextureAtlas - alloc & init
TextureAtlas * TextureAtlas::create(const std::string& file, ssize_t capacity)
{
TextureAtlas * textureAtlas = new TextureAtlas();
if(textureAtlas && textureAtlas->initWithFile(file, capacity))
{
textureAtlas->autorelease();
return textureAtlas;
}
CC_SAFE_DELETE(textureAtlas);
return nullptr;
}
TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, ssize_t capacity)
{
TextureAtlas * textureAtlas = new TextureAtlas();
if (textureAtlas && textureAtlas->initWithTexture(texture, capacity))
{
textureAtlas->autorelease();
return textureAtlas;
}
CC_SAFE_DELETE(textureAtlas);
return nullptr;
}
bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity)
{
// retained in property
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file);
if (texture)
{
return initWithTexture(texture, capacity);
}
else
{
CCLOG("cocos2d: Could not open file: %s", file.c_str());
return false;
}
}
bool TextureAtlas::initWithTexture(Texture2D *texture, ssize_t capacity)
{
CCASSERT(capacity>=0, "Capacity must be >= 0");
// CCASSERT(texture != nullptr, "texture should not be null");
_capacity = capacity;
_totalQuads = 0;
// retained in property
this->_texture = texture;
CC_SAFE_RETAIN(_texture);
// Re-initialization is not allowed
CCASSERT(_quads == nullptr && _indices == nullptr, "");
_quads = (V3F_C4B_T2F_Quad*)malloc( _capacity * sizeof(V3F_C4B_T2F_Quad) );
_indices = (GLushort *)malloc( _capacity * 6 * sizeof(GLushort) );
if( ! ( _quads && _indices) && _capacity > 0)
{
//CCLOG("cocos2d: TextureAtlas: not enough memory");
CC_SAFE_FREE(_quads);
CC_SAFE_FREE(_indices);
// release texture, should set it to null, because the destruction will
// release it too. see cocos2d-x issue #484
CC_SAFE_RELEASE_NULL(_texture);
return false;
}
memset( _quads, 0, _capacity * sizeof(V3F_C4B_T2F_Quad) );
memset( _indices, 0, _capacity * 6 * sizeof(GLushort) );
#if CC_ENABLE_CACHE_TEXTURE_DATA
// listen the event when app go to background
_backToForegroundlistener = EventListenerCustom::create(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(TextureAtlas::listenBackToForeground, this));
Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundlistener, -1);
#endif
this->setupIndices();
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
_dirty = true;
return true;
}
void TextureAtlas::listenBackToForeground(EventCustom* event)
{
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
// set _dirty to true to force it rebinding buffer
_dirty = true;
}
std::string TextureAtlas::getDescription() const
{
return StringUtils::format("<TextureAtlas | totalQuads = %d>", static_cast<int>(_totalQuads));
}
void TextureAtlas::setupIndices()
{
if (_capacity == 0)
return;
for( int i=0; i < _capacity; i++)
{
_indices[i*6+0] = i*4+0;
_indices[i*6+1] = i*4+1;
_indices[i*6+2] = i*4+2;
// inverted index. issue #179
_indices[i*6+3] = i*4+3;
_indices[i*6+4] = i*4+2;
_indices[i*6+5] = i*4+1;
}
}
//TextureAtlas - VAO / VBO specific
void TextureAtlas::setupVBOandVAO()
{
glGenVertexArrays(1, &_VAOname);
GL::bindVAO(_VAOname);
#define kQuadSize sizeof(_quads[0].bl)
glGenBuffers(2, &_buffersVBO[0]);
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _capacity, _quads, GL_DYNAMIC_DRAW);
// vertices
glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices));
// colors
glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors));
// tex coords
glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORDS);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _capacity * 6, _indices, GL_STATIC_DRAW);
// Must unbind the VAO before changing the element buffer.
GL::bindVAO(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
CHECK_GL_ERROR_DEBUG();
}
void TextureAtlas::setupVBO()
{
glGenBuffers(2, &_buffersVBO[0]);
mapBuffers();
}
void TextureAtlas::mapBuffers()
{
// Avoid changing the element buffer for whatever VAO might be bound.
GL::bindVAO(0);
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _capacity, _quads, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _capacity * 6, _indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
CHECK_GL_ERROR_DEBUG();
}
// TextureAtlas - Update, Insert, Move & Remove
void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, ssize_t index)
{
CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index");
_totalQuads = MAX( index+1, _totalQuads);
_quads[index] = *quad;
_dirty = true;
}
void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, ssize_t index)
{
CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index");
_totalQuads++;
CCASSERT( _totalQuads <= _capacity, "invalid totalQuads");
// issue #575. index can be > totalQuads
auto remaining = (_totalQuads-1) - index;
// last object doesn't need to be moved
if( remaining > 0)
{
// texture coordinates
memmove( &_quads[index+1],&_quads[index], sizeof(_quads[0]) * remaining );
}
_quads[index] = *quad;
_dirty = true;
}
void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, ssize_t index, ssize_t amount)
{
CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount");
_totalQuads += amount;
CCASSERT( _totalQuads <= _capacity, "invalid totalQuads");
// issue #575. index can be > totalQuads
auto remaining = (_totalQuads-1) - index - amount;
// last object doesn't need to be moved
if( remaining > 0)
{
// tex coordinates
memmove( &_quads[index+amount],&_quads[index], sizeof(_quads[0]) * remaining );
}
auto max = index + amount;
int j = 0;
for (ssize_t i = index; i < max ; i++)
{
_quads[index] = quads[j];
index++;
j++;
}
_dirty = true;
}
void TextureAtlas::insertQuadFromIndex(ssize_t oldIndex, ssize_t newIndex)
{
CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
if( oldIndex == newIndex )
{
return;
}
// because it is ambiguous in iphone, so we implement abs ourselves
// unsigned int howMany = abs( oldIndex - newIndex);
auto howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex);
auto dst = oldIndex;
auto src = oldIndex + 1;
if( oldIndex > newIndex)
{
dst = newIndex+1;
src = newIndex;
}
// texture coordinates
V3F_C4B_T2F_Quad quadsBackup = _quads[oldIndex];
memmove( &_quads[dst],&_quads[src], sizeof(_quads[0]) * howMany );
_quads[newIndex] = quadsBackup;
_dirty = true;
}
void TextureAtlas::removeQuadAtIndex(ssize_t index)
{
CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index");
auto remaining = (_totalQuads-1) - index;
// last object doesn't need to be moved
if( remaining )
{
// texture coordinates
memmove( &_quads[index],&_quads[index+1], sizeof(_quads[0]) * remaining );
}
_totalQuads--;
_dirty = true;
}
void TextureAtlas::removeQuadsAtIndex(ssize_t index, ssize_t amount)
{
CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds");
auto remaining = (_totalQuads) - (index + amount);
_totalQuads -= amount;
if ( remaining )
{
memmove( &_quads[index], &_quads[index+amount], sizeof(_quads[0]) * remaining );
}
_dirty = true;
}
void TextureAtlas::removeAllQuads()
{
_totalQuads = 0;
}
// TextureAtlas - Resize
bool TextureAtlas::resizeCapacity(ssize_t newCapacity)
{
CCASSERT(newCapacity>=0, "capacity >= 0");
if( newCapacity == _capacity )
{
return true;
}
auto oldCapactiy = _capacity;
// update capacity and totolQuads
_totalQuads = MIN(_totalQuads, newCapacity);
_capacity = newCapacity;
V3F_C4B_T2F_Quad* tmpQuads = nullptr;
GLushort* tmpIndices = nullptr;
// when calling initWithTexture(fileName, 0) on bada device, calloc(0, 1) will fail and return nullptr,
// so here must judge whether _quads and _indices is nullptr.
if (_quads == nullptr)
{
tmpQuads = (V3F_C4B_T2F_Quad*)malloc( _capacity * sizeof(_quads[0]) );
if (tmpQuads != nullptr)
{
memset(tmpQuads, 0, _capacity * sizeof(_quads[0]) );
}
}
else
{
tmpQuads = (V3F_C4B_T2F_Quad*)realloc( _quads, sizeof(_quads[0]) * _capacity );
if (tmpQuads != nullptr && _capacity > oldCapactiy)
{
memset(tmpQuads+oldCapactiy, 0, (_capacity - oldCapactiy)*sizeof(_quads[0]) );
}
_quads = nullptr;
}
if (_indices == nullptr)
{
tmpIndices = (GLushort*)malloc( _capacity * 6 * sizeof(_indices[0]) );
if (tmpIndices != nullptr)
{
memset( tmpIndices, 0, _capacity * 6 * sizeof(_indices[0]) );
}
}
else
{
tmpIndices = (GLushort*)realloc( _indices, sizeof(_indices[0]) * _capacity * 6 );
if (tmpIndices != nullptr && _capacity > oldCapactiy)
{
memset( tmpIndices+oldCapactiy, 0, (_capacity-oldCapactiy) * 6 * sizeof(_indices[0]) );
}
_indices = nullptr;
}
if( ! ( tmpQuads && tmpIndices) ) {
CCLOG("cocos2d: TextureAtlas: not enough memory");
CC_SAFE_FREE(tmpQuads);
CC_SAFE_FREE(tmpIndices);
CC_SAFE_FREE(_quads);
CC_SAFE_FREE(_indices);
_capacity = _totalQuads = 0;
return false;
}
_quads = tmpQuads;
_indices = tmpIndices;
setupIndices();
mapBuffers();
_dirty = true;
return true;
}
void TextureAtlas::increaseTotalQuadsWith(ssize_t amount)
{
CCASSERT(amount>=0, "amount >= 0");
_totalQuads += amount;
}
void TextureAtlas::moveQuadsFromIndex(ssize_t oldIndex, ssize_t amount, ssize_t newIndex)
{
CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0");
CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
CCASSERT(oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
if( oldIndex == newIndex )
{
return;
}
//create buffer
size_t quadSize = sizeof(V3F_C4B_T2F_Quad);
V3F_C4B_T2F_Quad* tempQuads = (V3F_C4B_T2F_Quad*)malloc( quadSize * amount);
memcpy( tempQuads, &_quads[oldIndex], quadSize * amount );
if (newIndex < oldIndex)
{
// move quads from newIndex to newIndex + amount to make room for buffer
memmove( &_quads[newIndex], &_quads[newIndex+amount], (oldIndex-newIndex)*quadSize);
}
else
{
// move quads above back
memmove( &_quads[oldIndex], &_quads[oldIndex+amount], (newIndex-oldIndex)*quadSize);
}
memcpy( &_quads[newIndex], tempQuads, amount*quadSize);
free(tempQuads);
_dirty = true;
}
void TextureAtlas::moveQuadsFromIndex(ssize_t index, ssize_t newIndex)
{
CCASSERT(index>=0 && newIndex>=0, "values must be >= 0");
CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds");
memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0]));
}
void TextureAtlas::fillWithEmptyQuadsFromIndex(ssize_t index, ssize_t amount)
{
CCASSERT(index>=0 && amount>=0, "values must be >= 0");
V3F_C4B_T2F_Quad quad;
memset(&quad, 0, sizeof(quad));
auto to = index + amount;
for (ssize_t i = index ; i < to ; i++)
{
_quads[i] = quad;
}
}
// TextureAtlas - Drawing
void TextureAtlas::drawQuads()
{
this->drawNumberOfQuads(_totalQuads, 0);
}
void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads)
{
CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0");
this->drawNumberOfQuads(numberOfQuads, 0);
}
void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads, ssize_t start)
{
CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0");
if(!numberOfQuads)
return;
GL::bindTexture2D(_texture->getName());
if (Configuration::getInstance()->supportsShareableVAO())
{
//
// Using VBO and VAO
//
// XXX: update is done in draw... perhaps it should be done in a timer
if (_dirty)
{
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// option 1: subdata
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] );
// option 2: data
// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW);
// option 3: orphaning + glMapBuffer
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (numberOfQuads-start), nullptr, GL_DYNAMIC_DRAW);
void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(buf, _quads, sizeof(_quads[0])* (numberOfQuads-start));
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
_dirty = false;
}
GL::bindVAO(_VAOname);
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
#endif
glDrawElements(GL_TRIANGLES, (GLsizei) numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])) );
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
// glBindVertexArray(0);
}
else
{
//
// Using VBO without VAO
//
#define kQuadSize sizeof(_quads[0].bl)
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// XXX: update is done in draw... perhaps it should be done in a timer
if (_dirty)
{
glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * numberOfQuads , &_quads[start] );
_dirty = false;
}
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
// vertices
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, vertices));
// colors
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, colors));
// tex coords
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glDrawElements(GL_TRIANGLES, (GLsizei)numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,numberOfQuads*6);
CHECK_GL_ERROR_DEBUG();
}
NS_CC_END
| MandukaGames/tutorial-puzzle | cocos2d/cocos/2d/CCTextureAtlas.cpp | C++ | mit | 19,758 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Aug 31 23:15:48 CEST 2015 -->
<title>IObjectBooleanNullCheck (FailFast v.1.3)</title>
<meta name="date" content="2015-08-31">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="IObjectBooleanNullCheck (FailFast v.1.3)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/IObjectBooleanNullCheck.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../starkcoder/failfast/checks/objects/booleans/IObjectBooleanNotSameCheck.html" title="interface in starkcoder.failfast.checks.objects.booleans"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../starkcoder/failfast/checks/objects/booleans/IObjectBooleanSameCheck.html" title="interface in starkcoder.failfast.checks.objects.booleans"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?starkcoder/failfast/checks/objects/booleans/IObjectBooleanNullCheck.html" target="_top">Frames</a></li>
<li><a href="IObjectBooleanNullCheck.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">starkcoder.failfast.checks.objects.booleans</div>
<h2 title="Interface IObjectBooleanNullCheck" class="title">Interface IObjectBooleanNullCheck</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href="../../../../../starkcoder/failfast/checks/ICheck.html" title="interface in starkcoder.failfast.checks">ICheck</a></dd>
</dl>
<dl>
<dt>All Known Subinterfaces:</dt>
<dd><a href="../../../../../starkcoder/failfast/checks/IChecker.html" title="interface in starkcoder.failfast.checks">IChecker</a>, <a href="../../../../../starkcoder/failfast/checks/objects/booleans/IObjectBooleanChecker.html" title="interface in starkcoder.failfast.checks.objects.booleans">IObjectBooleanChecker</a>, <a href="../../../../../starkcoder/failfast/checks/objects/IObjectChecker.html" title="interface in starkcoder.failfast.checks.objects">IObjectChecker</a></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../starkcoder/failfast/checks/AChecker.html" title="class in starkcoder.failfast.checks">AChecker</a>, <a href="../../../../../starkcoder/failfast/checks/Checker.html" title="class in starkcoder.failfast.checks">Checker</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">IObjectBooleanNullCheck</span>
extends <a href="../../../../../starkcoder/failfast/checks/ICheck.html" title="interface in starkcoder.failfast.checks">ICheck</a></pre>
<div class="block">Specifies a null check for Boolean.</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Keld Oelykke</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../starkcoder/failfast/checks/objects/booleans/IObjectBooleanNullCheck.html#isBooleanNull(java.lang.Object, java.lang.Boolean)">isBooleanNull</a></strong>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> caller,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html?is-external=true" title="class or interface in java.lang">Boolean</a> referenceA)</code>
<div class="block">Checks if the Boolean is null.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="isBooleanNull(java.lang.Object, java.lang.Boolean)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isBooleanNull</h4>
<pre>boolean isBooleanNull(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> caller,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html?is-external=true" title="class or interface in java.lang">Boolean</a> referenceA)</pre>
<div class="block">Checks if the Boolean is null.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>caller</code> - end-user instance initiating the check</dd><dd><code>referenceA</code> - reference to null check</dd>
<dt><span class="strong">Returns:</span></dt><dd>true, if referenced object is null, otherwise false</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - if caller is null</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/IObjectBooleanNullCheck.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../starkcoder/failfast/checks/objects/booleans/IObjectBooleanNotSameCheck.html" title="interface in starkcoder.failfast.checks.objects.booleans"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../starkcoder/failfast/checks/objects/booleans/IObjectBooleanSameCheck.html" title="interface in starkcoder.failfast.checks.objects.booleans"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?starkcoder/failfast/checks/objects/booleans/IObjectBooleanNullCheck.html" target="_top">Frames</a></li>
<li><a href="IObjectBooleanNullCheck.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><i>The MIT License (MIT) - Copyright © 2014-2015 Keld Oelykke. All Rights Reserved.</i></small></p>
</body>
</html>
| KeldOelykke/FailFast | Java/Web/war/releases/1.3/api/starkcoder/failfast/checks/objects/booleans/IObjectBooleanNullCheck.html | HTML | mit | 9,915 |
Eleven Note
=========
Eleven Note is a simple note taking app without all the fluff written in Swift for iOS.
- Create / Read / Update / Delete notes
- Serialize and store notes in the sandbox documents folder
About Eleven Fifty
-----------
Eleven Fifty is an immersive coding academy where you will build and ship three apps to the AppStore in just one week!
We don’t waste valuable classroom instruction time teaching you to draw circles, create things by hand that the Integrated Development Environment will do for you, or build apps that nobody in their right mind would ever use. Instead, we teach you how to build apps that you already use every day. We start with the simplest parts of a project, such as the login screen, and then progressively dig deeper, exposing our students to the most important portions of the frameworks. Learn more about us at [elevenfifty.com].
Learning
-----------
This app is written in a way that is easy for newcomers to Swift or app development in general. Advanced users would likely take a different approach to building this app.
This app explores the following:
* Storyboards
* Model-View-Controller Pattern
* Singleton Pattern
* UIViewController
* UITableViewController / UITableViewDelegate / UITableViewDataSource
* UITableViewCell
* UILabel
* UITextField
* UITextView
* UIBarButtonItem
* UINavigationController
* NSFileManager / NSKeyedArchiver / NSKeyedUnarchiver
License
----
MIT
[elevenfifty.com]:http://elevenfifty.com
| tkunstek/ElevenNote | Readme.md | Markdown | mit | 1,490 |
var module = angular.module('angular-bind-html-compile', []);
module.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
// In case value is a TrustedValueHolderType, sometimes it
// needs to be explicitly called into a string in order to
// get the HTML string.
element.html(value && value.toString());
// If scope is provided use it, otherwise use parent scope
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);
| SimiaryLabs/pteraformer | client/lib/angular-bind-html-compile.js | JavaScript | mit | 819 |
#include <iostream>
#include <map>
#include <cctype>
#include <vector>
#include <set>
#include <string>
#include <fstream>
#include <stdexcept>
#include <sstream>
#include <iomanip>
using namespace std;
namespace
{
class Date
{
int month = -1; // [1..12]
int day = -1; // [1..31]
int year = -1; // [0..9999]
void throwWrongDate(const string& sDate) const
{
throw invalid_argument("Wrong date format: " + sDate);
}
public:
int GetYear() const { return year; }
int GetMonth() const { return month; }
int GetDay() const { return day; }
Date() {}
explicit Date(const string& sDate)
{
if (sDate.find('+') != string::npos) throwWrongDate(sDate);
stringstream ss(sDate);
char first_symbol = ss.peek();
if (first_symbol == '-') throwWrongDate(sDate);
ss >> year;
if (!ss.good() || year < 0 || year > 9999) throwWrongDate(sDate);
char delim = 0;
ss >> delim;
if (delim != '-') throwWrongDate(sDate);
ss >> month;
if (!ss.good()) throwWrongDate(sDate);
delim = 0;
ss >> delim;
if (delim != '-') throwWrongDate(sDate);
ss >> day;
if (ss.bad() || ss.fail() || !ss.eof()) throwWrongDate(sDate);
if (month < 1 || month > 12) throw invalid_argument("Month value is invalid: " + to_string(month));
if (day < 1 || day > 31) throw invalid_argument("Day value is invalid: " + to_string(day));
}
};
bool operator<(const Date& lhs, const Date& rhs)
{
if (lhs.GetYear() < rhs.GetYear()) return true;
if (lhs.GetYear() > rhs.GetYear()) return false;
if (lhs.GetMonth() < rhs.GetMonth()) return true;
if (lhs.GetMonth() > rhs.GetMonth()) return false;
return lhs.GetDay() < rhs.GetDay();
}
ostream& operator<< (ostream& os, const Date& date)
{
os << setw(4) << setfill('0') << date.GetYear() << '-'
<< setw(2) << setfill('0') << date.GetMonth() << '-'
<< setw(2) << setfill('0') << date.GetDay();
return os;
}
istream& operator>> (istream& is, Date& date)
{
string sdate;
is >> sdate;
date = Date{ sdate };
return is;
}
class Database
{
map<Date, set<string>> storage;
public:
void AddEvent(const Date& date, const string& event)
{
storage[date].insert(event);
}
bool DeleteEvent(const Date& date, const string& event)
{
if (storage.count(date) > 0 && storage.at(date).count(event) > 0)
{
storage[date].erase(event);
if (storage[date].size() == 0) // removed last event of date
{
storage.erase(date);
}
return true;
}
return false;
}
size_t DeleteDate(const Date& date)
{
if (storage.count(date) == 0) return 0;
size_t deleted = storage.at(date).size();
storage.at(date).clear();
return deleted;
}
vector<string> Find(const Date& date) const
{
vector<string> events;
if (storage.count(date) > 0)
{
for (const auto& e : storage.at(date))
{
events.push_back(e);
}
}
return std::move(events);
}
void Print() const
{
for (const auto& date : storage)
{
for (const auto& e : date.second)
{
cout << date.first << " " << e << endl;
}
}
}
};
void ExecuteCommand(const string& command, Database& db)
{
if (command.find_first_not_of(" \t") == string::npos) return;
istringstream ss(command);
string cmd_code;
ss >> cmd_code;
if (cmd_code == "Add")
{
Date date;
ss >> date;
if (ss.eof())
{
throw invalid_argument("Unknown command: " + command);
}
string event;
ss >> event;
if (event.find_first_not_of(" \t") == string::npos)
{
throw invalid_argument("Unknown command: " + command);
}
db.AddEvent(date, event);
}
else if (cmd_code == "Del")
{
Date date;
ss >> date;
string event;
if (ss >> event && event != "") // delete specific event
{
if (db.DeleteEvent(date, event))
{
cout << "Deleted successfully" << endl;
}
else
{
cout << "Event not found" << endl;
}
}
else // delete by date
{
cout << "Deleted " << db.DeleteDate(date) << " events" << endl;
}
}
else if (cmd_code == "Find")
{
Date date;
ss >> date;
vector<string> events = db.Find(date);
for (const auto& e : events)
{
cout << e << endl;
}
}
else if (cmd_code == "Print")
{
db.Print();
}
else
{
throw invalid_argument("Unknown command: " + cmd_code);
}
}
}
int main_05_01()
{
Database db;
//ifstream fin("d:\\q");
istream& in = cin;
string command;
while (getline(in, command))
{
if (command == "") continue;
try
{
ExecuteCommand(command, db);
}
catch(const exception& ex)
{
cout << ex.what() << endl;
return -1;
}
}
return 0;
}
| zakhars/Education | Coursera/Yandex_CppWhite/Coursera_CppWhite_Week05_Task01.cpp | C++ | mit | 5,992 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- <link rel="icon" href="/assets/images/logo.png"> -->
<title>Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge) | Bianca Pereira</title>
<!-- Begin Jekyll SEO tag v2.7.1 -->
<title>Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge) | Bianca Pereira</title>
<meta name="generator" content="Jekyll v4.2.0" />
<meta property="og:title" content="Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge)" />
<meta name="author" content="bianca" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Day 4 of the Gumroad 14 Day Product Challenge" />
<meta property="og:description" content="Day 4 of the Gumroad 14 Day Product Challenge" />
<meta property="og:site_name" content="Bianca Pereira" />
<meta property="og:image" content="https://cdn.pixabay.com/photo/2014/06/18/13/23/time-371226_1280.jpg" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2020-10-29T00:00:00+00:00" />
<meta name="twitter:card" content="summary_large_image" />
<meta property="twitter:image" content="https://cdn.pixabay.com/photo/2014/06/18/13/23/time-371226_1280.jpg" />
<meta property="twitter:title" content="Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge)" />
<script type="application/ld+json">
{"datePublished":"2020-10-29T00:00:00+00:00","description":"Day 4 of the Gumroad 14 Day Product Challenge","url":"/posts/Day-4-Gumroad-14-Day-Product-Challenge-2020-10-29/","@type":"BlogPosting","dateModified":"2020-10-29T00:00:00+00:00","mainEntityOfPage":{"@type":"WebPage","@id":"/posts/Day-4-Gumroad-14-Day-Product-Challenge-2020-10-29/"},"publisher":{"@type":"Organization","logo":{"@type":"ImageObject","url":"/assets/images/logo.png"},"name":"bianca"},"image":"https://cdn.pixabay.com/photo/2014/06/18/13/23/time-371226_1280.jpg","author":{"@type":"Person","name":"bianca"},"headline":"Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge)","@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="/assets/css/screen.css" rel="stylesheet">
<link href="/assets/css/main.css" rel="stylesheet">
<script src="/assets/js/jquery.min.js"></script>
</head>
<!-- change your GA id in _config.yml -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '', 'auto');
ga('send', 'pageview');
</script>
<body class="layout-post">
<!-- defer loading of font and font awesome -->
<noscript id="deferred-styles">
<link href="https://fonts.googleapis.com/css?family=Righteous%7CMerriweather:300,300i,400,400i,700,700i" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.rawgit.com/jpswalsh/academicons/master/css/academicons.min.css">
</noscript>
<!-- Begin Menu Navigation
================================================== -->
<nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top mediumnavigation nav-down">
<div class="container pr-0">
<!-- Begin Logo -->
<a class="navbar-brand" href="/">
Bianca Pereira
</a>
<!-- End Logo -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarMediumish" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarMediumish">
<!-- Begin Menu -->
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="/">About</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="/posts">Blog</a>
</li>
<!--
<li class="nav-item">
<a class="nav-link" href="/projects">Projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/hobbies">Hobbies</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/publications">Publications</a>
</li>
-->
<script src="/assets/js/lunr.js"></script>
<style>
.lunrsearchresult .title {color: #d9230f;}
.lunrsearchresult .url {color: silver;}
.lunrsearchresult a {display: block; color: #777;}
.lunrsearchresult a:hover, .lunrsearchresult a:focus {text-decoration: none;}
.lunrsearchresult a:hover .title {text-decoration: underline;}
</style>
<form class="bd-search" onSubmit="return lunr_search(document.getElementById('lunrsearch').value);">
<input type="text" class="form-control text-small launch-modal-search" id="lunrsearch" name="q" maxlength="255" value="" placeholder="Type and enter..."/>
</form>
<div id="lunrsearchresults">
<ul></ul>
</div>
<script src="/assets/js/lunrsearchengine.js"></script>
</ul>
<!-- End Menu -->
</div>
</div>
</nav>
<!-- End Navigation
================================================== -->
<div class="site-content">
<div class="container">
<!-- Content
================================================== -->
<div class="main-content">
<!-- Begin Article
================================================== -->
<div class="container">
<div class="row">
<!-- Post Share -->
<div class="col-md-2 pl-0">
<div class="share sticky-top sticky-top-offset">
<p>
Share
</p>
<ul>
<li class="ml-1 mr-1">
<a target="_blank" href="https://twitter.com/intent/tweet?text=@bianca_oli_per Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge)&url=/posts/Day-4-Gumroad-14-Day-Product-Challenge-2020-10-29/" onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;">
<i class="fab fa-twitter"></i>
</a>
</li>
<li class="ml-1 mr-1">
<a target="_blank" href="https://facebook.com/sharer/sharer.php?u=/posts/Day-4-Gumroad-14-Day-Product-Challenge-2020-10-29/" onclick="window.open(this.href, 'facebook-share', 'width=550,height=435');return false;">
<i class="fab fa-facebook-f"></i>
</a>
</li>
<li class="ml-1 mr-1">
<a target="_blank" href="https://www.linkedin.com/shareArticle?mini=true&url=/posts/Day-4-Gumroad-14-Day-Product-Challenge-2020-10-29/" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-linkedin-in"></i>
</a>
</li>
</ul>
<div class="sep">
</div>
<ul>
<li>
<a class="small smoothscroll" href="#disqus_thread"></a>
</li>
</ul>
</div>
</div>
<!-- Post -->
<div class="col-md-9 flex-first flex-md-unordered">
<div class="mainheading">
<!-- Author Box -->
<div class="row post-top-meta">
<div class="col-xs-12 col-md-3 col-lg-2 text-center text-md-left mb-4 mb-md-0">
<img class="author-thumb" src="https://www.gravatar.com/avatar/92baedfd8ff5c99d3185a6f0ab4c694c?s=250&d=mm&r=x" alt="Bianca Pereira">
</div>
<div class="col-xs-12 col-md-9 col-lg-10 text-center text-md-left">
<div class-"row"><a target="_blank" class="link-dark" href="http://biancapereira.me">Bianca Pereira</a><a target="_blank" href="https://twitter.com/bianca_oli_per" class="btn follow">Follow</a></div>
<div class-"row"> <span class="author-description">A researcher and software developer at work, a feminist by ideal, and an educator by passion.</span></div>
</div>
</div>
<!-- Post Title -->
<h1 class="posttitle">Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge)</h1>
</div>
<!-- Adsense if enabled from _config.yml (change your pub id and slot) -->
<!-- End Adsense -->
<!-- Post Featured Image
<img class="featured-image img-fluid" src="https://cdn.pixabay.com/photo/2014/06/18/13/23/time-371226_1280.jpg" alt="Day 4: Taking easy and creating the timeline. (Gumroad 14 Day Product Challenge)">
End Featured Image -->
<!-- Post Content -->
<div class="article-post">
<!-- Toc if any -->
<!-- End Toc -->
<p>Given the fact that I prefer to write first thing in the morning rather than at the end of the day (the time I have assigned to this project) I have changed my timelines and went easy on myself today.</p>
<p>For today I had just created the timeline for the development of the product, with expected completion date to Friday 06th November.</p>
<p>As my MVP, I am thinking it as simple as a PDF created via Google Docs (that also exports as ePUB, by the way), some basic illustrations using diagrams.net and a cover with free stock images and free fonts. When the MVP is done then perhaps I can spend some time studying how to use more professional applications for formatting the book.</p>
<p>Meanwhile there is an opportunity to participate in a tweetchat next Monday on the topic of my book. Very exciting! :)</p>
<center><div class="jekyll-twitter-plugin"><blockquote class="twitter-tweet"><p lang="en" dir="ltr">Next Monday <a href="https://twitter.com/hashtag/VirtualNotViral?src=hash&ref_src=twsrc%5Etfw">#VirtualNotViral</a> chats about a month of and for academic writing. What does it mean for you? <a href="https://t.co/acj0tXofEx">pic.twitter.com/acj0tXofEx</a></p>— @PhD-VirtualNotViral (@virtualnotviral) <a href="https://twitter.com/virtualnotviral/status/1321786183710552064?ref_src=twsrc%5Etfw">October 29, 2020</a></blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div></center>
<p>Looking forward for the next steps in the 14 Day Product challenge.</p>
</div>
<!-- Post Date -->
<p>
<small>
<span class="post-date"><time class="post-date" datetime="2020-10-29">29 Oct 2020</time></span>
</small>
</p>
<!-- Post Categories -->
<div class="after-post-cats">
<ul class="tags mb-4">
<li>
<a class="smoothscroll" href="/categories#blog">blog</a>
</li>
</ul>
</div>
<!-- End Categories -->
<!-- Post Tags -->
<div class="after-post-tags">
<ul class="tags">
<li>
<a class="smoothscroll" href="/tags#gumroad-challenge">#gumroad challenge</a>
</li>
</ul>
</div>
<!-- End Tags -->
<!-- Prev/Next -->
<div class="row PageNavigation d-flex justify-content-between font-weight-bold">
<a class="prev d-block col-md-6" href="/posts/Day-3-Gumroad-14-Day-Product_Challenge-2020-10-28/"> « Day 3: Validating the idea and Product Outline. (Gumroad 14 Day Product Challenge)</a>
<a class="next d-block col-md-6 text-lg-right" href="/posts/Days-5-and-6-Gumroad-14-Day-Product_Challenge-2020-10-31/">Days 5 and 6: Creating the product and no book cover yet. (Gumroad 14 Day Product Challenge) » </a>
<div class="clearfix"></div>
</div>
<!-- End Categories -->
</div>
<!-- End Post -->
</div>
</div>
<!-- End Article
================================================== -->
<!-- Begin Comments
================================================== -->
<div class="container">
<div id="comments" class="row justify-content-center mb-5">
<div class="col-md-8">
<section class="disqus">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'bianca-pereira';
var disqus_developer = 0;
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = window.location.protocol + '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</section>
</div>
</div>
</div>
<!--End Comments
================================================== -->
</div>
</div>
<!-- Categories Jumbotron
================================================== -->
<!--<div class="jumbotron fortags">
<div class="d-md-flex h-100">
<div class="col-md-4 transpdark align-self-center text-center h-100">
<div class="d-md-flex align-items-center justify-content-center h-100">
<h2 class="d-md-block align-self-center py-1 font-weight-light">Explore <span class="d-none d-md-inline">→</span></h2>
</div>
</div>
<div class="col-md-8 p-5 align-self-center text-center">
<a class="mt-1 mb-1" href="/categories#blog">blog (13)</a>
<a class="mt-1 mb-1" href="/categories#events">events (8)</a>
</div>
</div>
</div>
-->
<!-- Begin Footer
================================================== -->
<footer class="footer">
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-4 text-center text-lg-left">
<a target="_blank" href="https://www.wowthemes.net/mediumish-free-jekyll-template/">Mediumish Jekyll Theme</a> by WowThemes.net
</div>
<div class="col-md-4 col-sm-4 text-center text-lg-center">
Copyright © 2021 Bianca Pereira
</div>
<div class="col-md-4 col-sm-4 text-center text-lg-right">
<span class="social">
<a target="_blank" href="https://twitter.com/bianca_oli_per" onclick="window.open(this.href, 'twitter', 'width=550,height=235');return false;">
<i class="fab fa-twitter"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://scholar.google.com/citations?user=bEpicW4AAAAJ" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="ai ai-google-scholar"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://www.slideshare.net/bianca_oliveira" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-slideshare"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://github.com/bianca-pereira" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-github"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://linkedin.com/in/biancaolipereira/" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-linkedin-in"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://www.facebook.com/walkInIreland/" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-facebook"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://www.quora.com/profile/Bianca-Pereira-7/en" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-quora"></i>
</a>
</span>
<span class="social">
<a target="_blank" href="https://soundcloud.com/user-671615919" onclick="window.open(this.href, 'width=550,height=435');return false;">
<i class="fab fa-soundcloud"></i>
</a>
</span>
</div>
</div>
</div>
</footer>
<!-- End Footer
================================================== -->
</div> <!-- /.site-content -->
<!-- Scripts
================================================== -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="/assets/js/mediumish.js"></script>
<script src="/assets/js/ie10-viewport-bug-workaround.js"></script>
<script id="dsq-count-scr" src="//bianca-pereira.disqus.com/count.js"></script>
</body>
</html>
| bianca-pereira/bianca-pereira.github.com | posts/Day-4-Gumroad-14-Day-Product-Challenge-2020-10-29/index.html | HTML | mit | 19,342 |
package com.apollographql.apollo.rx;
import com.apollographql.apollo.ApolloCall;
import com.apollographql.apollo.ApolloPrefetch;
import com.apollographql.apollo.ApolloQueryWatcher;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.internal.util.Cancelable;
import javax.annotation.Nonnull;
import rx.Completable;
import rx.CompletableSubscriber;
import rx.Emitter;
import rx.Observable;
import rx.Subscription;
import rx.exceptions.Exceptions;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Cancellable;
import rx.subscriptions.Subscriptions;
import static com.apollographql.apollo.api.internal.Utils.checkNotNull;
/**
* The RxApollo class provides methods for converting ApolloCall
* and ApolloWatcher types to RxJava 1 Observables.
*/
public final class RxApollo {
private RxApollo() {
}
/**
* Converts an {@link ApolloQueryWatcher} into an Observable. Honors the back pressure from downstream with the back
* pressure strategy {@link rx.Emitter.BackpressureMode#LATEST}.
*
* @param watcher the ApolloQueryWatcher to convert
* @param <T> the value type
* @return the converted Observable
*/
@Nonnull
public static <T> Observable<Response<T>> from(@Nonnull final ApolloQueryWatcher<T> watcher) {
return from(watcher, Emitter.BackpressureMode.LATEST);
}
/**
* Converts an {@link ApolloQueryWatcher} into an Observable.
*
* @param watcher the ApolloQueryWatcher to convert
* @param backpressureMode the back pressure strategy to apply to the observable source.
* @param <T> the value type
* @return the converted Observable
*/
@Nonnull public static <T> Observable<Response<T>> from(@Nonnull final ApolloQueryWatcher<T> watcher,
@Nonnull Emitter.BackpressureMode backpressureMode) {
checkNotNull(backpressureMode, "backpressureMode == null");
checkNotNull(watcher, "watcher == null");
return Observable.create(new Action1<Emitter<Response<T>>>() {
@Override public void call(final Emitter<Response<T>> emitter) {
emitter.setCancellation(new Cancellable() {
@Override public void cancel() throws Exception {
watcher.cancel();
}
});
watcher.enqueueAndWatch(new ApolloCall.Callback<T>() {
@Override public void onResponse(@Nonnull Response<T> response) {
emitter.onNext(response);
}
@Override public void onFailure(@Nonnull ApolloException e) {
Exceptions.throwIfFatal(e);
emitter.onError(e);
}
});
}
}, backpressureMode);
}
/**
* Converts an {@link ApolloCall} to a Observable. The number of emissions this Observable will have
* is based on the {@link com.apollographql.apollo.fetcher.ResponseFetcher} used with the call.
*
* @param call the ApolloCall to convert
* @param <T> the value type
* @param backpressureMode The {@link rx.Emitter.BackpressureMode} to use.
* @return the converted Observable
*/
@Nonnull public static <T> Observable<Response<T>> from(@Nonnull final ApolloCall<T> call,
Emitter.BackpressureMode backpressureMode) {
checkNotNull(call, "call == null");
return Observable.create(new Action1<Emitter<Response<T>>>() {
@Override public void call(final Emitter<Response<T>> emitter) {
emitter.setCancellation(new Cancellable() {
@Override public void cancel() throws Exception {
call.cancel();
}
});
call.enqueue(new ApolloCall.Callback<T>() {
@Override public void onResponse(@Nonnull Response<T> response) {
emitter.onNext(response);
}
@Override public void onFailure(@Nonnull ApolloException e) {
Exceptions.throwIfFatal(e);
emitter.onError(e);
}
@Override public void onCompleted() {
emitter.onCompleted();
}
});
}
}, backpressureMode);
}
/**
* Converts an {@link ApolloCall} to a Observable with
* backpressure mode {@link rx.Emitter.BackpressureMode#BUFFER}. The number of emissions this Observable will have
* is based on the {@link com.apollographql.apollo.fetcher.ResponseFetcher} used with the call.
*
* @param call the ApolloCall to convert
* @param <T> the value type
* @return the converted Observable
*/
@Nonnull public static <T> Observable<Response<T>> from(@Nonnull final ApolloCall<T> call) {
return from(call, Emitter.BackpressureMode.BUFFER);
}
/**
* Converts an {@link ApolloPrefetch} to a Completable.
*
* @param prefetch the ApolloPrefetch to convert
* @return the converted Completable
*/
@Nonnull public static Completable from(@Nonnull final ApolloPrefetch prefetch) {
checkNotNull(prefetch, "prefetch == null");
return Completable.create(new Completable.OnSubscribe() {
@Override public void call(final CompletableSubscriber subscriber) {
Subscription subscription = getSubscription(subscriber, prefetch);
try {
prefetch.execute();
if (!subscription.isUnsubscribed()) {
subscriber.onCompleted();
}
} catch (ApolloException e) {
Exceptions.throwIfFatal(e);
if (!subscription.isUnsubscribed()) {
subscriber.onError(e);
}
}
}
});
}
private static Subscription getSubscription(CompletableSubscriber subscriber, final Cancelable cancelable) {
Subscription subscription = Subscriptions.create(new Action0() {
@Override public void call() {
cancelable.cancel();
}
});
subscriber.onSubscribe(subscription);
return subscription;
}
}
| sav007/apollo-android | apollo-rxsupport/src/main/java/com/apollographql/apollo/rx/RxApollo.java | Java | mit | 5,865 |
# Provides callbacks for internal worker use:
#
# def named_metric(metric)
# "HardWorker.#{Process.pid}.#{metric}"
# end
#
# worker = Gearman::Worker.new
# worker.on_grab_job { StatsD.increment(named_metric('grab_job')) }
# worker.on_job_assign { StatsD.increment(named_metric('job_assign')) }
# worker.on_no_job { StatsD.increment(named_metric('no_job')) }
# worker.on_work_complete { StatsD.increment(named_metric('work_complete')) }
module Gearman
class Worker
module Callbacks
%w(connect grab_job no_job job_assign work_complete work_fail
work_exception).each do |event|
define_method("on_#{event}") do |&callback|
instance_variable_set("@__on_#{event}", callback)
end
define_method("run_#{event}_callback") do
callback = instance_variable_get("@__on_#{event}")
return unless callback
begin
callback.call
rescue Exception => e
logger.error "#{event} failed: #{e.inspect}"
end
end
end
end
end
end | johnewart/gearman-ruby | lib/gearman/worker/callbacks.rb | Ruby | mit | 1,057 |
NIGUN
### Website for promoting the issue of Jewish music on the network.
Pleas visit our [live aplication](https://github.com/chagitniss/nigun/blob/master/NIGUN/client/views/home.html)(-not working yet, come back soon!)
### [our chat](https://gitter.im/jce-il-se-class-2017a-nigun/Lobby?source=orgpage)
[Issue Board](https://github.com/chagitniss/nigun/projects/1)
### Disclaimer
This project is developed as part of the requirements for a [software engineering course](//https://github.com/jce-il/se-class-materials) at the software engineering department - [Azrieli College of Engineering](http://www.jce.ac.il/), Jerusalem, Israel.
Please visit our wiki for furthur project info:
### [User Manual](https://github.com/chagitniss/nigun/wiki/User-Manual)
### [Team Page](https://github.com/chagitniss/nigun/wiki/Team)

### Project Documents
- [Project Idea](https://github.com/chagitniss/nigun/blob/master/%D7%A0%D7%99%D7%92%D7%95%D7%9F.pptx)
- [Project Inception & Planing](https://github.com/chagitniss/nigun/wiki/Inception---Planing)
- [Software Requirements Specification](https://github.com/chagitniss/nigun/wiki/SRS)
- [Software Design Specification](https://github.com/chagitniss/nigun/wiki/SDS)
### Iteration Pages
- [Iteration 0 - ZFR](https://github.com/chagitniss/nigun/wiki/ZFR)
- [Iteration 1 - MVP](https://github.com/chagitniss/nigun/wiki/Iteration-1-MVP)
- [Iteration 2](https://github.com/chagitniss/nigun/wiki/Iteration-2)
- [Iteration 3](https://github.com/chagitniss/nigun/wiki/Iteration-3)
- [Iteration 4](https://github.com/chagitniss/nigun/wiki/Iteration-4)
- [Iteration 5-final!!](https://github.com/chagitniss/nigun/wiki/Iteration-5---Final!!)
| chagitniss/nigun | README.md | Markdown | mit | 1,742 |
/////////////////////////////////////////////////////////////////////////////////
//
// Photoshop PSD FileType Plugin for Paint.NET
// http://psdplugin.codeplex.com/
//
// This software is provided under the MIT License:
// Copyright (c) 2006-2007 Frank Blumenberg
// Copyright (c) 2010-2014 Tao Yue
//
//
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
namespace Memoria.Prime.PsdFile
{
[DebuggerDisplay("Layer Info: { _key }")]
public class RawLayerInfo : LayerInfo
{
private String _signature;
public override String Signature
{
get { return _signature; }
}
private String _key;
public override String Key
{
get { return _key; }
}
public Byte[] Data { get; private set; }
public RawLayerInfo(String key, String signature = "8BIM")
{
_signature = signature;
_key = key;
}
public RawLayerInfo(PsdBinaryReader reader, String signature, String key,
Int64 dataLength)
{
_signature = signature;
_key = key;
Util.CheckByteArrayLength(dataLength);
Data = reader.ReadBytes((Int32)dataLength);
}
protected override void WriteData(PsdBinaryWriter writer)
{
writer.Write(Data);
}
}
}
| Albeoris/Memoria | Memoria.Prime/PsdFile/Layers/LayerInfo/RawLayerInfo.cs | C# | mit | 1,305 |
package pq
import (
"bufio"
"crypto/md5"
"crypto/tls"
"crypto/x509"
"database/sql"
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"unicode"
"github.com/the42/ogdat/Godeps/_workspace/src/github.com/lib/pq/oid"
)
// Common error types
var (
ErrNotSupported = errors.New("pq: Unsupported command")
ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction")
ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server")
ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less.")
ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly.")
)
type drv struct{}
func (d *drv) Open(name string) (driver.Conn, error) {
return Open(name)
}
func init() {
sql.Register("postgres", &drv{})
}
type parameterStatus struct {
// server version in the same format as server_version_num, or 0 if
// unavailable
serverVersion int
// the current location based on the TimeZone value of the session, if
// available
currentLocation *time.Location
}
type transactionStatus byte
const (
txnStatusIdle transactionStatus = 'I'
txnStatusIdleInTransaction transactionStatus = 'T'
txnStatusInFailedTransaction transactionStatus = 'E'
)
func (s transactionStatus) String() string {
switch s {
case txnStatusIdle:
return "idle"
case txnStatusIdleInTransaction:
return "idle in transaction"
case txnStatusInFailedTransaction:
return "in a failed transaction"
default:
errorf("unknown transactionStatus %d", s)
}
panic("not reached")
}
type Dialer interface {
Dial(network, address string) (net.Conn, error)
DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
}
type defaultDialer struct{}
func (d defaultDialer) Dial(ntw, addr string) (net.Conn, error) {
return net.Dial(ntw, addr)
}
func (d defaultDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout(ntw, addr, timeout)
}
type conn struct {
c net.Conn
buf *bufio.Reader
namei int
scratch [512]byte
txnStatus transactionStatus
parameterStatus parameterStatus
saveMessageType byte
saveMessageBuffer []byte
// If true, this connection is bad and all public-facing functions should
// return ErrBadConn.
bad bool
// If set, this connection should never use the binary format when
// receiving query results from prepared statements. Only provided for
// debugging.
disablePreparedBinaryResult bool
// Whether to always send []byte parameters over as binary. Enables single
// round-trip mode for non-prepared Query calls.
binaryParameters bool
}
// Handle driver-side settings in parsed connection string.
func (c *conn) handleDriverSettings(o values) (err error) {
boolSetting := func(key string, val *bool) error {
if value := o.Get(key); value != "" {
if value == "yes" {
*val = true
} else if value == "no" {
*val = false
} else {
return fmt.Errorf("unrecognized value %q for %s", value, key)
}
}
return nil
}
err = boolSetting("disable_prepared_binary_result", &c.disablePreparedBinaryResult)
if err != nil {
return err
}
err = boolSetting("binary_parameters", &c.binaryParameters)
if err != nil {
return err
}
return nil
}
func (c *conn) writeBuf(b byte) *writeBuf {
c.scratch[0] = b
return &writeBuf{
buf: c.scratch[:5],
pos: 1,
}
}
func Open(name string) (_ driver.Conn, err error) {
return DialOpen(defaultDialer{}, name)
}
func DialOpen(d Dialer, name string) (_ driver.Conn, err error) {
// Handle any panics during connection initialization. Note that we
// specifically do *not* want to use errRecover(), as that would turn any
// connection errors into ErrBadConns, hiding the real error message from
// the user.
defer errRecoverNoErrBadConn(&err)
o := make(values)
// A number of defaults are applied here, in this order:
//
// * Very low precedence defaults applied in every situation
// * Environment variables
// * Explicitly passed connection information
o.Set("host", "localhost")
o.Set("port", "5432")
// N.B.: Extra float digits should be set to 3, but that breaks
// Postgres 8.4 and older, where the max is 2.
o.Set("extra_float_digits", "2")
for k, v := range parseEnviron(os.Environ()) {
o.Set(k, v)
}
if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") {
name, err = ParseURL(name)
if err != nil {
return nil, err
}
}
if err := parseOpts(name, o); err != nil {
return nil, err
}
// Use the "fallback" application name if necessary
if fallback := o.Get("fallback_application_name"); fallback != "" {
if !o.Isset("application_name") {
o.Set("application_name", fallback)
}
}
// We can't work with any client_encoding other than UTF-8 currently.
// However, we have historically allowed the user to set it to UTF-8
// explicitly, and there's no reason to break such programs, so allow that.
// Note that the "options" setting could also set client_encoding, but
// parsing its value is not worth it. Instead, we always explicitly send
// client_encoding as a separate run-time parameter, which should override
// anything set in options.
if enc := o.Get("client_encoding"); enc != "" && !isUTF8(enc) {
return nil, errors.New("client_encoding must be absent or 'UTF8'")
}
o.Set("client_encoding", "UTF8")
// DateStyle needs a similar treatment.
if datestyle := o.Get("datestyle"); datestyle != "" {
if datestyle != "ISO, MDY" {
panic(fmt.Sprintf("setting datestyle must be absent or %v; got %v",
"ISO, MDY", datestyle))
}
} else {
o.Set("datestyle", "ISO, MDY")
}
// If a user is not provided by any other means, the last
// resort is to use the current operating system provided user
// name.
if o.Get("user") == "" {
u, err := userCurrent()
if err != nil {
return nil, err
} else {
o.Set("user", u)
}
}
cn := &conn{}
err = cn.handleDriverSettings(o)
if err != nil {
return nil, err
}
cn.c, err = dial(d, o)
if err != nil {
return nil, err
}
cn.ssl(o)
cn.buf = bufio.NewReader(cn.c)
cn.startup(o)
// reset the deadline, in case one was set (see dial)
if timeout := o.Get("connect_timeout"); timeout != "" && timeout != "0" {
err = cn.c.SetDeadline(time.Time{})
}
return cn, err
}
func dial(d Dialer, o values) (net.Conn, error) {
ntw, addr := network(o)
// SSL is not necessary or supported over UNIX domain sockets
if ntw == "unix" {
o["sslmode"] = "disable"
}
// Zero or not specified means wait indefinitely.
if timeout := o.Get("connect_timeout"); timeout != "" && timeout != "0" {
seconds, err := strconv.ParseInt(timeout, 10, 0)
if err != nil {
return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err)
}
duration := time.Duration(seconds) * time.Second
// connect_timeout should apply to the entire connection establishment
// procedure, so we both use a timeout for the TCP connection
// establishment and set a deadline for doing the initial handshake.
// The deadline is then reset after startup() is done.
deadline := time.Now().Add(duration)
conn, err := d.DialTimeout(ntw, addr, duration)
if err != nil {
return nil, err
}
err = conn.SetDeadline(deadline)
return conn, err
}
return d.Dial(ntw, addr)
}
func network(o values) (string, string) {
host := o.Get("host")
if strings.HasPrefix(host, "/") {
sockPath := path.Join(host, ".s.PGSQL."+o.Get("port"))
return "unix", sockPath
}
return "tcp", host + ":" + o.Get("port")
}
type values map[string]string
func (vs values) Set(k, v string) {
vs[k] = v
}
func (vs values) Get(k string) (v string) {
return vs[k]
}
func (vs values) Isset(k string) bool {
_, ok := vs[k]
return ok
}
// scanner implements a tokenizer for libpq-style option strings.
type scanner struct {
s []rune
i int
}
// newScanner returns a new scanner initialized with the option string s.
func newScanner(s string) *scanner {
return &scanner{[]rune(s), 0}
}
// Next returns the next rune.
// It returns 0, false if the end of the text has been reached.
func (s *scanner) Next() (rune, bool) {
if s.i >= len(s.s) {
return 0, false
}
r := s.s[s.i]
s.i++
return r, true
}
// SkipSpaces returns the next non-whitespace rune.
// It returns 0, false if the end of the text has been reached.
func (s *scanner) SkipSpaces() (rune, bool) {
r, ok := s.Next()
for unicode.IsSpace(r) && ok {
r, ok = s.Next()
}
return r, ok
}
// parseOpts parses the options from name and adds them to the values.
//
// The parsing code is based on conninfo_parse from libpq's fe-connect.c
func parseOpts(name string, o values) error {
s := newScanner(name)
for {
var (
keyRunes, valRunes []rune
r rune
ok bool
)
if r, ok = s.SkipSpaces(); !ok {
break
}
// Scan the key
for !unicode.IsSpace(r) && r != '=' {
keyRunes = append(keyRunes, r)
if r, ok = s.Next(); !ok {
break
}
}
// Skip any whitespace if we're not at the = yet
if r != '=' {
r, ok = s.SkipSpaces()
}
// The current character should be =
if r != '=' || !ok {
return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes))
}
// Skip any whitespace after the =
if r, ok = s.SkipSpaces(); !ok {
// If we reach the end here, the last value is just an empty string as per libpq.
o.Set(string(keyRunes), "")
break
}
if r != '\'' {
for !unicode.IsSpace(r) {
if r == '\\' {
if r, ok = s.Next(); !ok {
return fmt.Errorf(`missing character after backslash`)
}
}
valRunes = append(valRunes, r)
if r, ok = s.Next(); !ok {
break
}
}
} else {
quote:
for {
if r, ok = s.Next(); !ok {
return fmt.Errorf(`unterminated quoted string literal in connection string`)
}
switch r {
case '\'':
break quote
case '\\':
r, _ = s.Next()
fallthrough
default:
valRunes = append(valRunes, r)
}
}
}
o.Set(string(keyRunes), string(valRunes))
}
return nil
}
func (cn *conn) isInTransaction() bool {
return cn.txnStatus == txnStatusIdleInTransaction ||
cn.txnStatus == txnStatusInFailedTransaction
}
func (cn *conn) checkIsInTransaction(intxn bool) {
if cn.isInTransaction() != intxn {
cn.bad = true
errorf("unexpected transaction status %v", cn.txnStatus)
}
}
func (cn *conn) Begin() (_ driver.Tx, err error) {
if cn.bad {
return nil, driver.ErrBadConn
}
defer cn.errRecover(&err)
cn.checkIsInTransaction(false)
_, commandTag, err := cn.simpleExec("BEGIN")
if err != nil {
return nil, err
}
if commandTag != "BEGIN" {
cn.bad = true
return nil, fmt.Errorf("unexpected command tag %s", commandTag)
}
if cn.txnStatus != txnStatusIdleInTransaction {
cn.bad = true
return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus)
}
return cn, nil
}
func (cn *conn) Commit() (err error) {
if cn.bad {
return driver.ErrBadConn
}
defer cn.errRecover(&err)
cn.checkIsInTransaction(true)
// We don't want the client to think that everything is okay if it tries
// to commit a failed transaction. However, no matter what we return,
// database/sql will release this connection back into the free connection
// pool so we have to abort the current transaction here. Note that you
// would get the same behaviour if you issued a COMMIT in a failed
// transaction, so it's also the least surprising thing to do here.
if cn.txnStatus == txnStatusInFailedTransaction {
if err := cn.Rollback(); err != nil {
return err
}
return ErrInFailedTransaction
}
_, commandTag, err := cn.simpleExec("COMMIT")
if err != nil {
if cn.isInTransaction() {
cn.bad = true
}
return err
}
if commandTag != "COMMIT" {
cn.bad = true
return fmt.Errorf("unexpected command tag %s", commandTag)
}
cn.checkIsInTransaction(false)
return nil
}
func (cn *conn) Rollback() (err error) {
if cn.bad {
return driver.ErrBadConn
}
defer cn.errRecover(&err)
cn.checkIsInTransaction(true)
_, commandTag, err := cn.simpleExec("ROLLBACK")
if err != nil {
if cn.isInTransaction() {
cn.bad = true
}
return err
}
if commandTag != "ROLLBACK" {
return fmt.Errorf("unexpected command tag %s", commandTag)
}
cn.checkIsInTransaction(false)
return nil
}
func (cn *conn) gname() string {
cn.namei++
return strconv.FormatInt(int64(cn.namei), 10)
}
func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) {
b := cn.writeBuf('Q')
b.string(q)
cn.send(b)
for {
t, r := cn.recv1()
switch t {
case 'C':
res, commandTag = cn.parseComplete(r.string())
case 'Z':
cn.processReadyForQuery(r)
// done
return
case 'E':
err = parseError(r)
case 'T', 'D', 'I':
// ignore any results
default:
cn.bad = true
errorf("unknown response for simple query: %q", t)
}
}
}
func (cn *conn) simpleQuery(q string) (res *rows, err error) {
defer cn.errRecover(&err)
st := &stmt{cn: cn, name: ""}
b := cn.writeBuf('Q')
b.string(q)
cn.send(b)
for {
t, r := cn.recv1()
switch t {
case 'C', 'I':
// We allow queries which don't return any results through Query as
// well as Exec. We still have to give database/sql a rows object
// the user can close, though, to avoid connections from being
// leaked. A "rows" with done=true works fine for that purpose.
if err != nil {
cn.bad = true
errorf("unexpected message %q in simple query execution", t)
}
res = &rows{
cn: cn,
colNames: st.colNames,
colTyps: st.colTyps,
colFmts: st.colFmts,
done: true,
}
case 'Z':
cn.processReadyForQuery(r)
// done
return
case 'E':
res = nil
err = parseError(r)
case 'D':
if res == nil {
cn.bad = true
errorf("unexpected DataRow in simple query execution")
}
// the query didn't fail; kick off to Next
cn.saveMessage(t, r)
return
case 'T':
// res might be non-nil here if we received a previous
// CommandComplete, but that's fine; just overwrite it
res = &rows{cn: cn}
res.colNames, res.colFmts, res.colTyps = parsePortalRowDescribe(r)
// To work around a bug in QueryRow in Go 1.2 and earlier, wait
// until the first DataRow has been received.
default:
cn.bad = true
errorf("unknown response for simple query: %q", t)
}
}
}
// Decides which column formats to use for a prepared statement. The input is
// an array of type oids, one element per result column.
func decideColumnFormats(colTyps []oid.Oid, forceText bool) (colFmts []format, colFmtData []byte) {
if len(colTyps) == 0 {
return nil, colFmtDataAllText
}
colFmts = make([]format, len(colTyps))
if forceText {
return colFmts, colFmtDataAllText
}
allBinary := true
allText := true
for i, o := range colTyps {
switch o {
// This is the list of types to use binary mode for when receiving them
// through a prepared statement. If a type appears in this list, it
// must also be implemented in binaryDecode in encode.go.
case oid.T_bytea:
fallthrough
case oid.T_int8:
fallthrough
case oid.T_int4:
fallthrough
case oid.T_int2:
colFmts[i] = formatBinary
allText = false
default:
allBinary = false
}
}
if allBinary {
return colFmts, colFmtDataAllBinary
} else if allText {
return colFmts, colFmtDataAllText
} else {
colFmtData = make([]byte, 2+len(colFmts)*2)
binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts)))
for i, v := range colFmts {
binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v))
}
return colFmts, colFmtData
}
}
func (cn *conn) prepareTo(q, stmtName string) *stmt {
st := &stmt{cn: cn, name: stmtName}
b := cn.writeBuf('P')
b.string(st.name)
b.string(q)
b.int16(0)
b.next('D')
b.byte('S')
b.string(st.name)
b.next('S')
cn.send(b)
cn.readParseResponse()
st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse()
st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult)
cn.readReadyForQuery()
return st
}
func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) {
if cn.bad {
return nil, driver.ErrBadConn
}
defer cn.errRecover(&err)
if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") {
return cn.prepareCopyIn(q)
}
return cn.prepareTo(q, cn.gname()), nil
}
func (cn *conn) Close() (err error) {
if cn.bad {
return driver.ErrBadConn
}
defer cn.errRecover(&err)
// Don't go through send(); ListenerConn relies on us not scribbling on the
// scratch buffer of this connection.
err = cn.sendSimpleMessage('X')
if err != nil {
return err
}
return cn.c.Close()
}
// Implement the "Queryer" interface
func (cn *conn) Query(query string, args []driver.Value) (_ driver.Rows, err error) {
if cn.bad {
return nil, driver.ErrBadConn
}
defer cn.errRecover(&err)
// Check to see if we can use the "simpleQuery" interface, which is
// *much* faster than going through prepare/exec
if len(args) == 0 {
return cn.simpleQuery(query)
}
if cn.binaryParameters {
cn.sendBinaryModeQuery(query, args)
cn.readParseResponse()
cn.readBindResponse()
rows := &rows{cn: cn}
rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse()
cn.postExecuteWorkaround()
return rows, nil
} else {
st := cn.prepareTo(query, "")
st.exec(args)
return &rows{
cn: cn,
colNames: st.colNames,
colTyps: st.colTyps,
colFmts: st.colFmts,
}, nil
}
}
// Implement the optional "Execer" interface for one-shot queries
func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) {
if cn.bad {
return nil, driver.ErrBadConn
}
defer cn.errRecover(&err)
// Check to see if we can use the "simpleExec" interface, which is
// *much* faster than going through prepare/exec
if len(args) == 0 {
// ignore commandTag, our caller doesn't care
r, _, err := cn.simpleExec(query)
return r, err
}
if cn.binaryParameters {
cn.sendBinaryModeQuery(query, args)
cn.readParseResponse()
cn.readBindResponse()
cn.readPortalDescribeResponse()
cn.postExecuteWorkaround()
res, _, err = cn.readExecuteResponse("Execute")
return res, err
} else {
// Use the unnamed statement to defer planning until bind
// time, or else value-based selectivity estimates cannot be
// used.
st := cn.prepareTo(query, "")
r, err := st.Exec(args)
if err != nil {
panic(err)
}
return r, err
}
}
func (cn *conn) send(m *writeBuf) {
_, err := cn.c.Write(m.wrap())
if err != nil {
panic(err)
}
}
func (cn *conn) sendStartupPacket(m *writeBuf) {
// sanity check
if m.buf[0] != 0 {
panic("oops")
}
_, err := cn.c.Write((m.wrap())[1:])
if err != nil {
panic(err)
}
}
// Send a message of type typ to the server on the other end of cn. The
// message should have no payload. This method does not use the scratch
// buffer.
func (cn *conn) sendSimpleMessage(typ byte) (err error) {
_, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'})
return err
}
// saveMessage memorizes a message and its buffer in the conn struct.
// recvMessage will then return these values on the next call to it. This
// method is useful in cases where you have to see what the next message is
// going to be (e.g. to see whether it's an error or not) but you can't handle
// the message yourself.
func (cn *conn) saveMessage(typ byte, buf *readBuf) {
if cn.saveMessageType != 0 {
cn.bad = true
errorf("unexpected saveMessageType %d", cn.saveMessageType)
}
cn.saveMessageType = typ
cn.saveMessageBuffer = *buf
}
// recvMessage receives any message from the backend, or returns an error if
// a problem occurred while reading the message.
func (cn *conn) recvMessage(r *readBuf) (byte, error) {
// workaround for a QueryRow bug, see exec
if cn.saveMessageType != 0 {
t := cn.saveMessageType
*r = cn.saveMessageBuffer
cn.saveMessageType = 0
cn.saveMessageBuffer = nil
return t, nil
}
x := cn.scratch[:5]
_, err := io.ReadFull(cn.buf, x)
if err != nil {
return 0, err
}
// read the type and length of the message that follows
t := x[0]
n := int(binary.BigEndian.Uint32(x[1:])) - 4
var y []byte
if n <= len(cn.scratch) {
y = cn.scratch[:n]
} else {
y = make([]byte, n)
}
_, err = io.ReadFull(cn.buf, y)
if err != nil {
return 0, err
}
*r = y
return t, nil
}
// recv receives a message from the backend, but if an error happened while
// reading the message or the received message was an ErrorResponse, it panics.
// NoticeResponses are ignored. This function should generally be used only
// during the startup sequence.
func (cn *conn) recv() (t byte, r *readBuf) {
for {
var err error
r = &readBuf{}
t, err = cn.recvMessage(r)
if err != nil {
panic(err)
}
switch t {
case 'E':
panic(parseError(r))
case 'N':
// ignore
default:
return
}
}
}
// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by
// the caller to avoid an allocation.
func (cn *conn) recv1Buf(r *readBuf) byte {
for {
t, err := cn.recvMessage(r)
if err != nil {
panic(err)
}
switch t {
case 'A', 'N':
// ignore
case 'S':
cn.processParameterStatus(r)
default:
return t
}
}
}
// recv1 receives a message from the backend, panicking if an error occurs
// while attempting to read it. All asynchronous messages are ignored, with
// the exception of ErrorResponse.
func (cn *conn) recv1() (t byte, r *readBuf) {
r = &readBuf{}
t = cn.recv1Buf(r)
return t, r
}
func (cn *conn) ssl(o values) {
verifyCaOnly := false
tlsConf := tls.Config{}
switch mode := o.Get("sslmode"); mode {
case "require", "":
tlsConf.InsecureSkipVerify = true
case "verify-ca":
// We must skip TLS's own verification since it requires full
// verification since Go 1.3.
tlsConf.InsecureSkipVerify = true
verifyCaOnly = true
case "verify-full":
tlsConf.ServerName = o.Get("host")
case "disable":
return
default:
errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode)
}
cn.setupSSLClientCertificates(&tlsConf, o)
cn.setupSSLCA(&tlsConf, o)
w := cn.writeBuf(0)
w.int32(80877103)
cn.sendStartupPacket(w)
b := cn.scratch[:1]
_, err := io.ReadFull(cn.c, b)
if err != nil {
panic(err)
}
if b[0] != 'S' {
panic(ErrSSLNotSupported)
}
client := tls.Client(cn.c, &tlsConf)
if verifyCaOnly {
cn.verifyCA(client, &tlsConf)
}
cn.c = client
}
// verifyCA carries out a TLS handshake to the server and verifies the
// presented certificate against the effective CA, i.e. the one specified in
// sslrootcert or the system CA if sslrootcert was not specified.
func (cn *conn) verifyCA(client *tls.Conn, tlsConf *tls.Config) {
err := client.Handshake()
if err != nil {
panic(err)
}
certs := client.ConnectionState().PeerCertificates
opts := x509.VerifyOptions{
DNSName: client.ConnectionState().ServerName,
Intermediates: x509.NewCertPool(),
Roots: tlsConf.RootCAs,
}
for i, cert := range certs {
if i == 0 {
continue
}
opts.Intermediates.AddCert(cert)
}
_, err = certs[0].Verify(opts)
if err != nil {
panic(err)
}
}
// This function sets up SSL client certificates based on either the "sslkey"
// and "sslcert" settings (possibly set via the environment variables PGSSLKEY
// and PGSSLCERT, respectively), or if they aren't set, from the .postgresql
// directory in the user's home directory. If the file paths are set
// explicitly, the files must exist. The key file must also not be
// world-readable, or this function will panic with
// ErrSSLKeyHasWorldPermissions.
func (cn *conn) setupSSLClientCertificates(tlsConf *tls.Config, o values) {
var missingOk bool
sslkey := o.Get("sslkey")
sslcert := o.Get("sslcert")
if sslkey != "" && sslcert != "" {
// If the user has set an sslkey and sslcert, they *must* exist.
missingOk = false
} else {
// Automatically load certificates from ~/.postgresql.
user, err := user.Current()
if err != nil {
// user.Current() might fail when cross-compiling. We have to
// ignore the error and continue without client certificates, since
// we wouldn't know where to load them from.
return
}
sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
missingOk = true
}
// Check that both files exist, and report the error or stop, depending on
// which behaviour we want. Note that we don't do any more extensive
// checks than this (such as checking that the paths aren't directories);
// LoadX509KeyPair() will take care of the rest.
keyfinfo, err := os.Stat(sslkey)
if err != nil && missingOk {
return
} else if err != nil {
panic(err)
}
_, err = os.Stat(sslcert)
if err != nil && missingOk {
return
} else if err != nil {
panic(err)
}
// If we got this far, the key file must also have the correct permissions
kmode := keyfinfo.Mode()
if kmode != kmode&0600 {
panic(ErrSSLKeyHasWorldPermissions)
}
cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
if err != nil {
panic(err)
}
tlsConf.Certificates = []tls.Certificate{cert}
}
// Sets up RootCAs in the TLS configuration if sslrootcert is set.
func (cn *conn) setupSSLCA(tlsConf *tls.Config, o values) {
if sslrootcert := o.Get("sslrootcert"); sslrootcert != "" {
tlsConf.RootCAs = x509.NewCertPool()
cert, err := ioutil.ReadFile(sslrootcert)
if err != nil {
panic(err)
}
ok := tlsConf.RootCAs.AppendCertsFromPEM(cert)
if !ok {
errorf("couldn't parse pem in sslrootcert")
}
}
}
// isDriverSetting returns true iff a setting is purely for configuring the
// driver's options and should not be sent to the server in the connection
// startup packet.
func isDriverSetting(key string) bool {
switch key {
case "host", "port":
return true
case "password":
return true
case "sslmode", "sslcert", "sslkey", "sslrootcert":
return true
case "fallback_application_name":
return true
case "connect_timeout":
return true
case "disable_prepared_binary_result":
return true
case "binary_parameters":
return true
default:
return false
}
}
func (cn *conn) startup(o values) {
w := cn.writeBuf(0)
w.int32(196608)
// Send the backend the name of the database we want to connect to, and the
// user we want to connect as. Additionally, we send over any run-time
// parameters potentially included in the connection string. If the server
// doesn't recognize any of them, it will reply with an error.
for k, v := range o {
if isDriverSetting(k) {
// skip options which can't be run-time parameters
continue
}
// The protocol requires us to supply the database name as "database"
// instead of "dbname".
if k == "dbname" {
k = "database"
}
w.string(k)
w.string(v)
}
w.string("")
cn.sendStartupPacket(w)
for {
t, r := cn.recv()
switch t {
case 'K':
case 'S':
cn.processParameterStatus(r)
case 'R':
cn.auth(r, o)
case 'Z':
cn.processReadyForQuery(r)
return
default:
errorf("unknown response for startup: %q", t)
}
}
}
func (cn *conn) auth(r *readBuf, o values) {
switch code := r.int32(); code {
case 0:
// OK
case 3:
w := cn.writeBuf('p')
w.string(o.Get("password"))
cn.send(w)
t, r := cn.recv()
if t != 'R' {
errorf("unexpected password response: %q", t)
}
if r.int32() != 0 {
errorf("unexpected authentication response: %q", t)
}
case 5:
s := string(r.next(4))
w := cn.writeBuf('p')
w.string("md5" + md5s(md5s(o.Get("password")+o.Get("user"))+s))
cn.send(w)
t, r := cn.recv()
if t != 'R' {
errorf("unexpected password response: %q", t)
}
if r.int32() != 0 {
errorf("unexpected authentication response: %q", t)
}
default:
errorf("unknown authentication response: %d", code)
}
}
type format int
const formatText format = 0
const formatBinary format = 1
// One result-column format code with the value 1 (i.e. all binary).
var colFmtDataAllBinary []byte = []byte{0, 1, 0, 1}
// No result-column format codes (i.e. all text).
var colFmtDataAllText []byte = []byte{0, 0}
type stmt struct {
cn *conn
name string
colNames []string
colFmts []format
colFmtData []byte
colTyps []oid.Oid
paramTyps []oid.Oid
closed bool
}
func (st *stmt) Close() (err error) {
if st.closed {
return nil
}
if st.cn.bad {
return driver.ErrBadConn
}
defer st.cn.errRecover(&err)
w := st.cn.writeBuf('C')
w.byte('S')
w.string(st.name)
st.cn.send(w)
st.cn.send(st.cn.writeBuf('S'))
t, _ := st.cn.recv1()
if t != '3' {
st.cn.bad = true
errorf("unexpected close response: %q", t)
}
st.closed = true
t, r := st.cn.recv1()
if t != 'Z' {
st.cn.bad = true
errorf("expected ready for query, but got: %q", t)
}
st.cn.processReadyForQuery(r)
return nil
}
func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) {
if st.cn.bad {
return nil, driver.ErrBadConn
}
defer st.cn.errRecover(&err)
st.exec(v)
return &rows{
cn: st.cn,
colNames: st.colNames,
colTyps: st.colTyps,
colFmts: st.colFmts,
}, nil
}
func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) {
if st.cn.bad {
return nil, driver.ErrBadConn
}
defer st.cn.errRecover(&err)
st.exec(v)
res, _, err = st.cn.readExecuteResponse("simple query")
return res, err
}
func (st *stmt) exec(v []driver.Value) {
if len(v) >= 65536 {
errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v))
}
if len(v) != len(st.paramTyps) {
errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps))
}
cn := st.cn
w := cn.writeBuf('B')
w.byte(0) // unnamed portal
w.string(st.name)
if cn.binaryParameters {
cn.sendBinaryParameters(w, v)
} else {
w.int16(0)
w.int16(len(v))
for i, x := range v {
if x == nil {
w.int32(-1)
} else {
b := encode(&cn.parameterStatus, x, st.paramTyps[i])
w.int32(len(b))
w.bytes(b)
}
}
}
w.bytes(st.colFmtData)
w.next('E')
w.byte(0)
w.int32(0)
w.next('S')
cn.send(w)
cn.readBindResponse()
cn.postExecuteWorkaround()
}
func (st *stmt) NumInput() int {
return len(st.paramTyps)
}
// parseComplete parses the "command tag" from a CommandComplete message, and
// returns the number of rows affected (if applicable) and a string
// identifying only the command that was executed, e.g. "ALTER TABLE". If the
// command tag could not be parsed, parseComplete panics.
func (cn *conn) parseComplete(commandTag string) (driver.Result, string) {
commandsWithAffectedRows := []string{
"SELECT ",
// INSERT is handled below
"UPDATE ",
"DELETE ",
"FETCH ",
"MOVE ",
"COPY ",
}
var affectedRows *string
for _, tag := range commandsWithAffectedRows {
if strings.HasPrefix(commandTag, tag) {
t := commandTag[len(tag):]
affectedRows = &t
commandTag = tag[:len(tag)-1]
break
}
}
// INSERT also includes the oid of the inserted row in its command tag.
// Oids in user tables are deprecated, and the oid is only returned when
// exactly one row is inserted, so it's unlikely to be of value to any
// real-world application and we can ignore it.
if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") {
parts := strings.Split(commandTag, " ")
if len(parts) != 3 {
cn.bad = true
errorf("unexpected INSERT command tag %s", commandTag)
}
affectedRows = &parts[len(parts)-1]
commandTag = "INSERT"
}
// There should be no affected rows attached to the tag, just return it
if affectedRows == nil {
return driver.RowsAffected(0), commandTag
}
n, err := strconv.ParseInt(*affectedRows, 10, 64)
if err != nil {
cn.bad = true
errorf("could not parse commandTag: %s", err)
}
return driver.RowsAffected(n), commandTag
}
type rows struct {
cn *conn
colNames []string
colTyps []oid.Oid
colFmts []format
done bool
rb readBuf
}
func (rs *rows) Close() error {
// no need to look at cn.bad as Next() will
for {
err := rs.Next(nil)
switch err {
case nil:
case io.EOF:
return nil
default:
return err
}
}
}
func (rs *rows) Columns() []string {
return rs.colNames
}
func (rs *rows) Next(dest []driver.Value) (err error) {
if rs.done {
return io.EOF
}
conn := rs.cn
if conn.bad {
return driver.ErrBadConn
}
defer conn.errRecover(&err)
for {
t := conn.recv1Buf(&rs.rb)
switch t {
case 'E':
err = parseError(&rs.rb)
case 'C', 'I':
continue
case 'Z':
conn.processReadyForQuery(&rs.rb)
rs.done = true
if err != nil {
return err
}
return io.EOF
case 'D':
n := rs.rb.int16()
if err != nil {
conn.bad = true
errorf("unexpected DataRow after error %s", err)
}
if n < len(dest) {
dest = dest[:n]
}
for i := range dest {
l := rs.rb.int32()
if l == -1 {
dest[i] = nil
continue
}
dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i], rs.colFmts[i])
}
return
default:
errorf("unexpected message after execute: %q", t)
}
}
}
// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be
// used as part of an SQL statement. For example:
//
// tblname := "my_table"
// data := "my_data"
// err = db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", pq.QuoteIdentifier(tblname)), data)
//
// Any double quotes in name will be escaped. The quoted identifier will be
// case sensitive when used in a query. If the input string contains a zero
// byte, the result will be truncated immediately before it.
func QuoteIdentifier(name string) string {
end := strings.IndexRune(name, 0)
if end > -1 {
name = name[:end]
}
return `"` + strings.Replace(name, `"`, `""`, -1) + `"`
}
func md5s(s string) string {
h := md5.New()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil))
}
func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) {
// Do one pass over the parameters to see if we're going to send any of
// them over in binary. If we are, create a paramFormats array at the
// same time.
var paramFormats []int
for i, x := range args {
_, ok := x.([]byte)
if ok {
if paramFormats == nil {
paramFormats = make([]int, len(args))
}
paramFormats[i] = 1
}
}
if paramFormats == nil {
b.int16(0)
} else {
b.int16(len(paramFormats))
for _, x := range paramFormats {
b.int16(x)
}
}
b.int16(len(args))
for _, x := range args {
if x == nil {
b.int32(-1)
} else {
datum := binaryEncode(&cn.parameterStatus, x)
b.int32(len(datum))
b.bytes(datum)
}
}
}
func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) {
if len(args) >= 65536 {
errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args))
}
b := cn.writeBuf('P')
b.byte(0) // unnamed statement
b.string(query)
b.int16(0)
b.next('B')
b.int16(0) // unnamed portal and statement
cn.sendBinaryParameters(b, args)
b.bytes(colFmtDataAllText)
b.next('D')
b.byte('P')
b.byte(0) // unnamed portal
b.next('E')
b.byte(0)
b.int32(0)
b.next('S')
cn.send(b)
}
func (c *conn) processParameterStatus(r *readBuf) {
var err error
param := r.string()
switch param {
case "server_version":
var major1 int
var major2 int
var minor int
_, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor)
if err == nil {
c.parameterStatus.serverVersion = major1*10000 + major2*100 + minor
}
case "TimeZone":
c.parameterStatus.currentLocation, err = time.LoadLocation(r.string())
if err != nil {
c.parameterStatus.currentLocation = nil
}
default:
// ignore
}
}
func (c *conn) processReadyForQuery(r *readBuf) {
c.txnStatus = transactionStatus(r.byte())
}
func (cn *conn) readReadyForQuery() {
t, r := cn.recv1()
switch t {
case 'Z':
cn.processReadyForQuery(r)
return
default:
cn.bad = true
errorf("unexpected message %q; expected ReadyForQuery", t)
}
}
func (cn *conn) readParseResponse() {
t, r := cn.recv1()
switch t {
case '1':
return
case 'E':
err := parseError(r)
cn.readReadyForQuery()
panic(err)
default:
cn.bad = true
errorf("unexpected Parse response %q", t)
}
}
func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []oid.Oid) {
for {
t, r := cn.recv1()
switch t {
case 't':
nparams := r.int16()
paramTyps = make([]oid.Oid, nparams)
for i := range paramTyps {
paramTyps[i] = r.oid()
}
case 'n':
return paramTyps, nil, nil
case 'T':
colNames, colTyps = parseStatementRowDescribe(r)
return paramTyps, colNames, colTyps
case 'E':
err := parseError(r)
cn.readReadyForQuery()
panic(err)
default:
cn.bad = true
errorf("unexpected Describe statement response %q", t)
}
}
}
func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []oid.Oid) {
t, r := cn.recv1()
switch t {
case 'T':
return parsePortalRowDescribe(r)
case 'n':
return nil, nil, nil
case 'E':
err := parseError(r)
cn.readReadyForQuery()
panic(err)
default:
cn.bad = true
errorf("unexpected Describe response %q", t)
}
panic("not reached")
}
func (cn *conn) readBindResponse() {
t, r := cn.recv1()
switch t {
case '2':
return
case 'E':
err := parseError(r)
cn.readReadyForQuery()
panic(err)
default:
cn.bad = true
errorf("unexpected Bind response %q", t)
}
}
func (cn *conn) postExecuteWorkaround() {
// Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores
// any errors from rows.Next, which masks errors that happened during the
// execution of the query. To avoid the problem in common cases, we wait
// here for one more message from the database. If it's not an error the
// query will likely succeed (or perhaps has already, if it's a
// CommandComplete), so we push the message into the conn struct; recv1
// will return it as the next message for rows.Next or rows.Close.
// However, if it's an error, we wait until ReadyForQuery and then return
// the error to our caller.
for {
t, r := cn.recv1()
switch t {
case 'E':
err := parseError(r)
cn.readReadyForQuery()
panic(err)
case 'C', 'D', 'I':
// the query didn't fail, but we can't process this message
cn.saveMessage(t, r)
return
default:
cn.bad = true
errorf("unexpected message during extended query execution: %q", t)
}
}
}
// Only for Exec(), since we ignore the returned data
func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) {
for {
t, r := cn.recv1()
switch t {
case 'C':
res, commandTag = cn.parseComplete(r.string())
case 'Z':
cn.processReadyForQuery(r)
return res, commandTag, err
case 'E':
err = parseError(r)
case 'T', 'D', 'I':
// ignore any results
default:
cn.bad = true
errorf("unknown %s response: %q", protocolState, t)
}
}
}
func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []oid.Oid) {
n := r.int16()
colNames = make([]string, n)
colTyps = make([]oid.Oid, n)
for i := range colNames {
colNames[i] = r.string()
r.next(6)
colTyps[i] = r.oid()
r.next(6)
// format code not known when describing a statement; always 0
r.next(2)
}
return
}
func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []oid.Oid) {
n := r.int16()
colNames = make([]string, n)
colFmts = make([]format, n)
colTyps = make([]oid.Oid, n)
for i := range colNames {
colNames[i] = r.string()
r.next(6)
colTyps[i] = r.oid()
r.next(6)
colFmts[i] = format(r.int16())
}
return
}
// parseEnviron tries to mimic some of libpq's environment handling
//
// To ease testing, it does not directly reference os.Environ, but is
// designed to accept its output.
//
// Environment-set connection information is intended to have a higher
// precedence than a library default but lower than any explicitly
// passed information (such as in the URL or connection string).
func parseEnviron(env []string) (out map[string]string) {
out = make(map[string]string)
for _, v := range env {
parts := strings.SplitN(v, "=", 2)
accrue := func(keyname string) {
out[keyname] = parts[1]
}
unsupported := func() {
panic(fmt.Sprintf("setting %v not supported", parts[0]))
}
// The order of these is the same as is seen in the
// PostgreSQL 9.1 manual. Unsupported but well-defined
// keys cause a panic; these should be unset prior to
// execution. Options which pq expects to be set to a
// certain value are allowed, but must be set to that
// value if present (they can, of course, be absent).
switch parts[0] {
case "PGHOST":
accrue("host")
case "PGHOSTADDR":
unsupported()
case "PGPORT":
accrue("port")
case "PGDATABASE":
accrue("dbname")
case "PGUSER":
accrue("user")
case "PGPASSWORD":
accrue("password")
case "PGPASSFILE", "PGSERVICE", "PGSERVICEFILE", "PGREALM":
unsupported()
case "PGOPTIONS":
accrue("options")
case "PGAPPNAME":
accrue("application_name")
case "PGSSLMODE":
accrue("sslmode")
case "PGSSLCERT":
accrue("sslcert")
case "PGSSLKEY":
accrue("sslkey")
case "PGSSLROOTCERT":
accrue("sslrootcert")
case "PGREQUIRESSL", "PGSSLCRL":
unsupported()
case "PGREQUIREPEER":
unsupported()
case "PGKRBSRVNAME", "PGGSSLIB":
unsupported()
case "PGCONNECT_TIMEOUT":
accrue("connect_timeout")
case "PGCLIENTENCODING":
accrue("client_encoding")
case "PGDATESTYLE":
accrue("datestyle")
case "PGTZ":
accrue("timezone")
case "PGGEQO":
accrue("geqo")
case "PGSYSCONFDIR", "PGLOCALEDIR":
unsupported()
}
}
return out
}
// isUTF8 returns whether name is a fuzzy variation of the string "UTF-8".
func isUTF8(name string) bool {
// Recognize all sorts of silly things as "UTF-8", like Postgres does
s := strings.Map(alnumLowerASCII, name)
return s == "utf8" || s == "unicode"
}
func alnumLowerASCII(ch rune) rune {
if 'A' <= ch && ch <= 'Z' {
return ch + ('a' - 'A')
}
if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' {
return ch
}
return -1 // discard
}
| the42/ogdat | Godeps/_workspace/src/github.com/lib/pq/conn.go | GO | mit | 42,454 |
.webdav-login-dialog label {
text-align: left;
display: block;
}
.webdav-config-dialog input,
.webdav-login-dialog input {
width: 100%;
display: block;
}
.webdav-domain-edit,
.domain-icon {
margin-right: 5px;
display:inline-block;
background: 50% 50% no-repeat;
background-size: 16px 16px;
width: 16px;
height:16px;
}
.webdav-domain-edit {
padding-right: 5px;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAXUlEQVR42mNgGBKgoKAgAYj/Q3ECJZrBmCLNRBuASzNRXhhemj8AsQExmgWA+ABZmpEMUQDiC+RqBtnugOQVA1JTG8jWCVCvbIAaCKIboDgAZAFWg////08RptgAAMDo/Jm25cdCAAAAAElFTkSuQmCC);
width: 20px;
height: 100%;
margin: 0 0 0 10px;
vertical-align: middle;
border: 1px solid transparent;
border-radius: 2px;
}
.webdav-builtin-server {
text-align: left;
padding-top:20px;
}
.webdav-builtin-server .webdav-use-builtin-btn {
border: solid 1px #D9D9D9;
border-radius:4px;
display:inline-block;
background-color: #DEDEDE;
height:2em;
padding:0px 10px;
}
/*changes button styles on hover.*/
.webdav-builtin-server .webdav-use-builtin-btn:hover {
background-color: #d1d1d1;
border-color: #337AB7;
cursor: pointer;
}
.webdav-builtin-server .webdav-builtin-url {
display: inline-block;
width: 65%;
margin-left: 5px;
}
.enforced-servers-config {
padding: 20px;
text-align: center;
}
.enforced-servers-config #webdav-browse-url {
width: 70%;
}
.webdav-repo-preview {
display: inline-block;
height: inherit;
}
.webdav-repo-preview:hover .webdav-domain-edit {
background-color: lightgrey;
}
.webdav-repo-preview:hover .webdav-domain-edit:hover {
border-color: grey;
cursor: pointer;
}
.autosave-status-clean,
.autosave-status-saving,
.autosave-status-error {
margin-left: 5px;
color: #c0c3c5;
cursor: pointer;
}
.autosave-failed-save-as,
.autosave-failed-download {
font-weight: bold;
text-decoration: none;
}
.webdav-hide-logout .webdav-logout-container {
display: none;
}
.webdav-logout-container {
position: absolute;
top: 5px;
right: 10px;
padding: 2px 5px;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
z-index: 1;
color: #F3F4F4;
}
.webdav-logout-container:hover {
border-color: #D3D3D3;
}
.webdav-logout-container .webdav-username {
color: #cccccc;
}
| oxygenxml/webapp-webdav-integration | resources/webdav.css | CSS | mit | 2,433 |
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "power_templates"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| ricardobaumann/power_templates | test/dummy/config/application.rb | Ruby | mit | 1,025 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2015 The Anoncoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "merkleblock.h"
#include "hash.h"
#include "block.h" // for MAX_BLOCK_SIZE
#include "util.h"
using namespace std;
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{
header = block.GetBlockHeader();
vector<bool> vMatch;
vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const uint256& hash = block.vtx[i].GetHash();
if (filter.IsRelevantAndUpdate(block.vtx[i]))
{
vMatch.push_back(true);
vMatchedTxn.push_back(make_pair(i, hash));
}
else
vMatch.push_back(false);
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
if (height == 0) {
// hash at height 0 is the txids themself
return vTxid[pos];
} else {
// calculate left hash
uint256 left = CalcHash(height-1, pos*2, vTxid), right;
// calculate right hash if not beyond the end of the array - copy left hash otherwise1
if (pos*2+1 < CalcTreeWidth(height-1))
right = CalcHash(height-1, pos*2+1, vTxid);
else
right = left;
// combine subhashes
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
// determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
fParentOfMatch |= vMatch[p];
// store as flag bit
vBits.push_back(fParentOfMatch);
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, store hash and stop
vHash.push_back(CalcHash(height, pos, vTxid));
} else {
// otherwise, don't store any hash, but descend into the subtrees
TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
if (pos*2+1 < CalcTreeWidth(height-1))
TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
}
}
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure
fBad = true;
return 0;
}
bool fParentOfMatch = vBits[nBitsUsed++];
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (nHashUsed >= vHash.size()) {
// overflowed the hash array - failure
fBad = true;
return 0;
}
const uint256 &hash = vHash[nHashUsed++];
if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
vMatch.push_back(hash);
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
if (pos*2+1 < CalcTreeWidth(height-1))
right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
else
right = left;
// and combine them before returning
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
// reset state
vBits.clear();
vHash.clear();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
vMatch.clear();
// An empty set will not work
if (nTransactions == 0)
return 0;
// check for excessively high numbers of transactions
if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
return 0;
// there can never be more hashes provided than one for every txid
if (vHash.size() > nTransactions)
return 0;
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (vBits.size() < vHash.size())
return 0;
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
unsigned int nBitsUsed = 0, nHashUsed = 0;
uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
// verify that no problems occured during the tree traversal
if (fBad)
return 0;
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
return 0;
// verify that all hashes were consumed
if (nHashUsed != vHash.size())
return 0;
return hashMerkleRoot;
}
| GroundRod/anoncoin | src/merkleblock.cpp | C++ | mit | 5,729 |
『ビットコインのよくある質問』
=====================
著者:ゲイリー・ローウェ
原文:https://multibit.org/faq.html
##ライセンス
[MITライセンス](http://sourceforge.jp/projects/opensource/wiki/licenses%2FMIT_license)
| mknz/multibit-faq-japanese | README.md | Markdown | mit | 257 |
using TNRD.Editor.Core;
using TNRD.Editor.Utilities;
using UnityEditor;
using UnityEngine;
public class NoteEditor : ExtendedEditor {
[MenuItem( "Window/Editor Examples/Note Editor" )]
private static void Create() {
var window = GetWindow<NoteEditor>( "Notes", true, Utils.InspectorWindowType );
window.minSize = new Vector2( 400, 400 );
window.Show();
}
protected override void OnInitialize() {
base.OnInitialize();
RepaintOnUpdate = true;
AddWindow( new NoteWindow() );
}
}
| Miguel-Barreiro/ExtendedEditor | ExtendedEditor/Assets/Examples/NoteEditor/NoteEditor.cs | C# | mit | 551 |
__new_xsh_getoptionname()
{
local arg="${1}"
if [ "${arg}" = '--' ]
then
# End of options marker
return 0
fi
if [ "${arg:0:2}" = "--" ]
then
# It's a long option
echo "${arg:2}"
return 0
fi
if [ "${arg:0:1}" = "-" ] && [ ${#arg} -gt 1 ]
then
# It's a short option (or a combination of)
local index="$(expr ${#arg} - 1)"
echo "${arg:${index}}"
return 0
fi
}
__new_xsh_getfindpermoptions()
{
local access="${1}"
local res=''
while [ ! -z "${access}" ]
do
res="${res} -perm /u=${access:0:1},g=${access:0:1},o=${access:0:1}"
access="${access:1}"
done
echo "${res}"
}
__new_xsh_appendfsitems()
{
local current="${1}"
shift
local currentLength="${#current}"
local d
local b
local isHomeShortcut=false
[ "${current:0:1}" == "~" ] && current="${HOME}${current:1}" && isHomeShortcut=true
if [ "${current:$(expr ${currentLength} - 1)}" == "/" ]
then
d="${current%/}"
b=''
else
d="$(dirname "${current}")"
b="$(basename "${current}")"
fi
if [ -d "${d}" ]
then
local findCommand="find \"${d}\" -mindepth 1 -maxdepth 1 -name \"${b}*\" -a \\( ${@} \\)"
local files="$(eval ${findCommand} | while read file; do printf "%q\n" "${file#./}"; done)"
local IFS=$'\n'
local temporaryRepliesArray=(${files})
for ((i=0;${i}<${#temporaryRepliesArray[*]};i++))
do
local p="${temporaryRepliesArray[$i]}"
[ "${d}" != "." ] && p="${d}/$(basename "${p}")"
[ -d "${p}" ] && p="${p%/}/"
temporaryRepliesArray[$i]="${p}"
done
for ((i=0;${i}<${#temporaryRepliesArray[*]};i++))
do
COMPREPLY[${#COMPREPLY[*]}]="${temporaryRepliesArray[${i}]}"
done
fi
}
__new_xsh_bashcompletion()
{
#Context
COMPREPLY=()
local current="${COMP_WORDS[COMP_CWORD]}"
local previous="${COMP_WORDS[COMP_CWORD-1]}"
local first="${COMP_WORDS[1]}"
local globalargs="--name --output --path --embed --options --functions --help --version --ns-xml-path -n -o"
local args="${globalargs}"
# Option proposal
if [[ ${current} == -* ]]
then
COMPREPLY=( $(compgen -W "${args}" -- ${current}) )
for ((i=0;$i<${#COMPREPLY[*]};i++)); do COMPREPLY[${i}]="${COMPREPLY[${i}]} ";done
return 0
fi
# Option argument proposal
local option="$(__new_xsh_getoptionname ${previous})"
if [ ! -z "${option}" ]
then
case "${option}" in
"name" | "n")
[ ${#COMPREPLY[*]} -eq 0 ] && COMPREPLY[0]="\"${current#\"}"
return 0
[ ${#COMPREPLY[*]} -gt 0 ] && return 0
;;
"output" | "path" | "o")
__new_xsh_appendfsitems "${current}" $(__new_xsh_getfindpermoptions rw) -type d
[ ${#COMPREPLY[*]} -gt 0 ] && return 0
;;
"ns-xml-path")
__new_xsh_appendfsitems "${current}" -type d
[ ${#COMPREPLY[*]} -gt 0 ] && return 0
;;
esac
fi
# Last hope: files and folders
COMPREPLY=( $(compgen -fd -- "${current}") )
for ((i=0;${i}<${#COMPREPLY[*]};i++))
do
[ -d "${COMPREPLY[$i]}" ] && COMPREPLY[$i]="${COMPREPLY[$i]%/}/"
done
return 0
}
complete -o nospace -F __new_xsh_bashcompletion new-xsh.sh
| noresources/ns-xml | resources/bash_completion.d/new-xsh.sh | Shell | mit | 2,987 |
<?php
namespace Krisawzm\Embed\Components;
use Cms\Classes\ComponentBase;
use Krisawzm\Embed\Models\Settings;
use Lang;
class Kickstarter extends ComponentBase
{
/**
* {@inheritdoc}
*/
public function componentDetails()
{
return [
'name' => 'krisawzm.embed::kickstarter.details.name',
'description' => 'krisawzm.embed::kickstarter.details.description',
];
}
/**
* {@inheritdoc}
*/
public function defineProperties()
{
$css_units = Settings::get('valid_css_units', 'px');
return [
'url' => [
'title' => 'krisawzm.embed::kickstarter.properties.url.title',
'description' => 'krisawzm.embed::kickstarter.properties.url.description',
'default' => 'https://',
'type' => 'string',
'validationPattern' => '^https?:\/\/(www\.)?kickstarter\.com\/?.+$',
'validationMessage' => Lang::get('krisawzm.embed::kickstarter.properties.url.validationMessage'),
],
'type' => [
'title' => 'krisawzm.embed::kickstarter.properties.type.title',
'description' => 'krisawzm.embed::kickstarter.properties.type.description',
'default' => 'video',
'type' => 'dropdown',
'options' => ['video' => 'Video', 'card' => 'Card'],
],
'width' => [
'title' => 'krisawzm.embed::common.properties.width.title',
'description' => 'krisawzm.embed::kickstarter.properties.width.description',
'default' => '360',
'type' => 'string',
'validationPattern' => '^(auto|0)$|^\d+(\.\d+)?(%|'.$css_units.')?$',
'validationMessage' => Lang::get('krisawzm.embed::common.properties.width.validationMessage'),
],
'height' => [
'title' => 'krisawzm.embed::common.properties.height.title',
'description' => 'krisawzm.embed::kickstarter.properties.height.description',
'default' => '480',
'type' => 'string',
'validationPattern' => '^(auto|0)$|^\d+(\.\d+)?(%|'.$css_units.')?$',
'validationMessage' => Lang::get('krisawzm.embed::common.properties.height.validationMessage'),
],
];
}
/**
* Get the iframe src.
*
* @return string
*/
public function src()
{
$path = rtrim(parse_url($this->property('url'), PHP_URL_PATH), '/');
return '//www.kickstarter.com' . $path . '/widget/' .
$this->property('type') . '.html';
}
}
| krisawzm/embed-plugin | components/Kickstarter.php | PHP | mit | 2,900 |
namespace Cosmetics.Common
{
using System;
public static class Validator
{
public static void CheckIfNull(object obj, string message = null)
{
if (obj == null)
{
throw new NullReferenceException(message);
}
}
public static void CheckIfStringIsNullOrEmpty(string text, string message = null)
{
if (string.IsNullOrEmpty(text))
{
throw new NullReferenceException(message);
}
}
public static void CheckIfStringLengthIsValid(string text, int max, int min = 0, string message = null)
{
if (text.Length < min || max < text.Length)
{
throw new IndexOutOfRangeException(message);
}
}
internal static void CheckIfStringLengthIsValid(string value, int categoryMaxLength1, int categoryMinLength1, string v1, string v2, int categoryMinLength2, int categoryMaxLength2)
{
throw new NotImplementedException();
}
}
}
| shopOFF/TelerikAcademyCourses | CSharp-OOP/TelerikOOPExamPreparation/Workshop-Cosmetics/Workshop-Cosmetics/Cosmetics-Skeleton/Cosmetics/Common/Validator.cs | C# | mit | 1,087 |
define(function () {
var Backbone = require('backbone');
var _ = require('underscore');
// var challengeTemplate = require('text!/js/tpl/challenge-view.html');
var pagetpl = require('text!/js/tpl/ratings.html');
var PageView = Backbone.Marionette.ItemView.extend({
template: _.template(pagetpl),
ui: {
}
, events: {
}
, initialize: function() {
}
, onDomRefresh: function() {
var addPie = function(ctx) {
var data = [
{
value: 65,
color: "#5cb85c",
highlight: "#5cb85c",
label: "5 stars"
},
{
value: 13,
color: "#337ab7",
highlight: "#337ab7",
label: "4 stars"
},
{
value: 7,
color: "#5bc0de",
highlight: "#5bc0de",
label: "3 stars"
},
{
value: 10,
color: "#f0ad4e",
highlight: "#f0ad4e",
label: "2 stars"
},
{
value: 5,
color: "#d9534f",
highlight: "#d9534f",
label: "1 star"
}
]
var myPieChart = new Chart(ctx).Pie(data, {
animateScale: true
});
};
var ctx = this.$('#graph-feedback')[0].getContext("2d");
addPie(ctx);
}
});
return PageView;
}); | angelhack-moja/moja-backoffice | public/js/ratings.js | JavaScript | mit | 2,090 |
package com.alorma.gitskarios.core.client;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by Bernat on 08/07/2014.
*/
public class StoreCredentials {
private static final String USER_NAME = StoreCredentials.class.getSimpleName() + ".USER_NAME";
private static final String USER_TOKEN = StoreCredentials.class.getSimpleName() + ".USER_TOKEN";
private static final String USER_SCOPES = StoreCredentials.class.getSimpleName() + ".USER_SCOPES";
private static final String USER_SCOPES_NO_ASK = StoreCredentials.class.getSimpleName() + ".USER_SCOPES_NO_ASK";
private final SharedPreferences.Editor editor;
private final SharedPreferences preferences;
public StoreCredentials(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = preferences.edit();
}
public void storeToken(String accessToken) {
editor.putString(USER_TOKEN, accessToken);
editor.apply();
}
public String token() {
return preferences.getString(USER_TOKEN, null);
}
public void storeScopes(String scopes) {
editor.putString(USER_SCOPES, scopes);
editor.commit();
}
public String scopes() {
return preferences.getString(USER_SCOPES, null);
}
public void saveScopeNoAsk(boolean scopesNoAsk) {
editor.putBoolean(USER_SCOPES_NO_ASK, scopesNoAsk);
editor.commit();
}
public Boolean scopeNoAsk() {
return preferences.getBoolean(USER_SCOPES_NO_ASK, false);
}
public void clear() {
editor.clear();
editor.commit();
}
public void storeUsername(String name) {
editor.putString(USER_NAME, name);
editor.apply();
}
public String getUserName() {
return preferences.getString(USER_NAME, null);
}
}
| jmue/Gitskarios | sdks/gitskarios-core/src/main/java/com/alorma/gitskarios/core/client/StoreCredentials.java | Java | mit | 1,747 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Spect.Net.Z80Assembler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Spect.Net.Z80Assembler")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb7bd2ca-017a-43be-993b-b8c4d58ee4b5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Dotneteer/spectnetide | Assembler/Spect.Net.Assembler/Properties/AssemblyInfo.cs | C# | mit | 1,415 |
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\User;
use AppBundle\Entity\Category;
class CategoryController extends Controller
{
const DATE_FORMAT = 'Y-m-d';
/**
* @Route("/category/view/{id}", defaults={"id" = 0}, name="categoryView")
* @Method({"POST"})
*/
public function viewCategoryAction($id)
{
$data = array('children' => array(), 'ads' => array());
if ($id == 0)
{
$data['id'] = 0;
$data['name'] = 'root';
foreach ($this->getRootCategories() as $c)
{
$data['children'][] = array('id' => $c->getId(), 'name' => $c->getName(), 'hasChildren' => !$c->getChildren()->isEmpty());
}
}
else
{
$category = $this->getDoctrine()->getRepository('AppBundle:Category')->find($id);
if (!$category)
{
throw $this->createNotFoundException("Category with id $id not found");
}
$data['id'] = $category->getId();
$data['name'] = $category->getName();
foreach ($category->getChildren() as $c)
{
$data['children'][] = array('id' => $c->getId(), 'name' => $c->getName(), 'hasChildren' => !$c->getChildren()->isEmpty());
}
$ads = $this->getOpenAds($category);
if ($ads)
{
foreach ($ads as $ad)
{
$data['ads'][] = array(
'id' => $ad->getId(),
'title' => $ad->getTitle(),
'price' => (float)$ad->getPrice(),
'postedFrom' => $ad->getPostedFrom()->getName() . ', ' . $ad->getPostedFrom()->getCity()->getName(),
'postedAt' => $ad->getPostedAt()->format(self::DATE_FORMAT)
);
}
}
}
return new Response(json_encode($data));
}
private function getRootCategories()
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT c FROM AppBundle:Category c WHERE c.parent is null');
return $query->getResult();
}
private function getOpenAds($category)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT a FROM AppBundle:Ad a WHERE a.category = :cat and a.approved=true and a.closed=false')
->setParameter('cat', $category);
return $query->getResult();
}
}
| mfasia/CWBayWS | src/AppBundle/Controller/CategoryController.php | PHP | mit | 2,534 |
<header>
<h1>LifeChanger PoC</h1>
</header>
<charsheet></charsheet>
| tobal/lifechanger-poc | src/lifechanger/app.html | HTML | mit | 71 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Unobtanium</source>
<translation>Acerca de Unobtanium</translation>
</message>
<message>
<location line="+39"/>
<source><b>Unobtanium</b> version</source>
<translation>Versión de <b>Unobtanium</b></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 ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Este es un software experimental.
Distribuido bajo la licencia MIT/X11, vea el archivo adjunto
COPYING o http://www.opensource.org/licenses/mit-license.php.
Este producto incluye software desarrollado por OpenSSL Project para su uso en
el OpenSSL Toolkit (http://www.openssl.org/) y software criptográfico escrito por
Eric Young ([email protected]) y el software UPnP escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Unobtanium developers</source>
<translation>Los programadores Unobtanium</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Libreta de direcciones</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Haga doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear una nueva dirección</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiar la dirección seleccionada al portapapeles del sistema</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Añadir dirección</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Unobtanium 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>Estas son sus direcciones Unobtanium para recibir pagos. Puede utilizar una diferente por cada persona emisora para saber quién le está pagando.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copiar dirección</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Mostrar código &QR </translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Unobtanium address</source>
<translation>Firmar un mensaje para demostrar que se posee una dirección Unobtanium</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Firmar mensaje</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Borrar de la lista la dirección seleccionada</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar a un archivo los datos de esta pestaña</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Unobtanium address</source>
<translation>Verificar un mensaje para comprobar que fue firmado con la dirección Unobtanium indicada</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verificar mensaje</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Unobtanium addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Estas son sus direcciones Unobtanium para enviar pagos. Compruebe siempre la cantidad y la dirección receptora antes de transferir monedas.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copiar &etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Enviar &monedas</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exportar datos de la libreta de direcciones</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error al exportar</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de contraseña</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introducir contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita la nueva contraseña</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>Introduzca la nueva contraseña del monedero.<br/>Por favor elija una con <b>10 o más caracteres aleatorios</b> u <b>ocho o más palabras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Cifrar el monedero</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación requiere su contraseña para desbloquear el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear monedero</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación requiere su contraseña para descifrar el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Descifrar el monedero</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambiar contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduzca la contraseña anterior del monedero y la nueva. </translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar cifrado del monedero</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL YOUR UNOBTANIUM</b>!</source>
<translation>Atencion: ¡Si cifra su monedero y pierde la contraseña perderá <b>TODOS SUS UNOBTANIUM</b>!"</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que desea cifrar su monedero?</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>IMPORTANTE: Cualquier copia de seguridad que haya realizado previamente de su archivo de monedero debe reemplazarse con el nuevo archivo de monedero cifrado. Por razones de seguridad, las copias de seguridad previas del archivo de monedero no cifradas serán inservibles en cuanto comience a usar el nuevo monedero cifrado.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Aviso: ¡La tecla de bloqueo de mayúsculas está activada!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Monedero cifrado</translation>
</message>
<message>
<location line="-56"/>
<source>Unobtanium will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your unobtaniums from being stolen by malware infecting your computer.</source>
<translation>Unobtanium se cerrará para finalizar el proceso de cifrado. Recuerde que el cifrado de su monedero no puede proteger totalmente sus unobtaniums de robo por malware que infecte su sistema.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Ha fallado el cifrado del monedero</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Ha fallado el cifrado del monedero debido a un error interno. El monedero no ha sido cifrado.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo del monedero</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contraseña introducida para descifrar el monedero es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado el descifrado del monedero</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Se ha cambiado correctamente la contraseña del monedero.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Firmar &mensaje...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando con la red…</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Vista general</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar vista general del monedero</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transacciones</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Examinar el historial de transacciones</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Editar la lista de las direcciones y etiquetas almacenadas</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Mostrar la lista de direcciones utilizadas para recibir pagos</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir de la aplicación</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Unobtanium</source>
<translation>Mostrar información acerca de Unobtanium</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar información acerca de Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Cifrar monedero…</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Copia de &respaldo del monedero...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña…</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importando bloques de disco...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindexando bloques en disco...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Unobtanium address</source>
<translation>Enviar monedas a una dirección Unobtanium</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Unobtanium</source>
<translation>Modificar las opciones de configuración de Unobtanium</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Copia de seguridad del monedero en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>Ventana de &depuración</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir la consola de depuración y diagnóstico</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verificar mensaje...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Unobtanium</source>
<translation>Unobtanium</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Enviar</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Recibir</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Direcciones</translation>
</message>
<message>
<location line="+22"/>
<source>&About Unobtanium</source>
<translation>&Acerca de Unobtanium</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar/ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Mostrar u ocultar la ventana principal</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Cifrar las claves privadas de su monedero</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Unobtanium addresses to prove you own them</source>
<translation>Firmar mensajes con sus direcciones Unobtanium para demostrar la propiedad</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Unobtanium addresses</source>
<translation>Verificar mensajes comprobando que están firmados con direcciones Unobtanium concretas</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>A&yuda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Unobtanium client</source>
<translation>Cliente Unobtanium</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Unobtanium network</source>
<translation><numerusform>%n conexión activa hacia la red Unobtanium</numerusform><numerusform>%n conexiones activas hacia la red Unobtanium</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Ninguna fuente de bloques disponible ...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Se han procesado %1 de %2 bloques (estimados) del historial de transacciones.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Procesados %1 bloques del historial de transacciones.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n día</numerusform><numerusform>%n días</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 atrás</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>El último bloque recibido fue generado hace %1.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Las transacciones posteriores a esta aún no están visibles.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Información</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>Esta transacción supera el límite de tamaño. Puede enviarla con una comisión de %1, destinada a los nodos que procesen su transacción para contribuir al mantenimiento de la red. ¿Desea pagar esta comisión?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Actualizando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirme la tarifa de la transacción</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Gestión de URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Unobtanium address or malformed URI parameters.</source>
<translation>¡No se puede interpretar la URI! Esto puede deberse a una dirección Unobtanium inválida o a parámetros de URI mal formados.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>desbloqueado</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>bloqueado</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Unobtanium can no longer continue safely and will quit.</source>
<translation>Ha ocurrido un error crítico. Unobtanium ya no puede continuar con seguridad y se cerrará.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Alerta de red</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etiqueta asociada con esta entrada en la libreta</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</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>La dirección asociada con esta entrada en la guía. Solo puede ser modificada para direcciones de envío.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nueva dirección para recibir</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección para enviar</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envío</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya está presente en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Unobtanium address.</source>
<translation>La dirección introducida "%1" no es una dirección Unobtanium válida.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Ha fallado la generación de la nueva clave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Unobtanium-Qt</source>
<translation>Unobtanium-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versión</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>opciones de la línea de órdenes</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Opciones GUI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Establecer el idioma, por ejemplo, "es_ES" (predeterminado: configuración regional del sistema)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Arrancar minimizado</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Mostrar pantalla de bienvenida en el inicio (predeterminado: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</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>Tarifa de transacción opcional por kB que ayuda a asegurar que sus transacciones sean procesadas rápidamente. La mayoría de transacciones son de 1kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciones</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Unobtanium after logging in to the system.</source>
<translation>Iniciar Unobtanium automáticamente al encender el sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Unobtanium on system login</source>
<translation>&Iniciar Unobtanium al iniciar el sistema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Restablecer todas las opciones del cliente a las predeterminadas.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Restablecer opciones</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Red</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Unobtanium client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abrir automáticamente el puerto del cliente Unobtanium en el router. Esta opción solo funciona si el router admite UPnP y está activado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Unobtanium network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Conectar a la red Unobtanium a través de un proxy SOCKS (ej. para conectar con la red Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Conectar a través de un proxy SOCKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Dirección &IP del proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Dirección IP del proxy (ej. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versión SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versión del proxy SOCKS (ej. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Ventana</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar a la bandeja en vez de a la barra de tareas</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>Minimizar en lugar de salir de la aplicación al cerrar la ventana.Cuando esta opción está activa, la aplicación solo se puede cerrar seleccionando Salir desde el menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interfaz</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>I&dioma de la interfaz de usuario</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Unobtanium.</source>
<translation>El idioma de la interfaz de usuario puede establecerse aquí. Este ajuste se aplicará cuando se reinicie Unobtanium.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Mostrar las cantidades en la &unidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían monedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Unobtanium addresses in the transaction list or not.</source>
<translation>Mostrar o no las direcciones Unobtanium en la lista de transacciones.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Mostrar las direcciones en la lista de transacciones</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Aplicar</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>predeterminado</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirme el restablecimiento de las opciones</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Algunas configuraciones pueden requerir un reinicio del cliente para que sean efectivas.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>¿Quiere proceder?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Unobtanium.</source>
<translation>Esta configuración tendrá efecto tras reiniciar Unobtanium.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>La dirección proxy indicada es inválida.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Desde</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Unobtanium network after a connection is established, but this process has not completed yet.</source>
<translation>La información mostrada puede estar desactualizada. Su monedero se sincroniza automáticamente con la red Unobtanium después de que se haya establecido una conexión , pero este proceso aún no se ha completado.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>No confirmado(s):</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>No disponible:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Saldo recién minado que aún no está disponible.</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Movimientos recientes</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Su saldo actual</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>Total de las transacciones que faltan por confirmar y que no contribuyen al saldo actual</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>desincronizado</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start unobtanium: click-to-pay handler</source>
<translation>No se pudo iniciar unobtanium: manejador de pago-al-clic</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Diálogo de códigos QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Solicitud de pago</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Cuantía:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiqueta:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mensaje:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Guardar como...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error al codificar la URI en el código QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>La cantidad introducida es inválida. Compruébela, por favor.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI esultante demasiado larga. Intente reducir el texto de la etiqueta / mensaje.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Guardar código QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imágenes PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nombre del cliente</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>N/D</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versión del cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Información</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Utilizando la versión OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Hora de inicio</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Red</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de conexiones</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>En la red de pruebas</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadena de bloques</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de bloques</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Bloques totales estimados</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Hora del último bloque</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Opciones de la línea de órdenes</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Unobtanium-Qt help message to get a list with possible Unobtanium command-line options.</source>
<translation>Mostrar el mensaje de ayuda de Unobtanium-Qt que enumera las opciones disponibles de línea de órdenes para Unobtanium.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Mostrar</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Fecha de compilación</translation>
</message>
<message>
<location line="-104"/>
<source>Unobtanium - Debug window</source>
<translation>Unobtanium - Ventana de depuración</translation>
</message>
<message>
<location line="+25"/>
<source>Unobtanium Core</source>
<translation>Núcleo de Unobtanium</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Archivo de registro de depuración</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Unobtanium debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Abrir el archivo de registro de depuración en el directorio actual de datos. Esto puede llevar varios segundos para archivos de registro grandes.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Borrar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Unobtanium RPC console.</source>
<translation>Bienvenido a la consola RPC de Unobtanium</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>Use las flechas arriba y abajo para navegar por el historial y <b>Control+L</b> para limpiar la pantalla.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Escriba <b>help</b> para ver un resumen de los comandos disponibles.</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>Enviar monedas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a multiples destinatarios de una vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Añadir &destinatario</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Eliminar todos los campos de las transacciones</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</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>Confirmar el envío</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> a %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envío de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>¿Está seguro de que desea enviar %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>y</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de recepción no es válida, compruébela de nuevo.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor de 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa su saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa su saldo cuando se incluye la tasa de envío de %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Se ha encontrado una dirección duplicada. Solo se puede enviar a cada dirección una vez por operación de envío.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Error: ¡Ha fallado la creación de la transacción!</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>Error: transacción rechazada. Puede haber ocurrido si alguna de las monedas ya estaba gastada o si ha usado una copia de wallet.dat y las monedas se gastaron en la copia pero no se han marcado así aquí.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Envío</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ca&ntidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>La dirección a la que enviar el pago (p. ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</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>Etiquete esta dirección para añadirla a la libreta</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elija una dirección de la libreta de direcciones</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>Pegar dirección desde portapapeles</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>Eliminar destinatario</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Unobtanium address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduzca una dirección Unobtanium (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Firmas - Firmar / verificar un mensaje</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Firmar mensaje</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>Puede firmar mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa vaga, ya que los ataques de phishing pueden tratar de engañarle para suplantar su identidad. Firme solo declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>La dirección con la que firmar el mensaje (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Elija una dirección de la libreta de direcciones</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>Pegar dirección desde portapapeles</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>Introduzca el mensaje que desea firmar aquí</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Firma</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar la firma actual al portapapeles del sistema</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Unobtanium address</source>
<translation>Firmar el mensaje para demostrar que se posee esta dirección Unobtanium</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Firmar &mensaje</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Limpiar todos los campos de la firma de mensaje</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verificar mensaje</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>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>La dirección con la que se firmó el mensaje (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Unobtanium address</source>
<translation>Verificar el mensaje para comprobar que fue firmado con la dirección Unobtanium indicada</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verificar &mensaje</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Limpiar todos los campos de la verificación de mensaje</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Unobtanium address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduzca una dirección Unobtanium (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Haga clic en "Firmar mensaje" para generar la firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Unobtanium signature</source>
<translation>Introduzca una firma Unobtanium</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>La dirección introducida es inválida.</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>Verifique la dirección e inténtelo de nuevo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>La dirección introducida no corresponde a una clave.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Se ha cancelado el desbloqueo del monedero. </translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>No se dispone de la clave privada para la dirección introducida.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ha fallado la firma del mensaje.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensaje firmado.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>No se puede decodificar la firma.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Compruebe la firma e inténtelo de nuevo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>La firma no coincide con el resumen del mensaje.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>La verificación del mensaje ha fallado.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensaje verificado.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+25"/>
<source>The Unobtanium developers</source>
<translation>Los programadores Unobtanium</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>Abierto hasta %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/fuera de línea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciones</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitir a través de %n nodo</numerusform><numerusform>, transmitir a través de %n nodos</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Fuente</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>dirección propia</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión de transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad neta</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Identificador de transacción</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>Las monedas generadas deben esperar 120 bloques antes de que se puedan gastar. Cuando se generó este bloque, se emitió a la red para ser agregado a la cadena de bloques. Si no consigue incorporarse a la cadena, su estado cambiará a "no aceptado" y las monedas no se podrán gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque casi al mismo tiempo que el suyo.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Información de depuración</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>entradas</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadero</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, todavía no se ha sido difundido satisfactoriamente</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Fuera de línea (%1 confirmaciones)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>No confirmado (%1 de %2 confirmaciones)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</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>El saldo recién minado estará disponible cuando venza el plazo en %n bloque más</numerusform><numerusform>El saldo recién minado estará disponible cuando venza el plazo en %n bloques más</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>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibidos de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pago propio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nd)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora en que se recibió la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino de la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad retirada o añadida al saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A usted mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduzca una dirección o etiqueta que buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar cuantía</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar identificador de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalles de la transacción</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportar datos de la transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exportando</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar a un archivo los datos de esta pestaña</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Respaldo de monedero</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Datos de monedero (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Ha fallado el respaldo</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Se ha producido un error al intentar guardar los datos del monedero en la nueva ubicación.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Se ha completado con éxito la copia de respaldo</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Los datos del monedero se han guardado con éxito en la nueva ubicación.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Unobtanium version</source>
<translation>Versión de Unobtanium</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or unobtaniumd</source>
<translation>Envíar comando a -server o unobtaniumd</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: unobtanium.conf)</source>
<translation>Especificar archivo de configuración (predeterminado: unobtanium.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: unobtaniumd.pid)</source>
<translation>Especificar archivo pid (predeterminado: unobtanium.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar directorio para los datos</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Establecer el tamaño de caché de la base de datos en megabytes (predeterminado: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Escuchar conexiones en <puerto> (predeterminado: 8333 o testnet: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener como máximo <n> conexiones a pares (predeterminado: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Conectar a un nodo para obtener direcciones de pares y desconectar</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Especifique su propia dirección pública</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral para la desconexión de pares con mal comportamiento (predeterminado: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos en que se evita la reconexión de pares con mal comportamiento (predeterminado: 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>Ha ocurrido un error al configurar el puerto RPC %u para escucha en IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>Escuchar conexiones JSON-RPC en <puerto> (predeterminado: 8332 o testnet:18332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr como demonio y aceptar comandos
</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Usar la red de pruebas
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceptar conexiones desde el exterior (predeterminado: 1 si no -proxy o -connect)</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=unobtaniumrpc
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 "Unobtanium Alert" [email protected]
</source>
<translation>%s, debe establecer un valor rpcpassword en el archivo de configuración:
%s
Se recomienda utilizar la siguiente contraseña aleatoria:
rpcuser=unobtaniumrpc
rpcpassword=%s
(no es necesario recordar esta contraseña)
El nombre de usuario y la contraseña DEBEN NO ser iguales.
Si el archivo no existe, créelo con permisos de archivo de solo lectura.
Se recomienda también establecer alertnotify para recibir notificaciones de problemas.
Por ejemplo: alertnotify=echo %%s | mail -s "Unobtanium Alert" [email protected]
</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>Ha ocurrido un error al configurar el puerto RPC %u para escuchar mediante IPv6. Recurriendo a IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Vincular a la dirección dada y escuchar siempre en ella. Utilice la notación [host]:port para IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Unobtanium is probably already running.</source>
<translation>No se puede bloquear el directorio de datos %s. Probablemente Unobtanium ya se está ejecutando.</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>¡Error: se ha rechazado la transacción! Esto puede ocurrir si ya se han gastado algunas de las monedas del monedero, como ocurriría si hubiera hecho una copia de wallet.dat y se hubieran gastado monedas a partir de la copia, con lo que no se habrían marcado aquí como gastadas.</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>¡Error: Esta transacción requiere una comisión de al menos %s debido a su monto, complejidad, o al uso de fondos recién recibidos!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Ejecutar orden cuando se reciba un aviso relevante (%s en cmd se reemplazará por el mensaje)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Ejecutar comando cuando una transacción del monedero cambia (%s en cmd se remplazará por TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Establecer el tamaño máximo de las transacciones de alta prioridad/comisión baja en bytes (predeterminado: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>Esta es una versión de pre-prueba - utilícela bajo su propio riesgo. No la utilice para usos comerciales o de minería.</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>Aviso: ¡-paytxfee tiene un valor muy alto! Esta es la comisión que pagará si envía una transacción.</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>Aviso: ¡Las transacciones mostradas pueden no ser correctas! Puede necesitar una actualización o bien otros nodos necesitan actualizarse.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Unobtanium will not work properly.</source>
<translation>Precaución: Por favor, ¡revise que la fecha y hora de su ordenador son correctas! Si su reloj está mal, Unobtanium no funcionará correctamente.</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>Aviso: ¡Error al leer wallet.dat! Todas las claves se han leído correctamente, pero podrían faltar o ser incorrectos los datos de transacciones o las entradas de la libreta de direcciones.</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>Aviso: ¡Recuperados datos de wallet.dat corrupto! El wallet.dat original se ha guardado como wallet.{timestamp}.bak en %s; si hubiera errores en su saldo o transacciones, deberá restaurar una copia de seguridad.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Intento de recuperar claves privadas de un wallet.dat corrupto</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Opciones de creación de bloques:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Conectar sólo a los nodos (o nodo) especificados</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corrupción de base de datos de bloques detectada.</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descubrir dirección IP propia (predeterminado: 1 al escuchar sin -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>¿Quieres reconstruir la base de datos de bloques ahora?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Error al inicializar la base de datos de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Error al inicializar el entorno de la base de datos del monedero %s</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Error cargando base de datos de bloques</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Error al abrir base de datos de bloques.</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Error: ¡Espacio en disco bajo!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Error: ¡El monedero está bloqueado; no se puede crear la transacción!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Error: error de sistema: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>No se ha podido leer la información de bloque</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>No se ha podido leer el bloque</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>No se ha podido sincronizar el índice de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>No se ha podido escribir en el índice de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>No se ha podido escribir la información de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>No se ha podido escribir el bloque</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>No se ha podido escribir la información de archivo</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>No se ha podido escribir en la base de datos de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>No se ha podido escribir en el índice de transacciones</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>No se han podido escribir los datos de deshacer</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Encontrar pares mediante búsqueda de DNS (predeterminado: 1 salvo con -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generar monedas (por defecto: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Cuántos bloques comprobar al iniciar (predeterminado: 288, 0 = todos)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Como es de exhaustiva la verificación de bloques (0-4, por defecto 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>No hay suficientes descriptores de archivo disponibles. </translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Reconstruir el índice de la cadena de bloques a partir de los archivos blk000??.dat actuales</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Establecer el número de hilos para atender las llamadas RPC (predeterminado: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verificando bloques...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verificando monedero...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importa los bloques desde un archivo blk000??.dat externo</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>Configura el número de hilos para el script de verificación (hasta 16, 0 = auto, <0 = leave that many cores free, por fecto: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Información</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Dirección -tor inválida: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Inválido por el monto -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Inválido por el monto -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Mantener índice de transacciones completo (predeterminado: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Búfer de recepción máximo por conexión, <n>*1000 bytes (predeterminado: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Búfer de recepción máximo por conexión, , <n>*1000 bytes (predeterminado: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Aceptar solamente cadena de bloques que concuerde con los puntos de control internos (predeterminado: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Conectarse solo a nodos de la red <net> (IPv4, IPv6 o Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Mostrar información de depuración adicional. Implica todos los demás opciones -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Mostrar información de depuración adicional</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Anteponer marca temporal a la información de depuración</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la Bitcoin Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Elija la versión del proxy socks a usar (4-5, predeterminado: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar información de trazas/depuración a la consola en lugar de al archivo debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Enviar información de trazas/depuración al depurador</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Establecer tamaño máximo de bloque en bytes (predeterminado: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Reducir el archivo debug.log al iniciar el cliente (predeterminado: 1 sin -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Transacción falló</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar el tiempo máximo de conexión en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Error de sistema: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Monto de la transacción muy pequeño</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Montos de transacciones deben ser positivos</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transacción demasiado grande</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 1 al escuchar)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utilizar proxy para conectar a Tor servicios ocultos (predeterminado: igual que -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Nombre de usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Aviso: Esta versión es obsoleta, actualización necesaria!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Necesita reconstruir las bases de datos con la opción -reindex para modificar -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupto. Ha fallado la recuperación.</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Ejecutar un comando cuando cambia el mejor bloque (%s en cmd se sustituye por el hash de bloque)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar el monedero al último formato</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajustar el número de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Volver a examinar la cadena de bloques en busca de transacciones del monedero perdidas</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (predeterminado: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifrados aceptados (predeterminado: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible conectar con %s en este sistema (bind ha dado el error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Conectar mediante proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir búsquedas DNS para -addnode, -seednode y -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Cargando direcciones...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error al cargar wallet.dat: el monedero está dañado</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Unobtanium</source>
<translation>Error al cargar wallet.dat: El monedero requiere una versión más reciente de Unobtanium</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Unobtanium to complete</source>
<translation>El monedero ha necesitado ser reescrito. Reinicie Unobtanium para completar el proceso</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error al cargar wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy inválida: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>La red especificada en -onlynet '%s' es desconocida</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Solicitada versión de proxy -socks desconocida: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>No se puede resolver la dirección de -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>No se puede resolver la dirección de -externalip: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Cuantía no válida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Cargando el índice de bloques...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Añadir un nodo al que conectarse y tratar de mantener la conexión abierta</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Unobtanium is probably already running.</source>
<translation>No es posible conectar con %s en este sistema. Probablemente Unobtanium ya está ejecutándose.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Tarifa por KB que añadir a las transacciones que envíe</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Cargando monedero...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>No se puede rebajar el monedero</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>No se puede escribir la dirección predeterminada</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Reexplorando...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Para utilizar la opción %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</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>Tiene que establecer rpcpassword=<contraseña> en el fichero de configuración: ⏎
%s ⏎
Si el archivo no existe, créelo con permiso de lectura solamente del propietario.</translation>
</message>
</context>
</TS> | Unobtanium-dev/Unobtanium | src/qt/locale/bitcoin_es.ts | TypeScript | mit | 119,597 |
require 'rflags/flag'
require 'rflags/file_flag'
require 'rflags/redis_flag'
module RFlags
def flag(definition)
name, backend = resolve_flag_params(definition)
instance_variable_set("@#{name}".to_sym, backend)
instance_eval <<-MTD, __FILE__, __LINE__
def #{name}
@#{name}
end
MTD
end
def lazy_flag(name, &block)
if !block
raise "RFlags##{__method__} needs a block"
end
resolve = -> do
opts = block.call
resolve_flag_backend_class(opts).new(*opts)
end
instance_variable_set(:"@#{name}_block", resolve)
instance_eval(<<-MTD, __FILE__, __LINE__)
def #{name}
@#{name} ||= @#{name}_block.call
end
MTD
end
private
def resolve_flag_params(definition)
case definition
when String, Symbol
[definition, RFlags::Flag.new]
when Hash
name = definition.keys[0]
backend_opts = definition[name]
backend_class = resolve_flag_backend_class(backend_opts)
[name, backend_class.new(*backend_opts)]
else
raise TypeError, "Can't handle #{definition.class}"
end
end
def resolve_flag_backend_class(opts)
case opts
when String, Pathname
RFlags::FileFlag
when Array
class_name = opts[0].class
::Object.const_get("::RFlags::#{class_name}Flag")
else
raise TypeError, "Can't handle #{opts.class}"
end
end
end
| mediaslave24/rflags | lib/rflags.rb | Ruby | mit | 1,409 |
<section class="u-section-separator">
<h2 id="how-when" class="content__h2">How and when to take</h2>
<p>Always take your naproxen tablets with or just after a meal so you don't get an upset stomach.</p>
<p>As a general rule in adults, the dose to treat:</p>
<ul>
<li>diseases of joints is 500mg to 1000mg daily in 1 to 2 divided doses</li>
<li>muscle, bone disorders and painful periods is 500mg at first, then 250mg every 6 to 8 hours as required</li>
<li>attacks of gout is 750mg, then 250mg every 8 hours until the attack has passed</li>
</ul>
<p>Doses are usually lower for elderly people and people with heart, liver or kidney problems.</p>
<p>The doctor will use your child's weight to work out the right dose.</p>
<p>If you get naproxen on prescription, the dose depends on the reason why you're taking it, your age, how well your liver and kidneys work and how well it helps your symptoms.</p>
<p>If you buy naproxen from a pharmacy for painful menstrual periods:</p>
<ul>
<li>on the first day - take 2 tablets when the pain starts, then after 6 to 8 hours one more tablet that day if you need to</li>
<li>on the second and following days - take one tablet every 6 to 8 hours if needed</li>
</ul>
<p>Do not take more than 3 tablets a day.</p>
<h3>How to take it</h3>
<p>Naproxen on prescription comes as 2 different tablets - effervescent and gastro-resistant tablets.</p>
<p>Effervescent tablets are dissolved in water before you take them.</p>
<p>Gastro-resistant tablets have a coating to protect them from being broken down by the acid in your stomach. Instead, the medicine is released further down the gut in your intestine.</p>
<p>If you take gastro-resistant tablets, swallow them whole with or after food. Do not crush or chew them.</p>
<p>If you take effervescent tablets, dissolve 1 to 2 tablets in a glass (150ml) of water and drink.</p>
<p>Doses of 3 tablets should be dissolved in 300ml. To make sure there is no medicine left, rinse the empty glass with a small amount of water and drink it. Take with or after food.</p>
<h3>What if I forget to take it? </h3>
<p>Take your forgotten dose as soon as you remember, unless it is nearly time for your next dose. Do not take a double dose to make up for a forgotten dose.</p>
<p>If you forget doses often, it may help to set an alarm to remind you. You could also ask your pharmacist for advice on other ways that are suitable for you and your medicines.</p>
<h3>What if I take too much?</h3>
<p>If you take too many naproxen tablets by accident, you are more likely to get some of the common side effects. If this happens, contact your doctor straight away.</p>
</section>
| NHSChoices/medicines-alpha | app/views/naproxen/includes/how-when-to-take.html | HTML | mit | 2,711 |
import * as QUnit from "qunitjs";
import { integrationModule, testObjects } from "../../integration-test-helpers/integration-test-helpers";
import { assignFromJson } from "../../model-helpers/model-helpers"
import { tap } from "../../utils/obj";
import {WebServerConfig} from "../web-server-config";
import { Api } from "../../api/endpoints";
import {User} from "../../user-model/user-model";
import * as Rx from "rx";
import {ServerSession} from "../../sessions/session-model";
import { Headers } from "../header-and-cookie-names";
integrationModule(__filename);
QUnit.test("json requests are rejected until the xsrf matches the session", (assert) => {
var endpoint = new Api.Endpoint("myendpoint", Object, Object);
var handlers = [{
endpoint: endpoint,
handle: (req:Object, res:Object, user$:Rx.Observable<User>) => {
return Rx.Observable.just(res);
}
}];
testObjects.testServer.jsonServiceHandlers = () => handlers;
testObjects.testServer.testRouter.get("/setsession", (req, res) => {
var session = req.session as ServerSession;
session.sessionXsrfToken = "session-token";
res.send("Set");
});
testObjects.testServer.start();
testObjects.testClient.jsonRequest(endpoint.path, {})
.flatMap(([res, body]) => {
assert.deepEqual(body, {error: true, xsrfFailure: true});
assert.equal(res.statusCode, 401);
return testObjects.testClient.request("/setsession");
})
.flatMap(([res, body]) => {
assert.deepEqual(body, "Set");
assert.equal(res.statusCode, 200);
return testObjects.testClient.jsonRequest(endpoint.path, {},
{[Headers.XSRF_TOKEN]: "session-token"});
})
.flatMap(([res, body]) => {
assert.deepEqual(body, {});
assert.equal(res.statusCode, 200);
return testObjects.testClient.jsonRequest(endpoint.path, {},
{[Headers.XSRF_TOKEN]: "wrong-token"});
})
.map(([res, body]) => {
assert.deepEqual(body, {error: true, xsrfFailure: true});
assert.equal(res.statusCode, 401);
return null;
}).finally(() => testObjects.testServer.close())
.merge(testObjects.testServer.lifecycle$.map(() => null))
.doOnError((e) => {
assert.ok(false, e + "");
})
.finally(assert.async())
.subscribe();
})
| corps/nama | web-server/tests/security.node.test.ts | TypeScript | mit | 2,281 |
/*
* Index module
*
* Entry point - Import and initialise all required parts of the app
*/
// Compatibility
import 'babel-polyfill';
// Imports
import app from './core/app';
import router from './core/router';
import Vue from 'vue';
// Routes
import './routes';
// Filters
import './filter/string';
// Components
import './component/questions-tree';
import './component/sequence-display';
import './component/match-display';
Vue.config.debug = true;
init();
/*
* Initialise app
*/
function init() {
app.init();
router.init();
} | tancredi/hr-hackathon-chilist-app | client/lib/index.js | JavaScript | mit | 549 |
<?php
namespace Doctrine\Tests\ORM\Tools\Export;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\Export\Driver\XmlExporter;
/**
* Test case for XmlClassMetadataExporterTest
*
* @author Jonathan H. Wage <[email protected]>
* @author Roman Borschel <[email protected]
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link http://www.phpdoctrine.org
* @since 2.0
* @version $Revision$
*/
class XmlClassMetadataExporterTest extends AbstractClassMetadataExporterTest
{
protected function _getType()
{
return 'xml';
}
/**
* @group DDC-3428
*/
public function testSequenceGenerator() {
$exporter = new XmlExporter();
$metadata = new ClassMetadata('entityTest');
$metadata->mapField(array(
"fieldName" => 'id',
"type" => 'integer',
"columnName" => 'id',
"id" => true,
));
$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE);
$metadata->setSequenceGeneratorDefinition(array(
'sequenceName' => 'seq_entity_test_id',
'allocationSize' => 5,
'initialValue' => 1
));
$expectedFileContent = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping
xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"
>
<entity name="entityTest">
<id name="id" type="integer" column="id">
<generator strategy="SEQUENCE"/>
<sequence-generator sequence-name="seq_entity_test_id" allocation-size="5" initial-value="1"/>
</id>
</entity>
</doctrine-mapping>
XML;
$this->assertXmlStringEqualsXmlString($expectedFileContent, $exporter->exportClassMetadata($metadata));
}
/**
* @group 1214
* @group 1216
* @group DDC-3439
*/
public function testFieldOptionsExport() {
$exporter = new XmlExporter();
$metadata = new ClassMetadata('entityTest');
$metadata->mapField(array(
"fieldName" => 'myField',
"type" => 'string',
"columnName" => 'my_field',
"options" => array(
"default" => "default_string",
"comment" => "The comment for the field",
),
));
$expectedFileContent = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="entityTest">
<field name="myField" type="string" column="my_field">
<options>
<option name="default">default_string</option>
<option name="comment">The comment for the field</option>
</options>
</field>
</entity>
</doctrine-mapping>
XML;
$this->assertXmlStringEqualsXmlString($expectedFileContent, $exporter->exportClassMetadata($metadata));
}
}
| steevanb/doctrine2-fix-persistent-collection-clear | tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php | PHP | mit | 3,332 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard for C:\xampp\htdocs\monitor\application/models</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="span12">
<ul class="breadcrumb">
<li><a href="index.html">C:\xampp\htdocs\monitor\application</a> <span class="divider">/</span></li>
<li><a href="models.html">models</a></li>
<li class="active">(Dashboard)</li>
</ul>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="span6">
<h2>Class Coverage Distribution</h2>
<div id="classCoverageDistribution"></div>
</div>
<div class="span6">
<h2>Class Complexity</h2>
<div id="classComplexity"></div>
</div>
</div>
<div class="row">
<div class="span6">
<h2>Top Project Risks</h2>
<ul>
<li><a href="models_Model_jadwal.php.html#3">Model_jadwal</a> (25)</li>
</ul>
</div>
<div class="span6">
<h2>Least Tested Methods</h2>
<ul>
<li><a href="models_Model_jadwal.php.html#33">Model_jadwal::delete</a> (0%)</li>
<li><a href="models_Model_jadwal.php.html#15">Model_jadwal::find</a> (0%)</li>
<li><a href="models_Model_jadwal.php.html#39">Model_jadwal::update</a> (0%)</li>
<li><a href="models_Model_jadwal.php.html#5">Model_jadwal::all</a> (75%)</li>
</ul>
</div>
</div>
<footer>
<p>
<small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 1.2.11</a> using <a href="http://www.php.net/" target="_top">PHP 7.1.9</a> and <a href="http://phpunit.de/">PHPUnit 3.7.21</a> at Tue Oct 17 16:34:32 CEST 2017.</small>
</p>
</footer>
</div>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var classCoverageDistribution = new Highcharts.Chart({
chart: {
renderTo: 'classCoverageDistribution',
type: 'column'
},
title: {text: ''},
legend: {enabled: false},
credits: {enabled: false},
tooltip: {enabled: false},
xAxis: {
labels: {style: {fontSize: '8px'}},
categories: [
'0%','0-10%','10-20%','20-30%','30-40%','40-50%','50-60%','60-70%','70-80%','80-90%','90-100%','100%'
]
},
yAxis: {
title: '',
labels: {style: {fontSize: '8px'}},
},
series: [{
data: [0,0,0,0,0,1,0,0,0,0,0,3]
}],
});
var classComplexity = new Highcharts.Chart({
chart: {
renderTo: 'classComplexity',
type: 'scatter'
},
title: {text: ''},
legend: {enabled: false},
credits: {enabled: false},
xAxis: {
title: {text: 'Code Coverage (in percent)'},
labels: {enabled: true},
},
yAxis: {
title: {text: 'Cyclomatic Complexity'},
labels: {enabled: true},
},
tooltip: {
formatter: function() {
return this.point.config[2];
}
},
series: [{
data: [[100,1,"<a href=\"models_M_account.php.html#3\">M_Account<\/a>"],[40.909090909090914,9,"<a href=\"models_Model_jadwal.php.html#3\">Model_jadwal<\/a>"],[100,4,"<a href=\"models_Model_users.php.html#3\">Model_users<\/a>"],[100,2,"<a href=\"models_list_mhs.php.html#3\">List_mhs<\/a>"]],
marker: {
symbol: 'diamond'
}
}],
});
});
</script>
</body>
</html>
| kveeen/monitorTA | application/tests/build/coverage/models.dashboard.html | HTML | mit | 3,813 |
version https://git-lfs.github.com/spec/v1
oid sha256:c61d4a2666180088d3586fda6904896a5d55e669bd0d936740603cd38ef4872f
size 366
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.0/datatable-paginator/lang/datatable-paginator.js | JavaScript | mit | 128 |
'use strict';
import fetch from 'cross-fetch';
/**
* Time stamp regex that AlphaVantage uses.
*/
const timestamp = /[0-9]{4}-[0-9]{2}-[0-9]{2}( [0-9]{2}:[0-9]{2}:[0-9]{2})?/g;
/**
* Price regex for target markets in target currency.
*/
const cryptoMarketPrice = /1a\. price \(.*\)/g;
/**
* Price open regex for target markets in target currency.
*/
const cryptoMarketOpen = /1a\. open \(.*\)/g;
/**
* Price high regex for target markets in target currency.
*/
const cryptoMarketHigh = /2a\. high \(.*\)/g;
/**
* Price low regex for target markets in target currency.
*/
const cryptoMarketLow = /3a\. low \(.*\)/g;
/**
* Price close regex for target markets in target currency.
*/
const cryptoMarketClose = /4a\. close \(.*\)/g;
/**
* The data keys to replace from the AlphaVantage API.
*/
const keys = {
'Aroon Down': 'down',
'Aroon Up': 'up',
'Meta Data': 'meta',
'Realtime Currency Exchange Rate': 'rate',
'Rank A: Real-Time Performance': 'real',
'Rank B: 1 Day Performance': '1day',
'Rank C: 5 Day Performance': '5day',
'Rank D: 1 Month Performance': '1month',
'Rank E: 3 Month Performance': '3month',
'Rank F: Year-to-Date (YTD) Performance': 'ytd',
'Rank G: 1 Year Performance': '1year',
'Rank H: 3 Year Performance': '3year',
'Rank I: 5 Year Performance': '5year',
'Rank J: 10 Year Performance': '10year',
Information: 'information',
'Last Refreshed': 'updated',
'Time Series (1min)': 'data',
'Time Series (Daily)': 'data',
'Time Series (Digital Currency Intraday)': 'data',
'Time Series (Digital Currency Daily)': 'data',
'Time Series (Digital Currency Weekly)': 'data',
'Time Series (Digital Currency Monthly)': 'data',
'Time Series FX (Daily)': 'data',
'Time Series FX (1min)': 'data',
'Time Series FX (5min)': 'data',
'Time Series FX (15min)': 'data',
'Time Series FX (30min)': 'data',
'Time Series FX (60min)': 'data',
'Time Series FX (Weekly)': 'data',
'Time Series FX (Monthly)': 'data',
'Weekly Time Series': 'data',
'Weekly Adjusted Time Series': 'data',
'Monthly Adjusted Time Series': 'data',
'Monthly Time Series': 'data',
'Stock Quotes': 'data',
'Global Quote': 'data',
'Technical Analysis: SMA': 'data',
'Technical Analysis: EMA': 'data',
'Technical Analysis: WMA': 'data',
'Technical Analysis: DEMA': 'data',
'Technical Analysis: TEMA': 'data',
'Technical Analysis: TRIMA': 'data',
'Technical Analysis: KAMA': 'data',
'Technical Analysis: MAMA': 'data',
'Technical Analysis: T3': 'data',
'Technical Analysis: MACD': 'data',
'Technical Analysis: MACDEXT': 'data',
'Technical Analysis: STOCH': 'data',
'Technical Analysis: STOCHF': 'data',
'Technical Analysis: RSI': 'data',
'Technical Analysis: STOCHRSI': 'data',
'Technical Analysis: WILLR': 'data',
'Technical Analysis: ADX': 'data',
'Technical Analysis: ADXR': 'data',
'Technical Analysis: APO': 'data',
'Technical Analysis: PPO': 'data',
'Technical Analysis: MOM': 'data',
'Technical Analysis: BOP': 'data',
'Technical Analysis: CCI': 'data',
'Technical Analysis: CMO': 'data',
'Technical Analysis: ROC': 'data',
'Technical Analysis: ROCR': 'data',
'Technical Analysis: AROON': 'data',
'Technical Analysis: AROONOSC': 'data',
'Technical Analysis: MFI': 'data',
'Technical Analysis: TRIX': 'data',
'Technical Analysis: ULTOSC': 'data',
'Technical Analysis: DX': 'data',
'Technical Analysis: MINUS_DI': 'data',
'Technical Analysis: PLUS_DI': 'data',
'Technical Analysis: MINUS_DM': 'data',
'Technical Analysis: PLUS_DM': 'data',
'Technical Analysis: BBANDS': 'data',
'Technical Analysis: MIDPOINT': 'data',
'Technical Analysis: MIDPRICE': 'data',
'Technical Analysis: SAR': 'data',
'Technical Analysis: TRANGE': 'data',
'Technical Analysis: ATR': 'data',
'Technical Analysis: NATR': 'data',
'Technical Analysis: Chaikin A/D': 'data',
'Technical Analysis: ADOSC': 'data',
'Technical Analysis: OBV': 'data',
'Technical Analysis: HT_TRENDLINE': 'data',
'Technical Analysis: HT_SINE': 'data',
'Technical Analysis: HT_TRENDMODE': 'data',
'Technical Analysis: HT_DCPERIOD': 'data',
'Technical Analysis: HT_DCPHASE': 'data',
'Technical Analysis: HT_PHASOR': 'data',
'01. symbol': 'symbol',
'02. open': 'open',
'03. high': 'high',
'04. low': 'low',
'05. price': 'price',
'06. volume': 'volume',
'07. latest trading day': 'latest_trading_day',
'08. previous close': 'prev_close',
'09. change': 'change',
'10. change percent': 'change_percent',
'1. Information': 'information',
'1. From_Currency Code': 'from_currency',
'2. From Symbol': 'from_currency',
'1: Symbol': 'symbol',
'1. open': 'open',
'1b. price (USD)': 'usd',
'1b. open (USD)': 'usd_open',
'2. price': 'price',
'2. high': 'high',
'2. From_Currency Name': 'from_currency_name',
'2. Symbol': 'symbol',
'2. volume': 'volume',
'2: Indicator': 'indicator',
'2. Digital Currency Code': 'coin',
'2b. high (USD)': 'usd_high',
'3. low': 'low',
'3. To_Currency Code': 'to_currency',
'3. To Symbol': 'to_currency',
'3. Last Refreshed': 'updated',
'4. Last Refreshed': 'updated',
'3. Digital Currency Name': 'coin_name',
'3. market cap (USD)': 'cap',
'3. volume': 'volume',
'3b. low (USD)': 'usd_low',
'4. Output Size': 'size',
'4. To_Currency Name': 'to_currency_name',
'4. close': 'close',
'4. Interval': 'interval',
'5. Interval': 'interval',
'4. Market Code': 'market',
'4. Time Zone': 'zone',
'4. timestamp': 'updated',
'4b. close (USD)': 'usd_close',
'5. adjusted close': 'adjusted',
'5. Exchange Rate': 'value',
'5. Market Name': 'market_name',
'5: Time Period': 'period',
'5. Output Size': 'size',
'6. Output Size': 'size',
'5. Time Zone': 'zone',
'5. volume': 'volume',
'5: Series Type': 'series',
'5.1: Fast Limit': 'fastlimit',
'5.1: Fast Period': 'fastperiod',
'5.1: FastK Period': 'fastkperiod',
'5.1: Acceleration': 'acceleration',
'5.1: Time Period 1': 'timeperiod1',
'5.2: Slow Limit': 'slowlimit',
'5.2: Slow Period': 'slowperiod',
'5.2: SlowK Period': 'slowkperiod',
'5.2: FastD Period': 'fastdperiod',
'5.2: SlowK Period': 'slowkperiod',
'5.2: Maximum': 'maximum',
'5.2: Time Period 2': 'timeperiod2',
'5.3: Signal Period': 'signalperiod',
'5.3: SlowK MA Type': 'slowkmatype',
'5.3: FastD MA Type': 'fastdmatype',
'5.3: MA Type': 'matype',
'5.3: Time Period 3': 'timeperiod3',
'5.4: Fast MA Type': 'fastmatype',
'5.4: SlowD Period': 'slowdperiod',
'5.5: Slow MA Type': 'slowmatype',
'5.5: SlowD MA Type': 'slowdmatype',
'5.6: Signal MA Type': 'signalmatype',
'6. volume': 'volume',
'6. Time Zone': 'zone',
'6. market cap (USD)': 'cap',
'5. Last Refreshed': 'updated',
'6. Last Refreshed': 'updated',
'6: Volume Factor (vFactor)': 'volume',
'6: Series Type': 'series',
'6. Interval': 'interval',
'6.1: FastK Period': 'fastkperiod',
'6.1: Deviation multiplier for upper band': 'nbdevup',
'6.2: FastD Period': 'fastdperiod',
'6.2: Deviation multiplier for lower band': 'nbdevdn',
'6.3: FastD MA Type': 'fastdmatype',
'6.3: MA Type': 'matype',
'7: Series Type': 'series',
'7. Time Zone': 'zone',
'7. Last Refreshed': 'updated',
'7. dividend amount': 'dividend',
'8. Time Zone': 'zone',
'8. split coefficient': 'split',
'1. symbol': 'symbol',
'2. name': 'name',
'3. type': 'type',
'4. region': 'region',
'5. marketOpen': 'market_open',
'6. marketClose': 'market_close',
'7. timezone': 'zone',
'8. currency': 'currency',
'9. matchScore': 'match_score'
};
export default (config) => {
/**
* Recursively walk the data tree and replace weird keys with a normalized set.
*
* @param {Object|String|Number} data
* The data to normalize.
*
* @returns {Object|String|Number}
* Normalized data.
*/
const polish = (data) => {
// If this is not an object, dont recurse.
if (!data || typeof data !== 'object') {
return data;
}
// If the data is a complex object, walk all subtrees to normalize all branches.
let clean = {};
Object.keys(data).forEach((key) => {
key = key.toString();
// If the key is a date time string, convert it to an iso timestamp.
if (timestamp.test(key)) {
clean[new Date(key).toISOString()] = polish(data[key]);
return;
}
// Rekey the crypto market open currency.
if (cryptoMarketOpen.test(key)) {
clean['market_open'] = polish(data[key]);
return;
}
// Rekey the crypto market high currency.
if (cryptoMarketHigh.test(key)) {
clean['market_high'] = polish(data[key]);
return;
}
// Rekey the crypto market low currency.
if (cryptoMarketLow.test(key)) {
clean['market_low'] = polish(data[key]);
return;
}
// Rekey the crypto market close currency.
if (cryptoMarketClose.test(key)) {
clean['market_close'] = polish(data[key]);
return;
}
clean[keys[key] || key] = polish(data[key]);
});
return clean;
};
/**
* Util function to build the proper API url.
*
* @param {Object} params
* The parameter object as type:value pairs.
*
* @returns {String}
* The API url to use for a given function and input parameters.
*/
const url = (params) => {
params = Object.keys(params || {})
.map((type) => {
let value = params[type];
if (value !== undefined) {
return `${type}=${value}`;
}
return undefined;
})
.filter((value) => value !== undefined)
.join('&');
return `${config.base}${params}`;
};
/**
* Wrapper function generator for any endpoint.
*
* @param {String} type
* The API function type to use
*
* @returns {Function}
* The callback function to use in the sdk.
*/
const fn = (type) => (params) =>
fetch(url(Object.assign({}, params, { function: type })))
.then((res) => {
if (res.status !== 200) {
throw `An AlphaVantage error occurred. ${res.status}: ${res.text()}`;
}
return res.json();
})
.then((data) => {
if (
data['Meta Data'] === undefined &&
data['Realtime Currency Exchange Rate'] === undefined &&
data['Global Quote'] === undefined &&
data['bestMatches'] === undefined &&
data['Symbol'] === undefined &&
data['symbol'] === undefined &&
data['name'] === undefined &&
data['interval'] === undefined &&
data['unit'] === undefined &&
data['data'] === undefined
) {
throw `An AlphaVantage error occurred. ${data['Information'] || JSON.stringify(data)}`;
}
return data;
});
return {
url,
polish,
fn
};
};
| zackurben/alphavantage | lib/util.js | JavaScript | mit | 10,872 |
using System.Collections.Generic;
using UnityEngine.Assertions;
namespace GGM.Core
{
public interface IObjectPool
{
int RemainingObjectCount { get; }
void OnDestroyPool();
}
public abstract class ObjectPool<T>: IObjectPool where T : class
{
protected Queue<T> _objects;
private int _startSize = 0;
public int RemainingObjectCount
{
get { return _objects.Count; }
}
public bool IsDestroied { get; private set; }
/// <param name="objectCreator">Object를 생성하는 Func.</param>
protected ObjectPool()
{
InitObjectPool();
}
/// <param name="objectCreator">Object를 생성하는 Func.</param>
/// <param name="size">Pool의 크기, 2의 배수일 수록 좋습니다.</param>
protected ObjectPool(int size)
{
InitObjectPool(size);
}
private void InitObjectPool(int size = 16)
{
IsDestroied = false;
_startSize = size;
_objects = new Queue<T>(size);
Allocate(size);
}
/// <summary>
/// 객체를 생성하는 메소드입니다. 상속받아 객체를 생성하고 반환해야합니다.
/// </summary>
/// <returns>생성되는 객체.</returns>
protected abstract T CreateObject();
/// <summary>
/// 객체를 반환할때 쓰는 메소드입니다.
/// 풀이 파괴되어 있는 경우에는 해당 객체에 대해 DestoryObject를 실행합니다.
/// </summary>
/// <param name="returnObject">반활 될 객체입니다.</param>
public void EnqueueObject(T returnObject)
{
if (IsDestroied == true)
DestroyObject(returnObject);
else
{
EnqueueProcess(returnObject);
_objects.Enqueue(returnObject);
}
}
/// <summary>
/// Enqueue시 마다, Enqueue되는 오브젝트에 적용되는 처리.
/// </summary>
/// <param name="enqueuedObject">Enqueue되는 오브젝트</param>
protected abstract void EnqueueProcess(T enqueuedObject);
/// <summary>
/// 객체를 꺼낼때 쓰는 메소드입니다. 만일 풀에 남아있는 객체가 없으면, 초기화때 지정된 사이즈만큼 재 생성 해줍니다.
/// 이는 부하가 생길 수 있으니 초기화 단계에서 사이즈를 잘 잡아주어야 합니다.
/// </summary>
/// <returns>풀에서 꺼내지는 객체입니다.</returns>
public T DequeueObject()
{
Assert.IsFalse(IsDestroied, "풀이 이미 파괴되어있습니다.");
if (_objects.Count == 0)
Allocate(_startSize);
var dequeuedObject = _objects.Dequeue();
DequeueProcess(dequeuedObject);
return dequeuedObject;
}
/// <summary>
/// Dequeue시 마다, Dequeue되는 오브젝트에 적용되는 처리.
/// </summary>
/// <param name="dequeuedObject">Dequeue되는 오브젝트</param>
protected abstract void DequeueProcess(T dequeuedObject);
private void Allocate(int size)
{
for (int i = 0; i < size; i++)
EnqueueObject(CreateObject());
}
/// <summary>
/// 풀을 파괴할때 호출되는 메소드입니다. 직접적으로 호출해선 안됩니다.
/// ObjectPoolService를 통해 풀을 Remove해주어야합니다.
/// </summary>
public void OnDestroyPool()
{
IsDestroied = true;
foreach (var destroiedObject in _objects)
DestroyObject(destroiedObject);
_objects.Clear();
}
/// <summary>
/// 객체가 파괴되어야 할때 각 처리가 필요한 경우 해당 메소드를 상속받아 처리합니다.
/// 이는 OnDestroyPool에서 풀에 있는 객체마다 하나씩 실행해 준 뒤 풀을 Clear합니다.
/// 또한 풀이 파괴된 이후 반환되는 객체에 대해서도 호출됩니다.
/// </summary>
/// <param name="destroiedObject"></param>
protected virtual void DestroyObject(T destroiedObject) { }
}
} | GoodGoodJM/GGMFramework | Assets/GGM/Scripts/Core/ObjectPool.cs | C# | mit | 4,391 |
require 'test/unit'
require 'resource_template'
class TestResourceTemplate < Test::Unit::TestCase
attr_reader :json, :resource_templates, :resource_templates_by_name, :user, :user_articles, :user_article, :edit_user_article
def setup
@json ||= File.read(File.dirname(__FILE__) + '/fixtures/described_routes_test.json')
@resource_templates = ResourceTemplate::ResourceTemplates.new(JSON.parse(@json))
@resource_templates_by_name = @resource_templates.all_by_name
@user = @resource_templates_by_name['user']
@user_articles = @resource_templates_by_name['user_articles']
@user_article = @resource_templates_by_name['user_article']
@edit_user_article = @resource_templates_by_name['edit_user_article']
end
def test_fixture
assert_kind_of(ResourceTemplate, user_articles)
assert_kind_of(ResourceTemplate, user_article)
assert_kind_of(ResourceTemplate, edit_user_article)
assert_equal('user_article', user_article.name)
assert_equal(['user_id', 'article_id'], user_article.params)
assert_equal(['format'], user_article.optional_params)
assert_equal('articles', user_articles.rel)
assert_nil(user_article.rel)
assert_equal('edit', edit_user_article.rel)
assert_equal('/users/{user_id}/articles{-prefix|.|format}', user_articles.path_template)
assert_equal('http://localhost:3000/users/{user_id}/articles{-prefix|.|format}', user_articles.uri_template)
assert(user_articles.resource_templates.member?(user_article))
assert(user_article.resource_templates.member?(edit_user_article))
end
def test_json
assert_equal(
JSON.parse(json),
JSON.parse(resource_templates.to_json))
end
def test_yaml
assert_equal(
JSON.parse(json),
YAML.load(resource_templates.to_yaml))
end
def test_find_by_rel
assert_equal([user_article], user_articles.find_by_rel(nil))
assert_equal([edit_user_article], user_article.find_by_rel('edit'))
end
def test_positional_params
assert_equal(['user_id', 'article_id', 'format'], user_article.positional_params(nil))
assert_equal(['article_id', 'format'], user_article.positional_params(user_articles))
end
def test_partial_expand
expanded_user_articles = user_articles.partial_expand('user_id' => 'dojo', 'format' => 'json')
expanded_edit_user_article = expanded_user_articles.resource_templates.all_by_name['edit_user_article']
assert_equal(['article_id'], expanded_edit_user_article.params)
assert(expanded_edit_user_article.optional_params.empty?)
assert_equal('/users/dojo/articles/{article_id}/edit.json', expanded_edit_user_article.path_template)
end
def test_uri_for
assert_equal('http://localhost:3000/users/dojo/articles', user_articles.uri_for('user_id' => 'dojo'))
assert_equal('http://localhost:3000/users/dojo/articles.json', user_articles.uri_for('user_id' => 'dojo', 'format' => 'json'))
end
def test_uri_for_with_missing_params
assert_raises(ArgumentError) do
user_articles.uri_for('format' => 'json') # no user_id param
end
end
def test_uri_for_with_no_uri_template
users = ResourceTemplate.new('path_template' => '/users')
assert_raises(RuntimeError) do
users.uri_for({})
end
assert_equal('http://localhost:3000/users', users.uri_for({}, 'http://localhost:3000'))
end
def test_path_for
assert_equal('/users/dojo/articles', user_articles.path_for('user_id' => 'dojo'))
assert_equal('/users/dojo/articles.json', user_articles.path_for('user_id' => 'dojo', 'format' => 'json'))
end
def test_path_for_with_missing_params
assert_raises(ArgumentError) do
user_articles.path_for('format' => 'json') # no user_id param
end
end
def test_path_for_with_no_path_template
assert_raises(RuntimeError) do
ResourceTemplate.new.path_for({}) # no path_template
end
end
def test_parent
assert_equal("user", user_articles.parent.name)
assert_equal("users", user_articles.parent.parent.name)
assert_nil(user_articles.parent.parent.parent)
end
def test_expand_links
assert_equal(
[
{
"name" => "new_user_article",
"options" => ["GET"],
"path_template" => "/users/dojo/articles/new{-prefix|.|format}",
"uri_template" => "http://localhost:3000/users/dojo/articles/new{-prefix|.|format}",
"rel" => "new_user_article",
"optional_params" => ["format"]
},
{
"name" => "recent_user_articles",
"options" => ["GET"],
"path_template" => "/users/dojo/articles/recent{-prefix|.|format}",
"uri_template" => "http://localhost:3000/users/dojo/articles/recent{-prefix|.|format}",
"rel" => "recent",
"optional_params" => ["format"]
}
],
user_articles.resource_templates.expand_links({'user_id' => 'dojo'}).to_parsed)
end
def test_all_preorder
assert_equal(
[
"user",
"user_articles",
"user_article",
"edit_user_article",
"new_user_article",
"recent_user_articles",
"edit_user",
"user_profile",
"edit_user_profile",
"new_user_profile"
],
user.all_preorder.map{|rt| rt.name})
end
def test_all_postorder
assert_equal(
[
"edit_user_article",
"user_article",
"new_user_article",
"recent_user_articles",
"user_articles",
"edit_user",
"edit_user_profile",
"new_user_profile",
"user_profile",
"user"
],
user.all_postorder.map{|rt| rt.name})
end
end
| asplake/described_routes | test/test_resource_template.rb | Ruby | mit | 5,761 |
require File.dirname(__FILE__) + '/test_helper'
class TestingController < ActionController::Base
self.view_paths = [ File.dirname(__FILE__) + "/views" ]
private
def rescue_action(exception); exception; end
end
class PeopleController < TestingController
def show
@person = 'Timothy'
end
end
class PeoplePresenter < ApplicationPresenter
attr_accessor :person
def display_name
content_tag(:h1, person)
end
end
class RenderWithPresenterTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = PeopleController.new
end
def test_rendering_from_a_controller_uses_the_presenter_for_that_controller
get :show
assert_equal "<h1>Tim</h1>", @response.body
end
end
#
# class DeterminingDefaultPresenter < Test::Unit::TestCase
# def setup
# @request = ActionController::TestRequest.new
# @response = ActionController::TestResponse.new
# @request.host = "www.example.com"
# end
#
# def test_rendering_an_action_for_a_controller_that_has_its_own_presenter_uses_that_presenter_as_the_template
# @controller = PeopleController.new
# get :noop
# assert_equal PeoplePresenter, @response.template.class
# end
#
# def test_rendering_an_action_for_a_controller_that_does_not_have_its_own_presenter_uses_the_application_presenter_as_the_template
# @controller = AccountsController.new
# get :noop
# assert_equal ApplicationPresenter, @response.template.class
# end
#
# def test_rendering_a_partial_from_a_different_controller_without_explicitly_specifying_which_presenter_to_use_chooses_the_presenter_for_the_controller_where_the_partial_lives_if_it_exists
# @controller = AccountsController.new
#
# # The initial wrapping presenter
# flexmock(ApplicationPresenter).new_instances.should_receive(:new).once.ordered
# flexmock(ApplicationPresenter).new_instances.should_receive(:rendering_template_from_another_controller?).once.ordered
# # Then one PeoplePresenter for each of the two person partials rendered from the people/ view directory
# flexmock(PeoplePresenter).new_instances.should_receive(:new).once.ordered
# get :list
# end
#
# def test_object_passed_to_partial_is_set_as_an_attribute_of_the_presenter_used_to_render_the_partial_rathern_than_just_a_local
# @controller = AccountsController.new
# # The object was passed to the partial
# assert_nothing_raised do
# get :list
# end
# assert_match %r|<h1>Tim</h1>|, @response.body
# end
# end
| mvanholstyn/render_with_presenter | test/render_with_presenter_test.rb | Ruby | mit | 2,627 |
module Pohoda
module Builders
module Ofr
class OfferSummaryType
include ParserCore::BaseBuilder
def builder
root = Ox::Element.new(name)
root = add_attributes_and_namespaces(root)
root << build_element('ofr:roundingDocument', data[:rounding_document], data[:rounding_document_attributes]) if data.key? :rounding_document
root << build_element('ofr:roundingVAT', data[:rounding_vat], data[:rounding_vat_attributes]) if data.key? :rounding_vat
root << build_element('ofr:typeCalculateVATInclusivePrice', data[:type_calculate_vat_inclusive_price], data[:type_calculate_vat_inclusive_price_attributes]) if data.key? :type_calculate_vat_inclusive_price
if data.key? :home_currency
root << Typ::TypeCurrencyHome.new('ofr:homeCurrency', data[:home_currency]).builder
end
if data.key? :foreign_currency
root << Typ::TypeCurrencyForeign.new('ofr:foreignCurrency', data[:foreign_currency]).builder
end
root
end
end
end
end
end | Masa331/pohoda | lib/pohoda/builders/ofr/offer_summary_type.rb | Ruby | mit | 1,091 |
/* -- translated by f2c (version 20100827).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
/* Table of constant values */
static int c__1 = 1;
static int c_false = FALSE_;
static int c__2 = 2;
static double c_b26 = 1.;
static double c_b30 = 0.;
static int c_true = TRUE_;
int RELAPACK_dtrsyl_rec2(char *trana, char *tranb, int *isgn, int
*m, int *n, double *a, int *lda, double *b, int *
ldb, double *c__, int *ldc, double *scale, int *info)
{
/* System generated locals */
int a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2,
i__3, i__4;
double d__1, d__2;
/* Local variables */
static int j, k, l;
static double x[4] /* was [2][2] */;
static int k1, k2, l1, l2;
static double a11, db, da11, vec[4] /* was [2][2] */, dum[1], eps,
sgn;
extern double ddot_(int *, double *, int *, double *,
int *);
static int ierr;
static double smin, suml, sumr;
extern /* Subroutine */ int dscal_(int *, double *, double *,
int *);
extern int lsame_(char *, char *, ftnlen, ftnlen);
static int knext, lnext;
static double xnorm;
extern /* Subroutine */ int dlaln2_(int *, int *, int *,
double *, double *, double *, int *, double *,
double *, double *, int *, double *, double *
, double *, int *, double *, double *, int *),
dlasy2_(int *, int *, int *, int *, int *,
double *, int *, double *, int *, double *,
int *, double *, double *, int *, double *,
int *), dlabad_(double *, double *);
extern double dlamch_(char *, ftnlen), dlange_(char *, int *,
int *, double *, int *, double *, ftnlen);
static double scaloc;
extern /* Subroutine */ int xerbla_(char *, int *, ftnlen);
static double bignum;
static int notrna, notrnb;
static double smlnum;
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
b_dim1 = *ldb;
b_offset = 1 + b_dim1;
b -= b_offset;
c_dim1 = *ldc;
c_offset = 1 + c_dim1;
c__ -= c_offset;
/* Function Body */
notrna = lsame_(trana, "N", (ftnlen)1, (ftnlen)1);
notrnb = lsame_(tranb, "N", (ftnlen)1, (ftnlen)1);
*info = 0;
if (! notrna && ! lsame_(trana, "T", (ftnlen)1, (ftnlen)1) && ! lsame_(
trana, "C", (ftnlen)1, (ftnlen)1)) {
*info = -1;
} else if (! notrnb && ! lsame_(tranb, "T", (ftnlen)1, (ftnlen)1) && !
lsame_(tranb, "C", (ftnlen)1, (ftnlen)1)) {
*info = -2;
} else if (*isgn != 1 && *isgn != -1) {
*info = -3;
} else if (*m < 0) {
*info = -4;
} else if (*n < 0) {
*info = -5;
} else if (*lda < max(1,*m)) {
*info = -7;
} else if (*ldb < max(1,*n)) {
*info = -9;
} else if (*ldc < max(1,*m)) {
*info = -11;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DTRSYL", &i__1, (ftnlen)6);
return 0;
}
*scale = 1.;
if (*m == 0 || *n == 0) {
return 0;
}
eps = dlamch_("P", (ftnlen)1);
smlnum = dlamch_("S", (ftnlen)1);
bignum = 1. / smlnum;
dlabad_(&smlnum, &bignum);
smlnum = smlnum * (double) (*m * *n) / eps;
bignum = 1. / smlnum;
/* Computing MAX */
d__1 = smlnum, d__2 = eps * dlange_("M", m, m, &a[a_offset], lda, dum, (
ftnlen)1), d__1 = max(d__1,d__2), d__2 = eps * dlange_("M", n, n,
&b[b_offset], ldb, dum, (ftnlen)1);
smin = max(d__1,d__2);
sgn = (double) (*isgn);
if (notrna && notrnb) {
lnext = 1;
i__1 = *n;
for (l = 1; l <= i__1; ++l) {
if (l < lnext) {
goto L60;
}
if (l == *n) {
l1 = l;
l2 = l;
} else {
if (b[l + 1 + l * b_dim1] != 0.) {
l1 = l;
l2 = l + 1;
lnext = l + 2;
} else {
l1 = l;
l2 = l;
lnext = l + 1;
}
}
knext = *m;
for (k = *m; k >= 1; --k) {
if (k > knext) {
goto L50;
}
if (k == 1) {
k1 = k;
k2 = k;
} else {
if (a[k + (k - 1) * a_dim1] != 0.) {
k1 = k - 1;
k2 = k;
knext = k - 2;
} else {
k1 = k;
k2 = k;
knext = k - 1;
}
}
if (l1 == l2 && k1 == k2) {
i__2 = *m - k1;
/* Computing MIN */
i__3 = k1 + 1;
/* Computing MIN */
i__4 = k1 + 1;
suml = ddot_(&i__2, &a[k1 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l1 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
scaloc = 1.;
a11 = a[k1 + k1 * a_dim1] + sgn * b[l1 + l1 * b_dim1];
da11 = abs(a11);
if (da11 <= smin) {
a11 = smin;
da11 = smin;
*info = 1;
}
db = abs(vec[0]);
if (da11 < 1. && db > 1.) {
if (db > bignum * da11) {
scaloc = 1. / db;
}
}
x[0] = vec[0] * scaloc / a11;
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L10: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
} else if (l1 == l2 && k1 != k2) {
i__2 = *m - k2;
/* Computing MIN */
i__3 = k2 + 1;
/* Computing MIN */
i__4 = k2 + 1;
suml = ddot_(&i__2, &a[k1 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l1 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__2 = *m - k2;
/* Computing MIN */
i__3 = k2 + 1;
/* Computing MIN */
i__4 = k2 + 1;
suml = ddot_(&i__2, &a[k2 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l1 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k2 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
d__1 = -sgn * b[l1 + l1 * b_dim1];
dlaln2_(&c_false, &c__2, &c__1, &smin, &c_b26, &a[k1 + k1
* a_dim1], lda, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L20: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k2 + l1 * c_dim1] = x[1];
} else if (l1 != l2 && k1 == k2) {
i__2 = *m - k1;
/* Computing MIN */
i__3 = k1 + 1;
/* Computing MIN */
i__4 = k1 + 1;
suml = ddot_(&i__2, &a[k1 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l1 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = sgn * (c__[k1 + l1 * c_dim1] - (suml + sgn *
sumr));
i__2 = *m - k1;
/* Computing MIN */
i__3 = k1 + 1;
/* Computing MIN */
i__4 = k1 + 1;
suml = ddot_(&i__2, &a[k1 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l2 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k1 + c_dim1], ldc, &b[l2 *
b_dim1 + 1], &c__1);
vec[1] = sgn * (c__[k1 + l2 * c_dim1] - (suml + sgn *
sumr));
d__1 = -sgn * a[k1 + k1 * a_dim1];
dlaln2_(&c_true, &c__2, &c__1, &smin, &c_b26, &b[l1 + l1 *
b_dim1], ldb, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L30: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[1];
} else if (l1 != l2 && k1 != k2) {
i__2 = *m - k2;
/* Computing MIN */
i__3 = k2 + 1;
/* Computing MIN */
i__4 = k2 + 1;
suml = ddot_(&i__2, &a[k1 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l1 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__2 = *m - k2;
/* Computing MIN */
i__3 = k2 + 1;
/* Computing MIN */
i__4 = k2 + 1;
suml = ddot_(&i__2, &a[k1 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l2 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k1 + c_dim1], ldc, &b[l2 *
b_dim1 + 1], &c__1);
vec[2] = c__[k1 + l2 * c_dim1] - (suml + sgn * sumr);
i__2 = *m - k2;
/* Computing MIN */
i__3 = k2 + 1;
/* Computing MIN */
i__4 = k2 + 1;
suml = ddot_(&i__2, &a[k2 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l1 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k2 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
i__2 = *m - k2;
/* Computing MIN */
i__3 = k2 + 1;
/* Computing MIN */
i__4 = k2 + 1;
suml = ddot_(&i__2, &a[k2 + min(i__3,*m) * a_dim1], lda, &
c__[min(i__4,*m) + l2 * c_dim1], &c__1);
i__2 = l1 - 1;
sumr = ddot_(&i__2, &c__[k2 + c_dim1], ldc, &b[l2 *
b_dim1 + 1], &c__1);
vec[3] = c__[k2 + l2 * c_dim1] - (suml + sgn * sumr);
dlasy2_(&c_false, &c_false, isgn, &c__2, &c__2, &a[k1 +
k1 * a_dim1], lda, &b[l1 + l1 * b_dim1], ldb, vec,
&c__2, &scaloc, x, &c__2, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L40: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[2];
c__[k2 + l1 * c_dim1] = x[1];
c__[k2 + l2 * c_dim1] = x[3];
}
L50:
;
}
L60:
;
}
} else if (! notrna && notrnb) {
lnext = 1;
i__1 = *n;
for (l = 1; l <= i__1; ++l) {
if (l < lnext) {
goto L120;
}
if (l == *n) {
l1 = l;
l2 = l;
} else {
if (b[l + 1 + l * b_dim1] != 0.) {
l1 = l;
l2 = l + 1;
lnext = l + 2;
} else {
l1 = l;
l2 = l;
lnext = l + 1;
}
}
knext = 1;
i__2 = *m;
for (k = 1; k <= i__2; ++k) {
if (k < knext) {
goto L110;
}
if (k == *m) {
k1 = k;
k2 = k;
} else {
if (a[k + 1 + k * a_dim1] != 0.) {
k1 = k;
k2 = k + 1;
knext = k + 2;
} else {
k1 = k;
k2 = k;
knext = k + 1;
}
}
if (l1 == l2 && k1 == k2) {
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
scaloc = 1.;
a11 = a[k1 + k1 * a_dim1] + sgn * b[l1 + l1 * b_dim1];
da11 = abs(a11);
if (da11 <= smin) {
a11 = smin;
da11 = smin;
*info = 1;
}
db = abs(vec[0]);
if (da11 < 1. && db > 1.) {
if (db > bignum * da11) {
scaloc = 1. / db;
}
}
x[0] = vec[0] * scaloc / a11;
if (scaloc != 1.) {
i__3 = *n;
for (j = 1; j <= i__3; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L70: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
} else if (l1 == l2 && k1 != k2) {
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k2 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k2 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
d__1 = -sgn * b[l1 + l1 * b_dim1];
dlaln2_(&c_true, &c__2, &c__1, &smin, &c_b26, &a[k1 + k1 *
a_dim1], lda, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__3 = *n;
for (j = 1; j <= i__3; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L80: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k2 + l1 * c_dim1] = x[1];
} else if (l1 != l2 && k1 == k2) {
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = sgn * (c__[k1 + l1 * c_dim1] - (suml + sgn *
sumr));
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k1 * a_dim1 + 1], &c__1, &c__[l2 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k1 + c_dim1], ldc, &b[l2 *
b_dim1 + 1], &c__1);
vec[1] = sgn * (c__[k1 + l2 * c_dim1] - (suml + sgn *
sumr));
d__1 = -sgn * a[k1 + k1 * a_dim1];
dlaln2_(&c_true, &c__2, &c__1, &smin, &c_b26, &b[l1 + l1 *
b_dim1], ldb, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__3 = *n;
for (j = 1; j <= i__3; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L90: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[1];
} else if (l1 != l2 && k1 != k2) {
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k1 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k1 * a_dim1 + 1], &c__1, &c__[l2 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k1 + c_dim1], ldc, &b[l2 *
b_dim1 + 1], &c__1);
vec[2] = c__[k1 + l2 * c_dim1] - (suml + sgn * sumr);
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k2 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k2 + c_dim1], ldc, &b[l1 *
b_dim1 + 1], &c__1);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
i__3 = k1 - 1;
suml = ddot_(&i__3, &a[k2 * a_dim1 + 1], &c__1, &c__[l2 *
c_dim1 + 1], &c__1);
i__3 = l1 - 1;
sumr = ddot_(&i__3, &c__[k2 + c_dim1], ldc, &b[l2 *
b_dim1 + 1], &c__1);
vec[3] = c__[k2 + l2 * c_dim1] - (suml + sgn * sumr);
dlasy2_(&c_true, &c_false, isgn, &c__2, &c__2, &a[k1 + k1
* a_dim1], lda, &b[l1 + l1 * b_dim1], ldb, vec, &
c__2, &scaloc, x, &c__2, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__3 = *n;
for (j = 1; j <= i__3; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L100: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[2];
c__[k2 + l1 * c_dim1] = x[1];
c__[k2 + l2 * c_dim1] = x[3];
}
L110:
;
}
L120:
;
}
} else if (! notrna && ! notrnb) {
lnext = *n;
for (l = *n; l >= 1; --l) {
if (l > lnext) {
goto L180;
}
if (l == 1) {
l1 = l;
l2 = l;
} else {
if (b[l + (l - 1) * b_dim1] != 0.) {
l1 = l - 1;
l2 = l;
lnext = l - 2;
} else {
l1 = l;
l2 = l;
lnext = l - 1;
}
}
knext = 1;
i__1 = *m;
for (k = 1; k <= i__1; ++k) {
if (k < knext) {
goto L170;
}
if (k == *m) {
k1 = k;
k2 = k;
} else {
if (a[k + 1 + k * a_dim1] != 0.) {
k1 = k;
k2 = k + 1;
knext = k + 2;
} else {
k1 = k;
k2 = k;
knext = k + 1;
}
}
if (l1 == l2 && k1 == k2) {
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__2 = *n - l1;
/* Computing MIN */
i__3 = l1 + 1;
/* Computing MIN */
i__4 = l1 + 1;
sumr = ddot_(&i__2, &c__[k1 + min(i__3,*n) * c_dim1], ldc,
&b[l1 + min(i__4,*n) * b_dim1], ldb);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
scaloc = 1.;
a11 = a[k1 + k1 * a_dim1] + sgn * b[l1 + l1 * b_dim1];
da11 = abs(a11);
if (da11 <= smin) {
a11 = smin;
da11 = smin;
*info = 1;
}
db = abs(vec[0]);
if (da11 < 1. && db > 1.) {
if (db > bignum * da11) {
scaloc = 1. / db;
}
}
x[0] = vec[0] * scaloc / a11;
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L130: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
} else if (l1 == l2 && k1 != k2) {
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k1 + min(i__3,*n) * c_dim1], ldc,
&b[l1 + min(i__4,*n) * b_dim1], ldb);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k2 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k2 + min(i__3,*n) * c_dim1], ldc,
&b[l1 + min(i__4,*n) * b_dim1], ldb);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
d__1 = -sgn * b[l1 + l1 * b_dim1];
dlaln2_(&c_true, &c__2, &c__1, &smin, &c_b26, &a[k1 + k1 *
a_dim1], lda, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L140: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k2 + l1 * c_dim1] = x[1];
} else if (l1 != l2 && k1 == k2) {
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k1 + min(i__3,*n) * c_dim1], ldc,
&b[l1 + min(i__4,*n) * b_dim1], ldb);
vec[0] = sgn * (c__[k1 + l1 * c_dim1] - (suml + sgn *
sumr));
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k1 * a_dim1 + 1], &c__1, &c__[l2 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k1 + min(i__3,*n) * c_dim1], ldc,
&b[l2 + min(i__4,*n) * b_dim1], ldb);
vec[1] = sgn * (c__[k1 + l2 * c_dim1] - (suml + sgn *
sumr));
d__1 = -sgn * a[k1 + k1 * a_dim1];
dlaln2_(&c_false, &c__2, &c__1, &smin, &c_b26, &b[l1 + l1
* b_dim1], ldb, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L150: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[1];
} else if (l1 != l2 && k1 != k2) {
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k1 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k1 + min(i__3,*n) * c_dim1], ldc,
&b[l1 + min(i__4,*n) * b_dim1], ldb);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k1 * a_dim1 + 1], &c__1, &c__[l2 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k1 + min(i__3,*n) * c_dim1], ldc,
&b[l2 + min(i__4,*n) * b_dim1], ldb);
vec[2] = c__[k1 + l2 * c_dim1] - (suml + sgn * sumr);
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k2 * a_dim1 + 1], &c__1, &c__[l1 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k2 + min(i__3,*n) * c_dim1], ldc,
&b[l1 + min(i__4,*n) * b_dim1], ldb);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
i__2 = k1 - 1;
suml = ddot_(&i__2, &a[k2 * a_dim1 + 1], &c__1, &c__[l2 *
c_dim1 + 1], &c__1);
i__2 = *n - l2;
/* Computing MIN */
i__3 = l2 + 1;
/* Computing MIN */
i__4 = l2 + 1;
sumr = ddot_(&i__2, &c__[k2 + min(i__3,*n) * c_dim1], ldc,
&b[l2 + min(i__4,*n) * b_dim1], ldb);
vec[3] = c__[k2 + l2 * c_dim1] - (suml + sgn * sumr);
dlasy2_(&c_true, &c_true, isgn, &c__2, &c__2, &a[k1 + k1 *
a_dim1], lda, &b[l1 + l1 * b_dim1], ldb, vec, &
c__2, &scaloc, x, &c__2, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__2 = *n;
for (j = 1; j <= i__2; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L160: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[2];
c__[k2 + l1 * c_dim1] = x[1];
c__[k2 + l2 * c_dim1] = x[3];
}
L170:
;
}
L180:
;
}
} else if (notrna && ! notrnb) {
lnext = *n;
for (l = *n; l >= 1; --l) {
if (l > lnext) {
goto L240;
}
if (l == 1) {
l1 = l;
l2 = l;
} else {
if (b[l + (l - 1) * b_dim1] != 0.) {
l1 = l - 1;
l2 = l;
lnext = l - 2;
} else {
l1 = l;
l2 = l;
lnext = l - 1;
}
}
knext = *m;
for (k = *m; k >= 1; --k) {
if (k > knext) {
goto L230;
}
if (k == 1) {
k1 = k;
k2 = k;
} else {
if (a[k + (k - 1) * a_dim1] != 0.) {
k1 = k - 1;
k2 = k;
knext = k - 2;
} else {
k1 = k;
k2 = k;
knext = k - 1;
}
}
if (l1 == l2 && k1 == k2) {
i__1 = *m - k1;
/* Computing MIN */
i__2 = k1 + 1;
/* Computing MIN */
i__3 = k1 + 1;
suml = ddot_(&i__1, &a[k1 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l1 * c_dim1], &c__1);
i__1 = *n - l1;
/* Computing MIN */
i__2 = l1 + 1;
/* Computing MIN */
i__3 = l1 + 1;
sumr = ddot_(&i__1, &c__[k1 + min(i__2,*n) * c_dim1], ldc,
&b[l1 + min(i__3,*n) * b_dim1], ldb);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
scaloc = 1.;
a11 = a[k1 + k1 * a_dim1] + sgn * b[l1 + l1 * b_dim1];
da11 = abs(a11);
if (da11 <= smin) {
a11 = smin;
da11 = smin;
*info = 1;
}
db = abs(vec[0]);
if (da11 < 1. && db > 1.) {
if (db > bignum * da11) {
scaloc = 1. / db;
}
}
x[0] = vec[0] * scaloc / a11;
if (scaloc != 1.) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L190: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
} else if (l1 == l2 && k1 != k2) {
i__1 = *m - k2;
/* Computing MIN */
i__2 = k2 + 1;
/* Computing MIN */
i__3 = k2 + 1;
suml = ddot_(&i__1, &a[k1 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l1 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k1 + min(i__2,*n) * c_dim1], ldc,
&b[l1 + min(i__3,*n) * b_dim1], ldb);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__1 = *m - k2;
/* Computing MIN */
i__2 = k2 + 1;
/* Computing MIN */
i__3 = k2 + 1;
suml = ddot_(&i__1, &a[k2 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l1 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k2 + min(i__2,*n) * c_dim1], ldc,
&b[l1 + min(i__3,*n) * b_dim1], ldb);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
d__1 = -sgn * b[l1 + l1 * b_dim1];
dlaln2_(&c_false, &c__2, &c__1, &smin, &c_b26, &a[k1 + k1
* a_dim1], lda, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L200: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k2 + l1 * c_dim1] = x[1];
} else if (l1 != l2 && k1 == k2) {
i__1 = *m - k1;
/* Computing MIN */
i__2 = k1 + 1;
/* Computing MIN */
i__3 = k1 + 1;
suml = ddot_(&i__1, &a[k1 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l1 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k1 + min(i__2,*n) * c_dim1], ldc,
&b[l1 + min(i__3,*n) * b_dim1], ldb);
vec[0] = sgn * (c__[k1 + l1 * c_dim1] - (suml + sgn *
sumr));
i__1 = *m - k1;
/* Computing MIN */
i__2 = k1 + 1;
/* Computing MIN */
i__3 = k1 + 1;
suml = ddot_(&i__1, &a[k1 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l2 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k1 + min(i__2,*n) * c_dim1], ldc,
&b[l2 + min(i__3,*n) * b_dim1], ldb);
vec[1] = sgn * (c__[k1 + l2 * c_dim1] - (suml + sgn *
sumr));
d__1 = -sgn * a[k1 + k1 * a_dim1];
dlaln2_(&c_false, &c__2, &c__1, &smin, &c_b26, &b[l1 + l1
* b_dim1], ldb, &c_b26, &c_b26, vec, &c__2, &d__1,
&c_b30, x, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L210: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[1];
} else if (l1 != l2 && k1 != k2) {
i__1 = *m - k2;
/* Computing MIN */
i__2 = k2 + 1;
/* Computing MIN */
i__3 = k2 + 1;
suml = ddot_(&i__1, &a[k1 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l1 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k1 + min(i__2,*n) * c_dim1], ldc,
&b[l1 + min(i__3,*n) * b_dim1], ldb);
vec[0] = c__[k1 + l1 * c_dim1] - (suml + sgn * sumr);
i__1 = *m - k2;
/* Computing MIN */
i__2 = k2 + 1;
/* Computing MIN */
i__3 = k2 + 1;
suml = ddot_(&i__1, &a[k1 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l2 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k1 + min(i__2,*n) * c_dim1], ldc,
&b[l2 + min(i__3,*n) * b_dim1], ldb);
vec[2] = c__[k1 + l2 * c_dim1] - (suml + sgn * sumr);
i__1 = *m - k2;
/* Computing MIN */
i__2 = k2 + 1;
/* Computing MIN */
i__3 = k2 + 1;
suml = ddot_(&i__1, &a[k2 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l1 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k2 + min(i__2,*n) * c_dim1], ldc,
&b[l1 + min(i__3,*n) * b_dim1], ldb);
vec[1] = c__[k2 + l1 * c_dim1] - (suml + sgn * sumr);
i__1 = *m - k2;
/* Computing MIN */
i__2 = k2 + 1;
/* Computing MIN */
i__3 = k2 + 1;
suml = ddot_(&i__1, &a[k2 + min(i__2,*m) * a_dim1], lda, &
c__[min(i__3,*m) + l2 * c_dim1], &c__1);
i__1 = *n - l2;
/* Computing MIN */
i__2 = l2 + 1;
/* Computing MIN */
i__3 = l2 + 1;
sumr = ddot_(&i__1, &c__[k2 + min(i__2,*n) * c_dim1], ldc,
&b[l2 + min(i__3,*n) * b_dim1], ldb);
vec[3] = c__[k2 + l2 * c_dim1] - (suml + sgn * sumr);
dlasy2_(&c_false, &c_true, isgn, &c__2, &c__2, &a[k1 + k1
* a_dim1], lda, &b[l1 + l1 * b_dim1], ldb, vec, &
c__2, &scaloc, x, &c__2, &xnorm, &ierr);
if (ierr != 0) {
*info = 1;
}
if (scaloc != 1.) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
dscal_(m, &scaloc, &c__[j * c_dim1 + 1], &c__1);
/* L220: */
}
*scale *= scaloc;
}
c__[k1 + l1 * c_dim1] = x[0];
c__[k1 + l2 * c_dim1] = x[2];
c__[k2 + l1 * c_dim1] = x[1];
c__[k2 + l2 * c_dim1] = x[3];
}
L230:
;
}
L240:
;
}
}
return 0;
}
| HPAC/ReLAPACK | src/dtrsyl_rec2.c | C | mit | 29,476 |
---
layout: post
title: 注册海外Apple ID
category: [浅谈]
tags: [Apple, ID]
published: True
---
整体流程:
1、注册内地 ID(可在网页或者App store注册)
2、开启小飞机代理
3、登录苹果官网,并修改收货地址。在账单地址里面修改成想要的地区
4、使用目标地区的地址
- 4.1、 [美国地址生成器 http://www.haoweichi.com](http://www.haoweichi.com)
- 4.2、香港地址,直接百度搜索 “香港地图” ,在里面随便找个商城,大部分门店都带有地址和电话。
5、将生成/查找到的地址电话填到账单地址上,并保存即可
6、测试是否成功
| vingeart/vingeart.github.io | _posts/浅谈/2020-06-06-注册海外Apple ID.md | Markdown | mit | 664 |
// ------------------------------------------------------------------------
// ========================================================================
// THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR
// ========================================================================
// Template: IViewModel.tt
using System.CodeDom.Compiler;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using Entities=WPAppStudio.Entities;
using EntitiesBase=WPAppStudio.Entities.Base;
namespace WPAppStudio.ViewModel.Interfaces
{
/// <summary>
/// WhoWeAre_Detail ViewModel interface.
/// </summary>
[CompilerGenerated]
[GeneratedCode("Radarc", "4.0")]
public interface IWhoWeAre_DetailViewModel
{
/// <summary>
/// Gets/Sets the CurrentWhoWeAreSchema property.
/// </summary>
Entities.WhoWeAreSchema CurrentWhoWeAreSchema { get; set; }
/// <summary>
/// Gets the TextToSpeechWhoWeAre_DetailStaticControlCommand command.
/// </summary>
ICommand TextToSpeechWhoWeAre_DetailStaticControlCommand { get; }
/// <summary>
/// Gets the ShareWhoWeAre_DetailStaticControlCommand command.
/// </summary>
ICommand ShareWhoWeAre_DetailStaticControlCommand { get; }
/// <summary>
/// Gets the PinToStartWhoWeAre_DetailStaticControlCommand command.
/// </summary>
ICommand PinToStartWhoWeAre_DetailStaticControlCommand { get; }
}
}
| tejaswisingh/Turboc-for-windows8-WINDOWS-PHONE-APP | WP8App/ViewModel/Interfaces/IWhoWeAre_DetailViewModel.cs | C# | mit | 1,568 |
//line parse.y:8
package main
import __yyfmt__ "fmt"
//line parse.y:8
import (
"clive/dbg"
"os"
"strings"
)
var (
debugYacc bool
yprintf = dbg.FlagPrintf(os.Stderr, &debugYacc)
lvl int
)
//line parse.y:24
type yySymType struct {
yys int
sval string
nd *Nd
rdr Redirs
}
const NAME = 57346
const NL = 57347
const INBLK = 57348
const HEREBLK = 57349
const FORBLK = 57350
const PIPEBLK = 57351
const LEN = 57352
const IF = 57353
const ELSE = 57354
const ELSIF = 57355
const FOR = 57356
const APP = 57357
const WHILE = 57358
const FUNC = 57359
const INTERRUPT = 57360
const ERROR = 57361
var yyToknames = []string{
"NAME",
"NL",
"INBLK",
"HEREBLK",
"FORBLK",
"PIPEBLK",
"LEN",
"IF",
"ELSE",
"ELSIF",
"FOR",
"APP",
"WHILE",
"FUNC",
"INTERRUPT",
"ERROR",
"'^'",
}
var yyStatenames = []string{}
const yyEofCode = 1
const yyErrCode = 2
const yyMaxDepth = 200
//line parse.y:412
//line yacctab:1
var yyExca = []int{
-1, 1,
1, -1,
-2, 0,
-1, 2,
1, 1,
-2, 0,
-1, 82,
22, 12,
-2, 0,
}
const yyNprod = 69
const yyPrivate = 57344
var yyTokenNames []string
var yyStates []string
const yyLast = 206
var yyAct = []int{
24, 25, 18, 52, 13, 100, 3, 7, 2, 32,
43, 15, 34, 120, 136, 35, 51, 68, 9, 49,
50, 129, 28, 114, 54, 57, 121, 36, 40, 90,
107, 58, 39, 131, 60, 34, 16, 64, 65, 66,
72, 73, 10, 27, 14, 15, 29, 30, 20, 31,
28, 26, 67, 76, 22, 127, 23, 11, 49, 50,
88, 19, 82, 12, 85, 78, 80, 114, 51, 94,
16, 27, 48, 34, 28, 97, 51, 98, 29, 30,
46, 31, 28, 93, 47, 102, 69, 34, 106, 32,
108, 109, 92, 110, 137, 27, 34, 89, 79, 49,
50, 133, 34, 27, 51, 118, 29, 30, 87, 31,
28, 123, 117, 34, 101, 126, 125, 128, 124, 122,
115, 130, 116, 51, 83, 29, 30, 20, 31, 28,
26, 27, 81, 22, 135, 23, 49, 50, 84, 51,
19, 29, 30, 71, 31, 28, 51, 59, 29, 30,
27, 31, 28, 61, 134, 51, 132, 29, 30, 101,
31, 28, 51, 86, 29, 30, 27, 31, 28, 62,
113, 119, 74, 27, 55, 56, 111, 105, 104, 103,
96, 91, 27, 77, 75, 70, 63, 38, 37, 27,
95, 112, 53, 42, 41, 45, 44, 33, 6, 1,
99, 5, 8, 21, 17, 4,
}
var yyPact = []int{
40, -1000, 40, -1000, -1000, -1000, -1000, -14, 6, -1000,
-1000, 184, 183, -1000, 4, -1000, -1000, 57, 158, -1000,
-1000, 162, 158, 119, 127, -1000, 119, 149, 182, 119,
119, 119, -1000, 6, 62, 181, -1000, 122, -1000, 151,
180, -1000, 57, -1000, -1000, -1000, 179, 74, 62, 127,
-1000, -1000, 110, 40, 102, 117, 119, 142, 87, 64,
76, 5, 177, -1000, 70, 61, 47, -1000, -1000, 176,
-1000, -1000, 127, -1000, 135, 60, -1000, -1000, 175, 174,
173, -1000, 40, -1000, -1000, 9, -1000, -1000, -1000, -1000,
172, -1000, -1000, -1000, -1000, 165, 42, 98, 100, 90,
-1000, 167, -15, -1000, -2, -1000, 97, -1000, 96, 94,
93, 30, 119, -1000, -1000, -1000, -1000, -1000, -1000, -4,
12, 152, -1000, 79, -1000, -1000, -1000, -1000, -1000, 150,
127, 158, -11, -1000, -1000, 72, -1000, -1000,
}
var yyPgo = []int{
0, 8, 205, 7, 204, 203, 202, 3, 201, 200,
5, 2, 0, 1, 4, 199, 6, 198, 197, 17,
10, 196, 195, 194, 193, 18, 192, 191, 190,
}
var yyR1 = []int{
0, 15, 1, 1, 16, 16, 16, 2, 2, 2,
2, 26, 7, 8, 17, 27, 27, 19, 19, 28,
3, 3, 14, 4, 4, 4, 4, 4, 4, 4,
5, 5, 23, 23, 24, 24, 20, 20, 21, 22,
22, 22, 18, 18, 18, 6, 6, 6, 6, 6,
6, 13, 13, 13, 9, 9, 10, 25, 25, 11,
11, 11, 11, 12, 12, 12, 12, 12, 12,
}
var yyR2 = []int{
0, 1, 2, 1, 1, 1, 1, 3, 2, 1,
1, 0, 2, 5, 2, 1, 0, 3, 0, 0,
6, 1, 2, 1, 3, 3, 1, 5, 5, 5,
5, 6, 1, 0, 2, 1, 1, 1, 2, 3,
3, 6, 1, 2, 0, 3, 3, 5, 6, 8,
5, 3, 3, 3, 2, 1, 4, 1, 1, 2,
2, 1, 1, 1, 2, 3, 5, 2, 3,
}
var yyChk = []int{
-1000, -15, -1, -16, -2, -8, -17, -3, -6, -25,
2, 17, 23, -14, 4, 5, 30, -4, -11, 21,
8, -5, 14, 16, -12, -13, 11, 31, 10, 6,
7, 9, -16, -18, 26, 29, -25, 4, 4, 28,
24, -23, -24, -20, -21, -22, 23, 27, 15, -12,
-13, 4, -7, -26, -7, 12, 13, -11, -3, 20,
-3, 4, 20, 4, -3, -3, -3, -25, -19, 24,
4, 21, -12, -13, 21, 4, -20, 4, -19, 24,
-19, 22, -1, 22, 21, -3, 21, 21, -12, 21,
24, 4, 22, 22, 22, -28, 4, -7, -11, -9,
-10, 24, 25, 4, 4, 4, -7, 21, -7, -7,
-7, 4, -27, 5, 25, 22, 22, 22, -10, 4,
28, 28, 22, -7, 22, 22, 22, 25, -14, 25,
-12, 21, 4, 22, 4, -11, 25, 22,
}
var yyDef = []int{
0, -2, -2, 3, 4, 5, 6, 44, 0, 9,
10, 0, 0, 21, 63, 57, 58, 33, 23, 11,
11, 26, 0, 0, 61, 62, 0, 0, 0, 0,
0, 0, 2, 0, 18, 42, 8, 0, 14, 0,
0, 22, 32, 35, 36, 37, 0, 18, 18, 59,
60, 63, 0, 0, 0, 0, 0, 0, 0, 0,
0, 64, 0, 67, 0, 0, 0, 7, 19, 0,
43, 11, 45, 46, 0, 0, 34, 38, 0, 0,
0, 24, -2, 25, 11, 0, 11, 11, 68, 11,
0, 65, 51, 52, 53, 16, 0, 0, 0, 0,
55, 0, 0, 39, 0, 40, 0, 11, 0, 0,
0, 0, 0, 15, 17, 13, 47, 50, 54, 0,
0, 0, 27, 0, 28, 29, 30, 66, 20, 0,
48, 0, 0, 31, 56, 0, 41, 49,
}
var yyTok1 = []int{
1, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 31, 3, 29, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 30,
23, 28, 27, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 24, 3, 25, 20, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 21, 26, 22,
}
var yyTok2 = []int{
2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19,
}
var yyTok3 = []int{
0,
}
//line yaccpar:1
/* parser for yacc output */
var yyDebug = 0
type yyLexer interface {
Lex(lval *yySymType) int
Error(s string)
}
const yyFlag = -1000
func yyTokname(c int) string {
// 4 is TOKSTART above
if c>=4 && c-4<len(yyToknames) {
if yyToknames[c-4] != "" {
return yyToknames[c-4]
}
}
return __yyfmt__.Sprintf("tok-%v", c)
}
func yyStatname(s int) string {
if s>=0 && s<len(yyStatenames) {
if yyStatenames[s] != "" {
return yyStatenames[s]
}
}
return __yyfmt__.Sprintf("state-%v", s)
}
func yylex1(lex yyLexer, lval *yySymType) int {
c := 0
char := lex.Lex(lval)
if char <= 0 {
c = yyTok1[0]
goto out
}
if char < len(yyTok1) {
c = yyTok1[char]
goto out
}
if char >= yyPrivate {
if char < yyPrivate+len(yyTok2) {
c = yyTok2[char-yyPrivate]
goto out
}
}
for i := 0; i < len(yyTok3); i += 2 {
c = yyTok3[i+0]
if c == char {
c = yyTok3[i+1]
goto out
}
}
out:
if c == 0 {
c = yyTok2[1] /* unknown char */
}
if yyDebug >= 3 {
__yyfmt__.Printf("lex %s(%d)\n", yyTokname(c), uint(char))
}
return c
}
func yyParse(yylex yyLexer) int {
var yyn int
var yylval yySymType
var yyVAL yySymType
yyS := make([]yySymType, yyMaxDepth)
Nerrs := 0 /* number of errors */
Errflag := 0 /* error recovery flag */
yystate := 0
yychar := -1
yyp := -1
goto yystack
ret0:
return 0
ret1:
return 1
yystack:
/* put a state and value onto the stack */
if yyDebug >= 4 {
__yyfmt__.Printf("char %v in %v\n", yyTokname(yychar), yyStatname(yystate))
}
yyp++
if yyp >= len(yyS) {
nyys := make([]yySymType, len(yyS)*2)
copy(nyys, yyS)
yyS = nyys
}
yyS[yyp] = yyVAL
yyS[yyp].yys = yystate
yynewstate:
yyn = yyPact[yystate]
if yyn <= yyFlag {
goto yydefault /* simple state */
}
if yychar < 0 {
yychar = yylex1(yylex, &yylval)
}
yyn += yychar
if yyn<0 || yyn>=yyLast {
goto yydefault
}
yyn = yyAct[yyn]
if yyChk[yyn] == yychar { /* valid shift */
yychar = -1
yyVAL = yylval
yystate = yyn
if Errflag > 0 {
Errflag--
}
goto yystack
}
yydefault:
/* default state action */
yyn = yyDef[yystate]
if yyn == -2 {
if yychar < 0 {
yychar = yylex1(yylex, &yylval)
}
/* look through exception table */
xi := 0
for {
if yyExca[xi+0]==-1 && yyExca[xi+1]==yystate {
break
}
xi += 2
}
for xi += 2; ; xi += 2 {
yyn = yyExca[xi+0]
if yyn<0 || yyn==yychar {
break
}
}
yyn = yyExca[xi+1]
if yyn < 0 {
goto ret0
}
}
if yyn == 0 {
/* error ... attempt to resume parsing */
switch Errflag {
case 0: /* brand new error */
yylex.Error("syntax error")
Nerrs++
if yyDebug >= 1 {
__yyfmt__.Printf("%s", yyStatname(yystate))
__yyfmt__.Printf(" saw %s\n", yyTokname(yychar))
}
fallthrough
case 1, 2: /* incompletely recovered error ... try again */
Errflag = 3
/* find a state where "error" is a legal shift action */
for yyp >= 0 {
yyn = yyPact[yyS[yyp].yys] + yyErrCode
if yyn>=0 && yyn<yyLast {
yystate = yyAct[yyn] /* simulate a shift of "error" */
if yyChk[yystate] == yyErrCode {
goto yystack
}
}
/* the current p has no shift on "error", pop stack */
if yyDebug >= 2 {
__yyfmt__.Printf("error recovery pops state %d\n", yyS[yyp].yys)
}
yyp--
}
/* there is no state on the stack with an error shift ... abort */
goto ret1
case 3: /* no shift yet; clobber input char */
if yyDebug >= 2 {
__yyfmt__.Printf("error recovery discards %s\n", yyTokname(yychar))
}
if yychar == yyEofCode {
goto ret1
}
yychar = -1
goto yynewstate /* try again in the same state */
}
}
/* reduction by production yyn */
if yyDebug >= 2 {
__yyfmt__.Printf("reduce %v in:\n\t%v\n", yyn, yyStatname(yystate))
}
yynt := yyn
yypt := yyp
_ = yypt // guard against "declared and not used"
yyp -= yyR2[yyn]
yyVAL = yyS[yyp+1]
/* consult goto table to find next state */
yyn = yyR1[yyn]
yyg := yyPgo[yyn]
yyj := yyg + yyS[yyp].yys + 1
if yyj >= yyLast {
yystate = yyAct[yyg]
} else {
yystate = yyAct[yyj]
if yyChk[yystate] != -yyn {
yystate = yyAct[yyg]
}
}
// dummy call; replaced with literal code
switch yynt {
case 1:
yyVAL.nd = yyS[yypt-0].nd
case 2:
//line parse.y:43
{
if lvl == 0 {
yyVAL.nd = nil
} else {
yyVAL.nd = yyS[yypt-1].nd.Add(yyS[yypt-0].nd)
}
}
case 3:
//line parse.y:51
{
if lvl == 0 {
yyVAL.nd = nil
} else {
yyVAL.nd = NewList(Ncmds, yyS[yypt-0].nd)
}
}
case 4:
//line parse.y:62
{
if lvl==0 && yyS[yypt-0].nd!=nil && !Interrupted {
if nerrors > 0 {
yprintf("ERR %s\n", yyS[yypt-0].nd.sprint())
} else {
yprintf("%s\n", yyS[yypt-0].nd.sprint())
yyS[yypt-0].nd.Exec()
}
nerrors = 0
}
yyVAL.nd = yyS[yypt-0].nd
}
case 5:
//line parse.y:75
{
yyVAL.nd = yyS[yypt-0].nd
}
case 6:
//line parse.y:79
{
yyVAL.nd = yyS[yypt-0].nd
}
case 7:
//line parse.y:86
{
yyVAL.nd = yyS[yypt-2].nd
if yyS[yypt-1].sval != "" {
yyVAL.nd.Args = append(yyVAL.nd.Args, yyS[yypt-1].sval)
}
}
case 8:
//line parse.y:93
{
yyVAL.nd = yyS[yypt-1].nd
}
case 9:
//line parse.y:97
{
yyVAL.nd = NewNd(Nnop)
}
case 10:
//line parse.y:101
{
yyVAL.nd = nil
}
case 11:
//line parse.y:108
{
lvl++
Prompter.SetPrompt(prompt2)
}
case 12:
//line parse.y:113
{
lvl--
if lvl == 0 {
Prompter.SetPrompt(prompt)
}
yyVAL.nd = yyS[yypt-0].nd
}
case 13:
//line parse.y:124
{
f := NewNd(Nfunc, yyS[yypt-3].sval).Add(yyS[yypt-1].nd)
yprintf("%s\n", f.sprint())
funcs[yyS[yypt-3].sval] = f
yyVAL.nd = nil
}
case 14:
//line parse.y:134
{
yprintf("< %s\n", yyS[yypt-0].sval)
lexer.source(yyS[yypt-0].sval)
yyVAL.nd = nil
}
case 17:
//line parse.y:148
{
yyVAL.sval = yyS[yypt-1].sval
}
case 18:
//line parse.y:152
{
yyVAL.sval = "1"
}
case 19:
//line parse.y:159
{
Prompter.SetPrompt(prompt2)
}
case 20:
//line parse.y:163
{
Prompter.SetPrompt(prompt)
last := yyS[yypt-5].nd.Last()
if strings.Contains(yyS[yypt-3].sval, "0") {
dbg.Warn("bad redirect for pipe")
nerrors++
}
last.Redirs = append(last.Redirs, NewRedir(yyS[yypt-3].sval, "|", false)...)
last.Redirs.NoDups()
yyS[yypt-0].nd.Redirs = append(yyS[yypt-0].nd.Redirs, NewRedir("0", "|", false)...)
yyS[yypt-0].nd.Redirs.NoDups()
yyVAL.nd = yyS[yypt-5].nd.Add(yyS[yypt-0].nd)
}
case 21:
//line parse.y:177
{
yyVAL.nd = NewList(Npipe, yyS[yypt-0].nd)
}
case 22:
//line parse.y:184
{
yyVAL.nd = yyS[yypt-1].nd
yyS[yypt-0].rdr.NoDups()
yyVAL.nd.Redirs = yyS[yypt-0].rdr
}
case 23:
//line parse.y:193
{
yyS[yypt-0].nd.Kind = Nexec
yyVAL.nd = yyS[yypt-0].nd
}
case 24:
//line parse.y:198
{
yyVAL.nd = yyS[yypt-1].nd
}
case 25:
//line parse.y:202
{
yyS[yypt-1].nd.Kind = Nforblk
yyVAL.nd = yyS[yypt-1].nd
}
case 26:
yyVAL.nd = yyS[yypt-0].nd
case 27:
//line parse.y:208
{
yyVAL.nd = yyS[yypt-4].nd.Add(nil, yyS[yypt-1].nd)
}
case 28:
//line parse.y:212
{
yyVAL.nd = NewList(Nfor, yyS[yypt-3].nd, yyS[yypt-1].nd)
}
case 29:
//line parse.y:216
{
yyVAL.nd = NewList(Nwhile, yyS[yypt-3].nd, yyS[yypt-1].nd)
}
case 30:
//line parse.y:223
{
yyVAL.nd = NewList(Nif, yyS[yypt-3].nd, yyS[yypt-1].nd)
}
case 31:
//line parse.y:227
{
yyVAL.nd = yyS[yypt-5].nd.Add(yyS[yypt-3].nd, yyS[yypt-1].nd)
}
case 32:
//line parse.y:234
{
yyVAL.rdr = yyS[yypt-0].rdr
}
case 33:
//line parse.y:238
{
yyVAL.rdr = nil
}
case 34:
//line parse.y:245
{
yyVAL.rdr = append(yyS[yypt-1].rdr, yyS[yypt-0].rdr...)
}
case 35:
yyVAL.rdr = yyS[yypt-0].rdr
case 36:
yyVAL.rdr = yyS[yypt-0].rdr
case 37:
yyVAL.rdr = yyS[yypt-0].rdr
case 38:
//line parse.y:259
{
yyVAL.rdr = NewRedir("0", yyS[yypt-0].sval, false)
}
case 39:
//line parse.y:266
{
if strings.Contains(yyS[yypt-1].sval, "0") {
dbg.Warn("bad redirect for '>'")
nerrors++
}
yyVAL.rdr = NewRedir(yyS[yypt-1].sval, yyS[yypt-0].sval, false)
}
case 40:
//line parse.y:274
{
if strings.Contains(yyS[yypt-1].sval, "0") {
dbg.Warn("bad redirect for '>'")
nerrors++
}
yyVAL.rdr = NewRedir(yyS[yypt-1].sval, yyS[yypt-0].sval, true)
}
case 41:
//line parse.y:282
{
yyVAL.rdr = NewDup(yyS[yypt-3].sval, yyS[yypt-1].sval)
}
case 42:
//line parse.y:289
{
yyVAL.sval = "&"
}
case 43:
//line parse.y:293
{
yyVAL.sval = yyS[yypt-0].sval
}
case 44:
//line parse.y:297
{
yyVAL.sval = ""
}
case 45:
//line parse.y:304
{
yyVAL.nd = NewNd(Nset, yyS[yypt-2].sval).Add(yyS[yypt-0].nd)
}
case 46:
//line parse.y:308
{
yyVAL.nd = NewNd(Nset, yyS[yypt-2].sval).Add(yyS[yypt-0].nd)
}
case 47:
//line parse.y:312
{
yyVAL.nd = NewNd(Nset, yyS[yypt-4].sval).Add(yyS[yypt-1].nd.Child...)
}
case 48:
//line parse.y:316
{
yyVAL.nd = NewNd(Nset, yyS[yypt-5].sval, yyS[yypt-3].sval).Add(yyS[yypt-0].nd)
}
case 49:
//line parse.y:320
{
yyVAL.nd = NewNd(Nset, yyS[yypt-7].sval, yyS[yypt-5].sval).Add(yyS[yypt-1].nd.Child...)
}
case 50:
//line parse.y:324
{
yyS[yypt-1].nd.Args = append(yyS[yypt-1].nd.Args, yyS[yypt-4].sval)
yyVAL.nd = yyS[yypt-1].nd
}
case 51:
//line parse.y:332
{
yyVAL.nd = NewList(Ninblk, yyS[yypt-1].nd)
}
case 52:
//line parse.y:336
{
yyVAL.nd = NewList(Nhereblk, yyS[yypt-1].nd)
}
case 53:
//line parse.y:340
{
yyVAL.nd = NewList(Npipeblk, yyS[yypt-1].nd)
}
case 54:
//line parse.y:347
{
yyVAL.nd = yyS[yypt-1].nd.Add(yyS[yypt-0].nd)
}
case 55:
//line parse.y:351
{
yyVAL.nd = NewList(Nset, yyS[yypt-0].nd)
}
case 56:
//line parse.y:357
{
yyVAL.nd = NewNd(Nset, yyS[yypt-2].sval, yyS[yypt-0].sval)
}
case 59:
//line parse.y:369
{
yyVAL.nd = yyS[yypt-1].nd.Add(yyS[yypt-0].nd)
}
case 60:
//line parse.y:373
{
yyVAL.nd = yyS[yypt-1].nd.Add(yyS[yypt-0].nd)
}
case 61:
//line parse.y:377
{
yyVAL.nd = NewList(Nnames, yyS[yypt-0].nd)
}
case 62:
//line parse.y:381
{
yyVAL.nd = NewList(Nnames, yyS[yypt-0].nd)
}
case 63:
//line parse.y:388
{
yyVAL.nd = NewNd(Nname, yyS[yypt-0].sval)
}
case 64:
//line parse.y:392
{
yyVAL.nd = NewNd(Nval, yyS[yypt-0].sval)
}
case 65:
//line parse.y:396
{
yyVAL.nd = NewNd(Njoin, yyS[yypt-0].sval)
}
case 66:
//line parse.y:400
{
yyVAL.nd = NewNd(Nval, yyS[yypt-3].sval, yyS[yypt-1].sval)
}
case 67:
//line parse.y:404
{
yyVAL.nd = NewNd(Nlen, yyS[yypt-0].sval)
}
case 68:
//line parse.y:408
{
yyVAL.nd = NewList(Napp, yyS[yypt-2].nd, yyS[yypt-0].nd)
}
}
goto yystack /* stack new state and value */
}
| sbinet-staging/clive | cmd/oldql/y.go | GO | mit | 16,009 |
package io.github.sunxu3074.shoppoingdemo.activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import io.github.sunxu3074.shoppoingdemo.R;
public class BaseActivity extends ActionBarActivity {
private static final int ACTIONBAR_BACKGROUND = R.color.actionbar_background;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
initActionBar();
}
private void initActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(ACTIONBAR_BACKGROUND));
//google的actionbar是分为上下两栏显示的,上面的代码只能设置顶部actionbar的背景色,
//为了让下面的背景色一致,还需要添加一行代码:
actionBar.setSplitBackgroundDrawable(new ColorDrawable(ACTIONBAR_BACKGROUND));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_base, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| sunxu3074/ShoppingCartDemo | app/src/main/java/io/github/sunxu3074/shoppoingdemo/activity/BaseActivity.java | Java | mit | 1,845 |
import React from 'react';
// eslint-disable-next-line
import TextInput from 'ringcentral-widgets/components/TextInput';
const props = {};
/**
* A example of `TextInput`
*/
const TextInputDemo = () => (
<TextInput
{...props}
/>
);
export default TextInputDemo;
| u9520107/ringcentral-js-widget | packages/ringcentral-widgets-docs/src/app/pages/Components/TextInput/Demo.js | JavaScript | mit | 273 |
using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using GPSoft.Games.GPMagic.GPMagicBase.Model;
using GPSoft.Games.GPMagic.GPMagicBase.Model.Database;
using GPSoft.Helper.Files;
using GPSoft.Helper.Utility;
namespace GPSoft.Games.GPMagic.GPSearch.UI
{
public partial class FormImportCardsSetting : Form
{
private const string CBX_DISPLAY_NAME = "PropertyText";
private const string CBX_VALUE_NAME = "PropertyName";
private const string MESSAGE_MODELNAMENOTALLOWEMPTY = "模板名称不允许为空";
private const string MESSAGE_DISPLAYNAMENOTALLOWEMPTY = "标签文字不允许为空";
private ImportExportModel currentModel = new ImportExportModel();
private enum ModelEditStatus
{
Create,
Modify
}
private ModelEditStatus editStatus = ModelEditStatus.Create;
public FormImportCardsSetting()
{
InitializeComponent();
FillComboBoxCardProperties();
}
private void FillComboBoxCardProperties()
{
Type cardType = typeof(ListCardTotal);
DataTable tblCardProperties = new DataTable();
tblCardProperties.Columns.Add(CBX_DISPLAY_NAME, typeof(string));
tblCardProperties.Columns.Add(CBX_VALUE_NAME, typeof(string));
foreach (PropertyInfo property in cardType.GetProperties())
{
object[] attributes = property.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
DescriptionAttribute colAttr = (DescriptionAttribute)attributes[0];
if (colAttr != null)
{
tblCardProperties.Rows.Add(colAttr.Description, property.Name);
}
}
}
BindingComboBoxData(cbxListModeCardPropertyName, tblCardProperties, CBX_DISPLAY_NAME, CBX_VALUE_NAME);
BindingComboBoxData(cbxTableModeCardPropertyName, tblCardProperties, CBX_DISPLAY_NAME, CBX_VALUE_NAME);
}
private void BindingComboBoxData(ComboBox cbx, DataTable source, string displayName, string valueName)
{
cbx.DataSource = source;
cbx.DisplayMember = displayName;
cbx.ValueMember = valueName;
}
private void btnTableModeClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnAddListModeStructure_Click(object sender, EventArgs e)
{
SaveCurrentCardProperty();
}
private void SaveCurrentCardProperty()
{
CardProperty newCardProperty = GenerateCardProperty();
if (currentModel.CardProperties.Contains(newCardProperty))
{
int index = currentModel.CardProperties.IndexOf(newCardProperty);
currentModel.CardProperties[index] = newCardProperty;
}
else
{
lbxListModeCardProperties.Items.Add(GenerateListModeCardPropertyText(newCardProperty));
currentModel.CardProperties.Add(newCardProperty);
}
}
private string GenerateListModeCardPropertyText(CardProperty property)
{
string result = string.Empty;
DataTable tblProperty = (DataTable)cbxListModeCardPropertyName.DataSource;
foreach (DataRow aRow in tblProperty.Rows)
{
if (aRow[cbxListModeCardPropertyName.ValueMember].Equals(property.PropertyName))
{
result = string.Format("{0}({1})",
property.Name,
aRow[cbxListModeCardPropertyName.DisplayMember].ToString());
break;
}
}
return result;
}
private CardProperty GenerateCardProperty()
{
CardProperty result = new CardProperty();
result.Name = tbxPropertyDisplayText.Text;
result.PropertyName = cbxListModeCardPropertyName.SelectedValue.ToString();
return result;
}
private void btnDelListModeStructure_Click(object sender, EventArgs e)
{
lbxListModeCardProperties.Items.Remove(lbxListModeCardProperties.SelectedItem);
CardProperty existCardProperty = GenerateCardProperty();
if (currentModel.CardProperties.Contains(existCardProperty))
currentModel.CardProperties.Remove(existCardProperty);
}
private void btnListModeClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void LoadModel()
{
currentModel = ObjectXMLSerialize<ImportExportModel>.Load(currentModel, currentModel.Path);
}
private void SaveModel()
{
SaveCurrentCardProperty();
FileHelper.CreateDirectory(Path.GetDirectoryName(currentModel.Path));
ObjectXMLSerialize<ImportExportModel>.Save(currentModel, currentModel.Path);
}
private void SaveAsModel()
{
}
private void btnSave_Click(object sender, EventArgs e)
{
if(CheckCurrentModel())
SaveModel();
}
private bool CheckCurrentModel()
{
bool result = true;
currentModel.Name = tbxModelName.Text;
result = 0 != currentModel.Name.Length;
if (result)
{
if (0 == currentModel.Path.Length)
{
currentModel.Path = Path.Combine(UtilityHelper.ApplicationPath,
string.Format("{0}\\{1}.{2}",
DefaultDirectoryName.ImportExport,
currentModel.Name,
DefaultExtention.ImportExport));
}
}
else
{
MessageBox.Show(MESSAGE_MODELNAMENOTALLOWEMPTY,
DialogInformation.TitleWarning,
MessageBoxButtons.OK, MessageBoxIcon.Warning);
tbxModelName.Focus();
}
return result;
}
private void btnSaveAs_Click(object sender, EventArgs e)
{
}
private void mnuItemOpenModel_Click(object sender, EventArgs e)
{
FormImportCardsModelList frmSelectModel = new FormImportCardsModelList();
ImportExportModel model = frmSelectModel.ShowDialog();
if (null != model)
{
this.editStatus = ModelEditStatus.Modify;
FillCardPropertiesList(model);
}
}
private void FillCardPropertiesList(ImportExportModel model)
{
switch (model.Type)
{
case ImportModelType.List:
FillListModeCardProperties(model);
break;
case ImportModelType.Table:
break;
}
}
private void FillListModeCardProperties(ImportExportModel model)
{
lbxListModeCardProperties.Items.Clear();
this.currentModel.Assign(model);
tbxModelDescription.Text = currentModel.Description;
tbxModelName.Text = currentModel.Name;
foreach (CardProperty property in model.CardProperties)
{
lbxListModeCardProperties.Items.Add(GenerateListModeCardPropertyText(property));
}
if (lbxListModeCardProperties.Items.Count > 0)
{
lbxListModeCardProperties.SelectedIndex = 0;
}
}
private void lbxListModeCardProperties_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbxListModeCardProperties.SelectedIndex > -1)
{
DisplayCardPropertyInformation(this.currentModel.CardProperties[lbxListModeCardProperties.SelectedIndex]);
}
}
private void DisplayCardPropertyInformation(CardProperty property)
{
tbxPropertyDisplayText.Text = property.Name;
cbxListModeCardPropertyName.SelectedValue = property.PropertyName;
}
}
}
| MuteG/gpmagic | GPSearch/UI/FormImportCardsSetting.cs | C# | mit | 8,672 |
/**
* Update Checking Unit
*
* Makes a request to Ghost.org to request release & custom notifications.
* The service is provided in return for users opting in to anonymous usage data collection.
*
* Blog owners can opt-out of update checks by setting `privacy: { useUpdateCheck: false }` in their config file.
*/
const crypto = require('crypto');
const exec = require('child_process').exec;
const moment = require('moment');
const Promise = require('bluebird');
const _ = require('lodash');
const url = require('url');
const debug = require('ghost-ignition').debug('update-check');
const api = require('./api').v2;
const config = require('./config');
const urlUtils = require('./lib/url-utils');
const errors = require('@tryghost/errors');
const {i18n, logging} = require('./lib/common');
const request = require('./lib/request');
const ghostVersion = require('./lib/ghost-version');
const internal = {context: {internal: true}};
const allowedCheckEnvironments = ['development', 'production'];
function nextCheckTimestamp() {
const now = Math.round(new Date().getTime() / 1000);
return now + (24 * 3600);
}
/**
* @description Centralised error handler for the update check unit.
*
* CASES:
* - the update check service returns an error
* - error during collecting blog stats
*
* We still need to ensure that we set the "next_update_check" to a new value, otherwise no more
* update checks will happen.
*
* @param err
*/
function updateCheckError(err) {
api.settings.edit({
settings: [{
key: 'next_update_check',
value: nextCheckTimestamp()
}]
}, internal);
err.context = i18n.t('errors.updateCheck.checkingForUpdatesFailed.error');
err.help = i18n.t('errors.updateCheck.checkingForUpdatesFailed.help', {url: 'https://ghost.org/docs/'});
logging.error(err);
}
/**
* @description Create a Ghost notification and call the API controller.
*
* @param {Object} notification
* @return {Promise}
*/
function createCustomNotification(notification) {
if (!notification) {
return Promise.resolve();
}
return Promise.each(notification.messages, function (message) {
let toAdd = {
// @NOTE: the update check service returns "0" or "1" (https://github.com/TryGhost/UpdateCheck/issues/43)
custom: !!notification.custom,
createdAt: moment(notification.created_at).toDate(),
status: message.status || 'alert',
type: message.type || 'info',
id: message.id,
dismissible: Object.prototype.hasOwnProperty.call(message, 'dismissible') ? message.dismissible : true,
top: !!message.top,
message: message.content
};
debug('Add Custom Notification', toAdd);
return api.notifications.add({notifications: [toAdd]}, {context: {internal: true}});
});
}
/**
* @description Collect stats from your blog.
* @returns {Promise}
*/
function updateCheckData() {
let data = {};
let mailConfig = config.get('mail');
data.ghost_version = ghostVersion.original;
data.node_version = process.versions.node;
data.env = config.get('env');
data.database_type = config.get('database').client;
data.email_transport = mailConfig &&
(mailConfig.options && mailConfig.options.service ?
mailConfig.options.service :
mailConfig.transport);
return Promise.props({
hash: api.settings.read(_.extend({key: 'db_hash'}, internal)).reflect(),
theme: api.settings.read(_.extend({key: 'active_theme'}, internal)).reflect(),
posts: api.posts.browse().reflect(),
users: api.users.browse(internal).reflect(),
npm: Promise.promisify(exec)('npm -v').reflect()
}).then(function (descriptors) {
const hash = descriptors.hash.value().settings[0];
const theme = descriptors.theme.value().settings[0];
const posts = descriptors.posts.value();
const users = descriptors.users.value();
const npm = descriptors.npm.value();
const blogUrl = urlUtils.urlFor('home', true);
const parsedBlogUrl = url.parse(blogUrl);
const blogId = parsedBlogUrl.hostname + parsedBlogUrl.pathname.replace(/\//, '') + hash.value;
data.url = blogUrl;
data.blog_id = crypto.createHash('md5').update(blogId).digest('hex');
data.theme = theme ? theme.value : '';
data.post_count = posts && posts.meta && posts.meta.pagination ? posts.meta.pagination.total : 0;
data.user_count = users && users.users && users.users.length ? users.users.length : 0;
data.blog_created_at = users && users.users && users.users[0] && users.users[0].created_at ? moment(users.users[0].created_at).unix() : '';
data.npm_version = npm.trim();
return data;
}).catch(updateCheckError);
}
/**
* @description Perform request to update check service.
*
* With the privacy setting `useUpdateCheck` you can control if you want to expose data/stats from your blog to the
* service. Enabled or disabled, you will receive the latest notification available from the service.
*
* @see https://ghost.org/docs/concepts/config/#privacy
* @returns {Promise}
*/
function updateCheckRequest() {
return updateCheckData()
.then(function then(reqData) {
let reqObj = {
timeout: 1000,
headers: {}
};
let checkEndpoint = config.get('updateCheck:url');
let checkMethod = config.isPrivacyDisabled('useUpdateCheck') ? 'GET' : 'POST';
// CASE: Expose stats and do a check-in
if (checkMethod === 'POST') {
reqObj.json = true;
reqObj.body = reqData;
reqObj.headers['Content-Length'] = Buffer.byteLength(JSON.stringify(reqData));
reqObj.headers['Content-Type'] = 'application/json';
} else {
reqObj.json = true;
reqObj.query = {
ghost_version: reqData.ghost_version
};
}
debug('Request Update Check Service', checkEndpoint);
return request(checkEndpoint, reqObj)
.then(function (response) {
return response.body;
})
.catch(function (err) {
// CASE: no notifications available, ignore
if (err.statusCode === 404) {
return {
next_check: nextCheckTimestamp(),
notifications: []
};
}
// CASE: service returns JSON error, deserialize into JS error
if (err.response && err.response.body && typeof err.response.body === 'object') {
err = errors.utils.deserialize(err.response.body);
}
throw err;
});
});
}
/**
* @description This function handles the response from the update check service.
*
* The helper does three things:
*
* 1. Updates the time in the settings table to know when we can execute the next update check request.
* 2. Iterates over the received notifications and filters them out based on your notification groups.
* 3. Calls a custom helper to generate a Ghost notification for the database.
*
* The structure of the response is:
*
* {
* id: 20,
* version: 'all4',
* messages:
* [{
* id: 'f8ff6c80-aa61-11e7-a126-6119te37e2b8',
* version: '^2',
* content: 'Hallouuuu custom',
* top: true,
* dismissible: true,
* type: 'info'
* }],
* created_at: '2021-10-06T07:00:00.000Z',
* custom: 1,
* next_check: 1555608722
* }
*
*
* Example for grouped custom notifications in config:
*
* "notificationGroups": ["migration", "something"]
*
* The group 'all' is a reserved name for general custom notifications, which every self hosted blog can receive.
*
* @param {Object} response
* @return {Promise}
*/
function updateCheckResponse(response) {
let notifications = [];
let notificationGroups = (config.get('notificationGroups') || []).concat(['all']);
debug('Notification Groups', notificationGroups);
debug('Response Update Check Service', response);
return api.settings.edit({settings: [{key: 'next_update_check', value: response.next_check}]}, internal)
.then(function () {
/**
* @NOTE:
*
* When we refactored notifications in Ghost 1.20, the service did not support returning multiple messages.
* But we wanted to already add the support for future functionality.
* That's why this helper supports two ways: returning an array of messages or returning an object with
* a "notifications" key. The second one is probably the best, because we need to support "next_check"
* on the root level of the response.
*/
if (_.isArray(response)) {
notifications = response;
} else if ((Object.prototype.hasOwnProperty.call(response, 'notifications') && _.isArray(response.notifications))) {
notifications = response.notifications;
} else {
// CASE: default right now
notifications = [response];
}
// CASE: Hook into received notifications and decide whether you are allowed to receive custom group messages.
if (notificationGroups.length) {
notifications = notifications.filter(function (notification) {
// CASE: release notification, keep
if (!notification.custom) {
return true;
}
// CASE: filter out messages based on your groups
return _.includes(notificationGroups.map(function (groupIdentifier) {
if (notification.version.match(new RegExp(groupIdentifier))) {
return true;
}
return false;
}), true) === true;
});
}
return Promise.each(notifications, createCustomNotification);
});
}
/**
* @description Entry point to trigger the update check unit.
*
* Based on a settings value, we check if `next_update_check` is less than now to decide whether
* we should request the update check service (http://updates.ghost.org) or not.
*
* @returns {Promise}
*/
function updateCheck() {
// CASE: The check will not happen if your NODE_ENV is not in the allowed defined environments.
if (_.indexOf(allowedCheckEnvironments, process.env.NODE_ENV) === -1) {
return Promise.resolve();
}
return api.settings.read(_.extend({key: 'next_update_check'}, internal))
.then(function then(result) {
const nextUpdateCheck = result.settings[0];
// CASE: Next update check should happen now?
// @NOTE: You can skip this check by adding a config value. This is helpful for developing.
if (!config.get('updateCheck:forceUpdate') && nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
return Promise.resolve();
}
return updateCheckRequest()
.then(updateCheckResponse)
.catch(updateCheckError);
})
.catch(updateCheckError);
}
module.exports = updateCheck;
| dgomesbr/diegomagalhaes.com | core/server/update-check.js | JavaScript | mit | 11,668 |
package com.bitdubai.fermat_dap_api.layer.dap_transaction.asset_issuing.exceptions;
import com.bitdubai.fermat_api.layer.DAPException;
/**
* The Class <code>package com.bitdubai.fermat_dap_api.layer.transaction.asset_issuing.developer.bitdubai.version_1.exceptions.CantInitializeAssetIssuingtransactionDatabaseException</code>
* is thrown when an error occurs initializing database
* <p/>
*
* Created by Manuel Perez - ([email protected]) on 08/09/15.
*
* @version 1.0
* @since Java JDK 1.7
*/
public class CantInitializeAssetIssuingTransactionDatabaseException extends DAPException {
public static final String DEFAULT_MESSAGE = "CAN'T INITIALIZE ASSET ISSUING TRANSACTION DATABASE EXCEPTION";
public CantInitializeAssetIssuingTransactionDatabaseException(final String message, final Exception cause, final String context, final String possibleReason) {
super(message, cause, context, possibleReason);
}
public CantInitializeAssetIssuingTransactionDatabaseException(final String message, final Exception cause) {
this(message, cause, "", "");
}
public CantInitializeAssetIssuingTransactionDatabaseException(final String message) {
this(message, null);
}
public CantInitializeAssetIssuingTransactionDatabaseException() {
this(DEFAULT_MESSAGE);
}
}
| fvasquezjatar/fermat-unused | fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/dap_transaction/asset_issuing/exceptions/CantInitializeAssetIssuingTransactionDatabaseException.java | Java | mit | 1,344 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="google-signin-client_id" content="96942535609-4i8alcj5ech3p2femq53q78kfuia48rv.apps.googleusercontent.com">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<title>Logger</title>
<!-- Bootstrap core CSS -->
<link href="../bootstrap-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<!--link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"-->
<!-- Custom styles for this template -->
<link href="../css/forum.css" rel="stylesheet"-->
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!--script src="../../assets/js/ie-emulation-modes-warning.js"></script-->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<div class="navbar-wrapper">
<div class="container">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index">One Day At a Time</a>
</div>
<div id="navbar" class="navbar-collapse collapse" margin="5px">
<ul class="nav navbar-nav">
<li class="#"><a href="about">About</a></li>
<li><a href="logger">Logger</a></li>
<li><a href="resources">Resources</a></li>
<li><a href="heroes">Heroes</a></li>
<li><a href="forum">Forum</a></li>
</ul>
<div align="right" align-vertical="middle" class="g-signin2" data-onsuccess="onSignIn"></div>
</div>
</div>
</nav>
</div>
</div>
<section class="container">
<section class="row clearfix">
<section class="col-md-12 column">
<ol class="breadcrumb">
<li><a href="#">Forum</a></li>
<li><a href="#">Management</a></li>
<li class="active">Logging and Journal Keeping</li>
</ol>
</section>
</section>
<section class="row clearfix">
<section class="col-md-12 column">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="panel panel-default">
<div class="panel-heading">
<section class="panel-title">
<time class="pull-right">
<i class="fa fa-calendar"></i> 2017-02-10 , <i class="fa fa-clock-o"></i> 10:38 PM
</time>
<section class="pull-left" id="id">
<abbr title="count of posts in this topic"></abbr>
</section>
</section>
</div>
<section class="row panel-body">
<section class="col-md-9">
<h2> <i class="fa fa-smile-o"></i> How often do you guys enter data?</h2>
<hr>
Hey, I was wondering how foten you guys entered in your data on ODAT or wrote it wdown if you prefer that. I started off doing it every day, but now I've taken to just doing it every week, since it's hard to find the time to sit down even for a little with all the homework and projects I've got going on. Just kind of curious to see how you guys use the site. Oh, and don't forget to tell me how it works out for you! Waiting a week makes me sometimes forget stuff from the early days, but it's so much nicer to enter it all in when I'm relaxing for once. :) Thanks!
</section>
<section id="user-description" class="col-md-3 ">
<section class="well">
<div class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-cricle"></i>Mr. Person Guy<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#"><i class="fa fa-user"></i> See profile</a></li>
<li><a href="#"><i class="fa fa-envelope"></i> Send PM</a></li>
<li><a href="#"><i class="fa fa-code"></i>View all Articles</a></li>
<li><a href="#"><i class="fa fa-th-list"></i>View all Posts</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-plus"></i>Add to contact List</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-cogs"></i> Manage User (for adminstrator)</a></li>
</ul>
</div>
<figure>
<img class="img-rounded img-responsive" src="../../images/profile.png" alt="Avatar">
<br><br><br>
<figcaption class="text-center">Average Joe, Yo<br><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half"></i> </figcaption>
</figure>
<dl class="dl-horizontal">
<dt>Joined: </dt>
<dd>10 February 2017</dd>
<dt>Posts:</dt>
<dd>1</dd>
</dl>
</section>
</section>
</section>
<div class="panel-footer">
<div class="row">
<section class="col-md-2 ">
<i class="fa fa-thumbs-up "></i><a href="#"> Thanks </a>| <i class="fa fa-warning "></i><a href="#"> Report </a>
</section>
<section class="col-md-4">
<span class="fa-stack">
<i class="fa fa-quote-right fa-stack-1x"></i>
<i class="fa fa-comment-o fa-lg fa-stack-1x"></i>
</span><a href="#"> Reply With Quote </a> |
<i class="fa fa-mail-reply "></i><a href="#"> Reply </a>|
<i class="fa fa-edit "></i><a href="#"> Edit Post </a>
</section>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
</section>
</html> | blabel3/LAPWebsite | pages/forum.html | HTML | mit | 7,364 |
"""
Created on 13 Jul 2016
@author: Bruno Beloff ([email protected])
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdPSUMonitor(object):
"""unix command line handler"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog { -c | -i INTERVAL } [-x] [-o] [-v]", version="%prog 1.0")
# compulsory...
self.__parser.add_option("--config-interval", "-c", action="store_true", dest="config_interval", default=False,
help="use PSU configuration interval specification")
self.__parser.add_option("--interval", "-i", type="float", nargs=1, action="store", dest="interval",
default=None, help="sampling interval in seconds")
# optional...
self.__parser.add_option("--ignore-standby", "-x", action="store_true", dest="ignore_standby", default=False,
help="ignore PSU standby status")
self.__parser.add_option("--no-output", "-o", action="store_true", dest="no_output", default=False,
help="suppress reporting on stdout")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if not self.config_interval and self.interval is None:
return False
if self.config_interval and self.interval is not None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
@property
def config_interval(self):
return self.__opts.config_interval
@property
def interval(self):
return self.__opts.interval
@property
def ignore_standby(self):
return self.__opts.ignore_standby
@property
def output(self):
return not self.__opts.no_output
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdPSUMonitor:{config_interval:%s, interval:%s, ignore_standby:%s, no_output:%s, verbose:%s}" % \
(self.config_interval, self.interval, self.ignore_standby, self.__opts.no_output, self.verbose)
| south-coast-science/scs_dev | src/scs_dev/cmd/cmd_psu_monitor.py | Python | mit | 2,866 |
package cz.habarta.typescript.generator.emitter;
import cz.habarta.typescript.generator.Settings;
import cz.habarta.typescript.generator.TsParameter;
import java.util.List;
public class TsArrowFunction extends TsExpression {
private final List<TsParameter> parameters;
// ConciseBody = FunctionBody | Expression;
private final TsExpression expression;
// private final List<TsStatement> body;
public TsArrowFunction(List<TsParameter> parameters, TsExpression expression) {
this.parameters = parameters;
this.expression = expression;
}
public List<TsParameter> getParameters() {
return parameters;
}
public TsExpression getExpression() {
return expression;
}
@Override
public String format(Settings settings) {
return Emitter.formatParameterList(parameters) + " => " + expression.format(settings);
}
}
| vojtechhabarta/typescript-generator | typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsArrowFunction.java | Java | mit | 911 |
<ion-footer-bar align-title="left" class="bar-dark">
<div class="buttons" ng-click="cartService.show()">
<button class="button ion-bag button-clear button-white"> My cart</button>
</div>
<h6 class="title"></h6>
<div class="buttons" ng-click="cartService.addToCart(product, cartCalcData.itemAmount)">
<button class="button ion-ios-plus-outline button-clear"> Add to cart</button>
</div>
</ion-footer-bar> | Bajtas/SquareMoose | gui/www/templates/shop/cart/cart-bottom-bar.html | HTML | mit | 442 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Alternet Tools 1.0 Reference Package ml.alternet.misc</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="style" />
</head>
<body>
<h3>
<a href="package-summary.html" target="classFrame">ml.alternet.misc</a>
</h3>
<h3>Classes</h3>
<ul>
<li>
<a href="CharRange.html" target="classFrame">BoundRange</a>
</li>
<li>
<a href="JAXBStream.html" target="classFrame">CacheStrategy</a>
</li>
<li>
<a href="Thrower.html" target="classFrame">Callable</a>
</li>
<li>
<a href="CharRange$.html" target="classFrame">Char</a>
</li>
<li>
<a href="CharArray.html" target="classFrame">CharArray</a>
</li>
<li>
<a href="CharRange$.html" target="classFrame">CharRange</a>
</li>
<li>
<a href="CharRange$.html" target="classFrame">Chars</a>
</li>
<li>
<a href="Type.html" target="classFrame">GenericArrayType</a>
</li>
<li>
<a href="InfoClass.html" target="classFrame">InfoClass</a>
</li>
<li>
<a href="JAXBStream.html" target="classFrame">Interceptor</a>
</li>
<li>
<a href="Invoker.html" target="classFrame">Invoker</a>
</li>
<li>
<a href="JAXBStream.html" target="classFrame">JAXBStream</a>
</li>
<li>
<a href="JNDIInitialContextFactory.html" target="classFrame">JNDIInitialContextFactory</a>
</li>
<li>
<a href="Type.html" target="classFrame">Kind</a>
</li>
<li>
<a href="JAXBStream.html" target="classFrame">ListSource</a>
</li>
<li>
<a href="Type$.html" target="classFrame">Native</a>
</li>
<li>
<a href="OmgException.html" target="classFrame">OmgException</a>
</li>
<li>
<a href="Type.html" target="classFrame">ParameterizedType</a>
</li>
<li>
<a href="Type.html" target="classFrame">Parsed</a>
</li>
<li>
<a href="Position.html" target="classFrame">Position</a>
</li>
<li>
<a href="CharRange$.html" target="classFrame">Range</a>
</li>
<li>
<a href="CharRange$.html" target="classFrame">Ranges</a>
</li>
<li>
<a href="CharRange.html" target="classFrame">Reversible</a>
</li>
<li>
<a href="SoftHashMap.html" target="classFrame">SoftEntry</a>
</li>
<li>
<a href="SoftHashMap.html" target="classFrame">SoftHashMap</a>
</li>
<li>
<a href="JAXBStream.html" target="classFrame">Source</a>
</li>
<li>
<a href="JAXBStream.html" target="classFrame">StreamSource</a>
</li>
<li>
<a href="Thrower.html" target="classFrame">Thrower</a>
</li>
<li>
<a href="ToDo.html" target="classFrame">ToDo</a>
</li>
<li>
<a href="TodoException.html" target="classFrame">TodoException</a>
</li>
<li>
<a href="Type$.html" target="classFrame">Type</a>
</li>
<li>
<a href="CharRange.html" target="classFrame">UnboundRange</a>
</li>
<li>
<a href="Type.html" target="classFrame">WildcardType</a>
</li>
<li>
<a href="WtfException.html" target="classFrame">WtfException</a>
</li>
</ul>
</body>
</html> | alternet/alternet.github.io | alternet-libs/tools/xref/ml/alternet/misc/package-frame.html | HTML | mit | 4,545 |
package biz.paluch.logging.gelf.logback;
import static org.junit.Assert.assertEquals;
import biz.paluch.logging.gelf.GelfTestSender;
import biz.paluch.logging.gelf.intern.GelfMessage;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import org.junit.Before;
import org.junit.Test;
import java.net.URL;
public class GelfLogbackAppenderSystemPropertiesTest {
public static final String LOG_MESSAGE = "foo bar test log message";
public static final String PROPERTY1 = "myproperty";
public static final String PROPERTY1_VALUE = "value of myproperty";
public static final String PROPERTY2 = "otherproperty";
public static final String PROPERTY2_VALUE = "value of otherproperty";
private LoggerContext lc = null;
@Before
public void before() throws Exception {
System.clearProperty(PROPERTY1);
System.clearProperty(PROPERTY2);
setup();
}
protected void setup() throws JoranException {
lc = new LoggerContext();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
URL xmlConfigFile = getClass().getResource("/logback-gelf-with-systemproperties-fields.xml");
configurator.doConfigure(xmlConfigFile);
GelfTestSender.getMessages().clear();
}
@Test
public void testDefaults() throws Exception {
Logger logger = lc.getLogger(getClass());
logger.info(LOG_MESSAGE);
assertEquals(1, GelfTestSender.getMessages().size());
GelfMessage gelfMessage = GelfTestSender.getMessages().get(0);
assertEquals(System.getProperty("user.language"), gelfMessage.getField("propertyField1"));
assertEquals("myproperty_IS_UNDEFINED", gelfMessage.getField("propertyField2"));
assertEquals("otherproperty:fallback_IS_UNDEFINED", gelfMessage.getField("propertyField3"));
assertEquals("embeddedmyproperty_IS_UNDEFINEDproperty", gelfMessage.getField("propertyField4"));
}
@Test
public void testAfterSetProperties() throws Exception {
System.setProperty(PROPERTY1, PROPERTY1_VALUE);
System.setProperty(PROPERTY2, PROPERTY2_VALUE);
setup();
Logger logger = lc.getLogger(getClass());
logger.info(LOG_MESSAGE);
assertEquals(1, GelfTestSender.getMessages().size());
GelfMessage gelfMessage = GelfTestSender.getMessages().get(0);
assertEquals(System.getProperty("user.language"), gelfMessage.getField("propertyField1"));
assertEquals(PROPERTY1_VALUE, gelfMessage.getField("propertyField2"));
assertEquals("otherproperty:fallback_IS_UNDEFINED", gelfMessage.getField("propertyField3"));
assertEquals("embedded" + PROPERTY1_VALUE + "property", gelfMessage.getField("propertyField4"));
}
}
| wikimedia/operations-debs-logstash-gelf | src/test/java/biz/paluch/logging/gelf/logback/GelfLogbackAppenderSystemPropertiesTest.java | Java | mit | 2,936 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dr.Know | Question</title>
<link rel="stylesheet" href="stylesheets/style.css" type="text/css" media="all" />
</head>
<body>
<div class="banner">
<div class="img2"><img src="images/slogan.PNG" alt="Welcome to Dr.Know!"/></div>
<a href="login.html"><p class="login">Login / Sign Up</p></a>
</div>
<div class="main">
<div class="top">
<div class="img"><img src="images/logo.png" alt="Welcome to Dr.Know!" height="100" width="180"/></div>
<div class="menu">
<ul>
<li><a href="/following">Followings</a></li>
<li><a href="ask.html">Ask</a></li>
<li><a href="tags.html">Tags</a></li>
<li><a href="index.html">Home</a></li>
</ul>
</div>
<div class="bar">
<input name="search" type="submit" id="search" value="Search"/>
<input name="searchbox" type="text" size="30" id="searchbox" value=" Search your question..." onBlur="if(this.value=='') {this.value=' Search your question...'}" onFocus="if(this.value==' Search your question...') {this.value=''; this.style.color='#999999';}" />
</div>
</div>
<div class="content">
<br/>
<p class="explore">Question</p>
<hr/>
<p class="question">How is Java different from other languages?</p>
<p class="explore">Answers(68)</p>
<input name="ans" type="button" id="answerbutton" value="Your Answer" onClick="window.location='answer.html'"/>
<br/><br/><br/>
<p class="info">Top Rated Answer:</p>
<p class="para">Due to how long Java has been around, almost any question you can imagine has already been asked, answered, indexed, and democratically perfected through upvotes on the Internet. It is seriously hard to stump a search engine with a Java coding problem. Java has a very rich API, and an incredible supporting open source ecosystem. There are tools upon tools for just about everything you would like to do. There's also an amazing community driven process that ensures growth in the right direction. Java is an Object Oriented language. It internally embraces best practices of object oriented design and strongly suggests that you learn and follow them.
<br/><br/>It also heavily promotes correct usage and many of the documented Design Patterns use Java as the language de facto. Understanding design patterns can lead to much more maintainable code. The IDEs available for Java will blow your mind. Due to its strong typing, you'll not only be notified immediately of errors, but you'll also be given suggestions that will refactor and reformat your code with clear explanations and extreme ease. After using them, most people wonder how they ever coded before. Java is running just about everywhere you can imagine. It's usually where most large applications end up due to its scalability, stability, and maintainability. There's also currently a gigantic push in the Java community to be the leader of the IoT (Internet of Things). And it's coming. Very fast. </p>
<br/>
<hr style="border:0.5px #cccccc dashed"/>
<br/>
<p class="info">Other Answers:</p>
<p class="para">Java has been well accepted in various business & domains (banking, health care, nutrition, agriculture, education, finance, telecom, biotechnology and many more). Java has got huge and best communicty from developers, researches, trainers, domain experts. Java may be blacking some areas. Hence it is still evolving without much loosing backward compatability.</p>
<br/><br/>
<hr style="border:0.5px #cccccc dashed"/>
<br/>
<p class="para">The fact is, every language has strengths and weaknesses; yes even Java has a bunch of lacunae that get overlooked by programmers because of the truckload of benefits it brings to the table. As a programmer, it's important to compare Java with other programing languages so that you are able to choose the best language for a particular project.</p>
<br/><br/>
</div>
<div class="bottom">
<br/>
<p class="creator">Nice to meet you in this knowledgeable world! | Created by <a href="/about">Yichao Chen</a></p>
</div>
</div>
</body>
</html>
| infsci2560sp16/full-stack-web-project-YichaoChen | src/main/resources/public/question.html | HTML | mit | 4,191 |
#Python 2.7
#Generate factorizations via primes to find divisors
from itertools import chain, combinations
def powerset(s): #retrieved from itertools documentation
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def primes(limit):
numbers = [True] * limit
for i in range(2, limit):
if not numbers[i]:
continue
for t in range(2 * i, limit, i):
numbers[t] = False
for i in range(2, limit):
if numbers[i]:
yield i
def proper_divisors(n, p):
prime_divisors = [x for x in p if x < n and n % x ==0]
factorization = []
for x in prime_divisors:
factorization.append(x)
t = n / x
while (t / x) * x == t:
factorization.append(x)
t /= x
divisors = set()
combs = powerset(factorization)
for c in combs:
if len(c) == 1:
divisors.add(c[0])
elif 1 < len(c) < len(factorization):
divisors.add(reduce(lambda x, y: x * y, c))
divisors.add(1)
return divisors
def abundant_numbers(limit):
abundant = set()
p = list(primes(limit))
for i in range(1, limit):
if i < sum(proper_divisors(i, p)):
abundant.add(i)
return abundant
a = abundant_numbers(28124)
double_a = set([i + j for i in a for j in a])
s = 0
for i in range(1, 28124):
if i not in double_a:
s += i
print s
| dooleykh/ProjectEuler | 23.py | Python | mit | 1,423 |
import React from 'react';
import { connect } from 'react-redux';
import Modal from 'react-modal';
import { ShareButtons, generateShareIcon} from 'react-share';
import { Link } from 'react-router-dom';
import * as authActions from '../../actions/authAction';
import * as modalActions from '../../actions/modalAction';
import {renderField} from "../Shared/renderReduxForm";
import SignInModal from "../SignInModal";
const {
FacebookShareButton,
GooglePlusShareButton,
LinkedinShareButton,
TwitterShareButton,
PinterestShareButton,
VKShareButton
} = ShareButtons;
const FacebookIcon = generateShareIcon('facebook');
const TwitterIcon = generateShareIcon('twitter');
const GooglePlusIcon = generateShareIcon('google');
const LinkedinIcon = generateShareIcon('linkedin');
const PinterestIcon = generateShareIcon('pinterest');
let FunctionalBar = class FunctionalBar extends React.Component{
constructor(props) {
super(props);
this.logout = this.logout.bind(this);
this.signin = this.signin.bind(this);
this.goToSignUp = this.goToSignUp.bind(this);
this.getUser = this.getUser.bind(this);
this.showXsNav = this.showXsNav.bind(this);
}
goToSignUp(values) {
this.context.router.history.push('/signup');
}
componentDidMount() {
}
logout(){
this.props.dispatch(authActions.userSignOut());
}
signin(){
let {auth} = this.props;
if (auth && auth.success){
return this.context.router.history.push(`/user`);
}
this.props.dispatch(modalActions.changeModal(true));
}
getUser(){
let { auth} = this.props;
if (!auth ||! auth.success || !auth.user) return <div/>;
let User = (auth.user.email && <div className="login-user">{auth.user.email}</div>);
User = User || (auth.user.profile && auth.user.profile.username && <div className="login-user">{auth.user.profile.username}</div>);
return User;
}
showXsNav(){
this.props.SmNavCtrl(true);
}
render() {
let { auth, showSigninModal} = this.props;
let Baselink = "https://react-redux-demo-chingching.herokuapp.com";
let link = Baselink;
// this.props.location.pathname && (link = Baselink + this.props.location.pathname);
// console.log(routes);
return (
<div className="banner">
<Link to="/home"> <h1><b>Hi-Tech</b> <span > Digital CCTV</span></h1></Link>
<p>
for all your residential, commercial and industrial needs. {"\u00a0"}<i className="fa fa-phone"/> {"\u00a0"} 02 9725 7733
</p>
<div className="signin">
{this.getUser()}
<FacebookShareButton url={link} className="social-share"> <FacebookIcon size={28} round={true} /> </FacebookShareButton>
<GooglePlusShareButton url={link} className="social-share"> <GooglePlusIcon size={28} round={true} /> </GooglePlusShareButton>
<LinkedinShareButton url={link} className="social-share"> <LinkedinIcon size={28} round={true} /> </LinkedinShareButton>
<TwitterShareButton url={link} className="social-share"> <TwitterIcon size={28} round={true} /> </TwitterShareButton>
<i className="fa fa-user signin-icon" aria-hidden="true" onClick={this.signin} />
<Link to="/signup"><i className="fa fa-user-plus signin-icon" aria-hidden="true"/></Link>
<i className="fa fa-sign-out signin-icon" aria-hidden="true" onClick={this.logout}/>
</div>
<span id="BTN" className="bar" onClick={this.showXsNav}><i className="fa fa-bars"/></span>
<div id="search" className="search"/>
<Modal isOpen={showSigninModal} contentLabel="Modal" className="Modal login-modal" overlayClassName="Overlay">
<SignInModal getGoogleAuth2={this.props.getGoogleAuth2}/>
</Modal>
</div>
);
}
};
FunctionalBar.propTypes = {
showSigninModal: React.PropTypes.bool.isRequired,
dispatch: React.PropTypes.func.isRequired,
getGoogleAuth2: React.PropTypes.func.isRequired,
SmNavCtrl: React.PropTypes.func.isRequired,
auth: React.PropTypes.object.isRequired,
};
FunctionalBar.contextTypes = {
router: React.PropTypes.object
};
function mapStateToProps(state) {
return {
auth: state.auth,
showSigninModal: state.modal.showModal,
};
}
FunctionalBar = connect(mapStateToProps)(FunctionalBar);
export default FunctionalBar;
| Grace951/ReactAU | src/shared/components/header/FunctionalBar.js | JavaScript | mit | 4,166 |
@extends('layouts.default')
@section('content')
<div class="row">
<div class="col-md-6">
<h1>Reset Your Password</h1>
{{ Form::open() }}
{{ Form::hidden('token', $token) }}
<!-- Email Form Input -->
<div class="form-group">
{{Form::label('email', 'Email:')}}
{{Form::email('email', null,['class' => 'form-control', 'required'])}}
</div>
<!-- Password Form Input -->
<div class="form-group">
{{Form::label('password', 'Password:')}}
{{Form::password('password',['class' => 'form-control', 'required'])}}
</div>
<!-- Password Confirmation Form Input -->
<div class="form-group">
{{Form::label('password_confirmation', 'Password Confirmation:')}}
{{Form::password('password_confirmation',['class' => 'form-control', 'required'])}}
</div>
<!-- Submit Form Input -->
<div class="form-group">
{{Form::submit('Submit', ['class' => 'btn btn-primary form-control'])}}
</div>
{{ Form::close() }}
</div>
</div>
@stop
| bionikspoon/playing-with-laravel---larabook | app/views/password/reset.blade.php | PHP | mit | 1,241 |
var _ = require('lodash'),
pg = require('../services/db').pg,
util = require('../lib/utilities');
var Directive = module.exports = pg.model("directives", {
schema: {
changeset_id: { type: Number, allowNull: false },
action: { type: String, allowNull: false },
object: String,
object_id: String,
data: String, // Stringified JSON object for shapes, types, sources
geometry: String, // Stringified coordinate array
way_nodes: String, // if object=way: List nodeId > '345,678'
// if object=way, action=delete: List seqId > '0,1,2'
// if object=node: List sequence-wayId > '0-1234,1-2345'
shape_relations: String, // if object=shape: List sequence-Type-role-id > '3-Way-outer-1234,4-Way-inner-2345'
// if object=node,way: List sequence-shapeId > '0-1234,1-2345'
created_at: Date
},
getters: {
data: parseJSON('data', {}),
geometry: parseJSON('geometry', []),
way_nodes: function() {
if (!_.isString(this.way_nodes)) return null;
return this.way_nodes.split(',');
},
shape_relations: function() {
if (!_.isString(this.shape_relations)) return null;
return this.shape_relations.split(',');
}
},
methods: {
asString: function() {
var data = _.map(this.data, function(val, key) {
return key + ' = ' + pg.engine.escape(val);
});
return [
this.action,
this.object,
this.object_id,
data.length ? 'data('+data.join(', ')+')' : null,
this.geometry.length ? 'geometry' + JSON.stringify(this.geometry) : null,
this.way_nodes ? 'with wayNodes(' + this.way_nodes.join(', ') + ')' : null,
this.shape_relations ? 'with shapeRelations('+this.shape_relations.join(', ')+')' : null,
].join(' ').replace(/\s+/g,' ').replace(/\s+$/,'');
}
}
});
function parseJSON(col, empty) {
return function() {
if (_.isString(this[col])) {
try {
return JSON.parse(this[col].replace(/\\/g,''));
} catch(err) {
return empty;
}
}
else if (_.isObject(this[col])) return this[col];
return empty;
};
}
Directive.addQueryMethod("changeset", function(id) {
return Directive.where({ changeset_id: id });
});
Directive._parseDirectives = function(id, directives) {
var now = new Date();
if (!Array.isArray(directives)) directives = [directives];
function stringify(d, col) {
if (typeof d[col] === 'object') d[col] = JSON.stringify(d[col]);
return d[col] ? d[col] : null;
}
return directives.map(function(d) {
if (d.toJSON) d = d.toJSON();
var newD = {};
newD.action = d.action.toLowerCase();
newD.object = d.object.toLowerCase();
newD.object_id = d.object_id;
newD.changeset_id = id;
newD.created_at = now;
newD.data = stringify(d, 'data');
newD.geometry = stringify(d, 'geometry');
newD.way_nodes = stringify(d, 'way_nodes');
newD.shape_relations = stringify(d, 'shape_relations');
return newD;
});
};
Directive.addQueryMethod("create", function(id, directives) {
directives = Directive._parseDirectives(id, directives);
return Directive.insert(directives);
}, function(directive) {
return directive.id;
});
// Gets all directives for a type
// Directive.getType
// Gets all directives for a shape
// Directive.getShape
// TODO: Checks directive if it's the most recent change
Directive.addMethod('checkConflict', function(callback) {
this.inConflict = false;
callback(null, this);
});
| atlastory/api | models/Directive.js | JavaScript | mit | 3,956 |
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>NPC | Schematics 2015</title>
<link rel="shortcut icon" href="<?php echo base_url(); ?>assets/img/icon.ico">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/components.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/responsee.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/animate.css">
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/modernizr.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/responsee.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body style="background-color:#fff">
<!-- HEADER -->
<header>
<!-- TOP NAV -->
<div class="line" >
<div class="l-1 s-12 hide-s" > <a href="<?php echo base_url(); ?>home"><img src="<?php echo base_url(); ?>assets/img/logo.svg" style="height:50px; margin-top:3px" class="center"/></a> </div>
<div class="l-11 s-12" style="background:none;">
<nav class="menu" style="background:none;">
<p class="nav-text">MENU</p>
<div class="top-nav" >
<ul class="chevron" id="menu-main">
<li><a href="<?php echo base_url(); ?>home">BERANDA</a></li>
<li><a href="<?php echo base_url(); ?>blog">BLOG</a></li>
<li><a href="<?php echo base_url(); ?>nlc">NLC</a></li>
<li><a href="<?php echo base_url(); ?>npc">NPC</a></li>
<li><a href="<?php echo base_url(); ?>nst">NST</a></li>
<li><a href="<?php echo base_url(); ?>reeva">REEVA</a></li>
<li><a href="<?php echo base_url(); ?>faq">FAQ</a></li>
<li><a href="<?php echo base_url(); ?>contact">CONTACT</a></li>
<li><a href="<?php echo base_url() ?>login">LOGIN</a></li>
<li><a href="<?php echo base_url(); ?>buat_akun">DAFTAR</a></li>
</ul>
</div>
</nav>
</div>
</div>
</header>
<header>
<div class="line wow fadeIn">
<section class="wow slideInRight" data-wow-duration="3s" data-wow-delay="5s" data-wow-offset="12" data-wow-iteration="9">
</section>
<div style="background:url('<?php echo base_url(); ?>assets/img/npc.png'), #f44236;height:60vh; background-position:left; background-size:cover; background-repeat:no-repeat;" ></div>
</div>
</header>
<section>
<div class="box">
<div class="s-12 l-8 center wow fadeInRight">
<section class="wow fadeInRight" data-wow-duration="3s" data-wow-delay="5s" data-wow-offset="12" data-wow-iteration="9">
</section>
<h1 align="left" style="color:#666;">NATIONAL PROGRAMMING CONTEST</h1>
<p align="left" style="color:#666;">NPC merupakan suatu kompetisi pemrograman tingkat nasional dengan standar kompetisi tingkat Internasional. Dalam NPC (National Programming Contest), peserta akan ditantang untuk menyelesaikan suatu permasalahan dengan membuat suatu program komputer. Bahasa pemrograman yang digunakan adalah Pascal (ekstensi file *.pas) atau C (ekstensi file *.c).</p>
<br>
<div class="pemisah"></div>
<br>
<ol type="A">
<li>
<h3>Persyaratan dan Biaya Pendaftaran</h3>
<ol type="1">
<li>
<p>Syarat:</p>
</li>
<ul style="list-style-type:none">
<li style="list-style-type:square">Perorangan dan bahasa pemrograman yang digunakan adalah Pascal atau C.</li>
</ul>
<li>
<p>Biaya Pendaftaran:</p>
</li>
<ul style="list-style-type:none">
<li style="list-style-type:square">Rp. 50.000,-/tim</li>
</ul>
</ol>
<br>
<div class="pemisah"></div>
<br>
<li>
<h3>Pelaksanaan NPC</h3>
<ol type="1">
<li>
<p style="list-style-type:square">Dilaksanakan secara online</p>
</li>
<li>
<p style="list-style-type:square">Babak final dengan 20 peserta yang lolos dari babak penyisihan akan dilaksanakan di Kampus Teknik Informatika ITS.</p>
</li>
</ol>
</li>
<br>
<div class="pemisah"></div>
<br>
<li>
<h3>Hadiah</h3>
<div class="line" style="margin-top:40px" >
<div align="center" >
<div class="s-12 l-five">
<div class="box-dark wow fadeIn"> <img src="<?php echo base_url() ?>assets/images/piala/1.png" class="img-rounded" style="max-width:100px;"> <p style="margin-bottom:30px">Rp. 3 juta</p></div>
</div>
<div class="s-12 l-five">
<div class="box-dark wow fadeIn"> <img src="<?php echo base_url() ?>assets/images/piala/2.png" class="img-rounded" style="max-width:100px;"> <p style="margin-bottom:30px">Rp. 2 juta</p></div>
</div>
<div class="s-12 l-five">
<div class="box-dark wow fadeIn"> <img src="<?php echo base_url() ?>assets/images/piala/3.png" class="img-rounded" style="max-width:100px;"> <p style="margin-bottom:30px">Rp. 1 juta</p></div>
</div>
<div class="s-12 l-five">
<div class="box-dark wow fadeIn"> <img src="<?php echo base_url() ?>assets/images/piala/4.png" class="img-rounded" style="max-width:100px;"> <p style="margin-bottom:30px">Rp. 0.5 juta</p></div>
</div>
<div class="s-12 l-five">
<div class="box-dark wow fadeIn"> <img src="<?php echo base_url() ?>assets/images/piala/5.png" class="img-rounded" style="max-width:100px;"> <p style="margin-bottom:30px">Rp. 0.5 juta</p></div>
</div>
<section class="wow flipInX" data-wow-duration="3s" data-wow-delay="10s" data-wow-offset="12" data-wow-iteration="15">
</section>
</div>
</div>
<p style="list-style-type:square">Semua juara akan mendapatkan sertifikat dan plakat juara dan hadiah uang.
</li>
<p style="list-style-type:square">*Diterima di Teknik Informatika ITS reguler melalui jalur SNMPTN / double degree (Korea, Belanda, Australia) berlaku peserta yang duduk di kelas 12 saat lomba berlangsung dan lulus UNAS.</p>
</li>
<br>
<div class="pemisah"></div>
<br>
<li>
<h3>Jadwal Penting</h3>
<ol type="1">
<li>
<p> 1 Juli 2015 - 16 September 2015</p>
</li>
</ul>
<li>
<p>Tutorial online: 31 agustus - 19 september</p>
</li>
<li>
<p>Warming up online: 18 september</p>
</li>
<ul style="list-style-type:none">
<li style="list-style-type:square">80 tim terbaik dari babak penyisihan berhak mengikuti babak perempat final.</li>
<li style="list-style-type:square">Diadakan di Kampus Teknik Informatika ITS</li>
<li style="list-style-type:square">Seluruh peserta akan mendapatkan sertifikat nasional</li>
<li style="list-style-type:square">Fasilitas Perempat Final: Kaos + Makan </li>
</ul>
<li>
<p>Final onsite @ teknik informatika its 11 oktober 2015</p>
</li>
<ul style="list-style-type:none">
<li style="list-style-type:square">Semifinal: 20 tim terbaik dari babak perempat final berhak mengikuti babak semifinal.</li>
<li style="list-style-type:square">Fasilitas Semifinal dan Final: Semua biaya penginapan, konsumsi, dan transportasi selama di Surabaya akan dibiayai panitia.</li>
</ul>
</ol>
</ol>
<form class="customform" action="<?php base_url(); ?>buat_akun?">
<br><br>
<div class="s-12 l-3 center"><button type="submit" style="background-color:#06F" name="event" value="npc">Daftar NPC</button></div>
</form>
</div>
</div>
</section>
<br>
<!--di sini timeline-->
<div class="pemisah"></div>
<h1 align="center">TIMELINE NPC</h1>
<br>
<div class="s-8 l-8 center">
<div class="line">
<div class="margin" align="center">
<div class="s-12 l-five"><div class="box-dark wow bounceIn">
<img src="<?php echo base_url();?>/assets/npc_tl/npc1.png" style="display:block;max-width: 150px; height: auto">
<p style="margin-bottom:30px">Pendaftaran Online</p></div></div>
<div class="s-12 l-five"><div class="box-dark wow bounceIn">
<img src="<?php echo base_url();?>/assets/npc_tl/npc2.png" style="display:block;max-width: 150px; height: auto">
<p style="margin-bottom:30px">Tutorial Online</p> </div></div>
<div class="s-12 l-five"><div class="box-dark wow bounceIn">
<img src="<?php echo base_url();?>/assets/npc_tl/npc3.png" style="display:block;max-width: 150px; height: auto">
<p style="margin-bottom:30px">Warmning Up Online</p></div></div>
<div class="s-12 l-five"><div class="box-dark wow bounceIn">
<img src="<?php echo base_url();?>/assets/npc_tl/npc4.png" style="display:block;max-width: 150px; height: auto">
<p style="margin-bottom:30px">Penyisihan Online</p></div></div>
<div class="s-12 l-five"><div class="box-dark wow bounceIn">
<img src="<?php echo base_url();?>/assets/npc_tl/npc5.png" style="display:block;max-width: 150px; height: auto">
<p style="margin-bottom:30px">Final Onsite at Teknik Informatika ITS</p></div></div>
</div>
</div>
</div>
<br>
<!--ampe sini-->
<script src="<?php echo base_url(); ?>assets/js/wow.min.js"></script>
<script>
wow = new WOW(
{
animateClass: 'animated',
offset: 100,
callback: function(box) {
console.log("WOW: animating <" + box.tagName.toLowerCase() + ">")
}
}
);
wow.init();
</script>
| didits/schematics | application/views/event/npc.php | PHP | mit | 9,008 |
{%- assign _excerpt_truncate = include.excerpt_truncate | default: 350 -%}
{%- assign _excerpt_type = include.excerpt_type -%}
{%- include snippets/get-locale-string.html key='READMORE' -%}
{%- assign _locale_readmore = __return -%}
{%- include snippets/get-locale-string.html key='YEAR' -%}
{%- assign _locale_year = __return -%}
{%- assign _sorted_list = include.articles -%}
{%- assign _sorted_list = _sorted_list | sort: 'date' -%}
{%- if include.reverse -%}
{%- assign _sorted_list = _sorted_list | reverse -%}
{%- endif -%}
{%- if include.type == 'item' -%}
<div class="article-list items items-divided">
{%- elsif include.type == 'brief' -%}
<div class="article-list items">
{%- elsif include.type == 'grid' -%}
{%- if include.size == 'sm' -%}
<div class="article-list grid gird-sm grid-p-3">
{%- else -%}
<div class="article-list grid grid-p-3">
{%- endif -%}
{%- endif -%}
{%- assign _last_year = '' -%}
{%- for _article in _sorted_list -%}
{%- include snippets/prepend-baseurl.html path=_article.url -%}
{%- assign _article_url = __return -%}
{%- if _article.cover -%}
{%- include snippets/get-nav-url.html path=_article.cover -%}
{%- assign _article_cover = __return -%}
{%- endif -%}
{%- if include.type == 'item' -%}
{%- if include.article_type == 'BlogPosting' -%}
<article class="item" itemscope itemtype="http://schema.org/BlogPosting">
{%- else -%}
<article class="item">
{%- endif -%}
{%- if _article.cover and include.show_cover-%}
{%- include snippets/get-nav-url.html path=_article.cover -%}
{%- assign _article_cover = __return -%}
<div class="item_image">
{%- if include.cover_size == 'lg' -%}
<img class="image image-lg" src="{{ _article_cover }}" />
{%- elsif include.cover_size == 'sm' -%}
<img class="image image-sm" src="{{ _article_cover }}" />
{%- else -%}
<img class="image" src="{{ _article_cover }}" />
{%- endif -%}
</div>
{%- endif -%}
<div class="item_content">
<header><a href="{{ _article_url }}"><h2 itemprop="headline" class="item_header">{{ _article.title }}</h2></a></header>
<div class="item_description">
{%- if _article.excerpt and include.show_excerpt -%}
<div class="article_content" itemprop="description articleBody">
{%- if _excerpt_type == 'html' -%}
{{ _article.excerpt }}
{%- else -%}
{{ _article.excerpt | strip_html | strip | truncate: _excerpt_truncate }}
{%- endif -%}
</div>
{%- endif -%}
{%- if include.show_readmore -%}
<p><a href="{{ _article_url }}">{{ _locale_readmore }} »</a></p>
{%- endif -%}
</div>
{%- if include.show_info -%}
{%- include snippets/assign.html target=site.data.variables.default.page.pageview source0=_article.pageview -%}
{%- assign _show_pageview = __return -%}
{%- include article-info.html article=_article show_pageview=_show_pageview -%}
{%- endif -%}
</div>
</article>
{%- elsif include.type == 'brief' -%}
{%- assign _article_year = _article.date | date: '%Y' -%}
{%- assign _current_year = _article_year | strip | url_encode -%}
{%- if _current_year != _last_year -%}
{%- unless forloop.first -%}</ul></section>{%- endunless -%}
<section><h2 class="article-list_group-header">{{ _current_year }} {{ _locale_year }}</h2><ul class="items">
{%- assign _last_year = _current_year -%}
{%- endif -%}
{%- include snippets/get-locale-string.html key='ARTICLE_LIST_DATE_FORMAT' -%}
{%- assign _article_date_format = __return -%}
<li class="item" itemscope itemtype="http://schema.org/BlogPosting" data-archive="{{ _current_year }}">
<table class="item_content item_table_brief">
<tbody>
<tr>
{%- if include.show_info -%}
<td class="item_table_brief_td" width="88px;5.5rem;"><span class="item_meta_brief">{{ _article.date | date: _article_date_format }}</span></td>
{%- endif -%}
<td class="item_table_brief_td" witdh="auto"><a itemprop="headline" class="item_header_brief" href="{{ _article_url }}">{{ _article.title }}</a></td>
</tr>
</tbody>
</table>
</li>
{%- if forloop.last -%}</ul></section>{%- endif -%}
{%- elsif include.type == 'grid' -%}
{%- if include.size == 'sm' -%}
<div class="cell cell-12 cell-md-4 cell-lg-3">
<div class="card card-flat">
{%- if _article.cover -%}
<div class="card_image">
<img class="image" src="{{ _article_cover }}" />
<div class="overlay overlay-bottom">
<header>
<a href="{{ _article_url }}"><h2 class="card_header">{{ _article.title }}</h2></a>
</header>
</div>
</div>
{%- endif -%}
</div>
</div>
{%- else -%}
<div class="cell cell-12 cell-md-6 cell-lg-4">
<div class="card card-flat">
{%- if _article.cover -%}
<div class="card_image"><img src="{{ _article_cover }}" /></div>
{%- endif -%}
<div class="card_content">
<header>
<a href="{{ _article_url }}"><h2 class="card_header">{{ _article.title }}</h2></a>
</header>
</div>
</div>
</div>
{%- endif -%}
{%- endif -%}
{%- endfor -%}
</div>
<p> </p> | chonghua/chonghua.github.io | _includes/archives-article-list.html | HTML | mit | 5,782 |
---
title: "The Nether"
playwright: Jennifer Haley
student_written: false
season: In House
season_sort: 240
period: Spring
venue: New Theatre
date_start: 2017-03-08
date_end: 2017-03-11
trivia:
- quote: For the 'jacks' scene, we had multiple balls so that if one dropped off the raised set the other one could still be used. Didn't stop Emma and Miguel losing them though.
name: Jack Ellis
submitted: 2017-11-25
cast:
- role: Morris
name: Jess Lundholm
- role: Sims / Papa
name: Jack Ellis
- role: Doyle
name: Daniel McVey
- role: Woodnut
name: Miguel Barrulas
- role: Iris
name: Emma Pallett
crew:
- role: Director
name: Joe Strickland
- role: Producer
name: Amy Naylor
- role: Assistant Director
name: Zoe Smith
- role: Lighting Designer
name: Darcey Graham
- role: Sound Designer
name: Emily Dimino
- role: Technical Director
name: Becca Potts
- role: Set Designer
name: Joe Strickland
- role: Design Assistant
name: Nat Henderson
- role: Technical Operator
name: Emma Barber
- role: Technical Operator
name: Hannah Burne
- role: Technical Operator
name: Adam Humphries
- role: Technical Operator
name: Adam Frankland
- role: Technical Operator
name: Zoe Smith
- role: Stage Manager
name: Jess Donn
- role: Stage Manager
name: Tom Proffitt
- role: Hair and Make-Up
name: Amy Greaves
- role: Poster Designer
name: David Mason
- role: Photographer
name: Zoe Smith
prod_shots: Dj7Spj
assets:
- type: poster
image: SJ7H7mc
- type: poster
image: kbgdZLF
- type: poster
image: n8Ctxr3
- type: poster
image: Gcw5Prr
- type: poster
image: gKFCk3Z
- type: poster
image: 6BwqXVS
- type: poster
image: D8b2WL7
- type: trailer
video: FvLtwHM
title: Show Trailer
- type: backstage
video: sJNMbgG
title: Backstage At
links:
- type: Review
href: http://www.hercampus.com/school/nottingham/review-nether-nottingham-new-theatre
snapshot: 5ng8i
publisher: HerCampus
author: Emily Brady
title: "Review: The Nether at The Nottingham New Theatre"
date: 2017-03-16
rating: 4/5
quote: "The strength of this production is in the unseen, and the build-up to the inevitable. It will challenge you and disturb you – and it is all the better for it."
- type: Review
href: http://www.impactnottingham.com/2017/03/the-nether-nnt/
snapshot: jhJm2
publisher: Impact
author: Shanai Momi
title: "The Nether @ NNT"
date: 2017-03-10
rating: 9/10
quote: "[T]he actors transport us into a dystopian nightmare future in which we are constantly tainted by our natural revulsion to people who seek such horrific thrills"
---
A young detective triggers an investigation into an area of The Nether, a virtual reality internet that provides total sensory immersion where users can log in, choose an identity and indulge their every desire. The area in question, The Hideaway, is the most beautifully created part of The Nether, yet home to one of the most twisted forms of entertainment; a Victorian mansion containing a group of virtual children for people to live out their violent and sexual desires with. She questions clients, employees, and the owner of The Hideaway, uncovering and questioning their justifications for the existence of this online world but, once the interrogation is over, will any of them be able to see this virtual world, or the real world, in the same way again?
| newtheatre/history-project | _shows/16_17/the_nether.md | Markdown | mit | 3,447 |
package org.littlewings.javaee7.batch
import java.io.Serializable
import javax.batch.api.partition.PartitionAnalyzer
import javax.batch.runtime.BatchStatus
import javax.enterprise.context.Dependent
import javax.inject.Named
import org.jboss.logging.Logger
@Dependent
@Named
class MyPartitionAnalyzer extends PartitionAnalyzer {
val logger: Logger = Logger.getLogger(getClass)
override def analyzeCollectorData(data: Serializable): Unit = {
logger.infof(s"[${Thread.currentThread.getName}] received data = ${data}")
}
override def analyzeStatus(batchStatus: BatchStatus, exitStatus: String): Unit = ()
}
| kazuhira-r/javaee7-scala-examples | jbatch-partitioned/src/main/scala/org/littlewings/javaee7/batch/MyPartitionAnalyzer.scala | Scala | mit | 620 |
<?php
/*
* This class was auto-generated from the API references found at
* https://epayments-api.developer-ingenico.com/s2sapi/v1/
*/
namespace Ingenico\Connect\Sdk\Domain\Mandates;
use Ingenico\Connect\Sdk\Domain\Mandates\Definitions\CreateMandateWithReturnUrl;
use UnexpectedValueException;
/**
* @package Ingenico\Connect\Sdk\Domain\Mandates
*/
class CreateMandateRequest extends CreateMandateWithReturnUrl
{
/**
* @return object
*/
public function toObject()
{
$object = parent::toObject();
return $object;
}
/**
* @param object $object
* @return $this
* @throws UnexpectedValueException
*/
public function fromObject($object)
{
parent::fromObject($object);
return $this;
}
}
| Ingenico-ePayments/connect-sdk-php | src/Ingenico/Connect/Sdk/Domain/Mandates/CreateMandateRequest.php | PHP | mit | 783 |
<?php namespace Orchestra\OAuth\Handlers;
use Orchestra\OAuth\User;
use Illuminate\Session\Store;
use Illuminate\Contracts\Auth\Authenticatable;
class UserLoggedIn
{
/**
* The session store implementation.
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* Construct a new user logged in handler.
*
* @param \Illuminate\Session\Store $session
*/
public function __construct(Store $session)
{
$this->session = $session;
}
/**
* Handle user logged in.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
*
* @return bool|null
*/
public function handle(Authenticatable $user)
{
$social = $this->session->get('authentication.social.oauth');
if (is_null($social)) {
return ;
}
$model = User::where('provider', '=', $social['provider'])
->where('uid', '=', $social['user']->getId())
->first();
if (is_null($model)) {
return ;
}
$model->setAttribute('user_id', $user->getAuthIdentifier());
$model->save();
return true;
}
}
| vitalysemenov/oauth | src/Handlers/UserLoggedIn.php | PHP | mit | 1,203 |
// Package xsrf is a container for the gorilla csrf package
package xsrf
import (
"net/http"
"github.com/blue-jay/core/view"
"github.com/gorilla/csrf"
)
// Info holds the config.
type Info struct {
AuthKey string
Secure bool
}
// Token sets token in the template to the CSRF token.
func Token(w http.ResponseWriter, r *http.Request, v *view.Info) {
v.Vars["token"] = csrf.Token(r)
}
| blue-jay/core | xsrf/xsrf.go | GO | mit | 394 |
// ===================================================================
// Author: Matt Kruse <[email protected]>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
// HISTORY
// ------------------------------------------------------------------
// Feb 7, 2005: Fixed a CSS styles to use px unit
// March 29, 2004: Added check in select() method for the form field
// being disabled. If it is, just return and don't do anything.
// March 24, 2004: Fixed bug - when month name and abbreviations were
// changed, date format still used original values.
// January 26, 2004: Added support for drop-down month and year
// navigation (Thanks to Chris Reid for the idea)
// September 22, 2003: Fixed a minor problem in YEAR calendar with
// CSS prefix.
// August 19, 2003: Renamed the function to get styles, and made it
// work correctly without an object reference
// August 18, 2003: Changed showYearNavigation and
// showYearNavigationInput to optionally take an argument of
// true or false
// July 31, 2003: Added text input option for year navigation.
// Added a per-calendar CSS prefix option to optionally use
// different styles for different calendars.
// July 29, 2003: Fixed bug causing the Today link to be clickable
// even though today falls in a disabled date range.
// Changed formatting to use pure CSS, allowing greater control
// over look-and-feel options.
// June 11, 2003: Fixed bug causing the Today link to be unselectable
// under certain cases when some days of week are disabled
// March 14, 2003: Added ability to disable individual dates or date
// ranges, display as light gray and strike-through
// March 14, 2003: Removed dependency on graypixel.gif and instead
/// use table border coloring
// March 12, 2003: Modified showCalendar() function to allow optional
// start-date parameter
// March 11, 2003: Modified select() function to allow optional
// start-date parameter
/*
DESCRIPTION: This object implements a popup calendar to allow the user to
select a date, month, quarter, or year.
COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform.
The calendar can be modified to work for any location in the world by
changing which weekday is displayed as the first column, changing the month
names, and changing the column headers for each day.
USAGE:
// Create a new CalendarPopup object of type WINDOW
var cal = new CalendarPopup();
// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv'
var cal = new CalendarPopup('mydiv');
// Easy method to link the popup calendar with an input box.
cal.select(inputObject, anchorname, dateFormat);
// Same method, but passing a default date other than the field's current value
cal.select(inputObject, anchorname, dateFormat, '01/02/2000');
// This is an example call to the popup calendar from a link to populate an
// input box. Note that to use this, date.js must also be included!!
<A HREF="#" onClick="cal.select(document.forms[0].date,'anchorname','MM/dd/yyyy'); return false;">Select</A>
// Set the type of date select to be used. By default it is 'date'.
cal.setDisplayType(type);
// When a date, month, quarter, or year is clicked, a function is called and
// passed the details. You must write this function, and tell the calendar
// popup what the function name is.
// Function to be called for 'date' select receives y, m, d
cal.setReturnFunction(functionname);
// Function to be called for 'month' select receives y, m
cal.setReturnMonthFunction(functionname);
// Function to be called for 'quarter' select receives y, q
cal.setReturnQuarterFunction(functionname);
// Function to be called for 'year' select receives y
cal.setReturnYearFunction(functionname);
// Show the calendar relative to a given anchor
cal.showCalendar(anchorname);
// Hide the calendar. The calendar is set to autoHide automatically
cal.hideCalendar();
// Set the month names to be used. Default are English month names
cal.setMonthNames("January","February","March",...);
// Set the month abbreviations to be used. Default are English month abbreviations
cal.setMonthAbbreviations("Jan","Feb","Mar",...);
// Show navigation for changing by the year, not just one month at a time
cal.showYearNavigation();
// Show month and year dropdowns, for quicker selection of month of dates
cal.showNavigationDropdowns();
// Set the text to be used above each day column. The days start with
// sunday regardless of the value of WeekStartDay
cal.setDayHeaders("S","M","T",...);
// Set the day for the first column in the calendar grid. By default this
// is Sunday (0) but it may be changed to fit the conventions of other
// countries.
cal.setWeekStartDay(1); // week is Monday - Sunday
// Set the weekdays which should be disabled in the 'date' select popup. You can
// then allow someone to only select week end dates, or Tuedays, for example
cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week
// Selectively disable individual days or date ranges. Disabled days will not
// be clickable, and show as strike-through text on current browsers.
// Date format is any format recognized by parseDate() in date.js
// Pass a single date to disable:
cal.addDisabledDates("2003-01-01");
// Pass null as the first parameter to mean "anything up to and including" the
// passed date:
cal.addDisabledDates(null, "01/02/03");
// Pass null as the second parameter to mean "including the passed date and
// anything after it:
cal.addDisabledDates("Jan 01, 2003", null);
// Pass two dates to disable all dates inbetween and including the two
cal.addDisabledDates("January 01, 2003", "Dec 31, 2003");
// When the 'year' select is displayed, set the number of years back from the
// current year to start listing years. Default is 2.
// This is also used for year drop-down, to decide how many years +/- to display
cal.setYearSelectStartOffset(2);
// Text for the word "Today" appearing on the calendar
cal.setTodayText("Today");
// The calendar uses CSS classes for formatting. If you want your calendar to
// have unique styles, you can set the prefix that will be added to all the
// classes in the output.
// For example, normal output may have this:
// <SPAN CLASS="cpTodayTextDisabled">Today<SPAN>
// But if you set the prefix like this:
cal.setCssPrefix("Test");
// The output will then look like:
// <SPAN CLASS="TestcpTodayTextDisabled">Today<SPAN>
// And you can define that style somewhere in your page.
// When using Year navigation, you can make the year be an input box, so
// the user can manually change it and jump to any year
cal.showYearNavigationInput();
// Set the calendar offset to be different than the default. By default it
// will appear just below and to the right of the anchorname. So if you have
// a text box where the date will go and and anchor immediately after the
// text box, the calendar will display immediately under the text box.
cal.offsetX = 20;
cal.offsetY = 20;
NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a CalendarPopup object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a CalendarPopup object
or the autoHide() will not work correctly.
5) The calendar popup display uses style sheets to make it look nice.
*/
// CONSTRUCTOR for the CalendarPopup Object
function CalendarPopup() {
var c;
if (arguments.length>0) {
c = new PopupWindow(arguments[0]);
} else {
c = new PopupWindow();
c.setSize(150,175);
}
c.offsetX = -152;
c.offsetY = 25;
c.autoHide();
// Calendar-specific properties
c.monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
c.monthAbbreviations = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
c.dayHeaders = new Array("S","M","T","W","T","F","S");
c.returnFunction = "CP_tmpReturnFunction";
c.returnMonthFunction = "CP_tmpReturnMonthFunction";
c.returnQuarterFunction = "CP_tmpReturnQuarterFunction";
c.returnYearFunction = "CP_tmpReturnYearFunction";
c.weekStartDay = 0;
c.isShowYearNavigation = false;
c.displayType = "date";
c.disabledWeekDays = new Object();
c.disabledDatesExpression = "";
c.yearSelectStartOffset = 2;
c.currentDate = null;
c.todayText="Today";
c.cssPrefix="";
c.isShowNavigationDropdowns=false;
c.isShowYearNavigationInput=false;
window.CP_calendarObject = null;
window.CP_targetInput = null;
window.CP_dateFormat = "MM/dd/yyyy";
// Method mappings
c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow;
c.setReturnFunction = CP_setReturnFunction;
c.setReturnMonthFunction = CP_setReturnMonthFunction;
c.setReturnQuarterFunction = CP_setReturnQuarterFunction;
c.setReturnYearFunction = CP_setReturnYearFunction;
c.setMonthNames = CP_setMonthNames;
c.setMonthAbbreviations = CP_setMonthAbbreviations;
c.setDayHeaders = CP_setDayHeaders;
c.setWeekStartDay = CP_setWeekStartDay;
c.setDisplayType = CP_setDisplayType;
c.setDisabledWeekDays = CP_setDisabledWeekDays;
c.addDisabledDates = CP_addDisabledDates;
c.setYearSelectStartOffset = CP_setYearSelectStartOffset;
c.setTodayText = CP_setTodayText;
c.showYearNavigation = CP_showYearNavigation;
c.showCalendar = CP_showCalendar;
c.hideCalendar = CP_hideCalendar;
c.getStyles = getCalendarStyles;
c.refreshCalendar = CP_refreshCalendar;
c.getCalendar = CP_getCalendar;
c.select = CP_select;
c.setCssPrefix = CP_setCssPrefix;
c.showNavigationDropdowns = CP_showNavigationDropdowns;
c.showYearNavigationInput = CP_showYearNavigationInput;
c.copyMonthNamesToWindow();
// Return the object
return c;
}
function CP_copyMonthNamesToWindow() {
// Copy these values over to the date.js
if (typeof(window.MONTH_NAMES)!="undefined" && window.MONTH_NAMES!=null) {
window.MONTH_NAMES = new Array();
for (var i=0; i<this.monthNames.length; i++) {
window.MONTH_NAMES[window.MONTH_NAMES.length] = this.monthNames[i];
}
for (var i=0; i<this.monthAbbreviations.length; i++) {
window.MONTH_NAMES[window.MONTH_NAMES.length] = this.monthAbbreviations[i];
}
}
}
// Temporary default functions to be called when items clicked, so no error is thrown
function CP_tmpReturnFunction(y,m,d) {
if (window.CP_targetInput!=null) {
var dt = new Date(y,m-1,d,0,0,0);
if (window.CP_calendarObject!=null) { window.CP_calendarObject.copyMonthNamesToWindow(); }
window.CP_targetInput.value = formatDate(dt,window.CP_dateFormat);
} else {
alert('Use setReturnFunction() to define which function will get the clicked results!');
}
}
function CP_tmpReturnMonthFunction(y,m) {
alert('Use setReturnMonthFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , month='+m);
}
function CP_tmpReturnQuarterFunction(y,q) {
alert('Use setReturnQuarterFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , quarter='+q);
}
function CP_tmpReturnYearFunction(y) {
alert('Use setReturnYearFunction() to define which function will get the clicked results!\nYou clicked: year='+y);
}
// Set the name of the functions to call to get the clicked item
function CP_setReturnFunction(name) { this.returnFunction = name; }
function CP_setReturnMonthFunction(name) { this.returnMonthFunction = name; }
function CP_setReturnQuarterFunction(name) { this.returnQuarterFunction = name; }
function CP_setReturnYearFunction(name) { this.returnYearFunction = name; }
// Over-ride the built-in month names
function CP_setMonthNames() {
for (var i=0; i<arguments.length; i++) { this.monthNames[i] = arguments[i]; }
this.copyMonthNamesToWindow();
}
// Over-ride the built-in month abbreviations
function CP_setMonthAbbreviations() {
for (var i=0; i<arguments.length; i++) { this.monthAbbreviations[i] = arguments[i]; }
this.copyMonthNamesToWindow();
}
// Over-ride the built-in column headers for each day
function CP_setDayHeaders() {
for (var i=0; i<arguments.length; i++) { this.dayHeaders[i] = arguments[i]; }
}
// Set the day of the week (0-7) that the calendar display starts on
// This is for countries other than the US whose calendar displays start on Monday(1), for example
function CP_setWeekStartDay(day) { this.weekStartDay = day; }
// Show next/last year navigation links
function CP_showYearNavigation() { this.isShowYearNavigation = (arguments.length>0)?arguments[0]:true; }
// Which type of calendar to display
function CP_setDisplayType(type) {
if (type!="date"&&type!="week-end"&&type!="month"&&type!="quarter"&&type!="year") { alert("Invalid display type! Must be one of: date,week-end,month,quarter,year"); return false; }
this.displayType=type;
}
// How many years back to start by default for year display
function CP_setYearSelectStartOffset(num) { this.yearSelectStartOffset=num; }
// Set which weekdays should not be clickable
function CP_setDisabledWeekDays() {
this.disabledWeekDays = new Object();
for (var i=0; i<arguments.length; i++) { this.disabledWeekDays[arguments[i]] = true; }
}
// Disable individual dates or ranges
// Builds an internal logical test which is run via eval() for efficiency
function CP_addDisabledDates(start, end) {
if (arguments.length==1) { end=start; }
if (start==null && end==null) { return; }
if (this.disabledDatesExpression!="") { this.disabledDatesExpression+= "||"; }
if (start!=null) { start = parseDate(start); start=""+start.getFullYear()+LZ(start.getMonth()+1)+LZ(start.getDate());}
if (end!=null) { end=parseDate(end); end=""+end.getFullYear()+LZ(end.getMonth()+1)+LZ(end.getDate());}
if (start==null) { this.disabledDatesExpression+="(ds<="+end+")"; }
else if (end ==null) { this.disabledDatesExpression+="(ds>="+start+")"; }
else { this.disabledDatesExpression+="(ds>="+start+"&&ds<="+end+")"; }
}
// Set the text to use for the "Today" link
function CP_setTodayText(text) {
this.todayText = text;
}
// Set the prefix to be added to all CSS classes when writing output
function CP_setCssPrefix(val) {
this.cssPrefix = val;
}
// Show the navigation as an dropdowns that can be manually changed
function CP_showNavigationDropdowns() { this.isShowNavigationDropdowns = (arguments.length>0)?arguments[0]:true; }
// Show the year navigation as an input box that can be manually changed
function CP_showYearNavigationInput() { this.isShowYearNavigationInput = (arguments.length>0)?arguments[0]:true; }
// Hide a calendar object
function CP_hideCalendar() {
if (arguments.length > 0) { window.popupWindowObjects[arguments[0]].hidePopup(); }
else { this.hidePopup(); }
}
// Refresh the contents of the calendar display
function CP_refreshCalendar(index) {
var calObject = window.popupWindowObjects[index];
if (arguments.length>1) {
calObject.populate(calObject.getCalendar(arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]));
} else {
calObject.populate(calObject.getCalendar());
}
calObject.refresh();
}
// Populate the calendar and display it
function CP_showCalendar(anchorname) {
if (arguments.length>1) {
if (arguments[1]==null||arguments[1]=="") {
this.currentDate=new Date();
} else {
this.currentDate=new Date(parseDate(arguments[1]));
}
}
this.populate(this.getCalendar());
this.showPopup(anchorname);
}
// Simple method to interface popup calendar with a text-entry box
function CP_select(inputobj, linkname, format) {
var selectedDate=(arguments.length>3)?arguments[3]:null;
if (!window.getDateFromFormat) {
alert("calendar.select: To use this method you must also include 'date.js' for date formatting");
return;
}
if (this.displayType!="date"&&this.displayType!="week-end") {
alert("calendar.select: This function can only be used with displayType 'date' or 'week-end'");
return;
}
if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") {
alert("calendar.select: Input object passed is not a valid form input object");
window.CP_targetInput=null;
return;
}
if (inputobj.disabled) { return; } // Can't use calendar input on disabled form input!
window.CP_targetInput = inputobj;
window.CP_calendarObject = this;
this.currentDate=null;
var time=0;
if (selectedDate!=null) {
time = getDateFromFormat(selectedDate,format);
} else if (inputobj.value!="") {
time = getDateFromFormat(inputobj.value,format);
}
if (selectedDate!=null || inputobj.value!="") {
if (time==0) { this.currentDate=null; }
else { this.currentDate=new Date(time); }
}
window.CP_dateFormat = format;
this.showCalendar(linkname);
}
// Get style block needed to display the calendar correctly
function getCalendarStyles() {
var result = "";
var p = "";
if (this!=null && typeof(this.cssPrefix)!="undefined" && this.cssPrefix!=null && this.cssPrefix!="") { p=this.cssPrefix; }
result += "<STYLE>\n";
result += "."+p+"cpYearNavigation,."+p+"cpMonthNavigation { background-color:#C0C0C0; text-align:center; vertical-align:center; text-decoration:none; color:#000000; font-weight:bold; }\n";
result += "."+p+"cpDayColumnHeader, ."+p+"cpYearNavigation,."+p+"cpMonthNavigation,."+p+"cpCurrentMonthDate,."+p+"cpCurrentMonthDateDisabled,."+p+"cpOtherMonthDate,."+p+"cpOtherMonthDateDisabled,."+p+"cpCurrentDate,."+p+"cpCurrentDateDisabled,."+p+"cpTodayText,."+p+"cpTodayTextDisabled,."+p+"cpText { font-family:arial; font-size:8pt; }\n";
result += "TD."+p+"cpDayColumnHeader { text-align:right; border:solid thin #C0C0C0;border-width:0px 0px 1px 0px; }\n";
result += "."+p+"cpCurrentMonthDate, ."+p+"cpOtherMonthDate, ."+p+"cpCurrentDate { text-align:right; text-decoration:none; }\n";
result += "."+p+"cpCurrentMonthDateDisabled, ."+p+"cpOtherMonthDateDisabled, ."+p+"cpCurrentDateDisabled { color:#D0D0D0; text-align:right; text-decoration:line-through; }\n";
result += "."+p+"cpCurrentMonthDate, .cpCurrentDate { color:#000000; }\n";
result += "."+p+"cpOtherMonthDate { color:#808080; }\n";
result += "TD."+p+"cpCurrentDate { color:white; background-color: #C0C0C0; border-width:1px; border:solid thin #800000; }\n";
result += "TD."+p+"cpCurrentDateDisabled { border-width:1px; border:solid thin #FFAAAA; }\n";
result += "TD."+p+"cpTodayText, TD."+p+"cpTodayTextDisabled { border:solid thin #C0C0C0; border-width:1px 0px 0px 0px;}\n";
result += "A."+p+"cpTodayText, SPAN."+p+"cpTodayTextDisabled { height:20px; }\n";
result += "A."+p+"cpTodayText { color:black; }\n";
result += "."+p+"cpTodayTextDisabled { color:#D0D0D0; }\n";
result += "."+p+"cpBorder { border:solid thin #808080; }\n";
result += "</STYLE>\n";
return result;
}
// Return a string containing all the calendar code to be displayed
function CP_getCalendar() {
var now = new Date();
var windowref = "";
var month, year='';
// Reference to window
if (this.type == "WINDOW") { windowref = "window.opener."; }
var result = "";
// If POPUP, write entire HTML document
if (this.type == "WINDOW") {
result += "<HTML><HEAD><TITLE>Calendar</TITLE>"+this.getStyles()+"</HEAD><BODY MARGINWIDTH=0 MARGINHEIGHT=0 TOPMARGIN=0 RIGHTMARGIN=0 LEFTMARGIN=0>\n";
result += '<CENTER><TABLE WIDTH=100% BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>\n';
} else {
result += '<TABLE CLASS="'+this.cssPrefix+'cpBorder" WIDTH=144 BORDER=1 BORDERWIDTH=1 CELLSPACING=0 CELLPADDING=1>\n';
result += '<TR><TD ALIGN=CENTER>\n';
result += '<CENTER>\n';
}
// Code for DATE display (default)
// -------------------------------
if (this.displayType=="date" || this.displayType=="week-end") {
if (this.currentDate==null) { this.currentDate = now; }
if (arguments.length > 0) { month = arguments[0]; }
else { month = this.currentDate.getMonth()+1; }
if (arguments.length > 1 && arguments[1]>0 && arguments[1]-0==arguments[1]) { year = arguments[1]; }
else { year = this.currentDate.getFullYear(); }
var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) {
daysinmonth[2] = 29;
}
var current_month = new Date(year,month-1,1);
var display_year = year;
var display_month = month;
var display_date = 1;
var weekday= current_month.getDay();
var offset = 0;
offset = (weekday >= this.weekStartDay) ? weekday-this.weekStartDay : 7-this.weekStartDay+weekday ;
if (offset > 0) {
display_month--;
if (display_month < 1) { display_month = 12; display_year--; }
display_date = daysinmonth[display_month]-offset+1;
}
var next_month = month+1;
var next_month_year = year;
if (next_month > 12) { next_month=1; next_month_year++; }
var last_month = month-1;
var last_month_year = year;
if (last_month < 1) { last_month=12; last_month_year--; }
var date_class;
if (this.type!="WINDOW") {
result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
}
result += '<TR>\n';
var refresh = windowref+'CP_refreshCalendar';
var refreshLink = 'javascript:' + refresh;
if (this.isShowNavigationDropdowns) {
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="78" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpMonthNavigation" name="cpMonth" onChange="'+refresh+'('+this.index+',this.options[this.selectedIndex].value-0,'+(year-0)+');">';
for( var monthCounter=1; monthCounter<=12; monthCounter++ ) {
var selected = (monthCounter==month) ? 'SELECTED' : '';
result += '<option value="'+monthCounter+'" '+selected+'>'+this.monthNames[monthCounter-1]+'</option>';
}
result += '</select></TD>';
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"> </TD>';
result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="56" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpYearNavigation" name="cpYear" onChange="'+refresh+'('+this.index+','+month+',this.options[this.selectedIndex].value-0);">';
for( var yearCounter=year-this.yearSelectStartOffset; yearCounter<=year+this.yearSelectStartOffset; yearCounter++ ) {
var selected = (yearCounter==year) ? 'SELECTED' : '';
result += '<option value="'+yearCounter+'" '+selected+'>'+yearCounter+'</option>';
}
result += '</select></TD>';
} else {
if (this.isShowYearNavigation) {
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');"><</A></TD>';
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="58"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+'</SPAN></TD>';
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">></A></TD>';
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"> </TD>';
result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year-1)+');"><</A></TD>';
if (this.isShowYearNavigationInput) {
result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><INPUT NAME="cpYear" CLASS="'+this.cssPrefix+'cpYearNavigation" SIZE="4" MAXLENGTH="4" VALUE="'+year+'" onBlur="'+refresh+'('+this.index+','+month+',this.value-0);"></TD>';
} else {
result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><SPAN CLASS="'+this.cssPrefix+'cpYearNavigation">'+year+'</SPAN></TD>';
}
result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year+1)+');">></A></TD>';
} else {
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');"><<</A></TD>\n';
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="100"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+' '+year+'</SPAN></TD>\n';
result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">>></A></TD>\n';
}
}
result += '</TR></TABLE>\n';
result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=0 CELLPADDING=1 ALIGN=CENTER>\n';
result += '<TR>\n';
for (var j=0; j<7; j++) {
result += '<TD CLASS="'+this.cssPrefix+'cpDayColumnHeader" WIDTH="14%"><SPAN CLASS="'+this.cssPrefix+'cpDayColumnHeader">'+this.dayHeaders[(this.weekStartDay+j)%7]+'</TD>\n';
}
result += '</TR>\n';
for (var row=1; row<=6; row++) {
result += '<TR>\n';
for (var col=1; col<=7; col++) {
var disabled=false;
if (this.disabledDatesExpression!="") {
var ds=""+display_year+LZ(display_month)+LZ(display_date);
eval("disabled=("+this.disabledDatesExpression+")");
}
var dateClass = "";
if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) {
dateClass = "cpCurrentDate";
} else if (display_month == month) {
dateClass = "cpCurrentMonthDate";
} else {
dateClass = "cpOtherMonthDate";
}
if (disabled || this.disabledWeekDays[col-1]) {
result += ' <TD CLASS="'+this.cssPrefix+dateClass+'"><SPAN CLASS="'+this.cssPrefix+dateClass+'Disabled">'+display_date+'</SPAN></TD>\n';
} else {
var selected_date = display_date;
var selected_month = display_month;
var selected_year = display_year;
if (this.displayType=="week-end") {
var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0);
d.setDate(d.getDate() + (7-col));
selected_year = d.getYear();
if (selected_year < 1000) { selected_year += 1900; }
selected_month = d.getMonth()+1;
selected_date = d.getDate();
}
result += ' <TD CLASS="'+this.cssPrefix+dateClass+'"><A HREF="javascript:'+windowref+this.returnFunction+'('+selected_year+','+selected_month+','+selected_date+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+this.cssPrefix+dateClass+'">'+display_date+'</A></TD>\n';
}
display_date++;
if (display_date > daysinmonth[display_month]) {
display_date=1;
display_month++;
}
if (display_month > 12) {
display_month=1;
display_year++;
}
}
result += '</TR>';
}
var current_weekday = now.getDay() - this.weekStartDay;
if (current_weekday < 0) {
current_weekday += 7;
}
result += '<TR>\n';
result += ' <TD COLSPAN=7 ALIGN=CENTER CLASS="'+this.cssPrefix+'cpTodayText">\n';
if (this.disabledDatesExpression!="") {
var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate());
eval("disabled=("+this.disabledDatesExpression+")");
}
if (disabled || this.disabledWeekDays[current_weekday+1]) {
result += ' <SPAN CLASS="'+this.cssPrefix+'cpTodayTextDisabled">'+this.todayText+'</SPAN>\n';
} else {
result += ' <A CLASS="'+this.cssPrefix+'cpTodayText" HREF="javascript:'+windowref+this.returnFunction+'(\''+now.getFullYear()+'\',\''+(now.getMonth()+1)+'\',\''+now.getDate()+'\');'+windowref+'CP_hideCalendar(\''+this.index+'\');">'+this.todayText+'</A>\n';
}
result += ' <BR>\n';
result += ' </TD></TR></TABLE></CENTER></TD></TR></TABLE>\n';
}
// Code common for MONTH, QUARTER, YEAR
// ------------------------------------
if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") {
if (arguments.length > 0) { year = arguments[0]; }
else {
if (this.displayType=="year") { year = now.getFullYear()-this.yearSelectStartOffset; }
else { var year = now.getFullYear(); }
}
if (this.displayType!="year" && this.isShowYearNavigation) {
result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
result += '<TR>\n';
result += ' <TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-1)+');"><<</A></TD>\n';
result += ' <TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="100">'+year+'</TD>\n';
result += ' <TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+1)+');">>></A></TD>\n';
result += '</TR></TABLE>\n';
}
}
// Code for MONTH display
// ----------------------
if (this.displayType=="month") {
// If POPUP, write entire HTML document
result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
for (var i=0; i<4; i++) {
result += '<TR>';
for (var j=0; j<3; j++) {
var monthindex = ((i*3)+j);
result += '<TD WIDTH=33% ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnMonthFunction+'('+year+','+(monthindex+1)+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+this.monthAbbreviations[monthindex]+'</A></TD>';
}
result += '</TR>';
}
result += '</TABLE></CENTER></TD></TR></TABLE>\n';
}
// Code for QUARTER display
// ------------------------
if (this.displayType=="quarter") {
result += '<BR><TABLE WIDTH=120 BORDER=1 CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER>\n';
for (var i=0; i<2; i++) {
result += '<TR>';
for (var j=0; j<2; j++) {
var quarter = ((i*2)+j+1);
result += '<TD WIDTH=50% ALIGN=CENTER><BR><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnQuarterFunction+'('+year+','+quarter+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">Q'+quarter+'</A><BR><BR></TD>';
}
result += '</TR>';
}
result += '</TABLE></CENTER></TD></TR></TABLE>\n';
}
// Code for YEAR display
// ---------------------
if (this.displayType=="year") {
var yearColumnSize = 4;
result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
result += '<TR>\n';
result += ' <TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-(yearColumnSize*2))+');"><<</A></TD>\n';
result += ' <TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+(yearColumnSize*2))+');">>></A></TD>\n';
result += '</TR></TABLE>\n';
result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
for (var i=0; i<yearColumnSize; i++) {
for (var j=0; j<2; j++) {
var currentyear = year+(j*yearColumnSize)+i;
result += '<TD WIDTH=50% ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnYearFunction+'('+currentyear+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+currentyear+'</A></TD>';
}
result += '</TR>';
}
result += '</TABLE></CENTER></TD></TR></TABLE>\n';
}
// Common
if (this.type == "WINDOW") {
result += "</BODY></HTML>\n";
}
return result;
}
| s3db/s3db | js/CalendarPopup.js | JavaScript | mit | 33,286 |
'use strict';
var ConsoleAppender = require('../appender/ConsoleAppender.js');
var PrintPattern = require('../PrintPattern.js');
var Record = require('../Record.js');
var Level = require('../Level.js');
var FileSystem = require('fs');
var Path = require('path');
var test = require('unit.js');
var should = test.should;
var record, print_pattern = new PrintPattern('{out}');
describe('Suite de testes do ConsoleAppender.', function() {
describe('Testes construção.', function() {
describe('Dado uma instância do ConsoleAppender', function() {
var console_appender = new ConsoleAppender('SimpleConsoleAppender', print_pattern);
describe('quando criada de forma simples', function() {
it('então deve conter a interface básica exigida para ser uma Appender.', function() {
should(console_appender.name).be.equal('SimpleConsoleAppender');
should(console_appender.write).be.type('function');
should(console_appender.writeSync).be.type('function');
});
});
describe('quando escrito um record de level menor que error', function() {
it('então a mensagem deveria sair no stream de saída do sistema operacional.', function() {
var original_out = process.stdout.write;
process.stdout.write = function(chunk) {
process.stdout.write = original_out;
should(chunk).be.equal('mensagem_out\n');
}
record = new Record('test.logger', Level.trace, 'mensagem_out');
console_appender.writeSync(record);
});
});
describe('quando escrito um record de level igual a error', function() {
it('então a mensagem deveria sair no stream de erro do sistema operacional.', function() {
var original_err = process.stderr.write;
var error = new Error('mensagem_err')
process.stderr.write = function(chunk) {
process.stderr.write = original_err;
should(chunk).be.equal(error.stack + '\n');
}
record = new Record('test.logger', Level.error, error);
console_appender.writeSync(record);
});
});
});
});
});
| michelwooller/LogAPI | test/ConsoleAppenderTest.js | JavaScript | mit | 2,039 |
package com.wt.studio.plugin.modeldesigner.dialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.internal.Workbench;
import com.wt.studio.plugin.modeldesigner.editor.model.BOModelDiagram;
import com.wt.studio.plugin.modeldesigner.editor.model.HdbColumnModel;
import com.wt.studio.plugin.modeldesigner.editor.model.HdbTableModel;
import com.wt.studio.plugin.modeldesigner.io.Reader.DiagramXmlReader;
import com.wt.studio.plugin.pagedesigner.gef.editpart.MOFunctionTableModelEditPart;
import com.wt.studio.plugin.pagedesigner.gef.model.FunctionColumnModel;
import com.wt.studio.plugin.pagedesigner.gef.model.MOFunctionTableModel;
import com.wt.studio.plugin.pagedesigner.utils.ConvertUtils;
import com.wt.studio.plugin.wizard.projects.dbhelp.ColumeModel;
import com.wt.studio.plugin.wizard.projects.dbhelp.HelpDBInit;
import com.wt.studio.plugin.wizard.projects.dbhelp.TableModel;
public class TableFromDataBase extends Dialog
{
private List<TableModel> tables=new ArrayList<TableModel>();
private List<HdbTableModel> hdbTables=new ArrayList<HdbTableModel>();
private Button b;
Composite fileArea;
/**
* container
*/
private Composite container;
/**
* 表信息
*/
private Combo comDS;
private Text txtPak;
private Text search;
private String pname;
private TableEditor editor;
/**
* 列表
*/
private Table table;
private String dburl = "";
private String dbuser = "";
private String dbpass = "";
private String dbType = "";
protected List<TableModel> tableModels;
private static String[] tableHeader = {
" 表名称 ",
" Model ",
" 描述 ",
" 问题 " };
public List<HdbTableModel> getHdbTables()
{
return hdbTables;
}
public void setHdbTables(List<HdbTableModel> hdbTables)
{
this.hdbTables = hdbTables;
}
public TableFromDataBase(Shell parentShell) throws FileNotFoundException, MalformedURLException, DocumentException
{
super(parentShell);
setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX);
}
protected Point getInitialSize() {
return new Point(800,600);
}
protected void configureShell(Shell newShell)
{
super.configureShell(newShell);
newShell.setText("从数据库中导入MO模型");
}
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
b=this.getButton(OK);
b.addSelectionListener(new SelectionListener(){
@Override
public void widgetDefaultSelected(SelectionEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void widgetSelected(SelectionEvent eve)
{
hdbTables.clear();
for(TableModel model:tables)
{
List<ColumeModel>columns=getSeletedColumes(model.getTableName());
HdbTableModel hdbTable=new HdbTableModel();
hdbTable.setCode(model.getTableName());
hdbTable.setTitle(getTable2ModelName(model.getTableName()));
for (ColumeModel lc : columns) {
HdbColumnModel column=new HdbColumnModel();
column.setId(uuid());
column.setCode(lc.getColumeName());
column.setName(lc.getName());
column.setDataType(lc.getDataType());
column.setLength(20);
boolean isKey=lc.getIsKey().equals("")?false:true;
column.setPK(isKey);
hdbTable.addColumn(column);
}
hdbTables.add(hdbTable);
}
}
});
}
protected Control createDialogArea(Composite parent)
{
GridData gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = SWT.FILL;
container = new Composite(parent, SWT.NONE);
container.setBounds(new Rectangle(0, 0, 800, 500));
container.setLayout(new GridLayout(1, false));
container.setLayoutData(gd);
Group gpTable = new Group(container, SWT.NONE);
gpTable.setText("数据源信息");
GridData gd1 = new GridData();
gd1.horizontalSpan = 2;
gd1.horizontalAlignment = GridData.FILL;
gpTable.setLayoutData(gd1);
gpTable.setLayout(new GridLayout(2, false));
// new Label(gpTable, SWT.NULL).setText("包名称:");
// txtPak = new Text(gpTable, SWT.BORDER);
// txtPak.setText(COMP_PRIX + pname);
// txtPak.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(gpTable, SWT.NULL).setText("数据源:");
comDS = new Combo(gpTable, SWT.NONE | SWT.READ_ONLY);
comDS.add("--请选择数据源--");
comDS.select(0);
for (String dbname : HelpDBInit.getDBNames()) {
comDS.add(dbname);
}
comDS.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd2 = new GridData();
gd2.horizontalAlignment = SWT.FILL;
gd2.grabExcessHorizontalSpace = true;
gd2.verticalAlignment = SWT.FILL;
gd2.verticalSpan = 0;
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = SWT.FILL;
gd.heightHint = 200;
search = new Text(container, SWT.BORDER);
search.setLayoutData(gd2);
search.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
table.removeAll();
hdbTables.clear();
for (final TableModel lc : tableModels) {
if (StringUtils.contains(lc.getTableName(),
StringUtils.upperCase(search.getText()))
|| StringUtils.contains(lc.getTableName(),
StringUtils.lowerCase(search.getText()))) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { lc.getTableName(),
getTable2ModelName(lc.getTableName()), "" });
}
}
}
});
table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION
| SWT.CHECK);
table.setHeaderVisible(true); // 显示表头
table.setLinesVisible(true); // 显示表格线
table.setLayoutData(gd);
table.addListener(SWT.Selection, new Listener(){
@Override
public void handleEvent(Event eve)
{
// TODO Auto-generated method stub
TableItem item=(TableItem)eve.item;
if(item.getChecked())
{
tables.add((TableModel) item.getData());
}
else
{
if(tables.contains(item.getData()))
{
tables.remove(item.getData());
}
}
}
});
for (int i = 0; i < tableHeader.length; i++) {
TableColumn tableColumn = new TableColumn(table, SWT.FILL);
tableColumn.setWidth(300);
tableColumn.setText(tableHeader[i]);
table.setHeaderVisible(true);
}
comDS.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent arg0) {
try {
table.removeAll();
search.setText("");
if (comDS.getSelectionIndex() != 0) {
String name = comDS.getText();
dbType = HelpDBInit.getDBType(name);
dburl = HelpDBInit.getDBUrl(name);
dbuser = HelpDBInit.getDBUser(name);
dbpass = HelpDBInit.getDBPass(name);
tableModels = HelpDBInit.getTableList(name, dbType,
dburl, dbuser, dbpass);
for (final TableModel lc : tableModels) {
TableItem item = new TableItem(table, SWT.NONE);
item.setData(lc);
item.setText(new String[] { lc.getTableName(),
getTable2ModelName(lc.getTableName()), "" });
}
}
} catch (Exception e) {
MessageDialog.openWarning(getShell(), "提示", "检查数据库连接!");
}
}
});
for (int i = 0; i < tableHeader.length; i++) {
table.getColumn(i).pack();
}
return parent;
}
protected void assembleColumeModels(List<ColumeModel> columeModels2,
List<ColumeModel> oldColumeModels2) {
for(ColumeModel item: columeModels2) {
for(ColumeModel item2: oldColumeModels2) {
if(StringUtils.equals(item.getColumeName(), item2.getColumeName())) {
item.setComment(item2.getComment());
item.setIsKey(StringUtils.equals(item2.getIsKey(),"1") ? "PK" : "");
item.setIsQueryCond(item2.getIsQueryCond());
item.setIsListShow(StringUtils.equals(item2.getIsListShow(),"1")?"是":"");
item.setManageControlType(item2.getManageControlType());
item.setManageDataType(item2.getManageDataType());
item.setValideType(item2.getValideType());
item.setRequid(StringUtils.equals(item2.getRequid(),"1")?"非空":"");
}
}
}
}
/* public void CreateTableButton(Table table,final TableItem item,final int i)
{
final TableEditor editor=new TableEditor(table);
checkEditors.add(editor);
final Button button=new Button(table,SWT.NULL);
button.setText("导入");
editor.grabHorizontal=true;
editor.setEditor(button,item,i);
button.addSelectionListener(new SelectionListener(){
@Override
public void widgetDefaultSelected(SelectionEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void widgetSelected(SelectionEvent arg0)
{
ConvertUtils conv=new ConvertUtils();
// TODO Auto-generated method stub
TableModel table=(TableModel) item.getData();
function.getColumns().clear();
List<ColumnModel> dbColumns=table.getColumns();
for(ColumnModel dbColumn:dbColumns)
{
FunctionColumnModel fcolumn=new FunctionColumnModel();
fcolumn.setDbColumnName(dbColumn.getCode());
fcolumn.setTitle(conv.convertTitle(dbColumn.getCode()));
try {
fcolumn.setId(conv.convertDataType(dbColumn.getDataType(),"orcal"));
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
fcolumn.setId("String");
}
try {
fcolumn.setDataType(conv.convertDataType(dbColumn.getDataType(),"orcal"));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
fcolumn.setDataType("String");
}
fcolumn.setUuid(dbColumn.getUuid());
boolean isFK=dbColumn.isFK()?true:false;
fcolumn.setFK(isFK);
boolean isPK=dbColumn.isPK()?true:false;
fcolumn.setPK(isPK);
function.addColumn(fcolumn);
}
function.setTableName(table.getCode());
function.setTitle(conv.convertTitle(table.getCode()));
}
});
}*/
/* private void createTableData(IFile file)
{
// TODO Auto-generated method stub
BOModelDiagram diagram = null;
try {
diagram = paresDiagram(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tableData.removeAll();
List <TableModel>tables=diagram.getTableModels();
for(TableModel table:tables)
{
TableItem item=new TableItem(tableData,SWT.NONE);
item.setText(0, table.getTitle());
item.setText(1,table.getCode());
item.setText(2,table.getComment());
item.setData(table);
CreateTableButton(tableData,item,5);
}
fileArea.layout();
}
*/
public List<ColumeModel> getSeletedColumes(String table) {
try {
return HelpDBInit.getTableColumeList(dbType, dburl, dbuser, dbpass,
table);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getStreamString(InputStream tInputStream) {
if (tInputStream != null) {
try {
BufferedReader tBufferedReader = new BufferedReader(
new InputStreamReader(tInputStream));
StringBuffer tStringBuffer = new StringBuffer();
String sTempOneLine = new String("");
while ((sTempOneLine = tBufferedReader.readLine()) != null) {
tStringBuffer.append(sTempOneLine);
}
return tStringBuffer.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
public static IProject getProject(){
IProject project = null;
//1.根据当前编辑器获取工程
IEditorPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if(part != null){
Object object = part.getEditorInput().getAdapter(IFile.class);
if(object != null){
project = ((IFile)object).getProject();
}
}
if(project == null){
ISelectionService selectionService =
Workbench.getInstance().getActiveWorkbenchWindow().getSelectionService();
ISelection selection = selectionService.getSelection();
if(selection instanceof IStructuredSelection) {
Object element = ((IStructuredSelection)selection).getFirstElement();
if (element instanceof IResource) {
project= ((IResource)element).getProject();
}
}
}
return project;
}
private static String uuid()
{
return UUID.randomUUID().toString().replace("-", "");
}
public static String getTable2ModelName(String table) {
String result = "";
for (String s : StringUtils.replaceEach(table,
new String[] { "-", " " }, new String[] { "", "" }).split("_")) {
result += StringUtils.capitalize(StringUtils.lowerCase(s));
}
return result;
}
}
| winture/wt-studio | com.wt.studio.plugin.modeldesigner/src/com/wt/studio/plugin/modeldesigner/dialog/TableFromDataBase.java | Java | mit | 15,411 |
'use strict';
var assert = console.assert;
var DomProcessor = require('../dom-processor');
describe('configuration using attributes of selected elements', function() {
var configLoader = {
load: function() {
return [{
selector: 'div',
replace: function($element) {
var id = $element.attr('id');
return '<span id="' + id + '"></span>';
}
}];
}
};
var processor = new DomProcessor(configLoader);
it('should replace <div> with <span> and keep the `id`', function() {
var result = processor.process('<div id="foo"></div>');
assert(result === '<span id="foo"></span>');
});
});
| BenjaminEckardt/dom-processor | test/element-attribute.test.js | JavaScript | mit | 661 |
package util
import (
"errors"
"os"
"path"
"strings"
)
var RootFiles = []string{".colonize.yaml", ".colonize.yml"}
// search through myPath till you find the config file, and return the path to
// it.
func FindCfgPath(myPath string) (string, error) {
// cleanup and combine config file and search path
cleanedP := path.Clean(myPath)
for _, rootfile := range RootFiles {
fSearch := path.Join(cleanedP, rootfile)
// if the file exists, return the full path to the config file.
if fileExists(fSearch) {
return fSearch, nil
}
}
// split it for recurisve search.
newP, _ := path.Split(cleanedP)
// if this is the end of the line for the path, return an error
if newP == "/" || newP == "" || newP == "." || newP == ".." {
return "", errors.New(RootFiles[0] + " not found in the directory tree.")
}
// recurse
return FindCfgPath(newP)
}
// return the basename of a given path
func GetBasename(myPath string) string {
return path.Base(myPath)
}
func GetTmplRelPath(full string, rootPath string) string {
return strings.Replace(strings.Replace(full, rootPath, "", 1), "/", "", 1)
}
func GetDir(myPath string) string {
return path.Dir(myPath)
}
func GetTreePaths(myPath string) []string {
elems := strings.Split(myPath, "/")
paths := make([]string, len(elems))
for i, _ := range elems {
paths[i] = strings.Join(elems[0:i+1], "/")
}
return paths
}
func AppendPathToPaths(ps []string, pName string) []string {
res := []string{}
for _, p := range ps {
res = append(res, path.Join(p, pName))
}
return res
}
func PrependPathToPaths(ps []string, pName string) []string {
res := []string{}
for _, p := range ps {
res = append(res, path.Join(pName, p))
}
return res
}
func PathJoin(p string, p2 string) string {
return path.Join(p, p2)
}
func AddFileToWalkablePath(myPath string, fName string) []string {
return AppendPathToPaths(GetTreePaths(myPath), fName)
}
// Search for a file.
func fileExists(p string) bool {
if _, err := os.Stat(p); err == nil {
return true
}
return false
}
func Touch(p ...string) error {
fn, err := os.Create(path.Join(p...))
defer fn.Close()
return err
}
| craigmonson/colonize | util/paths.go | GO | mit | 2,147 |
<?php
namespace TCG\Voyager\Traits;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use TCG\Voyager\Facades\Voyager;
use TCG\Voyager\Models\Translation;
use TCG\Voyager\Translator;
trait Translatable
{
/**
* Check if this model can translate.
*
* @return bool
*/
public function translatable()
{
if (isset($this->translatable) && $this->translatable == false) {
return false;
}
return !empty($this->getTranslatableAttributes());
}
/**
* Load translations relation.
*
* @return mixed
*/
public function translations()
{
return $this->hasMany(Voyager::model('Translation'), 'foreign_key', $this->getKeyName())
->where('table_name', $this->getTable())
->whereIn('locale', config('voyager.multilingual.locales', []));
}
/**
* This scope eager loads the translations for the default and the fallback locale only.
* We can use this as a shortcut to improve performance in our application.
*
* @param Builder $query
* @param string|null $locale
* @param string|bool $fallback
*/
public function scopeWithTranslation(Builder $query, $locale = null, $fallback = true)
{
if (is_null($locale)) {
$locale = app()->getLocale();
}
if ($fallback === true) {
$fallback = config('app.fallback_locale', 'en');
}
$query->with(['translations' => function (Relation $query) use ($locale, $fallback) {
$query->where(function ($q) use ($locale, $fallback) {
$q->where('locale', $locale);
if ($fallback !== false) {
$q->orWhere('locale', $fallback);
}
});
}]);
}
/**
* This scope eager loads the translations for the default and the fallback locale only.
* We can use this as a shortcut to improve performance in our application.
*
* @param Builder $query
* @param string|null|array $locales
* @param string|bool $fallback
*/
public function scopeWithTranslations(Builder $query, $locales = null, $fallback = true)
{
if (is_null($locales)) {
$locales = app()->getLocale();
}
if ($fallback === true) {
$fallback = config('app.fallback_locale', 'en');
}
$query->with(['translations' => function (Relation $query) use ($locales, $fallback) {
if (is_null($locales)) {
return;
}
$query->where(function ($q) use ($locales, $fallback) {
if (is_array($locales)) {
$q->whereIn('locale', $locales);
} else {
$q->where('locale', $locales);
}
if ($fallback !== false) {
$q->orWhere('locale', $fallback);
}
});
}]);
}
/**
* Translate the whole model.
*
* @param null|string $language
* @param bool[string $fallback
*
* @return Translator
*/
public function translate($language = null, $fallback = true)
{
if (!$this->relationLoaded('translations')) {
$this->load('translations');
}
return (new Translator($this))->translate($language, $fallback);
}
/**
* Get a single translated attribute.
*
* @param $attribute
* @param null $language
* @param bool $fallback
*
* @return null
*/
public function getTranslatedAttribute($attribute, $language = null, $fallback = true)
{
// If multilingual is not enabled don't check for translations
if (!config('voyager.multilingual.enabled')) {
return $this->getAttributeValue($attribute);
}
list($value) = $this->getTranslatedAttributeMeta($attribute, $language, $fallback);
return $value;
}
public function getTranslationsOf($attribute, array $languages = null, $fallback = true)
{
if (is_null($languages)) {
$languages = config('voyager.multilingual.locales', [config('voyager.multilingual.default')]);
}
$response = [];
foreach ($languages as $language) {
$response[$language] = $this->getTranslatedAttribute($attribute, $language, $fallback);
}
return $response;
}
public function getTranslatedAttributeMeta($attribute, $locale = null, $fallback = true)
{
// Attribute is translatable
//
if (!in_array($attribute, $this->getTranslatableAttributes())) {
return [$this->getAttribute($attribute), config('voyager.multilingual.default'), false];
}
if (!$this->relationLoaded('translations')) {
$this->load('translations');
}
if (is_null($locale)) {
$locale = app()->getLocale();
}
if ($fallback === true) {
$fallback = config('app.fallback_locale', 'en');
}
$default = config('voyager.multilingual.default');
$translations = $this->getRelation('translations')
->where('column_name', $attribute);
if ($default == $locale) {
return [$this->getAttribute($attribute), $default, true];
}
$localeTranslation = $translations->where('locale', $locale)->first();
if ($localeTranslation) {
return [$localeTranslation->value, $locale, true];
}
if ($fallback == $locale) {
return [$this->getAttribute($attribute), $locale, false];
}
if ($fallback == $default) {
return [$this->getAttribute($attribute), $locale, false];
}
$fallbackTranslation = $translations->where('locale', $fallback)->first();
if ($fallbackTranslation && $fallback !== false) {
return [$fallbackTranslation->value, $locale, true];
}
return [null, $locale, false];
}
/**
* Get attributes that can be translated.
*
* @return array
*/
public function getTranslatableAttributes()
{
return property_exists($this, 'translatable') ? $this->translatable : [];
}
public function setAttributeTranslations($attribute, array $translations, $save = false)
{
$response = [];
if (!$this->relationLoaded('translations')) {
$this->load('translations');
}
$default = config('voyager.multilingual.default', 'en');
$locales = config('voyager.multilingual.locales', [$default]);
foreach ($locales as $locale) {
if (empty($translations[$locale])) {
continue;
}
if ($locale == $default) {
$this->$attribute = $translations[$locale];
continue;
}
$tranlator = $this->translate($locale, false);
$tranlator->$attribute = $translations[$locale];
if ($save) {
$tranlator->save();
}
$response[] = $tranlator;
}
return $response;
}
/**
* Get entries filtered by translated value.
*
* @example Class::whereTranslation('title', '=', 'zuhause', ['de', 'iu'])
* @example $query->whereTranslation('title', '=', 'zuhause', ['de', 'iu'])
*
* @param string $field {required} the field your looking to find a value in.
* @param string $operator {required} value you are looking for or a relation modifier such as LIKE, =, etc.
* @param string $value {optional} value you are looking for. Only use if you supplied an operator.
* @param string|array $locales {optional} locale(s) you are looking for the field.
* @param bool $default {optional} if true checks for $value is in default database before checking translations.
*
* @return Builder
*/
public static function scopeWhereTranslation($query, $field, $operator, $value = null, $locales = null, $default = true)
{
if ($locales && !is_array($locales)) {
$locales = [$locales];
}
if (!isset($value)) {
$value = $operator;
$operator = '=';
}
$self = new static();
$table = $self->getTable();
return $query->whereIn($self->getKeyName(), Translation::where('table_name', $table)
->where('column_name', $field)
->where('value', $operator, $value)
->when(!is_null($locales), function ($query) use ($locales) {
return $query->whereIn('locale', $locales);
})
->pluck('foreign_key')
)->when($default, function ($query) use ($field, $operator, $value) {
return $query->orWhere($field, $operator, $value);
});
}
public function hasTranslatorMethod($name)
{
if (!isset($this->translatorMethods)) {
return false;
}
return isset($this->translatorMethods[$name]);
}
public function getTranslatorMethod($name)
{
if (!$this->hasTranslatorMethod($name)) {
return;
}
return $this->translatorMethods[$name];
}
public function deleteAttributeTranslations(array $attributes, $locales = null)
{
$this->translations()
->whereIn('column_name', $attributes)
->when(!is_null($locales), function ($query) use ($locales) {
$method = is_array($locales) ? 'whereIn' : 'where';
return $query->$method('locale', $locales);
})
->delete();
}
public function deleteAttributeTranslation($attribute, $locales = null)
{
$this->translations()
->where('column_name', $attribute)
->when(!is_null($locales), function ($query) use ($locales) {
$method = is_array($locales) ? 'whereIn' : 'where';
return $query->$method('locale', $locales);
})
->delete();
}
/**
* Prepare translations and set default locale field value.
*
* @param object $request
*
* @return array translations
*/
public function prepareTranslations(&$request)
{
$translations = [];
// Translatable Fields
$transFields = $this->getTranslatableAttributes();
foreach ($transFields as $field) {
if (!$request->input($field.'_i18n')) {
throw new Exception('Invalid Translatable field'.$field);
}
$trans = json_decode($request->input($field.'_i18n'), true);
// Set the default local value
$request->merge([$field => $trans[config('voyager.multilingual.default', 'en')]]);
$translations[$field] = $this->setAttributeTranslations(
$field,
$trans
);
// Remove field hidden input
unset($request[$field.'_i18n']);
}
// Remove language selector input
unset($request['i18n_selector']);
return $translations;
}
/**
* Prepare translations and set default locale field value.
*
* @param object $requestData
*
* @return array translations
*/
public function prepareTranslationsFromArray($field, &$requestData)
{
$translations = [];
$field = 'field_display_name_'.$field;
if (empty($requestData[$field.'_i18n'])) {
throw new Exception('Invalid Translatable field '.$field);
}
$trans = json_decode($requestData[$field.'_i18n'], true);
// Set the default local value
$requestData['display_name'] = $trans[config('voyager.multilingual.default', 'en')];
$translations['display_name'] = $this->setAttributeTranslations(
'display_name',
$trans
);
// Remove field hidden input
unset($requestData[$field.'_i18n']);
return $translations;
}
/**
* Save translations.
*
* @param object $translations
*
* @return void
*/
public function saveTranslations($translations)
{
foreach ($translations as $field => $locales) {
foreach ($locales as $locale => $translation) {
$translation->save();
}
}
}
}
| fletch3555/voyager | src/Traits/Translatable.php | PHP | mit | 12,568 |
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, session: { email: "", password: "" }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
end
| aaronhehehaha/CMPT276_CarPoolApp | CarPoolApp/test/integration/users_login_test.rb | Ruby | mit | 399 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let _ = require('lodash');
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
const pip_services3_couchbase_node_1 = require("pip-services3-couchbase-node");
class PasswordsCouchbasePersistence extends pip_services3_couchbase_node_1.IdentifiableCouchbasePersistence {
constructor() {
super('users', 'passwords');
}
convertToPublic(value) {
value = super.convertToPublic(value);
value.change_time = pip_services3_commons_node_1.DateTimeConverter.toNullableDateTime(value.change_time);
value.lock_time = pip_services3_commons_node_1.DateTimeConverter.toNullableDateTime(value.lock_time);
value.fail_time = pip_services3_commons_node_1.DateTimeConverter.toNullableDateTime(value.fail_time);
value.rec_expire_time = pip_services3_commons_node_1.DateTimeConverter.toNullableDateTime(value.rec_expire_time);
return value;
}
}
exports.PasswordsCouchbasePersistence = PasswordsCouchbasePersistence;
//# sourceMappingURL=PasswordsCouchbasePersistence.js.map | pip-services-users/pip-services-passwords-node | obj/src/persistence/PasswordsCouchbasePersistence.js | JavaScript | mit | 1,122 |
module Splatter
module Init
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def splat(*args)
if args.empty?
@splatter_args || [ ]
else
@splatter_args = args
end
end
end
def initialize(*args)
self.class.splat.each do |name|
instance_variable_set("@#{name}", args.shift)
end
end
end
end
| vroy/splatter | lib/splatter/init.rb | Ruby | mit | 425 |
---
title: HEDIS
is_name: true
---
HEDIS
| stokeclimsland/stokeclimsland | _cards/HEDIS.md | Markdown | mit | 46 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Spidermonkey.Managed;
namespace Spidermonkey {
public interface IRootable {
bool AddRoot (JSContextPtr context, JSRootPtr root);
void RemoveRoot (JSContextPtr context, JSRootPtr root);
}
public class Rooted<T> : IDisposable
where T : struct, IRootable
{
[StructLayout(LayoutKind.Sequential)]
public unsafe class _State {
public T Value;
public _State (T value) {
Value = value;
}
}
private readonly WeakReference ManagedContextReference;
public readonly JSContextPtr Context;
public readonly GCHandle Pin;
public readonly _State State;
public readonly JSRootPtr Root;
public bool IsDisposed { get; private set; }
public bool IsFinalizerEnabled {
get {
return (ManagedContextReference != null);
}
}
private Rooted (
JSContext managedContext,
JSContextPtr context,
T value
) {
if (context.IsZero)
throw new ArgumentNullException("context");
// HACK: Attempt to locate a managed context for a raw pointer if that's all we have.
// This lets us finalize safely.
if (managedContext == null)
managedContext = JSContext.FromPointer(context);
if (managedContext != null)
ManagedContextReference = managedContext.WeakSelf;
else
ManagedContextReference = null;
Context = context;
State = new _State(value);
Pin = GCHandle.Alloc(State, GCHandleType.Pinned);
Root = new JSRootPtr(Pin.AddrOfPinnedObject());
if (!default(T).AddRoot(context, Root))
throw new Exception("Failed to add root");
}
public Rooted (
JSContext managedContext,
T value = default(T)
) : this(managedContext, managedContext, value) {
}
/// <summary>
/// WARNING: Roots created using this constructor will leak if not disposed.
/// </summary>
public Rooted (
JSContextPtr context,
T value = default(T)
) : this(null, context, value) {
}
public void Dispose () {
if (IsDisposed)
return;
IsDisposed = true;
GC.SuppressFinalize(this);
default(T).RemoveRoot(Context, Root);
Pin.Free();
}
~Rooted () {
if (IsDisposed)
return;
// Determine whether it is safe to delete this root.
// If the owning context is destroyed, we will crash when unrooting.
// On the other hand, a dead context doesn't have roots anymore. :-)
bool canDispose = true;
JSContext mc;
if (ManagedContextReference == null)
canDispose = false;
else if (!ManagedContextReference.IsAlive)
canDispose = false;
else if ((mc = (JSContext)ManagedContextReference.Target) == null)
canDispose = false;
else if (mc.IsDisposed)
canDispose = false;
if (canDispose)
Dispose();
}
public T Value {
get {
return State.Value;
}
set {
State.Value = value;
}
}
public static implicit operator T (Rooted<T> rooted) {
return rooted.State.Value;
}
}
}
| kg/SpidermonkeySharp | Rooted.cs | C# | mit | 3,786 |
# IMPORTANT, call this module from /sandbox.py and run() it. This file cannot
# be called directly.
# @see http://stackoverflow.com/questions/4348452/
from lib.geo import util
from lib.geo.segment import Segment
from lib.geo.point import Point
from lib.geo.waypoint import Waypoint
from lib.geo.route import Route
from formation_flight.aircraft import Aircraft
from formation_flight import simulator
from formation_flight import config
from lib import debug
fuel_burn_per_nm = .88
formation_discount = .13
v_opt = 8.333
def fuel_diff(aircraft, departure_hub, arrival_hub, required_etah,
verbose = True):
origin = aircraft.route.waypoints[0]
destination = aircraft.route.waypoints[-1]
position = aircraft.get_position()
direct_length = aircraft.route.get_length()
origin_to_here = origin.distance_to(position)
here_to_hub_length = position.distance_to(departure_hub)
formation_length = departure_hub.distance_to(arrival_hub)
arrival_length = arrival_hub.distance_to(destination)
# Temporarily insert the hubs into the aircraft's route
old_waypoints = aircraft.route.waypoints
aircraft.route.waypoints = [aircraft.route.waypoints[0],
position,
departure_hub,
arrival_hub,
aircraft.route.waypoints[-1]]
planned_etah = aircraft.get_waypoint_eta()
t = simulator.get_time()
v_factor = (planned_etah - t) / (required_etah - t)
v_old = aircraft._speed
v_new = v_factor * v_old
v_penalty = speed_penalty(v_new)
direct_costs = direct_length * fuel_burn_per_nm
formation_costs = fuel_burn_per_nm * origin_to_here +\
v_penalty * fuel_burn_per_nm * here_to_hub_length +\
fuel_burn_per_nm * (1 - formation_discount) *\
formation_length +\
fuel_burn_per_nm * arrival_length
# Change route back to what it was
aircraft.route.waypoints = old_waypoints
if verbose:
headers = []
headers.append(('Mijn header', 'uhuh'))
messages = []
messages.append(('Flight', aircraft))
messages.append(('Departure hub', departure_hub))
messages.append(('Arrival hub', arrival_hub))
messages.append(('Time to hub (planned)', '%d time units' % (planned_etah - t)))
messages.append(('Time to hub (required)', '%d time units' % (required_etah - t)))
messages.append(('Current speed', '%.0f kts' % (v_old*60)))
messages.append(('Required speed', '%.0f kts' % (v_new*60)))
messages.append(('Sync fuel', '%.2f gallons' %
(v_penalty * fuel_burn_per_nm * here_to_hub_length)))
messages.append(('Fuel (solo flight)', '%.2f gallons' % direct_costs))
messages.append(('Fuel (formation flight)', '%.2f gallons' % formation_costs))
debug.print_table(messages = messages, headers = headers)
return direct_costs - formation_costs
def speed_penalty(v):
return 1 + abs(v - v_opt) / v_opt
def run():
planes = [
Aircraft(route = Route([Waypoint('AMS'), Waypoint('JFK')]))
]
simulator.execute([10], planes);
departure_hub = Waypoint('LHR')
arrival_hub = Waypoint('BOS')
p = fuel_diff(planes[0], departure_hub, arrival_hub, 20, verbose = True)
debug.print_table([('Net benefit', '%d gallons' % p)]) | mauzeh/formation-flight | sandbox/penalties.py | Python | mit | 3,527 |
package com.gglinux.course_design;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTable;
import javax.swing.JTextField;
public class StaffIndex implements ActionListener{
public JFrame frame;
private JDesktopPane desktop;
private JTextField author;
private JTextField receiver;
private JTextField content;
private JTextField title;
private JTable table;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private String user;
private JTextField textField_7;
private String password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StaffIndex window = new StaffIndex("","");
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public StaffIndex(String user,String password) {
this.user=user;
this.password=password;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 1000, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
desktop=new JDesktopPane();
desktop.setBackground(new Color(255, 255, 255));
frame.getContentPane().add(desktop);
JInternalFrame internalFrame = new JInternalFrame("\u6B22\u8FCE\u767B\u9646");
internalFrame.setClosable(true);
internalFrame.setBounds(100, 100, 600, 400);
desktop.add(internalFrame);
internalFrame.getContentPane().setLayout(null);
JLabel label = new JLabel("\u884C\u6587\u7BA1\u7406\u7CFB\u7EDF\u6B22\u8FCE\u4F60\u7684\u4F7F\u7528");
label.setForeground(new Color(0, 51, 255));
label.setFont(new Font("ËÎÌå", Font.PLAIN, 40));
label.setBounds(47, 43, 480, 52);
internalFrame.getContentPane().add(label);
internalFrame.setVisible(true);
JLabel lblNewLabel = new JLabel("\u4F5C\u8005\uFF1Agglinux");
lblNewLabel.setFont(new Font("ËÎÌå", Font.PLAIN, 15));
lblNewLabel.setBounds(204, 193, 119, 23);
internalFrame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("\u65F6\u95F4\uFF1A2014\u5E745\u670828\u65E5");
lblNewLabel_1.setFont(new Font("ËÎÌå", Font.PLAIN, 15));
lblNewLabel_1.setBounds(204, 245, 161, 18);
internalFrame.getContentPane().add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("E-mail\[email protected]");
lblNewLabel_2.setFont(new Font("ËÎÌå", Font.PLAIN, 15));
lblNewLabel_2.setBounds(204, 298, 199, 18);
internalFrame.getContentPane().add(lblNewLabel_2);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu_1 = new JMenu("\u4FEE\u6539");
menuBar.add(mnNewMenu_1);
JMenuItem menuItem_7 = new JMenuItem("ÃÜÂëÐÞ¸Ä");
mnNewMenu_1.add(menuItem_7);
JMenu mnNewMenu_2 = new JMenu("\u63A5\u6536");
menuBar.add(mnNewMenu_2);
JMenuItem menuItem_1 = new JMenuItem("ÐÐÎĽÓÊպͻظ´");
mnNewMenu_2.add(menuItem_1);
menuItem_1.addActionListener(this);
JMenu menu = new JMenu("\u67E5\u770B");
menuBar.add(menu);
JMenuItem menuItem = new JMenuItem("\u67E5\u770B\u4FE1\u606F");
menu.add(menuItem);
JMenu mnNewMenu_4 = new JMenu("\u9000\u51FA");
menuBar.add(mnNewMenu_4);
JMenuItem menuItem_6 = new JMenuItem("ÖØÐµÇ½");
mnNewMenu_4.add(menuItem_6);
menuItem_6.addActionListener(this);
JMenuItem menuItem_5 = new JMenuItem("Í˳öϵͳ");
mnNewMenu_4.add(menuItem_5);
menuItem_5.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand()=="Í˳öϵͳ"){
//JOptionPane.showMessageDialog(frame, "Í˳öϵͳ");
System.exit(0);
}
if(e.getActionCommand()=="ÖØÐµÇ½"){
//JOptionPane.showMessageDialog(frame, "ÖØÐµÇ½");
LoginFrame newperson=new LoginFrame();
newperson.frame.setVisible(true);
this.frame.dispose();
}
}
}
| gglinux/xingwen | src/StaffIndex.java | Java | mit | 4,273 |
#ifndef TRACKLAYER_HPP
#define TRACKLAYER_HPP
#include <string>
#include <iostream>
#include <tinyxml2.h>
#include <vector>
#include <ctime>
#include <layer.hpp>
#include "viewport.hpp"
#include "point.hpp"
namespace florb {
class tracklayer : public florb::layer
{
public:
tracklayer(const std::string &path);
tracklayer();
~tracklayer();
class event_notify;
class waypoint;
bool handle_evt_mouse(const florb::layer::event_mouse* evt);
bool handle_evt_key(const florb::layer::event_key* evt);
bool draw(const florb::viewport& vp, florb::canvas& os);
void load_track(const std::string &path);
void save_track(const std::string &path);
void clear_track();
void add_trackpoint(const florb::point2d<double>& p);
size_t selected();
void selection_get(std::vector<waypoint>& waypoints);
void selection_set(const std::vector<waypoint>& waypoints);
void selection_delete();
double trip();
void showwpmarkers(bool s);
private:
static const unsigned int wp_hotspot = 6;
static const std::string trackname;
struct gpx_trkpt {
double lat;
double lon;
double ele;
time_t time;
};
struct selection {
// Multiselect
bool multiselect;
// Dragging
bool dragging;
florb::point2d<double> dragorigin;
florb::point2d<double> dragcurrent;
std::vector< std::vector<florb::tracklayer::gpx_trkpt>::iterator > waypoints;
};
void notify();
bool press(const florb::layer::event_mouse* evt);
bool release(const florb::layer::event_mouse* evt);
bool drag(const florb::layer::event_mouse* evt);
bool key(const florb::layer::event_key* evt);
void trip_update();
void trip_calcall();
void parsetree(tinyxml2::XMLNode *parent);
std::vector<florb::tracklayer::gpx_trkpt> m_trkpts;
selection m_selection;
long double m_trip;
bool m_showwpmarkers;
};
class tracklayer::event_notify : public event_base
{
public:
event_notify() {};
~event_notify() {};
};
class tracklayer::waypoint
{
public:
waypoint(double lon, double lat, double ele, time_t ti) :
m_lon(lon),
m_lat(lat),
m_ele(ele),
m_time(ti) {};
~waypoint() {};
double lon() const { return m_lon; };
void lon(double l) { m_lon = l; };
double lat() const { return m_lat; };
void lat(double l) { m_lat = l; };
double elevation() const { return m_ele; };
void elevation(double ele) { m_ele = ele; };
time_t time() const { return m_time; };
void time(double t) { m_time = t; };
private:
double m_lon;
double m_lat;
double m_ele;
time_t m_time;
};
};
#endif // TRACKLAYER_HPP
| shugaa/florb | src/tracklayer.hpp | C++ | mit | 3,354 |
<!-- ####### -->
<!-- Content -->
<!-- ####### -->
<main>
<div class="main-content">
<!-- ###### -->
<!-- Header -->
<!-- ###### -->
<div class="row">
<div class="col s12">
<div style="width:80%" class="page-header">
<h1>
<i class="medium material-icons">live_help</i> <?= $encuestas->titulo ?>
</h1>
<p ><?= $encuestas->instrucciones ?></p>
</div>
</div>
</div>
<!-- #### -->
<!-- Body -->
<!-- #### -->
<section id="apps_crud_form">
<div class="crud-app">
<div class="fixed-action-btn">
<a class="btn-floating btn-large tooltipped" data-tooltip="Regresar" data-position="top" data-delay="50" href="<?= base_url().'ConLaPlayera/inicio' ?>">
<i class="large material-icons">undo</i>
</a>
<button class="btn-floating btn-large white tooltipped scrollToTop" data-tooltip="Scroll to top" data-position="top" data-delay="50">
<i class="large material-icons">keyboard_arrow_up</i>
</button>
</div>
<?php
$hidden = array('encuestas_id' => $encuestas->encuestas_id);
echo form_open('ConLaPlayera/contestar/' . $encuestas->encuestas_id,'', $hidden);
?>
<div class="row">
<div class="col offset-m2 s12 m8">
<?php
$msg = $this->session->flashdata('msg');
if ($msg){
echo $msg;
}
?>
<div class="panel panel-bordered" style="">
<div class="panel-body">
<div class="row no-gutter">
<div class="input-field col s6">
<i class="material-icons prefix">textsms</i>
<input style="font-weight: bold; font-size: 18px; color:black" type="text" name="nombre" id="autocomplete-input" class="autocomplete">
<label style="font-weight: bold; font-size: 18px; color:black" for="autocomplete-input">Nombre</label>
<?php echo form_error('nombre'); ?>
</div>
<div class="input-field col s6">
<input style="font-weight: bold; font-size: 18px; color:black" name="area" id="area" type="text" required="" aria-required="true" class="validate">
<label style="font-weight: bold; font-size: 18px; color:black" for="area">Àrea</label>
<?php echo form_error('area'); ?>
</div>
</div>
<?php
$count = 1;
foreach ($preguntas->result() as $row) {
?>
<div class="row no-gutter">
<div class="col s1">
</div>
<div class="col s10">
<p style="color: black; font-weight: bold; font-size: 16px;" ><?= $count ?>.- <?= $row->pregunta ?></p>
<?php
echo form_hidden('pregunta['.$count.']', $row->preguntas_id);
?>
</div>
</div>
<div class="row no-gutter">
<div class="col s1">
</div>
<div class="input-field col s10">
<select style=" border: solid 1px #000000; color: black, font-size: 16px;" name="respuesta[<?= $count ?>]" id="respuesta<?= $count ?>" required="" aria-required="true" class="browser-default validate">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
<?php
$count++;
}
?>
<br>
<div class="input-field row no-gutter">
<div class="col s1">
</div>
<div class="col s10">
<label style="color: black" for="comentario"><b>Comentarios</b></label>
<textarea style="color:black" name="comentario" id="comentario" class="materialize-textarea"></textarea>
</div>
</div>
</div>
<div class="panel-footer">
<div class="right-align">
<button type="reset" class="btn-flat waves-effect">
BORRAR
</button>
<button type="submit" class="btn-flat waves-effect">
FINALIZAR
</button>
</div>
</div>
</div>
</div>
<div class="col s12 m4">
<div class="helper"> </div>
</div>
</div>
<?= form_close() ?>
</div>
</section>
</div>
</main>
| si-quimera/avante | application/views/conla_playera/contestar.php | PHP | mit | 8,251 |
<?php
/**
* This file is part of the "NFQ Bundles" package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nfq\SeoBundle\Page;
/**
* Class AbstractSeoPage
* @package Nfq\SeoBundle\Page
*/
abstract class AbstractSeoPage
{
/**
* @var string
*/
protected $host;
/**
* @var string
*/
protected $simpleHost;
/**
* @var string
*/
protected $locale;
/**
* @var string
*/
protected $titleData;
/**
* @var array
*/
protected $metas;
/**
* @var array
*/
protected $headAttributes;
/**
* @var array
*/
protected $htmlAttributes;
/**
* @var array
*/
protected $langAlternates;
/**
* @var array
*/
protected $links;
/**
* An array of allowed query params for rels:
*
* @var array
*/
protected $linkOptions;
/**
* @inheritdoc
*/
public function __construct()
{
$this->titleData = [
'title' => '',
'extras' => [],
];
$this->metas = [
'http-equiv' => [],
'name' => [],
'schema' => [],
'charset' => [],
'property' => [],
];
$this->links = [
SeoPageInterface::SEO_REL_PREV => [],
SeoPageInterface::SEO_REL_NEXT => [],
SeoPageInterface::SEO_REL_CANONICAL => [],
SeoPageInterface::SEO_REL_ALTERNATE => [],
];
$this->linkOptions = [];
$this->htmlAttributes = [];
$this->headAttributes = [];
$this->langAlternates = [];
}
/**
* @param $type
* @return array
*/
protected function getLinks($type)
{
return isset($this->links[$type]) ? $this->links[$type] : $this->links;
}
/**
* @param string $type
* @param string $uri
* @return $this
*/
protected function setLink($type, $uri)
{
if (array_key_exists($type, $this->links)) {
$this->addLink($type, $uri, false);
}
return $this;
}
/**
* @param string $type
* @param array $uris
* @return $this
*/
protected function addLinks($type, array $uris)
{
if (array_key_exists($type, $this->links)) {
foreach($uris as $key => $uri) {
$this->addLink($type, $uri, $key);
}
}
return $this;
}
/**
* @param string $type
* @param string $data
* @param string|null|bool $index
* @return $this
*/
private function addLink($type, $data, $index = null)
{
if (is_null($index)) {
$this->links[$type][] = $data;
} elseif ($index === false) {
$this->links[$type] = $data;
} else {
$this->links[$type][$index] = $data;
}
return $this;
}
/**
* @param array $options
* @return $this
*/
public function setLinkOptions(array $options)
{
$this->linkOptions = $options;
return $this;
}
/**
* @inheritdoc
*/
public function getLinkOptions($option = null)
{
return $option && isset($this->linkOptions[$option]) ? $this->linkOptions[$option] : $this->linkOptions;
}
}
| nfq-rho/seo-bundle | Page/AbstractSeoPage.php | PHP | mit | 3,467 |
"""Tests for registry module - nodes methods"""
import vcr
from pygbif import registry
@vcr.use_cassette("test/vcr_cassettes/test_nodes.yaml")
def test_nodes():
"registry.nodes - basic test"
res = registry.nodes()
assert dict == res.__class__
assert 2 == len(res)
assert 100 == len(res["data"])
assert ["data", "meta"] == sorted(res.keys())
@vcr.use_cassette("test/vcr_cassettes/test_nodes_limit.yaml")
def test_nodes_limit():
"registry.nodes - limit param"
res = registry.nodes(limit=5)
assert dict == res.__class__
assert 5 == len(res["data"])
@vcr.use_cassette("test/vcr_cassettes/test_nodes_return.yaml")
def test_nodes_return():
"registry.nodes - data param"
res = registry.nodes(data="identifier", uuid="03e816b3-8f58-49ae-bc12-4e18b358d6d9")
assert dict == res.__class__
assert 2 == len(res)
assert 1 == len(res["data"])
assert 5 == len(res["data"][0])
assert "identifier" in res["data"][0].keys()
| sckott/pygbif | test/test-registry-nodes.py | Python | mit | 980 |
import java.util.Arrays;
import java.util.PriorityQueue;
public class KthLargestElementInAnArray {
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, nums.length - k + 1, 0, nums.length - 1);
}
private int quickSelect(int[] nums, int k, int low, int high) {
int pivot = nums[high];
int left = low;
int right = high;
while (true) {
while (nums[left] < pivot && left < right) left++;
while (nums[right] >= pivot && right > left) right--;
if (left == right) break;
swap(nums, left, right);
}
swap(nums, left, high);
if (left + 1 == k)
return pivot;
else if (k < left + 1)
return quickSelect(nums, k, low, left - 1);
else
return quickSelect(nums, k, left + 1, high);
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public int findKthLargest1(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
public int findKthLargest2(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
public static void main(String[] args) {
int[] nums = {3, 2, 1, 5, 6, 4};
int k = 2;
System.out.println(Arrays.toString(nums));
System.out.println(k);
KthLargestElementInAnArray solution = new KthLargestElementInAnArray();
System.out.println(solution.findKthLargest(nums, k));
}
} | dantin/leetcode-solutions | java/KthLargestElementInAnArray.java | Java | mit | 1,761 |
module SimpleRunner
def run
trap_signals
main_loop
end
def exiting?
!!@exiting
end
def trap_signals
trap('INT') {
exit 0
}
trap('TERM') {
@exiting = 1
raise Interrupt
}
end
def self.included(base)
base.instance_eval do
def self.run(&blk)
@runner = blk
end
end
end
def main_loop
blk = self.class.instance_variable_get(:@runner)
raise unless blk
self.instance_eval do
self.class.send(:define_method, :runner, &blk)
end
until exiting?
runner
end
rescue Interrupt
exit 0
end
end
| wanelo/sequel-schema-sharding-minotaur | lib/simple_runner.rb | Ruby | mit | 617 |
/**
* The MIT License (MIT)
* Copyright (c) 2013 OMG BPMN Model Interchange Working Group
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.omg.bpmn.miwg.api.output.dom.finding;
public class NoReferenceEntry extends AbstractFindingEntry {
public NoReferenceEntry() {
System.err.println("This should not happen");
}
@Override
public String toLine() {
return String.format("Reference not found");
}
}
| bpmn-miwg/bpmn-miwg-tools | analysis-tool-api/src/main/java/org/omg/bpmn/miwg/api/output/dom/finding/NoReferenceEntry.java | Java | mit | 1,468 |
/* $Id: sip_transport_tcp.h 5649 2017-09-15 05:32:08Z riza $ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <[email protected]>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJSIP_TRANSPORT_TCP_H__
#define __PJSIP_TRANSPORT_TCP_H__
/**
* @file sip_transport_tcp.h
* @brief SIP TCP Transport.
*/
#include <pjsip/sip_transport.h>
#include <pj/sock_qos.h>
/* Only declare the API if PJ_HAS_TCP is true */
#if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
PJ_BEGIN_DECL
/**
* @defgroup PJSIP_TRANSPORT_TCP TCP Transport
* @ingroup PJSIP_TRANSPORT
* @brief API to create and register TCP transport.
* @{
* The functions below are used to create TCP transport and register
* the transport to the framework.
*/
/**
* Settings to be specified when creating the TCP transport. Application
* should initialize this structure with its default values by calling
* pjsip_tcp_transport_cfg_default().
*/
typedef struct pjsip_tcp_transport_cfg
{
/**
* Address family to use. Valid values are pj_AF_INET() and
* pj_AF_INET6(). Default is pj_AF_INET().
*/
int af;
/**
* Optional address to bind the socket to. Default is to bind to
* PJ_INADDR_ANY and to any available port.
*/
pj_sockaddr bind_addr;
/**
* Should SO_REUSEADDR be used for the listener socket.
* Default value is PJSIP_TCP_TRANSPORT_REUSEADDR.
*/
pj_bool_t reuse_addr;
/**
* Optional published address, which is the address to be
* advertised as the address of this SIP transport.
* By default the bound address will be used as the published address.
*/
pjsip_host_port addr_name;
/**
* Number of simultaneous asynchronous accept() operations to be
* supported. It is recommended that the number here corresponds to
* the number of processors in the system (or the number of SIP
* worker threads).
*
* Default: 1
*/
unsigned async_cnt;
/**
* QoS traffic type to be set on this transport. When application wants
* to apply QoS tagging to the transport, it's preferable to set this
* field rather than \a qos_param fields since this is more portable.
*
* Default is QoS not set.
*/
pj_qos_type qos_type;
/**
* Set the low level QoS parameters to the transport. This is a lower
* level operation than setting the \a qos_type field and may not be
* supported on all platforms.
*
* Default is QoS not set.
*/
pj_qos_params qos_params;
/**
* Specify options to be set on the transport.
*
* By default there is no options.
*
*/
pj_sockopt_params sockopt_params;
} pjsip_tcp_transport_cfg;
/**
* Initialize pjsip_tcp_transport_cfg structure with default values for
* the specifed address family.
*
* @param cfg The structure to initialize.
* @param af Address family to be used.
*/
PJ_DECL(void) pjsip_tcp_transport_cfg_default(pjsip_tcp_transport_cfg *cfg,
int af);
/**
* Register support for SIP TCP transport by creating TCP listener on
* the specified address and port. This function will create an
* instance of SIP TCP transport factory and register it to the
* transport manager.
*
* @param endpt The SIP endpoint.
* @param local Optional local address to bind, or specify the
* address to bind the server socket to. Both IP
* interface address and port fields are optional.
* If IP interface address is not specified, socket
* will be bound to PJ_INADDR_ANY. If port is not
* specified, socket will be bound to any port
* selected by the operating system.
* @param async_cnt Number of simultaneous asynchronous accept()
* operations to be supported. It is recommended that
* the number here corresponds to the number of
* processors in the system (or the number of SIP
* worker threads).
* @param p_factory Optional pointer to receive the instance of the
* SIP TCP transport factory just created.
*
* @return PJ_SUCCESS when the transport has been successfully
* started and registered to transport manager, or
* the appropriate error code.
*/
PJ_DECL(pj_status_t) pjsip_tcp_transport_start(pjsip_endpoint *endpt,
const pj_sockaddr_in *local,
unsigned async_cnt,
pjsip_tpfactory **p_factory);
/**
* A newer variant of #pjsip_tcp_transport_start(), which allows specifying
* the published/public address of the TCP transport.
*
* @param endpt The SIP endpoint.
* @param local Optional local address to bind, or specify the
* address to bind the server socket to. Both IP
* interface address and port fields are optional.
* If IP interface address is not specified, socket
* will be bound to PJ_INADDR_ANY. If port is not
* specified, socket will be bound to any port
* selected by the operating system.
* @param a_name Optional published address, which is the address to be
* advertised as the address of this SIP transport.
* If this argument is NULL, then the bound address
* will be used as the published address.
* @param async_cnt Number of simultaneous asynchronous accept()
* operations to be supported. It is recommended that
* the number here corresponds to the number of
* processors in the system (or the number of SIP
* worker threads).
* @param p_factory Optional pointer to receive the instance of the
* SIP TCP transport factory just created.
*
* @return PJ_SUCCESS when the transport has been successfully
* started and registered to transport manager, or
* the appropriate error code.
*/
PJ_DECL(pj_status_t) pjsip_tcp_transport_start2(pjsip_endpoint *endpt,
const pj_sockaddr_in *local,
const pjsip_host_port *a_name,
unsigned async_cnt,
pjsip_tpfactory **p_factory);
/**
* Another variant of #pjsip_tcp_transport_start().
*
* @param endpt The SIP endpoint.
* @param cfg TCP transport settings. Application should initialize
* this setting with #pjsip_tcp_transport_cfg_default().
* @param p_factory Optional pointer to receive the instance of the
* SIP TCP transport factory just created.
*
* @return PJ_SUCCESS when the transport has been successfully
* started and registered to transport manager, or
* the appropriate error code.
*/
PJ_DECL(pj_status_t) pjsip_tcp_transport_start3(
pjsip_endpoint *endpt,
const pjsip_tcp_transport_cfg *cfg,
pjsip_tpfactory **p_factory
);
/**
* Retrieve the internal socket handle used by the TCP transport. Note
* that this socket normally is registered to ioqueue, so application
* needs to take care not to perform operation that disrupts ioqueue
* operation.
*
* @param transport The TCP transport.
*
* @return The socket handle, or PJ_INVALID_SOCKET if no socket
* is currently being used.
*/
PJ_DECL(pj_sock_t) pjsip_tcp_transport_get_socket(pjsip_transport *transport);
/**
* Start the TCP listener, if the listener is not started yet. This is useful
* to start the listener manually, if listener was not started when
* PJSIP_TCP_TRANSPORT_DONT_CREATE_LISTENER is set to 0.
*
* @param factory The SIP TCP transport factory.
*
* @param local The address where the listener should be bound to.
* Both IP interface address and port fields are optional.
* If IP interface address is not specified, socket
* will be bound to PJ_INADDR_ANY. If port is not
* specified, socket will be bound to any port
* selected by the operating system.
*
* @param a_name The published address for the listener.
* If this argument is NULL, then the bound address will
* be used as the published address.
*
* @return PJ_SUCCESS when the listener has been successfully
* started.
*/
PJ_DECL(pj_status_t) pjsip_tcp_transport_lis_start(pjsip_tpfactory *factory,
const pj_sockaddr *local,
const pjsip_host_port *a_name);
/**
* Restart the TCP listener. This will close the listener socket and recreate
* the socket based on the config used when starting the transport.
*
* @param factory The SIP TCP transport factory.
*
* @param local The address where the listener should be bound to.
* Both IP interface address and port fields are optional.
* If IP interface address is not specified, socket
* will be bound to PJ_INADDR_ANY. If port is not
* specified, socket will be bound to any port
* selected by the operating system.
*
* @param a_name The published address for the listener.
* If this argument is NULL, then the bound address will
* be used as the published address.
*
* @return PJ_SUCCESS when the listener has been successfully
* restarted.
*
*/
PJ_DECL(pj_status_t) pjsip_tcp_transport_restart(pjsip_tpfactory *factory,
const pj_sockaddr *local,
const pjsip_host_port *a_name);
PJ_END_DECL
/**
* @}
*/
#endif /* PJ_HAS_TCP */
#endif /* __PJSIP_TRANSPORT_TCP_H__ */
| YLTTeam/YLT_PJSip | YLT_PJSip/Classes/include/pjsip/sip_transport_tcp.h | C | mit | 9,708 |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Henge: l_ous</title>
<link rel="stylesheet" href="/vendor/bootstrap-3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/site.css">
</head>
<body>
<div id="staticBody">
<header>
<h1><img src="/imgs/logo.svg" alt="henge"></h1>
</header>
<h2>#731 l_ous</h2>
<ul id="words">
<li>laborious</li>
<li>lascivious</li>
<li>lecherous</li>
<li>libelous</li>
<li>licentious</li>
<li>litigious</li>
<li>loquacious</li>
<li>ludicrous</li>
<li>luminous</li>
<li>luscious</li>
<li>lustrous</li>
<li>luxurious</li>
</ul>
</div>
<div id="CircleApp" data-floor="61" data-floor-pos="10"></div>
<script type="text/javascript" src="/CircleApp.bundle.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-631498-5', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| henge-tech/henge-tech | docs/circles/l_ous.html | HTML | mit | 1,216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.