repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
tobiasrask/entity-api | src/field/field_types/field-type.js | 1786 | import DomainMap from 'domain-map'
import system from './../../system'
/**
* Field type.
*/
class FieldType {
/**
* Construct field type
*
* @param params
*/
constructor(variables = {}) {
this._registry = new DomainMap()
this._registry.set('properties', 'fieldTypeId', variables.fieldTypeId)
}
/**
* Get field type id.
*
* @return field type id
*/
getFieldTypeId() {
return this._registry.get('properties', 'fieldTypeId')
}
/**
* Set value. Value must be valid for instance type.
*
* @param value
* @return boolean succeed
*/
setValue(value) {
// Prepare field value
value = this.prepareFieldValue(value)
if (this.validateFieldValue(value)) {
this._registry.set('properties', 'value', value)
return true
} else {
system.log('FieldType', `Unable to set value, validation failed: ${value}`, 'error')
return false
}
}
/**
* Get value.
*
* @return value
*/
getValue() {
return this._registry.get('properties', 'value', this.getDefaultValue())
}
/**
* Set value.
*
* @param value
*/
setDefaultValue(value) {
this._registry.set('properties', 'defaultValue', value)
}
/**
* Get value.
*
* @return value
*/
getDefaultValue() {
return this._registry.get('properties', 'defaultValue', null)
}
/**
* Prepare field value. Allows fields to format values.
*
* @param value
* @return value
*/
prepareFieldValue(value) {
return value
}
/**
* Validate field value before assigning it.
*
* @return boolean is valid
*/
validateFieldValue(_value) {
return true
}
/**
* Method checks if value is empty
*
* @return boolean is empty
*/
isEmpty() {
return true
}
}
export default FieldType | mit |
tristil/method-todo | config/initializers/konacha.rb | 212 | Konacha.configure do |config|
config.spec_dir = 'spec/javascripts'
config.spec_matcher = /_spec\.|_test\./
config.stylesheets = %w(application)
config.driver = :webkit
end if defined?(Konacha)
| mit |
tdg5/gearo_worship | lib/reverb.rb | 927 | require 'faraday'
module Reverb
def self.queue
'reverb_requests'
end
def self.preprocess(keyword)
if keyword.include?('(')
return keyword[/(.*?)\s?\(/, 1]
else
return keyword
end
end
def self.perform(request_id, keyword)
conn = Faraday.new(:url => 'https://reverb.com:443')
processed_keyword = preprocess(keyword)
response = conn.get do |req|
req.url '/api/listings.json'
req.params['query'] = processed_keyword
req.headers['X-Auth-Token'] = AUTH_TOKEN
end
instrument = Instrument.find_by(name: keyword)
rec = ReverbRequestInstrument.find_by(request_id: request_id, instrument_id: instrument.id)
if rec
rec.completed = true
rec.save
end
result = JSON.parse(response.body)['listings']
response_json = result.empty? ? nil : JSON.generate(result)
ReverbResponse.create!(:request_id => request_id, :response => response_json, :instrument_id => instrument.id)
end
end
| mit |
honeypotio/techmap | src/components/LoadingIndicator/Wrapper.js | 180 | import styled from 'styled-components';
const Wrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
height: 100%;
`;
export default Wrapper;
| mit |
Fogelholk/CleverControl | action.php | 515 | <?php
if(is_numeric($_GET['switch'])){
$switch = escapeshellcmd($_GET['switch']);
switch ($_GET['action']) {
case "off":
$action = "f";
break;
case "on":
$action = "n";
break;
case "dim":
if(is_numeric($_GET['dimlevel'])){
$dimlevel = escapeshellcmd($_GET['dimlevel']);
}
$action = "v ".$dimlevel." -d";
break;
}
exec("tdtool -".$action." ".$switch." && tdtool --list-devices > tdtool-devices-new.txt && mv tdtool-devices-new.txt tdtool-devices.txt");
}
?>
| mit |
jelhan/croodle | api/config.default.php | 289 | <?php
return array(
/*
* dataDir (String)
* relative or absolute path to folder where polls are stored
*/
'dataDir' => getenv('CROODLE__DATA_DIR') ?: '../data/',
/*
* debug (Boolean)
* controls Slim debug mode
*/
'debug' => getenv('CROODLE__DEBUG') ?: false
);
| mit |
bostontrader/senmaker | src/nightmare/IntroTestLauncher.js | 837 | var Nightmare = require('nightmare')
var LanguageSwitchTest = require('./LanguageSwitchTest')
var IntroTest = require('./IntroTest')
describe('Intro', () => {
const url = 'http://localhost:8081'
it('Should work correctly', (done) => {
const nightmare = new Nightmare({show:true, width:600, height:800, zoomFactor: 0.5})
//const delayA = 10
const delayB = 250
const delayC = 1000
nightmare.goto(url).wait(delayC)
// By default the app starts in Chinese. Test that we can switch the language to English
.then( res => {return LanguageSwitchTest(nightmare, delayC)})
// And the rest of the test runs in English
.then( res => {return IntroTest(nightmare, delayB)})
.then(result => {done()})
}).timeout(4000)
})
| mit |
balanced/balanced-csharp | scenarios/scenarios/api_key_list/definition.cs | 17 | ApiKey.Query() | mit |
devbridge/BetterModules | BetterModules.Core.Web/Events/WebCoreEvents.cs | 3050 | using System.Web;
// ReSharper disable CheckNamespace
namespace BetterModules.Events
// ReSharper restore CheckNamespace
{
public class WebCoreEvents : EventsBase<WebCoreEvents>
{
/// <summary>
/// Occurs when a host starts.
/// </summary>
public event DefaultEventHandler<SingleItemEventArgs<HttpApplication>> HostStart;
public event DefaultEventHandler<SingleItemEventArgs<HttpApplication>> HostStop;
public event DefaultEventHandler<SingleItemEventArgs<HttpApplication>> HostError;
public event DefaultEventHandler<SingleItemEventArgs<HttpApplication>> HostAuthenticateRequest;
public event DefaultEventHandler<SingleItemEventArgs<HttpApplication>> RequestBegin;
public event DefaultEventHandler<SingleItemEventArgs<HttpApplication>> RequestEnd;
/// <summary>
/// Called when a host starts.
/// </summary>
/// <param name="host">The host.</param>
public void OnHostStart(HttpApplication host)
{
if (HostStart != null)
{
HostStart(new SingleItemEventArgs<HttpApplication>(host));
}
}
/// <summary>
/// Called when a host stops.
/// </summary>
/// <param name="host">The host.</param>
public void OnHostStop(HttpApplication host)
{
if (HostStop != null)
{
HostStop(new SingleItemEventArgs<HttpApplication>(host));
}
}
/// <summary>
/// Called when a host throws error.
/// </summary>
/// <param name="host">The host.</param>
public void OnHostError(HttpApplication host)
{
if (HostError != null)
{
HostError(new SingleItemEventArgs<HttpApplication>(host));
}
}
/// <summary>
/// Called when a host authenticates request.
/// </summary>
/// <param name="host">The host.</param>
public void OnHostAuthenticateRequest(HttpApplication host)
{
if (HostAuthenticateRequest != null)
{
HostAuthenticateRequest(new SingleItemEventArgs<HttpApplication>(host));
}
}
/// <summary>
/// Called when request begins.
/// </summary>
/// <param name="application">The application.</param>
public void OnRequestBegin(HttpApplication application)
{
if (RequestBegin != null)
{
RequestBegin(new SingleItemEventArgs<HttpApplication>(application));
}
}
/// <summary>
/// Called when request ends.
/// </summary>
/// <param name="application">The application.</param>
public void OnRequestEnd(HttpApplication application)
{
if (RequestEnd != null)
{
RequestEnd(new SingleItemEventArgs<HttpApplication>(application));
}
}
}
}
| mit |
zhkuskov/croogo_cms_2.0 | Vendor/croogo/croogo/Trackings/Test/Fixture/TrackingFixture.php | 1131 | <?php
/**
* TrackingFixture
*
*/
class TrackingFixture extends CakeTestFixture {
/**
* Fields
*
* @var array
*/
public $fields = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
'type' => array('type' => 'string', 'null' => false, 'default' => 'Analytics', 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'trackingid' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'created' => array('type' => 'date', 'null' => false, 'default' => null),
'updated' => array('type' => 'date', 'null' => false, 'default' => null),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1)
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
);
/**
* Records
*
* @var array
*/
public $records = array(
array(
'id' => 1,
'type' => 'Lorem ipsum dolor sit amet',
'trackingid' => 'Lorem ipsum dolor sit amet',
'created' => '2014-04-17',
'updated' => '2014-04-17'
),
);
}
| mit |
lbryio/lbry | torba/tests/client_tests/integration/test_transactions.py | 5869 | import logging
import asyncio
from itertools import chain
from torba.testcase import IntegrationTestCase
from torba.client.util import satoshis_to_coins, coins_to_satoshis
class BasicTransactionTests(IntegrationTestCase):
VERBOSITY = logging.WARN
async def test_variety_of_transactions_and_longish_history(self):
await self.blockchain.generate(300)
await self.assertBalance(self.account, '0.0')
addresses = await self.account.receiving.get_addresses()
# send 10 coins to first 10 receiving addresses and then 10 transactions worth 10 coins each
# to the 10th receiving address for a total of 30 UTXOs on the entire account
sends = list(chain(
(self.blockchain.send_to_address(address, 10) for address in addresses[:10]),
(self.blockchain.send_to_address(addresses[9], 10) for _ in range(10))
))
# use batching to reduce issues with send_to_address on cli
for batch in range(0, len(sends), 10):
txids = await asyncio.gather(*sends[batch:batch+10])
await asyncio.wait([self.on_transaction_id(txid) for txid in txids])
await self.assertBalance(self.account, '200.0')
self.assertEqual(20, await self.account.get_utxo_count())
# address gap should have increase by 10 to cover the first 10 addresses we've used up
addresses = await self.account.receiving.get_addresses()
self.assertEqual(30, len(addresses))
# there used to be a sync bug which failed to save TXIs between
# daemon restarts, clearing cache replicates that behavior
self.ledger._tx_cache.clear()
# spend from each of the first 10 addresses to the subsequent 10 addresses
txs = []
for address in addresses[10:20]:
txs.append(await self.ledger.transaction_class.create(
[],
[self.ledger.transaction_class.output_class.pay_pubkey_hash(
coins_to_satoshis('1.0'), self.ledger.address_to_hash160(address)
)],
[self.account], self.account
))
await asyncio.wait([self.broadcast(tx) for tx in txs])
await asyncio.wait([self.ledger.wait(tx) for tx in txs])
# verify that a previous bug which failed to save TXIs doesn't come back
# this check must happen before generating a new block
self.assertTrue(all([
tx.inputs[0].txo_ref.txo is not None
for tx in await self.ledger.db.get_transactions(txid__in=[tx.id for tx in txs])
]))
await self.blockchain.generate(1)
await asyncio.wait([self.ledger.wait(tx) for tx in txs])
await self.assertBalance(self.account, '199.99876')
# 10 of the UTXOs have been split into a 1 coin UTXO and a 9 UTXO change
self.assertEqual(30, await self.account.get_utxo_count())
# spend all 30 UTXOs into a a 199 coin UTXO and change
tx = await self.ledger.transaction_class.create(
[],
[self.ledger.transaction_class.output_class.pay_pubkey_hash(
coins_to_satoshis('199.0'), self.ledger.address_to_hash160(addresses[-1])
)],
[self.account], self.account
)
await self.broadcast(tx)
await self.ledger.wait(tx)
await self.blockchain.generate(1)
await self.ledger.wait(tx)
self.assertEqual(2, await self.account.get_utxo_count()) # 199 + change
await self.assertBalance(self.account, '199.99649')
async def test_sending_and_receiving(self):
account1, account2 = self.account, self.wallet.generate_account(self.ledger)
await self.ledger.subscribe_account(account2)
await self.assertBalance(account1, '0.0')
await self.assertBalance(account2, '0.0')
addresses = await self.account.receiving.get_addresses()
txids = await asyncio.gather(*(
self.blockchain.send_to_address(address, 1.1) for address in addresses[:5]
))
await asyncio.wait([self.on_transaction_id(txid) for txid in txids]) # mempool
await self.blockchain.generate(1)
await asyncio.wait([self.on_transaction_id(txid) for txid in txids]) # confirmed
await self.assertBalance(account1, '5.5')
await self.assertBalance(account2, '0.0')
address2 = await account2.receiving.get_or_create_usable_address()
tx = await self.ledger.transaction_class.create(
[],
[self.ledger.transaction_class.output_class.pay_pubkey_hash(
coins_to_satoshis('2.0'), self.ledger.address_to_hash160(address2)
)],
[account1], account1
)
await self.broadcast(tx)
await self.ledger.wait(tx) # mempool
await self.blockchain.generate(1)
await self.ledger.wait(tx) # confirmed
await self.assertBalance(account1, '3.499802')
await self.assertBalance(account2, '2.0')
utxos = await self.account.get_utxos()
tx = await self.ledger.transaction_class.create(
[self.ledger.transaction_class.input_class.spend(utxos[0])],
[],
[account1], account1
)
await self.broadcast(tx)
await self.ledger.wait(tx) # mempool
await self.blockchain.generate(1)
await self.ledger.wait(tx) # confirmed
tx = (await account1.get_transactions())[1]
self.assertEqual(satoshis_to_coins(tx.inputs[0].amount), '1.1')
self.assertEqual(satoshis_to_coins(tx.inputs[1].amount), '1.1')
self.assertEqual(satoshis_to_coins(tx.outputs[0].amount), '2.0')
self.assertEqual(tx.outputs[0].get_address(self.ledger), address2)
self.assertEqual(tx.outputs[0].is_change, False)
self.assertEqual(tx.outputs[1].is_change, True)
| mit |
Cerebri/material-ui | lib/svg-icons/av/slow-motion-video.js | 987 | 'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var AvSlowMotionVideo = React.createClass({
displayName: 'AvSlowMotionVideo',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M13.05 9.79L10 7.5v9l3.05-2.29L16 12zm0 0L10 7.5v9l3.05-2.29L16 12zm0 0L10 7.5v9l3.05-2.29L16 12zM11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zm1.61 6.74C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43zM22 12c0 5.16-3.92 9.42-8.95 9.95v-2.02C16.97 19.41 20 16.05 20 12s-3.03-7.41-6.95-7.93V2.05C18.08 2.58 22 6.84 22 12z' })
);
}
});
module.exports = AvSlowMotionVideo; | mit |
muditdholakia/camx | excr1.php | 4388 | <?php
session_start();
include("db_connect.php");
extract($_GET);
$d=date("20ymd");
if($mrk=="100")
{
$qx=mysql_query("insert into ex_record(ex_id,u_id,date_exam,attempt_que,discard_que,marks_obtained,ex_status,total_mark,timer,random) values ('NULL','".$_SESSION['unm']."','".$d."','NULL','NULL','NULL','PENDING','100','10800','YES')");
$xx=mysql_insert_id();
echo "<br />";
echo $xx;
$q1=mysql_query("select * from ex_data where mark='1' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 10");
while($r1=mysql_fetch_array($q1))
{
echo $r1[0];
echo $r1[2];
echo "<br />";
$qr1=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r1[0]."','".$r1[2]."')");
}
$q2=mysql_query("select * from ex_data where mark='2' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 10");
while($r2=mysql_fetch_array($q2))
{
echo $r2[0];
echo $r2[2];
echo "<br />";
$qr2=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r2[0]."','".$r2[2]."')");
}
$q3=mysql_query("select * from ex_data where mark='3' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 10");
while($r3=mysql_fetch_array($q3))
{
echo $r3[0];
echo $r3[2];
echo "<br />";
$qr3=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r3[0]."','".$r3[2]."')");
}
$q4=mysql_query("select * from ex_data where mark='4' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 10");
while($r4=mysql_fetch_array($q4))
{
echo $r4[0];
echo $r4[2];
echo "<br />";
$qr4=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r4[0]."','".$r4[2]."')");
}
$qry=mysql_query("select tmp_sr_no from temp_ex_data where srno='".$xx."'");
$qrr=mysql_fetch_array($qry);
echo $qrr[0];
echo "<br />";
$_SESSION['min']=1;
$_SESSION['max']=40;
$_SESSION['curr']=$qrr[0];
$_SESSION['qcount']=1;
$_SESSION['exid']=$xx;
$_SESSION['lastmove']=1;
printf("Mudit");
header("location:exampage.php");
}
if($mrk=="50")
{
$qx=mysql_query("insert into ex_record(ex_id,u_id,date_exam,attempt_que,discard_que,marks_obtained,ex_status,total_mark,timer,random) values ('NULL','".$_SESSION['unm']."','".$d."','NULL','NULL','NULL','PENDING','50','5400','YES')");
$xx=mysql_insert_id();
echo "<br />";
echo $xx;
$q1=mysql_query("select * from ex_data where mark='1' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 5");
while($r1=mysql_fetch_array($q1))
{
echo $r1[0];
echo $r1[2];
echo "<br />";
$qr1=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r1[0]."','".$r1[2]."')");
}
$q2=mysql_query("select * from ex_data where mark='2' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 5");
while($r2=mysql_fetch_array($q2))
{
echo $r2[0];
echo $r2[2];
echo "<br />";
$qr2=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r2[0]."','".$r2[2]."')");
}
$q3=mysql_query("select * from ex_data where mark='3' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 5");
while($r3=mysql_fetch_array($q3))
{
echo $r3[0];
echo $r3[2];
echo "<br />";
$qr3=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r3[0]."','".$r3[2]."')");
}
$q4=mysql_query("select * from ex_data where mark='4' and sub_id='".$sub."' and d_l='".$dl."' order by rand() limit 5");
while($r4=mysql_fetch_array($q4))
{
echo $r4[0];
echo $r4[2];
echo "<br />";
$qr4=mysql_query("insert into temp_ex_data(tmp_sr_no,srno,ex_que_id,tmp_que_str) values (NULL,'".$xx."','".$r4[0]."','".$r4[2]."')");
}
$qry=mysql_query("select tmp_sr_no from temp_ex_data where srno='".$xx."'");
$qrr=mysql_fetch_array($qry);
echo $qrr[0];
echo "<br />";
$_SESSION['min']=1;
$_SESSION['max']=20;
$_SESSION['curr']=$qrr[0];
$_SESSION['qcount']=1;
$_SESSION['exid']=$xx;
$_SESSION['lastmove']=1;
header("location:exampage.php");
}
?> | mit |
Worksite/angular-restsource | karma-e2e.conf.js | 1789 | // Karma configuration
// Generated on Fri Aug 09 2013 09:44:05 GMT-0700 (PDT)
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['ng-scenario'],
// list of files / patterns to load in the browser
files: [
// tests
'test/e2e/**/*.js'
],
// list of files to exclude
exclude: [],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'junit'],
junitReporter: {
outputFile: 'reports/test/e2e-test-results.xml'
},
// web server port
port: 9875,
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 5000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
proxies: {
'/': 'http://localhost:9090/'
}
});
};
| mit |
cuckata23/wurfl-data | data/nokia_111_ver1_subuadot1moz.php | 206 | <?php
return array (
'id' => 'nokia_111_ver1_subuadot1moz',
'fallback' => 'nokia_111_ver1',
'capabilities' =>
array (
'uaprof' => 'http://nds1.nds.nokia.com/uaprof/Nokia111.1r100.xml',
),
);
| mit |
Kanma/Ogre | PlugIns/OctreeSceneManager/src/OgreOctreeNode.cpp | 6846 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2012 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
/***************************************************************************
octreenode.cpp - description
-------------------
begin : Fri Sep 27 2002
copyright : (C) 2002 by Jon Anderson
email : janders@users.sf.net
Enhancements 2003 - 2004 (C) The OGRE Team
***************************************************************************/
#include <OgreRoot.h>
#include <OgreOctreeNode.h>
#include <OgreOctreeSceneManager.h>
namespace Ogre
{
unsigned long green = 0xFFFFFFFF;
unsigned short OctreeNode::mIndexes[ 24 ] = {0, 1, 1, 2, 2, 3, 3, 0, //back
0, 6, 6, 5, 5, 1, //left
3, 7, 7, 4, 4, 2, //right
6, 7, 5, 4 }; //front
unsigned long OctreeNode::mColors[ 8 ] = {green, green, green, green, green, green, green, green };
OctreeNode::OctreeNode( SceneManager* creator ) : SceneNode( creator )
{
mOctant = 0;
}
OctreeNode::OctreeNode( SceneManager* creator, const String& name ) : SceneNode( creator, name )
{
mOctant = 0;
}
OctreeNode::~OctreeNode()
{}
void OctreeNode::_removeNodeAndChildren( )
{
static_cast< OctreeSceneManager * > ( mCreator ) -> _removeOctreeNode( this );
//remove all the children nodes as well from the octree.
ChildNodeMap::iterator it = mChildren.begin();
while( it != mChildren.end() )
{
static_cast<OctreeNode *>( it->second ) -> _removeNodeAndChildren();
++it;
}
}
Node * OctreeNode::removeChild( unsigned short index )
{
OctreeNode *on = static_cast<OctreeNode* >( SceneNode::removeChild( index ) );
on -> _removeNodeAndChildren();
return on;
}
Node * OctreeNode::removeChild( Node* child )
{
OctreeNode *on = static_cast<OctreeNode* >( SceneNode::removeChild( child ) );
on -> _removeNodeAndChildren();
return on;
}
void OctreeNode::removeAllChildren()
{
ChildNodeMap::iterator i, iend;
iend = mChildren.end();
for (i = mChildren.begin(); i != iend; ++i)
{
OctreeNode* on = static_cast<OctreeNode*>(i->second);
on->setParent(0);
on->_removeNodeAndChildren();
}
mChildren.clear();
mChildrenToUpdate.clear();
}
Node * OctreeNode::removeChild( const String & name )
{
OctreeNode *on = static_cast< OctreeNode * >( SceneNode::removeChild( name ) );
on -> _removeNodeAndChildren( );
return on;
}
//same as SceneNode, only it doesn't care about children...
void OctreeNode::_updateBounds( void )
{
mWorldAABB.setNull();
mLocalAABB.setNull();
// Update bounds from own attached objects
ObjectMap::iterator i = mObjectsByName.begin();
AxisAlignedBox bx;
while ( i != mObjectsByName.end() )
{
// Get local bounds of object
bx = i->second ->getBoundingBox();
mLocalAABB.merge( bx );
mWorldAABB.merge( i->second ->getWorldBoundingBox(true) );
++i;
}
//update the OctreeSceneManager that things might have moved.
// if it hasn't been added to the octree, add it, and if has moved
// enough to leave it's current node, we'll update it.
if ( ! mWorldAABB.isNull() && mIsInSceneGraph )
{
static_cast < OctreeSceneManager * > ( mCreator ) -> _updateOctreeNode( this );
}
}
/** Since we are loose, only check the center.
*/
bool OctreeNode::_isIn( AxisAlignedBox &box )
{
// Always fail if not in the scene graph or box is null
if (!mIsInSceneGraph || box.isNull()) return false;
// Always succeed if AABB is infinite
if (box.isInfinite())
return true;
Vector3 center = mWorldAABB.getMaximum().midPoint( mWorldAABB.getMinimum() );
Vector3 bmin = box.getMinimum();
Vector3 bmax = box.getMaximum();
bool centre = ( bmax > center && bmin < center );
if (!centre)
return false;
// Even if covering the centre line, need to make sure this BB is not large
// enough to require being moved up into parent. When added, bboxes would
// end up in parent due to cascade but when updating need to deal with
// bbox growing too large for this child
Vector3 octreeSize = bmax - bmin;
Vector3 nodeSize = mWorldAABB.getMaximum() - mWorldAABB.getMinimum();
return nodeSize < octreeSize;
}
/** Addes the attached objects of this OctreeScene node into the queue. */
void OctreeNode::_addToRenderQueue( Camera* cam, RenderQueue *queue,
bool onlyShadowCasters, VisibleObjectsBoundsInfo* visibleBounds )
{
ObjectMap::iterator mit = mObjectsByName.begin();
while ( mit != mObjectsByName.end() )
{
MovableObject * mo = mit->second;
queue->processVisibleObject(mo, cam, onlyShadowCasters, visibleBounds);
++mit;
}
}
void OctreeNode::getRenderOperation( RenderOperation& rend )
{
/* TODO
rend.useIndexes = true;
rend.numTextureCoordSets = 0; // no textures
rend.vertexOptions = LegacyRenderOperation::VO_DIFFUSE_COLOURS;
rend.operationType = LegacyRenderOperation::OT_LINE_LIST;
rend.numVertices = 8;
rend.numIndexes = 24;
rend.pVertices = mCorners;
rend.pIndexes = mIndexes;
rend.pDiffuseColour = mColors;
const Vector3 * corners = _getLocalAABB().getAllCorners();
int index = 0;
for ( int i = 0; i < 8; i++ )
{
rend.pVertices[ index ] = corners[ i ].x;
index++;
rend.pVertices[ index ] = corners[ i ].y;
index++;
rend.pVertices[ index ] = corners[ i ].z;
index++;
}
*/
}
}
| mit |
erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Request/AlipayMobilePublicAppinfoUpdateRequest.cs | 2571 | using System;
using System.Collections.Generic;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AOP API: alipay.mobile.public.appinfo.update
/// </summary>
public class AlipayMobilePublicAppinfoUpdateRequest : IAopRequest<AlipayMobilePublicAppinfoUpdateResponse>
{
/// <summary>
/// 业务json
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.mobile.public.appinfo.update";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| mit |
eycopia/reporter | application/third_party/reporter/models/Notify_m.php | 941 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Class Notify_m
* @package Reporter\Models
* @author Jorge Copia Silva <eycopia@gmail.com>
* @license https://github.com/eycopia/reporter/blob/master/LICENSE
*/
class Notify_m extends CI_Model {
public function getPeopleToNotifyByReport($idReport){
$sql = "SELECT email FROM notify_report as rn
join notify as n on n.idNotify = rn.idNotify
where rn.idReport = $idReport and n.status = 1";
$rs = $this->db->query($sql);
return $rs->result();
}
/**
* Search by name of email
* @param string $q texto to search
*/
public function search($q){
$sql = "SELECT * FROM notify
WHERE email like '{$q}%' or full_name like '{$q}%'
and status = 1
LIMIT 20";
$query = $this->db->query($sql);
return $query->result();
}
}
| mit |
broodlab/archiveboy | toolbox/configs/eslint/eslint-ts.js | 1007 | module.exports = {
parser: "@typescript-eslint/parser", // Specifies the ESLint parser.
extends: [
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin.
"prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from the @typescript-eslint/eslint-plugin that would otherwise conflict with Prettier.
"plugin:prettier/recommended", // Enables eslint-plugin-prettier and displays Prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features.
sourceType: "module", // Allows for the use of imports.
},
rules: {
"sort-imports": "error",
"@typescript-eslint/explicit-member-accessibility": ["error", {accessibility: "no-public"}],
"@typescript-eslint/explicit-function-return-type": "off",
},
};
| mit |
auth0/auth0-api-java | src/test/java/com/auth0/client/mgmt/ManagementAPITest.java | 19603 | package com.auth0.client.mgmt;
import com.auth0.client.HttpOptions;
import com.auth0.client.MockServer;
import com.auth0.client.ProxyOptions;
import com.auth0.net.RateLimitInterceptor;
import com.auth0.net.Telemetry;
import com.auth0.net.TelemetryInterceptor;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import java.net.Proxy;
import static com.auth0.client.UrlMatcher.isUrl;
import static okhttp3.logging.HttpLoggingInterceptor.Level;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class ManagementAPITest {
private static final String DOMAIN = "domain.auth0.com";
private static final String API_TOKEN = "apiToken";
private MockServer server;
private ManagementAPI api;
@SuppressWarnings("deprecation")
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() throws Exception {
server = new MockServer();
api = new ManagementAPI(server.getBaseUrl(), API_TOKEN);
}
@After
public void tearDown() throws Exception {
server.stop();
}
// Configuration
@Test
public void shouldAcceptDomainWithNoScheme() {
ManagementAPI api = new ManagementAPI("me.something.com", API_TOKEN);
assertThat(api.getBaseUrl(), is(notNullValue()));
assertThat(api.getBaseUrl().toString(), isUrl("https", "me.something.com"));
}
@Test
public void shouldAcceptDomainWithHttpScheme() {
ManagementAPI api = new ManagementAPI("http://me.something.com", API_TOKEN);
assertThat(api.getBaseUrl(), is(notNullValue()));
assertThat(api.getBaseUrl().toString(), isUrl("http", "me.something.com"));
}
@Test
public void shouldThrowWhenDomainIsInvalid() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("The domain had an invalid format and couldn't be parsed as an URL.");
new ManagementAPI("", API_TOKEN);
}
@Test
public void shouldThrowWhenDomainIsNull() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("'domain' cannot be null!");
new ManagementAPI(null, API_TOKEN);
}
@Test
public void shouldThrowWhenApiTokenIsNull() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("'api token' cannot be null!");
new ManagementAPI(DOMAIN, null);
}
@Test
public void shouldThrowOnUpdateWhenApiTokenIsNull() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
exception.expect(IllegalArgumentException.class);
exception.expectMessage("'api token' cannot be null!");
api.setApiToken(null);
}
@Test
public void shouldUpdateApiToken() {
//Initialize with a token
ManagementAPI api = new ManagementAPI(DOMAIN, "first token");
assertThat(api.blacklists().apiToken, is("first token"));
assertThat(api.clientGrants().apiToken, is("first token"));
assertThat(api.clients().apiToken, is("first token"));
assertThat(api.connections().apiToken, is("first token"));
assertThat(api.deviceCredentials().apiToken, is("first token"));
assertThat(api.emailProvider().apiToken, is("first token"));
assertThat(api.emailTemplates().apiToken, is("first token"));
assertThat(api.grants().apiToken, is("first token"));
assertThat(api.guardian().apiToken, is("first token"));
assertThat(api.jobs().apiToken, is("first token"));
assertThat(api.logEvents().apiToken, is("first token"));
assertThat(api.resourceServers().apiToken, is("first token"));
assertThat(api.rules().apiToken, is("first token"));
assertThat(api.stats().apiToken, is("first token"));
assertThat(api.tenants().apiToken, is("first token"));
assertThat(api.tickets().apiToken, is("first token"));
assertThat(api.userBlocks().apiToken, is("first token"));
assertThat(api.users().apiToken, is("first token"));
//Update the token
api.setApiToken("new token");
assertThat(api.blacklists().apiToken, is("new token"));
assertThat(api.clientGrants().apiToken, is("new token"));
assertThat(api.clients().apiToken, is("new token"));
assertThat(api.connections().apiToken, is("new token"));
assertThat(api.deviceCredentials().apiToken, is("new token"));
assertThat(api.emailProvider().apiToken, is("new token"));
assertThat(api.emailTemplates().apiToken, is("new token"));
assertThat(api.grants().apiToken, is("new token"));
assertThat(api.guardian().apiToken, is("new token"));
assertThat(api.jobs().apiToken, is("new token"));
assertThat(api.logEvents().apiToken, is("new token"));
assertThat(api.resourceServers().apiToken, is("new token"));
assertThat(api.rules().apiToken, is("new token"));
assertThat(api.stats().apiToken, is("new token"));
assertThat(api.tenants().apiToken, is("new token"));
assertThat(api.tickets().apiToken, is("new token"));
assertThat(api.userBlocks().apiToken, is("new token"));
assertThat(api.users().apiToken, is("new token"));
}
@Test
public void shouldUseDefaultTimeoutIfNotSpecified() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().connectTimeoutMillis(), is(10 * 1000));
assertThat(api.getClient().readTimeoutMillis(), is(10 * 1000));
}
@Test
public void shouldUseZeroIfNegativeTimeoutConfigured() {
HttpOptions options = new HttpOptions();
options.setConnectTimeout(-1);
options.setReadTimeout(-1);
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN, options);
assertThat(api.getClient().connectTimeoutMillis(), is(0));
assertThat(api.getClient().readTimeoutMillis(), is(0));
}
@Test
public void shouldSetTimeoutsIfConfigured() {
HttpOptions options = new HttpOptions();
options.setConnectTimeout(20);
options.setReadTimeout(30);
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN, options);
assertThat(api.getClient().connectTimeoutMillis(), is(20 * 1000));
assertThat(api.getClient().readTimeoutMillis(), is(30 * 1000));
}
@Test
public void shouldNotUseProxyByDefault() throws Exception {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().proxy(), is(nullValue()));
Authenticator authenticator = api.getClient().proxyAuthenticator();
assertThat(authenticator, is(notNullValue()));
Route route = Mockito.mock(Route.class);
okhttp3.Request nonAuthenticatedRequest = new okhttp3.Request.Builder()
.url("https://test.com/app")
.addHeader("some-header", "some-value")
.build();
okhttp3.Response nonAuthenticatedResponse = new okhttp3.Response.Builder()
.protocol(Protocol.HTTP_2)
.code(200)
.message("OK")
.request(nonAuthenticatedRequest)
.build();
okhttp3.Request processedRequest = authenticator.authenticate(route, nonAuthenticatedResponse);
assertThat(processedRequest, is(nullValue()));
}
@Test
public void shouldUseProxy() throws Exception {
Proxy proxy = Mockito.mock(Proxy.class);
ProxyOptions proxyOptions = new ProxyOptions(proxy);
HttpOptions httpOptions = new HttpOptions();
httpOptions.setProxyOptions(proxyOptions);
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN, httpOptions);
assertThat(api.getClient().proxy(), is(proxy));
Authenticator authenticator = api.getClient().proxyAuthenticator();
assertThat(authenticator, is(notNullValue()));
Route route = Mockito.mock(Route.class);
okhttp3.Request nonAuthenticatedRequest = new okhttp3.Request.Builder()
.url("https://test.com/app")
.addHeader("some-header", "some-value")
.build();
okhttp3.Response nonAuthenticatedResponse = new okhttp3.Response.Builder()
.protocol(Protocol.HTTP_2)
.code(200)
.message("OK")
.request(nonAuthenticatedRequest)
.build();
okhttp3.Request processedRequest = authenticator.authenticate(route, nonAuthenticatedResponse);
assertThat(processedRequest, is(nullValue()));
}
@Test
public void shouldUseProxyWithAuthentication() throws Exception {
Proxy proxy = Mockito.mock(Proxy.class);
ProxyOptions proxyOptions = new ProxyOptions(proxy);
proxyOptions.setBasicAuthentication("johndoe", "psswd".toCharArray());
assertThat(proxyOptions.getBasicAuthentication(), is("Basic am9obmRvZTpwc3N3ZA=="));
HttpOptions httpOptions = new HttpOptions();
httpOptions.setProxyOptions(proxyOptions);
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN, httpOptions);
assertThat(api.getClient().proxy(), is(proxy));
Authenticator authenticator = api.getClient().proxyAuthenticator();
assertThat(authenticator, is(notNullValue()));
Route route = Mockito.mock(Route.class);
okhttp3.Request nonAuthenticatedRequest = new okhttp3.Request.Builder()
.url("https://test.com/app")
.addHeader("some-header", "some-value")
.build();
okhttp3.Response nonAuthenticatedResponse = new okhttp3.Response.Builder()
.protocol(Protocol.HTTP_2)
.code(200)
.message("OK")
.request(nonAuthenticatedRequest)
.build();
okhttp3.Request processedRequest = authenticator.authenticate(route, nonAuthenticatedResponse);
assertThat(processedRequest, is(notNullValue()));
assertThat(processedRequest.url(), is(HttpUrl.parse("https://test.com/app")));
assertThat(processedRequest.header("Proxy-Authorization"), is(proxyOptions.getBasicAuthentication()));
assertThat(processedRequest.header("some-header"), is("some-value"));
}
@Test
public void proxyShouldNotProcessAlreadyAuthenticatedRequest() throws Exception {
Proxy proxy = Mockito.mock(Proxy.class);
ProxyOptions proxyOptions = new ProxyOptions(proxy);
proxyOptions.setBasicAuthentication("johndoe", "psswd".toCharArray());
assertThat(proxyOptions.getBasicAuthentication(), is("Basic am9obmRvZTpwc3N3ZA=="));
HttpOptions httpOptions = new HttpOptions();
httpOptions.setProxyOptions(proxyOptions);
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN, httpOptions);
assertThat(api.getClient().proxy(), is(proxy));
Authenticator authenticator = api.getClient().proxyAuthenticator();
assertThat(authenticator, is(notNullValue()));
Route route = Mockito.mock(Route.class);
okhttp3.Request alreadyAuthenticatedRequest = new okhttp3.Request.Builder()
.url("https://test.com/app")
.addHeader("some-header", "some-value")
.header("Proxy-Authorization", "pre-existing-value")
.build();
okhttp3.Response alreadyAuthenticatedResponse = new okhttp3.Response.Builder()
.protocol(Protocol.HTTP_2)
.code(200)
.message("OK")
.request(alreadyAuthenticatedRequest)
.build();
okhttp3.Request processedRequest = authenticator.authenticate(route, alreadyAuthenticatedResponse);
assertThat(processedRequest, is(nullValue()));
}
@Test
public void shouldAddAndEnableTelemetryInterceptor() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(TelemetryInterceptor.class)));
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof TelemetryInterceptor) {
TelemetryInterceptor telemetry = (TelemetryInterceptor) i;
assertThat(telemetry.isEnabled(), is(true));
}
}
}
@Test
public void shouldUseCustomTelemetry() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(TelemetryInterceptor.class)));
Telemetry currentTelemetry = null;
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof TelemetryInterceptor) {
TelemetryInterceptor interceptor = (TelemetryInterceptor) i;
currentTelemetry = interceptor.getTelemetry();
}
}
assertThat(currentTelemetry, is(notNullValue()));
Telemetry newTelemetry = Mockito.mock(Telemetry.class);
api.setTelemetry(newTelemetry);
Telemetry updatedTelemetry = null;
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof TelemetryInterceptor) {
TelemetryInterceptor interceptor = (TelemetryInterceptor) i;
updatedTelemetry = interceptor.getTelemetry();
}
}
assertThat(updatedTelemetry, is(newTelemetry));
}
@Test
public void shouldDisableTelemetryInterceptor() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(TelemetryInterceptor.class)));
api.doNotSendTelemetry();
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof TelemetryInterceptor) {
TelemetryInterceptor telemetry = (TelemetryInterceptor) i;
assertThat(telemetry.isEnabled(), is(false));
}
}
}
@Test
public void shouldAddAndDisableLoggingInterceptor() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(HttpLoggingInterceptor.class)));
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof HttpLoggingInterceptor) {
HttpLoggingInterceptor logging = (HttpLoggingInterceptor) i;
assertThat(logging.getLevel(), is(Level.NONE));
}
}
}
@Test
public void shouldEnableLoggingInterceptor() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(HttpLoggingInterceptor.class)));
api.setLoggingEnabled(true);
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof HttpLoggingInterceptor) {
HttpLoggingInterceptor logging = (HttpLoggingInterceptor) i;
assertThat(logging.getLevel(), is(Level.BODY));
}
}
}
@Test
public void shouldDisableLoggingInterceptor() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(HttpLoggingInterceptor.class)));
api.setLoggingEnabled(false);
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof HttpLoggingInterceptor) {
HttpLoggingInterceptor logging = (HttpLoggingInterceptor) i;
assertThat(logging.getLevel(), is(Level.NONE));
}
}
}
@Test
public void shouldUseDefaultMaxRetriesIfNotConfigured() {
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN);
assertThat(api.getClient().interceptors(), hasItem(isA(RateLimitInterceptor.class)));
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof RateLimitInterceptor) {
RateLimitInterceptor rateLimitInterceptor = (RateLimitInterceptor) i;
assertThat(rateLimitInterceptor.getMaxRetries(), is(3));
}
}
}
@Test
public void shouldUseCustomMaxRetriesIfConfigured() {
HttpOptions options = new HttpOptions();
options.setManagementAPIMaxRetries(5);
ManagementAPI api = new ManagementAPI(DOMAIN, API_TOKEN, options);
assertThat(api.getClient().interceptors(), hasItem(isA(RateLimitInterceptor.class)));
for (Interceptor i : api.getClient().interceptors()) {
if (i instanceof RateLimitInterceptor) {
RateLimitInterceptor rateLimitInterceptor = (RateLimitInterceptor) i;
assertThat(rateLimitInterceptor.getMaxRetries(), is(5));
}
}
}
@Test
public void shouldThrowOnNegativeMaxRetriesConfiguration() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Retries must be between zero and ten.");
HttpOptions options = new HttpOptions();
options.setManagementAPIMaxRetries(-1);
}
@Test
public void shouldThrowOnTooManyMaxRetriesConfiguration() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Retries must be between zero and ten.");
HttpOptions options = new HttpOptions();
options.setManagementAPIMaxRetries(11);
}
//Entities
@Test
public void shouldGetBlacklists() {
assertThat(api.blacklists(), notNullValue());
}
@Test
public void shouldGetClientGrants() {
assertThat(api.clientGrants(), notNullValue());
}
@Test
public void shouldGetClients() {
assertThat(api.clients(), notNullValue());
}
@Test
public void shouldGetConnections() {
assertThat(api.connections(), notNullValue());
}
@Test
public void shouldGetDeviceCredentials() {
assertThat(api.deviceCredentials(), notNullValue());
}
@Test
public void shouldGetEmailProvider() {
assertThat(api.emailProvider(), notNullValue());
}
@Test
public void shouldGetEmailTemplates() {
assertThat(api.emailTemplates(), notNullValue());
}
@Test
public void shouldGetGrants() {
assertThat(api.grants(), notNullValue());
}
@Test
public void shouldGetGuardian() {
assertThat(api.guardian(), notNullValue());
}
@Test
public void shouldGetJobs() {
assertThat(api.jobs(), notNullValue());
}
@Test
public void shouldGetLogEvents() {
assertThat(api.logEvents(), notNullValue());
}
@Test
public void shouldGetResourceServers() {
assertThat(api.resourceServers(), notNullValue());
}
@Test
public void shouldGetRules() {
assertThat(api.rules(), notNullValue());
}
@Test
public void shouldGetStats() {
assertThat(api.stats(), notNullValue());
}
@Test
public void shouldGetTenants() {
assertThat(api.tenants(), notNullValue());
}
@Test
public void shouldGetTickets() {
assertThat(api.tickets(), notNullValue());
}
@Test
public void shouldGetUserBlocks() {
assertThat(api.userBlocks(), notNullValue());
}
@Test
public void shouldGetUsers() {
assertThat(api.users(), notNullValue());
}
}
| mit |
superarts/supply | lib/supply/options.rb | 5989 | require 'fastlane_core'
require 'credentials_manager'
module Supply
class Options
def self.available_options
@options ||= [
FastlaneCore::ConfigItem.new(key: :package_name,
env_name: "SUPPLY_PACKAGE_NAME",
short_option: "-p",
description: "The package name of the Application to modify",
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:package_name)),
FastlaneCore::ConfigItem.new(key: :track,
short_option: "-a",
env_name: "SUPPLY_TRACK",
description: "The Track to upload the Application to: production, beta, alpha or rollout",
default_value: 'production',
verify_block: proc do |value|
available = %w(production beta alpha rollout)
raise "Invalid value '#{value}', must be #{available.join(', ')}".red unless available.include? value
end),
FastlaneCore::ConfigItem.new(key: :rollout,
short_option: "-r",
description: "The percentage of the rollout",
default_value: '1.0',
verify_block: proc do |value|
available = %w(0.005 0.01 0.05 0.1 0.2 0.5 1.0)
raise "Invalid value '#{value}', must be #{available.join(', ')}".red unless available.include? value
end),
FastlaneCore::ConfigItem.new(key: :metadata_path,
env_name: "SUPPLY_METADATA_PATH",
short_option: "-m",
optional: true,
description: "Path to the directory containing the metadata files",
default_value: (Dir["./fastlane/metadata/android"] + Dir["./metadata"]).first,
verify_block: proc do |value|
raise "Could not find folder".red unless File.directory? value
end),
FastlaneCore::ConfigItem.new(key: :key,
env_name: "SUPPLY_KEY",
short_option: "-k",
description: "The p12 File used to authenticate with Google",
default_value: Dir["*.p12"].first || CredentialsManager::AppfileConfig.try_fetch_value(:keyfile),
verify_block: proc do |value|
raise "Could not find p12 file at path '#{File.expand_path(value)}'".red unless File.exist?(File.expand_path(value))
end),
FastlaneCore::ConfigItem.new(key: :issuer,
short_option: "-i",
env_name: "SUPPLY_ISSUER",
description: "The issuer of the p12 file (email address of the service account)",
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:issuer)),
FastlaneCore::ConfigItem.new(key: :apk,
env_name: "SUPPLY_APK",
description: "Path to the APK file to upload",
short_option: "-b",
default_value: Dir["*.apk"].last || Dir[File.join("app", "build", "outputs", "apk", "app-Release.apk")].last,
optional: true,
verify_block: proc do |value|
raise "Could not find apk file at path '#{value}'".red unless File.exist?(value)
raise "apk file is not an apk".red unless value.end_with?(value)
end),
FastlaneCore::ConfigItem.new(key: :skip_upload_apk,
env_name: "SUPPLY_SKIP_UPLOAD_APK",
optional: true,
description: "Whether to skip uploading APK",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_upload_metadata,
env_name: "SUPPLY_SKIP_UPLOAD_METADATA",
optional: true,
description: "Whether to skip uploading metadata",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_upload_images,
env_name: "SUPPLY_SKIP_UPLOAD_IMAGES",
optional: true,
description: "Whether to skip uploading images, screenshots not included",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_upload_screenshots,
env_name: "SUPPLY_SKIP_UPLOAD_SCREENSHOTS",
optional: true,
description: "Whether to skip uploading SCREENSHOTS",
is_string: false,
default_value: false)
]
end
end
end
| mit |
CyclopsMC/IntegratedDynamics | src/main/java/org/cyclops/integrateddynamics/infobook/pageelement/MechanicalDryingBasinRecipeAppendix.java | 845 | package org.cyclops.integrateddynamics.infobook.pageelement;
import net.minecraft.item.ItemStack;
import org.cyclops.cyclopscore.infobook.IInfoBook;
import org.cyclops.integrateddynamics.RegistryEntries;
import org.cyclops.integrateddynamics.core.recipe.type.RecipeMechanicalDryingBasin;
/**
* Mechanical drying basin recipes.
* @author rubensworks
*/
public class MechanicalDryingBasinRecipeAppendix extends DryingBasinRecipeAppendix {
public MechanicalDryingBasinRecipeAppendix(IInfoBook infoBook, RecipeMechanicalDryingBasin recipe) {
super(infoBook, recipe);
}
@Override
protected String getUnlocalizedTitle() {
return "block.integrateddynamics.mechanical_drying_basin";
}
protected ItemStack getCrafter() {
return new ItemStack(RegistryEntries.BLOCK_MECHANICAL_DRYING_BASIN);
}
}
| mit |
hiltongoncalves/PHPMyScrum | cake/libs/model/datasources/dbo_source.php | 84825 | <?php
/**
* Short description for file.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.model.datasources
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Set', 'String'));
/**
* DboSource
*
* Creates DBO-descendant objects from a given db connection configuration
*
* @package cake
* @subpackage cake.cake.libs.model.datasources
*/
class DboSource extends DataSource {
/**
* Description string for this Database Data Source.
*
* @var string
* @access public
*/
var $description = "Database Data Source";
/**
* index definition, standard cake, primary, index, unique
*
* @var array
*/
var $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
/**
* Database keyword used to assign aliases to identifiers.
*
* @var string
* @access public
*/
var $alias = 'AS ';
/**
* Caches result from query parsing operations
*
* @var array
* @access public
*/
var $methodCache = array();
/**
* Whether or not to cache the results of DboSource::name() and DboSource::conditions()
* into the memory cache. Set to false to disable the use of the memory cache.
*
* @var boolean.
* @access public
*/
var $cacheMethods = true ;
/**
* Bypass automatic adding of joined fields/associations.
*
* @var boolean
* @access private
*/
var $__bypass = false;
/**
* The set of valid SQL operations usable in a WHERE statement
*
* @var array
* @access private
*/
var $__sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
/**
* Index of basic SQL commands
*
* @var array
* @access protected
*/
var $_commands = array(
'begin' => 'BEGIN',
'commit' => 'COMMIT',
'rollback' => 'ROLLBACK'
);
/**
* List of table engine specific parameters used on table creating
*
* @var array
* @access public
*/
var $tableParameters = array();
/**
* List of engine specific additional field parameters used on table creating
*
* @var array
* @access public
*/
var $fieldParameters = array();
/**
* Constructor
*
* @param array $config Array of configuration information for the Datasource.
* @param boolean $autoConnect Whether or not the datasource should automatically connect.
* @access public
*/
function __construct($config = null, $autoConnect = true) {
if (!isset($config['prefix'])) {
$config['prefix'] = '';
}
parent::__construct($config);
$this->fullDebug = Configure::read() > 1;
if (!$this->enabled()) {
return false;
}
if ($autoConnect) {
return $this->connect();
} else {
return true;
}
}
/**
* Reconnects to database server with optional new settings
*
* @param array $config An array defining the new configuration settings
* @return boolean True on success, false on failure
* @access public
*/
function reconnect($config = null) {
$this->disconnect();
$this->setConfig($config);
$this->_sources = null;
return $this->connect();
}
/**
* Prepares a value, or an array of values for database queries by quoting and escaping them.
*
* @param mixed $data A value or an array of values to prepare.
* @param string $column The column into which this data will be inserted
* @param boolean $read Value to be used in READ or WRITE context
* @return mixed Prepared value or array of values.
* @access public
*/
function value($data, $column = null, $read = true) {
if (is_array($data) && !empty($data)) {
return array_map(
array(&$this, 'value'),
$data, array_fill(0, count($data), $column), array_fill(0, count($data), $read)
);
} elseif (is_object($data) && isset($data->type)) {
if ($data->type == 'identifier') {
return $this->name($data->value);
} elseif ($data->type == 'expression') {
return $data->value;
}
} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
return $data;
} else {
return null;
}
}
/**
* Returns an object to represent a database identifier in a query
*
* @param string $identifier
* @return object An object representing a database identifier to be used in a query
* @access public
*/
function identifier($identifier) {
$obj = new stdClass();
$obj->type = 'identifier';
$obj->value = $identifier;
return $obj;
}
/**
* Returns an object to represent a database expression in a query
*
* @param string $expression
* @return object An object representing a database expression to be used in a query
* @access public
*/
function expression($expression) {
$obj = new stdClass();
$obj->type = 'expression';
$obj->value = $expression;
return $obj;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return boolean
* @access public
*/
function rawQuery($sql) {
$this->took = $this->error = $this->numRows = false;
return $this->execute($sql);
}
/**
* Queries the database with given SQL statement, and obtains some metadata about the result
* (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
* If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
*
* ### Options
*
* - stats - Collect meta data stats for this query. Stats include time take, rows affected,
* any errors, and number of rows returned. Defaults to `true`.
* - log - Whether or not the query should be logged to the memory log.
*
* @param string $sql
* @param array $options
* @return mixed Resource or object representing the result set, or false on failure
* @access public
*/
function execute($sql, $options = array()) {
$defaults = array('stats' => true, 'log' => $this->fullDebug);
$options = array_merge($defaults, $options);
$t = getMicrotime();
$this->_result = $this->_execute($sql);
if ($options['stats']) {
$this->took = round((getMicrotime() - $t) * 1000, 0);
$this->affected = $this->lastAffected();
$this->error = $this->lastError();
$this->numRows = $this->lastNumRows();
}
if ($options['log']) {
$this->logQuery($sql);
}
if ($this->error) {
$this->showQuery($sql);
return false;
}
return $this->_result;
}
/**
* DataSource Query abstraction
*
* @return resource Result resource identifier.
* @access public
*/
function query() {
$args = func_get_args();
$fields = null;
$order = null;
$limit = null;
$page = null;
$recursive = null;
if (count($args) == 1) {
return $this->fetchAll($args[0]);
} elseif (count($args) > 1 && (strpos(strtolower($args[0]), 'findby') === 0 || strpos(strtolower($args[0]), 'findallby') === 0)) {
$params = $args[1];
if (strpos(strtolower($args[0]), 'findby') === 0) {
$all = false;
$field = Inflector::underscore(preg_replace('/^findBy/i', '', $args[0]));
} else {
$all = true;
$field = Inflector::underscore(preg_replace('/^findAllBy/i', '', $args[0]));
}
$or = (strpos($field, '_or_') !== false);
if ($or) {
$field = explode('_or_', $field);
} else {
$field = explode('_and_', $field);
}
$off = count($field) - 1;
if (isset($params[1 + $off])) {
$fields = $params[1 + $off];
}
if (isset($params[2 + $off])) {
$order = $params[2 + $off];
}
if (!array_key_exists(0, $params)) {
return false;
}
$c = 0;
$conditions = array();
foreach ($field as $f) {
$conditions[$args[2]->alias . '.' . $f] = $params[$c];
$c++;
}
if ($or) {
$conditions = array('OR' => $conditions);
}
if ($all) {
if (isset($params[3 + $off])) {
$limit = $params[3 + $off];
}
if (isset($params[4 + $off])) {
$page = $params[4 + $off];
}
if (isset($params[5 + $off])) {
$recursive = $params[5 + $off];
}
return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
} else {
if (isset($params[3 + $off])) {
$recursive = $params[3 + $off];
}
return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
}
} else {
if (isset($args[1]) && $args[1] === true) {
return $this->fetchAll($args[0], true);
} else if (isset($args[1]) && !is_array($args[1]) ) {
return $this->fetchAll($args[0], false);
} else if (isset($args[1]) && is_array($args[1])) {
$offset = 0;
if (isset($args[2])) {
$cache = $args[2];
} else {
$cache = true;
}
$args[1] = array_map(array(&$this, 'value'), $args[1]);
return $this->fetchAll(String::insert($args[0], $args[1]), $cache);
}
}
}
/**
* Returns a row from current resultset as an array
*
* @return array The fetched row as an array
* @access public
*/
function fetchRow($sql = null) {
if (!empty($sql) && is_string($sql) && strlen($sql) > 5) {
if (!$this->execute($sql)) {
return null;
}
}
if ($this->hasResult()) {
$this->resultSet($this->_result);
$resultRow = $this->fetchResult();
if (!empty($resultRow)) {
$this->fetchVirtualField($resultRow);
}
return $resultRow;
} else {
return null;
}
}
/**
* Returns an array of all result rows for a given SQL query.
* Returns false if no rows matched.
*
* @param string $sql SQL statement
* @param boolean $cache Enables returning/storing cached query results
* @return array Array of resultset rows, or false if no rows matched
* @access public
*/
function fetchAll($sql, $cache = true, $modelName = null) {
if ($cache && isset($this->_queryCache[$sql])) {
if (preg_match('/^\s*select/i', $sql)) {
return $this->_queryCache[$sql];
}
}
if ($this->execute($sql)) {
$out = array();
$first = $this->fetchRow();
if ($first != null) {
$out[] = $first;
}
while ($this->hasResult() && $item = $this->fetchResult()) {
$this->fetchVirtualField($item);
$out[] = $item;
}
if ($cache) {
if (strpos(trim(strtolower($sql)), 'select') !== false) {
$this->_queryCache[$sql] = $out;
}
}
if (empty($out) && is_bool($this->_result)) {
return $this->_result;
}
return $out;
} else {
return false;
}
}
/**
* Modifies $result array to place virtual fields in model entry where they belongs to
*
* @param array $resut REference to the fetched row
* @return void
*/
function fetchVirtualField(&$result) {
if (isset($result[0]) && is_array($result[0])) {
foreach ($result[0] as $field => $value) {
if (strpos($field, '__') === false) {
continue;
}
list($alias, $virtual) = explode('__', $field);
if (!ClassRegistry::isKeySet($alias)) {
return;
}
$model = ClassRegistry::getObject($alias);
if ($model->isVirtualField($virtual)) {
$result[$alias][$virtual] = $value;
unset($result[0][$field]);
}
}
if (empty($result[0])) {
unset($result[0]);
}
}
}
/**
* Returns a single field of the first of query results for a given SQL query, or false if empty.
*
* @param string $name Name of the field
* @param string $sql SQL query
* @return mixed Value of field read.
* @access public
*/
function field($name, $sql) {
$data = $this->fetchRow($sql);
if (!isset($data[$name]) || empty($data[$name])) {
return false;
} else {
return $data[$name];
}
}
/**
* Empties the method caches.
* These caches are used by DboSource::name() and DboSource::conditions()
*
* @return void
*/
function flushMethodCache() {
$this->methodCache = array();
}
/**
* Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
* Will retrieve a value from the cache if $value is null.
*
* If caching is disabled and a write is attempted, the $value will be returned.
* A read will either return the value or null.
*
* @param string $method Name of the method being cached.
* @param string $key The keyname for the cache operation.
* @param mixed $value The value to cache into memory.
* @return mixed Either null on failure, or the value if its set.
*/
function cacheMethod($method, $key, $value = null) {
if ($this->cacheMethods === false) {
if ($value !== null) {
return $value;
}
return null;
}
if ($value === null) {
return (isset($this->methodCache[$method][$key])) ? $this->methodCache[$method][$key] : null;
}
return $this->methodCache[$method][$key] = $value;
}
/**
* Returns a quoted name of $data for use in an SQL statement.
* Strips fields out of SQL functions before quoting.
*
* @param string $data
* @return string SQL field
* @access public
*/
function name($data) {
if (is_object($data) && isset($data->type)) {
return $data->value;
}
if ($data === '*') {
return '*';
}
if (is_array($data)) {
foreach ($data as $i => $dataItem) {
$data[$i] = $this->name($dataItem);
}
return $data;
}
$cacheKey = crc32($this->startQuote.$data.$this->endQuote);
if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
return $return;
}
$data = trim($data);
if (preg_match('/^[\w-]+(\.[\w-]+)*$/', $data)) { // string, string.string
if (strpos($data, '.') === false) { // string
return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
}
$items = explode('.', $data);
return $this->cacheMethod(__FUNCTION__, $cacheKey,
$this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
);
}
if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
return $this->cacheMethod(__FUNCTION__, $cacheKey,
$this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
);
}
if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
return $this->cacheMethod(__FUNCTION__, $cacheKey,
$matches[1] . '(' . $this->name($matches[2]) . ')'
);
}
if (
preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/', $data, $matches
)) {
return $this->cacheMethod(
__FUNCTION__, $cacheKey,
preg_replace(
'/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
)
);
}
return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
}
/**
* Checks if the source is connected to the database.
*
* @return boolean True if the database is connected, else false
* @access public
*/
function isConnected() {
return $this->connected;
}
/**
* Checks if the result is valid
*
* @return boolean True if the result is valid else false
* @access public
*/
function hasResult() {
return is_resource($this->_result);
}
/**
* Get the query log as an array.
*
* @param boolean $sorted Get the queries sorted by time taken, defaults to false.
* @return array Array of queries run as an array
* @access public
*/
function getLog($sorted = false, $clear = true) {
if ($sorted) {
$log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
} else {
$log = $this->_queriesLog;
}
if ($clear) {
$this->_queriesLog = array();
}
return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
}
/**
* Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
* will be rendered and output. If in a CLI environment, a plain text log is generated.
*
* @param boolean $sorted Get the queries sorted by time taken, defaults to false.
* @return void
*/
function showLog($sorted = false) {
$log = $this->getLog($sorted, false);
if (empty($log['log'])) {
return;
}
if (PHP_SAPI != 'cli') {
App::import('Core', 'View');
$controller = null;
$View =& new View($controller, false);
$View->set('logs', array($this->configKeyName => $log));
echo $View->element('sql_dump');
} else {
foreach ($log['log'] as $k => $i) {
print (($k + 1) . ". {$i['query']} {$i['error']}\n");
}
}
}
/**
* Log given SQL query.
*
* @param string $sql SQL statement
* @todo: Add hook to log errors instead of returning false
* @access public
*/
function logQuery($sql) {
$this->_queriesCnt++;
$this->_queriesTime += $this->took;
$this->_queriesLog[] = array(
'query' => $sql,
'error' => $this->error,
'affected' => $this->affected,
'numRows' => $this->numRows,
'took' => $this->took
);
if (count($this->_queriesLog) > $this->_queriesLogMax) {
array_pop($this->_queriesLog);
}
if ($this->error) {
return false;
}
}
/**
* Output information about an SQL query. The SQL statement, number of rows in resultset,
* and execution time in microseconds. If the query fails, an error is output instead.
*
* @param string $sql Query to show information on.
* @access public
*/
function showQuery($sql) {
$error = $this->error;
if (strlen($sql) > 200 && !$this->fullDebug && Configure::read() > 1) {
$sql = substr($sql, 0, 200) . '[...]';
}
if (Configure::read() > 0) {
$out = null;
if ($error) {
trigger_error('<span style="color:Red;text-align:left"><b>' . __('SQL Error:', true) . "</b> {$this->error}</span>", E_USER_WARNING);
} else {
$out = ('<small>[' . sprintf(__('Aff:%s Num:%s Took:%sms', true), $this->affected, $this->numRows, $this->took) . ']</small>');
}
pr(sprintf('<p style="text-align:left"><b>' . __('Query:', true) . '</b> %s %s</p>', $sql, $out));
}
}
/**
* Gets full table name including prefix
*
* @param mixed $model Either a Model object or a string table name.
* @param boolean $quote Whether you want the table name quoted.
* @return string Full quoted table name
* @access public
*/
function fullTableName($model, $quote = true) {
if (is_object($model)) {
$table = $model->tablePrefix . $model->table;
} elseif (isset($this->config['prefix'])) {
$table = $this->config['prefix'] . strval($model);
} else {
$table = strval($model);
}
if ($quote) {
return $this->name($table);
}
return $table;
}
/**
* The "C" in CRUD
*
* Creates new records in the database.
*
* @param Model $model Model object that the record is for.
* @param array $fields An array of field names to insert. If null, $model->data will be
* used to generate field names.
* @param array $values An array of values with keys matching the fields. If null, $model->data will
* be used to generate values.
* @return boolean Success
* @access public
*/
function create(&$model, $fields = null, $values = null) {
$id = null;
if ($fields == null) {
unset($fields, $values);
$fields = array_keys($model->data);
$values = array_values($model->data);
}
$count = count($fields);
for ($i = 0; $i < $count; $i++) {
$valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]), false);
}
for ($i = 0; $i < $count; $i++) {
$fieldInsert[] = $this->name($fields[$i]);
if ($fields[$i] == $model->primaryKey) {
$id = $values[$i];
}
}
$query = array(
'table' => $this->fullTableName($model),
'fields' => implode(', ', $fieldInsert),
'values' => implode(', ', $valueInsert)
);
if ($this->execute($this->renderStatement('create', $query))) {
if (empty($id)) {
$id = $this->lastInsertId($this->fullTableName($model, false), $model->primaryKey);
}
$model->setInsertID($id);
$model->id = $id;
return true;
} else {
$model->onError();
return false;
}
}
/**
* The "R" in CRUD
*
* Reads record(s) from the database.
*
* @param Model $model A Model object that the query is for.
* @param array $queryData An array of queryData information containing keys similar to Model::find()
* @param integer $recursive Number of levels of association
* @return mixed boolean false on error/failure. An array of results on success.
*/
function read(&$model, $queryData = array(), $recursive = null) {
$queryData = $this->__scrubQueryData($queryData);
$null = null;
$array = array();
$linkedModels = array();
$this->__bypass = false;
$this->__booleans = array();
if ($recursive === null && isset($queryData['recursive'])) {
$recursive = $queryData['recursive'];
}
if (!is_null($recursive)) {
$_recursive = $model->recursive;
$model->recursive = $recursive;
}
if (!empty($queryData['fields'])) {
$this->__bypass = true;
$queryData['fields'] = $this->fields($model, null, $queryData['fields']);
} else {
$queryData['fields'] = $this->fields($model);
}
$_associations = $model->__associations;
if ($model->recursive == -1) {
$_associations = array();
} else if ($model->recursive == 0) {
unset($_associations[2], $_associations[3]);
}
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
$external = isset($assocData['external']);
if ($model->useDbConfig == $linkModel->useDbConfig) {
if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
$linkedModels[$type . '/' . $assoc] = true;
}
}
}
}
$query = $this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null);
$resultSet = $this->fetchAll($query, $model->cacheQueries, $model->alias);
if ($resultSet === false) {
$model->onError();
return false;
}
$filtered = $this->__filterResults($resultSet, $model);
if ($model->recursive > -1) {
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
if (empty($linkedModels[$type . '/' . $assoc])) {
if ($model->useDbConfig == $linkModel->useDbConfig) {
$db =& $this;
} else {
$db =& ConnectionManager::getDataSource($linkModel->useDbConfig);
}
} elseif ($model->recursive > 1 && ($type == 'belongsTo' || $type == 'hasOne')) {
$db =& $this;
}
if (isset($db)) {
$stack = array($assoc);
$db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
unset($db);
}
}
}
$this->__filterResults($resultSet, $model, $filtered);
}
if (!is_null($recursive)) {
$model->recursive = $_recursive;
}
return $resultSet;
}
/**
* Passes association results thru afterFind filters of corresponding model
*
* @param array $results Reference of resultset to be filtered
* @param object $model Instance of model to operate against
* @param array $filtered List of classes already filtered, to be skipped
* @return array Array of results that have been filtered through $model->afterFind
* @access private
*/
function __filterResults(&$results, &$model, $filtered = array()) {
$filtering = array();
$count = count($results);
for ($i = 0; $i < $count; $i++) {
if (is_array($results[$i])) {
$classNames = array_keys($results[$i]);
$count2 = count($classNames);
for ($j = 0; $j < $count2; $j++) {
$className = $classNames[$j];
if ($model->alias != $className && !in_array($className, $filtered)) {
if (!in_array($className, $filtering)) {
$filtering[] = $className;
}
if (isset($model->{$className}) && is_object($model->{$className})) {
$data = $model->{$className}->afterFind(array(array($className => $results[$i][$className])), false);
}
if (isset($data[0][$className])) {
$results[$i][$className] = $data[0][$className];
}
}
}
}
}
return $filtering;
}
/**
* Queries associations. Used to fetch results on recursive models.
*
* @param Model $model Primary Model object
* @param Model $linkModel Linked model that
* @param string $type Association type, one of the model association types ie. hasMany
* @param unknown_type $association
* @param unknown_type $assocData
* @param array $queryData
* @param boolean $external Whether or not the association query is on an external datasource.
* @param array $resultSet Existing results
* @param integer $recursive Number of levels of association
* @param array $stack
*/
function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
if (!isset($resultSet) || !is_array($resultSet)) {
if (Configure::read() > 0) {
echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' ';
if (isset($this->error) && $this->error != null) {
echo $this->error;
}
echo '</div>';
}
return null;
}
$count = count($resultSet);
if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
$ins = $fetch = array();
for ($i = 0; $i < $count; $i++) {
if ($in = $this->insertQueryData('{$__cakeID__$}', $resultSet[$i], $association, $assocData, $model, $linkModel, $stack)) {
$ins[] = $in;
}
}
if (!empty($ins)) {
$fetch = $this->fetchAssociated($model, $query, $ins);
}
if (!empty($fetch) && is_array($fetch)) {
if ($recursive > 0) {
foreach ($linkModel->__associations as $type1) {
foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
$deepModel =& $linkModel->{$assoc1};
$tmpStack = $stack;
$tmpStack[] = $assoc1;
if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
$db =& $this;
} else {
$db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
}
$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
}
}
}
}
$this->__filterResults($fetch, $model);
return $this->__mergeHasMany($resultSet, $fetch, $association, $model, $linkModel, $recursive);
} elseif ($type === 'hasAndBelongsToMany') {
$ins = $fetch = array();
for ($i = 0; $i < $count; $i++) {
if ($in = $this->insertQueryData('{$__cakeID__$}', $resultSet[$i], $association, $assocData, $model, $linkModel, $stack)) {
$ins[] = $in;
}
}
if (!empty($ins)) {
if (count($ins) > 1) {
$query = str_replace('{$__cakeID__$}', '(' .implode(', ', $ins) .')', $query);
$query = str_replace('= (', 'IN (', $query);
$query = str_replace('= (', 'IN (', $query);
} else {
$query = str_replace('{$__cakeID__$}',$ins[0], $query);
}
$query = str_replace(' WHERE 1 = 1', '', $query);
}
$foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
$joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
$habtmFieldsCount = count($habtmFields);
$q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
if ($q != false) {
$fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
} else {
$fetch = null;
}
}
for ($i = 0; $i < $count; $i++) {
$row =& $resultSet[$i];
if ($type !== 'hasAndBelongsToMany') {
$q = $this->insertQueryData($query, $resultSet[$i], $association, $assocData, $model, $linkModel, $stack);
if ($q != false) {
$fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
} else {
$fetch = null;
}
}
$selfJoin = false;
if ($linkModel->name === $model->name) {
$selfJoin = true;
}
if (!empty($fetch) && is_array($fetch)) {
if ($recursive > 0) {
foreach ($linkModel->__associations as $type1) {
foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
$deepModel =& $linkModel->{$assoc1};
if (($type1 === 'belongsTo') || ($deepModel->alias === $model->alias && $type === 'belongsTo') || ($deepModel->alias != $model->alias)) {
$tmpStack = $stack;
$tmpStack[] = $assoc1;
if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
$db =& $this;
} else {
$db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
}
$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
}
}
}
}
if ($type == 'hasAndBelongsToMany') {
$uniqueIds = $merge = array();
foreach ($fetch as $j => $data) {
if (
(isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey])
) {
if ($habtmFieldsCount <= 2) {
unset($data[$with]);
}
$merge[] = $data;
}
}
if (empty($merge) && !isset($row[$association])) {
$row[$association] = $merge;
} else {
$this->__mergeAssociation($resultSet[$i], $merge, $association, $type);
}
} else {
$this->__mergeAssociation($resultSet[$i], $fetch, $association, $type, $selfJoin);
}
if (isset($resultSet[$i][$association])) {
$resultSet[$i][$association] = $linkModel->afterFind($resultSet[$i][$association], false);
}
} else {
$tempArray[0][$association] = false;
$this->__mergeAssociation($resultSet[$i], $tempArray, $association, $type, $selfJoin);
}
}
}
}
/**
* A more efficient way to fetch associations. Woohoo!
*
* @param model $model Primary model object
* @param string $query Association query
* @param array $ids Array of IDs of associated records
* @return array Association results
* @access public
*/
function fetchAssociated($model, $query, $ids) {
$query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
if (count($ids) > 1) {
$query = str_replace('= (', 'IN (', $query);
$query = str_replace('= (', 'IN (', $query);
}
return $this->fetchAll($query, $model->cacheQueries, $model->alias);
}
/**
* mergeHasMany - Merge the results of hasMany relations.
*
*
* @param array $resultSet Data to merge into
* @param array $merge Data to merge
* @param string $association Name of Model being Merged
* @param object $model Model being merged onto
* @param object $linkModel Model being merged
* @return void
*/
function __mergeHasMany(&$resultSet, $merge, $association, &$model, &$linkModel) {
foreach ($resultSet as $i => $value) {
$count = 0;
$merged[$association] = array();
foreach ($merge as $j => $data) {
if (isset($value[$model->alias]) && $value[$model->alias][$model->primaryKey] === $data[$association][$model->hasMany[$association]['foreignKey']]) {
if (count($data) > 1) {
$data = array_merge($data[$association], $data);
unset($data[$association]);
foreach ($data as $key => $name) {
if (is_numeric($key)) {
$data[$association][] = $name;
unset($data[$key]);
}
}
$merged[$association][] = $data;
} else {
$merged[$association][] = $data[$association];
}
}
$count++;
}
if (isset($value[$model->alias])) {
$resultSet[$i] = Set::pushDiff($resultSet[$i], $merged);
unset($merged);
}
}
}
/**
* Enter description here...
*
* @param unknown_type $data
* @param unknown_type $merge
* @param unknown_type $association
* @param unknown_type $type
* @param boolean $selfJoin
* @access private
*/
function __mergeAssociation(&$data, $merge, $association, $type, $selfJoin = false) {
if (isset($merge[0]) && !isset($merge[0][$association])) {
$association = Inflector::pluralize($association);
}
if ($type == 'belongsTo' || $type == 'hasOne') {
if (isset($merge[$association])) {
$data[$association] = $merge[$association][0];
} else {
if (count($merge[0][$association]) > 1) {
foreach ($merge[0] as $assoc => $data2) {
if ($assoc != $association) {
$merge[0][$association][$assoc] = $data2;
}
}
}
if (!isset($data[$association])) {
if ($merge[0][$association] != null) {
$data[$association] = $merge[0][$association];
} else {
$data[$association] = array();
}
} else {
if (is_array($merge[0][$association])) {
foreach ($data[$association] as $k => $v) {
if (!is_array($v)) {
$dataAssocTmp[$k] = $v;
}
}
foreach ($merge[0][$association] as $k => $v) {
if (!is_array($v)) {
$mergeAssocTmp[$k] = $v;
}
}
$dataKeys = array_keys($data);
$mergeKeys = array_keys($merge[0]);
if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
$data[$association][$association] = $merge[0][$association];
} else {
$diff = Set::diff($dataAssocTmp, $mergeAssocTmp);
$data[$association] = array_merge($merge[0][$association], $diff);
}
} elseif ($selfJoin && array_key_exists($association, $merge[0])) {
$data[$association] = array_merge($data[$association], array($association => array()));
}
}
}
} else {
if (isset($merge[0][$association]) && $merge[0][$association] === false) {
if (!isset($data[$association])) {
$data[$association] = array();
}
} else {
foreach ($merge as $i => $row) {
if (count($row) == 1) {
if (empty($data[$association]) || (isset($data[$association]) && !in_array($row[$association], $data[$association]))) {
$data[$association][] = $row[$association];
}
} else if (!empty($row)) {
$tmp = array_merge($row[$association], $row);
unset($tmp[$association]);
$data[$association][] = $tmp;
}
}
}
}
}
/**
* Generates an array representing a query or part of a query from a single model or two associated models
*
* @param Model $model
* @param Model $linkModel
* @param string $type
* @param string $association
* @param array $assocData
* @param array $queryData
* @param boolean $external
* @param array $resultSet
* @return mixed
* @access public
*/
function generateAssociationQuery(&$model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
$queryData = $this->__scrubQueryData($queryData);
$assocData = $this->__scrubQueryData($assocData);
if (empty($queryData['fields'])) {
$queryData['fields'] = $this->fields($model, $model->alias);
} elseif (!empty($model->hasMany) && $model->recursive > -1) {
$assocFields = $this->fields($model, $model->alias, array("{$model->alias}.{$model->primaryKey}"));
$passedFields = $this->fields($model, $model->alias, $queryData['fields']);
if (count($passedFields) === 1) {
$match = strpos($passedFields[0], $assocFields[0]);
$match1 = strpos($passedFields[0], 'COUNT(');
if ($match === false && $match1 === false) {
$queryData['fields'] = array_merge($passedFields, $assocFields);
} else {
$queryData['fields'] = $passedFields;
}
} else {
$queryData['fields'] = array_merge($passedFields, $assocFields);
}
unset($assocFields, $passedFields);
}
if ($linkModel == null) {
return $this->buildStatement(
array(
'fields' => array_unique($queryData['fields']),
'table' => $this->fullTableName($model),
'alias' => $model->alias,
'limit' => $queryData['limit'],
'offset' => $queryData['offset'],
'joins' => $queryData['joins'],
'conditions' => $queryData['conditions'],
'order' => $queryData['order'],
'group' => $queryData['group']
),
$model
);
}
if ($external && !empty($assocData['finderQuery'])) {
return $assocData['finderQuery'];
}
$alias = $association;
$self = ($model->name == $linkModel->name);
$fields = array();
if ((!$external && in_array($type, array('hasOne', 'belongsTo')) && $this->__bypass === false) || $external) {
$fields = $this->fields($linkModel, $alias, $assocData['fields']);
}
if (empty($assocData['offset']) && !empty($assocData['page'])) {
$assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
}
$assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
switch ($type) {
case 'hasOne':
case 'belongsTo':
$conditions = $this->__mergeConditions(
$assocData['conditions'],
$this->getConstraint($type, $model, $linkModel, $alias, array_merge($assocData, compact('external', 'self')))
);
if (!$self && $external) {
foreach ($conditions as $key => $condition) {
if (is_numeric($key) && strpos($condition, $model->alias . '.') !== false) {
unset($conditions[$key]);
}
}
}
if ($external) {
$query = array_merge($assocData, array(
'conditions' => $conditions,
'table' => $this->fullTableName($linkModel),
'fields' => $fields,
'alias' => $alias,
'group' => null
));
$query = array_merge(array('order' => $assocData['order'], 'limit' => $assocData['limit']), $query);
} else {
$join = array(
'table' => $this->fullTableName($linkModel),
'alias' => $alias,
'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
'conditions' => trim($this->conditions($conditions, true, false, $model))
);
$queryData['fields'] = array_merge($queryData['fields'], $fields);
if (!empty($assocData['order'])) {
$queryData['order'][] = $assocData['order'];
}
if (!in_array($join, $queryData['joins'])) {
$queryData['joins'][] = $join;
}
return true;
}
break;
case 'hasMany':
$assocData['fields'] = $this->fields($linkModel, $alias, $assocData['fields']);
if (!empty($assocData['foreignKey'])) {
$assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $alias, array("{$alias}.{$assocData['foreignKey']}")));
}
$query = array(
'conditions' => $this->__mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $alias, $assocData), $assocData['conditions']),
'fields' => array_unique($assocData['fields']),
'table' => $this->fullTableName($linkModel),
'alias' => $alias,
'order' => $assocData['order'],
'limit' => $assocData['limit'],
'group' => null
);
break;
case 'hasAndBelongsToMany':
$joinFields = array();
$joinAssoc = null;
if (isset($assocData['with']) && !empty($assocData['with'])) {
$joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
$joinTbl = $this->fullTableName($model->{$with});
$joinAlias = $joinTbl;
if (is_array($joinFields) && !empty($joinFields)) {
$joinFields = $this->fields($model->{$with}, $model->{$with}->alias, $joinFields);
$joinAssoc = $joinAlias = $model->{$with}->alias;
} else {
$joinFields = array();
}
} else {
$joinTbl = $this->fullTableName($assocData['joinTable']);
$joinAlias = $joinTbl;
}
$query = array(
'conditions' => $assocData['conditions'],
'limit' => $assocData['limit'],
'table' => $this->fullTableName($linkModel),
'alias' => $alias,
'fields' => array_merge($this->fields($linkModel, $alias, $assocData['fields']), $joinFields),
'order' => $assocData['order'],
'group' => null,
'joins' => array(array(
'table' => $joinTbl,
'alias' => $joinAssoc,
'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $alias)
))
);
break;
}
if (isset($query)) {
return $this->buildStatement($query, $model);
}
return null;
}
/**
* Returns a conditions array for the constraint between two models
*
* @param string $type Association type
* @param object $model Model object
* @param array $association Association array
* @return array Conditions array defining the constraint between $model and $association
* @access public
*/
function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
$assoc = array_merge(array('external' => false, 'self' => false), $assoc);
if (array_key_exists('foreignKey', $assoc) && empty($assoc['foreignKey'])) {
return array();
}
switch (true) {
case ($assoc['external'] && $type == 'hasOne'):
return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
break;
case ($assoc['external'] && $type == 'belongsTo'):
return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
break;
case (!$assoc['external'] && $type == 'hasOne'):
return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
break;
case (!$assoc['external'] && $type == 'belongsTo'):
return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
break;
case ($type == 'hasMany'):
return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
break;
case ($type == 'hasAndBelongsToMany'):
return array(
array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
);
break;
}
return array();
}
/**
* Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
*
* @param array $join An array defining a JOIN statement in a query
* @return string An SQL JOIN statement to be used in a query
* @access public
* @see DboSource::renderJoinStatement()
* @see DboSource::buildStatement()
*/
function buildJoinStatement($join) {
$data = array_merge(array(
'type' => null,
'alias' => null,
'table' => 'join_table',
'conditions' => array()
), $join);
if (!empty($data['alias'])) {
$data['alias'] = $this->alias . $this->name($data['alias']);
}
if (!empty($data['conditions'])) {
$data['conditions'] = trim($this->conditions($data['conditions'], true, false));
}
return $this->renderJoinStatement($data);
}
/**
* Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
*
* @param array $query An array defining an SQL query
* @param object $model The model object which initiated the query
* @return string An executable SQL statement
* @access public
* @see DboSource::renderStatement()
*/
function buildStatement($query, &$model) {
$query = array_merge(array('offset' => null, 'joins' => array()), $query);
if (!empty($query['joins'])) {
$count = count($query['joins']);
for ($i = 0; $i < $count; $i++) {
if (is_array($query['joins'][$i])) {
$query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
}
}
}
return $this->renderStatement('select', array(
'conditions' => $this->conditions($query['conditions'], true, true, $model),
'fields' => implode(', ', $query['fields']),
'table' => $query['table'],
'alias' => $this->alias . $this->name($query['alias']),
'order' => $this->order($query['order'], 'ASC', $model),
'limit' => $this->limit($query['limit'], $query['offset']),
'joins' => implode(' ', $query['joins']),
'group' => $this->group($query['group'], $model)
));
}
/**
* Renders a final SQL JOIN statement
*
* @param array $data
* @return string
* @access public
*/
function renderJoinStatement($data) {
extract($data);
return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})");
}
/**
* Renders a final SQL statement by putting together the component parts in the correct order
*
* @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
* @param array $data Array of data to insert into the query.
* @return string Rendered SQL expression to be run.
* @access public
*/
function renderStatement($type, $data) {
extract($data);
$aliases = null;
switch (strtolower($type)) {
case 'select':
return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
break;
case 'create':
return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
break;
case 'update':
if (!empty($alias)) {
$aliases = "{$this->alias}{$alias} {$joins} ";
}
return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}";
break;
case 'delete':
if (!empty($alias)) {
$aliases = "{$this->alias}{$alias} {$joins} ";
}
return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}";
break;
case 'schema':
foreach (array('columns', 'indexes', 'tableParameters') as $var) {
if (is_array(${$var})) {
${$var} = "\t" . join(",\n\t", array_filter(${$var}));
} else {
${$var} = '';
}
}
if (trim($indexes) != '') {
$columns .= ',';
}
return "CREATE TABLE {$table} (\n{$columns}{$indexes}){$tableParameters};";
break;
case 'alter':
break;
}
}
/**
* Merges a mixed set of string/array conditions
*
* @return array
* @access private
*/
function __mergeConditions($query, $assoc) {
if (empty($assoc)) {
return $query;
}
if (is_array($query)) {
return array_merge((array)$assoc, $query);
}
if (!empty($query)) {
$query = array($query);
if (is_array($assoc)) {
$query = array_merge($query, $assoc);
} else {
$query[] = $assoc;
}
return $query;
}
return $assoc;
}
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
* For databases that do not support aliases in UPDATE queries.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @return boolean Success
* @access public
*/
function update(&$model, $fields = array(), $values = null, $conditions = null) {
if ($values == null) {
$combined = $fields;
} else {
$combined = array_combine($fields, $values);
}
$fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
$alias = $joins = null;
$table = $this->fullTableName($model);
$conditions = $this->_matchRecords($model, $conditions);
if ($conditions === false) {
return false;
}
$query = compact('table', 'alias', 'joins', 'fields', 'conditions');
if (!$this->execute($this->renderStatement('update', $query))) {
$model->onError();
return false;
}
return true;
}
/**
* Quotes and prepares fields and values for an SQL UPDATE statement
*
* @param Model $model
* @param array $fields
* @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
* @param boolean $alias Include the model alias in the field name
* @return array Fields and values, quoted and preparted
* @access protected
*/
function _prepareUpdateFields(&$model, $fields, $quoteValues = true, $alias = false) {
$quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
$updates = array();
foreach ($fields as $field => $value) {
if ($alias && strpos($field, '.') === false) {
$quoted = $model->escapeField($field);
} elseif (!$alias && strpos($field, '.') !== false) {
$quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
$model->alias . '.', '', $field
)));
} else {
$quoted = $this->name($field);
}
if ($value === null) {
$updates[] = $quoted . ' = NULL';
continue;
}
$update = $quoted . ' = ';
if ($quoteValues) {
$update .= $this->value($value, $model->getColumnType($field), false);
} elseif (!$alias) {
$update .= str_replace($quotedAlias . '.', '', str_replace(
$model->alias . '.', '', $value
));
} else {
$update .= $value;
}
$updates[] = $update;
}
return $updates;
}
/**
* Generates and executes an SQL DELETE statement.
* For databases that do not support aliases in UPDATE queries.
*
* @param Model $model
* @param mixed $conditions
* @return boolean Success
* @access public
*/
function delete(&$model, $conditions = null) {
$alias = $joins = null;
$table = $this->fullTableName($model);
$conditions = $this->_matchRecords($model, $conditions);
if ($conditions === false) {
return false;
}
if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
$model->onError();
return false;
}
return true;
}
/**
* Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
* in databases that do not support aliases in UPDATE/DELETE queries.
*
* @param Model $model
* @param mixed $conditions
* @return array List of record IDs
* @access protected
*/
function _matchRecords(&$model, $conditions = null) {
if ($conditions === true) {
$conditions = $this->conditions(true);
} elseif ($conditions === null) {
$conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
} else {
$idList = $model->find('all', array(
'fields' => "{$model->alias}.{$model->primaryKey}",
'conditions' => $conditions
));
if (empty($idList)) {
return false;
}
$conditions = $this->conditions(array(
$model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
));
}
return $conditions;
}
/**
* Returns an array of SQL JOIN fragments from a model's associations
*
* @param object $model
* @return array
* @access protected
*/
function _getJoins($model) {
$join = array();
$joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
foreach ($joins as $assoc) {
if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig) {
$assocData = $model->getAssociated($assoc);
$join[] = $this->buildJoinStatement(array(
'table' => $this->fullTableName($model->{$assoc}),
'alias' => $assoc,
'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
'conditions' => trim($this->conditions(
$this->__mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)),
true, false, $model
))
));
}
}
return $join;
}
/**
* Returns an SQL calculation, i.e. COUNT() or MAX()
*
* @param model $model
* @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
* @param array $params Function parameters (any values must be quoted manually)
* @return string An SQL calculation function
* @access public
*/
function calculate(&$model, $func, $params = array()) {
$params = (array)$params;
switch (strtolower($func)) {
case 'count':
if (!isset($params[0])) {
$params[0] = '*';
}
if (!isset($params[1])) {
$params[1] = 'count';
}
if (is_object($model) && $model->isVirtualField($params[0])){
$arg = $this->__quoteFields($model->getVirtualField($params[0]));
} else {
$arg = $this->name($params[0]);
}
return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
case 'max':
case 'min':
if (!isset($params[1])) {
$params[1] = $params[0];
}
if (is_object($model) && $model->isVirtualField($params[0])) {
$arg = $this->__quoteFields($model->getVirtualField($params[0]));
} else {
$arg = $this->name($params[0]);
}
return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
break;
}
}
/**
* Deletes all the records in a table and resets the count of the auto-incrementing
* primary key, where applicable.
*
* @param mixed $table A string or model class representing the table to be truncated
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @access public
*/
function truncate($table) {
return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
}
/**
* Begin a transaction
*
* @param model $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions,
* or a transaction has not started).
* @access public
*/
function begin(&$model) {
if (parent::begin($model) && $this->execute($this->_commands['begin'])) {
$this->_transactionStarted = true;
return true;
}
return false;
}
/**
* Commit a transaction
*
* @param model $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions,
* or a transaction has not started).
* @access public
*/
function commit(&$model) {
if (parent::commit($model) && $this->execute($this->_commands['commit'])) {
$this->_transactionStarted = false;
return true;
}
return false;
}
/**
* Rollback a transaction
*
* @param model $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions,
* or a transaction has not started).
* @access public
*/
function rollback(&$model) {
if (parent::rollback($model) && $this->execute($this->_commands['rollback'])) {
$this->_transactionStarted = false;
return true;
}
return false;
}
/**
* Creates a default set of conditions from the model if $conditions is null/empty.
* If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
* were provided either null or false will be returned based on what was input.
*
* @param object $model
* @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
* or string conditions those conditions will be returned. With other values the model's existance will be checked.
* If the model doesn't exist a null or false will be returned depending on the input value.
* @param boolean $useAlias Use model aliases rather than table names when generating conditions
* @return mixed Either null, false, $conditions or an array of default conditions to use.
* @see DboSource::update()
* @see DboSource::conditions()
* @access public
*/
function defaultConditions(&$model, $conditions, $useAlias = true) {
if (!empty($conditions)) {
return $conditions;
}
$exists = $model->exists();
if (!$exists && $conditions !== null) {
return false;
} elseif (!$exists) {
return null;
}
$alias = $model->alias;
if (!$useAlias) {
$alias = $this->fullTableName($model, false);
}
return array("{$alias}.{$model->primaryKey}" => $model->getID());
}
/**
* Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
*
* @param unknown_type $model
* @param unknown_type $key
* @param unknown_type $assoc
* @return string
* @access public
*/
function resolveKey($model, $key, $assoc = null) {
if (empty($assoc)) {
$assoc = $model->alias;
}
if (!strpos('.', $key)) {
return $this->name($model->alias) . '.' . $this->name($key);
}
return $key;
}
/**
* Private helper method to remove query metadata in given data array.
*
* @param array $data
* @return array
* @access public
*/
function __scrubQueryData($data) {
foreach (array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group') as $key) {
if (!isset($data[$key]) || empty($data[$key])) {
$data[$key] = array();
}
}
return $data;
}
/**
* Converts model virtual fields into sql expressions to be fetched later
*
* @param Model $model
* @param string $alias Alias tablename
* @param mixed $fields virtual fields to be used on query
* @return array
*/
function _constructVirtualFields(&$model, $alias, $fields) {
$virtual = array();
foreach ($fields as $field) {
$virtualField = $this->name("{$alias}__{$field}");
$expression = $this->__quoteFields($model->getVirtualField($field));
$virtual[] = '(' .$expression . ") {$this->alias} {$virtualField}";
}
return $virtual;
}
/**
* Generates the fields list of an SQL query.
*
* @param Model $model
* @param string $alias Alias tablename
* @param mixed $fields
* @param boolean $quote If false, returns fields array unquoted
* @return array
* @access public
*/
function fields(&$model, $alias = null, $fields = array(), $quote = true) {
if (empty($alias)) {
$alias = $model->alias;
}
$cacheKey = array(
$model->useDbConfig,
$model->table,
array_keys($model->schema()),
$model->name,
$model->getVirtualField(),
$alias,
$fields,
$quote
);
$cacheKey = crc32(serialize($cacheKey));
if (isset($this->methodCache[__FUNCTION__][$cacheKey])) {
return $this->methodCache[__FUNCTION__][$cacheKey];
}
$allFields = empty($fields);
if ($allFields) {
$fields = array_keys($model->schema());
} elseif (!is_array($fields)) {
$fields = String::tokenize($fields);
}
$fields = array_values(array_filter($fields));
$virtual = array();
$virtualFields = $model->getVirtualField();
if (!empty($virtualFields)) {
$virtualKeys = array_keys($virtualFields);
foreach ($virtualKeys as $field) {
$virtualKeys[] = $model->alias . '.' . $field;
}
$virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
foreach ($virtual as $i => $field) {
if (strpos($field, '.') !== false) {
$virtual[$i] = str_replace($model->alias . '.', '', $field);
}
$fields = array_diff($fields, array($field));
}
$fields = array_values($fields);
}
if (!$quote) {
if (!empty($virtual)) {
$fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
}
return $fields;
}
$count = count($fields);
if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
for ($i = 0; $i < $count; $i++) {
if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
unset($fields[$i]);
continue;
}
if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
$fields[$i] = $fields[$i]->value;
} elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])){
continue;
} elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
$prepend = '';
if (strpos($fields[$i], 'DISTINCT') !== false) {
$prepend = 'DISTINCT ';
$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
}
$dot = strpos($fields[$i], '.');
if ($dot === false) {
$prefix = !(
strpos($fields[$i], ' ') !== false ||
strpos($fields[$i], '(') !== false
);
$fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
} else {
$value = array();
$comma = strpos($fields[$i], ',');
if ($comma === false) {
$build = explode('.', $fields[$i]);
if (!Set::numeric($build)) {
$fields[$i] = $this->name($build[0] . '.' . $build[1]);
}
$comma = String::tokenize($fields[$i]);
foreach ($comma as $string) {
if (preg_match('/^[0-9]+\.[0-9]+$/', $string)) {
$value[] = $string;
} else {
$build = explode('.', $string);
$value[] = $this->name(trim($build[0]) . '.' . trim($build[1]));
}
}
$fields[$i] = implode(', ', $value);
}
}
$fields[$i] = $prepend . $fields[$i];
} elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
if (isset($field[1])) {
if (strpos($field[1], '.') === false) {
$field[1] = $this->name($alias . '.' . $field[1]);
} else {
$field[0] = explode('.', $field[1]);
if (!Set::numeric($field[0])) {
$field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
$fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
}
}
}
}
}
}
if (!empty($virtual)) {
$fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
}
return $this->methodCache[__FUNCTION__][$cacheKey] = array_unique($fields);
}
/**
* Creates a WHERE clause by parsing given conditions data. If an array or string
* conditions are provided those conditions will be parsed and quoted. If a boolean
* is given it will be integer cast as condition. Null will return 1 = 1.
*
* @param mixed $conditions Array or string of conditions, or any value.
* @param boolean $quoteValues If true, values should be quoted
* @param boolean $where If true, "WHERE " will be prepended to the return value
* @param Model $model A reference to the Model instance making the query
* @return string SQL fragment
* @access public
*/
function conditions($conditions, $quoteValues = true, $where = true, $model = null) {
if (is_object($model)) {
$cacheKey = array(
$model->useDbConfig,
$model->table,
$model->schema(),
$model->name,
$model->getVirtualField(),
$conditions,
$quoteValues,
$where
);
} else {
$cacheKey = array($conditions, $quoteValues, $where);
}
$cacheKey = crc32(serialize($cacheKey));
if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
return $return;
}
$clause = $out = '';
if ($where) {
$clause = ' WHERE ';
}
if (is_array($conditions) && !empty($conditions)) {
$out = $this->conditionKeysToString($conditions, $quoteValues, $model);
if (empty($out)) {
return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . ' 1 = 1');
}
return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . implode(' AND ', $out));
}
if ($conditions === false || $conditions === true) {
return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . (int)$conditions . ' = 1');
}
if (empty($conditions) || trim($conditions) == '') {
return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . '1 = 1');
}
$clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
if (preg_match($clauses, $conditions, $match)) {
$clause = '';
}
if (trim($conditions) == '') {
$conditions = ' 1 = 1';
} else {
$conditions = $this->__quoteFields($conditions);
}
return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . $conditions);
}
/**
* Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
*
* @param array $conditions Array or string of conditions
* @param boolean $quoteValues If true, values should be quoted
* @param Model $model A reference to the Model instance making the query
* @return string SQL fragment
* @access public
*/
function conditionKeysToString($conditions, $quoteValues = true, $model = null) {
$c = 0;
$out = array();
$data = $columnType = null;
$bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
foreach ($conditions as $key => $value) {
$join = ' AND ';
$not = null;
if (is_array($value)) {
$valueInsert = (
!empty($value) &&
(substr_count($key, '?') == count($value) || substr_count($key, ':') == count($value))
);
}
if (is_numeric($key) && empty($value)) {
continue;
} elseif (is_numeric($key) && is_string($value)) {
$out[] = $not . $this->__quoteFields($value);
} elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
if (in_array(strtolower(trim($key)), $bool)) {
$join = ' ' . strtoupper($key) . ' ';
} else {
$key = $join;
}
$value = $this->conditionKeysToString($value, $quoteValues, $model);
if (strpos($join, 'NOT') !== false) {
if (strtoupper(trim($key)) == 'NOT') {
$key = 'AND ' . trim($key);
}
$not = 'NOT ';
}
if (empty($value[1])) {
if ($not) {
$out[] = $not . '(' . $value[0] . ')';
} else {
$out[] = $value[0] ;
}
} else {
$out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
}
} else {
if (is_object($value) && isset($value->type)) {
if ($value->type == 'identifier') {
$data .= $this->name($key) . ' = ' . $this->name($value->value);
} elseif ($value->type == 'expression') {
if (is_numeric($key)) {
$data .= $value->value;
} else {
$data .= $this->name($key) . ' = ' . $value->value;
}
}
} elseif (is_array($value) && !empty($value) && !$valueInsert) {
$keys = array_keys($value);
if (array_keys($value) === array_values(array_keys($value))) {
$count = count($value);
if ($count === 1) {
$data = $this->__quoteFields($key) . ' = (';
} else {
$data = $this->__quoteFields($key) . ' IN (';
}
if ($quoteValues) {
if (is_object($model)) {
$columnType = $model->getColumnType($key);
}
$data .= implode(', ', $this->value($value, $columnType));
}
$data .= ')';
} else {
$ret = $this->conditionKeysToString($value, $quoteValues, $model);
if (count($ret) > 1) {
$data = '(' . implode(') AND (', $ret) . ')';
} elseif (isset($ret[0])) {
$data = $ret[0];
}
}
} elseif (is_numeric($key) && !empty($value)) {
$data = $this->__quoteFields($value);
} else {
$data = $this->__parseKey($model, trim($key), $value);
}
if ($data != null) {
$out[] = $data;
$data = null;
}
}
$c++;
}
return $out;
}
/**
* Extracts a Model.field identifier and an SQL condition operator from a string, formats
* and inserts values, and composes them into an SQL snippet.
*
* @param Model $model Model object initiating the query
* @param string $key An SQL key snippet containing a field and optional SQL operator
* @param mixed $value The value(s) to be inserted in the string
* @return string
* @access private
*/
function __parseKey(&$model, $key, $value) {
$operatorMatch = '/^((' . implode(')|(', $this->__sqlOps);
$operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
$bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
if (!strpos($key, ' ')) {
$operator = '=';
} else {
list($key, $operator) = explode(' ', trim($key), 2);
if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
$key = $key . ' ' . $operator;
$split = strrpos($key, ' ');
$operator = substr($key, $split);
$key = substr($key, 0, $split);
}
}
$virtual = false;
if (is_object($model) && $model->isVirtualField($key)) {
$key = $this->__quoteFields($model->getVirtualField($key));
$virtual = true;
}
$type = (is_object($model) ? $model->getColumnType($key) : null);
$null = ($value === null || (is_array($value) && empty($value)));
if (strtolower($operator) === 'not') {
$data = $this->conditionKeysToString(
array($operator => array($key => $value)), true, $model
);
return $data[0];
}
$value = $this->value($value, $type);
if (!$virtual && $key !== '?') {
$isKey = (strpos($key, '(') !== false || strpos($key, ')') !== false);
$key = $isKey ? $this->__quoteFields($key) : $this->name($key);
}
if ($bound) {
return String::insert($key . ' ' . trim($operator), $value);
}
if (!preg_match($operatorMatch, trim($operator))) {
$operator .= ' =';
}
$operator = trim($operator);
if (is_array($value)) {
$value = implode(', ', $value);
switch ($operator) {
case '=':
$operator = 'IN';
break;
case '!=':
case '<>':
$operator = 'NOT IN';
break;
}
$value = "({$value})";
} elseif ($null) {
switch ($operator) {
case '=':
$operator = 'IS';
break;
case '!=':
case '<>':
$operator = 'IS NOT';
break;
}
}
if ($virtual) {
return "({$key}) {$operator} {$value}";
}
return "{$key} {$operator} {$value}";
}
/**
* Quotes Model.fields
*
* @param string $conditions
* @return string or false if no match
* @access private
*/
function __quoteFields($conditions) {
$start = $end = null;
$original = $conditions;
if (!empty($this->startQuote)) {
$start = preg_quote($this->startQuote);
}
if (!empty($this->endQuote)) {
$end = preg_quote($this->endQuote);
}
$conditions = str_replace(array($start, $end), '', $conditions);
$conditions = preg_replace_callback('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', array(&$this, '__quoteMatchedField'), $conditions);
if ($conditions !== null) {
return $conditions;
}
return $original;
}
/**
* Auxiliary function to qoute matches `Model.fields` from a preg_replace_callback call
*
* @param string matched string
* @return string quoted strig
* @access private
*/
function __quoteMatchedField($match) {
if (is_numeric($match[0])) {
return $match[0];
}
return $this->name($match[0]);
}
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @return string SQL limit/offset statement
* @access public
*/
function limit($limit, $offset = null) {
if ($limit) {
$rt = '';
if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
$rt = ' LIMIT';
}
if ($offset) {
$rt .= ' ' . $offset . ',';
}
$rt .= ' ' . $limit;
return $rt;
}
return null;
}
/**
* Returns an ORDER BY clause as a string.
*
* @param string $key Field reference, as a key (i.e. Post.title)
* @param string $direction Direction (ASC or DESC)
* @param object $model model reference (used to look for virtual field)
* @return string ORDER BY clause
* @access public
*/
function order($keys, $direction = 'ASC', $model = null) {
if (!is_array($keys)) {
$keys = array($keys);
}
$keys = array_filter($keys);
$result = array();
while (!empty($keys)) {
list($key, $dir) = each($keys);
array_shift($keys);
if (is_numeric($key)) {
$key = $dir;
$dir = $direction;
}
if (is_string($key) && strpos($key, ',') && !preg_match('/\(.+\,.+\)/', $key)) {
$key = array_map('trim', explode(',', $key));
}
if (is_array($key)) {
//Flatten the array
$key = array_reverse($key, true);
foreach ($key as $k => $v) {
if (is_numeric($k)) {
array_unshift($keys, $v);
} else {
$keys = array($k => $v) + $keys;
}
}
continue;
}
if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
$dir = $_dir[0];
$key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
}
if (strpos($key, '.')) {
$key = preg_replace_callback('/([a-zA-Z0-9_]{1,})\\.([a-zA-Z0-9_]{1,})/', array(&$this, '__quoteMatchedField'), $key);
}
$key = trim($key);
if (!preg_match('/\s/', $key) && !strpos($key,'.')) {
if (is_object($model) && $model->isVirtualField($key)) {
$key = '('.$this->__quoteFields($model->getVirtualField($key)).')';
} else {
$key = $this->name($key);
}
}
$key .= ' ' . trim($dir);
$result[] = $key;
}
if (!empty($result)) {
return ' ORDER BY ' . implode(', ', $result);
}
return '';
}
/**
* Create a GROUP BY SQL clause
*
* @param string $group Group By Condition
* @return mixed string condition or null
* @access public
*/
function group($group, $model = null) {
if ($group) {
if (!is_array($group)) {
$group = array($group);
}
foreach($group as $index => $key) {
if ($model->isVirtualField($key)) {
$group[$index] = '(' . $model->getVirtualField($key) . ')';
}
}
$group = implode(', ', $group);
return ' GROUP BY ' . $this->__quoteFields($group);
}
return null;
}
/**
* Disconnects database, kills the connection and says the connection is closed.
*
* @return void
* @access public
*/
function close() {
$this->disconnect();
}
/**
* Checks if the specified table contains any record matching specified SQL
*
* @param Model $model Model to search
* @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
* @return boolean True if the table has a matching record, else false
* @access public
*/
function hasAny(&$Model, $sql) {
$sql = $this->conditions($sql);
$table = $this->fullTableName($Model);
$alias = $this->alias . $this->name($Model->alias);
$where = $sql ? "{$sql}" : ' WHERE 1 = 1';
$id = $Model->escapeField();
$out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
if (is_array($out)) {
return $out[0]['count'];
}
return false;
}
/**
* Gets the length of a database-native column description, or null if no length
*
* @param string $real Real database-layer column type (i.e. "varchar(255)")
* @return mixed An integer or string representing the length of the column
* @access public
*/
function length($real) {
if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
trigger_error(__("FIXME: Can't parse field: " . $real, true), E_USER_WARNING);
$col = str_replace(array(')', 'unsigned'), '', $real);
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
}
if ($limit != null) {
return intval($limit);
}
return null;
}
$types = array(
'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
);
list($real, $type, $length, $offset, $sign, $zerofill) = $result;
$typeArr = $type;
$type = $type[0];
$length = $length[0];
$offset = $offset[0];
$isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
if ($isFloat && $offset) {
return $length.','.$offset;
}
if (($real[0] == $type) && (count($real) == 1)) {
return null;
}
if (isset($types[$type])) {
$length += $types[$type];
if (!empty($sign)) {
$length--;
}
} elseif (in_array($type, array('enum', 'set'))) {
$length = 0;
foreach ($typeArr as $key => $enumValue) {
if ($key == 0) {
continue;
}
$tmpLength = strlen($enumValue);
if ($tmpLength > $length) {
$length = $tmpLength;
}
}
}
return intval($length);
}
/**
* Translates between PHP boolean values and Database (faked) boolean values
*
* @param mixed $data Value to be translated
* @return mixed Converted boolean value
* @access public
*/
function boolean($data) {
if ($data === true || $data === false) {
if ($data === true) {
return 1;
}
return 0;
} else {
return !empty($data);
}
}
/**
* Inserts multiple values into a table
*
* @param string $table
* @param string $fields
* @param array $values
* @access protected
*/
function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
if (is_array($fields)) {
$fields = implode(', ', array_map(array(&$this, 'name'), $fields));
}
$count = count($values);
for ($x = 0; $x < $count; $x++) {
$this->query("INSERT INTO {$table} ({$fields}) VALUES {$values[$x]}");
}
}
/**
* Returns an array of the indexes in given datasource name.
*
* @param string $model Name of model to inspect
* @return array Fields in table. Keys are column and unique
* @access public
*/
function index($model) {
return false;
}
/**
* Generate a database-native schema for the given Schema object
*
* @param object $schema An instance of a subclass of CakeSchema
* @param string $tableName Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @access public
*/
function createSchema($schema, $tableName = null) {
if (!is_a($schema, 'CakeSchema')) {
trigger_error(__('Invalid schema object', true), E_USER_WARNING);
return null;
}
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$tableName || $tableName == $curTable) {
$cols = $colList = $indexes = $tableParameters = array();
$primary = null;
$table = $this->fullTableName($curTable);
foreach ($columns as $name => $col) {
if (is_string($col)) {
$col = array('type' => $col);
}
if (isset($col['key']) && $col['key'] == 'primary') {
$primary = $name;
}
if ($name !== 'indexes' && $name !== 'tableParameters') {
$col['name'] = $name;
if (!isset($col['type'])) {
$col['type'] = 'string';
}
$cols[] = $this->buildColumn($col);
} elseif ($name == 'indexes') {
$indexes = array_merge($indexes, $this->buildIndex($col, $table));
} elseif ($name == 'tableParameters') {
$tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
}
}
if (empty($indexes) && !empty($primary)) {
$col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
$indexes = array_merge($indexes, $this->buildIndex($col, $table));
}
$columns = $cols;
$out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
}
}
return $out;
}
/**
* Generate a alter syntax from CakeSchema::compare()
*
* @param unknown_type $schema
* @return boolean
*/
function alterSchema($compare, $table = null) {
return false;
}
/**
* Generate a "drop table" statement for the given Schema object
*
* @param object $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @access public
*/
function dropSchema($schema, $table = null) {
if (!is_a($schema, 'CakeSchema')) {
trigger_error(__('Invalid schema object', true), E_USER_WARNING);
return null;
}
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table == $curTable) {
$out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
}
/**
* Generate a database-native column schema string
*
* @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
* where options can be 'default', 'length', or 'key'.
* @return string
* @access public
*/
function buildColumn($column) {
$name = $type = null;
extract(array_merge(array('null' => true), $column));
if (empty($name) || empty($type)) {
trigger_error(__('Column name or type not defined in schema', true), E_USER_WARNING);
return null;
}
if (!isset($this->columns[$type])) {
trigger_error(sprintf(__('Column type %s does not exist', true), $type), E_USER_WARNING);
return null;
}
$real = $this->columns[$type];
$out = $this->name($name) . ' ' . $real['name'];
if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
if (isset($column['length'])) {
$length = $column['length'];
} elseif (isset($column['limit'])) {
$length = $column['limit'];
} elseif (isset($real['length'])) {
$length = $real['length'];
} else {
$length = $real['limit'];
}
$out .= '(' . $length . ')';
}
if (($column['type'] == 'integer' || $column['type'] == 'float' ) && isset($column['default']) && $column['default'] === '') {
$column['default'] = null;
}
$out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
$out .= ' ' . $this->columns['primary_key']['name'];
} elseif (isset($column['key']) && $column['key'] == 'primary') {
$out .= ' NOT NULL';
} elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
} elseif (isset($column['default'])) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type);
} elseif ($type !== 'timestamp' && !empty($column['null'])) {
$out .= ' DEFAULT NULL';
} elseif ($type === 'timestamp' && !empty($column['null'])) {
$out .= ' NULL';
} elseif (isset($column['null']) && $column['null'] == false) {
$out .= ' NOT NULL';
}
if ($type == 'timestamp' && isset($column['default']) && strtolower($column['default']) == 'current_timestamp') {
$out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
}
$out = $this->_buildFieldParameters($out, $column, 'afterDefault');
return $out;
}
/**
* Build the field parameters, in a position
*
* @param string $columnString The partially built column string
* @param array $columnData The array of column data.
* @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
* @return string a built column with the field parameters added.
* @access public
*/
function _buildFieldParameters($columnString, $columnData, $position) {
foreach ($this->fieldParameters as $paramName => $value) {
if (isset($columnData[$paramName]) && $value['position'] == $position) {
if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'])) {
continue;
}
$val = $columnData[$paramName];
if ($value['quote']) {
$val = $this->value($val);
}
$columnString .= ' ' . $value['value'] . $value['join'] . $val;
}
}
return $columnString;
}
/**
* Format indexes for create table
*
* @param array $indexes
* @param string $table
* @return array
* @access public
*/
function buildIndex($indexes, $table = null) {
$join = array();
foreach ($indexes as $name => $value) {
$out = '';
if ($name == 'PRIMARY') {
$out .= 'PRIMARY ';
$name = null;
} else {
if (!empty($value['unique'])) {
$out .= 'UNIQUE ';
}
$name = $this->startQuote . $name . $this->endQuote;
}
if (is_array($value['column'])) {
$out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
} else {
$out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
}
$join[] = $out;
}
return $join;
}
/**
* Read additional table parameters
*
* @param array $parameters
* @param string $table
* @return array
* @access public
*/
function readTableParameters($name) {
$parameters = array();
if ($this->isInterfaceSupported('listDetailedSources')) {
$currentTableDetails = $this->listDetailedSources($name);
foreach ($this->tableParameters as $paramName => $parameter) {
if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
$parameters[$paramName] = $currentTableDetails[$parameter['column']];
}
}
}
return $parameters;
}
/**
* Format parameters for create table
*
* @param array $parameters
* @param string $table
* @return array
* @access public
*/
function buildTableParameters($parameters, $table = null) {
$result = array();
foreach ($parameters as $name => $value) {
if (isset($this->tableParameters[$name])) {
if ($this->tableParameters[$name]['quote']) {
$value = $this->value($value);
}
$result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
}
}
return $result;
}
/**
* Guesses the data type of an array
*
* @param string $value
* @return void
* @access public
*/
function introspectType($value) {
if (!is_array($value)) {
if ($value === true || $value === false) {
return 'boolean';
}
if (is_float($value) && floatval($value) === $value) {
return 'float';
}
if (is_int($value) && intval($value) === $value) {
return 'integer';
}
if (is_string($value) && strlen($value) > 255) {
return 'text';
}
return 'string';
}
$isAllFloat = $isAllInt = true;
$containsFloat = $containsInt = $containsString = false;
foreach ($value as $key => $valElement) {
$valElement = trim($valElement);
if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
$isAllFloat = false;
} else {
$containsFloat = true;
continue;
}
if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
$isAllInt = false;
} else {
$containsInt = true;
continue;
}
$containsString = true;
}
if ($isAllFloat) {
return 'float';
}
if ($isAllInt) {
return 'integer';
}
if ($containsInt && !$containsString) {
return 'integer';
}
return 'string';
}
}
?> | mit |
SBUDoIT/unity-lab | core/styleguide/js/styleguide.js | 19143 | (function (w) {
var sw = document.body.clientWidth, //Viewport Width
sh = $(document).height(), //Viewport Height
minViewportWidth = ishMinimum, //Minimum Size for Viewport
maxViewportWidth = ishMaximum, //Maxiumum Size for Viewport
viewportResizeHandleWidth = 14, //Width of the viewport drag-to-resize handle
$sgViewport = $('#sg-viewport'), //Viewport element
$sizePx = $('.sg-size-px'), //Px size input element in toolbar
$sizeEms = $('.sg-size-em'), //Em size input element in toolbar
$bodySize = parseInt($('body').css('font-size')), //Body size of the document,
$headerHeight = $('.sg-header').height(),
discoID = false,
discoMode = false,
hayMode = false;
//Update dimensions on resize
$(w).resize(function() {
sw = document.body.clientWidth;
sh = $(document).height();
setAccordionHeight();
});
// Accordion dropdown
$('.sg-acc-handle').on("click", function(e){
e.preventDefault();
var $this = $(this),
$panel = $this.next('.sg-acc-panel'),
subnav = $this.parent().parent().hasClass('sg-acc-panel');
//Close other panels if link isn't a subnavigation item
if (!subnav) {
$('.sg-acc-handle').not($this).removeClass('active');
$('.sg-acc-panel').not($panel).removeClass('active');
}
//Activate selected panel
$this.toggleClass('active');
$panel.toggleClass('active');
setAccordionHeight();
});
//Accordion Height
function setAccordionHeight() {
var $activeAccordion = $('.sg-acc-panel.active').first(),
accordionHeight = $activeAccordion.height(),
availableHeight = sh-$headerHeight; //Screen height minus the height of the header
$activeAccordion.height(availableHeight); //Set height of accordion to the available height
}
$('.sg-nav-toggle').on("click", function(e){
e.preventDefault();
$('.sg-nav-container').toggleClass('active');
});
// "View (containing clean, code, raw, etc options) Trigger
$('#sg-t-toggle').on("click", function(e){
e.preventDefault();
$(this).parents('ul').toggleClass('active');
});
//Size Trigger
$('#sg-size-toggle').on("click", function(e){
e.preventDefault();
$(this).parents('ul').toggleClass('active');
});
//Phase View Events
$('.sg-size[data-size]').on("click", function(e){
e.preventDefault();
killDisco();
killHay();
var val = $(this).attr('data-size');
if (val.indexOf('px') > -1) {
$bodySize = 1;
}
val = val.replace(/[^\d.-]/g,'');
sizeiframe(Math.floor(val*$bodySize));
});
//Size View Events
// handle small button
function goSmall() {
killDisco();
killHay();
sizeiframe(getRandom(minViewportWidth,500));
}
$('#sg-size-s').on("click", function(e){
e.preventDefault();
goSmall();
});
jwerty.key('ctrl+shift+s', function(e) {
goSmall();
return false;
});
// handle medium button
function goMedium() {
killDisco();
killHay();
sizeiframe(getRandom(500,800));
}
$('#sg-size-m').on("click", function(e){
e.preventDefault();
goMedium();
});
jwerty.key('ctrl+shift+m', function(e) {
goLarge();
return false;
});
// handle large button
function goLarge() {
killDisco();
killHay();
sizeiframe(getRandom(800,1200));
}
$('#sg-size-l').on("click", function(e){
e.preventDefault();
goLarge();
});
jwerty.key('ctrl+shift+l', function(e) {
goLarge();
return false;
});
//Click Full Width Button
$('#sg-size-full').on("click", function(e){ //Resets
e.preventDefault();
killDisco();
killHay();
sizeiframe(sw);
});
//Click Random Size Button
$('#sg-size-random').on("click", function(e){
e.preventDefault();
killDisco();
killHay();
sizeiframe(getRandom(minViewportWidth,sw));
});
//Click for Disco Mode, which resizes the viewport randomly
$('#sg-size-disco').on("click", function(e){
e.preventDefault();
killHay();
if (discoMode) {
killDisco();
} else {
startDisco();
}
});
/* Disco Mode */
function disco() {
sizeiframe(getRandom(minViewportWidth,sw));
}
function killDisco() {
discoMode = false;
clearInterval(discoID);
discoID = false;
}
function startDisco() {
discoMode = true;
discoID = setInterval(disco, 800);
}
jwerty.key('ctrl+shift+d', function(e) {
if (!discoMode) {
startDisco();
} else {
killDisco();
}
return false;
});
//Stephen Hay Mode - "Start with the small screen first, then expand until it looks like shit. Time for a breakpoint!"
$('#sg-size-hay').on("click", function(e){
e.preventDefault();
killDisco();
if (hayMode) {
killHay();
} else {
startHay();
}
});
$('#sg-theme').on("click", function(e){
alert("Test");
$('body').addClass('bg-black light-theme');
$('body > .container').addClass("themeable");
});
//Stop Hay! Mode
function killHay() {
var currentWidth = $sgViewport.width();
hayMode = false;
$sgViewport.removeClass('hay-mode');
$('#sg-gen-container').removeClass('hay-mode');
sizeiframe(Math.floor(currentWidth));
}
// start Hay! mode
function startHay() {
hayMode = true;
$('#sg-gen-container').removeClass("vp-animate").width(minViewportWidth+viewportResizeHandleWidth);
$sgViewport.removeClass("vp-animate").width(minViewportWidth);
var timeoutID = window.setTimeout(function(){
$('#sg-gen-container').addClass('hay-mode').width(maxViewportWidth+viewportResizeHandleWidth);
$sgViewport.addClass('hay-mode').width(maxViewportWidth);
setInterval(function(){ var vpSize = $sgViewport.width(); updateSizeReading(vpSize); },100);
}, 200);
}
// start hay from a keyboard shortcut
jwerty.key('ctrl+shift+h', function(e) {
if (!hayMode) {
startHay();
} else {
killHay();
}
});
//Pixel input
$sizePx.on('keydown', function(e){
var val = Math.floor($(this).val());
if(e.keyCode === 38) { //If the up arrow key is hit
val++;
sizeiframe(val,false);
} else if(e.keyCode === 40) { //If the down arrow key is hit
val--;
sizeiframe(val,false);
} else if(e.keyCode === 13) { //If the Enter key is hit
e.preventDefault();
sizeiframe(val); //Size Iframe to value of text box
$(this).blur();
}
});
$sizePx.on('keyup', function(){
var val = Math.floor($(this).val());
updateSizeReading(val,'px','updateEmInput');
});
//Em input
$sizeEms.on('keydown', function(e){
var val = parseFloat($(this).val());
if(e.keyCode === 38) { //If the up arrow key is hit
val++;
sizeiframe(Math.floor(val*$bodySize),false);
} else if(e.keyCode === 40) { //If the down arrow key is hit
val--;
sizeiframe(Math.floor(val*$bodySize),false);
} else if(e.keyCode === 13) { //If the Enter key is hit
e.preventDefault();
sizeiframe(Math.floor(val*$bodySize)); //Size Iframe to value of text box
}
});
$sizeEms.on('keyup', function(){
var val = parseFloat($(this).val());
updateSizeReading(val,'em','updatePxInput');
});
// set 0 to 320px as a default
jwerty.key('ctrl+shift+0', function(e) {
e.preventDefault();
sizeiframe(320,true);
return false;
});
// handle the MQ click
var mqs = [];
$('#sg-mq a').each(function(i) {
mqs.push($(this).html());
// bind the click
$(this).on("click", function(i,k) {
return function(e) {
e.preventDefault();
var val = $(k).html();
var type = (val.indexOf("px") !== -1) ? "px" : "em";
val = val.replace(type,"");
var width = (type === "px") ? val*1 : val*$bodySize;
sizeiframe(width,true);
}
}(i,this));
// bind the keyboard shortcut. can't use cmd on a mac because 3 & 4 are for screenshots
jwerty.key('ctrl+shift+'+(i+1), function (k) {
return function(e) {
var val = $(k).html();
var type = (val.indexOf("px") !== -1) ? "px" : "em";
val = val.replace(type,"");
var width = (type === "px") ? val*1 : val*$bodySize;
sizeiframe(width,true);
return false;
}
}(this));
});
//Resize the viewport
//'size' is the target size of the viewport
//'animate' is a boolean for switching the CSS animation on or off. 'animate' is true by default, but can be set to false for things like nudging and dragging
function sizeiframe(size,animate) {
var theSize;
if(size>maxViewportWidth) { //If the entered size is larger than the max allowed viewport size, cap value at max vp size
theSize = maxViewportWidth;
} else if(size<minViewportWidth) { //If the entered size is less than the minimum allowed viewport size, cap value at min vp size
theSize = minViewportWidth;
} else {
theSize = size;
}
//Conditionally remove CSS animation class from viewport
if(animate===false) {
$('#sg-gen-container,#sg-viewport').removeClass("vp-animate"); //If aninate is set to false, remove animate class from viewport
} else {
$('#sg-gen-container,#sg-viewport').addClass("vp-animate");
}
$('#sg-gen-container').width(theSize+viewportResizeHandleWidth); //Resize viewport wrapper to desired size + size of drag resize handler
$sgViewport.width(theSize); //Resize viewport to desired size
var targetOrigin = (window.location.protocol === "file:") ? "*" : window.location.protocol+"//"+window.location.host;
var obj = JSON.stringify({ "resize": "true" });
document.getElementById('sg-viewport').contentWindow.postMessage(obj,targetOrigin);
updateSizeReading(theSize); //Update values in toolbar
saveSize(theSize); //Save current viewport to cookie
}
$("#sg-gen-container").on('transitionend webkitTransitionEnd', function(e){
var targetOrigin = (window.location.protocol === "file:") ? "*" : window.location.protocol+"//"+window.location.host;
var obj = JSON.stringify({ "resize": "true" });
document.getElementById('sg-viewport').contentWindow.postMessage(obj,targetOrigin);
});
function saveSize(size) {
if (!DataSaver.findValue('vpWidth')) {
DataSaver.addValue("vpWidth",size);
} else {
DataSaver.updateValue("vpWidth",size);
}
}
//Update Pixel and Em inputs
//'size' is the input number
//'unit' is the type of unit: either px or em. Default is px. Accepted values are 'px' and 'em'
//'target' is what inputs to update. Defaults to both
function updateSizeReading(size,unit,target) {
var emSize, pxSize;
if(unit==='em') { //If size value is in em units
emSize = size;
pxSize = Math.floor(size*$bodySize);
} else { //If value is px or absent
pxSize = size;
emSize = size/$bodySize;
}
if (target === 'updatePxInput') {
$sizePx.val(pxSize);
} else if (target === 'updateEmInput') {
$sizeEms.val(emSize.toFixed(2));
} else {
$sizeEms.val(emSize.toFixed(2));
$sizePx.val(pxSize);
}
}
/* Returns a random number between min and max */
function getRandom (min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//Update The viewport size
function updateViewportWidth(size) {
$("#sg-viewport").width(size);
$("#sg-gen-container").width(size*1 + 14);
updateSizeReading(size);
}
//Detect larger screen and no touch support
/*
if('ontouchstart' in document.documentElement && window.matchMedia("(max-width: 700px)").matches) {
$('body').addClass('no-resize');
$('#sg-viewport ').width(sw);
alert('workit');
} else {
}
*/
$('#sg-gen-container').on('touchstart', function(event){});
// handles widening the "viewport"
// 1. on "mousedown" store the click location
// 2. make a hidden div visible so that it can track mouse movements and make sure the pointer doesn't get lost in the iframe
// 3. on "mousemove" calculate the math, save the results to a cookie, and update the viewport
$('#sg-rightpull').mousedown(function(event) {
// capture default data
var origClientX = event.clientX;
var origViewportWidth = $sgViewport.width();
// show the cover
$("#sg-cover").css("display","block");
// add the mouse move event and capture data. also update the viewport width
$('#sg-cover').mousemove(function(event) {
var viewportWidth;
viewportWidth = origViewportWidth + 2*(event.clientX - origClientX);
if (viewportWidth > minViewportWidth) {
if (!DataSaver.findValue('vpWidth')) {
DataSaver.addValue("vpWidth",viewportWidth);
} else {
DataSaver.updateValue("vpWidth",viewportWidth);
}
sizeiframe(viewportWidth,false);
}
});
return false;
});
// on "mouseup" we unbind the "mousemove" event and hide the cover again
$('body').mouseup(function() {
$('#sg-cover').unbind('mousemove');
$('#sg-cover').css("display","none");
});
// capture the viewport width that was loaded and modify it so it fits with the pull bar
var origViewportWidth = $("#sg-viewport").width();
$("#sg-gen-container").width(origViewportWidth);
var testWidth = screen.width;
if (window.orientation !== undefined) {
testWidth = (window.orientation == 0) ? screen.width : screen.height;
}
if (($(window).width() == testWidth) && ('ontouchstart' in document.documentElement) && ($(window).width() <= 1024)) {
$("#sg-rightpull-container").width(0);
} else {
$("#sg-viewport").width(origViewportWidth - 14);
}
updateSizeReading($("#sg-viewport").width());
// get the request vars
var oGetVars = urlHandler.getRequestVars();
// pre-load the viewport width
var vpWidth = 0;
var trackViewportWidth = true; // can toggle this feature on & off
if ((oGetVars.h !== undefined) || (oGetVars.hay !== undefined)) {
startHay();
} else if ((oGetVars.d !== undefined) || (oGetVars.disco !== undefined)) {
startDisco();
} else if ((oGetVars.w !== undefined) || (oGetVars.width !== undefined)) {
vpWidth = (oGetVars.w !== undefined) ? oGetVars.w : oGetVars.width;
vpWidth = (vpWidth.indexOf("em") !== -1) ? Math.floor(Math.floor(vpWidth.replace("em",""))*$bodySize) : Math.floor(vpWidth.replace("px",""));
DataSaver.updateValue("vpWidth",vpWidth);
updateViewportWidth(vpWidth);
} else if (trackViewportWidth && (vpWidth = DataSaver.findValue("vpWidth"))) {
updateViewportWidth(vpWidth);
}
// load the iframe source
var patternName = "all";
var patternPath = "";
var iFramePath = window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+"styleguide/html/styleguide.html";
if ((oGetVars.p !== undefined) || (oGetVars.pattern !== undefined)) {
patternName = (oGetVars.p !== undefined) ? oGetVars.p : oGetVars.pattern;
patternPath = urlHandler.getFileName(patternName);
iFramePath = (patternPath !== "") ? window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+patternPath : iFramePath;
}
if (patternName !== "all") {
document.getElementById("title").innerHTML = "Pattern Lab - "+patternName;
history.replaceState({ "pattern": patternName }, null, null);
}
if (document.getElementById("sg-raw") != undefined) {
document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(patternName));
}
urlHandler.skipBack = true;
document.getElementById("sg-viewport").contentWindow.location.replace(iFramePath);
//Close all dropdowns and navigation
function closePanels() {
$('.sg-nav-container, .sg-nav-toggle, .sg-acc-handle, .sg-acc-panel').removeClass('active');
patternFinder.closeFinder();
}
// update the iframe with the source from clicked element in pull down menu. also close the menu
// having it outside fixes an auto-close bug i ran into
$('.sg-nav a').not('.sg-acc-handle').on("click", function(e){
e.preventDefault();
// update the iframe via the history api handler
var obj = JSON.stringify({ "path": urlHandler.getFileName($(this).attr("data-patternpartial")) });
document.getElementById("sg-viewport").contentWindow.postMessage(obj, urlHandler.targetOrigin);
closePanels();
});
// handle when someone clicks on the grey area of the viewport so it auto-closes the nav
$('#sg-vp-wrap').click(function() {
closePanels();
});
// Listen for resize changes
if (window.orientation !== undefined) {
var origOrientation = window.orientation;
window.addEventListener("orientationchange", function() {
if (window.orientation != origOrientation) {
$("#sg-gen-container").width($(window).width());
$("#sg-viewport").width($(window).width());
updateSizeReading($(window).width());
origOrientation = window.orientation;
}
}, false);
}
// watch the iframe source so that it can be sent back to everyone else.
// based on the great MDN docs at https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
function receiveIframeMessage(event) {
var data = (typeof event.data !== "string") ? event.data : JSON.parse(event.data);
// does the origin sending the message match the current host? if not dev/null the request
if ((window.location.protocol !== "file:") && (event.origin !== window.location.protocol+"//"+window.location.host)) {
return;
}
if (data.bodyclick !== undefined) {
closePanels();
} else if (data.patternpartial !== undefined) {
if (!urlHandler.skipBack) {
if ((history.state === undefined) || (history.state === null) || (history.state.pattern !== data.patternpartial)) {
urlHandler.pushPattern(data.patternpartial, data.path);
}
if (wsnConnected) {
var iFramePath = urlHandler.getFileName(data.patternpartial);
wsn.send( '{"url": "'+iFramePath+'", "patternpartial": "'+event.data.patternpartial+'" }' );
}
}
// reset the defaults
urlHandler.skipBack = false;
} else if (data.keyPress !== undefined) {
if (data.keyPress == 'ctrl+shift+s') {
goSmall();
} else if (data.keyPress == 'ctrl+shift+m') {
goMedium();
} else if (data.keyPress == 'ctrl+shift+l') {
goLarge();
} else if (data.keyPress == 'ctrl+shift+d') {
if (!discoMode) {
startDisco();
} else {
killDisco();
}
} else if (data.keyPress == 'ctrl+shift+h') {
if (!hayMode) {
startHay();
} else {
killHay();
}
} else if (data.keyPress == 'ctrl+shift+0') {
sizeiframe(320,true);
} else if (found = data.keyPress.match(/ctrl\+shift\+([1-9])/)) {
var val = mqs[(found[1]-1)];
var type = (val.indexOf("px") !== -1) ? "px" : "em";
val = val.replace(type,"");
var width = (type === "px") ? val*1 : val*$bodySize;
sizeiframe(width,true);
}
return false;
}
}
window.addEventListener("message", receiveIframeMessage, false);
if (qrCodeGeneratorOn) {
$('.sg-tools').click(function() {
if ((qrCodeGenerator.lastGenerated == "") || (qrCodeGenerator.lastGenerated != window.location.search)) {
qrCodeGenerator.getQRCode();
qrCodeGenerator.lastGenerated = window.location.search;
}
});
}
})(this);
| mit |
me-software/ArgeHeiwako.NET | src/ArgeHeiwako.Tests/Data/AnteilSteuerlicheLeistungsartTests.cs | 25595 | using ArgeHeiwako.Data;
using ArgeHeiwako.Data.Common;
using System;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace ArgeHeiwako.Tests.Data
{
[ExcludeFromCodeCoverage]
public class AnteilSteuerlicheLeistungsartTests
{
private Kostenart kostenart;
private ErweiterterOrdnungsbegriffAbrechnungsunternehmen ordnungsbegriffAbrechnungsunternehmen;
private OrdnungsbegriffWohnungsunternehmen ordnungsbegriffWohnungsunternehmen;
private SteuerlicheLeistungsart steuerlicheLeistungsart;
private Betrag rechnungsbetrag;
private Betrag nutzerAnteil;
private Prozent prozentualerNutzerAnteil;
private Betrag lohnanteilRechnungsbetrag;
private Betrag lohnanteilNutzerAnteil;
private Tag letzterTagNutzungszeitraum;
private AnteilSteuerlicheLeistungsart anteilSteuerlicheLeistungsart;
internal static AnteilSteuerlicheLeistungsart CreateDefault()
{
var item = new AnteilSteuerlicheLeistungsartTests();
return item.anteilSteuerlicheLeistungsart;
}
public AnteilSteuerlicheLeistungsartTests()
{
ordnungsbegriffAbrechnungsunternehmen = new ErweiterterOrdnungsbegriffAbrechnungsunternehmen(
new LiegenschaftsNummer(1),
new NutzergruppenNummer(1),
new WohnungsNummer(1),
new Nutzerfolge(1));
ordnungsbegriffWohnungsunternehmen = new OrdnungsbegriffWohnungsunternehmen("ID");
kostenart = Kostenart.Finde("050");
steuerlicheLeistungsart = SteuerlicheLeistungsart.Finde("00");
rechnungsbetrag = new Betrag(100.00M);
nutzerAnteil = new Betrag(5.0M);
prozentualerNutzerAnteil = new Prozent(5);
lohnanteilRechnungsbetrag = new Betrag(0);
lohnanteilNutzerAnteil = new Betrag(0);
letzterTagNutzungszeitraum = new Tag(new DateTime(2016, 12, 31));
anteilSteuerlicheLeistungsart = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum);
}
#region Ctor
[Fact]
public void Ctor_OrdnungsbegriffAbrechnungsunternehmenNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
null,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("ordnungsbegriffAbrechnungsunternehmen", ex.ParamName);
}
[Fact]
public void Ctor_OrdnungsbegriffWohnungsunternehmenNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
null,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("ordnungsbegriffWohnungsunternehmen", ex.ParamName);
}
[Fact]
public void Ctor_KostenartNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
null,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("kostenart", ex.ParamName);
}
[Fact]
public void Ctor_SteuerlicheLeistungsartNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
null,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("steuerlicheLeistungsart", ex.ParamName);
}
[Fact]
public void Ctor_RechnungsbetragNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
null,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("rechnungsbetrag", ex.ParamName);
}
[Fact]
public void Ctor_NutzerAnteilNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
null,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("nutzerAnteil", ex.ParamName);
}
[Fact]
public void Ctor_ProzentualerNutzerAnteilNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
null,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("prozentualerNutzerAnteil", ex.ParamName);
}
[Fact]
public void Ctor_LohnanteilRechnungsbetragNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
null,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum));
Assert.Equal("lohnanteilRechnungsbetrag", ex.ParamName);
}
[Fact]
public void Ctor_LohnanteilNutzerAnteilNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
null,
letzterTagNutzungszeitraum));
Assert.Equal("lohnanteilNutzerAnteil", ex.ParamName);
}
[Fact]
public void Ctor_LetzterTagNutzungszeitraumNull_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
null));
Assert.Equal("letzterTagNutzungszeitraum", ex.ParamName);
}
[Theory]
[InlineData("228")]
[InlineData("242")]
[InlineData("254")]
[InlineData("311")]
public void Ctor_KostenartText_TooLongStringThrowsArgumentOutOfRangeException(string kostenartSchluessel)
{
var variableKostenart = Kostenart.Finde(kostenartSchluessel);
var ex = Assert.Throws<ArgumentOutOfRangeException>(
() => new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
variableKostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
kostenartText: new string(' ', 26))
);
Assert.Equal("kostenartText", ex.ParamName);
}
#endregion
#region Kostenart
[Fact]
public void Kostenart_Get_ReturnsBackingField()
{
Assert.Equal(kostenart, anteilSteuerlicheLeistungsart.Kostenart);
}
#endregion
#region OrdnungsbegriffAbrechnungsunternehmen
[Fact]
public void OrdnungsbegriffAbrechnungsunternehmen_Get_ReturnsBackingField()
{
Assert.Equal(ordnungsbegriffAbrechnungsunternehmen, anteilSteuerlicheLeistungsart.OrdnungsbegriffAbrechnungsunternehmen);
}
#endregion
#region OrdnungsbegriffWohnungsunternehmen
[Fact]
public void OrdnungsbegriffWohnungsunternehmen_Get_ReturnsBackingField()
{
Assert.Equal(ordnungsbegriffWohnungsunternehmen, anteilSteuerlicheLeistungsart.OrdnungsbegriffWohnungsunternehmen);
}
#endregion
#region SteuerlicheLeistungsart
[Fact]
public void SteuerlicheLeistungsart_Get_ReturnsBackingField()
{
Assert.Equal(steuerlicheLeistungsart, anteilSteuerlicheLeistungsart.SteuerlicheLeistungsart);
}
#endregion
#region Rechnungsbetrag
[Fact]
public void Rechnungsbetrag_Get_ReturnsBackingField()
{
Assert.Equal(rechnungsbetrag, anteilSteuerlicheLeistungsart.Rechnungsbetrag);
}
#endregion
#region NutzerAnteil
[Fact]
public void NutzerAnteil_Get_ReturnsBackingField()
{
Assert.Equal(nutzerAnteil, anteilSteuerlicheLeistungsart.NutzerAnteil);
}
#endregion
#region ProzentualerNutzerAnteil
[Fact]
public void ProzentualerNutzerAnteil_Get_ReturnsBackingField()
{
Assert.Equal(prozentualerNutzerAnteil, anteilSteuerlicheLeistungsart.ProzentualerNutzerAnteil);
}
#endregion
#region ProzentualerNutzerAnteil
[Fact]
public void LohnanteilRechnungsbetrag_Get_ReturnsBackingField()
{
Assert.Equal(lohnanteilRechnungsbetrag, anteilSteuerlicheLeistungsart.LohnanteilRechnungsbetrag);
}
#endregion
#region LohnanteilNutzerAnteil
[Fact]
public void LohnanteilNutzerAnteil_Get_ReturnsBackingField()
{
Assert.Equal(lohnanteilNutzerAnteil, anteilSteuerlicheLeistungsart.LohnanteilNutzerAnteil);
}
#endregion
#region LetzterTagNutzungszeitraum
[Fact]
public void LetzterTagNutzungszeitraum_Get_ReturnsBackingField()
{
Assert.Equal(letzterTagNutzungszeitraum, anteilSteuerlicheLeistungsart.LetzterTagNutzungszeitraum);
}
#endregion
#region SatzfolgeNummer
[Fact]
public void SatzfolgeNummer_Get_DefaultReturnsNull()
{
Assert.Null(anteilSteuerlicheLeistungsart.SatzfolgeNummer);
}
[Fact]
public void SatzfolgeNummer_Get_AfterSetReturnsValue()
{
var satzfolgeNummer = new SatzfolgeNummer(1);
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
satzfolgeNummer: satzfolgeNummer);
Assert.Equal(satzfolgeNummer, item.SatzfolgeNummer);
}
#endregion
#region Abrechnungsunternehmen
[Fact]
public void Abrechnungsunternehmen_Get_DefaultReturnsNull()
{
Assert.Null(anteilSteuerlicheLeistungsart.Abrechnungsunternehmen);
}
[Fact]
public void Abrechnungsunternehmen_Get_AfterSetReturnsValue()
{
var abrechnungsunternehmen = Abrechnungsunternehmen.Finde(30);
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
abrechnungsunternehmen: abrechnungsunternehmen);
Assert.Equal(abrechnungsunternehmen, item.Abrechnungsunternehmen);
}
#endregion
#region AbrechnungsfolgeNummer
[Fact]
public void AbrechnungsfolgeNummer_Get_DefaultReturnsNull()
{
Assert.Null(anteilSteuerlicheLeistungsart.AbrechnungsfolgeNummer);
}
[Fact]
public void AbrechnungsfolgeNummer_Get_AfterSetReturnsValue()
{
var abrechnungsfolgeNummer = new AbrechnungsfolgeNummer(" ");
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
abrechnungsfolgeNummer: abrechnungsfolgeNummer);
Assert.Equal(abrechnungsfolgeNummer, item.AbrechnungsfolgeNummer);
}
#endregion
#region KostenartText
[Fact]
public void KostenartText_Get_DefaultReturnsNull()
{
Assert.Null(anteilSteuerlicheLeistungsart.KostenartText);
}
[Fact]
public void KostenartText_Get_AfterSetReturnsValue()
{
var kostenartText = "Test";
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
kostenartText: kostenartText);
Assert.Equal(kostenartText, item.KostenartText);
}
#endregion
#region ToString()
[Fact]
public void ToString_ReturnsStringLength133()
{
Assert.Equal(133, anteilSteuerlicheLeistungsart.ToString().Length);
}
[Fact]
public void ToString_MandatoryItemsSet_ReturnsCorrectString()
{
var expected =
"E835 000000001000100011ID 050 00000001000000000005000050000000000000000000000311216";
Assert.Equal(expected, anteilSteuerlicheLeistungsart.ToString());
}
[Fact]
public void ToString_KostenartTextSet_ReturnsCorrectString()
{
var expected =
"E835 000000001000100011ID 050Testkosten 00000001000000000005000050000000000000000000000311216";
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
kostenartText: "Testkosten");
Assert.Equal(expected, item.ToString());
}
[Fact]
public void ToString_AbrechnungsfolgeNummerSet_ReturnsCorrectString()
{
var expected =
"E835 000000001000100011ID 1050 00000001000000000005000050000000000000000000000311216";
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
abrechnungsfolgeNummer: new AbrechnungsfolgeNummer("1"));
Assert.Equal(expected, item.ToString());
}
[Fact]
public void ToString_AbrechnungsunternehmenSet_ReturnsCorrectString()
{
var expected =
"E835 30000000001000100011ID 050 00000001000000000005000050000000000000000000000311216";
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
abrechnungsunternehmen: Abrechnungsunternehmen.Finde(30));
Assert.Equal(expected, item.ToString());
}
[Fact]
public void ToString_SatzfolgeNummerSet_ReturnsCorrectString()
{
var expected =
"E8350000001 000000001000100011ID 050 00000001000000000005000050000000000000000000000311216";
var item = new AnteilSteuerlicheLeistungsart(
ordnungsbegriffAbrechnungsunternehmen,
ordnungsbegriffWohnungsunternehmen,
kostenart,
steuerlicheLeistungsart,
rechnungsbetrag,
nutzerAnteil,
prozentualerNutzerAnteil,
lohnanteilRechnungsbetrag,
lohnanteilNutzerAnteil,
letzterTagNutzungszeitraum,
satzfolgeNummer: new SatzfolgeNummer(1));
Assert.Equal(expected, item.ToString());
}
#endregion
#region FromString()
[Fact]
public void FromString_Null_ThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(() => AnteilSteuerlicheLeistungsart.FromString(null));
Assert.Equal("anteilSteuerlicheLeistungsartString", ex.ParamName);
}
[Fact]
public void FromString_EmptyString_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => AnteilSteuerlicheLeistungsart.FromString(string.Empty));
Assert.Equal("anteilSteuerlicheLeistungsartString", ex.ParamName);
}
[Fact]
public void FromString_StringLength132Characters_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => AnteilSteuerlicheLeistungsart.FromString(new string(' ', 132)));
Assert.Equal("anteilSteuerlicheLeistungsartString", ex.ParamName);
}
[Fact]
public void FromString_StringLength134Characters_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => AnteilSteuerlicheLeistungsart.FromString(new string(' ', 134)));
Assert.Equal("anteilSteuerlicheLeistungsartString", ex.ParamName);
}
[Fact]
public void FromString_DoesNotStartWithE835_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => AnteilSteuerlicheLeistungsart.FromString(new string(' ', 133)));
Assert.Equal("anteilSteuerlicheLeistungsartString", ex.ParamName);
}
[Fact]
public void FromString_Field2Pos5To11_ReturnsSatzfolgenummer()
{
var satzfolgeNummer = new SatzfolgeNummer(1);
var satz = new AnteilSteuerlicheLeistungsart(ordnungsbegriffAbrechnungsunternehmen, ordnungsbegriffWohnungsunternehmen, kostenart, steuerlicheLeistungsart, rechnungsbetrag, nutzerAnteil, prozentualerNutzerAnteil, lohnanteilRechnungsbetrag, lohnanteilNutzerAnteil, letzterTagNutzungszeitraum, satzfolgeNummer);
Assert.Equal(satzfolgeNummer.ToString(), AnteilSteuerlicheLeistungsart.FromString(satz.ToString()).SatzfolgeNummer.ToString());
}
[Fact]
public void FromString_Field3Pos12To13_ReturnsAbrechnungsunternehmen()
{
var abrechnungsunternehmen = Abrechnungsunternehmen.Finde(30);
var satz = new AnteilSteuerlicheLeistungsart(ordnungsbegriffAbrechnungsunternehmen, ordnungsbegriffWohnungsunternehmen, kostenart, steuerlicheLeistungsart, rechnungsbetrag, nutzerAnteil, prozentualerNutzerAnteil, lohnanteilRechnungsbetrag, lohnanteilNutzerAnteil, letzterTagNutzungszeitraum, abrechnungsunternehmen: abrechnungsunternehmen);
Assert.Equal(abrechnungsunternehmen, AnteilSteuerlicheLeistungsart.FromString(satz.ToString()).Abrechnungsunternehmen);
}
[Fact]
public void FromString_Field4Pos14To31_ReturnsOrdnungsbegriffAbrechnungsunternehmen()
{
var satz = new AnteilSteuerlicheLeistungsart(ordnungsbegriffAbrechnungsunternehmen, ordnungsbegriffWohnungsunternehmen, kostenart, steuerlicheLeistungsart, rechnungsbetrag, nutzerAnteil, prozentualerNutzerAnteil, lohnanteilRechnungsbetrag, lohnanteilNutzerAnteil, letzterTagNutzungszeitraum);
Assert.Equal(ordnungsbegriffAbrechnungsunternehmen.ToString(), AnteilSteuerlicheLeistungsart.FromString(satz.ToString()).OrdnungsbegriffAbrechnungsunternehmen.ToString());
}
[Fact]
public void FromString_DefaultValidE835_ReturnsValidE835()
{
var validString = CreateDefault().ToString();
Assert.Equal(validString, AnteilSteuerlicheLeistungsart.FromString(validString).ToString());
}
#endregion
}
}
| mit |
lancecarlson/flails | rails/config/routes.rb | 2442 | ActionController::Routing::Routes.draw do |map|
map.rubyamf_gateway 'rubyamf_gateway', :controller => 'rubyamf', :action => 'gateway'
map.resources :accounts
map.resources :clients
map.resources :posts, :collection => {:reset => :get}
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'sessions', :action => 'new'
map.register '/register', :controller => 'users', :action => 'create'
map.signup '/signup', :controller => 'users', :action => 'new'
map.resources :users
map.resource :session
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
| mit |
jake1164/FuelEconomyWSC | FuelEconomyWSC/Areas/HelpPage/SampleGeneration/ImageSample.cs | 1057 | using System;
namespace FuelEconomyWSC.Areas.HelpPage
{
/// <summary>
/// This represents an image sample on the help page. There's a display template named ImageSample associated with this class.
/// </summary>
public class ImageSample
{
/// <summary>
/// Initializes a new instance of the <see cref="ImageSample"/> class.
/// </summary>
/// <param name="src">The URL of an image.</param>
public ImageSample(string src)
{
if (src == null)
{
throw new ArgumentNullException("src");
}
Src = src;
}
public string Src { get; private set; }
public override bool Equals(object obj)
{
ImageSample other = obj as ImageSample;
return other != null && Src == other.Src;
}
public override int GetHashCode()
{
return Src.GetHashCode();
}
public override string ToString()
{
return Src;
}
}
} | mit |
c410echo/echo-asp | admin/browse-by-tag.aspx.cs | 391 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class browsebytag : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ods_get_tkt_bytags_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
}
} | mit |
zumwalt/start | node_modules/gulp/node_modules/gulp-util/test/linefeed-min.js | 87 | var util=require("../"),should=require("should"),path=require("path");require("mocha"); | mit |
RawSanj/SOFRepos | SpringBootJDBCDemo/src/test/java/com/rawsanj/bootjdbc/SpringBootJdbcDemoApplicationTests.java | 349 | package com.rawsanj.bootjdbc;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootJdbcDemoApplicationTests {
@Test
public void contextLoads() {
}
}
| mit |
mAAdhaTTah/readlinks | client/selectors/index.js | 45 | export const selectProps = props$ => props$;
| mit |
igaster/eloquent-inheritance | src/InheritsEloquent.php | 3431 | <?php namespace igaster\EloquentInheritance;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Query\Builder;
class InheritsEloquent extends ModelComposer{
public $query = null;
// -----------------------------------------------
// Factories
// -----------------------------------------------
public static function build(){
$instance = new static;
$parentTable = $instance->getParentTable();
$childTable = $instance->getChildTable();
$childFK = static::$childFK;
$instance->query = new customBuilder($instance, \DB::table($parentTable)
->leftJoin($childTable, "$parentTable.id", '=', "$childTable.$childFK"));
$instance->setHierarcy(new static::$parentClass, new static::$childClass);
return $instance;
}
public static function createFrom($parent, $child){
return static::build()->setHierarcy($parent, $child)->save();
}
// -----------------------------------------------
// Get Table Names
// -----------------------------------------------
public function getParentTable(){
return (new static::$parentClass)->getTable();
}
public function getChildTable(){
return (new static::$childClass)->getTable();
}
// -----------------------------------------------
// Get Models
// -----------------------------------------------
public function parent(){
return isset($this->models[1]) ? $this->models[1] : null;
}
public function child(){
return isset($this->models[0]) ? $this->models[0] : null;
}
// -----------------------------------------------
// Set Models
// -----------------------------------------------
public function setHierarcy($parent, $child){
$childFK = static::$childFK;
$this->models[0] = $child;
$this->models[1] = $parent;
if (!empty($parent) && !empty($child)) {
$child->$childFK = $parent->id;
}
return $this;
}
public function setParent($parent){
return $this->setHierarcy($parent, $this->child());
}
public function setChild($child){
return $this->setHierarcy($this->parent(), $child);
}
// -----------------------------------------------
// Redifine some queryBuilder methods
// -----------------------------------------------
public static function create($data){
$parent = new static::$parentClass;
$child = new static::$childClass;
foreach ($data as $key => $value) {
if(in_array($key, static::$childKeys)){
$child->$key = $value;
} else {
$parent->$key = $value;
}
}
$parent->save();
return static::createFrom($parent, $child);
}
public function update($data){
foreach ($data as $key => $value) {
$this->setPropertyValue($key,$value);
}
return $this->save();
}
public function save(){
parent::save();
return $this;
}
// -----------------------------------------------
// Route queryBuilder methods to internal Builder
// -----------------------------------------------
public static function __callStatic($name, $arguments) {
$instance = static::build();
return $instance->__call($name,$arguments);
}
public function __call($name, $arguments) {
if($this->query->method_exists($name)){
$result = static::callObjectMethod($this->query, $name, $arguments);
return is_a($result, customBuilder::class) ? $this : $result;
}
return parent::__call($name, $arguments);
}
} | mit |
floriandejonckheere/metal_archives | lib/metal_archives/types/boolean.rb | 631 | # frozen_string_literal: true
module MetalArchives
module Types
##
# Boolean type
#
class Boolean
# rubocop:disable Lint/BooleanSymbol
FALSE_VALUES = [
false, 0,
"0", :"0",
"f", :f,
"F", :F,
"false", :false,
"FALSE", :FALSE,
"off", :off,
"OFF", :OFF,
].freeze
# rubocop:enable Lint/BooleanSymbol
def self.cast(value)
!FALSE_VALUES.include?(value)
end
def self.serialize(value)
value.to_s
end
end
end
end
MetalArchives::Types.register(:boolean, MetalArchives::Types::Boolean)
| mit |
juliangoacher/jquery.nub | docs/web/examples/blog-demo/sections/links/setup.js | 63 | function(){
console.log('Running main section js code.');
} | mit |
rstiller/slf4ts-console | lib/slf4ts/index.ts | 411 | import "source-map-support/register";
import { LoggerBindings } from "slf4ts-api";
import { ConsoleLoggerBinding } from "./ConsoleLoggerBinding";
/**
* Instances a new {@link ConsoleLoggerBinding}
*
* @export
* @param {LoggerBindings} registry The bindings collection to register with.
*/
module.exports = function(registry: LoggerBindings) {
registry.registerBinding(new ConsoleLoggerBinding());
};
| mit |
kbhaines/psychic-rat | log/log.go | 515 | package log
import (
"context"
"fmt"
"log"
)
const (
logLevel = " LOG"
errorLevel = "ERROR"
)
func Logf(c context.Context, s string, args ...interface{}) {
logf(c, logLevel, s, args...)
}
func Errorf(c context.Context, s string, args ...interface{}) {
logf(c, errorLevel, s, args...)
}
func logf(c context.Context, level string, s string, args ...interface{}) {
rid := c.Value("rid")
uid := c.Value("uid")
userLog := fmt.Sprintf(s, args...)
log.Printf("%s: %d %s %s", level, rid, uid, userLog)
}
| mit |
hehonghui/simpledb | database/src/main/java/com/simple/database/cursor/AutoCloseCursor.java | 1076 | package com.simple.database.cursor;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.database.sqlite.SQLiteCursor;
import android.util.Log;
/**
* 确保 Cursor对象会被正确的关闭
* Created by mrsimple on 19/4/16.
*/
public class AutoCloseCursor extends CursorWrapper {
public AutoCloseCursor(Cursor cursor) {
super(cursor);
}
@Override
protected void finalize() throws Throwable {
try {
if (!getWrappedCursor().isClosed()) {
showLeakInfo((SQLiteCursor) getWrappedCursor());
close();
}
} finally {
super.finalize();
}
}
private void showLeakInfo(SQLiteCursor cursor) {
Log.e("", "### ==========> Cursor泄露了, Cursor中的字段为 : ");
String[] columnNames = cursor.getColumnNames();
for (int i = 0; i < columnNames.length; i++) {
Log.e("", "### column -> " + columnNames[i]);
}
Log.e("", "### ==========>Cursor 泄露 !!!!!! END ");
}
}
| mit |
dlras2/HashingLibrary | BitFn.HashingLibrary.Tests/Algorithms/MurmurHash3/HashSize.cs | 552 | using Microsoft.VisualStudio.TestTools.UnitTesting;
using Run00.MsTest;
namespace BitFn.HashingLibrary.Tests.Algorithms.MurmurHash3
{
[TestClass]
[CategorizeByConventionClass(typeof(HashSize))]
public class HashSize
{
[TestMethod]
[CategorizeByConvention]
public void WhenGotten_ShouldReturnConstant()
{
// Arrange
const int expected = 32;
var algorithm = new HashingLibrary.Algorithms.MurmurHash3();
// Act
var actual = ((IHashAlgorithm)algorithm).HashSize;
// Assert
Assert.AreEqual(expected, actual);
}
}
}
| mit |
jtauber/Rev | rev/__init__.py | 23 | from .core import Repo
| mit |
CollDev/petramas | src/Petramas/MainBundle/Controller/BoletaMaterialController.php | 8040 | <?php
namespace Petramas\MainBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Petramas\MainBundle\Entity\BoletaMaterial;
use Petramas\MainBundle\Form\BoletaMaterialType;
/**
* BoletaMaterial controller.
*
* @Route("/boletamaterial")
*/
class BoletaMaterialController extends Controller
{
/**
* Lists all BoletaMaterial entities.
*
* @Route("/", name="boletamaterial")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('PetramasMainBundle:BoletaMaterial')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new BoletaMaterial entity.
*
* @Route("/", name="boletamaterial_create")
* @Method("POST")
* @Template("PetramasMainBundle:BoletaMaterial:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new BoletaMaterial();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$this->get('session')->getFlashBag()->set(
'success',
array(
'title' => 'Nueva!',
'message' => 'Boleta material creada con éxito.'
)
);
return $this->redirect($this->generateUrl('boletamaterial_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a BoletaMaterial entity.
*
* @param BoletaMaterial $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(BoletaMaterial $entity)
{
$form = $this->createForm(new BoletaMaterialType(), $entity, array(
'action' => $this->generateUrl('boletamaterial_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Crear', 'attr' => array('class' => 'btn btn-primary entity-submit pull-right')));
return $form;
}
/**
* Displays a form to create a new BoletaMaterial entity.
*
* @Route("/new", name="boletamaterial_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new BoletaMaterial();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a BoletaMaterial entity.
*
* @Route("/{id}", name="boletamaterial_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PetramasMainBundle:BoletaMaterial')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find BoletaMaterial entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing BoletaMaterial entity.
*
* @Route("/{id}/edit", name="boletamaterial_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PetramasMainBundle:BoletaMaterial')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find BoletaMaterial entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a BoletaMaterial entity.
*
* @param BoletaMaterial $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(BoletaMaterial $entity)
{
$form = $this->createForm(new BoletaMaterialType(), $entity, array(
'action' => $this->generateUrl('boletamaterial_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Editar', 'attr' => array('class' => 'btn btn-warning entity-submit pull-right')));
return $form;
}
/**
* Edits an existing BoletaMaterial entity.
*
* @Route("/{id}", name="boletamaterial_update")
* @Method("PUT")
* @Template("PetramasMainBundle:BoletaMaterial:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PetramasMainBundle:BoletaMaterial')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find BoletaMaterial entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
$this->get('session')->getFlashBag()->set(
'success',
array(
'title' => 'Editada!',
'message' => 'Boleta material actualizada satisfactoriamente.'
)
);
return $this->redirect($this->generateUrl('boletamaterial', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a BoletaMaterial entity.
*
* @Route("/{id}", name="boletamaterial_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PetramasMainBundle:BoletaMaterial')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find BoletaMaterial entity.');
}
$em->remove($entity);
$em->flush();
$this->get('session')->getFlashBag()->set(
'success',
array(
'title' => 'Eliminada!',
'message' => 'Boleta material removida.'
)
);
}
return $this->redirect($this->generateUrl('boletamaterial'));
}
/**
* Creates a form to delete a BoletaMaterial entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('boletamaterial_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Eliminar', 'attr' => array('class' => 'btn btn-danger entity-submit-delete pull-right')))
->getForm()
;
}
}
| mit |
BookedOut/CRToastAndroid | CRToastLibrary/src/main/java/com/tagantroy/crtoast/CRToast.java | 15845 | package com.tagantroy.crtoast;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.lang.reflect.Field;
import java.util.Map;
public class CRToast {
public interface ICRToast{
boolean onTapped();
}
Thread timer;
private AnimationStyle animationStyle;
private int duration;
private int backgroundColor;
private int height;
private Drawable image;
private boolean isDismissibleWithTap;
private boolean isImage;
private boolean isInsideActionBar;
private String notificationMessage;
private int notificationMessageColor = 0;
private int subTitleColor = 0;
private Typeface notificationMessageFont = null;
private int notificationMessageFontSize = -1;
private Typeface subTitleFont = null;
private int notificationLayoutGravity = -1;
private int notificationMessageGravity = -1;
private int subTitleGravity = -1;
private int subTitleFontSize = -1;
private String subtitleText;
private View customView;
private ICRToast icrToast;
private Activity activity;
private View view;
private boolean isHomeButtonEnabled = false;
private boolean isBackButtonEnabled = false;
WindowManager windowManager;
public static class Builder {
private AnimationStyle animationStyle = AnimationStyle.TopToTop;
private int duration = -1;
private int backgroundColor = Color.RED;
private int height = 72;
private Drawable image = null;
private boolean isDismissibleWithTap = false;
private boolean isImage = false;
private boolean isInsideActionBar = false;
private boolean isHomeButtonEnabled = false;
private boolean isBackButtonEnabled = false;
private String notificationMessage = "";
private int notificationMessageColor = 0;
private int subTitleColor = 0;
private Typeface notificationMessageFont = null;
private int notificationMessageFontSize = -1;
private Typeface subTitleFont = null;
private int subTitleFontSize = -1;
private int notificationLayoutGravity = -1;
private int notificationMessageGravity = -1;
private int subTitleGravity = -1;
private String subtitleText = "";
private View customView=null;
private ICRToast icrToast = null;
private Activity activity;
public Builder() {
this.activity = getRunningActivity();
}
public Builder(Activity activity) {
this.activity = activity;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private Activity getRunningActivity() {
try {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread")
.invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map activities = (Map) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
return (Activity) activityField.get(activityRecord);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Didn't find the running activity");
}
public Builder animationStyle(AnimationStyle val) {
animationStyle = val;
return this;
}
public Builder backgroundColor(int val) {
backgroundColor = val;
return this;
}
public Builder notificationMessageColor(int val){
notificationMessageColor = val;
return this;
}
public Builder subTitleColor(int val){
subTitleColor = val;
return this;
}
public Builder notificationMessageFont(Typeface val,int fontSize){
notificationMessageFont = val;
notificationMessageFontSize = fontSize;
return this;
}
public Builder subTitleFont(Typeface val,int fontSize){
subTitleFont = val;
subTitleFontSize = fontSize;
return this;
}
public Builder notificationLayoutGravity(int val) {
notificationLayoutGravity = val;
return this;
}
public Builder notificationMessageGravity(int val){
notificationMessageGravity = val;
return this;
}
public Builder subTitleGravity(int val){
subTitleGravity = val;
return this;
}
public Builder homeButtonEnabled(boolean val){
isHomeButtonEnabled = val;
return this;
}
public Builder backButtonEnabled(boolean val){
isBackButtonEnabled = val;
return this;
}
public Builder customHeight(int val) {
height = val;
return this;
}
public Builder customView(View val){
customView = val;
return this;
}
public Builder dismissWithTap(boolean val) {
isDismissibleWithTap = val;
return this;
}
public Builder onTapped(ICRToast val){
icrToast = val;
return this;
}
public Builder duration(int val) {
duration = val;
return this;
}
public Builder image(Drawable val) {
isImage = true;
image = val;
return this;
}
public Builder notificationMessage(String val) {
notificationMessage = val;
return this;
}
public Builder subtitleText(String val) {
subtitleText = val;
return this;
}
public Builder insideActionBar(boolean val) {
isInsideActionBar = val;
return this;
}
public CRToast build() {
return new CRToast(this);
}
}
private CRToast(Builder builder) {
animationStyle = builder.animationStyle;
backgroundColor = builder.backgroundColor;
duration = builder.duration;
isImage = builder.isImage;
image = builder.image;
height = builder.height;
isDismissibleWithTap = builder.isDismissibleWithTap;
icrToast = builder.icrToast;
isInsideActionBar = builder.isInsideActionBar;
notificationMessage = builder.notificationMessage;
subtitleText = builder.subtitleText;
notificationMessageColor = builder.notificationMessageColor;
subTitleColor = builder.subTitleColor;
notificationMessageFont = builder.notificationMessageFont;
notificationMessageFontSize = builder.notificationMessageFontSize;
subTitleFont = builder.subTitleFont;
subTitleFontSize = builder.subTitleFontSize;
notificationLayoutGravity = builder.notificationLayoutGravity;
notificationMessageGravity = builder.notificationMessageGravity;
subTitleGravity = builder.subTitleGravity;
activity = builder.activity;
customView = builder.customView;
isBackButtonEnabled = builder.isBackButtonEnabled;
isHomeButtonEnabled = builder.isHomeButtonEnabled;
windowManager = (WindowManager) activity
.getSystemService(Context.WINDOW_SERVICE);
if(customView != null){
view = customView;
} else {
view = generateToast();
}
int statusBarPadding = getStatusBarHeight(activity);
if (isStatusBarVisible()) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, statusBarPadding, 0, statusBarPadding);
view.setLayoutParams(lp);
}
if (isInsideActionBar) {
view.setPadding(0, statusBarPadding, 0, 0);
}
}
void show() {
windowManager.addView(view, getLayoutParams());
if(duration!=-1)
startTimer(duration);
}
void dismiss() {
removeToast();
}
private synchronized void removeToast() {
try {
if (view != null) {
windowManager.removeView(view);
}
}catch (IllegalArgumentException e){}
}
private void startTimer(final int duration) {
final Handler handler = new Handler();
timer = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(duration);
handler.post(new Runnable() {
@Override
public void run() {
CRToastManager.dismiss();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
timer.start();
}
private LinearLayout generateToast() {
int statusBarHeight = getStatusBarHeight(activity);
int toastXML = activity.getResources()
.getIdentifier("toast", "layout", activity.getPackageName());
LinearLayout view = (LinearLayout) activity.getLayoutInflater()
.inflate(toastXML, null);
int notificationLayoutId = activity.getResources().getIdentifier("notificationLayoutHolder", "id", activity.getPackageName());
int messageId = activity.getResources()
.getIdentifier("notificationMessage", "id", activity.getPackageName());
int subtitleId = activity.getResources()
.getIdentifier("subtitleText", "id", activity.getPackageName());
int customImageViewId = activity.getResources()
.getIdentifier("customImageView", "id", activity.getPackageName());
int marginViewId = activity.getResources()
.getIdentifier("marginView", "id", activity.getPackageName());
LinearLayout notificationLayoutHolder = (LinearLayout) view.findViewById(notificationLayoutId);
LinearLayout marginLL = (LinearLayout) view.findViewById(marginViewId);
LinearLayout.LayoutParams tempParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
marginLL.setLayoutParams(tempParams);
TextView message = (TextView) view.findViewById(messageId);
TextView subtitle = (TextView) view.findViewById(subtitleId);
ImageView customImageView = (ImageView) view.findViewById(customImageViewId);
view.setBackgroundColor(backgroundColor);
subtitle.setText(subtitleText);
message.setText(notificationMessage);
if(subtitleText== null || subtitleText.length()==0){
message.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
subtitle.setVisibility(View.GONE);
}
if(icrToast!=null){
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(icrToast.onTapped())
CRToastManager.dismiss();
}
});
}else{
if (isDismissibleWithTap) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CRToastManager.dismiss();
}
});
}
}
if (isImage) {
customImageView.setImageDrawable(image);
}
if(notificationMessageColor!=0){
message.setTextColor(notificationMessageColor);
}
if(notificationMessageFont!=null){
message.setTypeface(notificationMessageFont);
}
if(notificationMessageFontSize!=-1){
message.setTextSize(notificationMessageFontSize/ activity.getResources().getDisplayMetrics().density);
}
if(notificationLayoutGravity != -1) {
notificationLayoutHolder.setGravity(notificationLayoutGravity);
}
if(notificationMessageGravity!=-1){
message.setGravity(notificationMessageGravity);
}
if(subTitleColor!=0){
subtitle.setTextColor(subTitleColor);
}
if(subTitleFont!=null){
subtitle.setTypeface(subTitleFont);
}
if(subTitleFontSize!=-1){
subtitle.setTextSize(subTitleFontSize/ activity.getResources().getDisplayMetrics().density);
}
if(subTitleGravity!=-1){
subtitle.setGravity(subTitleGravity);
}
return view;
}
private int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
private WindowManager.LayoutParams getLayoutParams() {
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
if(isHomeButtonEnabled )
layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
else
layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
if(isBackButtonEnabled) {
layoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
} else {
layoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
}
layoutParams.format = PixelFormat.RGB_888;
layoutParams.width = ActionBar.LayoutParams.MATCH_PARENT;
layoutParams.height = ((int) Math.ceil(height * activity.getResources().getDisplayMetrics().density)) + getStatusBarHeight(activity);
layoutParams.gravity = Gravity.TOP;
layoutParams.windowAnimations = animationStyle.getStyle(activity);
return layoutParams;
}
private boolean isStatusBarVisible() {
int result = 0;
int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = activity.getResources().getDimensionPixelSize(resourceId);
}
return result != 0;
}
} | mit |
jaredcsullivan/RESTful-MEAN-TodoApp | gulpfile.js | 1011 | var gulp = require('gulp'),
nodemon = require('gulp-nodemon'),
jshint = require('gulp-jshint'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps');
gulp.task('default', ['watch']);
gulp.task('start', function () {
nodemon({
script: './bin/www',
env: { 'NODE_ENV': 'development' },
ext: "js",
nodeArgs: ['/usr/local/bin/node-theseus']
})
})
gulp.task('lint', function () {
gulp.src('./**/*.js')
.pipe(jshint())
})
gulp.task('develop', function () {
nodemon({ script: './bin/www',
ignore: ['ignored.js'],
tasks: ['lint'] })
.on('restart', function () {
console.log('restarted!')
})
})
gulp.task('build-css', function() {
return gulp.src('public/css/**/*.css')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write())
.pipe(gulp.dest('public/css/stylesheets'));
});
gulp.task('watch', function() {
gulp.watch('./**/*.js', ['jshint']);
gulp.watch('public/css/**/*.css', ['build-css']);
}); | mit |
go-oleg/debug-live | src/debugLive.js | 625 | var net = require('net');
module.exports = function(evalFunc,port) {
if(!port) {
throw new Error("Please specify the `port` as the second parameter to Debug Live.");
}
var server = net.createServer(function (socket) {
socket.write("Welcome to Debug Live:\n>");
socket.on("data", function(data) {
var result = "";
try {
result = evalFunc(data.toString());
}
catch(e) {
result = e;
}
finally {
socket.write(result + "\n>");
}
});
});
server.listen(port, '127.0.0.1');
console.log("Debug Live is running on port " + port + ". `telnet localhost " + port + "` to connect.");
}
| mit |
FREEZX/socket.io | lib/namespace.js | 5006 |
/**
* Module dependencies.
*/
var Socket = require('./socket');
var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');
var debug = require('debug')('socket.io:namespace');
var hasBin = require('has-binary-data');
/**
* Module exports.
*/
module.exports = exports = Namespace;
/**
* Blacklisted events.
*/
exports.events = [
'connect', // for symmetry with client
'connection',
'newListener'
];
/**
* Flags.
*/
exports.flags = ['json'];
/**
* `EventEmitter#emit` reference.
*/
var emit = Emitter.prototype.emit;
/**
* Namespace constructor.
*
* @param {Server} server instance
* @param {Socket} name
* @api private
*/
function Namespace(server, name){
this.name = name;
this.server = server;
this.sockets = [];
this.connected = {};
this.fns = [];
this.ids = 0;
this.acks = {};
this.initAdapter();
}
/**
* Inherits from `EventEmitter`.
*/
Namespace.prototype = Object.create(Emitter.prototype);
/**
* Apply flags from `Socket`.
*/
exports.flags.forEach(function(flag){
Namespace.prototype.__defineGetter__(flag, function(){
this.flags = this.flags || {};
this.flags[flag] = true;
return this;
});
});
/**
* Initializes the `Adapter` for this nsp.
* Run upon changing adapter by `Server#adapter`
* in addition to the constructor.
*
* @api private
*/
Namespace.prototype.initAdapter = function(){
this.adapter = new (this.server.adapter())(this);
};
/**
* Sets up namespace middleware.
*
* @return {Namespace} self
* @api public
*/
Namespace.prototype.use = function(fn){
this.fns.push(fn);
return this;
};
/**
* Executes the middleware for an incoming client.
*
* @param {Socket} socket that will get added
* @param {Function} last fn call in the middleware
* @api private
*/
Namespace.prototype.run = function(socket, fn){
var fns = this.fns.slice(0);
if (!fns.length) return fn(null);
function run(i){
fns[i](socket, function(err){
// upon error, short-circuit
if (err) return fn(err);
// if no middleware left, summon callback
if (!fns[i + 1]) return fn(null);
// go on to next
run(i + 1);
});
}
run(0);
};
/**
* Targets a room when emitting.
*
* @param {String} name
* @return {Namespace} self
* @api public
*/
Namespace.prototype.to =
Namespace.prototype['in'] = function(name){
this.rooms = this.rooms || [];
if (!~this.rooms.indexOf(name)) this.rooms.push(name);
return this;
};
/**
* Adds a new client.
*
* @return {Socket}
* @api private
*/
Namespace.prototype.add = function(client, fn){
debug('adding socket to nsp %s', this.name);
var socket = new Socket(this, client);
var self = this;
this.run(socket, function(err){
process.nextTick(function(){
if ('open' == client.conn.readyState) {
if (err) return socket.error(err.data || err.message);
// track socket
self.sockets.push(socket);
// it's paramount that the internal `onconnect` logic
// fires before user-set events to prevent state order
// violations (such as a disconnection before the connection
// logic is complete)
socket.onconnect();
if (fn) fn();
// fire user-set events
self.emit('connect', socket);
self.emit('connection', socket);
} else {
debug('next called after client was closed - ignoring socket');
}
});
});
return socket;
};
/**
* Removes a client. Called by each `Socket`.
*
* @api private
*/
Namespace.prototype.remove = function(socket){
var i = this.sockets.indexOf(socket);
if (~i) {
this.sockets.splice(i, 1);
} else {
debug('ignoring remove for %s', socket.id);
}
};
/**
* Gets all clients in room
*
* @param {String} room id
* @param {Function} callback, callback function
* @api public
*/
Namespace.prototype.clients = function(name, fn){
this.adapter.clients(name, fn);
};
/**
* Emits to all clients.
*
* @return {Namespace} self
* @api public
*/
Namespace.prototype.emit = function(ev){
if (~exports.events.indexOf(ev)) {
emit.apply(this, arguments);
} else {
// set up packet object
var args = Array.prototype.slice.call(arguments);
var parserType = parser.EVENT; // default
if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
var packet = { type: parserType, data: args };
if ('function' == typeof args[args.length - 1]) {
throw new Error('Callbacks are not supported when broadcasting');
}
this.adapter.broadcast(packet, {
rooms: this.rooms,
flags: this.flags
});
delete this.rooms;
delete this.flags;
}
return this;
};
/**
* Sends a `message` event to all clients.
*
* @return {Namespace} self
* @api public
*/
Namespace.prototype.send =
Namespace.prototype.write = function(){
var args = Array.prototype.slice.call(arguments);
args.unshift('message');
this.emit.apply(this, args);
return this;
};
| mit |
teoreteetik/api-snippets | sync/rest/streams/create-stream/create-stream.6.x.py | 444 | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
stream = client.sync \
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.sync_streams \
.create(unique_name="MyStream")
print(stream.sid)
| mit |
exclusivecoin/Exclusive | src/qt/locale/bitcoin_zh_CN.ts | 125091 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_CN" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About ExclusiveCoin</source>
<translation>关于黑币</translation>
</message>
<message>
<location line="+39"/>
<source><b>ExclusiveCoin</b> version</source>
<translation>黑币客户端 版本</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The ExclusiveCoin developers</source>
<translation>版权所有 © 2009-2014 比特币Bitcoin开发组
版权所有 © 2012-2014 新星币Novacoin开发组
版权所有 © 2014 黑币ExclusiveCoin开发组</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
测试版软件
经MIT/X11软件授权发布, 具体参见http://www.opensource.org/licenses/mit-license.php.
本产品包括由OpenSSL Project (http://www.openssl.org/)开发的OpenSSL工具包 ,由 Eric Young (eay@cryptsoft.com) 撰写的密码学软件以及由 Thomas Bernard 撰写的UPnP软件.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>地址簿</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>双击编辑地址或标签</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>创建新地址</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>复制当前选中的地址到系统剪贴板</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>新建地址(&N)</translation>
</message>
<message>
<location line="-46"/>
<source>These are your ExclusiveCoin 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>这是您用来接收支付的黑币地址列表。为不同的支付方建立不同的地址以便于了解支付来源。</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>复制地址(&C)</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>显示二维码(&Q)</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a ExclusiveCoin address</source>
<translation>对信息进行签名以证明您对该黑币地址的所有权</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>签名(&M)</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>从列表中删除选中的地址</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified ExclusiveCoin address</source>
<translation>验证信息以保证其经过指定黑币地址的签名</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>验证消息(&V)</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>删除(&D)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>复制标签(&L)</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>编辑(&E)</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>导出地址簿数据</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗号分隔文件 (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>导出时发生错误</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>无法写入文件 %1 。</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>密码对话框</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>输入密码</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>新密码</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>重复新密码</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>在系统允许的情况下用于防止sendmoney欺诈,并未提供真正的安全防护措施。</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>仅用于权益增值</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>输入钱包的新密码。<br/>使用的密码请至少包含<b>10个以上随机字符</>,或者是<b>8个以上的单词</b>。</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>加密钱包</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>此操作需要您首先使用密码解锁该钱包。</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>解锁钱包</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>该操作需要您首先使用密码解密钱包。</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>解密钱包</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>更改密码</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>请输入该钱包的旧密码与新密码。</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>确认加密钱包</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>警告:如果您丢失了加密该钱包的密码,其中所有的黑币将会丢失!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>您确定需要为钱包加密吗?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>重要提示:您以前备份的钱包文件应该替换成最新生成的加密钱包文件(重新备份)。从安全性上考虑,您以前备份的未加密的钱包文件,在您使用新的加密钱包后将无效,请重新备份。</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>警告:大写锁定键处于打开状态!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>钱包已加密</translation>
</message>
<message>
<location line="-58"/>
<source>ExclusiveCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>黑币客户端即将关闭以完成加密过程。请记住,加密钱包并不能完全防止您的电子货币被入侵您计算机的木马软件盗窃。</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>钱包加密失败</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>由于一个本地错误,加密钱包的操作已经失败。您的钱包没能被加密。</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>密码不匹配。</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>钱包解锁失败</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>用于解密钱包的密码不正确。</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>钱包解密失败。</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>修改钱包密码成功。</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>消息签名(&M)...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>正在与网络同步...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>概况(&O)</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>显示钱包概况</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>交易记录(&T)</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>查看交易历史</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>地址簿(&A)</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>管理已储存的地址和标签</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>接收黑币(&R)</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>显示用于接收支付的地址列表</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>发送货币(&S)</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>退出(&X)</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>退出程序</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about ExclusiveCoin</source>
<translation>显示关于黑币的信息</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>关于 &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>显示 Qt 相关信息</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>选项(&O)...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>加密钱包(&E)...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>备份钱包(&B)...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>更改密码(&C)...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>~%n 个区块未完成</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>交易记录已下载%3% (%1 / %2 个区块)</translation>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>导出(&E)</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a ExclusiveCoin address</source>
<translation>向指定的地址发送黑币</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for ExclusiveCoin</source>
<translation>更改设置选项</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>导出当前标签页的数据</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>加密/解密钱包</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>备份钱包到其他文件夹</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>更改钱包加密口令</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>调试窗口(&D)</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>打开调试和诊断控制台</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>验证消息(&V)...</translation>
</message>
<message>
<location line="-202"/>
<source>ExclusiveCoin</source>
<translation>黑币</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>钱包</translation>
</message>
<message>
<location line="+180"/>
<source>&About ExclusiveCoin</source>
<translation>关于黑币(&A)</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>显示 / 隐藏(&S)</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>解锁钱包</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>锁定钱包(&L)</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>锁定钱包</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>文件(&F)</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>设置(&S)</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>帮助(&H)</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>分页工具栏</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>工具栏</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[测试网络]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>ExclusiveCoin client</source>
<translation>黑币客户端</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to ExclusiveCoin network</source>
<translation><numerusform>与黑币网络建立了 %n 个连接</numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>已下载 %1 个区块的交易记录</translation>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>权益增值中 <br>您的权重为 %1 <br>网络总权重为 %2<br>预计将在 %3 之后获得收益</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>未进行权益增值,因为钱包已锁定</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>未进行权益增值,因为钱包处于离线状态</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>未进行权益增值,因为钱包正在同步</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>未进行权益增值,因为钱包中没有成熟的黑币</translation>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n 秒前</numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About ExclusiveCoin card</source>
<translation>关于黑币卡</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about ExclusiveCoin card</source>
<translation>显示关于黑币卡的信息</translation>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation>解锁钱包(&U)</translation>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n 分钟前</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n 小时前</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n 天前</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>已是最新</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>更新中...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>最近生成的区块接收于%1</translation>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>该笔交易数据量太大,需支付%1手续费给执行该笔交易的网络结点。您愿意支付吗?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>手续费确认</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>发送交易</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>流入交易</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>日期: %1
金额: %2
类别: %3
地址: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI处理</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid ExclusiveCoin address or malformed URI parameters.</source>
<translation>无法解析URI:无效的黑币地址或错误的URI参数。</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>钱包已被<b>加密</b>,当前为<b>解锁</b>状态</translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>钱包已被<b>加密</b>,当前为<b>锁定</b>状态</translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>备份钱包</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>钱包数据文件(*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>备份失败</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>试图将钱包地址保存到新位置时出现错误</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation><numerusform>%n秒</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n 分钟</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n 小时</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n 天</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation>未进行权益增值</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. ExclusiveCoin can no longer continue safely and will quit.</source>
<translation>发生严重错误,黑币客户端即将关闭。</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>网络警报</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>黑币控制</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>总量:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>字节:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>金额:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>优先级:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>费用:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>低输出</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>否</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>加上交易费用后:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>变更 : </translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(不)全选</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>树状模式</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>列表模式</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>金额</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>确认</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>已确认</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>优先级</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>复制地址</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>复制标签</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>复制金额</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>复制交易编号</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>复制金额</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>复制交易费</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>复制含交易费的金额</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>复制字节</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>复制优先级</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>复制低输出</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>复制零钱</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>最高</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>高</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>中高</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>中等</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>中低</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>低</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>最低</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>DUST</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>是</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>交易数据量超过10000字节时,该标签变为红色。
此时每kb数据量将会收取 %1 的手续费。
可能有+/-1字节的误差。</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>优先度较高的交易有更高可能进入到区块中。
当优先度为中级以下时,该标签变为红色。
此时需要收取每kb %1 的手续费。</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>如果收款人所收款项少于 %1,该标签变为红色。
此时需收取 %2 的手续费。
低于该手续费的0.546倍的款项将被显示为DUST。</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>如果零钱少于 %1,该标签变为红色。
此时需收取 %2 的手续费。</translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>来自%1的零钱 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(零钱)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>编辑地址</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>标签(&L)</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>地址簿内该项目对应的标签</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>地址(&A)</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>地址簿内该项目对应的地址。只有“收款人地址”分类下的地址可以修改。</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>新建接收地址</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>新建发送地址</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>编辑接收地址</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>编辑发送地址</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>输入的地址“%1”已经存在于地址簿中。</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid ExclusiveCoin address.</source>
<translation>“%1” 不是有效的黑币地址。</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>无法解锁钱包</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>新的密钥生成失败。</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>ExclusiveCoin-Qt</source>
<translation>黑币客户端ExclusiveCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>版本</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>使用</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>命令行选项</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>用户界面选项</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>设定语言,例如 “de_DE" (默认语言为本地操作系统语言)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>启动时最小化</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>登录时显示Logo界面 (默认开启)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>选项</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>主要(&M)</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. Fee 0.01 recommended.</source>
<translation>支付可选的交易手续费以加速交易(每kB)。大多数交易的数据量为1kB。推荐额0.01。</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>支付交易费用(&F)</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>保留金额不参与权益累积,可以随时使用。</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>保留</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start ExclusiveCoin after logging in to the system.</source>
<translation>开机自动启动黑币客户端</translation>
</message>
<message>
<location line="+3"/>
<source>&Start ExclusiveCoin on system login</source>
<translation>开机时自动启动黑币客户端(&S)</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>关机时断开区块和地址数据连接使得它们可以被移动到其他目录。这样做会使关机速度变慢。钱包数据总是断开存储的。</translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>关机时断开区块和地址数据库连接(&D)</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>网络(&N)</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the ExclusiveCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>路由器自动打开黑币客户端端口。该功能仅在路由器开启UPnP支持时有效。</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>使用 &UPnP 映射端口</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the ExclusiveCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>经SOCKS代理连接到黑币网络(例如使用Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>经SOCKS代理连接(&C)</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>代理服务器 &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>代理地址(如:127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>端口(&P):</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>代理端口(例如 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>Socks 版本(&V):</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Socks 代理版本(例如 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>窗口(&W)</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>最小化窗口后仅显示托盘图标</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>最小化到托盘(&M)</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>当窗口关闭时程序最小化而不是退出。当使用该选项时,程序只能通过在菜单中选择退出来关闭</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>单击关闭按钮最小化(&I)</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>显示(&D)</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>用户界面语言(&L):</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting ExclusiveCoin.</source>
<translation>在此设置用户界面语言。重启黑币客户端后设置生效。</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>黑币金额单位(&U):</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>选择黑币单位。</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show ExclusiveCoin addresses in the transaction list or not.</source>
<translation>是否在交易列表中显示黑币地址</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>在交易清单中显示黑币地址(&D)</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>是否需要交易源地址控制功能。</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>显示黑币控制选项(仅用于专家用户)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>确定(&O)</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>取消(&C)</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>应用(&A)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>默认</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting ExclusiveCoin.</source>
<translation>重启客户端后设置生效</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>提供的代理服务器地址无效。</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>表单</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the ExclusiveCoin network after a connection is established, but this process has not completed yet.</source>
<translation>所显示的信息尚未更新,建立连接后钱包客户端会自动和网络进行同步,但目前该过程尚未完成。</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation>用于权益累积:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>未确认:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>钱包</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>可用金额:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>您当前可使用的余额</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>未成熟的:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>尚未成熟的挖矿收入余额</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>总额:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>您当前的总余额</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>最近交易记录</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>尚未确认的交易总额(不计入目前钱包余额)</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>正在进行权益累积的货币总额(不计入目前钱包余额)</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>数据未同步</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR二维码对话框</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>请求支付</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>金额:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>标签:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>信息:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>另存为(&S)...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>URI编为QR二维码时出错。</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>输入的金额无效,请检查。</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>生成的URI过长,请减短标签或消息的长度。</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>保存QR二维码</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG图片(*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>客户端名称</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>不可用</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>客户端版本</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>信息(&I)</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>使用 OpenSSL 版本</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>启动时间</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>网络</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>连接数</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>测试网</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>数据链</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>当前数据块数量</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>预计数据块数量</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>上一数据块时间</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>打开(&O)</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>命令行选项</translation>
</message>
<message>
<location line="+7"/>
<source>Show the ExclusiveCoin-Qt help message to get a list with possible ExclusiveCoin command-line options.</source>
<translation>显示关于命令行选项的帮助信息。</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>显示(&S)</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>控制台(&C)</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>创建时间</translation>
</message>
<message>
<location line="-104"/>
<source>ExclusiveCoin - Debug window</source>
<translation>黑币客户端-调试窗口</translation>
</message>
<message>
<location line="+25"/>
<source>ExclusiveCoin Core</source>
<translation>黑币核心进程</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>调试日志文件</translation>
</message>
<message>
<location line="+7"/>
<source>Open the ExclusiveCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>打开调试日志文件,对于较大的文件,这可能持续几秒钟。</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>清空控制台</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the ExclusiveCoin RPC console.</source>
<translation>欢迎使用黑币RPC控制台。</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>使用上下方向键浏览历史, <b>Ctrl-L</b>清除屏幕。</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>使用 <b>help</b> 命令显示帮助信息。</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>发送货币</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>交易源地址控制功能</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>输入...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>自动选择</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>存款不足!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>总量:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>字节:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>金额:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 hack</source>
<translation>123.456 hack {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>优先级:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>中等</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>费用:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>低输出</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>no</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>加上交易费用后:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>零钱</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>自定义零钱地址</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>一次发送给多个接收者</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>添加收款人(&R)</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>删除所有交易区域</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>清除所有(&A)</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>余额:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 hack</source>
<translation>123.456 hack</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>确认并发送货币</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>发送(&E)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a ExclusiveCoin address (e.g. ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>输入黑币地址(例如:ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>复制金额</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>复制金额</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>复制交易费</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>复制含交易费的金额</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>复制字节</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>复制优先级</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>复制低输出</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>复制零钱</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> 至 %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>确认发送货币</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>确认要发送 %1 ?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>和</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>收款人地址不合法,请检查。</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>支付金额必须大于0。</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>金额超出您的账上余额。</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>计入 %1 交易费后的金额超出您的账上余额。</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>发现重复的地址, 每次只能对同一地址发送一次。</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>错误:交易创建失败。</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>错误:交易被拒绝。可能由于钱包中部分金额已被使用,例如您使用了钱包数据的副本,在副本中某些金额已被使用,但在此处尚未被标记为已使用。</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid ExclusiveCoin address</source>
<translation>警告:无效的黑币地址</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>警告:未知的零钱地址</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>表单</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>金额(&M)</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>付给(&T):</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>为这个地址输入一个标签,以便将它添加到您的地址簿</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>标签(&L):</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>收款人地址(例:ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>从地址簿选择地址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>从剪贴板粘贴地址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>删除收款人</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a ExclusiveCoin address (e.g. ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>输入一个黑币地址 (例:ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>签名 - 为消息签名/验证签名消息</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>签名消息(&S)</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>您可以用你的地址对消息进行签名,以证明您是该地址的所有人。注意不要对模棱两可的消息签名,以免遭受钓鱼式攻击。请确保消息内容准确的表达了您的真实意愿。</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>用来签名该消息的地址(例: ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>从地址簿里选择一个地址</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>从剪贴板粘贴地址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>请输入您要发送的签名消息</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>复制当前签名至剪切板</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this ExclusiveCoin address</source>
<translation>对该消息进行签名以证明您对该黑币地址的所有权</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>清空所有签名消息栏</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>清除所有(&A)</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>验证消息(&V)</translation>
</message>
<message>
<location line="-64"/>
<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>在下面输入签名地址,消息(请确保换行符、空格符、制表符等等一个不漏)和签名以验证消息。请确保签名信息准确,提防中间人攻击。</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>用来签名该消息的黑币地址(例: ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified ExclusiveCoin address</source>
<translation>确认该消息以保证它经由指定的黑币地址签名</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>清空所有验证消息栏</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a ExclusiveCoin address (e.g. ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>输入黑币地址(例: ExclusiveCoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>单击“签名消息“产生签名。</translation>
</message>
<message>
<location line="+3"/>
<source>Enter ExclusiveCoin signature</source>
<translation>输入黑币签名</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>输入的地址非法。</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>请检查地址后重试。</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>输入的地址没有关联的公私钥对。</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>钱包解锁动作取消。</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>找不到输入地址关联的私钥。</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>消息签名失败。</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>消息已签名。</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>签名无法解码。</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>请检查签名后重试。</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>签名与消息摘要不匹配。</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>消息验证失败。</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>消息验证成功。</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>至 %1 个数据块时开启</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>为 %n 个数据块开启</numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>发现冲突</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1 / 离线</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/未确认</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 已确认</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>状态</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>通过 %n 个节点广播</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>源</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>生成</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>来自</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>到</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>自己的地址</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>标签</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>收入</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>将在 %n 个数据块后成熟</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>未被接受</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>支出</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>交易费</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>净额</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>消息</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>备注</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>交易ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 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>通过权益累积获得的金额需要在510个块确认后方可使用。此数据块生成时,将被广播到网络并加入区块链。如果未能成功加入区块链,其状态会显示为“未接受”,该部分金额也不可被使用。如果其他节点在您生成区块后的几秒钟内也生成了区块,这种情况会偶尔发生。</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>调试信息</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>交易</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>输入</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>金额</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>正确</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>错误</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>,未被成功广播</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>未知</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>交易细节</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>当前面板显示了交易的详细信息</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>类型</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>数量</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>至 %1 个数据块时开启</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>已确认 (%1 条确认信息)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>为 %n 个更多的区块开启</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>掉线</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>未确认的 </translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>确认中 (推荐 %2个确认,已经有 %1个确认)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>冲突的</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>未成熟 (%1 个确认,将在 %2 个后可用)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>此数据块未被任何其他节点接收,可能不被接受!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>已生成但未被接受</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>接收于</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>收款来自</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>发送给</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>付款给自己</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>挖矿所得</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(不可用)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>交易状态。 鼠标移到此区域可显示确认项数量。</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>接收到交易的时间</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>交易类别。</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>交易目的地址。</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>从余额添加或移除的金额。</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>全部</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>今天</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>本周</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>本月</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>上月</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>今年</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>范围...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>接收于</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>发送给</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>到自己</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>挖矿所得</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>其他</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>输入地址或标签进行搜索</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>最小金额</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>复制地址</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>复制标签</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>复制金额</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>复制交易编号</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>编辑标签</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>显示交易详情</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>输出交易数据</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗号分隔文件 (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>已确认</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>类别</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>金额</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>导出出现错误</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>无法写入文件 %1 。</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>范围:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>到</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>正在发送</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>ExclusiveCoin version</source>
<translation>黑币客户端 版本</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>使用:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or ExclusiveCoind</source>
<translation>向-server服务器或ExclusiveCoind发送命令</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>列出命令
</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>获得某条命令的帮助
</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>选项:
</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: ExclusiveCoin.conf)</source>
<translation>指定配置文件(默认: ExclusiveCoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: ExclusiveCoind.pid)</source>
<translation>指定pid文件(默认: ExclusiveCoind.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>指定钱包文件(数据目录内)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>指定数据目录
</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>设置数据库缓冲区大小 (缺省: 25MB)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>设置数据库日志文件大小(单位MB,默认值100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>监听<port>端口的连接 (默认: 15714 测试网: 25714)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>最大连接数 <n> (缺省: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>连接一个节点并获取对端地址,然后断开连接</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>指定您的公共地址</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>以IPv6 [host]:端口绑定给定地址</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation>进行权益累积以支持黑币网络并获得报酬(默认: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>断开出现问题节点阀值(缺省: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Number of seconds to keep misbehaving peers from reconnecting (缺省: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>设置RPC监听端口%u时发生错误, IPv4:%s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>离线保存区块和地址数据库. 增加关机时间。 (默认: 0)</translation>
</message>
<message>
<location line="+109"/>
<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>错误:交易被拒绝。可能由于钱包中部分金额已被使用,例如您使用了钱包数据的副本,在副本中某些金额已被使用,但在此处尚未被标记为已使用。</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>错误:该笔交易需至少支付 %s 的手续费。</translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>监听 <port> 端口的JSON-RPC连接 (默认: 15715 测试网: 25715)</translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>接受命令行和 JSON-RPC 命令
</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>错误:交易创建失败。</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>错误:钱包已锁定,无法创建交易。</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>正在导入区块链数据文件</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>正在导入高速区块链数据文件</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>在后台运行并接受命令
</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>使用测试网络
</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>接受来自外部的连接 (缺省: 如果不带 -proxy or -connect 参数设置为1)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>在IPv6模式下设置RPC监听端口 %u 失败,返回到IPv4模式: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>数据库环境 %s 初始化错误。要修复,备份该目录并将其下除wallet.dat以外的文件全部删除。</translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>设置高优先度/低手续费交易的最大字节数 (默认: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>警告:-paytxfee 交易费设置得太高了!每笔交易都将支付交易费。</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong ExclusiveCoin will not work properly.</source>
<translation>警告:请确认您计算机的本地时间。如果时钟错误,黑币客户端将不能正常工作。</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>警告:钱包文件wallet.dat读取失败!最重要的公钥、私钥数据都没有问题,但是交易记录或地址簿数据不正确,或者存在数据丢失。</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>警告:钱包文件wallet.dat损坏! 原始的钱包文件已经备份到%s目录下并重命名为{timestamp}.bak 。如果您的账户余额或者交易记录不正确,请使用您的钱包备份文件恢复。</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>尝试从损坏的钱包文件wallet.dat中恢复私钥</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>数据块创建选项:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>仅连接到指定节点</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>发现自己的IP地址(缺省:不带 -externalip 参数监听时设置为1)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>监听端口失败。请使用 -listen=0 参数。</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>以DNS查找方式寻找节点 (默认:1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>同步检测点政策 (默认:严格)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>无效的 -tor 地址: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>-reservebalance=<amount> 金额无效</translation>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>每个连接的最大接收缓存,<n>*1000 字节(缺省:5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>每个连接的最大发送缓存,<n>*1000 字节(缺省:1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>仅连接至指定网络的节点<net>(IPv4, IPv6 或者 Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>输出额外的调试信息。相当于开启了其它所有-debug选项</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>输出额外的网络调试信息</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>将时间信息加入调试输出中</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL选项:(参见Bitcoin Wiki关于SSL设置栏目)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>选择要使用的SOCKS代理版本 (4-5, 默认 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>跟踪/调试信息输出到控制台,不输出到 debug.log 文件</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>发送跟踪/调试信息给调试者</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>设置最大区块大小 (默认:250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>设置最小数据块大小(缺省:0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>客户端启动时压缩debug.log文件(缺省:no-debug模式时为1)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>设置连接超时时间(缺省:5000毫秒)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>无法为记录点签名,错误的记录点密钥。</translation>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>使用UPnP映射监听端口 (缺省: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>使用UPnp映射监听端口(缺省: 监听状态设为1)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>开启代理以使用隐藏服务 (默认: 和-proxy设置相同)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC 连接用户名</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>正在检查数据库完整性...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>警告:检测到同步记录点错误,已跳过。</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>警告:磁盘空间低。</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>警告:该软件版本已过时,请升级!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>钱包文件wallet.dat损坏,抢救备份失败</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC 连接密码
</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=ExclusiveCoinrpc
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 "ExclusiveCoin Alert" admin@foo.com
</source>
<translation>%s, 必须在配置文件里设置rpc密码:
%s
建议使用如下的随机密码:
rpcuser=ExclusiveCoinrpc
rpcpassword=%s
(不需要记住该密码)
用户名和密码不能重复。
如果该文件不存在,请自行创建并设为用户本身只读权限。
建议创建提示以监测可能的问题,如:
alertnotify=echo %%s | mail -s "ExclusiveCoin Alert" admin@foo.com
</translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>寻找使用互联网接力聊天的节点 (默认: 1) {0)?}</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>自动和其它节点同步时间。如果本地计算机世界是准确的,建议关闭。(默认: 1)</translation>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>创建交易时自动忽略该值以下的数额 (默认:0.01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>允许从指定IP接受到的 JSON-RPC 连接</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>向IP地址为 <ip> 的节点发送指令 (缺省: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>当最佳数据块变化时执行命令 (命令行中的 %s 会被替换成数据块哈希值)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>当最佳区块变化时执行命令 (命令行中的 %s 会被替换成区块哈希值)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>要求对零钱进行确认 (默认:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation>强制要求交易脚本使用标准PUSH算子 (默认:1)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>收到相关提示时执行命令 (命令中的%s将被信息替换)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>将钱包升级到最新的格式</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>设置密钥池大小为 <n> (缺省: 100)
</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>重新扫描区块链以查找遗漏的钱包交易</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>启动时检测的区块数量 (默认: 2500, 0表示检测全部)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>区块确认的彻底程度 (0-6, 默认: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>从外部 blk000?.dat 文件导入区块</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>为 JSON-RPC 连接使用 OpenSSL (https) 连接</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>服务器证书 (默认为 server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>服务器私钥 (默认为 server.pem)
</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>可用加密算法 (默认: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>错误:无法创建交易,已解锁的钱包仅用于权益累积。</translation>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>警告:发现无效的记录点。所显示的交易信息未必正确!请升级客户端或联系开发者。</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>本帮助信息
</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>钱包 %s 位于数据目录 %s 之外.</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. ExclusiveCoin is probably already running.</source>
<translation>无法从数据目录 %s 获得锁定. 黑币客户端可能已在运行中.</translation>
</message>
<message>
<location line="-98"/>
<source>ExclusiveCoin</source>
<translation>黑币</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>无法绑定本机端口 %s (返回错误消息 %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>通过socks代理连接</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>使用 -addnode, -seednode 和 -connect 选项时允许查询DNS</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>正在加载地址簿...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>blkindex.dat 文件加载出错</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat 钱包文件加载出错:钱包损坏</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of ExclusiveCoin</source>
<translation>wallet.dat 钱包文件加载出错:需要新版本的客户端</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart ExclusiveCoin to complete</source>
<translation>需要重写钱包,重启客户端以完成该操作。</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat 钱包文件加载出错</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>无效的代理地址:%s</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet 指定的是未知网络:%s</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>被指定的是未知socks代理版本: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>无法解析 -bind 端口地址: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>无法解析 -externalip 地址: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>非法金额 -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>错误:无法启动节点</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>正在发送</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>无效金额</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>金额不足</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>正在加载数据块索引...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>添加节点并与其保持连接</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. ExclusiveCoin is probably already running.</source>
<translation>无法绑定到该计算机上的 %s. 黑币客户端可能已在运行中。</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>每kB交易所支付的手续费</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>无效的数量。 -mininput=<amount>: '%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>正在加载钱包...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>无法降级钱包</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>无法初始化密钥池。</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>无法写入默认地址</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>正在重新扫描...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>加载完成</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>使用 %s 选项</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>错误</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>您必须在配置文件中加入选项 rpcpassword :
%s
如果配置文件不存在,请新建,并将文件权限设置为仅允许文件所有者读取.</translation>
</message>
</context>
</TS> | mit |
yassdg/cert-sn | app/cache/dev/appDevUrlGenerator.php | 39806 | <?php
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Psr\Log\LoggerInterface;
/**
* appDevUrlGenerator
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlGenerator extends Symfony\Component\Routing\Generator\UrlGenerator
{
private static $declaredRoutes = array(
'_wdt' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/_wdt', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_home' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:homeAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_search' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:searchAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/search', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_search_bar' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/search_bar', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_purge' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/purge', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_info' => array ( 0 => array ( 0 => 'about', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:infoAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'about', ), 1 => array ( 0 => 'text', 1 => '/_profiler/info', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_phpinfo' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/phpinfo', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_search_results' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/search/results', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:panelAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_router' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.router:panelAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/router', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_exception' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.exception:showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/exception', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),),
'_profiler_exception_css' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.exception:cssAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/exception.css', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),),
'_configurator_home' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_configurator/', ), ), 4 => array ( ), 5 => array ( ),),
'_configurator_step' => array ( 0 => array ( 0 => 'index', ), 1 => array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'index', ), 1 => array ( 0 => 'text', 1 => '/_configurator/step', ), ), 4 => array ( ), 5 => array ( ),),
'_configurator_final' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_configurator/final', ), ), 4 => array ( ), 5 => array ( ),),
'_twig_error_test' => array ( 0 => array ( 0 => 'code', 1 => '_format', ), 1 => array ( '_controller' => 'twig.controller.preview_error:previewErrorPageAction', '_format' => 'html', ), 2 => array ( 'code' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '.', 2 => '[^/]++', 3 => '_format', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'code', ), 2 => array ( 0 => 'text', 1 => '/_error', ), ), 4 => array ( ), 5 => array ( ),),
'document' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/document/', ), ), 4 => array ( ), 5 => array ( ),),
'document_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/document', ), ), 4 => array ( ), 5 => array ( ),),
'document_new' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::newAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/document/new', ), ), 4 => array ( ), 5 => array ( ),),
'document_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::createAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/document/create', ), ), 4 => array ( ), 5 => array ( ),),
'document_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/document', ), ), 4 => array ( ), 5 => array ( ),),
'document_update' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::updateAction', ), 2 => array ( '_method' => 'POST|PUT', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/document', ), ), 4 => array ( ), 5 => array ( ),),
'document_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\DocumentController::deleteAction', ), 2 => array ( '_method' => 'POST|DELETE', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/document', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_accueil' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_apropos' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::aproposAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/apropos', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_services' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::servicesAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/services', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_partenaires' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::partenairesAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/partenaires', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_contact' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::contactAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/contact', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_declarer' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::declarerAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/di', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_ListingIncident' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::listerIncidentAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/li', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_ListingVulnerabilite' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::listerVulnerabiliteAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/listeVulnerabilite', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_ListeAlerte' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::listeAlerteAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/alertes', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_ListeAnnonce' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::listeAnnonceAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/annonces', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_articles' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::listeArticlesAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/incident/articles', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_voirAlerte' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::voirAlerteAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/voirAlerte', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_voirVulnerabilite' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::voirVulnerabiliteAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/voirVulnerabilite', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), ), 4 => array ( ), 5 => array ( ),),
'cert_incident_voirAnnonce' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\IncidentController::annonceAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/annonce', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), ), 4 => array ( ), 5 => array ( ),),
'sdz_blog_homepage' => array ( 0 => array ( 0 => 'name', ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\DefaultController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'name', ), 1 => array ( 0 => 'text', 1 => '/blog/hello', ), ), 4 => array ( ), 5 => array ( ),),
'sdzblog_accueil' => array ( 0 => array ( 0 => 'page', ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\BlogController::indexAction', 'page' => 1, ), 2 => array ( 'page' => '\\d*', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d*', 3 => 'page', ), 1 => array ( 0 => 'text', 1 => '/blog', ), ), 4 => array ( ), 5 => array ( ),),
'sdzblog_voir' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\BlogController::voirAction', ), 2 => array ( 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/blog/article', ), ), 4 => array ( ), 5 => array ( ),),
'sdzblog_ajouter' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\BlogController::ajouterAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/blog/ajouter', ), ), 4 => array ( ), 5 => array ( ),),
'sdzblog_modifier' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\BlogController::modifierAction', ), 2 => array ( 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/blog/modifier', ), ), 4 => array ( ), 5 => array ( ),),
'sdzblog_supprimer' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\BlogController::supprimerAction', ), 2 => array ( 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/blog/supprimer', ), ), 4 => array ( ), 5 => array ( ),),
'sdzblog_voir_slug' => array ( 0 => array ( 0 => 'annee', 1 => 'slug', 2 => 'format', ), 1 => array ( '_controller' => 'Sdz\\BlogBundle\\Controller\\BlogController::voirSlugAction', 'format' => 'html', ), 2 => array ( 'annee' => '\\d{4}', 'format' => 'html|xml', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '.', 2 => 'html|xml', 3 => 'format', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/\\.]++', 3 => 'slug', ), 2 => array ( 0 => 'variable', 1 => '/', 2 => '\\d{4}', 3 => 'annee', ), 3 => array ( 0 => 'text', 1 => '/blog', ), ), 4 => array ( ), 5 => array ( ),),
'homepage' => array ( 0 => array ( ), 1 => array ( '_controller' => 'AppBundle\\Controller\\DefaultController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/articles/', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/articles', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles_new' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::newAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/articles/new', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::createAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/articles/create', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/articles', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles_update' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::updateAction', ), 2 => array ( '_method' => 'POST|PUT', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/articles', ), ), 4 => array ( ), 5 => array ( ),),
'admin_articles_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\ArticlesController::deleteAction', ), 2 => array ( '_method' => 'POST|DELETE', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/articles', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/users/', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/users', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users_new' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::newAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/users/new', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::createAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/users/create', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/users', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users_update' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::updateAction', ), 2 => array ( '_method' => 'POST|PUT', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/users', ), ), 4 => array ( ), 5 => array ( ),),
'admin_users_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\UserBundle\\Controller\\UserController::deleteAction', ), 2 => array ( '_method' => 'POST|DELETE', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/users', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_security_login' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::loginAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/login', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_security_check' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::checkAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/login_check', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_security_logout' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::logoutAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/logout', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_profile_show' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ProfileController::showAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/profile/', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_profile_edit' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ProfileController::editAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/profile/edit', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_registration_register' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::registerAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/register/', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_registration_check_email' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::checkEmailAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/register/check-email', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_registration_confirm' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::confirmAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/register/confirm', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_registration_confirmed' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::confirmedAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/register/confirmed', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_resetting_request' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::requestAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/resetting/request', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_resetting_send_email' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::sendEmailAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/resetting/send-email', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_resetting_check_email' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::checkEmailAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/resetting/check-email', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_resetting_reset' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::resetAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/resetting/reset', ), ), 4 => array ( ), 5 => array ( ),),
'fos_user_change_password' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ChangePasswordController::changePasswordAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/profile/change-password', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/annonce/', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/annonce', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce_new' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::newAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/annonce/new', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::createAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/annonce/create', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/annonce', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce_update' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::updateAction', ), 2 => array ( '_method' => 'POST|PUT', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/annonce', ), ), 4 => array ( ), 5 => array ( ),),
'admin_annonce_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AnnonceController::deleteAction', ), 2 => array ( '_method' => 'POST|DELETE', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/annonce', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/vulnerabilite/', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/vulnerabilite', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite_new' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::newAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/vulnerabilite/new', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::createAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/vulnerabilite/create', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/vulnerabilite', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite_update' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::updateAction', ), 2 => array ( '_method' => 'POST|PUT', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/vulnerabilite', ), ), 4 => array ( ), 5 => array ( ),),
'admin_vulnerabilite_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\VulnerabiliteController::deleteAction', ), 2 => array ( '_method' => 'POST|DELETE', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/vulnerabilite', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/alerte/', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/alerte', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte_new' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::newAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/alerte/new', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::createAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/alerte/create', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/alerte', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte_update' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::updateAction', ), 2 => array ( '_method' => 'POST|PUT', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/alerte', ), ), 4 => array ( ), 5 => array ( ),),
'admin_alerte_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Cert\\IncidentBundle\\Controller\\AlerteController::deleteAction', ), 2 => array ( '_method' => 'POST|DELETE', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/alerte', ), ), 4 => array ( ), 5 => array ( ),),
);
/**
* Constructor.
*/
public function __construct(RequestContext $context, LoggerInterface $logger = null)
{
$this->context = $context;
$this->logger = $logger;
}
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (!isset(self::$declaredRoutes[$name])) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}
list($variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes) = self::$declaredRoutes[$name];
return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);
}
}
| mit |
microsoft/vscode | src/vs/workbench/api/browser/mainThreadWindow.ts | 2669 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { ExtHostContext, ExtHostWindowShape, IOpenUriOptions, MainContext, MainThreadWindowShape } from '../common/extHost.protocol';
import { IHostService } from 'vs/workbench/services/host/browser/host';
@extHostNamedCustomer(MainContext.MainThreadWindow)
export class MainThreadWindow implements MainThreadWindowShape {
private readonly proxy: ExtHostWindowShape;
private readonly disposables = new DisposableStore();
private readonly resolved = new Map<number, IDisposable>();
constructor(
extHostContext: IExtHostContext,
@IHostService private readonly hostService: IHostService,
@IOpenerService private readonly openerService: IOpenerService,
) {
this.proxy = extHostContext.getProxy(ExtHostContext.ExtHostWindow);
Event.latch(hostService.onDidChangeFocus)
(this.proxy.$onDidChangeWindowFocus, this.proxy, this.disposables);
}
dispose(): void {
this.disposables.dispose();
for (const value of this.resolved.values()) {
value.dispose();
}
this.resolved.clear();
}
$getWindowVisibility(): Promise<boolean> {
return Promise.resolve(this.hostService.hasFocus);
}
async $openUri(uriComponents: UriComponents, uriString: string | undefined, options: IOpenUriOptions): Promise<boolean> {
const uri = URI.from(uriComponents);
let target: URI | string;
if (uriString && URI.parse(uriString).toString() === uri.toString()) {
// called with string and no transformation happened -> keep string
target = uriString;
} else {
// called with URI or transformed -> use uri
target = uri;
}
return this.openerService.open(target, {
openExternal: true,
allowTunneling: options.allowTunneling,
allowContributedOpeners: options.allowContributedOpeners,
});
}
async $asExternalUri(uriComponents: UriComponents, options: IOpenUriOptions): Promise<UriComponents> {
const result = await this.openerService.resolveExternalUri(URI.revive(uriComponents), options);
return result.resolved;
}
}
| mit |
surin675/query | Model/16pf.php | 2297 | <?php
class Question16PF
{
public function sertQuestion16PF($group){
include("ConnectDatabase.php");
$sql_sert = "SELECT `q_16pf_id`, `question`, `choice1`, `choice2`, `choice3`, `pers_type`, `Positive`, `negative` FROM `question_16pf` WHERE `pers_type`='$group'";
$result = $conn->query($sql_sert);
return $result;
}
public function deleteQuestion16PF($ID){
include("ConnectDatabase.php");
$sqldelete = "DELETE FROM `question_16pf` WHERE `q_16pf_id` = $ID";
$result = $conn->query($sqldelete);
$conn->close();
}
public function insertQuestion16PF($q, $c1, $c2, $c3, $group, $p, $n){
include("ConnectDatabase.php");
$sqlInsert= "INSERT INTO `question_16pf` (`q_16pf_id`, `question`, `choice1`, `choice2`, `choice3`, `pers_type`, `positive`, `negative`) VALUES (NULL, '$q', '$c1', '$c2', '$c3', '$group', '$p', '$n');";
$result = $conn->query($sqlInsert);
$conn->close();
}
public function editQuestion16PF($id, $q, $c1, $c2, $c3){
include("ConnectDatabase.php");
$sqlInsert= "UPDATE `question_16pf` SET `question` = '$q', `choice1` = '$c1', `choice2` = '$c2', `choice3` = '$c3' WHERE `question_16pf`.`q_16pf_id` = '$id';";
$result = $conn->query($sqlInsert);
$conn->close();
}
public function checkQ16PF($question){
include("ConnectDatabase.php");
$sql_sert = "SELECT `q_16pf_id`, `question`, `choice1`, `choice2`, `choice3`, `pers_type`, `Positive`, `negative` FROM `question_16pf` WHERE `question`='$question'";
$result = $conn->query($sql_sert);
return $result;
}
public function checkQ16PFEdit($id, $question){
include("ConnectDatabase.php");
$sql_sert = "SELECT `q_16pf_id`, `question`, `choice1`, `choice2`, `choice3`, `pers_type`, `Positive`, `negative` FROM `question_16pf` WHERE `question`='$question' AND `q_16pf_id`<>'$id'";
$result = $conn->query($sql_sert);
return $result;
}
}
?> | mit |
AndrewZheng/vue-learn | gulpfile.js | 1887 | /**
* Created by andrew on 2017/9/17.
*/
'use strict';
var gulp = require('gulp');
var webpack = require('webpack');
//用于gulp传递参数
var minimist = require('minimist');
var gutil = require('gulp-util');
var src = process.cwd() + '/src';
var assets = process.cwd() + '/dist';
var knownOptions = {
string: 'env',
default: {env: process.env.NODE_ENV || 'production'}
};
var options = minimist(process.argv.slice(2), knownOptions);
var webpackConf = require('./webpack.config');
var webpackConfDev = require('./webpack-dev.config');
var webpackServer=require('webpack-dev-server');
var remoteServer = {
host: '172.16.10.191',
remotePath: '/www/tomcat/webapps/webpacktest',
user: 'root',
pass: 'fjKL32jKL132jKljK342L'
};
var localServer = webpackServer;
//check code
gulp.task('hint', function () {
var jshint = require('gulp-jshint')
var stylish = require('jshint-stylish')
return gulp.src([
'!' + src + '/scripts/lib/**/*.js',
src + '/scripts/**/*.js'
])
.pipe(jshint())
.pipe(jshint.reporter(stylish));
})
// clean assets
gulp.task('clean', ['hint'], function () {
var clean = require('gulp-clean');
return gulp.src(assets, {read: true}).pipe(clean())
});
//run webpack pack
gulp.task('pack', ['clean'], function (done) {
var _conf = options.env === 'production' ? webpackConf : webpackConfDev;
webpack(_conf, function (err, stats) {
if (err) throw new gutil.PluginError('webpack', err)
gutil.log('[webpack]', stats.toString({colors: true}))
done()
});
});
//default task
gulp.task('default', ['pack'])
//deploy assets to remote server
gulp.task('deploy', function () {
var sftp = require('gulp-sftp');
var _conf = options.env === 'production' ? remoteServer : localServer;
return gulp.src(assets + '/**')
.pipe(sftp(_conf))
}) | mit |
robwormald/gitrank | app/packages/npm/hoek@2.13.0/lib/index.js | 19261 | /* */
(function(Buffer, process) {
var Crypto = require("crypto");
var Path = require("path");
var Util = require("util");
var Escape = require("./escape");
var internals = {};
exports.clone = function(obj, seen) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
seen = seen || {
orig: [],
copy: []
};
var lookup = seen.orig.indexOf(obj);
if (lookup !== -1) {
return seen.copy[lookup];
}
var newObj;
var cloneDeep = false;
if (!Array.isArray(obj)) {
if (Buffer.isBuffer(obj)) {
newObj = new Buffer(obj);
} else if (obj instanceof Date) {
newObj = new Date(obj.getTime());
} else if (obj instanceof RegExp) {
newObj = new RegExp(obj);
} else {
var proto = Object.getPrototypeOf(obj);
if (!proto || proto.isImmutable) {
newObj = obj;
} else {
newObj = Object.create(proto);
cloneDeep = true;
}
}
} else {
newObj = [];
cloneDeep = true;
}
seen.orig.push(obj);
seen.copy.push(newObj);
if (cloneDeep) {
var keys = Object.getOwnPropertyNames(obj);
for (var i = 0,
il = keys.length; i < il; ++i) {
var key = keys[i];
var descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor.get || descriptor.set) {
Object.defineProperty(newObj, key, descriptor);
} else {
newObj[key] = exports.clone(obj[key], seen);
}
}
}
return newObj;
};
exports.merge = function(target, source, isNullOverride, isMergeArrays) {
exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
if (!source) {
return target;
}
if (Array.isArray(source)) {
exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
if (isMergeArrays === false) {
target.length = 0;
}
for (var i = 0,
il = source.length; i < il; ++i) {
target.push(exports.clone(source[i]));
}
return target;
}
var keys = Object.keys(source);
for (var k = 0,
kl = keys.length; k < kl; ++k) {
var key = keys[k];
var value = source[key];
if (value && typeof value === 'object') {
if (!target[key] || typeof target[key] !== 'object' || (Array.isArray(target[key]) ^ Array.isArray(value)) || value instanceof Date || Buffer.isBuffer(value) || value instanceof RegExp) {
target[key] = exports.clone(value);
} else {
exports.merge(target[key], value, isNullOverride, isMergeArrays);
}
} else {
if (value !== null && value !== undefined) {
target[key] = value;
} else if (isNullOverride !== false) {
target[key] = value;
}
}
}
return target;
};
exports.applyToDefaults = function(defaults, options, isNullOverride) {
exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
if (!options) {
return null;
}
var copy = exports.clone(defaults);
if (options === true) {
return copy;
}
return exports.merge(copy, options, isNullOverride === true, false);
};
exports.cloneWithShallow = function(source, keys) {
if (!source || typeof source !== 'object') {
return source;
}
var storage = internals.store(source, keys);
var copy = exports.clone(source);
internals.restore(copy, source, storage);
return copy;
};
internals.store = function(source, keys) {
var storage = {};
for (var i = 0,
il = keys.length; i < il; ++i) {
var key = keys[i];
var value = exports.reach(source, key);
if (value !== undefined) {
storage[key] = value;
internals.reachSet(source, key, undefined);
}
}
return storage;
};
internals.restore = function(copy, source, storage) {
var keys = Object.keys(storage);
for (var i = 0,
il = keys.length; i < il; ++i) {
var key = keys[i];
internals.reachSet(copy, key, storage[key]);
internals.reachSet(source, key, storage[key]);
}
};
internals.reachSet = function(obj, key, value) {
var path = key.split('.');
var ref = obj;
for (var i = 0,
il = path.length; i < il; ++i) {
var segment = path[i];
if (i + 1 === il) {
ref[segment] = value;
}
ref = ref[segment];
}
};
exports.applyToDefaultsWithShallow = function(defaults, options, keys) {
exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
exports.assert(keys && Array.isArray(keys), 'Invalid keys');
if (!options) {
return null;
}
var copy = exports.cloneWithShallow(defaults, keys);
if (options === true) {
return copy;
}
var storage = internals.store(options, keys);
exports.merge(copy, options, false, false);
internals.restore(copy, options, storage);
return copy;
};
exports.deepEqual = function(obj, ref, options, seen) {
options = options || {prototype: true};
var type = typeof obj;
if (type !== typeof ref) {
return false;
}
if (type !== 'object' || obj === null || ref === null) {
if (obj === ref) {
return obj !== 0 || 1 / obj === 1 / ref;
}
return obj !== obj && ref !== ref;
}
seen = seen || [];
if (seen.indexOf(obj) !== -1) {
return true;
}
seen.push(obj);
if (Array.isArray(obj)) {
if (!Array.isArray(ref)) {
return false;
}
if (obj.length !== ref.length) {
return false;
}
for (var i = 0,
il = obj.length; i < il; ++i) {
if (!exports.deepEqual(obj[i], ref[i])) {
return false;
}
}
return true;
}
if (Buffer.isBuffer(obj)) {
if (!Buffer.isBuffer(ref)) {
return false;
}
if (obj.length !== ref.length) {
return false;
}
for (var j = 0,
jl = obj.length; j < jl; ++j) {
if (obj[j] !== ref[j]) {
return false;
}
}
return true;
}
if (obj instanceof Date) {
return (ref instanceof Date && obj.getTime() === ref.getTime());
}
if (obj instanceof RegExp) {
return (ref instanceof RegExp && obj.toString() === ref.toString());
}
if (options.prototype) {
if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
return false;
}
}
var keys = Object.getOwnPropertyNames(obj);
if (keys.length !== Object.getOwnPropertyNames(ref).length) {
return false;
}
for (var k = 0,
kl = keys.length; k < kl; ++k) {
var key = keys[k];
var descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor.get) {
if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) {
return false;
}
} else if (!exports.deepEqual(obj[key], ref[key], options, seen)) {
return false;
}
}
return true;
};
exports.unique = function(array, key) {
var index = {};
var result = [];
for (var i = 0,
il = array.length; i < il; ++i) {
var id = (key ? array[i][key] : array[i]);
if (index[id] !== true) {
result.push(array[i]);
index[id] = true;
}
}
return result;
};
exports.mapToObject = function(array, key) {
if (!array) {
return null;
}
var obj = {};
for (var i = 0,
il = array.length; i < il; ++i) {
if (key) {
if (array[i][key]) {
obj[array[i][key]] = true;
}
} else {
obj[array[i]] = true;
}
}
return obj;
};
exports.intersect = function(array1, array2, justFirst) {
if (!array1 || !array2) {
return [];
}
var common = [];
var hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1);
var found = {};
for (var i = 0,
il = array2.length; i < il; ++i) {
if (hash[array2[i]] && !found[array2[i]]) {
if (justFirst) {
return array2[i];
}
common.push(array2[i]);
found[array2[i]] = true;
}
}
return (justFirst ? null : common);
};
exports.contain = function(ref, values, options) {
var valuePairs = null;
if (typeof ref === 'object' && typeof values === 'object' && !Array.isArray(ref) && !Array.isArray(values)) {
valuePairs = values;
values = Object.keys(values);
} else {
values = [].concat(values);
}
options = options || {};
exports.assert(arguments.length >= 2, 'Insufficient arguments');
exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
exports.assert(values.length, 'Values array cannot be empty');
var compare = options.deep ? exports.deepEqual : function(a, b) {
return a === b;
};
var misses = false;
var matches = new Array(values.length);
for (var i = 0,
il = matches.length; i < il; ++i) {
matches[i] = 0;
}
if (typeof ref === 'string') {
var pattern = '(';
for (i = 0, il = values.length; i < il; ++i) {
var value = values[i];
exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
pattern += (i ? '|' : '') + exports.escapeRegex(value);
}
var regex = new RegExp(pattern + ')', 'g');
var leftovers = ref.replace(regex, function($0, $1) {
var index = values.indexOf($1);
++matches[index];
return '';
});
misses = !!leftovers;
} else if (Array.isArray(ref)) {
for (i = 0, il = ref.length; i < il; ++i) {
for (var j = 0,
jl = values.length,
matched = false; j < jl && matched === false; ++j) {
matched = compare(ref[i], values[j]) && j;
}
if (matched !== false) {
++matches[matched];
} else {
misses = true;
}
}
} else {
var keys = Object.keys(ref);
for (i = 0, il = keys.length; i < il; ++i) {
var key = keys[i];
var pos = values.indexOf(key);
if (pos !== -1) {
if (valuePairs && !compare(ref[key], valuePairs[key])) {
return false;
}
++matches[pos];
} else {
misses = true;
}
}
}
var result = false;
for (i = 0, il = matches.length; i < il; ++i) {
result = result || !!matches[i];
if ((options.once && matches[i] > 1) || (!options.part && !matches[i])) {
return false;
}
}
if (options.only && misses) {
return false;
}
return result;
};
exports.flatten = function(array, target) {
var result = target || [];
for (var i = 0,
il = array.length; i < il; ++i) {
if (Array.isArray(array[i])) {
exports.flatten(array[i], result);
} else {
result.push(array[i]);
}
}
return result;
};
exports.reach = function(obj, chain, options) {
options = options || {};
if (typeof options === 'string') {
options = {separator: options};
}
var path = chain.split(options.separator || '.');
var ref = obj;
for (var i = 0,
il = path.length; i < il; ++i) {
var key = path[i];
if (key[0] === '-' && Array.isArray(ref)) {
key = key.slice(1, key.length);
key = ref.length - key;
}
if (!ref || !ref.hasOwnProperty(key) || (typeof ref !== 'object' && options.functions === false)) {
exports.assert(!options.strict || i + 1 === il, 'Missing segment', key, 'in reach path ', chain);
exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
ref = options.default;
break;
}
ref = ref[key];
}
return ref;
};
exports.formatStack = function(stack) {
var trace = [];
for (var i = 0,
il = stack.length; i < il; ++i) {
var item = stack[i];
trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
}
return trace;
};
exports.formatTrace = function(trace) {
var display = [];
for (var i = 0,
il = trace.length; i < il; ++i) {
var row = trace[i];
display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
}
return display;
};
exports.callStack = function(slice) {
var v8 = Error.prepareStackTrace;
Error.prepareStackTrace = function(err, stack) {
return stack;
};
var capture = {};
Error.captureStackTrace(capture, arguments.callee);
var stack = capture.stack;
Error.prepareStackTrace = v8;
var trace = exports.formatStack(stack);
if (slice) {
return trace.slice(slice);
}
return trace;
};
exports.displayStack = function(slice) {
var trace = exports.callStack(slice === undefined ? 1 : slice + 1);
return exports.formatTrace(trace);
};
exports.abortThrow = false;
exports.abort = function(message, hideStack) {
if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
throw new Error(message || 'Unknown error');
}
var stack = '';
if (!hideStack) {
stack = exports.displayStack(1).join('\n\t');
}
console.log('ABORT: ' + message + '\n\t' + stack);
process.exit(1);
};
exports.assert = function(condition) {
if (condition) {
return ;
}
if (arguments.length === 2 && arguments[1] instanceof Error) {
throw arguments[1];
}
var msgs = [];
for (var i = 1,
il = arguments.length; i < il; ++i) {
if (arguments[i] !== '') {
msgs.push(arguments[i]);
}
}
msgs = msgs.map(function(msg) {
return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg);
});
throw new Error(msgs.join(' ') || 'Unknown error');
};
exports.Timer = function() {
this.ts = 0;
this.reset();
};
exports.Timer.prototype.reset = function() {
this.ts = Date.now();
};
exports.Timer.prototype.elapsed = function() {
return Date.now() - this.ts;
};
exports.Bench = function() {
this.ts = 0;
this.reset();
};
exports.Bench.prototype.reset = function() {
this.ts = exports.Bench.now();
};
exports.Bench.prototype.elapsed = function() {
return exports.Bench.now() - this.ts;
};
exports.Bench.now = function() {
var ts = process.hrtime();
return (ts[0] * 1e3) + (ts[1] / 1e6);
};
exports.escapeRegex = function(string) {
return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
};
exports.base64urlEncode = function(value, encoding) {
var buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary'));
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
exports.base64urlDecode = function(value, encoding) {
if (value && !/^[\w\-]*$/.test(value)) {
return new Error('Invalid character');
}
try {
var buf = new Buffer(value, 'base64');
return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
} catch (err) {
return err;
}
};
exports.escapeHeaderAttribute = function(attribute) {
exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
};
exports.escapeHtml = function(string) {
return Escape.escapeHtml(string);
};
exports.escapeJavaScript = function(string) {
return Escape.escapeJavaScript(string);
};
exports.nextTick = function(callback) {
return function() {
var args = arguments;
process.nextTick(function() {
callback.apply(null, args);
});
};
};
exports.once = function(method) {
if (method._hoekOnce) {
return method;
}
var once = false;
var wrapped = function() {
if (!once) {
once = true;
method.apply(null, arguments);
}
};
wrapped._hoekOnce = true;
return wrapped;
};
exports.isAbsolutePath = function(path, platform) {
if (!path) {
return false;
}
if (Path.isAbsolute) {
return Path.isAbsolute(path);
}
platform = platform || process.platform;
if (platform !== 'win32') {
return path[0] === '/';
}
return !!/^(?:[a-zA-Z]:[\\\/])|(?:[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/])/.test(path);
};
exports.isInteger = function(value) {
return (typeof value === 'number' && parseFloat(value) === parseInt(value, 10) && !isNaN(value));
};
exports.ignore = function() {};
exports.inherits = Util.inherits;
exports.format = Util.format;
exports.transform = function(source, transform, options) {
exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source object: must be null, undefined, or an object');
var result = {};
var keys = Object.keys(transform);
for (var k = 0,
kl = keys.length; k < kl; ++k) {
var key = keys[k];
var path = key.split('.');
var sourcePath = transform[key];
exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings');
var segment;
var res = result;
while (path.length > 1) {
segment = path.shift();
if (!res[segment]) {
res[segment] = {};
}
res = res[segment];
}
segment = path.shift();
res[segment] = exports.reach(source, sourcePath, options);
}
return result;
};
exports.uniqueFilename = function(path, extension) {
if (extension) {
extension = extension[0] !== '.' ? '.' + extension : extension;
} else {
extension = '';
}
path = Path.resolve(path);
var name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
return Path.join(path, name);
};
exports.stringify = function() {
try {
return JSON.stringify.apply(null, arguments);
} catch (err) {
return '[Cannot display object: ' + err.message + ']';
}
};
exports.shallow = function(source) {
var target = {};
var keys = Object.keys(source);
for (var i = 0,
il = keys.length; i < il; ++i) {
var key = keys[i];
target[key] = source[key];
}
return target;
};
})(require("buffer").Buffer, require("process"));
| mit |
jgretz/ReactNativeInTheWild | code/app/src/features/shared/styles/loading.js | 158 | import {StyleSheet} from 'react-native';
export default StyleSheet.create({
loading: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
| mit |
anarchicknight/nativescript-texttospeech | demo/app/main-page.ts | 375 | import { EventData } from 'tns-core-modules/data/observable';
import { Page } from 'tns-core-modules/ui/page';
import { HelloWorldModel } from './main-view-model';
// Event handler for Page "navigatingTo" event attached in main-page.xml
export function navigatingTo(args: EventData) {
const page = args.object as Page;
page.bindingContext = new HelloWorldModel(page);
}
| mit |
dongdiemthuy/nutrixs-ng-admin | src/javascripts/test/e2e/spec.js | 1158 | describe('ng-admin', function() {
describe('Dashboard', function () {
it('should display a navigation menu linking to all entities', function () {
browser.get(browser.baseUrl);
$$('.nav li').then(function (items) {
expect(items.length).toBe(3);
expect(items[0].getText()).toBe('Posts');
expect(items[1].getText()).toBe('✉ Comments');
expect(items[2].getText()).toBe('Tags');
});
});
it('should display a panel for each entity with a list of recent items', function () {
browser.get(browser.baseUrl);
element.all(by.repeater('panel in dashboardController.panels')).then(function (panels) {
expect(panels.length).toBe(3);
expect(panels[0].all(by.css('.panel-heading')).first().getText()).toBe('Recent posts');
expect(panels[1].all(by.css('.panel-heading')).first().getText()).toBe('Last comments');
expect(panels[2].all(by.css('.panel-heading')).first().getText()).toBe('Recent tags');
});
});
});
});
| mit |
siddontang/polaris | router.go | 1922 | package polaris
import (
"fmt"
"net/http"
"regexp"
"strings"
)
type router struct {
literalLocs map[string]*location
regexpLocs []*location
app *App
}
func newRouter(app *App) *router {
r := new(router)
r.app = app
r.literalLocs = make(map[string]*location)
r.regexpLocs = make([]*location, 0)
return r
}
func (router *router) regLocation(l *location, pattern string) error {
meta := regexp.QuoteMeta(pattern)
if meta == pattern {
if _, ok := router.literalLocs[pattern]; ok {
return fmt.Errorf("literal %s location is registered already", pattern)
}
router.literalLocs[pattern] = l
} else {
if strings.HasPrefix(pattern, "^") {
pattern = "^" + pattern
}
if strings.HasSuffix(pattern, "$") {
pattern = pattern + "$"
}
for _, l := range router.regexpLocs {
if l.pattern == pattern {
return fmt.Errorf("regexp %s location is registered already", pattern)
}
}
var err error
l.regexpPattern, err = regexp.Compile(pattern)
if err != nil {
return err
}
router.regexpLocs = append(router.regexpLocs, l)
}
return nil
}
/*
handler must be a struct which has one or more methods below:
Get, Post, Put, Head, Delete
*/
func (router *router) Handle(pattern string, handler interface{}) error {
if len(pattern) == 0 {
return fmt.Errorf("pattern cannot be empty")
}
l, err := newLocation(pattern, handler)
if err != nil {
return err
}
l.app = router.app
if err = router.regLocation(l, pattern); err != nil {
return err
}
return nil
}
func (router *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if l, ok := router.literalLocs[path]; ok {
l.invoke(w, r)
} else {
for _, l := range router.regexpLocs {
args := l.regexpPattern.FindStringSubmatch(path)
if args != nil {
l.invoke(w, r, args[1:]...)
return
}
}
http.Error(w, "", http.StatusNotFound)
return
}
}
| mit |
stratumgs/stratumgs-python-client | sgsclient/example/tictactoe/manual.py | 2509 | """
.. module sgsclient.example.tictactoe.manual
An example client for TicTacToe that prompts the user for input.
When executed directly it will call :func:`sgsclient.main` with
``supported_games = ["tictactoe"]`` and ``max_games = 1``.
"""
import functools
from sgsclient import StratumGSClientInstance, main
_BOARD_TEMPLATE = "\n{} | {} | {}" \
"\n---------" \
"\n{} | {} | {}" \
"\n---------" \
"\n{} | {} | {}\n"
class TicTacToeClient(StratumGSClientInstance):
"""
An example TicTacToe client that prompts the user for input.
"""
def __init__(self, *args):
super(TicTacToeClient, self).__init__(*args)
self._board = None
self._winner = None
def server_closed_connection(self):
"""
Print out the end status of the game when the server closes the
connection.
"""
print("Game Over!")
if self._winner:
print("Player {} wins!".format(self._winner))
else:
print("Draw!")
def _make_move(self):
"""
Makes a move. Prompts the user for input until they provide a valid
move, then sends that move to the server.
"""
while True:
move = input("Your Move? (row, column) ")
try:
row, col = (int(x.strip()) for x in move.split(","))
except:
print("Invalid input value.")
continue
break
self.send_message_to_server({
"type": "move",
"row": row,
"column": col
})
def message_received_from_server(self, message):
"""
Handle a received message from the server.
"""
if message["type"] == "state":
self._board = message["board"]
self._winner = message["winner"]
elif message["type"] == "turn":
print("\nYour turn!")
board = list(map(lambda x: x or " ",
functools.reduce(lambda x, y: x+y, self._board, [])))
print(_BOARD_TEMPLATE.format(*board))
self._make_move()
elif message["type"] == "repeat-turn":
print("The server rejected your last move.")
print("The error was:", message["error"])
self._make_move()
if __name__ == "__main__":
main(TicTacToeClient, supported_games=["tictactoe"], max_games=1)
| mit |
sh0umik/fhir-protobuff | goal.pb.go | 14072 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: goal.proto
package buffer
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
type Goal struct {
Status string `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"`
Category []*Category `protobuf:"bytes,2,rep,name=category" json:"category,omitempty"`
OutcomeReference []*OutcomeReference `protobuf:"bytes,3,rep,name=outcomeReference" json:"outcomeReference,omitempty"`
Addresses []*Addresses `protobuf:"bytes,4,rep,name=addresses" json:"addresses,omitempty"`
Description *Description `protobuf:"bytes,5,opt,name=description" json:"description,omitempty"`
StartDate string `protobuf:"bytes,6,opt,name=startDate" json:"startDate,omitempty"`
ResourceType string `protobuf:"bytes,7,opt,name=resourceType" json:"resourceType,omitempty"`
Text *Text `protobuf:"bytes,8,opt,name=text" json:"text,omitempty"`
ExpressedBy *ExpressedBy `protobuf:"bytes,9,opt,name=expressedBy" json:"expressedBy,omitempty"`
StatusReason string `protobuf:"bytes,10,opt,name=statusReason" json:"statusReason,omitempty"`
Priority *Priority `protobuf:"bytes,11,opt,name=priority" json:"priority,omitempty"`
Target *Target `protobuf:"bytes,12,opt,name=target" json:"target,omitempty"`
StatusDate string `protobuf:"bytes,13,opt,name=statusDate" json:"statusDate,omitempty"`
Identifier []*Identifier `protobuf:"bytes,14,rep,name=identifier" json:"identifier,omitempty"`
Id string `protobuf:"bytes,15,opt,name=id" json:"id,omitempty"`
Subject *Subject `protobuf:"bytes,16,opt,name=subject" json:"subject,omitempty"`
Meta *Meta `protobuf:"bytes,17,opt,name=meta" json:"meta,omitempty"`
}
func (m *Goal) Reset() { *m = Goal{} }
func (m *Goal) String() string { return proto.CompactTextString(m) }
func (*Goal) ProtoMessage() {}
func (*Goal) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{0} }
func (m *Goal) GetStatus() string {
if m != nil {
return m.Status
}
return ""
}
func (m *Goal) GetCategory() []*Category {
if m != nil {
return m.Category
}
return nil
}
func (m *Goal) GetOutcomeReference() []*OutcomeReference {
if m != nil {
return m.OutcomeReference
}
return nil
}
func (m *Goal) GetAddresses() []*Addresses {
if m != nil {
return m.Addresses
}
return nil
}
func (m *Goal) GetDescription() *Description {
if m != nil {
return m.Description
}
return nil
}
func (m *Goal) GetStartDate() string {
if m != nil {
return m.StartDate
}
return ""
}
func (m *Goal) GetResourceType() string {
if m != nil {
return m.ResourceType
}
return ""
}
func (m *Goal) GetText() *Text {
if m != nil {
return m.Text
}
return nil
}
func (m *Goal) GetExpressedBy() *ExpressedBy {
if m != nil {
return m.ExpressedBy
}
return nil
}
func (m *Goal) GetStatusReason() string {
if m != nil {
return m.StatusReason
}
return ""
}
func (m *Goal) GetPriority() *Priority {
if m != nil {
return m.Priority
}
return nil
}
func (m *Goal) GetTarget() *Target {
if m != nil {
return m.Target
}
return nil
}
func (m *Goal) GetStatusDate() string {
if m != nil {
return m.StatusDate
}
return ""
}
func (m *Goal) GetIdentifier() []*Identifier {
if m != nil {
return m.Identifier
}
return nil
}
func (m *Goal) GetId() string {
if m != nil {
return m.Id
}
return ""
}
func (m *Goal) GetSubject() *Subject {
if m != nil {
return m.Subject
}
return nil
}
func (m *Goal) GetMeta() *Meta {
if m != nil {
return m.Meta
}
return nil
}
type Target struct {
DetailRange *DetailRange `protobuf:"bytes,1,opt,name=detailRange" json:"detailRange,omitempty"`
DueDate string `protobuf:"bytes,2,opt,name=dueDate" json:"dueDate,omitempty"`
Measure *Measure `protobuf:"bytes,3,opt,name=measure" json:"measure,omitempty"`
}
func (m *Target) Reset() { *m = Target{} }
func (m *Target) String() string { return proto.CompactTextString(m) }
func (*Target) ProtoMessage() {}
func (*Target) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{1} }
func (m *Target) GetDetailRange() *DetailRange {
if m != nil {
return m.DetailRange
}
return nil
}
func (m *Target) GetDueDate() string {
if m != nil {
return m.DueDate
}
return ""
}
func (m *Target) GetMeasure() *Measure {
if m != nil {
return m.Measure
}
return nil
}
type Measure struct {
Coding []*Coding `protobuf:"bytes,1,rep,name=coding" json:"coding,omitempty"`
}
func (m *Measure) Reset() { *m = Measure{} }
func (m *Measure) String() string { return proto.CompactTextString(m) }
func (*Measure) ProtoMessage() {}
func (*Measure) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{2} }
func (m *Measure) GetCoding() []*Coding {
if m != nil {
return m.Coding
}
return nil
}
type DetailRange struct {
High *High `protobuf:"bytes,1,opt,name=high" json:"high,omitempty"`
Low *Low `protobuf:"bytes,2,opt,name=low" json:"low,omitempty"`
}
func (m *DetailRange) Reset() { *m = DetailRange{} }
func (m *DetailRange) String() string { return proto.CompactTextString(m) }
func (*DetailRange) ProtoMessage() {}
func (*DetailRange) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{3} }
func (m *DetailRange) GetHigh() *High {
if m != nil {
return m.High
}
return nil
}
func (m *DetailRange) GetLow() *Low {
if m != nil {
return m.Low
}
return nil
}
type Low struct {
Code string `protobuf:"bytes,1,opt,name=code" json:"code,omitempty"`
Value int64 `protobuf:"varint,2,opt,name=value" json:"value,omitempty"`
Unit string `protobuf:"bytes,3,opt,name=unit" json:"unit,omitempty"`
System string `protobuf:"bytes,4,opt,name=system" json:"system,omitempty"`
}
func (m *Low) Reset() { *m = Low{} }
func (m *Low) String() string { return proto.CompactTextString(m) }
func (*Low) ProtoMessage() {}
func (*Low) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{4} }
func (m *Low) GetCode() string {
if m != nil {
return m.Code
}
return ""
}
func (m *Low) GetValue() int64 {
if m != nil {
return m.Value
}
return 0
}
func (m *Low) GetUnit() string {
if m != nil {
return m.Unit
}
return ""
}
func (m *Low) GetSystem() string {
if m != nil {
return m.System
}
return ""
}
type High struct {
Code string `protobuf:"bytes,1,opt,name=code" json:"code,omitempty"`
Value int64 `protobuf:"varint,2,opt,name=value" json:"value,omitempty"`
Unit string `protobuf:"bytes,3,opt,name=unit" json:"unit,omitempty"`
System string `protobuf:"bytes,4,opt,name=system" json:"system,omitempty"`
}
func (m *High) Reset() { *m = High{} }
func (m *High) String() string { return proto.CompactTextString(m) }
func (*High) ProtoMessage() {}
func (*High) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{5} }
func (m *High) GetCode() string {
if m != nil {
return m.Code
}
return ""
}
func (m *High) GetValue() int64 {
if m != nil {
return m.Value
}
return 0
}
func (m *High) GetUnit() string {
if m != nil {
return m.Unit
}
return ""
}
func (m *High) GetSystem() string {
if m != nil {
return m.System
}
return ""
}
type ExpressedBy struct {
Display string `protobuf:"bytes,1,opt,name=display" json:"display,omitempty"`
Reference string `protobuf:"bytes,2,opt,name=reference" json:"reference,omitempty"`
}
func (m *ExpressedBy) Reset() { *m = ExpressedBy{} }
func (m *ExpressedBy) String() string { return proto.CompactTextString(m) }
func (*ExpressedBy) ProtoMessage() {}
func (*ExpressedBy) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{6} }
func (m *ExpressedBy) GetDisplay() string {
if m != nil {
return m.Display
}
return ""
}
func (m *ExpressedBy) GetReference() string {
if m != nil {
return m.Reference
}
return ""
}
type Description struct {
Text string `protobuf:"bytes,1,opt,name=text" json:"text,omitempty"`
}
func (m *Description) Reset() { *m = Description{} }
func (m *Description) String() string { return proto.CompactTextString(m) }
func (*Description) ProtoMessage() {}
func (*Description) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{7} }
func (m *Description) GetText() string {
if m != nil {
return m.Text
}
return ""
}
type OutcomeReference struct {
Display string `protobuf:"bytes,1,opt,name=display" json:"display,omitempty"`
Reference string `protobuf:"bytes,2,opt,name=reference" json:"reference,omitempty"`
}
func (m *OutcomeReference) Reset() { *m = OutcomeReference{} }
func (m *OutcomeReference) String() string { return proto.CompactTextString(m) }
func (*OutcomeReference) ProtoMessage() {}
func (*OutcomeReference) Descriptor() ([]byte, []int) { return fileDescriptor8, []int{8} }
func (m *OutcomeReference) GetDisplay() string {
if m != nil {
return m.Display
}
return ""
}
func (m *OutcomeReference) GetReference() string {
if m != nil {
return m.Reference
}
return ""
}
func init() {
proto.RegisterType((*Goal)(nil), "buffer.Goal")
proto.RegisterType((*Target)(nil), "buffer.Target")
proto.RegisterType((*Measure)(nil), "buffer.Measure")
proto.RegisterType((*DetailRange)(nil), "buffer.DetailRange")
proto.RegisterType((*Low)(nil), "buffer.Low")
proto.RegisterType((*High)(nil), "buffer.High")
proto.RegisterType((*ExpressedBy)(nil), "buffer.ExpressedBy")
proto.RegisterType((*Description)(nil), "buffer.Description")
proto.RegisterType((*OutcomeReference)(nil), "buffer.OutcomeReference")
}
func init() { proto.RegisterFile("goal.proto", fileDescriptor8) }
var fileDescriptor8 = []byte{
// 616 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0x4d, 0x6f, 0x13, 0x31,
0x10, 0x55, 0x3e, 0x9a, 0x34, 0xb3, 0xa1, 0x4d, 0x0d, 0x42, 0x16, 0x02, 0x14, 0xf6, 0x80, 0x8a,
0x84, 0x8a, 0x08, 0xe2, 0x07, 0x40, 0x5b, 0xf1, 0xa1, 0x16, 0x90, 0xe9, 0x0d, 0x2e, 0xee, 0xee,
0x64, 0x6b, 0x94, 0xac, 0x23, 0xdb, 0x4b, 0x9b, 0x3b, 0x3f, 0x8c, 0x9f, 0x86, 0x3c, 0x6b, 0x6f,
0x36, 0xe5, 0x86, 0xc4, 0xcd, 0x7e, 0xef, 0x79, 0xe6, 0xcd, 0x8c, 0x6d, 0x80, 0x42, 0xcb, 0xc5,
0xd1, 0xca, 0x68, 0xa7, 0xd9, 0xe0, 0xb2, 0x9a, 0xcf, 0xd1, 0x3c, 0x18, 0x67, 0x7a, 0xb9, 0xd4,
0x65, 0x8d, 0xa6, 0xbf, 0x77, 0xa0, 0xff, 0x4e, 0xcb, 0x05, 0xbb, 0x0f, 0x03, 0xeb, 0xa4, 0xab,
0x2c, 0xef, 0x4c, 0x3b, 0x87, 0x23, 0x11, 0x76, 0xec, 0x39, 0xec, 0x66, 0xd2, 0x61, 0xa1, 0xcd,
0x9a, 0x77, 0xa7, 0xbd, 0xc3, 0x64, 0x36, 0x39, 0xaa, 0x23, 0x1d, 0x1d, 0x07, 0x5c, 0x34, 0x0a,
0x76, 0x02, 0x13, 0x5d, 0xb9, 0x4c, 0x2f, 0x51, 0xe0, 0x1c, 0x0d, 0x96, 0x19, 0xf2, 0x1e, 0x9d,
0xe2, 0xf1, 0xd4, 0xe7, 0x5b, 0xbc, 0xf8, 0xeb, 0x04, 0x7b, 0x01, 0x23, 0x99, 0xe7, 0x06, 0xad,
0x45, 0xcb, 0xfb, 0x74, 0xfc, 0x20, 0x1e, 0x7f, 0x13, 0x09, 0xb1, 0xd1, 0xb0, 0xd7, 0x90, 0xe4,
0x68, 0x33, 0xa3, 0x56, 0x4e, 0xe9, 0x92, 0xef, 0x4c, 0x3b, 0x87, 0xc9, 0xec, 0x6e, 0x3c, 0x72,
0xb2, 0xa1, 0x44, 0x5b, 0xc7, 0x1e, 0xc2, 0xc8, 0x3a, 0x69, 0xdc, 0x89, 0x74, 0xc8, 0x07, 0x54,
0xf6, 0x06, 0x60, 0x29, 0x8c, 0x0d, 0x5a, 0x5d, 0x99, 0x0c, 0x2f, 0xd6, 0x2b, 0xe4, 0x43, 0x12,
0x6c, 0x61, 0x6c, 0x0a, 0x7d, 0x87, 0x37, 0x8e, 0xef, 0x52, 0xc6, 0x71, 0xcc, 0x78, 0x81, 0x37,
0x4e, 0x10, 0xe3, 0xad, 0xe1, 0xcd, 0x8a, 0x7c, 0xe6, 0x6f, 0xd7, 0x7c, 0xb4, 0x6d, 0xed, 0x74,
0x43, 0x89, 0xb6, 0xce, 0x27, 0xaf, 0x07, 0x20, 0x50, 0x5a, 0x5d, 0x72, 0xa8, 0x93, 0xb7, 0x31,
0x3f, 0x9a, 0x95, 0x51, 0xda, 0x28, 0xb7, 0xe6, 0x09, 0xc5, 0x6d, 0x46, 0xf3, 0x25, 0xe0, 0xa2,
0x51, 0xb0, 0xa7, 0x30, 0x70, 0xd2, 0x14, 0xe8, 0xf8, 0x98, 0xb4, 0x7b, 0x8d, 0x59, 0x42, 0x45,
0x60, 0xd9, 0x63, 0x80, 0x3a, 0x0b, 0x75, 0xe5, 0x0e, 0xe5, 0x6d, 0x21, 0x6c, 0x06, 0xa0, 0x72,
0x2c, 0x9d, 0x9a, 0x2b, 0x34, 0x7c, 0x8f, 0xa6, 0xc3, 0x62, 0xac, 0x0f, 0x0d, 0x23, 0x5a, 0x2a,
0xb6, 0x07, 0x5d, 0x95, 0xf3, 0x7d, 0x8a, 0xd5, 0x55, 0x39, 0x7b, 0x06, 0x43, 0x5b, 0x5d, 0xfe,
0xc0, 0xcc, 0xf1, 0x09, 0x99, 0xd9, 0x8f, 0x01, 0xbe, 0xd6, 0xb0, 0x88, 0xbc, 0xef, 0xf0, 0x12,
0x9d, 0xe4, 0x07, 0xdb, 0x1d, 0x3e, 0x47, 0x27, 0x05, 0x31, 0xe9, 0xaf, 0x0e, 0x0c, 0xea, 0x1a,
0xea, 0x7b, 0xe0, 0xa4, 0x5a, 0x08, 0x59, 0x16, 0x48, 0x37, 0x79, 0xeb, 0x1e, 0x34, 0x94, 0x68,
0xeb, 0x18, 0x87, 0x61, 0x5e, 0x21, 0xd5, 0xdb, 0x25, 0x8f, 0x71, 0xeb, 0x8d, 0x2e, 0x51, 0xda,
0xca, 0xf8, 0x6b, 0xbc, 0x65, 0xf4, 0xbc, 0x86, 0x45, 0xe4, 0xd3, 0x97, 0x30, 0x0c, 0x98, 0x6f,
0x75, 0xa6, 0x73, 0x55, 0x16, 0xbc, 0x43, 0xed, 0x69, 0x5a, 0x7d, 0x4c, 0xa8, 0x08, 0x6c, 0xfa,
0x09, 0x92, 0x96, 0x27, 0x5f, 0xea, 0x95, 0x2a, 0xae, 0x82, 0xed, 0xa6, 0xd4, 0xf7, 0xaa, 0xb8,
0x12, 0xc4, 0xb0, 0x47, 0xd0, 0x5b, 0xe8, 0x6b, 0x32, 0x99, 0xcc, 0x92, 0x28, 0x38, 0xd3, 0xd7,
0xc2, 0xe3, 0xe9, 0x37, 0xe8, 0x9d, 0xe9, 0x6b, 0xc6, 0xa0, 0x9f, 0xe9, 0x1c, 0xc3, 0x43, 0xa6,
0x35, 0xbb, 0x07, 0x3b, 0x3f, 0xe5, 0xa2, 0xaa, 0x0b, 0xec, 0x89, 0x7a, 0xe3, 0x95, 0x55, 0xa9,
0x1c, 0xd5, 0x36, 0x12, 0xb4, 0xa6, 0x8f, 0x60, 0x6d, 0x1d, 0x2e, 0x79, 0x3f, 0x7c, 0x04, 0xb4,
0x4b, 0xbf, 0x43, 0xdf, 0x3b, 0xf9, 0x4f, 0xd1, 0x4f, 0x21, 0x69, 0xbd, 0x05, 0x9a, 0x88, 0xb2,
0xab, 0x85, 0x5c, 0x87, 0x3c, 0x71, 0xeb, 0xdf, 0xac, 0x69, 0xbe, 0x96, 0x7a, 0x5a, 0x1b, 0x20,
0x7d, 0xe2, 0x3b, 0xba, 0x79, 0xe0, 0x2c, 0x3c, 0xcf, 0xe0, 0xd5, 0xaf, 0xd3, 0x8f, 0x30, 0xb9,
0xfd, 0x05, 0xfd, 0x6b, 0xba, 0xcb, 0x01, 0x7d, 0xa2, 0xaf, 0xfe, 0x04, 0x00, 0x00, 0xff, 0xff,
0x0a, 0x0c, 0x80, 0x30, 0x68, 0x05, 0x00, 0x00,
}
| mit |
ministryofjustice/manchester_traffic_offences_pleas | apps/feedback/migrations/0004_auto_20150902_1040.py | 710 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('feedback', '0003_auto_20150902_0933'),
]
operations = [
migrations.AddField(
model_name='userratingaggregate',
name='question_tag',
field=models.CharField(default=b'overall', max_length=24),
),
migrations.AddField(
model_name='userratingaggregate',
name='question_text',
field=models.CharField(default='Overall, how satisfied were you with this service?', max_length=255),
preserve_default=False,
),
]
| mit |
reyesoft/ngx-jsonapi | src/tests/factories/photos.service.ts | 702 | import { Resource } from '../../resource';
import { Service } from '../../service';
export class Photo extends Resource {
public attributes = {
title: '',
uri: '',
imageable_id: '',
created_at: new Date(),
updated_at: new Date()
};
public type = 'photos';
public ttl = 0;
public static test_ttl;
public constructor() {
super();
if (Photo.test_ttl || Photo.test_ttl === 0) {
this.ttl = Photo.test_ttl;
}
}
}
export class PhotosService extends Service<Photo> {
public constructor() {
super();
this.register();
}
public resource = Photo;
public type = 'photos';
}
| mit |
jaharkes/home-assistant | homeassistant/core.py | 39312 | """
Core components of Home Assistant.
Home Assistant is a Home Automation framework for observing the state
of entities and react to changes.
"""
# pylint: disable=unused-import, too-many-lines
import asyncio
from concurrent.futures import ThreadPoolExecutor
import enum
import logging
import os
import re
import signal
import sys
import threading
from types import MappingProxyType
from typing import Optional, Any, Callable, List # NOQA
import aiohttp
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.const import (
ATTR_DOMAIN, ATTR_FRIENDLY_NAME, ATTR_NOW, ATTR_SERVICE,
ATTR_SERVICE_CALL_ID, ATTR_SERVICE_DATA, EVENT_CALL_SERVICE,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
EVENT_SERVICE_EXECUTED, EVENT_SERVICE_REGISTERED, EVENT_STATE_CHANGED,
EVENT_TIME_CHANGED, MATCH_ALL, RESTART_EXIT_CODE,
SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, __version__)
from homeassistant.exceptions import (
HomeAssistantError, InvalidEntityFormatError)
from homeassistant.util.async import (
run_coroutine_threadsafe, run_callback_threadsafe)
import homeassistant.util as util
import homeassistant.util.dt as dt_util
import homeassistant.util.location as location
from homeassistant.util.unit_system import UnitSystem, METRIC_SYSTEM # NOQA
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
DOMAIN = "homeassistant"
# How often time_changed event should fire
TIMER_INTERVAL = 1 # seconds
# How long we wait for the result of a service call
SERVICE_CALL_LIMIT = 10 # seconds
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
# Size of a executor pool
EXECUTOR_POOL_SIZE = 15
# Time for cleanup internal pending tasks
TIME_INTERVAL_TASKS_CLEANUP = 10
_LOGGER = logging.getLogger(__name__)
def split_entity_id(entity_id: str) -> List[str]:
"""Split a state entity_id into domain, object_id."""
return entity_id.split(".", 1)
def valid_entity_id(entity_id: str) -> bool:
"""Test if an entity ID is a valid format."""
return ENTITY_ID_PATTERN.match(entity_id) is not None
def callback(func: Callable[..., None]) -> Callable[..., None]:
"""Annotation to mark method as safe to call from within the event loop."""
# pylint: disable=protected-access
func._hass_callback = True
return func
def is_callback(func: Callable[..., Any]) -> bool:
"""Check if function is safe to be called in the event loop."""
return '_hass_callback' in func.__dict__
class CoreState(enum.Enum):
"""Represent the current state of Home Assistant."""
not_running = "NOT_RUNNING"
starting = "STARTING"
running = "RUNNING"
stopping = "STOPPING"
def __str__(self) -> str:
"""Return the event."""
return self.value
class HomeAssistant(object):
"""Root object of the Home Assistant home automation."""
def __init__(self, loop=None):
"""Initialize new Home Assistant object."""
if sys.platform == "win32":
self.loop = loop or asyncio.ProactorEventLoop()
else:
self.loop = loop or asyncio.get_event_loop()
self.executor = ThreadPoolExecutor(max_workers=5)
self.loop.set_default_executor(self.executor)
self.loop.set_exception_handler(self._async_exception_handler)
self._pending_tasks = []
self._pending_sheduler = None
self.bus = EventBus(self)
self.services = ServiceRegistry(self.bus, self.async_add_job,
self.loop)
self.states = StateMachine(self.bus, self.loop)
self.config = Config() # type: Config
# This is a dictionary that any component can store any data on.
self.data = {}
self.state = CoreState.not_running
self.exit_code = None
self._websession = None
@property
def is_running(self) -> bool:
"""Return if Home Assistant is running."""
return self.state in (CoreState.starting, CoreState.running)
@property
def websession(self):
"""Return an aiohttp session to make web requests."""
if self._websession is None:
self._websession = aiohttp.ClientSession(loop=self.loop)
return self._websession
def start(self) -> None:
"""Start home assistant."""
# Register the async start
self.loop.create_task(self.async_start())
# Run forever and catch keyboard interrupt
try:
# Block until stopped
_LOGGER.info("Starting Home Assistant core loop")
self.loop.run_forever()
except KeyboardInterrupt:
self.loop.call_soon(self._async_stop_handler)
self.loop.run_forever()
finally:
self.loop.close()
@asyncio.coroutine
def async_start(self):
"""Finalize startup from inside the event loop.
This method is a coroutine.
"""
_LOGGER.info("Starting Home Assistant")
self.state = CoreState.starting
# Register the restart/stop event
self.services.async_register(
DOMAIN, SERVICE_HOMEASSISTANT_STOP, self._async_stop_handler)
self.services.async_register(
DOMAIN, SERVICE_HOMEASSISTANT_RESTART, self._async_restart_handler)
# Setup signal handling
if sys.platform != 'win32':
try:
self.loop.add_signal_handler(
signal.SIGTERM, self._async_stop_handler)
except ValueError:
_LOGGER.warning('Could not bind to SIGTERM.')
try:
self.loop.add_signal_handler(
signal.SIGHUP, self._async_restart_handler)
except ValueError:
_LOGGER.warning('Could not bind to SIGHUP.')
# pylint: disable=protected-access
self.loop._thread_ident = threading.get_ident()
self._async_tasks_cleanup()
_async_create_timer(self)
self.bus.async_fire(EVENT_HOMEASSISTANT_START)
self.state = CoreState.running
@callback
def _async_tasks_cleanup(self):
"""Cleanup all pending tasks in a time interval.
This method must be run in the event loop.
"""
self._pending_tasks = [task for task in self._pending_tasks
if not task.done()]
# sheduled next cleanup
self._pending_sheduler = self.loop.call_later(
TIME_INTERVAL_TASKS_CLEANUP, self._async_tasks_cleanup)
def add_job(self, target: Callable[..., None], *args: Any) -> None:
"""Add job to the executor pool.
target: target to call.
args: parameters for method to call.
"""
self.loop.call_soon_threadsafe(self.async_add_job, target, *args)
@callback
def async_add_job(self, target: Callable[..., None], *args: Any) -> None:
"""Add a job from within the eventloop.
This method must be run in the event loop.
target: target to call.
args: parameters for method to call.
"""
task = None
if asyncio.iscoroutine(target):
task = self.loop.create_task(target)
elif is_callback(target):
self.loop.call_soon(target, *args)
elif asyncio.iscoroutinefunction(target):
task = self.loop.create_task(target(*args))
else:
task = self.loop.run_in_executor(None, target, *args)
# if a task is sheduled
if task is not None:
self._pending_tasks.append(task)
@callback
def async_run_job(self, target: Callable[..., None], *args: Any) -> None:
"""Run a job from within the event loop.
This method must be run in the event loop.
target: target to call.
args: parameters for method to call.
"""
if is_callback(target):
target(*args)
else:
self.async_add_job(target, *args)
def _loop_empty(self) -> bool:
"""Python 3.4.2 empty loop compatibility function."""
# pylint: disable=protected-access
if sys.version_info < (3, 4, 3):
return len(self.loop._scheduled) == 0 and \
len(self.loop._ready) == 0
else:
return self.loop._current_handle is None and \
len(self.loop._ready) == 0
def block_till_done(self) -> None:
"""Block till all pending work is done."""
run_coroutine_threadsafe(
self.async_block_till_done(), loop=self.loop).result()
@asyncio.coroutine
def async_block_till_done(self):
"""Block till all pending work is done."""
while True:
# Wait for the pending tasks are down
pending = [task for task in self._pending_tasks
if not task.done()]
self._pending_tasks.clear()
if len(pending) > 0:
yield from asyncio.wait(pending, loop=self.loop)
# Verify the loop is empty
ret = yield from self.loop.run_in_executor(None, self._loop_empty)
if ret and not self._pending_tasks:
break
def stop(self) -> None:
"""Stop Home Assistant and shuts down all threads."""
run_coroutine_threadsafe(self.async_stop(), self.loop)
@asyncio.coroutine
def async_stop(self) -> None:
"""Stop Home Assistant and shuts down all threads.
This method is a coroutine.
"""
self.state = CoreState.stopping
self.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
if self._pending_sheduler is not None:
self._pending_sheduler.cancel()
yield from self.async_block_till_done()
self.executor.shutdown()
if self._websession is not None:
yield from self._websession.close()
self.state = CoreState.not_running
self.loop.stop()
# pylint: disable=no-self-use
@callback
def _async_exception_handler(self, loop, context):
"""Handle all exception inside the core loop."""
kwargs = {}
exception = context.get('exception')
if exception:
kwargs['exc_info'] = (type(exception), exception,
exception.__traceback__)
_LOGGER.error('Error doing job: %s', context['message'],
**kwargs)
@callback
def _async_stop_handler(self, *args):
"""Stop Home Assistant."""
self.exit_code = 0
self.loop.create_task(self.async_stop())
@callback
def _async_restart_handler(self, *args):
"""Restart Home Assistant."""
self.exit_code = RESTART_EXIT_CODE
self.loop.create_task(self.async_stop())
class EventOrigin(enum.Enum):
"""Represent the origin of an event."""
local = "LOCAL"
remote = "REMOTE"
def __str__(self):
"""Return the event."""
return self.value
class Event(object):
"""Represents an event within the Bus."""
__slots__ = ['event_type', 'data', 'origin', 'time_fired']
def __init__(self, event_type, data=None, origin=EventOrigin.local,
time_fired=None):
"""Initialize a new event."""
self.event_type = event_type
self.data = data or {}
self.origin = origin
self.time_fired = time_fired or dt_util.utcnow()
def as_dict(self):
"""Create a dict representation of this Event.
Async friendly.
"""
return {
'event_type': self.event_type,
'data': dict(self.data),
'origin': str(self.origin),
'time_fired': self.time_fired,
}
def __repr__(self):
"""Return the representation."""
# pylint: disable=maybe-no-member
if self.data:
return "<Event {}[{}]: {}>".format(
self.event_type, str(self.origin)[0],
util.repr_helper(self.data))
else:
return "<Event {}[{}]>".format(self.event_type,
str(self.origin)[0])
def __eq__(self, other):
"""Return the comparison."""
return (self.__class__ == other.__class__ and
self.event_type == other.event_type and
self.data == other.data and
self.origin == other.origin and
self.time_fired == other.time_fired)
class EventBus(object):
"""Allows firing of and listening for events."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize a new event bus."""
self._listeners = {}
self._hass = hass
@callback
def async_listeners(self):
"""Dict with events and the number of listeners.
This method must be run in the event loop.
"""
return {key: len(self._listeners[key])
for key in self._listeners}
@property
def listeners(self):
"""Dict with events and the number of listeners."""
return run_callback_threadsafe(
self._hass.loop, self.async_listeners
).result()
def fire(self, event_type: str, event_data=None, origin=EventOrigin.local):
"""Fire an event."""
self._hass.loop.call_soon_threadsafe(self.async_fire, event_type,
event_data, origin)
@callback
def async_fire(self, event_type: str, event_data=None,
origin=EventOrigin.local, wait=False):
"""Fire an event.
This method must be run in the event loop.
"""
if event_type != EVENT_HOMEASSISTANT_STOP and \
self._hass.state == CoreState.stopping:
raise HomeAssistantError('Home Assistant is shutting down.')
# Copy the list of the current listeners because some listeners
# remove themselves as a listener while being executed which
# causes the iterator to be confused.
get = self._listeners.get
listeners = get(MATCH_ALL, []) + get(event_type, [])
event = Event(event_type, event_data, origin)
if event_type != EVENT_TIME_CHANGED:
_LOGGER.info("Bus:Handling %s", event)
if not listeners:
return
for func in listeners:
self._hass.async_add_job(func, event)
def listen(self, event_type, listener):
"""Listen for all events or events of a specific type.
To listen to all events specify the constant ``MATCH_ALL``
as event_type.
"""
async_remove_listener = run_callback_threadsafe(
self._hass.loop, self.async_listen, event_type, listener).result()
def remove_listener():
"""Remove the listener."""
run_callback_threadsafe(
self._hass.loop, async_remove_listener).result()
return remove_listener
@callback
def async_listen(self, event_type, listener):
"""Listen for all events or events of a specific type.
To listen to all events specify the constant ``MATCH_ALL``
as event_type.
This method must be run in the event loop.
"""
if event_type in self._listeners:
self._listeners[event_type].append(listener)
else:
self._listeners[event_type] = [listener]
def remove_listener():
"""Remove the listener."""
self._async_remove_listener(event_type, listener)
return remove_listener
def listen_once(self, event_type, listener):
"""Listen once for event of a specific type.
To listen to all events specify the constant ``MATCH_ALL``
as event_type.
Returns function to unsubscribe the listener.
"""
async_remove_listener = run_callback_threadsafe(
self._hass.loop, self.async_listen_once, event_type, listener,
).result()
def remove_listener():
"""Remove the listener."""
run_callback_threadsafe(
self._hass.loop, async_remove_listener).result()
return remove_listener
@callback
def async_listen_once(self, event_type, listener):
"""Listen once for event of a specific type.
To listen to all events specify the constant ``MATCH_ALL``
as event_type.
Returns registered listener that can be used with remove_listener.
This method must be run in the event loop.
"""
@callback
def onetime_listener(event):
"""Remove listener from eventbus and then fire listener."""
if hasattr(onetime_listener, 'run'):
return
# Set variable so that we will never run twice.
# Because the event bus loop might have async_fire queued multiple
# times, its possible this listener may already be lined up
# multiple times as well.
# This will make sure the second time it does nothing.
setattr(onetime_listener, 'run', True)
self._async_remove_listener(event_type, onetime_listener)
self._hass.async_run_job(listener, event)
return self.async_listen(event_type, onetime_listener)
@callback
def _async_remove_listener(self, event_type, listener):
"""Remove a listener of a specific event_type.
This method must be run in the event loop.
"""
try:
self._listeners[event_type].remove(listener)
# delete event_type list if empty
if not self._listeners[event_type]:
self._listeners.pop(event_type)
except (KeyError, ValueError):
# KeyError is key event_type listener did not exist
# ValueError if listener did not exist within event_type
_LOGGER.warning('Unable to remove unknown listener %s',
listener)
class State(object):
"""Object to represent a state within the state machine.
entity_id: the entity that is represented.
state: the state of the entity
attributes: extra information on entity and state
last_changed: last time the state was changed, not the attributes.
last_updated: last time this object was updated.
"""
__slots__ = ['entity_id', 'state', 'attributes',
'last_changed', 'last_updated']
def __init__(self, entity_id, state, attributes=None, last_changed=None,
last_updated=None):
"""Initialize a new state."""
if not valid_entity_id(entity_id):
raise InvalidEntityFormatError((
"Invalid entity id encountered: {}. "
"Format should be <domain>.<object_id>").format(entity_id))
self.entity_id = entity_id.lower()
self.state = str(state)
self.attributes = MappingProxyType(attributes or {})
self.last_updated = last_updated or dt_util.utcnow()
self.last_changed = last_changed or self.last_updated
@property
def domain(self):
"""Domain of this state."""
return split_entity_id(self.entity_id)[0]
@property
def object_id(self):
"""Object id of this state."""
return split_entity_id(self.entity_id)[1]
@property
def name(self):
"""Name of this state."""
return (
self.attributes.get(ATTR_FRIENDLY_NAME) or
self.object_id.replace('_', ' '))
def as_dict(self):
"""Return a dict representation of the State.
Async friendly.
To be used for JSON serialization.
Ensures: state == State.from_dict(state.as_dict())
"""
return {'entity_id': self.entity_id,
'state': self.state,
'attributes': dict(self.attributes),
'last_changed': self.last_changed,
'last_updated': self.last_updated}
@classmethod
def from_dict(cls, json_dict):
"""Initialize a state from a dict.
Async friendly.
Ensures: state == State.from_json_dict(state.to_json_dict())
"""
if not (json_dict and 'entity_id' in json_dict and
'state' in json_dict):
return None
last_changed = json_dict.get('last_changed')
if isinstance(last_changed, str):
last_changed = dt_util.parse_datetime(last_changed)
last_updated = json_dict.get('last_updated')
if isinstance(last_updated, str):
last_updated = dt_util.parse_datetime(last_updated)
return cls(json_dict['entity_id'], json_dict['state'],
json_dict.get('attributes'), last_changed, last_updated)
def __eq__(self, other):
"""Return the comparison of the state."""
return (self.__class__ == other.__class__ and
self.entity_id == other.entity_id and
self.state == other.state and
self.attributes == other.attributes)
def __repr__(self):
"""Return the representation of the states."""
attr = "; {}".format(util.repr_helper(self.attributes)) \
if self.attributes else ""
return "<state {}={}{} @ {}>".format(
self.entity_id, self.state, attr,
dt_util.as_local(self.last_changed).isoformat())
class StateMachine(object):
"""Helper class that tracks the state of different entities."""
def __init__(self, bus, loop):
"""Initialize state machine."""
self._states = {}
self._bus = bus
self._loop = loop
def entity_ids(self, domain_filter=None):
"""List of entity ids that are being tracked."""
future = run_callback_threadsafe(
self._loop, self.async_entity_ids, domain_filter
)
return future.result()
@callback
def async_entity_ids(self, domain_filter=None):
"""List of entity ids that are being tracked.
This method must be run in the event loop.
"""
if domain_filter is None:
return list(self._states.keys())
domain_filter = domain_filter.lower()
return [state.entity_id for state in self._states.values()
if state.domain == domain_filter]
def all(self):
"""Create a list of all states."""
return run_callback_threadsafe(self._loop, self.async_all).result()
@callback
def async_all(self):
"""Create a list of all states.
This method must be run in the event loop.
"""
return list(self._states.values())
def get(self, entity_id):
"""Retrieve state of entity_id or None if not found.
Async friendly.
"""
return self._states.get(entity_id.lower())
def is_state(self, entity_id, state):
"""Test if entity exists and is specified state.
Async friendly.
"""
state_obj = self.get(entity_id)
return state_obj and state_obj.state == state
def is_state_attr(self, entity_id, name, value):
"""Test if entity exists and has a state attribute set to value.
Async friendly.
"""
state_obj = self.get(entity_id)
return state_obj and state_obj.attributes.get(name, None) == value
def remove(self, entity_id):
"""Remove the state of an entity.
Returns boolean to indicate if an entity was removed.
"""
return run_callback_threadsafe(
self._loop, self.async_remove, entity_id).result()
@callback
def async_remove(self, entity_id):
"""Remove the state of an entity.
Returns boolean to indicate if an entity was removed.
This method must be run in the event loop.
"""
entity_id = entity_id.lower()
old_state = self._states.pop(entity_id, None)
if old_state is None:
return False
event_data = {
'entity_id': entity_id,
'old_state': old_state,
'new_state': None,
}
self._bus.async_fire(EVENT_STATE_CHANGED, event_data)
return True
def set(self, entity_id, new_state, attributes=None, force_update=False):
"""Set the state of an entity, add entity if it does not exist.
Attributes is an optional dict to specify attributes of this state.
If you just update the attributes and not the state, last changed will
not be affected.
"""
run_callback_threadsafe(
self._loop,
self.async_set, entity_id, new_state, attributes, force_update,
).result()
@callback
def async_set(self, entity_id, new_state, attributes=None,
force_update=False):
"""Set the state of an entity, add entity if it does not exist.
Attributes is an optional dict to specify attributes of this state.
If you just update the attributes and not the state, last changed will
not be affected.
This method must be run in the event loop.
"""
entity_id = entity_id.lower()
new_state = str(new_state)
attributes = attributes or {}
old_state = self._states.get(entity_id)
is_existing = old_state is not None
same_state = (is_existing and old_state.state == new_state and
not force_update)
same_attr = is_existing and old_state.attributes == attributes
if same_state and same_attr:
return
# If state did not exist or is different, set it
last_changed = old_state.last_changed if same_state else None
state = State(entity_id, new_state, attributes, last_changed)
self._states[entity_id] = state
event_data = {
'entity_id': entity_id,
'old_state': old_state,
'new_state': state,
}
self._bus.async_fire(EVENT_STATE_CHANGED, event_data)
class Service(object):
"""Represents a callable service."""
__slots__ = ['func', 'description', 'fields', 'schema',
'is_callback', 'is_coroutinefunction']
def __init__(self, func, description, fields, schema):
"""Initialize a service."""
self.func = func
self.description = description or ''
self.fields = fields or {}
self.schema = schema
self.is_callback = is_callback(func)
self.is_coroutinefunction = asyncio.iscoroutinefunction(func)
def as_dict(self):
"""Return dictionary representation of this service."""
return {
'description': self.description,
'fields': self.fields,
}
class ServiceCall(object):
"""Represents a call to a service."""
__slots__ = ['domain', 'service', 'data', 'call_id']
def __init__(self, domain, service, data=None, call_id=None):
"""Initialize a service call."""
self.domain = domain.lower()
self.service = service.lower()
self.data = MappingProxyType(data or {})
self.call_id = call_id
def __repr__(self):
"""Return the represenation of the service."""
if self.data:
return "<ServiceCall {}.{}: {}>".format(
self.domain, self.service, util.repr_helper(self.data))
else:
return "<ServiceCall {}.{}>".format(self.domain, self.service)
class ServiceRegistry(object):
"""Offers services over the eventbus."""
def __init__(self, bus, async_add_job, loop):
"""Initialize a service registry."""
self._services = {}
self._async_add_job = async_add_job
self._bus = bus
self._loop = loop
self._cur_id = 0
self._async_unsub_call_event = None
@property
def services(self):
"""Dict with per domain a list of available services."""
return run_callback_threadsafe(
self._loop, self.async_services,
).result()
@callback
def async_services(self):
"""Dict with per domain a list of available services.
This method must be run in the event loop.
"""
return {domain: {key: value.as_dict() for key, value
in self._services[domain].items()}
for domain in self._services}
def has_service(self, domain, service):
"""Test if specified service exists.
Async friendly.
"""
return service.lower() in self._services.get(domain.lower(), [])
def register(self, domain, service, service_func, description=None,
schema=None):
"""
Register a service.
Description is a dict containing key 'description' to describe
the service and a key 'fields' to describe the fields.
Schema is called to coerce and validate the service data.
"""
run_callback_threadsafe(
self._loop,
self.async_register, domain, service, service_func, description,
schema
).result()
@callback
def async_register(self, domain, service, service_func, description=None,
schema=None):
"""
Register a service.
Description is a dict containing key 'description' to describe
the service and a key 'fields' to describe the fields.
Schema is called to coerce and validate the service data.
This method must be run in the event loop.
"""
domain = domain.lower()
service = service.lower()
description = description or {}
service_obj = Service(service_func, description.get('description'),
description.get('fields', {}), schema)
if domain in self._services:
self._services[domain][service] = service_obj
else:
self._services[domain] = {service: service_obj}
if self._async_unsub_call_event is None:
self._async_unsub_call_event = self._bus.async_listen(
EVENT_CALL_SERVICE, self._event_to_service_call)
self._bus.async_fire(
EVENT_SERVICE_REGISTERED,
{ATTR_DOMAIN: domain, ATTR_SERVICE: service}
)
def call(self, domain, service, service_data=None, blocking=False):
"""
Call a service.
Specify blocking=True to wait till service is executed.
Waits a maximum of SERVICE_CALL_LIMIT.
If blocking = True, will return boolean if service executed
succesfully within SERVICE_CALL_LIMIT.
This method will fire an event to call the service.
This event will be picked up by this ServiceRegistry and any
other ServiceRegistry that is listening on the EventBus.
Because the service is sent as an event you are not allowed to use
the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data.
"""
return run_coroutine_threadsafe(
self.async_call(domain, service, service_data, blocking),
self._loop
).result()
@asyncio.coroutine
def async_call(self, domain, service, service_data=None, blocking=False):
"""
Call a service.
Specify blocking=True to wait till service is executed.
Waits a maximum of SERVICE_CALL_LIMIT.
If blocking = True, will return boolean if service executed
succesfully within SERVICE_CALL_LIMIT.
This method will fire an event to call the service.
This event will be picked up by this ServiceRegistry and any
other ServiceRegistry that is listening on the EventBus.
Because the service is sent as an event you are not allowed to use
the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data.
This method is a coroutine.
"""
call_id = self._generate_unique_id()
event_data = {
ATTR_DOMAIN: domain.lower(),
ATTR_SERVICE: service.lower(),
ATTR_SERVICE_DATA: service_data,
ATTR_SERVICE_CALL_ID: call_id,
}
if blocking:
fut = asyncio.Future(loop=self._loop)
@callback
def service_executed(event):
"""Callback method that is called when service is executed."""
if event.data[ATTR_SERVICE_CALL_ID] == call_id:
fut.set_result(True)
unsub = self._bus.async_listen(EVENT_SERVICE_EXECUTED,
service_executed)
self._bus.async_fire(EVENT_CALL_SERVICE, event_data)
if blocking:
done, _ = yield from asyncio.wait([fut], loop=self._loop,
timeout=SERVICE_CALL_LIMIT)
success = bool(done)
unsub()
return success
@asyncio.coroutine
def _event_to_service_call(self, event):
"""Callback for SERVICE_CALLED events from the event bus."""
service_data = event.data.get(ATTR_SERVICE_DATA) or {}
domain = event.data.get(ATTR_DOMAIN).lower()
service = event.data.get(ATTR_SERVICE).lower()
call_id = event.data.get(ATTR_SERVICE_CALL_ID)
if not self.has_service(domain, service):
if event.origin == EventOrigin.local:
_LOGGER.warning('Unable to find service %s/%s',
domain, service)
return
service_handler = self._services[domain][service]
def fire_service_executed():
"""Fire service executed event."""
if not call_id:
return
data = {ATTR_SERVICE_CALL_ID: call_id}
if (service_handler.is_coroutinefunction or
service_handler.is_callback):
self._bus.async_fire(EVENT_SERVICE_EXECUTED, data)
else:
self._bus.fire(EVENT_SERVICE_EXECUTED, data)
try:
if service_handler.schema:
service_data = service_handler.schema(service_data)
except vol.Invalid as ex:
_LOGGER.error('Invalid service data for %s.%s: %s',
domain, service, humanize_error(service_data, ex))
fire_service_executed()
return
service_call = ServiceCall(domain, service, service_data, call_id)
if service_handler.is_callback:
service_handler.func(service_call)
fire_service_executed()
elif service_handler.is_coroutinefunction:
yield from service_handler.func(service_call)
fire_service_executed()
else:
def execute_service():
"""Execute a service and fires a SERVICE_EXECUTED event."""
service_handler.func(service_call)
fire_service_executed()
self._async_add_job(execute_service)
def _generate_unique_id(self):
"""Generate a unique service call id."""
self._cur_id += 1
return "{}-{}".format(id(self), self._cur_id)
class Config(object):
"""Configuration settings for Home Assistant."""
def __init__(self):
"""Initialize a new config object."""
self.latitude = None # type: Optional[float]
self.longitude = None # type: Optional[float]
self.elevation = None # type: Optional[int]
self.location_name = None # type: Optional[str]
self.time_zone = None # type: Optional[str]
self.units = METRIC_SYSTEM # type: UnitSystem
# If True, pip install is skipped for requirements on startup
self.skip_pip = False # type: bool
# List of loaded components
self.components = []
# Remote.API object pointing at local API
self.api = None
# Directory that holds the configuration
self.config_dir = None
def distance(self: object, lat: float, lon: float) -> float:
"""Calculate distance from Home Assistant.
Async friendly.
"""
return self.units.length(
location.distance(self.latitude, self.longitude, lat, lon), 'm')
def path(self, *path):
"""Generate path to the file within the config dir.
Async friendly.
"""
if self.config_dir is None:
raise HomeAssistantError("config_dir is not set")
return os.path.join(self.config_dir, *path)
def as_dict(self):
"""Create a dict representation of this dict.
Async friendly.
"""
time_zone = self.time_zone or dt_util.UTC
return {
'latitude': self.latitude,
'longitude': self.longitude,
'unit_system': self.units.as_dict(),
'location_name': self.location_name,
'time_zone': time_zone.zone,
'components': self.components,
'config_dir': self.config_dir,
'version': __version__
}
def _async_create_timer(hass, interval=TIMER_INTERVAL):
"""Create a timer that will start on HOMEASSISTANT_START."""
stop_event = asyncio.Event(loop=hass.loop)
# Setting the Event inside the loop by marking it as a coroutine
@callback
def stop_timer(event):
"""Stop the timer."""
stop_event.set()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer)
@asyncio.coroutine
def timer(interval, stop_event):
"""Create an async timer."""
_LOGGER.info("Timer:starting")
last_fired_on_second = -1
calc_now = dt_util.utcnow
while not stop_event.is_set():
now = calc_now()
# First check checks if we are not on a second matching the
# timer interval. Second check checks if we did not already fire
# this interval.
if now.second % interval or \
now.second == last_fired_on_second:
# Sleep till it is the next time that we have to fire an event.
# Aim for halfway through the second that fits TIMER_INTERVAL.
# If TIMER_INTERVAL is 10 fire at .5, 10.5, 20.5, etc seconds.
# This will yield the best results because time.sleep() is not
# 100% accurate because of non-realtime OS's
slp_seconds = interval - now.second % interval + \
.5 - now.microsecond/1000000.0
yield from asyncio.sleep(slp_seconds, loop=hass.loop)
now = calc_now()
last_fired_on_second = now.second
# Event might have been set while sleeping
if not stop_event.is_set():
try:
# Schedule the bus event
hass.loop.call_soon(
hass.bus.async_fire,
EVENT_TIME_CHANGED,
{ATTR_NOW: now}
)
except HomeAssistantError:
# HA raises error if firing event after it has shut down
break
@asyncio.coroutine
def start_timer(event):
"""Start our async timer."""
hass.loop.create_task(timer(interval, stop_event))
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_timer)
| mit |
Carrooi/Nette-Conversations | src/Model/Entities/IConversation.php | 473 | <?php
namespace Carrooi\Conversations\Model\Entities;
/**
*
* @author David Kudera
*/
interface IConversation
{
/**
* @return int
*/
public function getId();
/**
* @return \DateTime
*/
public function getCreatedAt();
/**
* @return \Carrooi\Conversations\Model\Entities\IUser
*/
public function getCreator();
/**
* @param \Carrooi\Conversations\Model\Entities\IUser $user
* @return $this
*/
public function setCreator(IUser $user);
}
| mit |
fgbs/metrics | lib/configobj/configobj.py | 89711 | # configobj.py
# A config file reader/writer that supports nested sections in config files.
# Copyright (C) 2005-2014:
# (name) : (email)
# Michael Foord: fuzzyman AT voidspace DOT org DOT uk
# Nicola Larosa: nico AT tekNico DOT net
# Rob Dennis: rdennis AT gmail DOT com
# Eli Courtwright: eli AT courtwright DOT org
# This software is licensed under the terms of the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
# ConfigObj 5 - main repository for documentation and issue tracking:
# https://github.com/DiffSK/configobj
import os
import re
import sys
import collections
from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
import six
from _version import __version__
# imported lazily to avoid startup performance hit if it isn't used
compiler = None
# A dictionary mapping BOM to
# the encoding to decode with, and what to set the
# encoding attribute to.
BOMS = {
BOM_UTF8: ('utf_8', None),
BOM_UTF16_BE: ('utf16_be', 'utf_16'),
BOM_UTF16_LE: ('utf16_le', 'utf_16'),
BOM_UTF16: ('utf_16', 'utf_16'),
}
# All legal variants of the BOM codecs.
# TODO: the list of aliases is not meant to be exhaustive, is there a
# better way ?
BOM_LIST = {
'utf_16': 'utf_16',
'u16': 'utf_16',
'utf16': 'utf_16',
'utf-16': 'utf_16',
'utf16_be': 'utf16_be',
'utf_16_be': 'utf16_be',
'utf-16be': 'utf16_be',
'utf16_le': 'utf16_le',
'utf_16_le': 'utf16_le',
'utf-16le': 'utf16_le',
'utf_8': 'utf_8',
'u8': 'utf_8',
'utf': 'utf_8',
'utf8': 'utf_8',
'utf-8': 'utf_8',
}
# Map of encodings to the BOM to write.
BOM_SET = {
'utf_8': BOM_UTF8,
'utf_16': BOM_UTF16,
'utf16_be': BOM_UTF16_BE,
'utf16_le': BOM_UTF16_LE,
None: BOM_UTF8
}
def match_utf8(encoding):
return BOM_LIST.get(encoding.lower()) == 'utf_8'
# Quote strings used for writing values
squot = "'%s'"
dquot = '"%s"'
noquot = "%s"
wspace_plus = ' \r\n\v\t\'"'
tsquot = '"""%s"""'
tdquot = "'''%s'''"
# Sentinel for use in getattr calls to replace hasattr
MISSING = object()
__all__ = (
'DEFAULT_INDENT_TYPE',
'DEFAULT_INTERPOLATION',
'ConfigObjError',
'NestingError',
'ParseError',
'DuplicateError',
'ConfigspecError',
'ConfigObj',
'SimpleVal',
'InterpolationError',
'InterpolationLoopError',
'MissingInterpolationOption',
'RepeatSectionError',
'ReloadError',
'UnreprError',
'UnknownType',
'flatten_errors',
'get_extra_values'
)
DEFAULT_INTERPOLATION = 'configparser'
DEFAULT_INDENT_TYPE = ' '
MAX_INTERPOL_DEPTH = 10
OPTION_DEFAULTS = {
'interpolation': True,
'raise_errors': False,
'list_values': True,
'create_empty': False,
'file_error': False,
'configspec': None,
'stringify': True,
# option may be set to one of ('', ' ', '\t')
'indent_type': None,
'encoding': None,
'default_encoding': None,
'unrepr': False,
'write_empty_values': False,
}
# this could be replaced if six is used for compatibility, or there are no
# more assertions about items being a string
def getObj(s):
global compiler
if compiler is None:
import compiler
s = "a=" + s
p = compiler.parse(s)
return p.getChildren()[1].getChildren()[0].getChildren()[1]
class UnknownType(Exception):
pass
class Builder(object):
def build(self, o):
if m is None:
raise UnknownType(o.__class__.__name__)
return m(o)
def build_List(self, o):
return list(map(self.build, o.getChildren()))
def build_Const(self, o):
return o.value
def build_Dict(self, o):
d = {}
i = iter(map(self.build, o.getChildren()))
for el in i:
d[el] = next(i)
return d
def build_Tuple(self, o):
return tuple(self.build_List(o))
def build_Name(self, o):
if o.name == 'None':
return None
if o.name == 'True':
return True
if o.name == 'False':
return False
# An undefined Name
raise UnknownType('Undefined Name')
def build_Add(self, o):
real, imag = list(map(self.build_Const, o.getChildren()))
try:
real = float(real)
except TypeError:
raise UnknownType('Add')
if not isinstance(imag, complex) or imag.real != 0.0:
raise UnknownType('Add')
return real+imag
def build_Getattr(self, o):
parent = self.build(o.expr)
return getattr(parent, o.attrname)
def build_UnarySub(self, o):
return -self.build_Const(o.getChildren()[0])
def build_UnaryAdd(self, o):
return self.build_Const(o.getChildren()[0])
_builder = Builder()
def unrepr(s):
if not s:
return s
# this is supposed to be safe
import ast
return ast.literal_eval(s)
class ConfigObjError(SyntaxError):
"""
This is the base class for all errors that ConfigObj raises.
It is a subclass of SyntaxError.
"""
def __init__(self, message='', line_number=None, line=''):
self.line = line
self.line_number = line_number
SyntaxError.__init__(self, message)
class NestingError(ConfigObjError):
"""
This error indicates a level of nesting that doesn't match.
"""
class ParseError(ConfigObjError):
"""
This error indicates that a line is badly written.
It is neither a valid ``key = value`` line,
nor a valid section marker line.
"""
class ReloadError(IOError):
"""
A 'reload' operation failed.
This exception is a subclass of ``IOError``.
"""
def __init__(self):
IOError.__init__(self, 'reload failed, filename is not set.')
class DuplicateError(ConfigObjError):
"""
The keyword or section specified already exists.
"""
class ConfigspecError(ConfigObjError):
"""
An error occured whilst parsing a configspec.
"""
class InterpolationError(ConfigObjError):
"""Base class for the two interpolation errors."""
class InterpolationLoopError(InterpolationError):
"""Maximum interpolation depth exceeded in string interpolation."""
def __init__(self, option):
InterpolationError.__init__(
self,
'interpolation loop detected in value "%s".' % option)
class RepeatSectionError(ConfigObjError):
"""
This error indicates additional sections in a section with a
``__many__`` (repeated) section.
"""
class MissingInterpolationOption(InterpolationError):
"""A value specified for interpolation was missing."""
def __init__(self, option):
msg = 'missing option "%s" in interpolation.' % option
InterpolationError.__init__(self, msg)
class UnreprError(ConfigObjError):
"""An error parsing in unrepr mode."""
class InterpolationEngine(object):
"""
A helper class to help perform string interpolation.
This class is an abstract base class; its descendants perform
the actual work.
"""
# compiled regexp to use in self.interpolate()
_KEYCRE = re.compile(r"%\(([^)]*)\)s")
_cookie = '%'
def __init__(self, section):
# the Section instance that "owns" this engine
self.section = section
def interpolate(self, key, value):
# short-cut
if not self._cookie in value:
return value
def recursive_interpolate(key, value, section, backtrail):
"""The function that does the actual work.
``value``: the string we're trying to interpolate.
``section``: the section in which that string was found
``backtrail``: a dict to keep track of where we've been,
to detect and prevent infinite recursion loops
This is similar to a depth-first-search algorithm.
"""
# Have we been here already?
if (key, section.name) in backtrail:
# Yes - infinite loop detected
raise InterpolationLoopError(key)
# Place a marker on our backtrail so we won't come back here again
backtrail[(key, section.name)] = 1
# Now start the actual work
match = self._KEYCRE.search(value)
while match:
# The actual parsing of the match is implementation-dependent,
# so delegate to our helper function
k, v, s = self._parse_match(match)
if k is None:
# That's the signal that no further interpolation is needed
replacement = v
else:
# Further interpolation may be needed to obtain final value
replacement = recursive_interpolate(k, v, s, backtrail)
# Replace the matched string with its final value
start, end = match.span()
value = ''.join((value[:start], replacement, value[end:]))
new_search_start = start + len(replacement)
# Pick up the next interpolation key, if any, for next time
# through the while loop
match = self._KEYCRE.search(value, new_search_start)
# Now safe to come back here again; remove marker from backtrail
del backtrail[(key, section.name)]
return value
# Back in interpolate(), all we have to do is kick off the recursive
# function with appropriate starting values
value = recursive_interpolate(key, value, self.section, {})
return value
def _fetch(self, key):
"""Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.
"""
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.main.interpolation = False
# Start at section that "owns" this InterpolationEngine
current_section = self.section
while True:
# try the current section first
val = current_section.get(key)
if val is not None and not isinstance(val, Section):
break
# try "DEFAULT" next
val = current_section.get('DEFAULT', {}).get(key)
if val is not None and not isinstance(val, Section):
break
# move up to parent and try again
# top-level's parent is itself
if current_section.parent is current_section:
# reached top level, time to give up
break
current_section = current_section.parent
# restore interpolation to previous value before returning
self.section.main.interpolation = save_interp
if val is None:
raise MissingInterpolationOption(key)
return val, current_section
def _parse_match(self, match):
"""Implementation-dependent helper function.
Will be passed a match object corresponding to the interpolation
key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
key in the appropriate config file section (using the ``_fetch()``
helper function) and return a 3-tuple: (key, value, section)
``key`` is the name of the key we're looking for
``value`` is the value found for that key
``section`` is a reference to the section where it was found
``key`` and ``section`` should be None if no further
interpolation should be performed on the resulting value
(e.g., if we interpolated "$$" and returned "$").
"""
raise NotImplementedError()
class ConfigParserInterpolation(InterpolationEngine):
"""Behaves like ConfigParser."""
_cookie = '%'
_KEYCRE = re.compile(r"%\(([^)]*)\)s")
def _parse_match(self, match):
key = match.group(1)
value, section = self._fetch(key)
return key, value, section
class TemplateInterpolation(InterpolationEngine):
"""Behaves like string.Template."""
_cookie = '$'
_delimiter = '$'
_KEYCRE = re.compile(r"""
\$(?:
(?P<escaped>\$) | # Two $ signs
(?P<named>[_a-z][_a-z0-9]*) | # $name format
{(?P<braced>[^}]*)} # ${name} format
)
""", re.IGNORECASE | re.VERBOSE)
def _parse_match(self, match):
# Valid name (in or out of braces): fetch value from section
key = match.group('named') or match.group('braced')
if key is not None:
value, section = self._fetch(key)
return key, value, section
# Escaped delimiter (e.g., $$): return single delimiter
if match.group('escaped') is not None:
# Return None for key and section to indicate it's time to stop
return None, self._delimiter, None
# Anything else: ignore completely, just return it unchanged
return None, match.group(), None
interpolation_engines = {
'configparser': ConfigParserInterpolation,
'template': TemplateInterpolation,
}
def __newobj__(cls, *args):
# Hack for pickle
return cls.__new__(cls, *args)
class Section(dict):
"""
A dictionary-like object that represents a section in a config file.
It does string interpolation if the 'interpolation' attribute
of the 'main' object is set to True.
Interpolation is tried first from this object, then from the 'DEFAULT'
section of this object, next from the parent and its 'DEFAULT' section,
and so on until the main object is reached.
A Section will behave like an ordered dictionary - following the
order of the ``scalars`` and ``sections`` attributes.
You can use this to change the order of members.
Iteration follows the order: scalars, then sections.
"""
def __setstate__(self, state):
dict.update(self, state[0])
self.__dict__.update(state[1])
def __reduce__(self):
state = (dict(self), self.__dict__)
return (__newobj__, (self.__class__,), state)
def __init__(self, parent, depth, main, indict=None, name=None):
"""
* parent is the section above
* depth is the depth level of this section
* main is the main ConfigObj
* indict is a dictionary to initialise the section with
"""
if indict is None:
indict = {}
dict.__init__(self)
# used for nesting level *and* interpolation
self.parent = parent
# used for the interpolation attribute
self.main = main
# level of nesting depth of this Section
self.depth = depth
# purely for information
self.name = name
#
self._initialise()
# we do this explicitly so that __setitem__ is used properly
# (rather than just passing to ``dict.__init__``)
for entry, value in indict.items():
self[entry] = value
def _initialise(self):
# the sequence of scalar values in this Section
self.scalars = []
# the sequence of sections in this Section
self.sections = []
# for comments :-)
self.comments = {}
self.inline_comments = {}
# the configspec
self.configspec = None
# for defaults
self.defaults = []
self.default_values = {}
self.extra_values = []
self._created = False
def _interpolate(self, key, value):
try:
# do we already have an interpolation engine?
engine = self._interpolation_engine
except AttributeError:
# not yet: first time running _interpolate(), so pick the engine
name = self.main.interpolation
if name == True: # note that "if name:" would be incorrect here
# backwards-compatibility: interpolation=True means use default
name = DEFAULT_INTERPOLATION
name = name.lower() # so that "Template", "template", etc. all work
class_ = interpolation_engines.get(name, None)
if class_ is None:
# invalid value for self.main.interpolation
self.main.interpolation = False
return value
else:
# save reference to engine so we don't have to do this again
engine = self._interpolation_engine = class_(self)
# let the engine do the actual work
return engine.interpolate(key, value)
def __getitem__(self, key):
"""Fetch the item and do string interpolation."""
val = dict.__getitem__(self, key)
if self.main.interpolation:
if isinstance(val, six.string_types):
return self._interpolate(key, val)
if isinstance(val, list):
def _check(entry):
if isinstance(entry, six.string_types):
return self._interpolate(key, entry)
return entry
new = [_check(entry) for entry in val]
if new != val:
return new
return val
def __setitem__(self, key, value, unrepr=False):
"""
Correctly set a value.
Making dictionary values Section instances.
(We have to special case 'Section' instances - which are also dicts)
Keys must be strings.
Values need only be strings (or lists of strings) if
``main.stringify`` is set.
``unrepr`` must be set when setting a value to a dictionary, without
creating a new sub-section.
"""
if not isinstance(key, six.string_types):
raise ValueError('The key "%s" is not a string.' % key)
# add the comment
if key not in self.comments:
self.comments[key] = []
self.inline_comments[key] = ''
# remove the entry from defaults
if key in self.defaults:
self.defaults.remove(key)
#
if isinstance(value, Section):
if key not in self:
self.sections.append(key)
dict.__setitem__(self, key, value)
elif isinstance(value, collections.Mapping) and not unrepr:
# First create the new depth level,
# then create the section
if key not in self:
self.sections.append(key)
new_depth = self.depth + 1
dict.__setitem__(
self,
key,
Section(
self,
new_depth,
self.main,
indict=value,
name=key))
else:
if key not in self:
self.scalars.append(key)
if not self.main.stringify:
if isinstance(value, six.string_types):
pass
elif isinstance(value, (list, tuple)):
for entry in value:
if not isinstance(entry, six.string_types):
raise TypeError('Value is not a string "%s".' % entry)
else:
raise TypeError('Value is not a string "%s".' % value)
dict.__setitem__(self, key, value)
def __delitem__(self, key):
"""Remove items from the sequence when deleting."""
dict. __delitem__(self, key)
if key in self.scalars:
self.scalars.remove(key)
else:
self.sections.remove(key)
del self.comments[key]
del self.inline_comments[key]
def get(self, key, default=None):
"""A version of ``get`` that doesn't bypass string interpolation."""
try:
return self[key]
except KeyError:
return default
def update(self, indict):
"""
A version of update that uses our ``__setitem__``.
"""
for entry in indict:
self[entry] = indict[entry]
def pop(self, key, default=MISSING):
"""
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised'
"""
try:
val = self[key]
except KeyError:
if default is MISSING:
raise
val = default
else:
del self[key]
return val
def popitem(self):
"""Pops the first (key,val)"""
sequence = (self.scalars + self.sections)
if not sequence:
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
return key, val
def clear(self):
"""
A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected
"""
dict.clear(self)
self.scalars = []
self.sections = []
self.comments = {}
self.inline_comments = {}
self.configspec = None
self.defaults = []
self.extra_values = []
def setdefault(self, key, default=None):
"""A version of setdefault that sets sequence if appropriate."""
try:
return self[key]
except KeyError:
self[key] = default
return self[key]
def items(self):
"""D.items() -> list of D's (key, value) pairs, as 2-tuples"""
return list(zip((self.scalars + self.sections), list(self.values())))
def keys(self):
"""D.keys() -> list of D's keys"""
return (self.scalars + self.sections)
def values(self):
"""D.values() -> list of D's values"""
return [self[key] for key in (self.scalars + self.sections)]
def iteritems(self):
"""D.iteritems() -> an iterator over the (key, value) items of D"""
return iter(list(self.items()))
def iterkeys(self):
"""D.iterkeys() -> an iterator over the keys of D"""
return iter((self.scalars + self.sections))
__iter__ = iterkeys
def itervalues(self):
"""D.itervalues() -> an iterator over the values of D"""
return iter(list(self.values()))
def __repr__(self):
"""x.__repr__() <==> repr(x)"""
def _getval(key):
try:
return self[key]
except MissingInterpolationOption:
return dict.__getitem__(self, key)
return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(_getval(key))))
for key in (self.scalars + self.sections)])
__str__ = __repr__
__str__.__doc__ = "x.__str__() <==> str(x)"
# Extra methods - not in a normal dictionary
def dict(self):
"""
Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0
"""
newdict = {}
for entry in self:
this_entry = self[entry]
if isinstance(this_entry, Section):
this_entry = this_entry.dict()
elif isinstance(this_entry, list):
# create a copy rather than a reference
this_entry = list(this_entry)
elif isinstance(this_entry, tuple):
# create a copy rather than a reference
this_entry = tuple(this_entry)
newdict[entry] = this_entry
return newdict
def merge(self, indict):
"""
A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... [section1]
... option1 = False
... # end of file'''.splitlines()
>>> c1 = ConfigObj(b)
>>> c2 = ConfigObj(a)
>>> c2.merge(c1)
>>> c2
ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}})
"""
for key, val in list(indict.items()):
if (key in self and isinstance(self[key], collections.Mapping) and
isinstance(val, collections.Mapping)):
self[key].merge(val)
else:
self[key] = val
def rename(self, oldkey, newkey):
"""
Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.
"""
if oldkey in self.scalars:
the_list = self.scalars
elif oldkey in self.sections:
the_list = self.sections
else:
raise KeyError('Key "%s" not found.' % oldkey)
pos = the_list.index(oldkey)
#
val = self[oldkey]
dict.__delitem__(self, oldkey)
dict.__setitem__(self, newkey, val)
the_list.remove(oldkey)
the_list.insert(pos, newkey)
comm = self.comments[oldkey]
inline_comment = self.inline_comments[oldkey]
del self.comments[oldkey]
del self.inline_comments[oldkey]
self.comments[newkey] = comm
self.inline_comments[newkey] = inline_comment
def walk(self, function, raise_errors=True,
call_on_sections=False, **keywargs):
"""
Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=False``, in which case set the return value to
``False``.
Any unrecognised keyword arguments you pass to walk, will be pased on
to the function you pass in.
Note: if ``call_on_sections`` is ``True`` then - on encountering a
subsection, *first* the function is called for the *whole* subsection,
and then recurses into it's members. This means your function must be
able to handle strings, dictionaries and lists. This allows you
to change the key of subsections as well as for ordinary members. The
return value when called on the whole subsection has to be discarded.
See the encode and decode methods for examples, including functions.
.. admonition:: caution
You can use ``walk`` to transform the names of members of a section
but you mustn't add or delete members.
>>> config = '''[XXXXsection]
... XXXXkey = XXXXvalue'''.splitlines()
>>> cfg = ConfigObj(config)
>>> cfg
ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}})
>>> def transform(section, key):
... val = section[key]
... newkey = key.replace('XXXX', 'CLIENT1')
... section.rename(key, newkey)
... if isinstance(val, (tuple, list, dict)):
... pass
... else:
... val = val.replace('XXXX', 'CLIENT1')
... section[newkey] = val
>>> cfg.walk(transform, call_on_sections=True)
{'CLIENT1section': {'CLIENT1key': None}}
>>> cfg
ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})
"""
out = {}
# scalars first
for i in range(len(self.scalars)):
entry = self.scalars[i]
try:
val = function(self, entry, **keywargs)
# bound again in case name has changed
entry = self.scalars[i]
out[entry] = val
except Exception:
if raise_errors:
raise
else:
entry = self.scalars[i]
out[entry] = False
# then sections
for i in range(len(self.sections)):
entry = self.sections[i]
if call_on_sections:
try:
function(self, entry, **keywargs)
except Exception:
if raise_errors:
raise
else:
entry = self.sections[i]
out[entry] = False
# bound again in case name has changed
entry = self.sections[i]
# previous result is discarded
out[entry] = self[entry].walk(
function,
raise_errors=raise_errors,
call_on_sections=call_on_sections,
**keywargs)
return out
def as_bool(self, key):
"""
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``as_bool`` is not case sensitive.
Any other input will raise a ``ValueError``.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_bool('a')
Traceback (most recent call last):
ValueError: Value "fish" is neither True nor False
>>> a['b'] = 'True'
>>> a.as_bool('b')
1
>>> a['b'] = 'off'
>>> a.as_bool('b')
0
"""
val = self[key]
if val == True:
return True
elif val == False:
return False
else:
try:
if not isinstance(val, six.string_types):
# TODO: Why do we raise a KeyError here?
raise KeyError()
else:
return self.main._bools[val.lower()]
except KeyError:
raise ValueError('Value "%s" is neither True nor False' % val)
def as_int(self, key):
"""
A convenience method which coerces the specified value to an integer.
If the value is an invalid literal for ``int``, a ``ValueError`` will
be raised.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_int('a')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'fish'
>>> a['b'] = '1'
>>> a.as_int('b')
1
>>> a['b'] = '3.2'
>>> a.as_int('b')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '3.2'
"""
return int(self[key])
def as_float(self, key):
"""
A convenience method which coerces the specified value to a float.
If the value is an invalid literal for ``float``, a ``ValueError`` will
be raised.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_float('a') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError: invalid literal for float(): fish
>>> a['b'] = '1'
>>> a.as_float('b')
1.0
>>> a['b'] = '3.2'
>>> a.as_float('b') #doctest: +ELLIPSIS
3.2...
"""
return float(self[key])
def as_list(self, key):
"""
A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]
>>> a.as_list('a')
[1]
"""
result = self[key]
if isinstance(result, (tuple, list)):
return list(result)
return [result]
def restore_default(self, key):
"""
Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised.
"""
default = self.default_values[key]
dict.__setitem__(self, key, default)
if key not in self.defaults:
self.defaults.append(key)
return default
def restore_defaults(self):
"""
Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn't delete or modify entries without default values.
"""
for key in self.default_values:
self.restore_default(key)
for section in self.sections:
self[section].restore_defaults()
class ConfigObj(Section):
"""An object to read, create, and write config files."""
_keyword = re.compile(r'''^ # line start
(\s*) # indentation
( # keyword
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'"=].*?) # no quotes
)
\s*=\s* # divider
(.*) # value (including list values and comments)
$ # line end
''',
re.VERBOSE)
_sectionmarker = re.compile(r'''^
(\s*) # 1: indentation
((?:\[\s*)+) # 2: section marker open
( # 3: section name open
(?:"\s*\S.*?\s*")| # at least one non-space with double quotes
(?:'\s*\S.*?\s*')| # at least one non-space with single quotes
(?:[^'"\s].*?) # at least one non-space unquoted
) # section name close
((?:\s*\])+) # 4: section marker close
\s*(\#.*)? # 5: optional comment
$''',
re.VERBOSE)
# this regexp pulls list values out as a single string
# or single values and comments
# FIXME: this regex adds a '' to the end of comma terminated lists
# workaround in ``_handle_value``
_valueexp = re.compile(r'''^
(?:
(?:
(
(?:
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\#][^,\#]*?) # unquoted
)
\s*,\s* # comma
)* # match all list items ending in a comma (if any)
)
(
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\#\s][^,]*?)| # unquoted
(?:(?<!,)) # Empty value
)? # last item in a list - or string value
)|
(,) # alternatively a single comma - empty list
)
\s*(\#.*)? # optional comment
$''',
re.VERBOSE)
# use findall to get the members of a list value
_listvalueexp = re.compile(r'''
(
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\#]?.*?) # unquoted
)
\s*,\s* # comma
''',
re.VERBOSE)
# this regexp is used for the value
# when lists are switched off
_nolistvalue = re.compile(r'''^
(
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'"\#].*?)| # unquoted
(?:) # Empty value
)
\s*(\#.*)? # optional comment
$''',
re.VERBOSE)
# regexes for finding triple quoted values on one line
_single_line_single = re.compile(r"^'''(.*?)'''\s*(#.*)?$")
_single_line_double = re.compile(r'^"""(.*?)"""\s*(#.*)?$')
_multi_line_single = re.compile(r"^(.*?)'''\s*(#.*)?$")
_multi_line_double = re.compile(r'^(.*?)"""\s*(#.*)?$')
_triple_quote = {
"'''": (_single_line_single, _multi_line_single),
'"""': (_single_line_double, _multi_line_double),
}
# Used by the ``istrue`` Section method
_bools = {
'yes': True, 'no': False,
'on': True, 'off': False,
'1': True, '0': False,
'true': True, 'false': False,
}
def __init__(self, infile=None, options=None, configspec=None, encoding=None,
interpolation=True, raise_errors=False, list_values=True,
create_empty=False, file_error=False, stringify=True,
indent_type=None, default_encoding=None, unrepr=False,
write_empty_values=False, _inspec=False):
"""
Parse a config file or create a config file object.
``ConfigObj(infile=None, configspec=None, encoding=None,
interpolation=True, raise_errors=False, list_values=True,
create_empty=False, file_error=False, stringify=True,
indent_type=None, default_encoding=None, unrepr=False,
write_empty_values=False, _inspec=False)``
"""
self._inspec = _inspec
# init the superclass
Section.__init__(self, self, 0, self)
infile = infile or []
_options = {'configspec': configspec,
'encoding': encoding, 'interpolation': interpolation,
'raise_errors': raise_errors, 'list_values': list_values,
'create_empty': create_empty, 'file_error': file_error,
'stringify': stringify, 'indent_type': indent_type,
'default_encoding': default_encoding, 'unrepr': unrepr,
'write_empty_values': write_empty_values}
if options is None:
options = _options
else:
import warnings
warnings.warn('Passing in an options dictionary to ConfigObj() is '
'deprecated. Use **options instead.',
DeprecationWarning)
# TODO: check the values too.
for entry in options:
if entry not in OPTION_DEFAULTS:
raise TypeError('Unrecognised option "%s".' % entry)
for entry, value in list(OPTION_DEFAULTS.items()):
if entry not in options:
options[entry] = value
keyword_value = _options[entry]
if value != keyword_value:
options[entry] = keyword_value
# XXXX this ignores an explicit list_values = True in combination
# with _inspec. The user should *never* do that anyway, but still...
if _inspec:
options['list_values'] = False
self._initialise(options)
configspec = options['configspec']
self._original_configspec = configspec
self._load(infile, configspec)
def _load(self, infile, configspec):
if isinstance(infile, six.string_types):
self.filename = infile
if os.path.isfile(infile):
with open(infile, 'rb') as h:
content = h.readlines() or []
elif self.file_error:
# raise an error if the file doesn't exist
raise IOError('Config file not found: "%s".' % self.filename)
else:
# file doesn't already exist
if self.create_empty:
# this is a good test that the filename specified
# isn't impossible - like on a non-existent device
with open(infile, 'w') as h:
h.write('')
content = []
elif isinstance(infile, (list, tuple)):
content = list(infile)
elif isinstance(infile, dict):
# initialise self
# the Section class handles creating subsections
if isinstance(infile, ConfigObj):
# get a copy of our ConfigObj
def set_section(in_section, this_section):
for entry in in_section.scalars:
this_section[entry] = in_section[entry]
for section in in_section.sections:
this_section[section] = {}
set_section(in_section[section], this_section[section])
set_section(infile, self)
else:
for entry in infile:
self[entry] = infile[entry]
del self._errors
if configspec is not None:
self._handle_configspec(configspec)
else:
self.configspec = None
return
elif getattr(infile, 'read', MISSING) is not MISSING:
# This supports file like objects
content = infile.read() or []
# needs splitting into lines - but needs doing *after* decoding
# in case it's not an 8 bit encoding
else:
raise TypeError('infile must be a filename, file like object, or list of lines.')
if content:
# don't do it for the empty ConfigObj
content = self._handle_bom(content)
# infile is now *always* a list
#
# Set the newlines attribute (first line ending it finds)
# and strip trailing '\n' or '\r' from lines
for line in content:
if (not line) or (line[-1] not in ('\r', '\n')):
continue
for end in ('\r\n', '\n', '\r'):
if line.endswith(end):
self.newlines = end
break
break
assert all(isinstance(line, six.string_types) for line in content), repr(content)
content = [line.rstrip('\r\n') for line in content]
self._parse(content)
# if we had any errors, now is the time to raise them
if self._errors:
info = "at line %s." % self._errors[0].line_number
if len(self._errors) > 1:
msg = "Parsing failed with several errors.\nFirst error %s" % info
error = ConfigObjError(msg)
else:
error = self._errors[0]
# set the errors attribute; it's a list of tuples:
# (error_type, message, line_number)
error.errors = self._errors
# set the config attribute
error.config = self
raise error
# delete private attributes
del self._errors
if configspec is None:
self.configspec = None
else:
self._handle_configspec(configspec)
def _initialise(self, options=None):
if options is None:
options = OPTION_DEFAULTS
# initialise a few variables
self.filename = None
self._errors = []
self.raise_errors = options['raise_errors']
self.interpolation = options['interpolation']
self.list_values = options['list_values']
self.create_empty = options['create_empty']
self.file_error = options['file_error']
self.stringify = options['stringify']
self.indent_type = options['indent_type']
self.encoding = options['encoding']
self.default_encoding = options['default_encoding']
self.BOM = False
self.newlines = None
self.write_empty_values = options['write_empty_values']
self.unrepr = options['unrepr']
self.initial_comment = []
self.final_comment = []
self.configspec = None
if self._inspec:
self.list_values = False
# Clear section attributes as well
Section._initialise(self)
def __repr__(self):
def _getval(key):
try:
return self[key]
except MissingInterpolationOption:
return dict.__getitem__(self, key)
return ('%s({%s})' % (self.__class__.__name__,
', '.join([('%s: %s' % (repr(key), repr(_getval(key))))
for key in (self.scalars + self.sections)])))
def _handle_bom(self, infile):
"""
Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding won't be discovered or removed.)
If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
removed. The BOM attribute will be set. UTF16 will be decoded to
unicode.
NOTE: This method must not be called with an empty ``infile``.
Specifying the *wrong* encoding is likely to cause a
``UnicodeDecodeError``.
``infile`` must always be returned as a list of lines, but may be
passed in as a single string.
"""
if ((self.encoding is not None) and
(self.encoding.lower() not in BOM_LIST)):
# No need to check for a BOM
# the encoding specified doesn't have one
# just decode
return self._decode(infile, self.encoding)
if isinstance(infile, (list, tuple)):
line = infile[0]
else:
line = infile
if isinstance(line, six.text_type):
# it's already decoded and there's no need to do anything
# else, just use the _decode utility method to handle
# listifying appropriately
return self._decode(infile, self.encoding)
if self.encoding is not None:
# encoding explicitly supplied
# And it could have an associated BOM
# TODO: if encoding is just UTF16 - we ought to check for both
# TODO: big endian and little endian versions.
enc = BOM_LIST[self.encoding.lower()]
if enc == 'utf_16':
# For UTF16 we try big endian and little endian
for BOM, (encoding, final_encoding) in list(BOMS.items()):
if not final_encoding:
# skip UTF8
continue
if infile.startswith(BOM):
### BOM discovered
##self.BOM = True
# Don't need to remove BOM
return self._decode(infile, encoding)
# If we get this far, will *probably* raise a DecodeError
# As it doesn't appear to start with a BOM
return self._decode(infile, self.encoding)
# Must be UTF8
BOM = BOM_SET[enc]
if not line.startswith(BOM):
return self._decode(infile, self.encoding)
newline = line[len(BOM):]
# BOM removed
if isinstance(infile, (list, tuple)):
infile[0] = newline
else:
infile = newline
self.BOM = True
return self._decode(infile, self.encoding)
# No encoding specified - so we need to check for UTF8/UTF16
for BOM, (encoding, final_encoding) in list(BOMS.items()):
if not isinstance(line, six.binary_type) or not line.startswith(BOM):
# didn't specify a BOM, or it's not a bytestring
continue
else:
# BOM discovered
self.encoding = final_encoding
if not final_encoding:
self.BOM = True
# UTF8
# remove BOM
newline = line[len(BOM):]
if isinstance(infile, (list, tuple)):
infile[0] = newline
else:
infile = newline
# UTF-8
if isinstance(infile, six.text_type):
return infile.splitlines(True)
elif isinstance(infile, six.binary_type):
return infile.decode('utf-8').splitlines(True)
else:
return self._decode(infile, 'utf-8')
# UTF16 - have to decode
return self._decode(infile, encoding)
if six.PY2 and isinstance(line, str):
# don't actually do any decoding, since we're on python 2 and
# returning a bytestring is fine
return self._decode(infile, None)
# No BOM discovered and no encoding specified, default to UTF-8
if isinstance(infile, six.binary_type):
return infile.decode('utf-8').splitlines(True)
else:
return self._decode(infile, 'utf-8')
def _a_to_u(self, aString):
"""Decode ASCII strings to unicode if a self.encoding is specified."""
if isinstance(aString, six.binary_type) and self.encoding:
return aString.decode(self.encoding)
else:
return aString
def _decode(self, infile, encoding):
"""
Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.
"""
if isinstance(infile, six.string_types):
return infile.splitlines(True)
if isinstance(infile, six.binary_type):
# NOTE: Could raise a ``UnicodeDecodeError``
if encoding:
return infile.decode(encoding).splitlines(True)
else:
return infile.splitlines(True)
if encoding:
for i, line in enumerate(infile):
if isinstance(line, six.binary_type):
# NOTE: The isinstance test here handles mixed lists of unicode/string
# NOTE: But the decode will break on any non-string values
# NOTE: Or could raise a ``UnicodeDecodeError``
infile[i] = line.decode(encoding)
return infile
def _decode_element(self, line):
"""Decode element to unicode if necessary."""
if isinstance(line, six.binary_type) and self.default_encoding:
return line.decode(self.default_encoding)
else:
return line
# TODO: this may need to be modified
def _str(self, value):
"""
Used by ``stringify`` within validate, to turn non-string values
into strings.
"""
if not isinstance(value, six.string_types):
# intentially 'str' because it's just whatever the "normal"
# string type is for the python version we're dealing with
return str(value)
else:
return value
def _parse(self, infile):
"""Actually parse the config file."""
temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = len(infile) - 1
cur_index = -1
reset_comment = False
while cur_index < maxline:
if reset_comment:
comment_list = []
cur_index += 1
line = infile[cur_index]
sline = line.strip()
# do we have anything on the line ?
if not sline or sline.startswith('#'):
reset_comment = False
comment_list.append(line)
continue
if not done_start:
# preserve initial comment
self.initial_comment = comment_list
comment_list = []
done_start = True
reset_comment = True
# first we check if it's a section marker
mat = self._sectionmarker.match(line)
if mat is not None:
# is a section line
(indent, sect_open, sect_name, sect_close, comment) = mat.groups()
if indent and (self.indent_type is None):
self.indent_type = indent
cur_depth = sect_open.count('[')
if cur_depth != sect_close.count(']'):
self._handle_error("Cannot compute the section depth",
NestingError, infile, cur_index)
continue
if cur_depth < this_section.depth:
# the new section is dropping back to a previous level
try:
parent = self._match_depth(this_section,
cur_depth).parent
except SyntaxError:
self._handle_error("Cannot compute nesting level",
NestingError, infile, cur_index)
continue
elif cur_depth == this_section.depth:
# the new section is a sibling of the current section
parent = this_section.parent
elif cur_depth == this_section.depth + 1:
# the new section is a child the current section
parent = this_section
else:
self._handle_error("Section too nested",
NestingError, infile, cur_index)
continue
sect_name = self._unquote(sect_name)
if sect_name in parent:
self._handle_error('Duplicate section name',
DuplicateError, infile, cur_index)
continue
# create the new section
this_section = Section(
parent,
cur_depth,
self,
name=sect_name)
parent[sect_name] = this_section
parent.inline_comments[sect_name] = comment
parent.comments[sect_name] = comment_list
continue
#
# it's not a section marker,
# so it should be a valid ``key = value`` line
mat = self._keyword.match(line)
if mat is None:
self._handle_error(
'Invalid line ({0!r}) (matched as neither section nor keyword)'.format(line),
ParseError, infile, cur_index)
else:
# is a keyword value
# value will include any inline comment
(indent, key, value) = mat.groups()
if indent and (self.indent_type is None):
self.indent_type = indent
# check for a multiline value
if value[:3] in ['"""', "'''"]:
try:
value, comment, cur_index = self._multiline(
value, infile, cur_index, maxline)
except SyntaxError:
self._handle_error(
'Parse error in multiline value',
ParseError, infile, cur_index)
continue
else:
if self.unrepr:
comment = ''
try:
value = unrepr(value)
except Exception as e:
if type(e) == UnknownType:
msg = 'Unknown name or type in value'
else:
msg = 'Parse error from unrepr-ing multiline value'
self._handle_error(msg, UnreprError, infile,
cur_index)
continue
else:
if self.unrepr:
comment = ''
try:
value = unrepr(value)
except Exception as e:
if isinstance(e, UnknownType):
msg = 'Unknown name or type in value'
else:
msg = 'Parse error from unrepr-ing value'
self._handle_error(msg, UnreprError, infile,
cur_index)
continue
else:
# extract comment and lists
try:
(value, comment) = self._handle_value(value)
except SyntaxError:
self._handle_error(
'Parse error in value',
ParseError, infile, cur_index)
continue
#
key = self._unquote(key)
if key in this_section:
self._handle_error(
'Duplicate keyword name',
DuplicateError, infile, cur_index)
continue
# add the key.
# we set unrepr because if we have got this far we will never
# be creating a new section
this_section.__setitem__(key, value, unrepr=True)
this_section.inline_comments[key] = comment
this_section.comments[key] = comment_list
continue
#
if self.indent_type is None:
# no indentation used, set the type accordingly
self.indent_type = ''
# preserve the final comment
if not self and not self.initial_comment:
self.initial_comment = comment_list
elif not reset_comment:
self.final_comment = comment_list
self.list_values = temp_list_values
def _match_depth(self, sect, depth):
"""
Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError.
"""
while depth < sect.depth:
if sect is sect.parent:
# we've reached the top level already
raise SyntaxError()
sect = sect.parent
if sect.depth == depth:
return sect
# shouldn't get here
raise SyntaxError()
def _handle_error(self, text, ErrorClass, infile, cur_index):
"""
Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index``
"""
line = infile[cur_index]
cur_index += 1
message = '{0} at line {1}.'.format(text, cur_index)
error = ErrorClass(message, cur_index, line)
if self.raise_errors:
# raise the error - parsing stops here
raise error
# store the error
# reraise when parsing has finished
self._errors.append(error)
def _unquote(self, value):
"""Return an unquoted version of a value"""
if not value:
# should only happen during parsing of lists
raise SyntaxError
if (value[0] == value[-1]) and (value[0] in ('"', "'")):
value = value[1:-1]
return value
def _quote(self, value, multiline=True):
"""
Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don't quote values that don't need it.
* Recursively quote members of a list and return a comma joined list.
* Multiline is ``False`` for lists.
* Obey list syntax for empty and single member lists.
If ``list_values=False`` then the value is only quoted if it contains
a ``\\n`` (is multiline) or '#'.
If ``write_empty_values`` is set, and the value is an empty string, it
won't be quoted.
"""
if multiline and self.write_empty_values and value == '':
# Only if multiline is set, so that it is used for values not
# keys, and not values that are part of a list
return ''
if multiline and isinstance(value, (list, tuple)):
if not value:
return ','
elif len(value) == 1:
return self._quote(value[0], multiline=False) + ','
return ', '.join([self._quote(val, multiline=False)
for val in value])
if not isinstance(value, six.string_types):
if self.stringify:
# intentially 'str' because it's just whatever the "normal"
# string type is for the python version we're dealing with
value = str(value)
else:
raise TypeError('Value "%s" is not a string.' % value)
if not value:
return '""'
no_lists_no_quotes = not self.list_values and '\n' not in value and '#' not in value
need_triple = multiline and ((("'" in value) and ('"' in value)) or ('\n' in value ))
hash_triple_quote = multiline and not need_triple and ("'" in value) and ('"' in value) and ('#' in value)
check_for_single = (no_lists_no_quotes or not need_triple) and not hash_triple_quote
if check_for_single:
if not self.list_values:
# we don't quote if ``list_values=False``
quot = noquot
# for normal values either single or double quotes will do
elif '\n' in value:
# will only happen if multiline is off - e.g. '\n' in key
raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
elif ((value[0] not in wspace_plus) and
(value[-1] not in wspace_plus) and
(',' not in value)):
quot = noquot
else:
quot = self._get_single_quote(value)
else:
# if value has '\n' or "'" *and* '"', it will need triple quotes
quot = self._get_triple_quote(value)
if quot == noquot and '#' in value and self.list_values:
quot = self._get_single_quote(value)
return quot % value
def _get_single_quote(self, value):
if ("'" in value) and ('"' in value):
raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
elif '"' in value:
quot = squot
else:
quot = dquot
return quot
def _get_triple_quote(self, value):
if (value.find('"""') != -1) and (value.find("'''") != -1):
raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
if value.find('"""') == -1:
quot = tdquot
else:
quot = tsquot
return quot
def _handle_value(self, value):
"""
Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)
"""
if self._inspec:
# Parsing a configspec so don't handle comments
return (value, '')
# do we look for lists in values ?
if not self.list_values:
mat = self._nolistvalue.match(value)
if mat is None:
raise SyntaxError()
# NOTE: we don't unquote here
return mat.groups()
#
mat = self._valueexp.match(value)
if mat is None:
# the value is badly constructed, probably badly quoted,
# or an invalid list
raise SyntaxError()
(list_values, single, empty_list, comment) = mat.groups()
if (list_values == '') and (single is None):
# change this if you want to accept empty values
raise SyntaxError()
# NOTE: note there is no error handling from here if the regex
# is wrong: then incorrect values will slip through
if empty_list is not None:
# the single comma - meaning an empty list
return ([], comment)
if single is not None:
# handle empty values
if list_values and not single:
# FIXME: the '' is a workaround because our regex now matches
# '' at the end of a list if it has a trailing comma
single = None
else:
single = single or '""'
single = self._unquote(single)
if list_values == '':
# not a list value
return (single, comment)
the_list = self._listvalueexp.findall(list_values)
the_list = [self._unquote(val) for val in the_list]
if single is not None:
the_list += [single]
return (the_list, comment)
def _multiline(self, value, infile, cur_index, maxline):
"""Extract the value, where we are in a multiline situation."""
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)
if mat is not None:
retval = list(mat.groups())
retval.append(cur_index)
return retval
elif newvalue.find(quot) != -1:
# somehow the triple quote is missing
raise SyntaxError()
#
while cur_index < maxline:
cur_index += 1
newvalue += '\n'
line = infile[cur_index]
if line.find(quot) == -1:
newvalue += line
else:
# end of multiline, process it
break
else:
# we've got to the end of the config, oops...
raise SyntaxError()
mat = multi_line.match(line)
if mat is None:
# a badly formed line
raise SyntaxError()
(value, comment) = mat.groups()
return (newvalue + value, comment, cur_index)
def _handle_configspec(self, configspec):
"""Parse the configspec."""
# FIXME: Should we check that the configspec was created with the
# correct settings ? (i.e. ``list_values=False``)
if not isinstance(configspec, ConfigObj):
try:
configspec = ConfigObj(configspec,
raise_errors=True,
file_error=True,
_inspec=True)
except ConfigObjError as e:
# FIXME: Should these errors have a reference
# to the already parsed ConfigObj ?
raise ConfigspecError('Parsing configspec failed: %s' % e)
except IOError as e:
raise IOError('Reading configspec failed: %s' % e)
self.configspec = configspec
def _set_configspec(self, section, copy):
"""
Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__
"""
configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
for entry in section.sections:
if entry not in configspec:
section[entry].configspec = many
for entry in configspec.sections:
if entry == '__many__':
continue
if entry not in section:
section[entry] = {}
section[entry]._created = True
if copy:
# copy comments
section.comments[entry] = configspec.comments.get(entry, [])
section.inline_comments[entry] = configspec.inline_comments.get(entry, '')
# Could be a scalar when we expect a section
if isinstance(section[entry], Section):
section[entry].configspec = configspec[entry]
def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return '%s%s%s%s%s' % (indent_string,
self._decode_element(self._quote(entry, multiline=False)),
self._a_to_u(' = '),
val,
self._decode_element(comment))
def _write_marker(self, indent_string, depth, entry, comment):
"""Write a section marker line"""
return '%s%s%s%s%s' % (indent_string,
self._a_to_u('[' * depth),
self._quote(self._decode_element(entry), multiline=False),
self._a_to_u(']' * depth),
self._decode_element(comment))
def _handle_comment(self, comment):
"""Deal with a comment."""
if not comment:
return ''
start = self.indent_type
if not comment.startswith('#'):
start += self._a_to_u(' # ')
return (start + comment)
# Public methods
def write(self, outfile=None, section=None):
"""
Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = 'test.ini'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj('test.ini', raise_errors=True)
1
>>> import os
>>> os.remove('test.ini')
"""
if self.indent_type is None:
# this can be true if initialised from a dictionary
self.indent_type = DEFAULT_INDENT_TYPE
out = []
cs = self._a_to_u('#')
csp = self._a_to_u('# ')
if section is None:
int_val = self.interpolation
self.interpolation = False
section = self
for line in self.initial_comment:
line = self._decode_element(line)
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith(cs):
line = csp + line
out.append(line)
indent_string = self.indent_type * section.depth
for entry in (section.scalars + section.sections):
if entry in section.defaults:
# don't write out default values
continue
for comment_line in section.comments[entry]:
comment_line = self._decode_element(comment_line.lstrip())
if comment_line and not comment_line.startswith(cs):
comment_line = csp + comment_line
out.append(indent_string + comment_line)
this_entry = section[entry]
comment = self._handle_comment(section.inline_comments[entry])
if isinstance(this_entry, Section):
# a section
out.append(self._write_marker(
indent_string,
this_entry.depth,
entry,
comment))
out.extend(self.write(section=this_entry))
else:
out.append(self._write_line(
indent_string,
entry,
this_entry,
comment))
if section is self:
for line in self.final_comment:
line = self._decode_element(line)
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith(cs):
line = csp + line
out.append(line)
self.interpolation = int_val
if section is not self:
return out
if (self.filename is None) and (outfile is None):
# output a list of lines
# might need to encode
# NOTE: This will *screw* UTF16, each line will start with the BOM
if self.encoding:
out = [l.encode(self.encoding) for l in out]
if (self.BOM and ((self.encoding is None) or
(BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
# Add the UTF8 BOM
if not out:
out.append('')
out[0] = BOM_UTF8 + out[0]
return out
# Turn the list to a string, joined with correct newlines
newline = self.newlines or os.linesep
if (getattr(outfile, 'mode', None) is not None and outfile.mode == 'w'
and sys.platform == 'win32' and newline == '\r\n'):
# Windows specific hack to avoid writing '\r\r\n'
newline = '\n'
output = self._a_to_u(newline).join(out)
if not output.endswith(newline):
output += newline
if isinstance(output, six.binary_type):
output_bytes = output
else:
output_bytes = output.encode(self.encoding or
self.default_encoding or
'ascii')
if self.BOM and ((self.encoding is None) or match_utf8(self.encoding)):
# Add the UTF8 BOM
output_bytes = BOM_UTF8 + output_bytes
if outfile is not None:
outfile.write(output_bytes)
else:
with open(self.filename, 'wb') as h:
h.write(output_bytes)
def validate(self, validator, preserve_errors=False, copy=False,
section=None):
"""
Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(validator)
(Normally having previously passed in the configspec when the ConfigObj
was created - you can dynamically assign a dictionary of checks to the
``configspec`` attribute of a section though).
It returns ``True`` if everything passes, or a dictionary of
pass/fails (True/False). If every member of a subsection passes, it
will just have the value ``True``. (It also returns ``False`` if all
members fail).
In addition, it converts the values from strings to their native
types if their checks pass (and ``stringify`` is set).
If ``preserve_errors`` is ``True`` (``False`` is default) then instead
of a marking a fail with a ``False``, it will preserve the actual
exception object. This can contain info about the reason for failure.
For example the ``VdtValueTooSmallError`` indicates that the value
supplied was too small. If a value (or section) is missing it will
still be marked as ``False``.
You must have the validate module to use ``preserve_errors=True``.
You can then use the ``flatten_errors`` function to turn your nested
results dictionary into a flattened list of failures - useful for
displaying meaningful error messages.
"""
if section is None:
if self.configspec is None:
raise ValueError('No configspec supplied.')
if preserve_errors:
# We do this once to remove a top level dependency on the validate module
# Which makes importing configobj faster
from validate import VdtMissingValue
self._vdtMissingValue = VdtMissingValue
section = self
if copy:
section.initial_comment = section.configspec.initial_comment
section.final_comment = section.configspec.final_comment
section.encoding = section.configspec.encoding
section.BOM = section.configspec.BOM
section.newlines = section.configspec.newlines
section.indent_type = section.configspec.indent_type
#
# section.default_values.clear() #??
configspec = section.configspec
self._set_configspec(section, copy)
def validate_entry(entry, spec, val, missing, ret_true, ret_false):
section.default_values.pop(entry, None)
try:
section.default_values[entry] = validator.get_default_value(configspec[entry])
except (KeyError, AttributeError, validator.baseErrorClass):
# No default, bad default or validator has no 'get_default_value'
# (e.g. SimpleVal)
pass
try:
check = validator.check(spec,
val,
missing=missing
)
except validator.baseErrorClass as e:
if not preserve_errors or isinstance(e, self._vdtMissingValue):
out[entry] = False
else:
# preserve the error
out[entry] = e
ret_false = False
ret_true = False
else:
ret_false = False
out[entry] = True
if self.stringify or missing:
# if we are doing type conversion
# or the value is a supplied default
if not self.stringify:
if isinstance(check, (list, tuple)):
# preserve lists
check = [self._str(item) for item in check]
elif missing and check is None:
# convert the None from a default to a ''
check = ''
else:
check = self._str(check)
if (check != val) or missing:
section[entry] = check
if not copy and missing and entry not in section.defaults:
section.defaults.append(entry)
return ret_true, ret_false
#
out = {}
ret_true = True
ret_false = True
unvalidated = [k for k in section.scalars if k not in configspec]
incorrect_sections = [k for k in configspec.sections if k in section.scalars]
incorrect_scalars = [k for k in configspec.scalars if k in section.sections]
for entry in configspec.scalars:
if entry in ('__many__', '___many___'):
# reserved names
continue
if (not entry in section.scalars) or (entry in section.defaults):
# missing entries
# or entries from defaults
missing = True
val = None
if copy and entry not in section.scalars:
# copy comments
section.comments[entry] = (
configspec.comments.get(entry, []))
section.inline_comments[entry] = (
configspec.inline_comments.get(entry, ''))
#
else:
missing = False
val = section[entry]
ret_true, ret_false = validate_entry(entry, configspec[entry], val,
missing, ret_true, ret_false)
many = None
if '__many__' in configspec.scalars:
many = configspec['__many__']
elif '___many___' in configspec.scalars:
many = configspec['___many___']
if many is not None:
for entry in unvalidated:
val = section[entry]
ret_true, ret_false = validate_entry(entry, many, val, False,
ret_true, ret_false)
unvalidated = []
for entry in incorrect_scalars:
ret_true = False
if not preserve_errors:
out[entry] = False
else:
ret_false = False
msg = 'Value %r was provided as a section' % entry
out[entry] = validator.baseErrorClass(msg)
for entry in incorrect_sections:
ret_true = False
if not preserve_errors:
out[entry] = False
else:
ret_false = False
msg = 'Section %r was provided as a single value' % entry
out[entry] = validator.baseErrorClass(msg)
# Missing sections will have been created as empty ones when the
# configspec was read.
for entry in section.sections:
# FIXME: this means DEFAULT is not copied in copy mode
if section is self and entry == 'DEFAULT':
continue
if section[entry].configspec is None:
unvalidated.append(entry)
continue
if copy:
section.comments[entry] = configspec.comments.get(entry, [])
section.inline_comments[entry] = configspec.inline_comments.get(entry, '')
check = self.validate(validator, preserve_errors=preserve_errors, copy=copy, section=section[entry])
out[entry] = check
if check == False:
ret_true = False
elif check == True:
ret_false = False
else:
ret_true = False
section.extra_values = unvalidated
if preserve_errors and not section._created:
# If the section wasn't created (i.e. it wasn't missing)
# then we can't return False, we need to preserve errors
ret_false = False
#
if ret_false and preserve_errors and out:
# If we are preserving errors, but all
# the failures are from missing sections / values
# then we can return False. Otherwise there is a
# real failure that we need to preserve.
ret_false = not any(out.values())
if ret_true:
return True
elif ret_false:
return False
return out
def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# Just to be sure ;-)
self._original_configspec = None
def reload(self):
"""
Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn't have
a filename attribute pointing to a file.
"""
if not isinstance(self.filename, six.string_types):
raise ReloadError()
filename = self.filename
current_options = {}
for entry in OPTION_DEFAULTS:
if entry == 'configspec':
continue
current_options[entry] = getattr(self, entry)
configspec = self._original_configspec
current_options['configspec'] = configspec
self.clear()
self._initialise(current_options)
self._load(filename, configspec)
class SimpleVal(object):
"""
A simple validator.
Can be used to check that all members expected are present.
To use it, provide a configspec with all your members in (the value given
will be ignored). Pass an instance of ``SimpleVal`` to the ``validate``
method of your ``ConfigObj``. ``validate`` will return ``True`` if all
members are present, or a dictionary with True/False meaning
present/missing. (Whole missing sections will be replaced with ``False``)
"""
def __init__(self):
self.baseErrorClass = ConfigObjError
def check(self, check, member, missing=False):
"""A dummy check method, always returns the value unchanged."""
if missing:
raise self.baseErrorClass()
return member
def flatten_errors(cfg, res, levels=None, results=None):
"""
An example function that will turn a nested dictionary of results
(as returned by ``ConfigObj.validate``) into a flat list.
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
dictionary returned by ``validate``.
(This is a recursive function, so you shouldn't use the ``levels`` or
``results`` arguments - they are used by the function.)
Returns a list of keys that failed. Each member of the list is a tuple::
([list of sections...], key, result)
If ``validate`` was called with ``preserve_errors=False`` (the default)
then ``result`` will always be ``False``.
*list of sections* is a flattened list of sections that the key was found
in.
If the section was missing (or a section was expected and a scalar provided
- or vice-versa) then key will be ``None``.
If the value (or section) was missing then ``result`` will be ``False``.
If ``validate`` was called with ``preserve_errors=True`` and a value
was present, but failed the check, then ``result`` will be the exception
object returned. You can use this as a string that describes the failure.
For example *The value "3" is of the wrong type*.
"""
if levels is None:
# first time called
levels = []
results = []
if res == True:
return sorted(results)
if res == False or isinstance(res, Exception):
results.append((levels[:], None, res))
if levels:
levels.pop()
return sorted(results)
for (key, val) in list(res.items()):
if val == True:
continue
if isinstance(cfg.get(key), collections.Mapping):
# Go down one level
levels.append(key)
flatten_errors(cfg[key], val, levels, results)
continue
results.append((levels[:], key, val))
#
# Go up one level
if levels:
levels.pop()
#
return sorted(results)
def get_extra_values(conf, _prepend=()):
"""
Find all the values and sections not in the configspec from a validated
ConfigObj.
``get_extra_values`` returns a list of tuples where each tuple represents
either an extra section, or an extra value.
The tuples contain two values, a tuple representing the section the value
is in and the name of the extra values. For extra values in the top level
section the first member will be an empty tuple. For values in the 'foo'
section the first member will be ``('foo',)``. For members in the 'bar'
subsection of the 'foo' section the first member will be ``('foo', 'bar')``.
NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't
been validated it will return an empty list.
"""
out = []
out.extend([(_prepend, name) for name in conf.extra_values])
for name in conf.sections:
if name not in conf.extra_values:
out.extend(get_extra_values(conf[name], _prepend + (name,)))
return out
"""*A programming language is a medium of expression.* - Paul Graham"""
| mit |
pachay/sf2-hwioab | src/Ailove/UserBundle/AiloveUserBundle.php | 128 | <?php
namespace Ailove\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AiloveUserBundle extends Bundle
{
}
| mit |
rmagick/rmagick.github.io | ex/texture_fill_to_border.rb | 926 | #!/home/software/ruby-1.8.7/bin/ruby -w
require 'RMagick'
# Demonstrate the Image#texture_fill_to_border method
# This example is nearly identical to the color_fill_to_border example.
before = Magick::Image.new(200,200) {
self.background_color = 'white'
self.border_color = 'black'
}
before.border!(1,1,'black')
circle = Magick::Draw.new
circle.fill('transparent')
circle.stroke('black')
circle.stroke_width(2)
circle.circle(100,100,180,100)
circle.fill('plum1')
circle.stroke('transparent')
circle.circle( 60,100, 40,100)
circle.circle(140,100,120,100)
circle.circle(100, 60,100, 40)
circle.circle(100,140,100,120)
circle.draw(before)
before.compression = Magick::LZWCompression
before.write('texture_fill_to_border_before.gif')
hat = Magick::Image.read('images/Flower_Hat.jpg').first
hat.resize!(0.3)
after = before.texture_fill_to_border(100,100, hat)
after.write('texture_fill_to_border_after.gif')
exit
| mit |
jtbaldwin/Alexa-Trash-Day | src/test/java/alexatesting/DataRequestTest.java | 5090 | package alexatesting;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JUnit tests for {@link TestDataRequest} class.
*
* @author J. Todd Baldwin
* @see <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-interface-reference#response-format">Alexa Skills Kit Docs: JSON Interface Reference for Custom Skills</a>
*/
@RunWith(JUnit4.class)
public class DataRequestTest {
/** Log object for this class */
private static final Logger log = LoggerFactory.getLogger(DataRequestTest.class);
/** Example of an actual {@link com.amazon.speech.speechlet.SpeechletRequest.IntentRequest} when converted to JSON and formatted. */
private static final String testRequestBasicExample =
"{\n"+
" \"session\": {\n"+
" \"sessionId\": \"SessionId.d9e67a5b-9380-471d-bb17-01fcf6efe006\",\n"+
" \"application\": {\n"+
" \"applicationId\": \"TEST-AMAZON-APPLICATION-ID\"\n"+
" },\n"+
" \"attributes\": {},\n"+
" \"user\": {\n"+
" \"userId\": \"TEST-USER-ID\"\n"+
" },\n"+
" \"new\": true\n"+
" },\n"+
" \"request\": {\n"+
" \"type\": \"IntentRequest\",\n"+
" \"requestId\": \"EdwRequestId.e58f0b97-8cfc-4165-8377-1f3071a1431b\",\n"+
" \"locale\": \"en-US\",\n"+
" \"timestamp\": \"2016-11-24T15:27:15Z\",\n"+ // Thursday
" \"intent\": {\n"+
" \"name\": \"TellNextPickupIntent\",\n"+
" \"slots\": {}\n"+
" }\n"+
" },\n"+
" \"version\": \"1.0\"\n"+
"}";
/** Example of an actual {@link com.amazon.speech.speechlet.SpeechletRequest.IntentRequest} when converted to JSON and formatted. */
private static final String testRequestComplexExample =
"{\n"+
" \"session\": {\n"+
" \"sessionId\": \"SessionId.ceaf16e6-3566-4a1a-b2d4-620422f3fda5\",\n"+
" \"application\": {\n"+
" \"applicationId\": \"TEST-AMAZON-APPLICATION-ID\"\n"+
" },\n"+
" \"attributes\": {},\n"+
" \"user\": {\n"+
" \"userId\": \"TEST-USER-ID\"\n"+
" },\n"+
" \"new\": true\n"+
" },\n"+
" \"request\": {\n"+
" \"type\": \"IntentRequest\",\n"+
" \"requestId\": \"EdwRequestId.60c03ee3-82b9-404e-afed-7887bb1f7ff2\",\n"+
" \"locale\": \"en-US\",\n"+
" \"timestamp\": \"2016-11-29T01:46:34Z\",\n"+
" \"intent\": {\n"+
" \"name\": \"AddScheduleIntent\",\n"+
" \"slots\": {\n"+
" \"DayOfWeek\": {\n"+
" \"name\": \"DayOfWeek\",\n"+
" \"value\": \"Monday\"\n"+
" },\n"+
" \"TimeOfDay\": {\n"+
" \"name\": \"TimeOfDay\",\n"+
" \"value\": \"16:00\"\n"+
" },\n"+
" \"PickupName\": {\n"+
" \"name\": \"PickupName\",\n"+
" \"value\": \"mail\"\n"+
" }\n"+
" }\n"+
" }\n"+
" },\n"+
" \"version\": \"1.0\"\n"+
"}";
/**
* JUnit test to confirm that a {@link TestDataRequest} object,
* when configured correctly and converted to JSON, will
* successfully match an actual JSON string generated from a
* {@link com.amazon.speech.speechlet.SpeechletRequest}
*/
@Test
public void testTestDataBasicRequest() {
log.info("testTestDataBasicRequest");
String expectedJson = testRequestBasicExample;
log.debug("testTestDataBasicRequest expected={}", expectedJson);
TestDataRequest testRequest = new TestDataRequest();
String actualJson = testRequest.toString();
log.debug("testTestDataBasicRequest actual={}", actualJson);
assertEquals(expectedJson, actualJson);
}
/**
* JUnit test to confirm that a {@link TestDataRequest} object,
* when configured correctly and converted to JSON, will
* successfully match an actual JSON string generated from a
* {@link com.amazon.speech.speechlet.SpeechletRequest}
*/
@Test
public void testTestDataComplexRequest() {
log.info("testTestDataComplexRequest");
String expectedJson = testRequestComplexExample;
log.info("testTestDataComplexRequest expected={}", expectedJson);
TestDataRequest testRequest = new TestDataRequest();
testRequest.setSessionSessionId("SessionId.ceaf16e6-3566-4a1a-b2d4-620422f3fda5");
testRequest.setSessionUserId("TEST-USER-ID");
testRequest.setRequestIntentName("AddScheduleIntent");
testRequest.setRequestRequestId("EdwRequestId.60c03ee3-82b9-404e-afed-7887bb1f7ff2");
testRequest.setRequestTimestamp("2016-11-29T01:46:34Z");
testRequest.addRequestIntentSlot("DayOfWeek","Monday");
testRequest.addRequestIntentSlot("TimeOfDay","16:00");
testRequest.addRequestIntentSlot("PickupName","mail");
String testDataRequestFormatted = testRequest.toString();
log.debug("testTestDataComplexRequest testDataRequest={}", testDataRequestFormatted);
String actualJson = testRequest.toString();
log.info("testTestDataComplexRequest actual={}", actualJson);
assertEquals(expectedJson, actualJson);
}
}
| mit |
caiocomandulli/lib-download-manager | src/com/comandulli/lib/download/DownloadManager.java | 3459 | package com.comandulli.lib.download;
import java.util.List;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.comandulli.lib.download.DownloadService.DownloadBinder;
/**
* The type Download manager.
*/
public class DownloadManager {
/**
* The enum Download type.
*/
public enum DownloadType {
/**
* Not set download type.
*/
NotSet, /**
* Mobile download type.
*/
Mobile, /**
* Wi fi only download type.
*/
WiFiOnly
}
private static DownloadType currentType = DownloadType.NotSet;
private static DownloadService service;
private static final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
DownloadBinder b = (DownloadBinder) service;
DownloadManager.service = b.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
};
/**
* Bind service.
*
* @param context the context
*/
public static void bindService(Context context) {
Intent intent = new Intent(context, DownloadService.class);
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
/**
* Unbind service.
*
* @param context the context
*/
public static void unbindService(Context context) {
context.unbindService(serviceConnection);
}
/**
* Add job.
*
* @param job the job
*/
public static void addJob(DownloadJob job) {
if (service != null) {
service.addJob(job);
}
}
/**
* Remove job.
*
* @param job the job
*/
public static void removeJob(DownloadJob job) {
if (service != null) {
service.removeJob(job.getName());
}
}
/**
* Remove job.
*
* @param name the name
*/
public static void removeJob(String name) {
if (service != null) {
service.removeJob(name);
}
}
/**
* Gets job.
*
* @param name the name
* @return the job
*/
public static DownloadJob getJob(String name) {
if (service != null) {
return service.getJob(name);
} else {
return null;
}
}
/**
* Add queue listener.
*
* @param downloadQueueListener the download queue listener
*/
public static void addQueueListener(DownloadQueueListener downloadQueueListener) {
if (service != null) {
service.addQueueListener(downloadQueueListener);
}
}
/**
* Remove queue listener.
*
* @param downloadQueueListener the download queue listener
*/
public static void removeQueueListener(DownloadQueueListener downloadQueueListener) {
if (service != null) {
service.removeQueueListener(downloadQueueListener);
}
}
/**
* Gets job list.
*
* @return the job list
*/
public static List<DownloadJob> getJobList() {
if (service != null) {
return service.getJobList();
} else {
return null;
}
}
/**
* Gets type.
*
* @return the type
*/
public static DownloadType getType() {
return currentType;
}
/**
* Sets type.
*
* @param type the type
*/
public static void setType(DownloadType type) {
currentType = type;
}
}
| mit |
vertiman/node-db-migrate | lib/driver/index.js | 3474 | var internals = {};
internals.mod = internals.mod || {};
internals.mod.log = require('../log');
internals.mod.type = require('../data_type');
var Shadow = require('./shadow');
var log = internals.mod.log;
var tunnel = require('tunnel-ssh'),
Promise = require('bluebird'),
SeederInterface = require('../interface/seederInterface.js'),
MigratorInterface = require('../interface/migratorInterface.js'),
resolve = require( 'resolve' );
var ShadowProto = {
createTable: function() { return Promise.resolve(); },
addForeignKey: function() { return Promise.resolve(); },
createCollection: function() { return Promise.resolve(); }
};
exports.connect = function (config, intern, callback) {
var driver, req;
var mod = internals.mod;
internals = intern;
internals.mod = mod;
//add interface extensions to allow drivers to add new methods
internals.interfaces = {
SeederInterface: SeederInterface.extending,
MigratorInterface: MigratorInterface.extending
};
if ( !config.user && config.username )
config.user = config.username;
if (config.driver === undefined) {
throw new Error(
'config must include a driver key specifing which driver to use');
}
if (config.driver && typeof (config.driver) === 'object') {
log.verbose('require:', config.driver.require);
driver = require(config.driver.require);
}
else {
switch(config.driver) {
case 'sqlite':
config.driver = 'sqlite3';
break;
case 'postgres':
case 'postgresql':
config.driver = 'pg';
break;
}
try {
req = 'db-migrate-' + config.driver;
log.verbose('require:', req);
try {
driver = require(
resolve.sync(req, { basedir: process.cwd() })
);
}
catch(e1) {
try {
driver = require(req);
}
catch (e2) {
driver = require('../../../' + req);
}
}
}
catch (e3) {
try {
//Fallback to internal drivers, while moving drivers to new repos
req = './' + config.driver;
log.verbose('require:', req);
driver = require(req);
}
catch (e4) {
return callback( { stack: 'No such driver found, please try to install it via ' +
'npm install db-migrate-' + config.driver + ' or ' +
'npm install -g db-migrate-' + config.driver } );
}
}
}
log.verbose('connecting');
var connect = function(config) {
driver.connect(config, intern, function (err, db) {
if (err) {
callback(err);
return;
}
log.verbose('connected');
if (!global.immunity)
db = Shadow.infect(db, internals, ShadowProto);
callback(null, db);
});
};
if (config.tunnel) {
var tunnelConfig = JSON.parse(JSON.stringify(config.tunnel));
tunnelConfig.dstHost = config.host;
tunnelConfig.dstPort = config.port;
if (tunnelConfig.privateKeyPath) {
tunnelConfig.privateKey = require('fs').readFileSync(tunnelConfig.privateKeyPath);
}
// Reassign the db host/port to point to our local ssh tunnel
config.host = '127.0.0.1';
config.port = tunnelConfig.localPort;
tunnel(tunnelConfig, function (err) {
if (err) {
callback(err);
return;
}
log.verbose('SSH tunnel connected on port ', tunnelConfig.localPort);
connect(config);
});
}
else {
connect(config);
}
};
| mit |
edosgn/colossus-sit | src/AppBundle/Form/CfgClaseAccidenteType.php | 765 | <?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CfgClaseAccidenteType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nombre')->add('estado');
}/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\CfgClaseAccidente'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_cfgclaseaccidente';
}
}
| mit |
doctorjbeam/railpagecore | lib/News/Index.php | 562 | <?php
/**
* News classes
* @since Version 3.0.1
* @version 3.0.1
* @author Michael Greenhill
* @package Railpage
* @copyright Copyright (c) 2012 Michael Greenhill
*/
namespace Railpage\News;
// Make sure the parent class is loaded
#require_once(__DIR__ . DS . "class.news.base.php");
/**
* News index
* @author Michael Greenhill
* @version 3.0.1
* @since Version 3.0.1
* @package Railpage
* @copyright Copyright (c) 2012 Michael Greenhill
*/
class Index extends Base {
// Do nothing
}
?> | mit |
QuincyWork/AllCodes | Cpp/Codes/Algorithm/Tree/TrieTree.cpp | 4904 | #include <gtest/gtest.h>
#include <list>
using namespace std;
class TrieTree
{
public:
const static int MAX_CHILD_KEY_COUNT = 30;
const static char STRING_END_TAG = '\xFF';
struct TrieNode
{
char nodeValue;
int nodeFreq;
list<TrieNode*> childNodes[MAX_CHILD_KEY_COUNT]; //ΪÁ˱ÜÃâÕâÀïÊý×éÌ«´ó£¬²ÉÓÃÊý×é+Á´±í·½Ê½
TrieNode()
{
nodeValue = 0;
nodeFreq = 0;
}
};
TrieTree();
~TrieTree();
public:
void Insert(const string& strVal);
void Delete(const string& strVal);
int Search(const string& strVal);
int CommonPrefix(const string& strVal);
private:
void Clean(TrieNode* rootNode);
bool DeleteNode(TrieNode* rootNode, const string& strVal, int nOffset);
TrieNode m_RootNode;
};
TrieTree::TrieTree()
{
};
TrieTree::~TrieTree()
{
Clean(&m_RootNode);
};
void TrieTree::Insert(const string& strVal)
{
if (strVal.empty())
{
return;
}
// ÔÚ×Ö·û´®Ä©Î²Ìí¼ÓÒ»¸öÌØÊâ×Ö·û£¬ÒÔÇø·ÖÊÇǰ׺»¹ÊÇÍêÕû×Ö·û´®
string strValue(strVal);
strValue += STRING_END_TAG;
TrieNode* pCurrentNode = &m_RootNode;
unsigned int nIndex = 0;
unsigned int nLength = strValue.length();
do
{
bool bExistVal = false;
char cValue = strValue[nIndex];
list<TrieNode*>& refListNode = pCurrentNode->childNodes[(unsigned char)cValue % MAX_CHILD_KEY_COUNT];
if (refListNode.size())
{
list<TrieNode*>::iterator it = refListNode.begin();
list<TrieNode*>::iterator itEnd = refListNode.end();
for (; it != itEnd; ++it)
{
if (cValue == (*it)->nodeValue)
{
(*it)->nodeFreq++;
bExistVal = true;
pCurrentNode = *it;
break;
}
}
}
// µ±Ç°²»´æÔÚ¶ÔÓ¦µÄ×Ö·û£¬Ôòн¨Ò»¸ö
if (!bExistVal)
{
TrieNode* pNewNode = new TrieNode();
pNewNode->nodeFreq = 1;
pNewNode->nodeValue = cValue;
refListNode.push_back(pNewNode);
pCurrentNode = pNewNode;
}
++nIndex;
}
while(nIndex < nLength);
}
void TrieTree::Delete(const string& strVal)
{
if (strVal.empty())
{
return;
}
string strValue(strVal);
strValue += STRING_END_TAG;
DeleteNode(&m_RootNode, strValue, 0);
}
int TrieTree::Search(const string& strVal)
{
if (strVal.empty())
{
return 0;
}
string strValue(strVal);
strValue += STRING_END_TAG;
return CommonPrefix(strValue);
}
int TrieTree::CommonPrefix(const string& strVal)
{
if (strVal.empty())
{
return 0;
}
TrieNode* pCurrentNode = &m_RootNode;
unsigned int nIndex = 0;
unsigned int nLength = strVal.length();
int nFreq = 0;
do
{
bool bExistVal = false;
char cValue = strVal[nIndex];
list<TrieNode*>& refListNode = pCurrentNode->childNodes[(unsigned char)cValue % MAX_CHILD_KEY_COUNT];
if (refListNode.size())
{
list<TrieNode*>::iterator it = refListNode.begin();
list<TrieNode*>::iterator itEnd = refListNode.end();
for (; it != itEnd; ++it)
{
if (cValue == (*it)->nodeValue)
{
nFreq = (*it)->nodeFreq;
bExistVal = true;
pCurrentNode = *it;
break;
}
}
}
// µ±Ç°²»´æÔÚ¶ÔÓ¦µÄ×Ö·û£¬ÔòûÓÐÕÒµ½
if (!bExistVal)
{
nFreq = 0;
break;
}
++nIndex;
}
while(nIndex < nLength);
return nFreq;
}
void TrieTree::Clean(TrieNode* rootNode)
{
if (!rootNode)
{
return;
}
for (int i=0; i<MAX_CHILD_KEY_COUNT; ++i)
{
list<TrieNode*>& refListNode = rootNode->childNodes[i];
if (refListNode.size())
{
list<TrieNode*>::iterator it = refListNode.begin();
list<TrieNode*>::iterator itEnd = refListNode.end();
for (; it != itEnd; ++it)
{
Clean(*it);
delete *it;
}
refListNode.clear();
}
}
}
bool TrieTree::DeleteNode(TrieNode* rootNode, const string& strVal, int nOffset)
{
if (!rootNode)
{
return false;
}
bool bDelChild = false;
char cValue = strVal[nOffset];
list<TrieNode*>& refListNode = rootNode->childNodes[(unsigned char)cValue % MAX_CHILD_KEY_COUNT];
if (refListNode.size())
{
list<TrieNode*>::iterator it = refListNode.begin();
list<TrieNode*>::iterator itEnd = refListNode.end();
for (; it != itEnd; ++it)
{
if ((*it)->nodeValue == cValue)
{
bDelChild = true;
// ×Ö·û´®Ã»ÓнáÊø£¬É¾³ýÏÂÒ»¸ö½Úµã
if (++nOffset < (int)strVal.length())
{
bDelChild = DeleteNode(*it, strVal, nOffset);
}
// ¸Ã½Úµã´ÎÊýΪ0£¬ËµÃ÷ÒѾûÓÐ×Ó½ÚµãÁË£¬ÒƳý¸Ã½Úµã
if (bDelChild &&
(0 == (--(*it)->nodeFreq)))
{
delete *it;
refListNode.erase(it);
}
break;
}
}
}
return bDelChild;
}
TEST(Structure, tTireTree)
{
// "abc","ab","bd","dda"
TrieTree tree;
tree.Insert("abc");
tree.Insert("ab");
tree.Insert("bd");
tree.Insert("dda");
ASSERT_EQ(tree.Search("ab"), 1);
ASSERT_EQ(tree.CommonPrefix("ab"), 2);
tree.Delete("ab");
ASSERT_EQ(tree.Search("ab"), 0);
ASSERT_EQ(tree.CommonPrefix("ab"), 1);
tree.Delete("abcd");
ASSERT_EQ(tree.Search("ab"), 0);
ASSERT_EQ(tree.Search("d"), 0);
ASSERT_EQ(tree.CommonPrefix("d"), 1);
ASSERT_EQ(tree.Search("fg"), 0);
tree.Delete("fg");
} | mit |
alpayOnal/flj | flj_android/app/src/main/java/com/muatik/flj/flj/UI/views/JobViewHolder.java | 2819 | package com.muatik.flj.flj.UI.views;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.TextView;
import com.muatik.flj.flj.R;
import com.muatik.flj.flj.UI.activities.JobDetail;
import com.muatik.flj.flj.UI.utilities.BusManager;
import com.muatik.flj.flj.UI.entities.Job;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by muatik on 24.07.2016.
*/
public class JobViewHolder extends RecyclerView.ViewHolder{
private Job job;
public class EventOnJobClicked {
public Job job;
public EventOnJobClicked(Job job) {
this.job = job;
}
}
private TextView title;
private TextView employer;
private TextView country;
private TextView city;
private TextView created_at;
public JobViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.job_title);
this.employer = (TextView) view.findViewById(R.id.job_employer);
this.country= (TextView) view.findViewById(R.id.job_country);
this.city= (TextView) view.findViewById(R.id.job_city);
this.created_at= (TextView) view.findViewById(R.id.job_created_at);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BusManager.get().post(new EventOnJobClicked(job));
}
});
}
public static String capitalize(String t) {
if (t != null)
return t.substring(0,1).toUpperCase() + t.substring(1).toLowerCase();
return t;
}
public void setJob(Job job) {
this.job = job;
title.setText(job.getTitle() + " " + job.getId());
setCity(job.getCity());
setCountry(job.getCountry());
setCreatedAt(job.getCreated_at());
setEmployer(job.getEmployer());
}
public void setCreatedAt(String created_at) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date d = format.parse(created_at);
this.created_at.setText(
DateUtils.getRelativeTimeSpanString(
d.getTime(),
new Date().getTime(),
DateUtils.MINUTE_IN_MILLIS));
} catch (ParseException e) {
e.printStackTrace();
}
}
public void setCity(String city) {
this.city.setText(capitalize(city) + ", ");
}
public void setCountry(String country) {
this.country.setText(capitalize(country));
}
public void setEmployer(String employer) {
this.employer.setText("Google Microsoft LTD. STI");
}
}
| mit |
molstar/molstar | src/mol-util/color/spaces/lab.ts | 4796 | /**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*
* Color conversion code adapted from chroma.js (https://github.com/gka/chroma.js)
* Copyright (c) 2011-2018, Gregor Aisch, BSD license
*/
import { Color } from '../color';
import { Hcl } from './hcl';
import { radToDeg } from '../../../mol-math/misc';
import { clamp } from '../../../mol-math/interpolate';
export { Lab };
interface Lab extends Array<number> { [d: number]: number, '@type': 'lab', length: 3 }
/**
* CIE LAB color
*
* - L* [0..100] - lightness from black to white
* - a [-100..100] - green (-) to red (+)
* - b [-100..100] - blue (-) to yellow (+)
*
* see https://en.wikipedia.org/wiki/CIELAB_color_space
*/
function Lab() {
return Lab.zero();
}
namespace Lab {
export function zero(): Lab {
const out = [0.1, 0.0, 0.0];
out[0] = 0;
return out as Lab;
}
export function create(l: number, a: number, b: number): Lab {
const out = zero();
out[0] = l;
out[1] = a;
out[2] = b;
return out;
}
export function fromColor(out: Lab, color: Color): Lab {
const [r, g, b] = Color.toRgb(color);
const [x, y, z] = rgbToXyz(r, g, b);
const l = 116 * y - 16;
out[0] = l < 0 ? 0 : l;
out[1] = 500 * (x - y);
out[2] = 200 * (y - z);
return out;
}
export function fromHcl(out: Lab, hcl: Hcl): Lab {
return Hcl.toLab(out, hcl);
}
export function toColor(lab: Lab): Color {
let y = (lab[0] + 16) / 116;
let x = isNaN(lab[1]) ? y : y + lab[1] / 500;
let z = isNaN(lab[2]) ? y : y - lab[2] / 200;
y = Yn * lab_xyz(y);
x = Xn * lab_xyz(x);
z = Zn * lab_xyz(z);
const r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z); // D65 -> sRGB
const g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
const b = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
return Color.fromRgb(
Math.round(clamp(r, 0, 255)),
Math.round(clamp(g, 0, 255)),
Math.round(clamp(b, 0, 255))
);
}
export function toHcl(out: Hcl, lab: Lab): Hcl {
const [l, a, b] = lab;
const c = Math.sqrt(a * a + b * b);
let h = (radToDeg(Math.atan2(b, a)) + 360) % 360;
if (Math.round(c * 10000) === 0) h = Number.NaN;
out[0] = h;
out[1] = c;
out[2] = l;
return out;
}
export function copy(out: Lab, c: Lab): Lab {
out[0] = c[0];
out[1] = c[1];
out[2] = c[2];
return out;
}
export function darken(out: Lab, c: Lab, amount: number): Lab {
out[0] = c[0] - Kn * amount;
out[1] = c[1];
out[2] = c[2];
return out;
}
export function lighten(out: Lab, c: Lab, amount: number): Lab {
return darken(out, c, -amount);
}
const tmpSaturateHcl = [0, 0, 0] as Hcl;
export function saturate(out: Lab, c: Lab, amount: number): Lab {
toHcl(tmpSaturateHcl, c);
return Hcl.toLab(out, Hcl.saturate(tmpSaturateHcl, tmpSaturateHcl, amount));
}
export function desaturate(out: Lab, c: Lab, amount: number): Lab {
return saturate(out, c, -amount);
}
// Corresponds roughly to RGB brighter/darker
const Kn = 18;
/** D65 standard referent */
const Xn = 0.950470;
const Yn = 1;
const Zn = 1.088830;
const T0 = 0.137931034; // 4 / 29
const T1 = 0.206896552; // 6 / 29
const T2 = 0.12841855; // 3 * t1 * t1
const T3 = 0.008856452; // t1 * t1 * t1
/** convert component from xyz to rgb */
function xyz_rgb(c: number) {
return 255 * (c <= 0.00304 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
}
/** convert component from lab to xyz */
function lab_xyz(t: number) {
return t > T1 ? t * t * t : T2 * (t - T0);
}
/** convert component from rgb to xyz */
function rgb_xyz(c: number) {
if ((c /= 255) <= 0.04045) return c / 12.92;
return Math.pow((c + 0.055) / 1.055, 2.4);
}
/** convert component from xyz to lab */
function xyz_lab(t: number) {
if (t > T3) return Math.pow(t, 1 / 3);
return t / T2 + T0;
}
function rgbToXyz(r: number, g: number, b: number) {
r = rgb_xyz(r);
g = rgb_xyz(g);
b = rgb_xyz(b);
const x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / Xn);
const y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / Yn);
const z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / Zn);
return [x, y, z];
}
} | mit |
factcenter/inchworm | src/test/java/org/factcenter/inchworm/ops/concrete/CircuitMuxRamTest.java | 1306 | package org.factcenter.inchworm.ops.concrete;
import org.factcenter.inchworm.*;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
public class CircuitMuxRamTest extends MemoryAreaTest {
// {blockSize,blockCount} parameters for testing.
@Parameterized.Parameters
public static Collection<Integer[]> memSizes() {
return Arrays.asList(new Integer[][]{
{8, 16},
});
}
@Override
protected MemoryFactory createAndSetupMemoryFactory(int playerId) throws Exception {
CircuitMuxMemoryFactory circuitMuxMemoryFactory = new CircuitMuxMemoryFactory();
circuitMuxMemoryFactory.setMoreParameters(otExtenders[playerId]);
return circuitMuxMemoryFactory;
}
public CircuitMuxRamTest(int blockSize, int blockCount) throws Exception {
super(blockSize, blockCount);
}
@Override
protected int[] getRandomIndexAndNum() {
// We only test powers of 2
int log2count = 32 - Integer.numberOfLeadingZeros(blockCount) - 1;
int num = log2count > 1 ? testRand.nextInt(log2count - 1) : 0;
num = 1 << num;
int idx = testRand.nextInt(blockCount);
idx &= ~(num - 1);
int[] pair = {idx, num};
return pair;
}
} | mit |
CorbinDallas/Rendition | Rendition.Core/cs/Utilities/Utilities.cs | 36017 | /*
Copyright (c) 2012 Tony Germaneri
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, AR
SING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* -------------------------------------------------------------------------
* utilities.cs
*
* Extentions for many types. Keeps me from typing so much.
* HTTP utilites for rewriting URLs and URIs and URLamas, and respons.blah shortcuts.
* Utitlies for dealing with binary streams. Paddles and whatnot.
* JSON serialzing and deserializng devices.
* JSON 'responder'. Converts a JSON string into a method and executes it.
* and obviously a bunch of string stuff.
* ------------------------------------------------------------------------- */
using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
using System.Xml;
using System.Timers;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using ZedGraph;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Drawing.Drawing2D;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;
using BarcodeLib;
namespace Rendition {
/// <summary>
/// Utitlites and extentions for standard objects.
/// </summary>
public static class Utilities {
/// <summary>
/// GUID Pattern
/// </summary>
public static Regex GuidPattern=new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$",RegexOptions.Compiled);
/// <summary>
/// Determines whether the specified string is a GUID.
/// </summary>
/// <returns>
/// <c>true</c> if the specified string is a GUID; otherwise, <c>false</c>.
/// </returns>
public static bool IsGuid(this string e) {
Regex guidPattern=new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$",RegexOptions.Compiled);
if(guidPattern.IsMatch(e)) {
return true;
}
return false;
}
/// <summary>
/// IIF
/// </summary>
/// <param name="condition">if set to <c>true</c> it will return the true result, otherwise the false.</param>
/// <param name="trueResult">The true result.</param>
/// <param name="falseResult">The false result.</param>
/// <returns></returns>
public static object Iif(bool condition,object trueResult,object falseResult) {
if(condition==true) { return trueResult; } else { return falseResult; }
}
/// <summary>
/// Encodes a string representation of the Guid prefixed with the letter "d".
/// For use in xHTML id fields where {,} and beginging id's with digits are illegal.
/// </summary>
/// <returns>An xHTML Id safe string.</returns>
public static String EncodeXMLId(this Guid g) {
return 'd'+g.ToString().Replace("}","").Replace("{","").Replace("-","_");
}
/// <summary>
/// Decodes a Guid that has been encoded with the encodeXMLId method.
/// </summary>
/// <returns>Guid from the encoded string.</returns>
public static Guid DecodeXMLId(this string e) {
if(e==null) { return Guid.Empty; };
if(e.Length<30) { return Guid.Empty; };
e=e.Substring(1,e.Length-1);
e=e.Replace("_","-");
Regex guidPattern=new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$",RegexOptions.Compiled);
if(guidPattern.IsMatch(e)) {
return new Guid(e);
}
return Guid.Empty;
}
/// <summary>
/// Encodes a string for safe output into JSON
/// </summary>
/// <returns>JSON Encoded string.</returns>
public static String ToJson(this string e) {
if(e==null) { return null; };
return e.Replace("\"","\\\"").Replace("\n","\\n").Replace("\r","\\r");
}
/// <summary>
/// Escapes string for safe usage in HTML using Server.HtmlEncode
/// </summary>
/// <param name="e">Input string</param>
/// <param name="max">Max length string is allowed to be</param>
/// <returns>Returns the escaped string.</returns>
public static string MaxLength(this string e,int max) {
if(e==null) { return null; };
if(e.Length>max) {
return e.Substring(0,max);
} else {
return e;
}
}
/// <summary>
/// Escapes string for safe usage in HTML using Server.HtmlEncode
/// </summary>
/// <param name="e">Input string</param>
/// <param name="max">Max length string is allowed to be</param>
/// <param name="trim">Trim the string too</param>
/// <returns>Returns the escaped string.</returns>
public static string MaxLength(this string e,int max,bool trim) {
if(e==null){return null;};
return e.Trim().MaxLength(max);
}
/// <summary>
/// Escapes string for safe usage in HTML using Server.HtmlEncode
/// </summary>
/// <param name="e">Input string</param>
/// <param name="max">Max length string is allowed to be</param>
/// <param name="trim">if set to <c>true</c> [trim].</param>
/// <param name="toLower">if set to <c>true</c> [to lower].</param>
/// <returns>Returns the escaped string.</returns>
public static string MaxLength(this string e,int max,bool trim,bool toLower) {
if(toLower) {
return e.Trim().MaxLength(max, trim).ToLower();
} else {
return e.Trim().MaxLength(max, trim);
}
}
/// <summary>
/// Escapes string for safe usage in HTML using Server.HtmlEncode
/// </summary>
/// <returns>Returns the escaped string.</returns>
public static string h(this string e) {
if(e==null) { return null; };
return HttpUtility.HtmlEncode(e);
}
/// <summary>
/// Escapes string for safe usage in a SQL query by replacing ' with ''
/// </summary>
/// <returns>Returns the escaped string.</returns>
public static string s(this string sql_to_inject) {
if(sql_to_inject==null) {
return null;
};
return sql_to_inject.Replace("'","''");
}
/// <summary>
/// Trims and lowers the case of a string.
/// Good for comparing strings that may have extra spaces or disimilar cases.
/// </summary>
/// <returns>The trimmed lower case version of the string.</returns>
public static string l(this string e) {
if(e==null) { return null; };
return e.Trim();
}
/// <summary>
/// HttpUtility.UrlEncode
/// </summary>
/// <returns>URL encoded string.</returns>
public static string UrlEncode(this string e) {
if(e==null) { return null; };
StringBuilder output = new StringBuilder("");
int x = 0;
Regex regex = new Regex("(^[a-zA-Z0-9_.]*)");
while (x < e.Length) {
MatchCollection matches = regex.Matches(e);
if (matches != null && matches.Count > 1 && matches[1].Value != "") {
output.Append(matches[1].Value);
x += matches[1].Value.Length;
} else {
if (e[x] == ' ')
output.Append("+");
else {
var hexVal = ((int)e[x]).ToString("X");
output.Append('%' + ( hexVal.Length < 2 ? "0" : "" ) + hexVal.ToUpper());
}
x++;
}
}
return output.ToString();
}
/// <summary>
/// HttpUtility.HtmlEncode
/// </summary>
/// <returns>HTML encoded string.</returns>
public static string HtmlEncode(this string e) {
if(e==null) { return null; };
return HttpUtility.HtmlEncode(e);
}
/// <summary>
/// returns the string +? if the string does contain a ? or string+& if the string does contain a ?.
/// </summary>
/// <returns>string with URI pad added</returns>
public static string UriPad(this string e) {
if(e==null) { return null; };
if(e.Contains("?")) {
return e+"&";
} else {
return e+"?";
}
}
/// <summary>
/// Removes the last X number of characters from the end of a StringBuilder string
/// </summary>
/// <param name="s">Input StringBuilder</param>
/// <param name="characters">Number of characters to remove from the end</param>
/// <returns>void</returns>
public static StringBuilder RemoveLast(this StringBuilder s,int characters) {
if(s.Length==0){
return s;
}
s.Remove(s.Length-characters,characters);
return s;
}
/// <summary>
/// Removes the last X number of characters from the end of a string
/// </summary>
/// <param name="s">Input string</param>
/// <param name="characters">Number of characters to remove from the end</param>
/// <returns>void</returns>
public static string RemoveLast(this string s,int characters) {
s.Remove(s.Length-characters,characters);
return s;
}
/// <summary>
/// Makes the string CSV file safe by adding double qutoes around strings with spaces,cr or lf.
/// </summary>
/// <param name="v">Input string</param>
/// <returns></returns>
public static string ToCsv(this string v) {
/* if there are quotes replace them with double quotes */
if(v.Contains("\"")) {
v.Replace("\"","\"\"");
}
/* if there are quotes,commas,cr or lf's put quotes around the string */
if(v.Contains(",")||v.Contains("\"")||v.Contains("\r")||v.Contains("\n")) {
v="\""+v+"\"";
}
return v;
}
/// <summary>
/// Gets the JSON array.
/// </summary>
/// <param name="d">The d.</param>
/// <returns></returns>
public static List<object> GetJsonArray(this SqlDataReader d) {
return GetJsonArray(d,true);
}
/// <summary>
/// returns a JSON array string from the SqlDataReader containing ONLY the raw record set.
/// </summary>
/// <param name="d">The SQL data reader</param>
/// <param name="closeConnection">Once the readers is complete, the reader is closed.</param>
/// <returns></returns>
public static List<object> GetJsonArray(this SqlDataReader d,bool closeConnection) {
List<object> j=new List<object>();
if(d.HasRows) {
int fCount=d.FieldCount;
while(d.Read()) {
List<object> r=new List<object>();
for(var x=0;fCount>x;x++) {
Type t=d.GetFieldType(x);
if(d.GetValue(x).GetType()==typeof(System.DBNull)) {
r.Add(null);
} else {
if(t==typeof(int)) {
r.Add(Convert.ToInt32(d.GetValue(x)));
} else if(t==typeof(double)||t==typeof(float)||t==typeof(decimal)) {
r.Add(Convert.ToDecimal(d.GetValue(x)));
} else if(t==typeof(bool)) {
r.Add(Convert.ToBoolean(d.GetValue(x)));
} else {
r.Add(Convert.ToString(d.GetValue(x)));
}
}
}
j.Add(r);
}
if(!closeConnection) {
d.Close();
}
}
return j;
}
/// <summary>
/// Returns the SqlDataReader as a JSON object with extened information about each row and column.
/// </summary>
/// <returns></returns>
public static Dictionary<string,object> GetJsonCollection(this SqlDataReader d) {
Dictionary<string,object> j=new Dictionary<string,object>();
if(d.HasRows) {
int counter=0;
int fCount=d.FieldCount;
while(d.Read()) {
List<object> r=new List<object>();
for(var x=0;fCount>x;x++) {
Type t=d.GetFieldType(x);
if(t==typeof(int)||t==typeof(double)||t==typeof(float)||t==typeof(decimal)) {
r.Add(Convert.ToInt32(d.GetValue(x)));
} else if(t==typeof(bool)) {
r.Add(Convert.ToBoolean(d.GetValue(x)));
} else {
r.Add(Convert.ToString(d.GetValue(x)));
}
}
j.Add("record"+counter++,r);
}
j.Add("length",counter);
}
return j;
}
/// <summary>
/// Converts a generic system type to a SqlDbType.
/// </summary>
/// <param name="t">The t.</param>
/// <returns></returns>
public static SqlDbType ToSqlDbType(this System.Type t) {
SqlParameter param;
System.ComponentModel.TypeConverter tc;
param=new SqlParameter();
tc=System.ComponentModel.TypeDescriptor.GetConverter(param.DbType);
if(tc.CanConvertFrom(t)) {
param.DbType=(DbType)tc.ConvertFrom(t.Name);
} else {
try {
param.DbType=(DbType)tc.ConvertFrom(t.Name);
} catch(Exception e) {
Main.debug.WriteLine(DateTime.Now.ToString()+':'+e.Message);
}
}
return param.SqlDbType;
}
/// <summary>
/// Finds the first occurance of the byte array [binarySearchArray] in the MemoryStream starting from [startSearchFrom].
/// </summary>
/// <param name="ms">Input memory stream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <param name="startSearchFrom">Start search from.</param>
/// <returns></returns>
public static long FindFirst(this MemoryStream ms,byte[] binarySearchArray,long startSearchFrom) {
List<long> outputList=ms.Find(binarySearchArray,startSearchFrom);
if(outputList.Count>0) {
return outputList[0];
} else {
return -1;
}
}
/// <summary>
/// Moves the MemoryStream backwards until the byte array [binarySearchArray] is found, then returns the location of the byte array.
/// </summary>
/// <param name="ms">Input memory stream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <returns></returns>
public static long MoveBackwardsUntil(this MemoryStream ms,byte[] binarySearchArray) {
return ms.MoveUntil(binarySearchArray,true);
}
/// <summary>
/// Moves the MemoryStream forward until the byte array [binarySearchArray] is found, then returns the location of the byte array.
/// </summary>
/// <param name="ms">Input memory stream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <returns></returns>
public static long MoveForwardUntil(this MemoryStream ms,byte[] binarySearchArray) {
return ms.MoveUntil(binarySearchArray,false);
}
/// <summary>
/// Moves the MemoryStream position forwards until it encouters [binarySearchArray], then it returns the position of that byte array.
/// [direction] sets forwards or backwards.
/// </summary>
/// <param name="ms">Input memory stream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <param name="direction">if set to <c>true</c> [direction].</param>
/// <returns></returns>
public static long MoveUntil(this MemoryStream ms,byte[] binarySearchArray,bool direction) {
const int BUFFER_LENGTH=10240;
byte[] buffer=new byte[BUFFER_LENGTH];
long bytes=BUFFER_LENGTH;
long searchOffset=0;
int searchLength=binarySearchArray.Length;
while(bytes>0) {
bytes=ms.Read(buffer,0,BUFFER_LENGTH);
for(var x=0;bytes>x;x++) {
for(var y=0;searchLength>y;y++) {
if(x+y>bytes-1) {
break;
}
if(binarySearchArray[y]!=buffer[x+y]) {
break;
}
if(searchLength-1==y) {
return x+y+searchOffset-searchLength-1;
}
}
}
if(!direction) {
searchOffset+=BUFFER_LENGTH-searchLength;
} else {
searchOffset-=BUFFER_LENGTH-searchLength;
}
}
return -1;
}
/// <summary>
/// Finds every instance of the byte array [binarySearchArray] in the MemoryStream, then returns a List of longs of their locations.
/// </summary>
/// <param name="ms">Input memory stream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <param name="startSearchFrom">The start search from.</param>
/// <returns></returns>
public static List<long> Find(this MemoryStream ms,byte[] binarySearchArray,long startSearchFrom) {
List<long> outputList=new List<long>();
long startingPosition=ms.Position;
ms.Position=startSearchFrom;
const int BUFFER_LENGTH=10240;
byte[] buffer=new byte[BUFFER_LENGTH];
long bytes=BUFFER_LENGTH;
long searchOffset=0;
int searchLength=binarySearchArray.Length;
while(bytes>0) {
bytes=ms.Read(buffer,0,BUFFER_LENGTH);
for(var x=0;bytes>x;x++) {
for(var y=0;searchLength>y;y++) {
if(x+y>bytes-1) {
break;
}
if(binarySearchArray[y]!=buffer[x+y]) {
break;
}
if(searchLength-1==y) {
outputList.Add(x+y+searchOffset-searchLength-1+startSearchFrom);
break;
}
}
}
searchOffset+=BUFFER_LENGTH;
}
ms.Position=startingPosition;
return outputList;
}
/// <summary>
/// Finds the first occurance of the byte array [binarySearchArray] in the FileStream starting from [startSearchFrom].
/// </summary>
/// <param name="fs">Input FileStream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <param name="startSearchFrom">Start search from.</param>
/// <returns></returns>
public static long FindFirst(this FileStream fs,byte[] binarySearchArray,long startSearchFrom) {
List<long> outputList=fs.Find(binarySearchArray,startSearchFrom);
if(outputList.Count>0) {
return outputList[0];
} else {
return -1;
}
}
/// <summary>
/// Moves the FileStream backwards until the byte array [binarySearchArray] is found, then returns the location of the byte array.
/// </summary>
/// <param name="fs">Input FileStream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <returns></returns>
public static long MoveBackwardsUntil(this FileStream fs,byte[] binarySearchArray) {
return fs.MoveUntil(binarySearchArray,true);
}
/// <summary>
/// Moves the FileStream forward until the byte array [binarySearchArray] is found, then returns the location of the byte array.
/// </summary>
/// <param name="fs">Input FileStream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <returns></returns>
public static long MoveForwardUntil(this FileStream fs,byte[] binarySearchArray) {
return fs.MoveUntil(binarySearchArray,false);
}
/// <summary>
/// Moves the FileStream position forwards until it encouters [binarySearchArray], then it returns the position of that byte array.
/// [direction] sets forwards or backwards.
/// </summary>
/// <param name="fs">The FileStream</param>
/// <param name="binarySearchArray">The binary search array.</param>
/// <param name="direction">if set to <c>true</c> the stream searches forwards.</param>
/// <returns></returns>
public static long MoveUntil(this FileStream fs,byte[] binarySearchArray,bool direction) {
const int BUFFER_LENGTH=10240;
byte[] buffer=new byte[BUFFER_LENGTH];
long bytes=BUFFER_LENGTH;
long searchOffset=0;
int searchLength=binarySearchArray.Length;
while(bytes>0) {
bytes=fs.Read(buffer,0,BUFFER_LENGTH);
for(var x=0;bytes>x;x++) {
for(var y=0;searchLength>y;y++) {
if(x+y>bytes-1) {
break;
}
if(binarySearchArray[y]!=buffer[x+y]) {
break;
}
if(searchLength-1==y) {
return x+y+searchOffset-searchLength-1;
}
}
}
if(!direction) {
searchOffset+=BUFFER_LENGTH;
} else {
searchOffset-=BUFFER_LENGTH;
}
}
return -1;
}
/// <summary>
/// Finds every occurace of [binarySearchArray] in the FileStream and returns the locations as a List of longs.
/// This function only searches forwards from the starting position.
/// </summary>
/// <param name="fs">The FileStream</param>
/// <param name="binarySearchArray">The byte array to search for.</param>
/// <param name="startSearchFrom">What position to start searching from.</param>
/// <returns></returns>
public static List<long> Find(this FileStream fs,byte[] binarySearchArray,long startSearchFrom) {
List<long> outputList=new List<long>();
long startingPosition=fs.Position;
fs.Position=startSearchFrom;
const int BUFFER_LENGTH=10240;
byte[] buffer=new byte[BUFFER_LENGTH];
long bytes=BUFFER_LENGTH;
long searchOffset=0;
int searchLength=binarySearchArray.Length;
while(bytes>0) {
bytes=fs.Read(buffer,0,BUFFER_LENGTH);
for(var x=0;bytes>x;x++) {
for(var y=0;searchLength>y;y++) {
if(x+y>bytes-1) {
break;
}
if(binarySearchArray[y]!=buffer[x+y]) {
break;
}
if(searchLength-1==y) {
outputList.Add(x+y+searchOffset-searchLength-1+startSearchFrom);
break;
}
}
}
searchOffset+=BUFFER_LENGTH;
}
fs.Position=startingPosition;
return outputList;
}
/// <summary>
/// Turns a date into Unix Epoch time (usualy for output into JSON).
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns></returns>
public static int ToSeconds(this DateTime dateTime) {
return dateTime.Hour*3600+dateTime.Minute*60+dateTime.Second;
}
/// <summary>
/// Turns almost anything into a JSON string.
/// </summary>
/// <returns></returns>
public static string ToJson(this object obj) {
Newtonsoft.Json.JsonSerializer json=new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling=NullValueHandling.Include;
json.ObjectCreationHandling=Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling=Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling=ReferenceLoopHandling.Error;
json.Error+=delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args){
string errObject = args.ErrorContext.OriginalObject.GetType().ToString();
String.Format("Error serializing object {0}.",errObject).Debug(5);
args.ErrorContext.Handled = true;
};
string output = "";
using(StringWriter sw=new StringWriter()){
Newtonsoft.Json.JsonTextWriter writer=new JsonTextWriter(sw);
writer.Formatting=Newtonsoft.Json.Formatting.Indented;
writer.QuoteChar='"';
json.Serialize(writer,obj);
output=sw.ToString();
}
return output;
}
/// <summary>
/// Turns JSON arrays and JSON objects into Lists and Dictionaries.
/// </summary>
/// <param name="jobject">The jobject.</param>
/// <returns></returns>
public static object JTokenToGeneric(this object jobject) {
if(jobject.GetType()==typeof(JValue)) {
JValue o=(JValue)jobject;
return o.Value;
} else if(jobject.GetType()==typeof(JArray)) {
List<object> j=new List<object>();
foreach(object b in jobject as JArray) {
j.Add(b.JTokenToGeneric());
}
return j;
} else {
Dictionary<string,object> j=new Dictionary<string,object>();
JObject o=(JObject)jobject;
foreach(KeyValuePair<string,JToken> i in o) {
j.Add(i.Key,i.Value.JTokenToGeneric());
}
return j;
}
}
/// <summary>
/// Check if the specified column exists in the data set.
/// </summary>
/// <param name="r">The r.</param>
/// <param name="columnName">Name of the column.</param>
/// <returns>
/// <c>true</c> if the specified r has column; otherwise, <c>false</c>.
/// </returns>
public static bool HasColumn(this SqlDataReader r,string columnName) {
try {
return r.GetOrdinal(columnName)>=0;
} catch(IndexOutOfRangeException) {
return false;
}
}
/// <summary>
/// If the key is present in the dictionary the key's value will be returned
/// else the argument defaultValue will be returned
/// or if the third argument is null then a missing key will result in a null value.
/// </summary>
/// <param name="d">The input Dictionary</param>
/// <param name="keyName">Name of the key.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="defaultValueOrNull">if set to <c>true</c> [default value or null].</param>
/// <returns></returns>
public static object KeyOrDefault(this Dictionary<string,object> d,
string keyName,object defaultValue,bool defaultValueOrNull) {
if(d.ContainsKey(keyName)) {
if(d[keyName]!=null) {
return d[keyName];
} else {
if(defaultValueOrNull) {
return defaultValue;
} else {
return null;
}
}
} else {
if(defaultValueOrNull) {
return defaultValue;
} else {
return null;
}
}
}
/// <summary>
/// If the key is present in the dictionary the key's value will be returned
/// else the argument defaultValue will be returned.
/// </summary>
/// <param name="d">Input Dictionary</param>
/// <param name="keyName">Name of the key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static object KeyOrDefault(this Dictionary<string,object> d,
string keyName,object defaultValue) {
if(d.ContainsKey(keyName)) {
return d[keyName];
} else {
return defaultValue;
}
}
/// <summary>
/// Turns a virtual path starting with ~ into a physical path on the server.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public static string VirtualToPhysicalSitePath(this string path){
return path.Replace("~/",Main.PhysicalApplicationPath).Replace("/","\\");
}
/// <summary>
/// Wrapper for HttpContext.Current.Response.Write.
/// Writes a line to the current HTTP client.
/// </summary>
/// <param name="stringToWrite">The string to write.</param>
public static void w(this object stringToWrite) {
HttpContext.Current.Response.Write(stringToWrite);
}
/// <summary>
/// Wrapper for HttpContext.Current.Response.Write.
/// Writes a line to the current HTTP client.
/// And optionaly flushes the response buffer to the HTTP client.
/// </summary>
/// <param name="stringToWrite">The string to write.</param>
/// <param name="flush">if set to <c>true</c> [flush].</param>
public static void w(this object stringToWrite,bool flush) {
HttpContext.Current.Response.Write(stringToWrite);
if(flush) {
HttpContext.Current.Response.Flush();
}
}
/// <summary>
/// Creates a randoms the number.
/// </summary>
/// <param name="min">Minimum number to generate.</param>
/// <param name="max">Maximum number to generate.</param>
/// <returns></returns>
private static int RandomNumber(int min,int max) {
Random random=new Random();
return random.Next(min,max);
}
/// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
private static string RandomString(int size,bool lowerCase) {
StringBuilder builder=new StringBuilder();
Random random=new Random();
char ch;
for(int i=0;i<size;i++) {
ch=Convert.ToChar(Convert.ToInt32(Math.Floor(26*random.NextDouble()+65)));
builder.Append(ch);
}
if(lowerCase)
return builder.ToString();
return builder.ToString();
}
/// <summary>
/// Creates a file name without extention based on a base64 Guid (but _not_ convertable back into a GUID).
/// </summary>
/// <param name="o">The Guid you want to turn into a file name.</param>
/// <returns>File name safe Guid value.</returns>
public static string ToFileName(this Guid o) {
return Regex.Replace(Convert.ToBase64String(o.ToByteArray()),"/|\\\\|:|\\*|\\?|\"|\\<|\\>|\\||\\+|\\=","");
}
/// <summary>
/// Creates a unique hash value from a Guid.
/// </summary>
/// <param name="o">The Guid you want to turn into a hash value.</param>
/// <returns>Base64 representation of the Guid</returns>
public static string ToBase64DomId(this Guid o) {
return "d"+Regex.Replace(Convert.ToBase64String(o.ToByteArray()),"/|\\\\|:|\\*|\\?|\"|\\<|\\>|\\||\\+|\\=","");
}
/// <summary>
/// Creates a unique hash value from a Guid.
/// </summary>
/// <param name="o">The Guid you want to turn into a hash value.</param>
/// <returns>Base64 representation of the Guid</returns>
public static string ToBase64Hash(this Guid o) {
return Regex.Replace(Convert.ToBase64String(o.ToByteArray()),"/|\\\\|:|\\*|\\?|\"|\\<|\\>|\\||\\+|\\=","");
}
/// <summary>
/// Gets the encoder info for a particualr mimeType.
/// </summary>
/// <param name="mimeType">Type of the MIME.</param>
/// <returns></returns>
internal static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(String mimeType){
int j;
System.Drawing.Imaging.ImageCodecInfo[] encoders;
encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j){
if(encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
/// <summary>
/// Saves the Bitmap as a JPG with options.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="path">The path.</param>
/// <param name="quality">The quality.</param>
public static void SaveJpg(this System.Drawing.Bitmap bitmap, string path, long quality){
System.Drawing.Imaging.ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, quality);
encoderParameters.Param[0] = encoderParameter;
using(Stream st=File.Create(path)){
bitmap.Save(st,codecInfo,encoderParameters);
}
return;
}
/// <summary>
/// Sends the object as a string to the debugging console (output,debug.log).
/// </summary>
/// <param name="o">The Object</param>
/// <param name="verbosity">The verbosity.</param>
/// <param name="supressDate">if set to <c>true</c> [supress date].</param>
/// <returns></returns>
public static object Debug(this object o, int verbosity, bool supressDate) {
string _msg = "";
try {
if(Main.LogVerbosity >= verbosity) {
_msg = o.ToString();
string output = (supressDate ? "" : DateTime.Now.ToString() + ":") + _msg;
if(Main.debug != null) {
Main.debug.WriteLine(output);
}
Rendition.TelnetServer.WriteToAllClients(_msg);
}
}catch{}
return o;
}
/// <summary>
/// Converts a string to a base 53 number (0-9, A-Z, a-z).
/// Limited to the size of the int class.
/// </summary>
/// <param name="base53number">The base53number.</param>
/// <returns></returns>
public static int ConvertBase53(string base53number){
char[] base32 = new char[] {
'0','1','2','3','4','5','6','7',
'8','9','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v',
'w','x','y','z','A','B','C','D',
'E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z'
};
int n = 0;
foreach (char d in base53number){
n = n << 5;
int idx = Array.IndexOf(base32, d);
if (idx == -1)
throw new Exception("Provided number contains invalid characters");
n += idx;
}
return n;
}
/// <summary>
/// Sends information to the output.
/// </summary>
/// <param name="o">The object to turn into a string and display on the console.</param>
/// <param name="verbosity">Verbosity level 1-10. 1 = quiet time. 10 = the truth shall set you free.</param>
/// <returns>The object passed.</returns>
public static object Debug(this object o, int verbosity) {
o.Debug(verbosity,false);
return o;
}
/// <summary>
/// Creates a connection when the connection passed is null.
/// </summary>
/// <param name="cn1">The CN1.</param>
/// <returns>Working SQL connection.</returns>
public static SqlConnection GetActiveConnectionWhenNull(SqlConnection cn1){
if(cn1!=null){
return cn1;
}else{
return Site.CreateConnection(true, true);
}
}
}
/// <summary>
/// Impersonates another user briefly
/// </summary>
public class Impersonation : IDisposable {
WindowsImpersonationContext ImpersonatedUser = null;
WindowsIdentity NewId = null;
[DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )]
private static extern bool LogonUser( String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken );
[DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
private extern static bool CloseHandle( IntPtr handle );
/// <summary>
/// Initializes a new instance of the <see cref="Impersonation"/> class.
/// </summary>
[PermissionSetAttribute( SecurityAction.Demand, Name = "FullTrust" )]
public Impersonation() {
try {
SafeTokenHandle safeTokenHandle = null;
string userName, domainName;
// Get the user token for the specified user, domain, and password using the
// unmanaged LogonUser method.
// The local machine name can be used for the domain name to impersonate a user on this machine.
domainName = Main.ElevatedSecurityDomain;
userName = Main.ElevatedSecurityUser;
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser( userName, domainName, Main.ElevatedSecurityPassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle );
if( false == returnValue ) {
int ret = Marshal.GetLastWin32Error();
( "LogonUser failed with error code : " + ret ).Debug( 0 );
throw new System.ComponentModel.Win32Exception( ret );
}
// Use the token handle returned by LogonUser.
NewId = new WindowsIdentity( safeTokenHandle.DangerousGetHandle() );
ImpersonatedUser = NewId.Impersonate();
} catch( Exception ex ) {
string msg = "Impersonate user exception occurred. " + ex.Message;
( msg ).Debug( 0 );
throw new Exception( msg );
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose() {
NewId.Dispose();
ImpersonatedUser.Dispose();
}
}
/// <summary>
/// Used by the Impersonation class
/// </summary>
internal sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeTokenHandle()
: base( true ) {
}
[DllImport( "kernel32.dll" )]
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs( UnmanagedType.Bool )]
private static extern bool CloseHandle( IntPtr handle );
protected override bool ReleaseHandle() {
return CloseHandle( handle );
}
}
} | mit |
swapnilchincholkar/josh-library | config/routes.rb | 1623 | Rails.application.routes.draw do
devise_for :users
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'application#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| mit |
kiskolabs/splendidbacon | spec/controllers/broadcast_reads_controller_spec.rb | 65 | require 'spec_helper'
describe BroadcastReadsController do
end
| mit |
geoffsmiller/RetroTechClub | retrotechclub/models/game.py | 3027 | from retrotechclub import db
game_master_platform = db.Table(
'game_master_platform',
db.Column('game_master_id', db.Integer, db.ForeignKey('game_master.id')),
db.Column('platform_id', db.Integer, db.ForeignKey('platform.id'))
)
game_master_publisher = db.Table(
'game_master_publisher',
db.Column('game_master_id', db.Integer, db.ForeignKey('game_master.id')),
db.Column('publisher_id', db.Integer, db.ForeignKey('company.id'))
)
game_master_developer = db.Table(
'game_master_developer',
db.Column('game_master_id', db.Integer, db.ForeignKey('game_master.id')),
db.Column('developer_id', db.Integer, db.ForeignKey('company.id'))
)
class GameMaster(db.Model):
__tablename = 'game_master'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
release_date = db.Column(db.Date())
description = db.Column(db.String(2040))
platforms = db.relationship(
'Platform',
secondary=game_master_platform,
backref=db.backref('game_masters', lazy='dynamic')
)
publishers = db.relationship(
'Company',
secondary=game_master_publisher,
backref=db.backref(
'published_game_masters',
lazy='dynamic'
)
)
developers = db.relationship(
'Company',
secondary=game_master_developer,
backref=db.backref(
'developed_game_masters',
lazy='dynamic'
)
)
game_releases = db.relationship(
'GameRelease',
backref='game_master',
lazy='dynamic'
)
def __init__(self, name, release_date, description):
self.name = name
self.release_date = release_date
self.description = description
class GameRelease(db.Model):
__tablename__ = 'game_release'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
release_date = db.Column(db.Date())
game_master_id = db.Column(db.Integer, db.ForeignKey('game_master.id'))
publisher_id = db.Column(db.Integer, db.ForeignKey('company.id'))
developer_id = db.Column(db.Integer, db.ForeignKey('company.id'))
description = db.Column(db.String(2040))
platform_id = db.Column(db.Integer, db.ForeignKey('platform.id'))
platform = db.relationship(
'Platform',
backref='games'
)
publisher = db.relationship(
'Company',
backref='published_games',
foreign_keys=[publisher_id]
)
developer = db.relationship(
'Company',
backref='developed_games',
foreign_keys=[developer_id]
)
def __init__(self, name, release_date, game_master_id, publisher_id,
developer_id, platform_id, description):
self.name = name
self.release_date = release_date
self.game_master_id = game_master_id
self.publisher_id = publisher_id
self.developer_id = developer_id
self.platform_id = platform_id
self.description = description
| mit |
phoenix-scholars/angular-pluf | Gruntfile.js | 15413 | /*
* Copyright (c) 2015 Phoenix Scholars Co. (http://dpq.co.ir)
*
* 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.
*/
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function(grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
/*
* به صورت خودکار تمام افزونههای مورد نیاز بار گذاری میشود. در صورتی که
* این افزونهها نامگذاری grunt را رعایت نمیکنند باید نام وظایف آنها نیز
* تعیین شود.
*/
require('jit-grunt')(grunt, {
useminPrepare : 'grunt-usemin',
ngtemplates : 'grunt-angular-templates'
});
/*
* تنظیمهای کلی بسته را ایجاد میکند. این تنظیمها بر اساس خصوصیتهای تعیین
* شده در پرونده bower.json تعیین میشود.
*/
var appConfig = {
app : require('./bower.json').srcPath || 'src',
dist : 'dist',
pkg : require('./bower.json')
};
// Define the configuration for all the tasks
grunt
.initConfig({
/*
* تنظیمهای پروژه: تمام تنظیمهایی که در وظایف استفاده میشود
* بر اساس این متغیر است.
*/
yeoman : appConfig,
/*
* اجرای تست ایستا روی تمام سروسهای ایجاد شده . با این کار
* مطمئن میشیم که خطای نحوی در برنامهها وجود نداره. برای این
* کار از تستهای ایستای jshint استفاده میکنیم. این برنامه
* میتونه پرندههای js رو دریافت و تحلیل کنه. توضیحات بیشتر در
* مورد این برنامه رو در مسیر زیر ببینید:
*
* http://jshint.com
*
* نکته: ما فرض کردیم که تمام کدها در پوشه اصلی و یک زیر پوشه
* دیگر نوشته می شود در صورتی که سلسله مراتب پوشهها بیشتر از
* این شد باید این تنظیمها تغییر کند.
*
* تنظیمهای به کار رفته در این پردازش در فایل .jshintrc وجود
* دارد و شما میتوانید در صورت نیاز این تنظیمها را تغییر دهید.
*
* برای استفاده از این تست در محیط grunt از بسته
* grunt-contrib-jshint استفاده شده است که به صورت خودکار و بر
* اساس تنظیمهای موجود این نوع تست را روی تمام کدهای موجود در
* نرم افزار اجرا میکند. برای اطلاعات بیشتر در مورد این افزونه
* به آدرس زیر مراجعه کنید:
*
* https://github.com/gruntjs/grunt-contrib-jshint
*
* برای اینکه نتیجههای تولید شده بر اساس این تست خوب نمایش داده
* بشه از یک افزونه دیگه به نام jshint-stylish استفاده شده است.
* البته شما میتونید از روشهای دیگهای برای تولید گزارش
* استفاده کنید. برای اطلاع بیشتر در این زمینه پیوند زیر رو
* ببینید:
*
* http://jshint.com/docs/reporters/
*
*
*/
jshint : {
options : {
jshintrc : '.jshintrc',
reporter : require('jshint-stylish')
},
all : {
src : [ 'Gruntfile.js', '<%= yeoman.app %>/{,*/}*.js' ]
},
test : {
options : {
jshintrc : 'test/.jshintrc'
},
src : [ 'test/spec/{,**/}*.js' ]
}
},
/*
* استایل کدها رو بررسی میکنه تا مطمئن بشیم که کدها خوش فرم
* نوشته شده اند. این یک نمونه تست هست که توش به نحوه نگارش کدها
* توجه میکنه. برای این کار از یک بسته به نام jscs استفاده شده
* است. برای کسب اطلاع بیشتر در مورد این بسته پیونده زیر رو
* ببینید:
*
* http://jscs.info/
*
* این برنامه رو با استفاده از افزونه grunt-jscs اجرا میکنیم.
* این افزونه امکان چک کردن تمام کدهای نوشته شده رو میده.
* اطلاعات بیشتر در مورد این افزونه در مسییر زیر وجود داره:
*
* https://github.com/jscs-dev/grunt-jscs
*
* برای این بسته هم یه سری تنظیمها در نظر گرفته شده که تو فایل
* .jscsrc وجود داره در صورت تمایل میتونید این تنظیمها رو بر
* اساس نیازهای خودتون به روز کنید.
*/
jscs : {
options : {
config : '.jscsrc',
verbose : true
},
all : {
src : [ 'Gruntfile.js', '<%= yeoman.app %>/{,*/}*.js' ]
},
test : {
src : [ 'test/spec/{,**/}*.js' ]
}
},
/*
* یکی از کارهایی که در تولید نهایی
*/
jsdoc : {
all : {
src : [ '<%= yeoman.app %>/{,**/}*.js' ],
options : {
destination : '<%= yeoman.dist %>/doc/jsdoc',
configure : 'node_modules/angular-jsdoc/common/conf.json',
template : 'node_modules/angular-jsdoc/angular-template',
tutorial : 'doc/tutorials',
readme : 'README.md'
},
},
},
/*
* مسیرها و دادههای موقت را حذف میکند تا شرایط برای اجرای
* دوباره مراحل ساخت آماده شود. خیلی از این فایلها به عنوان
* محصول و یا مستند ایجاد میشن و باید اونها رو قبل از هر بار
* تولید نسخه جدید حذف کنیم. پاک کردن با استفاده از این ماژول
* انجام میشه. اطلاعات بشتر رو از پیوند زیر مطالعه کنید:
*
* https://github.com/gruntjs/grunt-contrib-clean
*
* تمام پروندههایی که در مسیر .tmp و یا مسیر محصول نهایی ایجاد
* میشن به عنوان پرندههای اضافه در نظر گرفته میشوند و به صورت
* خودکار حذف میشوند.
*/
clean : {
dist : {
files : [ {
dot : true,
src : [ '.tmp', '<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*' ]
} ]
}
},
/*
* تمام وابستگیهایی که با استفاده از مدیریت بستههای bower نصب
* میشود شامل فایلهای هست که باید توی برنامهها اضافه بشه. این
* کار رو میشه به صورت خودکار انجام داد. بسته wiredep توی
* بخشههای متفاوتی از برنامه میتونه این وابستگیهای جدید رو
* تزریق کنه و شما رو از انجام این کار بی نیاز کنه. برای اطلاع
* بیشتر در مورد این افزونه پیونده زیر رو ببیندی:
* ؟؟
*
* این کار روش سادهای داره، یه الگو پیدا میشه و بعد وسط اون
* الگو با فهرست فایلهایی وابستگیها پر میشه.
*/
wiredep : {
// app: {
// src: ['<%= yeoman.app %>/index.html'],
// ignorePath: /\.\.\//
// },
test : {
devDependencies : true,
src : '<%= karma.unit.configFile %>',
ignorePath : /\.\.\//,
fileTypes : {
js : {
block : /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect : {
js : /'(.*\.js)'/gi
},
replace : {
js : '\'{{filePath}}\','
}
}
}
}
},
// The following *-min tasks will produce minified files in the
// dist folder
// By default, your `index.html`'s <!-- Usemin block --> will
// take care of
// minification. These next options are pre-configured if you do
// not wish
// to use the Usemin blocks.
uglify : {
dist : {
files : {
'<%= yeoman.dist %>/<%= yeoman.pkg.name %>.min.js' : [ '.tmp/{,*/}*.js' ]
}
}
},
/*
* کتابخونهها از مجموعهای از پروندههای اسکریپتی تشکیل شدن که
* در نهایت باید با هم ترکیب بشن و به صورت یک پرونده یکتا ذخیره
* بشن. این کار با استفاده از افزونه concat انجام میشه. اطلاعات
* بیشتر در این مورد تو مسیر زیر وجود داره:
*
* https://github.com/gruntjs/grunt-contrib-concat
*
* ما تمام فایلها رو سر هم میزنیم و دوتا پرونده ایجاد میکنیم،
* یکی مستقیم به عنوان محصول ارائه میشه ولی یکی تو پوشه موقت
* ایجاد میشه تا بتونیم کارهای دیگهای روش انجام بدیم.
*/
concat : {
tmp : {
src : [ '<%= yeoman.app %>/*.js',
'<%= yeoman.app %>/**/*.js' ],
dest : '.tmp/<%= yeoman.pkg.name %>.js'
},
dist : {
src : [ '<%= yeoman.app %>/*.js',
'<%= yeoman.app %>/**/*.js' ],
dest : '<%= yeoman.dist %>/<%= yeoman.pkg.name %>.js'
}
},
/*
* الگوهای متفاوتی در یک بسته طراحی میشه اما باید این الگوها رو
* بزنیم سر هم و حجمش رو کم کنی تا به یک کتابخونه مناسب برسیم.
* یکی از ابزارهایی که میتونه الگوهای ایجاد شده برای انگولار رو
* مدیریت کن بسته ngtemplates هست. برای اطلاع بیشتر در مورد این
* بسته پیوند زیر رو ببینید:
*
* https://github.com/ericclemmons/grunt-angular-templates
*
* این بسته رو میتونیم با سایر بستهها ترکیب کنیم.
*/
// ngtemplates: {
// dist: {
// options: {
// module: 'ngDigiDoci',
// // htmlmin: '<%= htmlmin.dist.options %>',
// usemin: '<%= yeoman.pkg.name %>.js'
// },
// cwd: '<%= yeoman.app %>',
// src: 'views/{,*/}*.html',
// dest: '.tmp/templateCache.js'
// }
// },
/*
* یکی از مشکلاتی که داریم دزدی کدها است و این جایی سخت تر میشه
* که نمیشه به سادگی کدهای انگولار رو به هم ریخت. البته توی
* بسته انگولار راهکارهایی برای این منظور در نظر گرفته شده. با
* استفاده از افزونه ngAnnotate ما ساختار کد رو تغییر میدیم و
* در نهایت به یک مدلی تبدیل میکنیم که بشه بهمش ریخت. برای
* اطلاع بیشتر در این زمینه یپوند زیر رو مشاهد کنید:
*
* https://github.com/mgol/grunt-ng-annotate
*
* این کار روی پروندههایی انجام میشه که توی مسیر .tmp ایجاد
* شده اند و همگی پروندههای موقت هستن. به این ترتیب میتونیم
* تمام پروندههای موجود در این مسیر رو کامل به هم بریزیم.
*/
ngAnnotate : {
dist : {
files : [ {
expand : true,
cwd : '.tmp/',
src : '*.js',
dest : '.tmp/'
} ]
}
},
// Copies remaining files to places other tasks can use
copy : {
// dist: {
// files: [{
// expand: true,
// dot: true,
// cwd: '<%= yeoman.app %>',
// dest: '<%= yeoman.dist %>',
// src: [
// '*.{ico,png,txt}',
// '*.html',
// 'images/{,*/}*.{webp}',
// 'styles/fonts/{,*/}*.*'
// ]
// }, {
// expand: true,
// cwd: '.tmp/images',
// dest: '<%= yeoman.dist %>/images',
// src: ['generated/*']
// }]
// },
styles : {
expand : true,
cwd : '<%= yeoman.app %>/styles',
dest : '.tmp/styles/',
src : '{,*/}*.css'
}
},
// // Run some tasks in parallel to speed up the build process
// concurrent: {
// server: [
// 'copy:styles'
// ],
// test: [
// 'copy:styles'
// ],
// dist: [
// 'copy:styles',
// 'imagemin',
// 'svgmin'
// ]
// },
/*
* اجرای تستها با بسته karma هست.
*
* https://github.com/karma-runner/grunt-karma
*
* مدلهای متفاوتی میشه تستها رو اجرا کرد. در صورتی که بخواهید
* کدها رو روی یک کاوشگر خاص به صورت رفع خطا اجرا کنید پیوند زیر
* اطالعات خوبی برای این کار ارائه کرده است:
*
* http://bahmutov.calepin.co/debugging-karma-unit-tests.html
*
*/
karma : {
unit : {
configFile : 'test/karma.conf.js',
singleRun : true
},
debug : {
configFile : 'test/karma.conf.js',
port : 9999,
singleRun : false,
browsers : [ 'Chrome' ]
}
},
});
grunt.registerTask('test', [ 'clean', 'wiredep', 'karma:unit' ]);
grunt.registerTask('debug', [ 'clean', 'wiredep', 'karma:debug' ]);
grunt.registerTask('build', [ 'clean:dist', 'wiredep',
// 'ngtemplates',
'concat', 'ngAnnotate',
// 'copy:dist',
// 'cdnify',
'uglify'
// 'usemin'
]);
grunt.registerTask('default', [ 'concat', 'newer:jshint', 'newer:jscs',
'test', 'build' ]);
};
| mit |
acidvertigo/willibert | Abstraction/Process.php | 191 | <?php
/***********************************************
* Process abstraction.
**********************************************/
namespace Willibert\Abstraction;
abstract class Process
{
}
| mit |
pydupont/CV | inc/sendEmail.php | 2085 | <?php
// Replace this with your own email address
$siteOwnersEmail = 'pierreyves.dupont@gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?> | mit |
rajeshwarn/MailKit | MailKit/Net/Imap/ImapCommand.cs | 17854 | //
// ImapCommand.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2014 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using MimeKit;
using MimeKit.IO;
using MimeKit.Utils;
#if NETFX_CORE
using Windows.Storage.Streams;
using Encoding = Portable.Text.Encoding;
#endif
namespace MailKit.Net.Imap {
/// <summary>
/// An IMAP continuation handler.
/// </summary>
/// <remarks>
/// All exceptions thrown by the handler are considered fatal and will
/// force-disconnect the connection. If a non-fatal error occurs, set
/// it on the <see cref="ImapCommand.Exception"/> property.
/// </remarks>
delegate void ImapContinuationHandler (ImapEngine engine, ImapCommand ic, string text);
/// <summary>
/// An IMAP untagged response handler.
/// </summary>
/// <remarks>
/// <para>Most IMAP commands return their results in untagged responses.</para>
/// </remarks>
delegate void ImapUntaggedHandler (ImapEngine engine, ImapCommand ic, int index);
delegate void ImapCommandResetHandler (ImapCommand ic);
/// <summary>
/// IMAP command status.
/// </summary>
enum ImapCommandStatus {
Created,
Queued,
Active,
Complete,
Error
}
enum ImapCommandResult {
None,
Ok,
No,
Bad
}
enum ImapLiteralType {
String,
Stream,
MimeMessage
}
enum ImapStringType {
Atom,
QString,
Literal
}
class ImapIdleContext : IDisposable
{
readonly CancellationTokenSource source;
public ImapIdleContext (ImapEngine engine, CancellationToken doneToken, CancellationToken cancellationToken)
{
source = CancellationTokenSource.CreateLinkedTokenSource (doneToken, cancellationToken);
CancellationToken = cancellationToken;
DoneToken = doneToken;
Engine = engine;
}
public ImapEngine Engine {
get; private set;
}
public CancellationToken CancellationToken {
get; private set;
}
public CancellationToken LinkedToken {
get { return source.Token; }
}
public CancellationToken DoneToken {
get; private set;
}
public bool IsCancellationRequested {
get { return CancellationToken.IsCancellationRequested; }
}
public bool IsDoneRequested {
get { return DoneToken.IsCancellationRequested; }
}
public void Dispose ()
{
source.Dispose ();
}
}
/// <summary>
/// An IMAP literal object.
/// </summary>
class ImapLiteral
{
public readonly ImapLiteralType Type;
public readonly object Literal;
readonly FormatOptions format;
public ImapLiteral (FormatOptions options, object literal)
{
format = options;
if (literal is MimeMessage) {
Type = ImapLiteralType.MimeMessage;
} else if (literal is Stream) {
Type = ImapLiteralType.Stream;
} else if (literal is string) {
literal = Encoding.UTF8.GetBytes ((string) literal);
Type = ImapLiteralType.String;
} else if (literal is byte[]) {
Type = ImapLiteralType.String;
} else {
throw new ArgumentException ("Unknown literal type");
}
Literal = literal;
}
/// <summary>
/// Gets the length of the literal, in bytes.
/// </summary>
/// <value>The length.</value>
public long Length {
get {
if (Type == ImapLiteralType.String)
return (long) ((byte[]) Literal).Length;
using (var measure = new MeasuringStream ()) {
switch (Type) {
case ImapLiteralType.Stream:
var stream = (Stream) Literal;
stream.CopyTo (measure, 4096);
stream.Position = 0;
break;
case ImapLiteralType.MimeMessage:
((MimeMessage) Literal).WriteTo (format, measure);
break;
}
return measure.Length;
}
}
}
/// <summary>
/// Writes the literal to the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public void WriteTo (ImapStream stream, CancellationToken cancellationToken)
{
if (Type == ImapLiteralType.String) {
var bytes = (byte[]) Literal;
stream.Write (bytes, 0, bytes.Length, cancellationToken);
stream.Flush (cancellationToken);
return;
}
if (Type == ImapLiteralType.MimeMessage) {
var message = (MimeMessage) Literal;
message.WriteTo (format, stream, cancellationToken);
stream.Flush (cancellationToken);
return;
}
var literal = (Stream) Literal;
var buf = new byte[4096];
int nread;
while ((nread = literal.Read (buf, 0, buf.Length)) > 0)
stream.Write (buf, 0, nread, cancellationToken);
stream.Flush (cancellationToken);
}
}
/// <summary>
/// A partial IMAP command.
/// </summary>
class ImapCommandPart
{
public readonly byte[] Command;
public readonly ImapLiteral Literal;
public ImapCommandPart (byte[] command, ImapLiteral literal)
{
Command = command;
Literal = literal;
}
}
/// <summary>
/// An IMAP command.
/// </summary>
class ImapCommand
{
public Dictionary<string, ImapUntaggedHandler> UntaggedHandlers { get; private set; }
public ImapContinuationHandler ContinuationHandler { get; set; }
public CancellationToken CancellationToken { get; private set; }
public ImapCommandStatus Status { get; internal set; }
public ImapCommandResult Result { get; internal set; }
public Exception Exception { get; internal set; }
public readonly List<ImapResponseCode> RespCodes;
public string ResultText { get; internal set; }
public ImapFolder Folder { get; private set; }
public object UserData { get; internal set; }
public string Tag { get; private set; }
public bool Bye { get; internal set; }
public int Id { get; internal set; }
readonly List<ImapCommandPart> parts = new List<ImapCommandPart> ();
readonly ImapEngine Engine;
int current;
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommand"/> class.
/// </summary>
/// <param name="engine">The IMAP engine that will be sending the command.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="folder">The IMAP folder that the command operates on.</param>
/// <param name="options">The formatting options.</param>
/// <param name="format">The command format.</param>
/// <param name="args">The command arguments.</param>
public ImapCommand (ImapEngine engine, CancellationToken cancellationToken, ImapFolder folder, FormatOptions options, string format, params object[] args)
{
UntaggedHandlers = new Dictionary<string, ImapUntaggedHandler> ();
RespCodes = new List<ImapResponseCode> ();
CancellationToken = cancellationToken;
Status = ImapCommandStatus.Created;
Result = ImapCommandResult.None;
Engine = engine;
Folder = folder;
using (var builder = new MemoryStream ()) {
var plus = (Engine.Capabilities & ImapCapabilities.LiteralPlus) != 0 ? "+" : string.Empty;
int argc = 0;
byte[] buf;
string str;
char c;
for (int i = 0; i < format.Length; i++) {
if (format[i] == '%') {
switch (format[++i]) {
case '%': // a literal %
builder.WriteByte ((byte) '%');
break;
case 'c': // a character
c = (char) args[argc++];
builder.WriteByte ((byte) c);
break;
case 'd': // an integer
str = ((int) args[argc++]).ToString ();
buf = Encoding.ASCII.GetBytes (str);
builder.Write (buf, 0, buf.Length);
break;
case 'u': // an unsigned integer
str = ((uint) args[argc++]).ToString ();
buf = Encoding.ASCII.GetBytes (str);
builder.Write (buf, 0, buf.Length);
break;
case 'F': // an ImapFolder
var utf7 = ((ImapFolder) args[argc++]).EncodedName;
AppendString (options, builder, utf7);
break;
case 'L':
var literal = new ImapLiteral (options, args[argc++]);
var length = literal.Length;
if (options.International)
str = "UTF8 (~{" + length + plus + "}\r\n";
else
str = "{" + length + plus + "}\r\n";
buf = Encoding.ASCII.GetBytes (str);
builder.Write (buf, 0, buf.Length);
parts.Add (new ImapCommandPart (builder.ToArray (), literal));
builder.SetLength (0);
if (options.International)
builder.WriteByte ((byte) ')');
break;
case 'S': // a string which may need to be quoted or made into a literal
AppendString (options, builder, (string) args[argc++]);
break;
case 's': // a safe atom string
buf = Encoding.ASCII.GetBytes ((string) args[argc++]);
builder.Write (buf, 0, buf.Length);
break;
default:
throw new FormatException ();
}
} else {
builder.WriteByte ((byte) format[i]);
}
}
parts.Add (new ImapCommandPart (builder.ToArray (), null));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommand"/> class.
/// </summary>
/// <param name="engine">The IMAP engine that will be sending the command.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="folder">The IMAP folder that the command operates on.</param>
/// <param name="format">The command format.</param>
/// <param name="args">The command arguments.</param>
public ImapCommand (ImapEngine engine, CancellationToken cancellationToken, ImapFolder folder, string format, params object[] args)
: this (engine, cancellationToken, folder, FormatOptions.Default, format, args)
{
}
static bool IsAtom (char c)
{
return c < 128 && !char.IsControl (c) && "(){ \t%*\\\"]".IndexOf (c) == -1;
}
bool IsQuotedSafe (char c)
{
return (c < 128 || Engine.UTF8Enabled) && !char.IsControl (c);
}
ImapStringType GetStringType (string value)
{
var type = ImapStringType.Atom;
for (int i = 0; i < value.Length; i++) {
if (!IsAtom (value[i])) {
if (!IsQuotedSafe (value[i]))
return ImapStringType.Literal;
type = ImapStringType.QString;
}
}
return type;
}
void AppendString (FormatOptions options, MemoryStream builder, string value)
{
byte[] buf;
switch (GetStringType (value)) {
case ImapStringType.Literal:
var literal = Encoding.UTF8.GetBytes (value);
var length = literal.Length.ToString ();
buf = Encoding.ASCII.GetBytes (length);
builder.WriteByte ((byte) '{');
builder.Write (buf, 0, buf.Length);
if (Engine.IsGMail || (Engine.Capabilities & ImapCapabilities.LiteralPlus) != 0)
builder.WriteByte ((byte) '+');
builder.WriteByte ((byte) '}');
builder.WriteByte ((byte) '\r');
builder.WriteByte ((byte) '\n');
if (Engine.IsGMail || (Engine.Capabilities & ImapCapabilities.LiteralPlus) != 0) {
builder.Write (literal, 0, literal.Length);
} else {
parts.Add (new ImapCommandPart (builder.ToArray (), new ImapLiteral (options, literal)));
builder.SetLength (0);
}
break;
case ImapStringType.QString:
buf = Encoding.UTF8.GetBytes (MimeUtils.Quote (value));
builder.Write (buf, 0, buf.Length);
break;
case ImapStringType.Atom:
buf = Encoding.UTF8.GetBytes (value);
builder.Write (buf, 0, buf.Length);
break;
}
}
/// <summary>
/// Registers the untagged handler for the specified atom token.
/// </summary>
/// <param name="atom">The atom token.</param>
/// <param name="handler">The handler.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="atom"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="handler"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Untagged handlers must be registered before the command has been queued.
/// </exception>
public void RegisterUntaggedHandler (string atom, ImapUntaggedHandler handler)
{
if (atom == null)
throw new ArgumentNullException ("atom");
if (handler == null)
throw new ArgumentNullException ("handler");
if (Status != ImapCommandStatus.Created)
throw new InvalidOperationException ("Untagged handlers must be registered before the command has been queued.");
UntaggedHandlers.Add (atom, handler);
}
/// <summary>
/// Sends the next part of the command to the server.
/// </summary>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="ImapProtocolException">
/// An IMAP protocol error occurred.
/// </exception>
public bool Step ()
{
var supportsLiteralPlus = (Engine.Capabilities & ImapCapabilities.LiteralPlus) != 0;
var idle = UserData as ImapIdleContext;
var result = ImapCommandResult.None;
ImapToken token;
if (current == 0) {
Tag = string.Format ("{0}{1:D8}", Engine.TagPrefix, Engine.Tag++);
var buf = Encoding.ASCII.GetBytes (Tag + " ");
Engine.Stream.Write (buf, 0, buf.Length, CancellationToken);
}
do {
var command = parts[current].Command;
Engine.Stream.Write (command, 0, command.Length, CancellationToken);
if (!supportsLiteralPlus || parts[current].Literal == null)
break;
parts[current].Literal.WriteTo (Engine.Stream, CancellationToken);
if (current + 1 >= parts.Count)
break;
current++;
} while (true);
Engine.Stream.Flush ();
// now we need to read the response...
do {
if (Engine.State == ImapEngineState.Idle) {
int timeout = Engine.Stream.ReadTimeout;
try {
Engine.Stream.ReadTimeout = -1;
token = Engine.ReadToken (idle.LinkedToken);
Engine.Stream.ReadTimeout = timeout;
} catch (OperationCanceledException) {
Engine.Stream.ReadTimeout = timeout;
if (idle.IsCancellationRequested)
throw;
Engine.Stream.IsConnected = true;
token = Engine.ReadToken (CancellationToken);
}
} else {
token = Engine.ReadToken (CancellationToken);
}
if (token.Type == ImapTokenType.Plus) {
// we've gotten a continuation response from the server
var text = Engine.ReadLine (CancellationToken).Trim ();
// if we've got a Literal pending, the '+' means we can send it now...
if (!supportsLiteralPlus && parts[current].Literal != null) {
parts[current].Literal.WriteTo (Engine.Stream, CancellationToken);
break;
}
Debug.Assert (ContinuationHandler != null, "The ImapCommand's ContinuationHandler is null");
ContinuationHandler (Engine, this, text);
} else if (token.Type == ImapTokenType.Asterisk) {
// we got an untagged response, let the engine handle this...
Engine.ProcessUntaggedResponse (CancellationToken);
} else if (token.Type == ImapTokenType.Atom && (string) token.Value == Tag) {
// the next token should be "OK", "NO", or "BAD"
token = Engine.ReadToken (CancellationToken);
if (token.Type == ImapTokenType.Atom) {
string atom = (string) token.Value;
switch (atom) {
case "BAD": result = ImapCommandResult.Bad; break;
case "OK": result = ImapCommandResult.Ok; break;
case "NO": result = ImapCommandResult.No; break;
}
if (result == ImapCommandResult.None)
throw ImapEngine.UnexpectedToken (token, false);
token = Engine.ReadToken (CancellationToken);
if (token.Type == ImapTokenType.OpenBracket) {
var code = Engine.ParseResponseCode (CancellationToken);
RespCodes.Add (code);
break;
}
if (token.Type != ImapTokenType.Eoln) {
// consume the rest of the line...
Engine.ReadLine (CancellationToken);
break;
}
} else {
// looks like we didn't get an "OK", "NO", or "BAD"...
throw ImapEngine.UnexpectedToken (token, false);
}
} else if (token.Type == ImapTokenType.OpenBracket) {
// Note: this is a work-around for broken IMAP servers like Office365.com that
// return RESP-CODES that are not preceded by "* OK " such as the example in
// issue #115 (https://github.com/jstedfast/MailKit/issues/115).
var code = Engine.ParseResponseCode (CancellationToken);
RespCodes.Add (code);
} else {
// no clue what we got...
throw ImapEngine.UnexpectedToken (token, false);
}
} while (true);
// the status should always be Active at this point, but just to be sure...
if (Status == ImapCommandStatus.Active) {
current++;
if (current >= parts.Count || result != ImapCommandResult.None) {
Status = ImapCommandStatus.Complete;
Result = result;
return false;
}
}
return true;
}
}
}
| mit |
ForestGuardian/ForestGuardianBackend | spec/controllers/modis_data_controller_spec.rb | 86 | require 'rails_helper'
RSpec.describe ModisDataController, type: :controller do
end
| mit |
floatinglacier/mastercard-api-explorer | packages/insomnia-httpsnippet/src/helpers/reducer.js | 354 | 'use strict'
module.exports = function (obj, pair) {
if (obj[pair.name] === undefined) {
obj[pair.name] = pair.value
return obj
}
if (Array.isArray(obj[pair.name])) {
obj[pair.name].push(pair.value)
return obj
}
// convert to array
var arr = [
obj[pair.name],
pair.value
]
obj[pair.name] = arr
return obj
}
| mit |
seanemmer/electrode | modules/charges/server/models/charges.server.model.js | 911 | 'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Charge Schema
*/
var ChargeSchema = new Schema({
vehicle: {
type: Schema.ObjectId,
ref: 'Vehicle',
index: true,
required: true
},
startTime: {
type: Date,
required: true
},
startLevel: {
type: Number,
min: 0,
max: 100,
required: true
},
endTime: {
type: Date,
default: null
},
endLevel: {
type: Number,
min: 0,
max: 110,
default: null
},
scheduleDay: {
type: String,
enum: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
required: true
},
scheduleTime: {
type: String,
match: /([1-9]|1[0-2]):[0-5][0-9](AM|PM)/,
required: true
},
scheduleTarget: {
type: Number,
min: 0,
max: 100,
required: true
}
});
mongoose.model('Charge', ChargeSchema);
| mit |
zniper/automag | magazine/apps/content/admin.py | 3009 | import logging
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.forms import FlatpageForm
from django import forms
from tinymce.widgets import TinyMCE
from articles.admin import ArticleAdmin as CoreArticleAdmin
from articles.forms import ArticleAdminForm, tag
from articles import models as core_models
from models import Article, Category, SingleImage
log = logging.getLogger('articles.forms')
class PageForm(FlatpageForm):
class Meta:
model = FlatPage
widgets = {
'content': TinyMCE(attrs={'cols': 120, 'rows': 30}),
}
class PageAdmin(FlatPageAdmin):
form = PageForm
class AttachmentInline(admin.TabularInline):
model = core_models.Attachment
extra = 5
max_num = 25
class ArticleForm(ArticleAdminForm):
categories = forms.ModelMultipleChoiceField(
Category.objects.all(),
widget=forms.CheckboxSelectMultiple(),
)
def __init__(self, *args, **kwargs):
super(ArticleForm, self).__init__(*args, **kwargs)
class Meta:
model = Article
widgets = {
'content': TinyMCE(attrs={'cols': 120, 'rows': 30}),
}
def clean_tags(self):
"""Turns the string of tags into a list"""
tags = [tag(t.strip()) for t in self.cleaned_data['tags'].split()
if len(t.strip())]
log.debug('Tagging Article %s with: %s' %
(self.cleaned_data.get('title', ''), tags))
self.cleaned_data['tags'] = tags
return self.cleaned_data['tags']
class ArticleAdmin(CoreArticleAdmin):
form = ArticleForm
fieldsets = (
(None, {'fields': ('title', 'content', 'tags', 'auto_tag', 'markup', 'status')}),
('Metadata', {
'fields': ('keywords', 'description', 'categories'),
'classes': ('collapse',)
}),
('Relationships', {
'fields': ('followup_for', 'related_articles'),
'classes': ('collapse',)
}),
('Scheduling', {'fields': ('publish_date', 'expiration_date')}),
('AddThis Button Options', {
'fields': ('use_addthis_button', 'addthis_use_author', 'addthis_username'),
'classes': ('collapse',)
}),
('Advanced', {
'fields': ('slug', 'is_active', 'featured', 'login_required', 'sites'),
'classes': ('collapse',)
}),
)
inlines = [AttachmentInline,]
def replace_model_admin(klass, new_klass):
try:
admin.site.unregister(klass)
except:
pass
finally:
admin.site.register(*new_klass)
replace_model_admin(core_models.Article, (Article, ArticleAdmin))
replace_model_admin(FlatPage, (FlatPage, PageAdmin))
admin.site.register(Category)
admin.site.register(SingleImage)
#try:
# from articles.models import Article as CoreArticle
# admin.site.unregister(CoreArticle)
#except:
# pass
| mit |
frc2171/website-2171 | robodogs/static/js/landing.js | 1136 | $(function() {
/* ========================
TYPING ANIMATION
======================== */
var $robodogs = $('#robodogs > span')
$robodogs.typed({
strings: $('#robodogs').attr("data-elements").split(","),
typeSpeed: 100,
backDelay: 3000,
loop: true
});
/* ========================
NAV SCROLL ANIMATION
======================== */
var scrollState = "top";
var $nav = $('nav');
var $window = $(window);
$window.scroll(function() {
var scrollTop = $window.scrollTop();
if (scrollTop != 0 && scrollState == "top") {
$nav.css("border-bottom-width","0");
$nav.animate({
height: '9%',
backgroundColor: 'rgba(0,0,0,0.8)'
}, 400);
scrollState = "scroll";
} else if (scrollTop == 0 && scrollState == "scroll") {
$nav.animate({
height: '15%',
backgroundColor: 'transparent'
}, 400);
$nav.css("border-bottom-width","1px");
scrollState = "top";
}
});
}); | mit |
l496501043/edpx-zhixin | env/phplib/ak/aclient/frame/source.class.php | 537 | <?php
/***************************************************************************
*
* Copyright (c) 2010 Baidu.com, Inc. All Rights Reserved
*
**************************************************************************/
/**
* @file frame/source.class.php
* @author wangweibing(com@baidu.com)
* @date 2010/12/10 17:40:59
* @brief
*
**/
abstract class AClientSource {
public abstract function set_conf($conf);
public abstract function get_resources();
}
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
?>
| mit |
DDTH/ddth-dao | ddth-dao-core/src/main/java/com/github/ddth/dao/utils/DatabaseVendor.java | 390 | package com.github.ddth.dao.utils;
/**
* JDBC driver vendor info.
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.8.3
*/
public enum DatabaseVendor {
UNKNOWN(0), MYSQL(10), POSTGRESQL(20), MSSQL(30), ORACLE(40);
private final int value;
DatabaseVendor(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
| mit |
digibyte/digibytego | src/js/controllers/preferencesBwsUrl.js | 1602 | 'use strict';
angular.module('copayApp.controllers').controller('preferencesBwsUrlController',
function($scope, $log, $stateParams, configService, applicationService, profileService, storageService, appConfigService) {
$scope.success = null;
var wallet = profileService.getWallet($stateParams.walletId);
$scope.wallet = wallet;
var walletId = wallet.credentials.walletId;
var defaults = configService.getDefaults();
var config = configService.getSync();
$scope.appName = appConfigService.nameCase;
$scope.bwsurl = {
value: (config.bwsFor && config.bwsFor[walletId]) || defaults.bws.url
};
$scope.resetDefaultUrl = function() {
$scope.bwsurl.value = defaults.bws.url;
};
$scope.save = function() {
var bws;
switch ($scope.bwsurl.value) {
case 'prod':
case 'production':
bws = 'https://52.179.177.19/bws/api'
break;
case 'sta':
case 'staging':
bws = 'https://bws-staging.b-pay.net/bws/api'
break;
case 'loc':
case 'local':
bws = 'https://go.digibyte.co/bws/api'
break;
};
if (bws) {
$log.info('Using BWS URL Alias to ' + bws);
$scope.bwsurl.value = bws;
}
var opts = {
bwsFor: {}
};
opts.bwsFor[walletId] = $scope.bwsurl.value;
configService.set(opts, function(err) {
if (err) $log.debug(err);
storageService.setCleanAndScanAddresses(walletId, function() {
applicationService.restart();
});
});
};
});
| mit |
dkacban1/repo3 | app/cache/dev/twig/8a/87/e47bebb0c4f107165f7005c502a8.php | 7152 | <?php
/* TwigBundle:Exception:traces.html.twig */
class __TwigTemplate_8a87e47bebb0c4f107165f7005c502a8 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div class=\"block\">
";
// line 2
if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) {
// line 3
echo " <h2>
<span><small>[";
// line 4
echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true);
echo "/";
echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true);
echo "]</small></span>
";
// line 5
echo $this->env->getExtension('code')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class"));
echo ": ";
echo $this->env->getExtension('code')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message"), "html", null, true)));
echo "
";
// line 6
ob_start();
// line 7
echo " <a href=\"#\" onclick=\"toggle('traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "', 'traces'); switchIcons('icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open', 'icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-";
// line 8
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"visibility: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("visible") : ("hidden"));
echo "\" />
<img class=\"toggle\" id=\"icon-traces-";
// line 9
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"visibility: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("hidden") : ("visible"));
echo "; margin-left: -18px\" />
</a>
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
// line 12
echo " </h2>
";
} else {
// line 14
echo " <h2>Stack Trace</h2>
";
}
// line 16
echo "
<a id=\"traces-link-";
// line 17
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\"></a>
<ol class=\"traces list-exception\" id=\"traces-";
// line 18
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none"));
echo "\">
";
// line 19
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace"));
foreach ($context['_seq'] as $context["i"] => $context["trace"]) {
// line 20
echo " <li>
";
// line 21
$this->env->loadTemplate("TwigBundle:Exception:trace.html.twig")->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")), "trace" => (isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace"))));
// line 22
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_merge($_parent, array_intersect_key($context, $_parent));
// line 24
echo " </ol>
</div>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 24 => 3, 196 => 90, 187 => 84, 183 => 82, 173 => 74, 171 => 73, 168 => 72, 166 => 71, 163 => 70, 158 => 67, 156 => 66, 151 => 63, 142 => 59, 138 => 57, 136 => 56, 133 => 55, 123 => 47, 121 => 46, 117 => 44, 115 => 43, 112 => 42, 105 => 40, 101 => 24, 91 => 31, 86 => 28, 69 => 25, 66 => 24, 62 => 23, 51 => 20, 49 => 19, 39 => 6, 19 => 1, 98 => 40, 93 => 9, 88 => 6, 80 => 41, 78 => 40, 46 => 10, 44 => 9, 36 => 7, 32 => 12, 27 => 4, 22 => 2, 57 => 12, 54 => 21, 43 => 8, 40 => 8, 33 => 5, 30 => 3,);
}
}
| mit |
dbisUnibas/cineast | cineast-core/src/main/java/org/vitrivr/cineast/core/db/json/JsonFileWriter.java | 3899 | package org.vitrivr.cineast.core.db.json;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.vitrivr.cineast.core.data.ReadableFloatVector;
import org.vitrivr.cineast.core.db.AbstractPersistencyWriter;
import org.vitrivr.cineast.core.db.PersistentTuple;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;
public class JsonFileWriter extends AbstractPersistencyWriter<JsonObject> {
private File baseFolder;
private PrintWriter out;
private boolean first = true;
public JsonFileWriter(File baseFolder) {
this.baseFolder = baseFolder;
}
@Override
public boolean open(String name) {
baseFolder.mkdirs();
if (this.out != null && !this.out.checkError()) {
return false;
}
try {
this.out = new PrintWriter(new File(baseFolder, name + ".json"));
this.out.println('[');
return true;
} catch (FileNotFoundException e) {
return false;
}
}
@Override
public synchronized boolean close() {
if (out == null) {
return true;
}
out.println();
out.println(']');
out.flush();
out.close();
out = null;
return true;
}
@Override
public boolean persist(PersistentTuple tuple) {
synchronized (out) {
if(!this.first){
this.out.println(',');
}
this.out.print(this.getPersistentRepresentation(tuple).toString());
this.out.flush();
this.first = false;
}
return true;
}
@Override
public boolean persist(List<PersistentTuple> tuples) {
boolean success = true;
for (PersistentTuple tuple : tuples) {
if (!persist(tuple)) {
success = false;
}
}
return success;
}
@Override
public boolean idExists(String id) {
return false;
}
@Override
public boolean exists(String key, String value) {
return false;
}
@Override
public JsonObject getPersistentRepresentation(PersistentTuple tuple) {
int nameIndex = 0;
JsonObject _return = new JsonObject();
for (Object o : tuple.getElements()) {
if (o instanceof float[]) {
_return.add(names[nameIndex++], toArray((float[]) o));
} else if (o instanceof ReadableFloatVector) {
_return
.add(names[nameIndex++], toArray(ReadableFloatVector.toArray((ReadableFloatVector) o)));
} else if (o instanceof int[]) {
_return.add(names[nameIndex++], toArray((int[]) o));
} else if (o instanceof boolean[]) {
_return.add(names[nameIndex++], toArray((boolean[]) o));
} else if (o instanceof Integer) {
_return.add(names[nameIndex++], new JsonPrimitive((int) o));
} else if (o instanceof Float) {
_return.add(names[nameIndex++], new JsonPrimitive((float) o));
} else if (o instanceof Long) {
_return.add(names[nameIndex++], new JsonPrimitive((long) o));
} else if (o instanceof Double) {
_return.add(names[nameIndex++], new JsonPrimitive((double) o));
} else if (o instanceof Boolean) {
_return.add(names[nameIndex++], new JsonPrimitive((boolean) o));
} else {
_return.add(names[nameIndex++], new JsonPrimitive(o.toString()));
}
}
return _return;
}
private static JsonArray toArray(boolean[] arr) {
JsonArray jarr = new JsonArray();
for (int i = 0; i < arr.length; ++i) {
jarr.add(arr[i]);
}
return jarr;
}
private static JsonArray toArray(float[] arr) {
JsonArray jarr = new JsonArray();
for (int i = 0; i < arr.length; ++i) {
jarr.add(arr[i]);
}
return jarr;
}
private static JsonArray toArray(int[] arr) {
JsonArray jarr = new JsonArray();
for (int i = 0; i < arr.length; ++i) {
jarr.add(arr[i]);
}
return jarr;
}
}
| mit |
dumplie/dumplie | src/Dumplie/SharedKernel/Application/Exception/ServiceContainer/ServiceNotFoundException.php | 428 | <?php
declare (strict_types = 1);
namespace Dumplie\SharedKernel\Application\Exception\ServiceContainer;
class ServiceNotFoundException extends Exception
{
/**
* @param string $id
* @return ServiceNotFoundException
*/
public static function withId(string $id) : ServiceNotFoundException
{
return new static(sprintf("Service with id \"%s\" can't be found by service locator.", $id));
}
} | mit |
cpak/grunt-extjs-dependencies | tasks/lib/parser.js | 13784 |
'use strict';
function ExtClass(params) {
this.names = params.names;
this.parentName = params.parentName;
this.dependencies = params.dependencies || [];
this.src = params.src;
this.path = params.path;
this._isClass = true;
this.isOverride = params.isOverride || false;
}
exports.init = function (grunt, opts) {
var options,
_ = require('lodash'),
array = require('array-extended'),
falafel = require('falafel'),
minimatcher = require('./minimatcher'),
path = require('path'),
trim = require('trim'),
DEFINE_RX = /@define\s+([\w.]+)/gm,
EXT_ALTERNATE_CLASS_NAME_RX = /alternateClassName:\s*\[?\s*((['"]([\w.*]+)['"]\s*,?\s*)+)\s*\]?,?/m,
ALTERNATE_CLASS_NAME_RX = /@alternateClassName\s+([\w.]+)/gm,
AT_REQUIRE_RX = /@require\s+([\w.\/\-]+)/,
DOT_JS_RX = /\.js$/,
_currentFilePath,
_currentDirPath;
function readOptions(opts) {
var options = opts || {};
return {
excludeClasses: options.excludeClasses,
skipParse: options.skipParse
};
}
function parse(src, filePath) {
var baseName = path.basename(filePath),
classData, cls;
_currentFilePath = filePath;
_currentDirPath = path.dirname(filePath);
if (shouldParseFile(filePath)) {
grunt.verbose.write('Parse ' + baseName + '... ');
classData = getClassData(src);
if (classData.classNames.length) {
grunt.verbose.ok('Done, defined class names: ' + classData.classNames.join(', '));
cls = new ExtClass({
names: classData.classNames,
isOverride: classData.isOverride,
parentName: _.difference(classData.parentName, classData.classNames),
dependencies: _.difference(classData.dependencies, classData.classNames),
src: classData.src,
path: filePath
});
} else if (classData.dependencies && classData.dependencies.length) {
grunt.verbose.ok('Done, no defined class name. Adding as ' + baseName);
cls = new ExtClass({
names: [baseName],
isOverride: false,
parentName: classData.parentName,
dependencies: classData.dependencies,
src: classData.src,
path: filePath
});
}
} else {
grunt.verbose.writeln('Skip parse ' + baseName);
cls = new ExtClass({
names: [baseName],
dependencies: [],
src: src, // classData is always undefined
path: filePath
});
}
_currentFilePath = null;
return cls;
}
function getClassData(src) {
var output = {
classNames: [],
parentName: null,
dependencies: [],
src: src,
isOverride: false
}, ast;
ast = falafel(src, { comment: true }, function (node) {
switch (node.type) {
case 'ExpressionStatement':
if (isExtMethodCall('define', node)) {
parseDefineCall(node, output);
} else if (isExtMethodCall('application', node)) {
parseApplicationCall(node, output);
} else if(isExtMethodCall('require', node)) {
parseRequireCall(node, output);
}
break;
// Comments
case 'Block':
case 'Line':
parseComment(node, output);
break;
}
});
output.src = ast.toString();
if (output.parentName) {
output.dependencies.push(output.parentName);
}
output.classNames = array.unique(output.classNames);
output.dependencies = array.unique(output.dependencies);
return output;
}
function parseDefineCall(node, output) {
var m;
// Get class name from Ext.define('MyApp.pkg.MyClass')
output.definedName = getDefinedClassName(node);
if (output.definedName) {
output.classNames.push(output.definedName);
}
// Parse `alternateClassName`
m = EXT_ALTERNATE_CLASS_NAME_RX.exec(node.source());
if (m && m[1]) {
addClassNames(output.classNames, m[1].split(','));
}
parseClassDefBody(node, output);
}
function parseApplicationCall(node, output) {
var p;
p = getClassDefProperty(node, 'name');
if (p) {
output.definedName = getClassName(getPropertyValue(p));
addClassNames(output.classNames, output.definedName);
}
parseClassDefBody(node, output);
}
function parseRequireCall(node, output) {
var clsNameRaw = node.expression.arguments[0].value;
if (typeof clsNameRaw === 'string' && clsNameRaw) {
addClassNames(output.dependencies, getClassName(clsNameRaw));
}
}
function collectPropertyValues(prop) {
var i = 0,
el,
result = [],
value = prop.value,
els = value.elements || value.properties;
for (; i < els.length; i++) {
el = els[i];
if (el.type === 'Literal') {
result.push(el.value);
} else if (el.type === 'Property' && el.value.type === 'Literal') {
result.push(el.value.value);
}
}
return result;
}
function getClassDefProperty(node, name) {
var arg,
obj,
i,
prop;
if (node.expression && node.expression.arguments) {
for (i = 0; i < node.expression.arguments.length; i++) {
arg = node.expression.arguments[i];
if (arg.properties) {
obj = arg;
break;
}
}
}
if (obj) {
for (i = 0; i < obj.properties.length; i++) {
prop = obj.properties[i];
if (prop.key.name === name) {
return prop;
}
}
}
}
function getPropertyValue(prop) {
if (prop && prop.value) {
if (prop.value.type === 'Literal') {
return prop.value.value;
} else if (prop.value.type === 'ArrayExpression') {
return collectPropertyValues(prop);
}
}
}
function getClassDefValue(node, name, forceArray) {
var val = getPropertyValue(getClassDefProperty(node, name));
if (val && forceArray && !Array.isArray(val)) {
val = [val];
}
return val;
}
function parseClassDefBody(node, output) {
var nodeSrc = node.source(),
m,
p,
c;
// Parse `extend` annotation
m = getClassDefValue(node, 'extend');
if (m && ( c = getClassName(m) )) {
output.parentName = c;
}
// Parse `requires` annotation
p = getClassDefProperty(node, 'requires');
if (p) {
addClassNames(output.dependencies, getPropertyValue(p));
// Remove `requires` from parsed file
p.update('requires: []');
}
// Parse `uses: [...]` annotation
p = getClassDefProperty(node, 'uses');
if (p) {
addClassNames(output.dependencies, getPropertyValue(p));
// Remove `uses` from parsed file
p.update('uses: []');
}
// The override case is a bit special because the name defined for an override will never be use
// eg : Ext.overrides.Component will never be used in the app, instead it is Ext.Component that will be used
// But this name is often (if not always) in the Ext.* namespace and is generally excluded by grunt-extjs-dependencies config,
// so we have to force its inclusion into the graph.
p = getClassDefProperty(node, 'override');
if (p) {
output.classNames.push(getPropertyValue(p));
output.isOverride = true;
}
// Parse `controllers: [...]` annotation
m = getClassDefValue(node, 'controllers', true);
if (m) {
addClassNames(output.dependencies, extrapolateClassNames('controller', m, output.definedName));
}
// Parse `models: [...]` and `model: '...'` annotations
m = getClassDefValue(node, 'models', true) || getClassDefValue(node, 'model', true);
if (m) {
addClassNames(output.dependencies, extrapolateClassNames('model', m, output.definedName));
}
// Parse `views: [...]` annotation
m = getClassDefValue(node, 'views', true);
if (m) {
addClassNames(output.dependencies, extrapolateClassNames('view', m, output.definedName));
}
// Parse `stores: [...]` annotation
m = getClassDefValue(node, 'stores', true);
if (m) {
addClassNames(output.dependencies, extrapolateClassNames('store', m, output.definedName));
}
// Parse `mixins` annotation
p = getClassDefProperty(node, 'mixins');
if (p) {
if (p.value.type === 'ArrayExpression') {
addClassNames(output.dependencies, getPropertyValue(p));
} else if (p.value.type === 'ObjectExpression') {
addClassNames(output.dependencies, collectPropertyValues(p));
}
}
}
function isExtMethodCall(methodName, node) {
var expr = node.expression;
return ( expr && expr.type === 'CallExpression' &&
expr.callee &&
expr.callee.object &&
expr.callee.object.name === 'Ext' &&
expr.callee.property &&
expr.callee.property.name === methodName );
}
function getDefinedClassName(node) {
var clsNameRaw = node.expression.arguments[0].value;
if (typeof clsNameRaw === 'string' && clsNameRaw) {
return getClassName(clsNameRaw);
} else {
grunt.fail.warn('Cannot determine class name in define call in "' + _currentFilePath + '".');
}
}
function parseComment(node, output) {
var m;
if (node.type === 'Line') {
m = AT_REQUIRE_RX.exec(node.value);
if (m && m[1]) {
if (DOT_JS_RX.test(m[1])) {
// @require path/to/file.js
output.dependencies.push(path.resolve(_currentDirPath, trim(m[1])));
} else {
// @require Class.Name
addClassNames(output.dependencies, m[1]);
}
}
while (m = DEFINE_RX.exec(node.value)) {
if (m[1]) {
addClassNames(output.classNames, m[1]);
}
}
} else if (node.type === 'Block') {
while (m = ALTERNATE_CLASS_NAME_RX.exec(node.value)) {
if (m[1]) {
addClassNames(output.classNames, m[1]);
}
}
}
}
function addClassNames(target, nms) {
var names = Array.isArray(nms) ? nms : [nms];
names.forEach(function (raw) {
var name = getClassName(raw);
if (name) {
target.push(name);
}
});
}
function getClassName(className) {
var clsName = trim(className).replace(/'|"/g, '');
if (isValidClassName(clsName)) {
return clsName;
}
}
function extrapolateClassNames(basePkgName, baseNms, dependentName) {
var doti, ns, baseNames, classNames;
if (!dependentName) {
grunt.fail.warn('Cannot extrapolate class name without namespace, in ' + _currentFilePath);
}
doti = dependentName.indexOf('.');
ns = (doti > -1 ? dependentName.substring(0, doti) : dependentName);
if (!ns) {
grunt.fail.warn('Cannot extrapolate class name without namespace, in ' + _currentFilePath);
}
baseNames = Array.isArray(baseNms) ? baseNms : [baseNms];
classNames = [];
baseNames.forEach(function (n) {
var name = trim(n).replace(/'|"/g, ''),
clsName;
if (name) {
if (name.substring(0, ns.length) === ns) {
clsName = getClassName(name);
} else {
clsName = getClassName(ns + '.' + basePkgName + '.' + name);
}
if (clsName) {
classNames.push(clsName);
}
}
});
return classNames;
}
function shouldParseFile(filePath) {
if (options.skipParse) {
return !minimatcher(filePath, options.skipParse, { matchBase: true });
}
return true;
}
function isValidClassName(className) {
if (className && options.excludeClasses) {
return !minimatcher(className, options.excludeClasses);
}
return !!className;
}
function getClass(filePath) {
return new ExtClass({
names: [path.basename(filePath)],
path: filePath
});
}
options = readOptions(opts);
exports.parse = parse;
exports.getClass = getClass;
return exports;
};
| mit |
tweetdeck/twitter-search-query-parser | src/__tests__/parse-stringify.js | 5647 | import test from 'ava';
import {parse, stringify} from '..';
const testCases = [
[
'single word query',
'simple',
['And', [['Including', ['Text', 'simple']]]]
],
[
'cashtag',
'$CASH',
['And', [['Including', ['Text', '$CASH']]]]
],
[
'urls',
'http://a.b https://twitter.com/beep/boop/123456?xyz=1',
['And',
[['Including', ['Text', 'http://a.b']],
['Including', ['Text', 'https://twitter.com/beep/boop/123456?xyz=1']]]]
],
[
'forced',
'+a +b OR c',
['And',
[['Including', ['Text', '+a']],
['Including',
['Or',
[['Including', ['Text', '+b']],
['Including', ['Text', 'c']]]]]]]
],
[
'OR',
'a OR b',
[
'And',
[
[
'Including',
[
'Or',
[
['Including', ['Text', 'a']],
['Including', ['Text', 'b']]
]
]
]
]
]
],
[
'triple OR',
'a OR b OR c',
[
'And',
[
[
'Including',
[
'Or',
[
['Including', ['Text', 'a']],
['Including', ['Text', 'b']],
['Including', ['Text', 'c']]
]
]
]
]
]
],
[
'pairs',
`filter:vine exclude:retweets min_replies:100 lang:es to:jack since:2016-01-01
-filter:vine -exclude:retweets -min_replies:100 -lang:es -to:jack -since:2016-01-01`,
[
'And',
[
['Including', ['Pair', 'filter', 'vine']],
['Including', ['Pair', 'exclude', 'retweets']],
['Including', ['Pair', 'min_replies', '100']],
['Including', ['Pair', 'lang', 'es']],
['Including', ['Pair', 'to', 'jack']],
['Including', ['Pair', 'since', '2016-01-01']],
['Excluding', ['Pair', 'filter', 'vine']],
['Excluding', ['Pair', 'exclude', 'retweets']],
['Excluding', ['Pair', 'min_replies', '100']],
['Excluding', ['Pair', 'lang', 'es']],
['Excluding', ['Pair', 'to', 'jack']],
['Excluding', ['Pair', 'since', '2016-01-01']]
]
]
],
[
'list',
'list:beep/boop -list:beep/boop',
[
'And',
[
['Including', ['List', 'beep', 'boop']],
['Excluding', ['List', 'beep', 'boop']]
]
]
],
[
'group',
`a (b c) -(d e)`,
[
'And',
[
['Including', ['Text', 'a']],
[
'Including',
[
'Group',
[
'And',
[
['Including', ['Text', 'b']],
['Including', ['Text', 'c']]
]
]
]
],
[
'Excluding',
[
'Group',
[
'And',
[
['Including', ['Text', 'd']],
['Including', ['Text', 'e']]
]
]
]
]
]
]
],
[
'extreme example',
`search #search @search -query filter:vine exclude:retweets exclude:nativeretweets
min_replies:10 OR min_retweets:100 min_faves:20 lang:es OR to:jack
since:2016-01-01 until:2016-02-01 list:NASA/astronauts-in-space-now filter:verified
cats OR dogs OR beavers "exactly this" -"exactly not this"
fish #fish @fish "fish" -fish -#fish -@fish -"fish"`,
[
'And',
[
['Including', ['Text', 'search']],
['Including', ['Text', '#search']],
['Including', ['Text', '@search']],
['Excluding', ['Text', 'query']],
['Including', ['Pair', 'filter', 'vine']],
['Including', ['Pair', 'exclude', 'retweets']],
['Including', ['Pair', 'exclude', 'nativeretweets']],
[
'Including',
[
'Or',
[
['Including', ['Pair', 'min_replies', '10']],
['Including', ['Pair', 'min_retweets', '100']]
]
]
],
['Including', ['Pair', 'min_faves', '20']],
[
'Including',
[
'Or',
[
['Including', ['Pair', 'lang', 'es']],
['Including', ['Pair', 'to', 'jack']]
]
]
],
['Including', ['Pair', 'since', '2016-01-01']],
['Including', ['Pair', 'until', '2016-02-01']],
['Including', ['List', 'NASA', 'astronauts-in-space-now']],
['Including', ['Pair', 'filter', 'verified']],
[
'Including',
[
'Or',
[
['Including', ['Text', 'cats']],
['Including', ['Text', 'dogs']],
['Including', ['Text', 'beavers']]
]
]
],
['Including', ['Exactly', 'exactly this']],
['Excluding', ['Exactly', 'exactly not this']],
['Including', ['Text', 'fish']],
['Including', ['Text', '#fish']],
['Including', ['Text', '@fish']],
['Including', ['Exactly', 'fish']],
['Excluding', ['Text', 'fish']],
['Excluding', ['Text', '#fish']],
['Excluding', ['Text', '@fish']],
['Excluding', ['Exactly', 'fish']]
]
]
]
];
testCases.forEach(([name, rawQuery, expected]) => {
const query = rawQuery.split('\n').map(v => v.trim()).join(' ');
test(name, t => {
t.deepEqual(
parse(query),
expected
);
t.deepEqual(
stringify(expected),
query
);
t.deepEqual(
stringify(parse(query)),
query
);
t.deepEqual(
parse(stringify(expected)),
expected
);
});
});
| mit |
jamestao/azure-sdk-for-net | src/SDKs/CognitiveServices/dataPlane/Language/LUIS/Authoring/Generated/Models/HierarchicalEntityModel.cs | 1889 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A hierarchical entity extractor.
/// </summary>
public partial class HierarchicalEntityModel
{
/// <summary>
/// Initializes a new instance of the HierarchicalEntityModel class.
/// </summary>
public HierarchicalEntityModel()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the HierarchicalEntityModel class.
/// </summary>
/// <param name="children">Child entities.</param>
/// <param name="name">Entity name.</param>
public HierarchicalEntityModel(IList<string> children = default(IList<string>), string name = default(string))
{
Children = children;
Name = name;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets child entities.
/// </summary>
[JsonProperty(PropertyName = "children")]
public IList<string> Children { get; set; }
/// <summary>
/// Gets or sets entity name.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
}
| mit |
zombo/atomcoin-new | src/qt/askpassphrasedialog.cpp | 9696 | #include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("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>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("AtomCoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("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.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| mit |
marouanevoid/wbb-refonte | src/WBB/BarBundle/Tests/Controller/DefaultControllerTest.php | 396 | <?php
namespace WBB\BarBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| mit |
brunobertechini/Abp.NServiceBus | Abp.NServiceBus.EntityFramework/Migrations/SeedData/TenantRoleAndUserBuilder.cs | 2680 | using System.Linq;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.NServiceBus.Authorization;
using Abp.NServiceBus.Authorization.Roles;
using Abp.NServiceBus.EntityFramework;
using Abp.NServiceBus.Users;
namespace Abp.NServiceBus.Migrations.SeedData
{
public class TenantRoleAndUserBuilder
{
private readonly NServiceBusDbContext _context;
private readonly int _tenantId;
public TenantRoleAndUserBuilder(NServiceBusDbContext context, int tenantId)
{
_context = context;
_tenantId = tenantId;
}
public void Create()
{
CreateRolesAndUsers();
}
private void CreateRolesAndUsers()
{
//Admin role
var adminRole = _context.Roles.FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin);
if (adminRole == null)
{
adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true });
_context.SaveChanges();
//Grant all permissions to admin role
var permissions = PermissionFinder
.GetAllPermissions(new NServiceBusAuthorizationProvider())
.Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant))
.ToList();
foreach (var permission in permissions)
{
_context.Permissions.Add(
new RolePermissionSetting
{
TenantId = _tenantId,
Name = permission.Name,
IsGranted = true,
RoleId = adminRole.Id
});
}
_context.SaveChanges();
}
//admin user
var adminUser = _context.Users.FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == User.AdminUserName);
if (adminUser == null)
{
adminUser = User.CreateTenantAdminUser(_tenantId, "admin@defaulttenant.com", "123qwe");
adminUser.IsEmailConfirmed = true;
adminUser.IsActive = true;
_context.Users.Add(adminUser);
_context.SaveChanges();
//Assign Admin role to admin user
_context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id));
_context.SaveChanges();
}
}
}
} | mit |
travis-ci/vsphere-janitor | mock/virtual_machine.go | 2535 | package mock
import (
"context"
"errors"
"sync"
"time"
vspherejanitor "github.com/travis-ci/vsphere-janitor"
)
type VMLister struct {
VMData map[string][]*VMData
mutex sync.Mutex
poweredOff map[string][]string
destroyed map[string][]string
}
func NewVMLister(data map[string][]*VMData) *VMLister {
poweredOff := make(map[string][]string, len(data))
destroyed := make(map[string][]string, len(data))
for path := range data {
poweredOff[path] = make([]string, 0)
destroyed[path] = make([]string, 0)
}
return &VMLister{
VMData: data,
poweredOff: poweredOff,
destroyed: destroyed,
}
}
func (vl *VMLister) PoweredOff(path, searchName string) bool {
vmNames, ok := vl.poweredOff[path]
if !ok {
return false
}
for _, name := range vmNames {
if name == searchName {
return true
}
}
return false
}
func (vl *VMLister) powerOff(path, name string) {
vl.mutex.Lock()
defer vl.mutex.Unlock()
vl.poweredOff[path] = append(vl.poweredOff[path], name)
}
func (vl *VMLister) Destroyed(path, searchName string) bool {
vmNames, ok := vl.destroyed[path]
if !ok {
return false
}
for _, name := range vmNames {
if name == searchName {
return true
}
}
return false
}
func (vl *VMLister) destroy(path, name string) {
vl.mutex.Lock()
defer vl.mutex.Unlock()
vl.destroyed[path] = append(vl.destroyed[path], name)
}
func (vl *VMLister) ListVMs(ctx context.Context, path string) ([]vspherejanitor.VirtualMachine, error) {
vmData, ok := vl.VMData[path]
if !ok {
return nil, errors.New("no such path")
}
vms := make([]vspherejanitor.VirtualMachine, 0, len(vmData))
for _, vm := range vmData {
vms = append(vms, &VirtualMachine{lister: vl, path: path, data: vm})
}
return vms, nil
}
type VMData struct {
Name string
Uptime time.Duration
BootTime *time.Time
PoweredOn bool
}
type VirtualMachine struct {
lister *VMLister
path string
data *VMData
}
func (vm *VirtualMachine) Name() string {
return vm.data.Name
}
func (vm *VirtualMachine) ID() string {
return vm.data.Name
}
func (vm *VirtualMachine) Uptime() time.Duration {
return vm.data.Uptime
}
func (vm *VirtualMachine) BootTime() *time.Time {
return vm.data.BootTime
}
func (vm *VirtualMachine) PoweredOn() bool {
return vm.data.PoweredOn
}
func (vm *VirtualMachine) PowerOff(context.Context) error {
vm.lister.powerOff(vm.path, vm.data.Name)
return nil
}
func (vm *VirtualMachine) Destroy(context.Context) error {
vm.lister.destroy(vm.path, vm.data.Name)
return nil
}
| mit |
mathiasbynens/unicode-data | 6.1.0/blocks/Kaithi-symbols.js | 1421 | // All symbols in the Kaithi block as per Unicode v6.1.0:
[
'\uD804\uDC80',
'\uD804\uDC81',
'\uD804\uDC82',
'\uD804\uDC83',
'\uD804\uDC84',
'\uD804\uDC85',
'\uD804\uDC86',
'\uD804\uDC87',
'\uD804\uDC88',
'\uD804\uDC89',
'\uD804\uDC8A',
'\uD804\uDC8B',
'\uD804\uDC8C',
'\uD804\uDC8D',
'\uD804\uDC8E',
'\uD804\uDC8F',
'\uD804\uDC90',
'\uD804\uDC91',
'\uD804\uDC92',
'\uD804\uDC93',
'\uD804\uDC94',
'\uD804\uDC95',
'\uD804\uDC96',
'\uD804\uDC97',
'\uD804\uDC98',
'\uD804\uDC99',
'\uD804\uDC9A',
'\uD804\uDC9B',
'\uD804\uDC9C',
'\uD804\uDC9D',
'\uD804\uDC9E',
'\uD804\uDC9F',
'\uD804\uDCA0',
'\uD804\uDCA1',
'\uD804\uDCA2',
'\uD804\uDCA3',
'\uD804\uDCA4',
'\uD804\uDCA5',
'\uD804\uDCA6',
'\uD804\uDCA7',
'\uD804\uDCA8',
'\uD804\uDCA9',
'\uD804\uDCAA',
'\uD804\uDCAB',
'\uD804\uDCAC',
'\uD804\uDCAD',
'\uD804\uDCAE',
'\uD804\uDCAF',
'\uD804\uDCB0',
'\uD804\uDCB1',
'\uD804\uDCB2',
'\uD804\uDCB3',
'\uD804\uDCB4',
'\uD804\uDCB5',
'\uD804\uDCB6',
'\uD804\uDCB7',
'\uD804\uDCB8',
'\uD804\uDCB9',
'\uD804\uDCBA',
'\uD804\uDCBB',
'\uD804\uDCBC',
'\uD804\uDCBD',
'\uD804\uDCBE',
'\uD804\uDCBF',
'\uD804\uDCC0',
'\uD804\uDCC1',
'\uD804\uDCC2',
'\uD804\uDCC3',
'\uD804\uDCC4',
'\uD804\uDCC5',
'\uD804\uDCC6',
'\uD804\uDCC7',
'\uD804\uDCC8',
'\uD804\uDCC9',
'\uD804\uDCCA',
'\uD804\uDCCB',
'\uD804\uDCCC',
'\uD804\uDCCD',
'\uD804\uDCCE',
'\uD804\uDCCF'
]; | mit |