code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/env python3 from heapq import heapify, heappop, heappush with open('NUOC.INP') as f: m, n = map(int, f.readline().split()) height = [[int(i) for i in line.split()] for line in f] queue = ([(h, 0, i) for i, h in enumerate(height[0])] + [(h, m - 1, i) for i, h in enumerate(height[-1])] + [(height[i][0], i, 0) for i in range(m)] + [(height[i][-1], i, n - 1) for i in range(m)]) heapify(queue) visited = ([[True] * n] + [[True] + [False] * (n - 2) + [True] for _ in range(m - 2)] + [[True] * n]) result = 0 while queue: h, i, j = heappop(queue) for x, y in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1): if 0 <= x < m and 0 <= y < n and not visited[x][y]: result += max(0, h - height[x][y]) heappush(queue, (max(height[x][y], h), x, y)) visited[x][y] = True with open('NUOC.OUT', 'w') as f: print(result, file=f)
McSinyx/hsg
others/other/nuoc.py
Python
gpl-3.0
941
#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <string.h> #define BUFFER_SIZE 1024 int main() { int socketfd; int port = 2047; struct sockaddr_in server_in; struct sockaddr_in client_in; int client_in_length = sizeof(client_in); char buffer[BUFFER_SIZE]; //Create a socket socketfd = socket(AF_INET, SOCK_DGRAM, 0); if (socketfd < 0) { perror("Creating a socket failed!"); return -1; } // Set the server address, by defaulting server_in to 0 // then setting it to the port, before binding memset((char *) &server_in, 0, sizeof(server_in)); server_in.sin_family = AF_INET; //IPV4 server_in.sin_port = htons(port); server_in.sin_addr.s_addr = htons(INADDR_ANY); //Any interface //Bind, Note the second parameter needs to be a sockaddr if (bind(socketfd, (struct sockaddr *) &server_in, sizeof(server_in)) == -1) { perror("Binding Failed, ec set to errno!"); return -2; } //Keep listening, for stuff while (true) { memset(buffer, 0, sizeof(buffer)); if (recvfrom(socketfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &client_in, (socklen_t *)&client_in_length) == -1) { perror("Recieving from client failed"); return -3; } if (sendto(socketfd, "OK\n", 3, 0, (struct sockaddr *) &client_in, client_in_length) == -1) perror("Sending to client failed"); //Make sure its not empty lines printf("Message: %s", buffer); } printf("Hello to the world of tomrow"); return 0; }
dashee/dashee
playground/src/udpserver.cpp
C++
gpl-3.0
1,733
/* ** ################################################################### ** This code is generated by the Device Initialization Tool. ** It is overwritten during code generation. ** USER MODIFICATION ARE NOT PRESERVED IN THIS FILE. ** ** Project : s08qe128 ** Processor : MCF51QE128CLK ** Version : Bean 01.001, Driver 01.03, CPU db: 3.00.000 ** Datasheet : MCF51QE128RM Rev. 1.0 Draft F ** Date/Time : 06/03/2009, 10:04 a.m. ** Abstract : ** This module contains device initialization code ** for selected on-chip peripherals. ** Contents : ** Function "MCU_init" initializes selected peripherals ** ** (c) Copyright UNIS, spol. s r.o. 1997-2006 ** UNIS, spol s r.o. ** Jundrovska 33 ** 624 00 Brno ** Czech Republic ** http : www.processorexpert.com ** mail : [email protected] ** ################################################################### */ #include "derivative.h" #define MCU_XTAL_CLK 8192000 #define MCU_REF_CLK_DIVIDER 256 #define MCU_REF_CLK (MCU_XTAL_CLK/MCU_REF_CLK_DIVIDER) #define MCU_FLL_OUT (MCU_REF_CLK*1536) #define MCU_BUSCLK (MCU_FLL_OUT/2) #define RTI_TICK 1 /* Real Time Interrupt [ms] */ #define RTI_MS(x) (x/RTI_TICK) /* Tick Base to ms */ #define reset_now() asm( "HALT" ) void mcu_init( unsigned char tick_ms ); unsigned long get_ts( void );
vortextech/RKH
demo/libbsp/platform/cfv1/DEMOQUE128/mcu/mcu.h
C
gpl-3.0
1,414
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Eth rpc implementation. use std::thread; use std::time::{Instant, Duration}; use std::sync::Arc; use rlp::{self, UntrustedRlp}; use time::get_time; use bigint::prelude::U256; use bigint::hash::{H64, H160, H256}; use util::Address; use parking_lot::Mutex; use ethash::SeedHashCompute; use ethcore::account_provider::{AccountProvider, DappId}; use ethcore::block::IsBlock; use ethcore::client::{MiningBlockChainClient, BlockId, TransactionId, UncleId}; use ethcore::ethereum::Ethash; use ethcore::filter::Filter as EthcoreFilter; use ethcore::header::{Header as BlockHeader, BlockNumber as EthBlockNumber}; use ethcore::log_entry::LogEntry; use ethcore::miner::{MinerService, ExternalMinerService}; use ethcore::transaction::SignedTransaction; use ethcore::snapshot::SnapshotService; use ethsync::{SyncProvider}; use jsonrpc_core::{BoxFuture, Result}; use jsonrpc_core::futures::future; use jsonrpc_macros::Trailing; use v1::helpers::{errors, limit_logs, fake_sign}; use v1::helpers::dispatch::{FullDispatcher, default_gas_price}; use v1::helpers::block_import::is_major_importing; use v1::helpers::accounts::unwrap_provider; use v1::traits::Eth; use v1::types::{ RichBlock, Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo, Transaction, CallRequest, Index, Filter, Log, Receipt, Work, H64 as RpcH64, H256 as RpcH256, H160 as RpcH160, U256 as RpcU256, }; use v1::metadata::Metadata; const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed"; /// Eth RPC options pub struct EthClientOptions { /// Return nonce from transaction queue when pending block not available. pub pending_nonce_from_queue: bool, /// Returns receipt from pending blocks pub allow_pending_receipt_query: bool, /// Send additional block number when asking for work pub send_block_number_in_get_work: bool, } impl EthClientOptions { /// Creates new default `EthClientOptions` and allows alterations /// by provided function. pub fn with<F: Fn(&mut Self)>(fun: F) -> Self { let mut options = Self::default(); fun(&mut options); options } } impl Default for EthClientOptions { fn default() -> Self { EthClientOptions { pending_nonce_from_queue: false, allow_pending_receipt_query: true, send_block_number_in_get_work: true, } } } /// Eth rpc implementation. pub struct EthClient<C, SN: ?Sized, S: ?Sized, M, EM> where C: MiningBlockChainClient, SN: SnapshotService, S: SyncProvider, M: MinerService, EM: ExternalMinerService { client: Arc<C>, snapshot: Arc<SN>, sync: Arc<S>, accounts: Option<Arc<AccountProvider>>, miner: Arc<M>, external_miner: Arc<EM>, seed_compute: Mutex<SeedHashCompute>, options: EthClientOptions, eip86_transition: u64, } impl<C, SN: ?Sized, S: ?Sized, M, EM> EthClient<C, SN, S, M, EM> where C: MiningBlockChainClient, SN: SnapshotService, S: SyncProvider, M: MinerService, EM: ExternalMinerService { /// Creates new EthClient. pub fn new( client: &Arc<C>, snapshot: &Arc<SN>, sync: &Arc<S>, accounts: &Option<Arc<AccountProvider>>, miner: &Arc<M>, em: &Arc<EM>, options: EthClientOptions ) -> Self { EthClient { client: client.clone(), snapshot: snapshot.clone(), sync: sync.clone(), miner: miner.clone(), accounts: accounts.clone(), external_miner: em.clone(), seed_compute: Mutex::new(SeedHashCompute::new()), options: options, eip86_transition: client.eip86_transition(), } } /// Attempt to get the `Arc<AccountProvider>`, errors if provider was not /// set. fn account_provider(&self) -> Result<Arc<AccountProvider>> { unwrap_provider(&self.accounts) } fn block(&self, id: BlockId, include_txs: bool) -> Result<Option<RichBlock>> { let client = &self.client; match (client.block(id.clone()), client.block_total_difficulty(id)) { (Some(block), Some(total_difficulty)) => { let view = block.header_view(); Ok(Some(RichBlock { inner: Block { hash: Some(view.hash().into()), size: Some(block.rlp().as_raw().len().into()), parent_hash: view.parent_hash().into(), uncles_hash: view.uncles_hash().into(), author: view.author().into(), miner: view.author().into(), state_root: view.state_root().into(), transactions_root: view.transactions_root().into(), receipts_root: view.receipts_root().into(), number: Some(view.number().into()), gas_used: view.gas_used().into(), gas_limit: view.gas_limit().into(), logs_bloom: view.log_bloom().into(), timestamp: view.timestamp().into(), difficulty: view.difficulty().into(), total_difficulty: Some(total_difficulty.into()), seal_fields: view.seal().into_iter().map(Into::into).collect(), uncles: block.uncle_hashes().into_iter().map(Into::into).collect(), transactions: match include_txs { true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t, self.eip86_transition)).collect()), false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()), }, extra_data: Bytes::new(view.extra_data()), }, extra_info: client.block_extra_info(id.clone()).expect(EXTRA_INFO_PROOF), })) }, _ => Ok(None) } } fn transaction(&self, id: TransactionId) -> Result<Option<Transaction>> { match self.client.transaction(id) { Some(t) => Ok(Some(Transaction::from_localized(t, self.eip86_transition))), None => Ok(None), } } fn uncle(&self, id: UncleId) -> Result<Option<RichBlock>> { let client = &self.client; let uncle: BlockHeader = match client.uncle(id) { Some(hdr) => hdr.decode(), None => { return Ok(None); } }; let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(uncle.parent_hash().clone())) { Some(difficulty) => difficulty, None => { return Ok(None); } }; let size = client.block(BlockId::Hash(uncle.hash())) .map(|block| block.into_inner().len()) .map(U256::from) .map(Into::into); let block = RichBlock { inner: Block { hash: Some(uncle.hash().into()), size: size, parent_hash: uncle.parent_hash().clone().into(), uncles_hash: uncle.uncles_hash().clone().into(), author: uncle.author().clone().into(), miner: uncle.author().clone().into(), state_root: uncle.state_root().clone().into(), transactions_root: uncle.transactions_root().clone().into(), number: Some(uncle.number().into()), gas_used: uncle.gas_used().clone().into(), gas_limit: uncle.gas_limit().clone().into(), logs_bloom: uncle.log_bloom().clone().into(), timestamp: uncle.timestamp().into(), difficulty: uncle.difficulty().clone().into(), total_difficulty: Some((uncle.difficulty().clone() + parent_difficulty).into()), receipts_root: uncle.receipts_root().clone().into(), extra_data: uncle.extra_data().clone().into(), seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(), uncles: vec![], transactions: BlockTransactions::Hashes(vec![]), }, extra_info: client.uncle_extra_info(id).expect(EXTRA_INFO_PROOF), }; Ok(Some(block)) } fn dapp_accounts(&self, dapp: DappId) -> Result<Vec<H160>> { let store = self.account_provider()?; store .note_dapp_used(dapp.clone()) .and_then(|_| store.dapp_addresses(dapp)) .map_err(|e| errors::account("Could not fetch accounts.", e)) } } pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFilter) -> Vec<Log> where M: MinerService { let receipts = miner.pending_receipts(best_block); let pending_logs = receipts.into_iter() .flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>()) .collect::<Vec<(H256, LogEntry)>>(); let result = pending_logs.into_iter() .filter(|pair| filter.matches(&pair.1)) .map(|pair| { let mut log = Log::from(pair.1); log.transaction_hash = Some(pair.0.into()); log }) .collect(); result } fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: MiningBlockChainClient { use ethcore::block_status::BlockStatus; match client.block_status(number.into()) { BlockStatus::InChain => Ok(()), BlockStatus::Pending => Ok(()), _ => Err(errors::unknown_block()), } } const MAX_QUEUE_SIZE_TO_MINE_ON: usize = 4; // because uncles go back 6. impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where C: MiningBlockChainClient + 'static, SN: SnapshotService + 'static, S: SyncProvider + 'static, M: MinerService + 'static, EM: ExternalMinerService + 'static, { type Metadata = Metadata; fn protocol_version(&self) -> Result<String> { let version = self.sync.status().protocol_version.to_owned(); Ok(format!("{}", version)) } fn syncing(&self) -> Result<SyncStatus> { use ethcore::snapshot::RestorationStatus; let status = self.sync.status(); let client = &self.client; let snapshot_status = self.snapshot.status(); let (warping, warp_chunks_amount, warp_chunks_processed) = match snapshot_status { RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } => (true, Some(block_chunks + state_chunks), Some(block_chunks_done + state_chunks_done)), _ => (false, None, None), }; if warping || is_major_importing(Some(status.state), client.queue_info()) { let chain_info = client.chain_info(); let current_block = U256::from(chain_info.best_block_number); let highest_block = U256::from(status.highest_block_number.unwrap_or(status.start_block_number)); let info = SyncInfo { starting_block: status.start_block_number.into(), current_block: current_block.into(), highest_block: highest_block.into(), warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into), warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into), }; Ok(SyncStatus::Info(info)) } else { Ok(SyncStatus::None) } } fn author(&self, meta: Metadata) -> Result<RpcH160> { let dapp = meta.dapp_id(); let mut miner = self.miner.author(); if miner == 0.into() { miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default(); } Ok(RpcH160::from(miner)) } fn is_mining(&self) -> Result<bool> { Ok(self.miner.is_currently_sealing()) } fn hashrate(&self) -> Result<RpcU256> { Ok(RpcU256::from(self.external_miner.hashrate())) } fn gas_price(&self) -> Result<RpcU256> { Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner))) } fn accounts(&self, meta: Metadata) -> Result<Vec<RpcH160>> { let dapp = meta.dapp_id(); let accounts = self.dapp_accounts(dapp.into())?; Ok(accounts.into_iter().map(Into::into).collect()) } fn block_number(&self) -> Result<RpcU256> { Ok(RpcU256::from(self.client.chain_info().best_block_number)) } fn balance(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> { let address = address.into(); let id = num.unwrap_or_default(); try_bf!(check_known(&*self.client, id.clone())); let res = match self.client.balance(&address, id.into()) { Some(balance) => Ok(balance.into()), None => Err(errors::state_pruned()), }; Box::new(future::done(res)) } fn storage_at(&self, address: RpcH160, pos: RpcU256, num: Trailing<BlockNumber>) -> BoxFuture<RpcH256> { let address: Address = RpcH160::into(address); let position: U256 = RpcU256::into(pos); let id = num.unwrap_or_default(); try_bf!(check_known(&*self.client, id.clone())); let res = match self.client.storage_at(&address, &H256::from(position), id.into()) { Some(s) => Ok(s.into()), None => Err(errors::state_pruned()), }; Box::new(future::done(res)) } fn transaction_count(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> { let address: Address = RpcH160::into(address); let res = match num.unwrap_or_default() { BlockNumber::Pending if self.options.pending_nonce_from_queue => { let nonce = self.miner.last_nonce(&address) .map(|n| n + 1.into()) .or_else(|| self.client.nonce(&address, BlockNumber::Pending.into())); match nonce { Some(nonce) => Ok(nonce.into()), None => Err(errors::database("latest nonce missing")) } } id => { try_bf!(check_known(&*self.client, id.clone())); match self.client.nonce(&address, id.into()) { Some(nonce) => Ok(nonce.into()), None => Err(errors::state_pruned()), } } }; Box::new(future::done(res)) } fn block_transaction_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> { Box::new(future::ok(self.client.block(BlockId::Hash(hash.into())) .map(|block| block.transactions_count().into()))) } fn block_transaction_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> { Box::new(future::ok(match num { BlockNumber::Pending => Some( self.miner.status().transactions_in_pending_block.into() ), _ => self.client.block(num.into()) .map(|block| block.transactions_count().into()) })) } fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> { Box::new(future::ok(self.client.block(BlockId::Hash(hash.into())) .map(|block| block.uncles_count().into()))) } fn block_uncles_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> { Box::new(future::ok(match num { BlockNumber::Pending => Some(0.into()), _ => self.client.block(num.into()) .map(|block| block.uncles_count().into() ), })) } fn code_at(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> { let address: Address = RpcH160::into(address); let id = num.unwrap_or_default(); try_bf!(check_known(&*self.client, id.clone())); let res = match self.client.code(&address, id.into()) { Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)), None => Err(errors::state_pruned()), }; Box::new(future::done(res)) } fn block_by_hash(&self, hash: RpcH256, include_txs: bool) -> BoxFuture<Option<RichBlock>> { Box::new(future::done(self.block(BlockId::Hash(hash.into()), include_txs))) } fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> { Box::new(future::done(self.block(num.into(), include_txs))) } fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> { let hash: H256 = hash.into(); let block_number = self.client.chain_info().best_block_number; let tx = try_bf!(self.transaction(TransactionId::Hash(hash))).or_else(|| { self.miner.transaction(block_number, &hash) .map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)) }); Box::new(future::ok(tx)) } fn transaction_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<Transaction>> { Box::new(future::done( self.transaction(TransactionId::Location(BlockId::Hash(hash.into()), index.value())) )) } fn transaction_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<Transaction>> { Box::new(future::done( self.transaction(TransactionId::Location(num.into(), index.value())) )) } fn transaction_receipt(&self, hash: RpcH256) -> BoxFuture<Option<Receipt>> { let best_block = self.client.chain_info().best_block_number; let hash: H256 = hash.into(); match (self.miner.pending_receipt(best_block, &hash), self.options.allow_pending_receipt_query) { (Some(receipt), true) => Box::new(future::ok(Some(receipt.into()))), _ => { let receipt = self.client.transaction_receipt(TransactionId::Hash(hash)); Box::new(future::ok(receipt.map(Into::into))) } } } fn uncle_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<RichBlock>> { Box::new(future::done(self.uncle(UncleId { block: BlockId::Hash(hash.into()), position: index.value() }))) } fn uncle_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<RichBlock>> { Box::new(future::done(self.uncle(UncleId { block: num.into(), position: index.value() }))) } fn compilers(&self) -> Result<Vec<String>> { Err(errors::deprecated("Compilation functionality is deprecated.".to_string())) } fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> { let include_pending = filter.to_block == Some(BlockNumber::Pending); let filter: EthcoreFilter = filter.into(); let mut logs = self.client.logs(filter.clone()) .into_iter() .map(From::from) .collect::<Vec<Log>>(); if include_pending { let best_block = self.client.chain_info().best_block_number; let pending = pending_logs(&*self.miner, best_block, &filter); logs.extend(pending); } let logs = limit_logs(logs, filter.limit); Box::new(future::ok(logs)) } fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work> { if !self.miner.can_produce_work_package() { warn!(target: "miner", "Cannot give work package - engine seals internally."); return Err(errors::no_work_required()) } let no_new_work_timeout = no_new_work_timeout.unwrap_or_default(); // check if we're still syncing and return empty strings in that case { //TODO: check if initial sync is complete here //let sync = self.sync; if /*sync.status().state != SyncState::Idle ||*/ self.client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON { trace!(target: "miner", "Syncing. Cannot give any work."); return Err(errors::no_work()); } // Otherwise spin until our submitted block has been included. let timeout = Instant::now() + Duration::from_millis(1000); while Instant::now() < timeout && self.client.queue_info().total_queue_size() > 0 { thread::sleep(Duration::from_millis(1)); } } if self.miner.author().is_zero() { warn!(target: "miner", "Cannot give work package - no author is configured. Use --author to configure!"); return Err(errors::no_author()) } self.miner.map_sealing_work(&*self.client, |b| { let pow_hash = b.hash(); let target = Ethash::difficulty_to_boundary(b.block().header().difficulty()); let seed_hash = self.seed_compute.lock().hash_block_number(b.block().header().number()); if no_new_work_timeout > 0 && b.block().header().timestamp() + no_new_work_timeout < get_time().sec as u64 { Err(errors::no_new_work()) } else if self.options.send_block_number_in_get_work { let block_number = b.block().header().number(); Ok(Work { pow_hash: pow_hash.into(), seed_hash: seed_hash.into(), target: target.into(), number: Some(block_number), }) } else { Ok(Work { pow_hash: pow_hash.into(), seed_hash: seed_hash.into(), target: target.into(), number: None }) } }).unwrap_or(Err(errors::internal("No work found.", ""))) } fn submit_work(&self, nonce: RpcH64, pow_hash: RpcH256, mix_hash: RpcH256) -> Result<bool> { if !self.miner.can_produce_work_package() { warn!(target: "miner", "Cannot submit work - engine seals internally."); return Err(errors::no_work_required()) } let nonce: H64 = nonce.into(); let pow_hash: H256 = pow_hash.into(); let mix_hash: H256 = mix_hash.into(); trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash); let seal = vec![rlp::encode(&mix_hash).into_vec(), rlp::encode(&nonce).into_vec()]; Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok()) } fn submit_hashrate(&self, rate: RpcU256, id: RpcH256) -> Result<bool> { self.external_miner.submit_hashrate(rate.into(), id.into()); Ok(true) } fn send_raw_transaction(&self, raw: Bytes) -> Result<RpcH256> { UntrustedRlp::new(&raw.into_vec()).as_val() .map_err(errors::rlp) .and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction)) .and_then(|signed_transaction| { FullDispatcher::dispatch_transaction( &*self.client, &*self.miner, signed_transaction.into(), ) }) .map(Into::into) } fn submit_transaction(&self, raw: Bytes) -> Result<RpcH256> { self.send_raw_transaction(raw) } fn call(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> { let request = CallRequest::into(request); let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp())); let num = num.unwrap_or_default(); let result = self.client.call(&signed, Default::default(), num.into()); Box::new(future::done(result .map(|b| b.output.into()) .map_err(errors::call) )) } fn estimate_gas(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> { let request = CallRequest::into(request); let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp())); Box::new(future::done(self.client.estimate_gas(&signed, num.unwrap_or_default().into()) .map(Into::into) .map_err(errors::call) )) } fn compile_lll(&self, _: String) -> Result<Bytes> { Err(errors::deprecated("Compilation of LLL via RPC is deprecated".to_string())) } fn compile_serpent(&self, _: String) -> Result<Bytes> { Err(errors::deprecated("Compilation of Serpent via RPC is deprecated".to_string())) } fn compile_solidity(&self, _: String) -> Result<Bytes> { Err(errors::deprecated("Compilation of Solidity via RPC is deprecated".to_string())) } }
destenson/ethcore--parity
rpc/src/v1/impls/eth.rs
Rust
gpl-3.0
22,169
/********************************************************************** ** smepowercad ** Copyright (C) 2015 Smart Micro Engineering GmbH ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************/ #ifndef CAD_HEATCOOL_RADIATORVALVE_H #define CAD_HEATCOOL_RADIATORVALVE_H #include "caditem.h" #include "items/cad_basic_box.h" class CAD_HeatCool_RadiatorValve : public CADitem { public: CAD_HeatCool_RadiatorValve(); virtual ~CAD_HeatCool_RadiatorValve(); virtual QList<CADitemTypes::ItemType> flangable_items(int flangeIndex); virtual QImage wizardImage(); virtual QString iconPath(); virtual QString domain(); virtual QString description(); virtual void calculate(); virtual void processWizardInput(); virtual QMatrix4x4 rotationOfFlange(quint8 num); // virtual void paint(GLWidget* glwidget); // QOpenGLBuffer arrayBufVertices; // QOpenGLBuffer indexBufFaces; // QOpenGLBuffer indexBufLines; qreal a, a2, l, l2, b; CAD_basic_box *radiator; }; #endif // CAD_HEATCOOL_RADIATORVALVE_H
sme-gmbh/smepowercad
items/cad_heatcool_radiatorvalve.h
C
gpl-3.0
1,700
package net.joaopms.PvPUtilities.helper; import net.minecraftforge.common.config.Configuration; import java.io.File; public class ConfigHelper { private static Configuration config; public static void init(File file) { config = new Configuration(file, true); config.load(); initConfig(); config.save(); } public static Configuration getConfig() { return config; } private static void initConfig() { config.get("overcastStatistics", "showOvercastLogo", true); config.get("overcastStatistics", "showKills", true); config.get("overcastStatistics", "showDeaths", true); config.get("overcastStatistics", "showFriends", false); config.get("overcastStatistics", "showKD", true); config.get("overcastStatistics", "showKK", false); config.get("overcastStatistics", "showServerJoins", false); config.get("overcastStatistics", "showDaysPlayed", false); config.get("overcastStatistics", "showRaindrops", false); config.get("overcastStatistics", "overlayOpacity", 0.5F); } }
joaopms/PvPUtilities
src/main/java/net/joaopms/PvPUtilities/helper/ConfigHelper.java
Java
gpl-3.0
1,117
""" Loads hyperspy as a regular python library, creates a spectrum with random numbers and plots it to a file""" import hyperspy.api as hs import numpy as np import matplotlib.pyplot as plt s = hs.signals.Spectrum(np.random.rand(1024)) s.plot() plt.savefig("testSpectrum.png")
to266/hyperspy
examples/hyperspy_as_library/minimal_example.py
Python
gpl-3.0
280
# Makefile.in generated by automake 1.14.1 from Makefile.am. # compat/jansson/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/ccminer pkgincludedir = $(includedir)/ccminer pkglibdir = $(libdir)/ccminer pkglibexecdir = $(libexecdir)/ccminer am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-unknown-linux-gnu host_triplet = x86_64-unknown-linux-gnu target_triplet = x86_64-unknown-linux-gnu subdir = compat/jansson DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/ccminer-config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) AR = ar ARFLAGS = cru AM_V_AR = $(am__v_AR_$(V)) am__v_AR_ = $(am__v_AR_$(AM_DEFAULT_VERBOSITY)) am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = libjansson_a_AR = $(AR) $(ARFLAGS) libjansson_a_LIBADD = am_libjansson_a_OBJECTS = dump.$(OBJEXT) error.$(OBJEXT) \ hashtable.$(OBJEXT) load.$(OBJEXT) memory.$(OBJEXT) \ pack_unpack.$(OBJEXT) strbuffer.$(OBJEXT) strconv.$(OBJEXT) \ utf.$(OBJEXT) value.$(OBJEXT) libjansson_a_OBJECTS = $(am_libjansson_a_OBJECTS) AM_V_P = $(am__v_P_$(V)) am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY)) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I. -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libjansson_a_SOURCES) DIST_SOURCES = $(libjansson_a_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /home/revolux/Desktop/ccminer/missing aclocal-1.14 ALLOCA = AMTAR = $${TAR-tar} AM_DEFAULT_VERBOSITY = 1 AUTOCONF = ${SHELL} /home/revolux/Desktop/ccminer/missing autoconf AUTOHEADER = ${SHELL} /home/revolux/Desktop/ccminer/missing autoheader AUTOMAKE = ${SHELL} /home/revolux/Desktop/ccminer/missing automake-1.14 AWK = gawk CC = gcc -std=gnu99 CCAS = gcc -std=gnu99 CCASDEPMODE = depmode=gcc3 CCASFLAGS = -g -O2 CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 CPP = gcc -std=gnu99 -E CPPFLAGS = CUDA_CFLAGS = -O3 -lineno -Xcompiler -Wall -D_FORCE_INLINES CUDA_INCLUDES = -I/usr/local/cuda/include CUDA_LDFLAGS = -L/usr/local/cuda/lib64 -ldl CUDA_LIBS = -lcudart CXX = g++ CXXDEPMODE = depmode=gcc3 CXXFLAGS = -O3 -march=native -D_REENTRANT -falign-functions=16 -falign-jumps=16 -falign-labels=16 CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = GREP = /bin/grep INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s JANSSON_LIBS = -ljansson LDFLAGS = LIBCURL = -L/usr/lib/x86_64-linux-gnu -lcurl LIBCURL_CPPFLAGS = LIBOBJS = LIBS = -lcrypto -lssl -lz LTLIBOBJS = MAINT = # MAKEINFO = ${SHELL} /home/revolux/Desktop/ccminer/missing makeinfo MKDIR_P = /bin/mkdir -p NVCC = /usr/local/cuda/bin/nvcc NVML_LIBPATH = libnvidia-ml.so OBJEXT = o OPENMP_CFLAGS = -fopenmp PACKAGE = ccminer PACKAGE_BUGREPORT = PACKAGE_NAME = ccminer PACKAGE_STRING = ccminer 2.2.1 PACKAGE_TARNAME = ccminer PACKAGE_URL = http://github.com/tpruvot/ccminer PACKAGE_VERSION = 2.2.1 PATH_SEPARATOR = : PTHREAD_FLAGS = -pthread PTHREAD_LIBS = -lpthread RANLIB = ranlib SET_MAKE = SHELL = /bin/bash STRIP = VERSION = 2.2.1 WS2_LIBS = _libcurl_config = abs_builddir = /home/revolux/Desktop/ccminer/compat/jansson abs_srcdir = /home/revolux/Desktop/ccminer/compat/jansson abs_top_builddir = /home/revolux/Desktop/ccminer abs_top_srcdir = /home/revolux/Desktop/ccminer ac_ct_CC = gcc ac_ct_CXX = g++ am__include = include am__leading_dot = . am__quote = am__tar = $${TAR-tar} chof - "$$tardir" am__untar = $${TAR-tar} xf - bindir = ${exec_prefix}/bin build = x86_64-unknown-linux-gnu build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-unknown-linux-gnu host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /home/revolux/Desktop/ccminer/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = $(MKDIR_P) oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target = x86_64-unknown-linux-gnu target_alias = target_cpu = x86_64 target_os = linux-gnu target_vendor = unknown top_build_prefix = ../../ top_builddir = ../.. top_srcdir = ../.. noinst_LIBRARIES = libjansson.a libjansson_a_SOURCES = \ jansson_private_config.h \ dump.c \ error.c \ hashtable.c hashtable.h \ jansson.h \ jansson_config.h \ jansson_private.h \ load.c \ memory.c \ pack_unpack.c \ strbuffer.c strbuffer.h \ strconv.c \ utf.c utf.h \ util.h \ value.c all: all-am .SUFFIXES: .SUFFIXES: .c .o .obj $(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign compat/jansson/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign compat/jansson/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: # $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): # $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) libjansson.a: $(libjansson_a_OBJECTS) $(libjansson_a_DEPENDENCIES) $(EXTRA_libjansson_a_DEPENDENCIES) $(AM_V_at)-rm -f libjansson.a $(AM_V_AR)$(libjansson_a_AR) libjansson.a $(libjansson_a_OBJECTS) $(libjansson_a_LIBADD) $(AM_V_at)$(RANLIB) libjansson.a mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c include ./$(DEPDIR)/dump.Po include ./$(DEPDIR)/error.Po include ./$(DEPDIR)/hashtable.Po include ./$(DEPDIR)/load.Po include ./$(DEPDIR)/memory.Po include ./$(DEPDIR)/pack_unpack.Po include ./$(DEPDIR)/strbuffer.Po include ./$(DEPDIR)/strconv.Po include ./$(DEPDIR)/utf.Po include ./$(DEPDIR)/value.Po .c.o: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ $(am__mv) $$depbase.Tpo $$depbase.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c -o $@ $< .c.obj: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ $(am__mv) $$depbase.Tpo $$depbase.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-noinstLIBRARIES mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
Revolux/Revoswitcher
ccminer/compat/jansson/Makefile
Makefile
gpl-3.0
17,263
/* $OpenBSD: stdlib.h,v 1.10 1999/06/11 22:47:48 espie Exp $ */ /* $NetBSD: stdlib.h,v 1.25 1995/12/27 21:19:08 jtc Exp $ */ /*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)stdlib.h 5.13 (Berkeley) 6/4/91 */ #ifndef _STDLIB_H_ #define _STDLIB_H_ #include <machine/ansi.h> #if !defined(_ANSI_SOURCE) /* for quad_t, etc. */ #include <sys/types.h> #endif #ifdef _BSD_SIZE_T_ typedef _BSD_SIZE_T_ size_t; #undef _BSD_SIZE_T_ #endif #ifdef _BSD_WCHAR_T_ typedef _BSD_WCHAR_T_ wchar_t; #undef _BSD_WCHAR_T_ #endif typedef struct { int quot; /* quotient */ int rem; /* remainder */ } div_t; typedef struct { long quot; /* quotient */ long rem; /* remainder */ } ldiv_t; #if !defined(_ANSI_SOURCE) typedef struct { quad_t quot; /* quotient */ quad_t rem; /* remainder */ } qdiv_t; #endif #ifndef NULL #ifdef __GNUG__ #define NULL __null #else #define NULL 0 #endif #endif #define EXIT_FAILURE 1 #define EXIT_SUCCESS 0 #define RAND_MAX 0x7fffffff #define MB_CUR_MAX 1 /* XXX */ #include <sys/cdefs.h> __BEGIN_DECLS __dead void abort __P((void)); int abs __P((int)); int atexit __P((void (*)(void))); double atof __P((const char *)); int atoi __P((const char *)); long atol __P((const char *)); void *bsearch __P((const void *, const void *, size_t, size_t, int (*)(const void *, const void *))); void *calloc __P((size_t, size_t)); div_t div __P((int, int)); __dead void exit __P((int)); void free __P((void *)); char *getenv __P((const char *)); long labs __P((long)); ldiv_t ldiv __P((long, long)); void *malloc __P((size_t)); void qsort __P((void *, size_t, size_t, int (*)(const void *, const void *))); int rand __P((void)); int rand_r __P((unsigned int *)); void *realloc __P((void *, size_t)); void srand __P((unsigned)); double strtod __P((const char *, char **)); long strtol __P((const char *, char **, int)); unsigned long strtoul __P((const char *, char **, int)); int system __P((const char *)); /* these are currently just stubs */ int mblen __P((const char *, size_t)); size_t mbstowcs __P((wchar_t *, const char *, size_t)); int wctomb __P((char *, wchar_t)); int mbtowc __P((wchar_t *, const char *, size_t)); size_t wcstombs __P((char *, const wchar_t *, size_t)); #if !defined(_ANSI_SOURCE) && !defined(_POSIX_SOURCE) #if defined(alloca) && (alloca == __builtin_alloca) && (__GNUC__ < 2) void *alloca __P((int)); /* built-in for gcc */ #else void *alloca __P((size_t)); #endif /* __GNUC__ */ char *getbsize __P((int *, long *)); char *cgetcap __P((char *, const char *, int)); int cgetclose __P((void)); int cgetent __P((char **, char **, const char *)); int cgetfirst __P((char **, char **)); int cgetmatch __P((char *, const char *)); int cgetnext __P((char **, char **)); int cgetnum __P((char *, const char *, long *)); int cgetset __P((const char *)); int cgetstr __P((char *, const char *, char **)); int cgetustr __P((char *, const char *, char **)); int daemon __P((int, int)); char *devname __P((int, int)); int getloadavg __P((double [], int)); long a64l __P((const char *)); char *l64a __P((long)); void cfree __P((void *)); int getopt __P((int, char * const *, const char *)); extern char *optarg; /* getopt(3) external variables */ extern int opterr; extern int optind; extern int optopt; extern int optreset; int getsubopt __P((char **, char * const *, char **)); extern char *suboptarg; /* getsubopt(3) external variable */ int heapsort __P((void *, size_t, size_t, int (*)(const void *, const void *))); int mergesort __P((void *, size_t, size_t, int (*)(const void *, const void *))); int radixsort __P((const unsigned char **, int, const unsigned char *, unsigned)); int sradixsort __P((const unsigned char **, int, const unsigned char *, unsigned)); char *initstate __P((unsigned int, char *, size_t)); long random __P((void)); char *realpath __P((const char *, char *)); char *setstate __P((const char *)); void srandom __P((unsigned int)); int putenv __P((const char *)); #ifdef NOTUSED_BY_PMON int setenv __P((const char *, const char *, int)); #endif void unsetenv __P((const char *)); void setproctitle __P((const char *, ...)); quad_t qabs __P((quad_t)); qdiv_t qdiv __P((quad_t, quad_t)); quad_t strtoq __P((const char *, char **, int)); u_quad_t strtouq __P((const char *, char **, int)); double drand48 __P((void)); double erand48 __P((unsigned short[3])); long jrand48 __P((unsigned short[3])); void lcong48 __P((unsigned short[7])); long lrand48 __P((void)); long mrand48 __P((void)); long nrand48 __P((unsigned short[3])); unsigned short *seed48 __P((unsigned short[3])); void srand48 __P((long)); u_int32_t arc4random __P((void)); void arc4random_stir __P((void)); void arc4random_addrandom __P((unsigned char *, int)); int getbaudval __P((int )); int getbaudrate __P((char *)); #endif /* !_ANSI_SOURCE && !_POSIX_SOURCE */ __END_DECLS #endif /* _STDLIB_H_ */
tupelo-shen/my_test
doc/linux/mips-architecture/loongson-datasheet/pmon/src/pmon-loongson3/include/stdlib.h
C
gpl-3.0
6,742
<?php /* Copyright (C) 2014 Daniel Preussker <[email protected]> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * Custom Frontpage * @author f0o <[email protected]> * @copyright 2014 f0o, LibreNMS * @license GPL */ use Illuminate\Support\Facades\Auth; use LibreNMS\Alert\AlertUtil; use LibreNMS\Config; $install_dir = Config::get('install_dir'); if (Config::get('map.engine', 'leaflet') == 'leaflet') { $temp_output = ' <script src="js/leaflet.js"></script> <script src="js/leaflet.markercluster.js"></script> <script src="js/leaflet.awesome-markers.min.js"></script> <div id="leaflet-map"></div> <script> '; $init_lat = Config::get('leaflet.default_lat', 51.48); $init_lng = Config::get('leaflet.default_lng', 0); $init_zoom = Config::get('leaflet.default_zoom', 5); $group_radius = Config::get('leaflet.group_radius', 80); $tile_url = Config::get('leaflet.tile_url', '{s}.tile.openstreetmap.org'); $show_status = [0, 1]; $map_init = '[' . $init_lat . ', ' . $init_lng . '], ' . sprintf('%01.1f', $init_zoom); $temp_output .= 'var map = L.map(\'leaflet-map\', { zoomSnap: 0.1 } ).setView(' . $map_init . '); L.tileLayer(\'//' . $tile_url . '/{z}/{x}/{y}.png\', { attribution: \'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors\' }).addTo(map); var markers = L.markerClusterGroup({ maxClusterRadius: ' . $group_radius . ', iconCreateFunction: function (cluster) { var markers = cluster.getAllChildMarkers(); var n = 0; color = "green" newClass = "Cluster marker-cluster marker-cluster-small leaflet-zoom-animated leaflet-clickable"; for (var i = 0; i < markers.length; i++) { if (markers[i].options.icon.options.markerColor == "blue" && color != "red") { color = "blue"; } if (markers[i].options.icon.options.markerColor == "red") { color = "red"; } } return L.divIcon({ html: cluster.getChildCount(), className: color+newClass, iconSize: L.point(40, 40) }); }, }); var redMarker = L.AwesomeMarkers.icon({ icon: \'server\', markerColor: \'red\', prefix: \'fa\', iconColor: \'white\' }); var blueMarker = L.AwesomeMarkers.icon({ icon: \'server\', markerColor: \'blue\', prefix: \'fa\', iconColor: \'white\' }); var greenMarker = L.AwesomeMarkers.icon({ icon: \'server\', markerColor: \'green\', prefix: \'fa\', iconColor: \'white\' }); '; // Checking user permissions if (Auth::user()->hasGlobalRead()) { // Admin or global read-only - show all devices $sql = "SELECT DISTINCT(`device_id`),`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng` FROM `devices` LEFT JOIN `locations` ON `devices`.`location_id`=`locations`.`id` WHERE `disabled`=0 AND `ignore`=0 AND ((`lat` != '' AND `lng` != '') OR (`location` REGEXP '\[[0-9\.\, ]+\]')) AND `status` IN " . dbGenPlaceholders(count($show_status)) . ' ORDER BY `status` ASC, `hostname`'; $param = $show_status; } else { // Normal user - grab devices that user has permissions to $device_ids = Permissions::devicesForUser()->toArray() ?: [0]; $sql = "SELECT DISTINCT(`devices`.`device_id`) as `device_id`,`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng` FROM `devices` LEFT JOIN `locations` ON `devices`.location_id=`locations`.`id` WHERE `disabled`=0 AND `ignore`=0 AND ((`lat` != '' AND `lng` != '') OR (`location` REGEXP '\[[0-9\.\, ]+\]')) AND `devices`.`device_id` IN " . dbGenPlaceholders(count($device_ids)) . ' AND `status` IN ' . dbGenPlaceholders(count($show_status)) . ' ORDER BY `status` ASC, `hostname`'; $param = array_merge($device_ids, $show_status); } foreach (dbFetchRows($sql, $param) as $map_devices) { $icon = 'greenMarker'; $z_offset = 0; $tmp_loc = parse_location($map_devices['location']); if (is_numeric($tmp_loc['lat']) && is_numeric($tmp_loc['lng'])) { $map_devices['lat'] = $tmp_loc['lat']; $map_devices['lng'] = $tmp_loc['lng']; } if ($map_devices['status'] == 0) { if (AlertUtil::isMaintenance($map_devices['device_id'])) { if ($show_status == 0) { // Don't show icon if only down devices should be shown continue; } else { $icon = 'blueMarker'; $z_offset = 5000; } } else { $icon = 'redMarker'; $z_offset = 10000; // move marker to foreground } } $temp_output .= "var title = '<a href=\"" . \LibreNMS\Util\Url::deviceUrl((int) $map_devices['device_id']) . '"><img src="' . getIcon($map_devices) . '" width="32" height="32" alt=""> ' . format_hostname($map_devices) . "</a>'; var tooltip = '" . format_hostname($map_devices) . "'; var marker = L.marker(new L.LatLng(" . $map_devices['lat'] . ', ' . $map_devices['lng'] . "), {title: tooltip, icon: $icon, zIndexOffset: $z_offset}); marker.bindPopup(title); markers.addLayer(marker);\n"; } if (Config::get('network_map_show_on_worldmap')) { if (Auth::user()->hasGlobalRead()) { $sql = " SELECT ll.id AS left_id, ll.lat AS left_lat, ll.lng AS left_lng, rl.id AS right_id, rl.lat AS right_lat, rl.lng AS right_lng, sum(lp.ifHighSpeed) AS link_capacity, sum(lp.ifOutOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_out_usage_pct, sum(lp.ifInOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_in_usage_pct FROM devices AS ld, devices AS rd, links AS l, locations AS ll, locations AS rl, ports as lp WHERE l.local_device_id = ld.device_id AND l.remote_device_id = rd.device_id AND ld.location_id != rd.location_id AND ld.location_id = ll.id AND rd.location_id = rl.id AND lp.device_id = ld.device_id AND lp.port_id = l.local_port_id AND lp.ifType = 'ethernetCsmacd' AND ld.disabled = 0 AND ld.ignore = 0 AND rd.disabled = 0 AND rd.ignore = 0 AND lp.ifOutOctets_rate != 0 AND lp.ifInOctets_rate != 0 AND lp.ifOperStatus = 'up' AND ll.lat IS NOT NULL AND ll.lng IS NOT NULL AND rl.lat IS NOT NULL AND rl.lng IS NOT NULL AND ld.status IN " . dbGenPlaceholders(count($show_status)) . ' AND rd.status IN ' . dbGenPlaceholders(count($show_status)) . ' GROUP BY left_id, right_id, ll.lat, ll.lng, rl.lat, rl.lng '; $param = array_merge($show_status, $show_status); } else { $device_ids = Permissions::devicesForUser()->toArray() ?: [0]; $sql = " SELECT ll.id AS left_id, ll.lat AS left_lat, ll.lng AS left_lng, rl.id AS right_id, rl.lat AS right_lat, rl.lng AS right_lng, sum(lp.ifHighSpeed) AS link_capacity, sum(lp.ifOutOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_out_usage_pct, sum(lp.ifInOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_in_usage_pct FROM devices AS ld, devices AS rd, links AS l, locations AS ll, locations AS rl, ports as lp WHERE l.local_device_id = ld.device_id AND l.remote_device_id = rd.device_id AND ld.location_id != rd.location_id AND ld.location_id = ll.id AND rd.location_id = rl.id AND lp.device_id = ld.device_id AND lp.port_id = l.local_port_id AND lp.ifType = 'ethernetCsmacd' AND ld.disabled = 0 AND ld.ignore = 0 AND rd.disabled = 0 AND rd.ignore = 0 AND lp.ifOutOctets_rate != 0 AND lp.ifInOctets_rate != 0 AND lp.ifOperStatus = 'up' AND ll.lat IS NOT NULL AND ll.lng IS NOT NULL AND rl.lat IS NOT NULL AND rl.lng IS NOT NULL AND ld.status IN " . dbGenPlaceholders(count($show_status)) . ' AND rd.status IN ' . dbGenPlaceholders(count($show_status)) . ' AND ld.device_id IN ' . dbGenPlaceholders(count($device_ids)) . ' AND rd.device_id IN ' . dbGenPlaceholders(count($device_ids)) . ' GROUP BY left_id, right_id, ll.lat, ll.lng, rl.lat, rl.lng '; $param = array_merge($show_status, $show_status, $device_ids, $device_ids); } foreach (dbFetchRows($sql, $param) as $link) { $icon = 'greenMarker'; $z_offset = 0; $speed = $link['link_capacity'] / 1000; if ($speed > 500000) { $width = 20; } else { $width = round(0.77 * pow($speed, 0.25)); } $link_used = max($link['link_out_usage_pct'], $link['link_in_usage_pct']); $link_used = round(2 * $link_used, -1) / 2; if ($link_used > 100) { $link_used = 100; } if (is_nan($link_used)) { $link_used = 0; } $link_color = Config::get("network_map_legend.$link_used"); $temp_output .= 'var marker = new L.Polyline([new L.LatLng(' . $link['left_lat'] . ', ' . $link['left_lng'] . '), new L.LatLng(' . $link['right_lat'] . ', ' . $link['right_lng'] . ")], { color: '" . $link_color . "', weight: " . $width . ', opacity: 0.8, smoothFactor: 1 }); markers.addLayer(marker); '; } } $temp_output .= 'map.addLayer(markers); map.scrollWheelZoom.disable(); $(document).ready(function(){ $("#leaflet-map").on("click", function(event) { map.scrollWheelZoom.enable(); }); $("#leaflet-map").mouseleave(function(event) { map.scrollWheelZoom.disable(); }); }); </script>'; } else { $temp_output = 'Mapael engine not supported here'; } unset($common_output); $common_output[] = $temp_output;
rasssta/librenms
includes/html/common/worldmap.inc.php
PHP
gpl-3.0
11,457
package com.bruce.android.knowledge.custom_view.scanAnimation; /** * @author zhenghao.qi * @version 1.0 * @time 2015年11月09日14:45:32 */ public class ScanAnimaitonStrategy implements IAnimationStrategy { /** * 起始X坐标 */ private int startX; /** * 起始Y坐标 */ private int startY; /** * 起始点到终点的Y轴位移。 */ private int shift; /** * X Y坐标。 */ private double currentX, currentY; /** * 动画开始时间。 */ private long startTime; /** * 循环时间 */ private long cyclePeriod; /** * 动画正在进行时值为true,反之为false。 */ private boolean doing; /** * 进行动画展示的view */ private AnimationSurfaceView animationSurfaceView; public ScanAnimaitonStrategy(AnimationSurfaceView animationSurfaceView, int shift, long cyclePeriod) { this.animationSurfaceView = animationSurfaceView; this.shift = shift; this.cyclePeriod = cyclePeriod; initParams(); } public void start() { startTime = System.currentTimeMillis(); doing = true; } /** * 设置起始位置坐标 */ private void initParams() { int[] position = new int[2]; animationSurfaceView.getLocationInWindow(position); this.startX = position[0]; this.startY = position[1]; } /** * 根据当前时间计算小球的X/Y坐标。 */ public void compute() { long intervalTime = (System.currentTimeMillis() - startTime) % cyclePeriod; double angle = Math.toRadians(360 * 1.0d * intervalTime / cyclePeriod); int y = (int) (shift / 2 * Math.cos(angle)); y = Math.abs(y - shift/2); currentY = startY + y; doing = true; } @Override public boolean doing() { return doing; } public double getX() { return currentX; } public double getY() { return currentY; } public void cancel() { doing = false; } }
qizhenghao/Hello_Android
app/src/main/java/com/bruce/android/knowledge/custom_view/scanAnimation/ScanAnimaitonStrategy.java
Java
gpl-3.0
2,115
Wordpress 4.5.3 = 8fdd30960a4499c4e96caf8c5f43d6a2 Wordpress 4.1.13 = 9db7f2e6f8e36b05f7ced5f221e6254b Wordpress 3.8.16 = 9ebe6182b84d541634ded7e953aec282 Wordpress 3.4.2 = d59b6610752b975950f30735688efc36 Wordpress 5.1.1 = 2cde4ea09e0a8414786efdcfda5b9ae4 Wordpress 5.3.1 = 3f2b1e00c430271c6b9e901cc0857800
gohdan/DFC
known_files/hashes/wp-includes/js/tinymce/wp-tinymce.php
PHP
gpl-3.0
308
// needs Markdown.Converter.js at the moment (function () { var util = {}, position = {}, ui = {}, doc = window.document, re = window.RegExp, nav = window.navigator, SETTINGS = { lineLength: 72 }, // Used to work around some browser bugs where we can't use feature testing. uaSniffed = { isIE: /msie/.test(nav.userAgent.toLowerCase()), isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()), isOpera: /opera/.test(nav.userAgent.toLowerCase()) }; // ------------------------------------------------------------------- // YOUR CHANGES GO HERE // // I've tried to localize the things you are likely to change to // this area. // ------------------------------------------------------------------- // The text that appears on the upper part of the dialog box when // entering links. var linkDialogText = "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>"; var imageDialogText = "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br></p>"; // The default text that appears in the dialog input box when entering // links. var imageDefaultText = "http://"; var linkDefaultText = "http://"; var defaultHelpHoverTitle = "Markdown Editing Help"; // ------------------------------------------------------------------- // END OF YOUR CHANGES // ------------------------------------------------------------------- // help, if given, should have a property "handler", the click handler for the help button, // and can have an optional property "title" for the button's tooltip (defaults to "Markdown Editing Help"). // If help isn't given, not help button is created. // // The constructed editor object has the methods: // - getConverter() returns the markdown converter object that was passed to the constructor // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op. // - refreshPreview() forces the preview to be updated. This method is only available after run() was called. Markdown.Editor = function (markdownConverter, idPostfix, help) { idPostfix = idPostfix || ""; var hooks = this.hooks = new Markdown.HookCollection(); hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used. */ this.getConverter = function () { return markdownConverter; } var that = this, panels; this.run = function () { if (panels) return; // already initialized panels = new PanelCollection(idPostfix); var commandManager = new CommandManager(hooks); var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); }); var undoManager, uiManager; if (!/\?noundo/.test(doc.location.href)) { undoManager = new UndoManager(function () { previewManager.refresh(); if (uiManager) // not available on the first call uiManager.setUndoRedoButtonStates(); }, panels); this.textOperation = function (f) { undoManager.setCommandMode(); f(); that.refreshPreview(); } } uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help); uiManager.setUndoRedoButtonStates(); var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); }; forceRefresh(); }; } // before: contains all the text in the input box BEFORE the selection. // after: contains all the text in the input box AFTER the selection. function Chunks() { } // startRegex: a regular expression to find the start tag // endRegex: a regular expresssion to find the end tag Chunks.prototype.findTags = function (startRegex, endRegex) { var chunkObj = this; var regex; if (startRegex) { regex = util.extendRegExp(startRegex, "", "$"); this.before = this.before.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); regex = util.extendRegExp(startRegex, "^", ""); this.selection = this.selection.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); } if (endRegex) { regex = util.extendRegExp(endRegex, "", "$"); this.selection = this.selection.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); regex = util.extendRegExp(endRegex, "^", ""); this.after = this.after.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); } }; // If remove is false, the whitespace is transferred // to the before/after regions. // // If remove is true, the whitespace disappears. Chunks.prototype.trimWhitespace = function (remove) { var beforeReplacer, afterReplacer, that = this; if (remove) { beforeReplacer = afterReplacer = ""; } else { beforeReplacer = function (s) { that.before += s; return ""; } afterReplacer = function (s) { that.after = s + that.after; return ""; } } this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer); }; Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) { if (nLinesBefore === undefined) { nLinesBefore = 1; } if (nLinesAfter === undefined) { nLinesAfter = 1; } nLinesBefore++; nLinesAfter++; var regexText; var replacementText; // chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985 if (navigator.userAgent.match(/Chrome/)) { "X".match(/()./); } this.selection = this.selection.replace(/(^\n*)/, ""); this.startTag = this.startTag + re.$1; this.selection = this.selection.replace(/(\n*$)/, ""); this.endTag = this.endTag + re.$1; this.startTag = this.startTag.replace(/(^\n*)/, ""); this.before = this.before + re.$1; this.endTag = this.endTag.replace(/(\n*$)/, ""); this.after = this.after + re.$1; if (this.before) { regexText = replacementText = ""; while (nLinesBefore--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.before = this.before.replace(new re(regexText + "$", ""), replacementText); } if (this.after) { regexText = replacementText = ""; while (nLinesAfter--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.after = this.after.replace(new re(regexText, ""), replacementText); } }; // end of Chunks // A collection of the important regions on the page. // Cached so we don't have to keep traversing the DOM. // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around // this issue: // Internet explorer has problems with CSS sprite buttons that use HTML // lists. When you click on the background image "button", IE will // select the non-existent link text and discard the selection in the // textarea. The solution to this is to cache the textarea selection // on the button's mousedown event and set a flag. In the part of the // code where we need to grab the selection, we check for the flag // and, if it's set, use the cached area instead of querying the // textarea. // // This ONLY affects Internet Explorer (tested on versions 6, 7 // and 8) and ONLY on button clicks. Keyboard shortcuts work // normally since the focus never leaves the textarea. function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); this.preview = doc.getElementById("wmd-preview" + postfix); this.input = doc.getElementById("wmd-input" + postfix); }; // Returns true if the DOM element is visible, false if it's hidden. // Checks if display is anything other than none. util.isVisible = function (elem) { if (window.getComputedStyle) { // Most browsers return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none"; } else if (elem.currentStyle) { // IE return elem.currentStyle["display"] !== "none"; } }; // Adds a listener callback to a DOM element which is fired on a specified // event. util.addEvent = function (elem, event, listener) { if (elem.attachEvent) { // IE only. The "on" is mandatory. elem.attachEvent("on" + event, listener); } else { // Other browsers. elem.addEventListener(event, listener, false); } }; // Removes a listener callback from a DOM element which is fired on a specified // event. util.removeEvent = function (elem, event, listener) { if (elem.detachEvent) { // IE only. The "on" is mandatory. elem.detachEvent("on" + event, listener); } else { // Other browsers. elem.removeEventListener(event, listener, false); } }; // Converts \r\n and \r to \n. util.fixEolChars = function (text) { text = text.replace(/\r\n/g, "\n"); text = text.replace(/\r/g, "\n"); return text; }; // Extends a regular expression. Returns a new RegExp // using pre + regex + post as the expression. // Used in a few functions where we have a base // expression and we want to pre- or append some // conditions to it (e.g. adding "$" to the end). // The flags are unchanged. // // regex is a RegExp, pre and post are strings. util.extendRegExp = function (regex, pre, post) { if (pre === null || pre === undefined) { pre = ""; } if (post === null || post === undefined) { post = ""; } var pattern = regex.toString(); var flags; // Replace the flags with empty space and store them. pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) { flags = flagsPart; return ""; }); // Remove the slash delimiters on the regular expression. pattern = pattern.replace(/(^\/|\/$)/g, ""); pattern = pre + pattern + post; return new re(pattern, flags); } // UNFINISHED // The assignment in the while loop makes jslint cranky. // I'll change it to a better loop later. position.getTop = function (elem, isInner) { var result = elem.offsetTop; if (!isInner) { while (elem = elem.offsetParent) { result += elem.offsetTop; } } return result; }; position.getHeight = function (elem) { return elem.offsetHeight || elem.scrollHeight; }; position.getWidth = function (elem) { return elem.offsetWidth || elem.scrollWidth; }; position.getPageSize = function () { var scrollWidth, scrollHeight; var innerWidth, innerHeight; // It's not very clear which blocks work with which browsers. if (self.innerHeight && self.scrollMaxY) { scrollWidth = doc.body.scrollWidth; scrollHeight = self.innerHeight + self.scrollMaxY; } else if (doc.body.scrollHeight > doc.body.offsetHeight) { scrollWidth = doc.body.scrollWidth; scrollHeight = doc.body.scrollHeight; } else { scrollWidth = doc.body.offsetWidth; scrollHeight = doc.body.offsetHeight; } if (self.innerHeight) { // Non-IE browser innerWidth = self.innerWidth; innerHeight = self.innerHeight; } else if (doc.documentElement && doc.documentElement.clientHeight) { // Some versions of IE (IE 6 w/ a DOCTYPE declaration) innerWidth = doc.documentElement.clientWidth; innerHeight = doc.documentElement.clientHeight; } else if (doc.body) { // Other versions of IE innerWidth = doc.body.clientWidth; innerHeight = doc.body.clientHeight; } var maxWidth = Math.max(scrollWidth, innerWidth); var maxHeight = Math.max(scrollHeight, innerHeight); return [maxWidth, maxHeight, innerWidth, innerHeight]; }; // Handles pushing and popping TextareaStates for undo/redo commands. // I should rename the stack variables to list. function UndoManager(callback, panels) { var undoObj = this; var undoStack = []; // A stack of undo states var stackPtr = 0; // The index of the current state var mode = "none"; var lastState; // The last state var timer; // The setTimeout handle for cancelling the timer var inputStateObj; // Set the mode for later logic steps. var setMode = function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }; var refreshState = function (isInitialState) { inputStateObj = new TextareaState(panels, isInitialState); timer = undefined; }; this.setCommandMode = function () { mode = "command"; saveState(); timer = setTimeout(refreshState, 0); }; this.canUndo = function () { return stackPtr > 1; }; this.canRedo = function () { if (undoStack[stackPtr + 1]) { return true; } return false; }; // Removes the last state and restores it. this.undo = function () { if (undoObj.canUndo()) { if (lastState) { // What about setting state -1 to null or checking for undefined? lastState.restore(); lastState = null; } else { undoStack[stackPtr] = new TextareaState(panels); undoStack[--stackPtr].restore(); if (callback) { callback(); } } } mode = "none"; panels.input.focus(); refreshState(); }; // Redo an action. this.redo = function () { if (undoObj.canRedo()) { undoStack[++stackPtr].restore(); if (callback) { callback(); } } mode = "none"; panels.input.focus(); refreshState(); }; // Push the input area state to the stack. var saveState = function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }; var handleCtrlYZ = function (event) { var handled = false; if (event.ctrlKey || event.metaKey) { // IE and Opera do not support charCode. var keyCode = event.charCode || event.keyCode; var keyCodeChar = String.fromCharCode(keyCode); switch (keyCodeChar) { case "y": undoObj.redo(); handled = true; break; case "z": if (!event.shiftKey) { undoObj.undo(); } else { undoObj.redo(); } handled = true; break; } } if (handled) { if (event.preventDefault) { event.preventDefault(); } if (window.event) { window.event.returnValue = false; } return; } }; // Set the mode depending on what is going on in the input area. var handleModeChange = function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }; var setEventHandlers = function () { util.addEvent(panels.input, "keypress", function (event) { // keyCode 89: y // keyCode 90: z if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) { event.preventDefault(); } }); var handlePaste = function () { if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) { if (timer == undefined) { mode = "paste"; saveState(); refreshState(); } } }; util.addEvent(panels.input, "keydown", handleCtrlYZ); util.addEvent(panels.input, "keydown", handleModeChange); util.addEvent(panels.input, "mousedown", function () { setMode("moving"); }); panels.input.onpaste = handlePaste; panels.input.ondrop = handlePaste; }; var init = function () { setEventHandlers(); refreshState(true); saveState(); }; init(); } // end of UndoManager // The input textarea state/contents. // This is used to implement undo/redo by the undo manager. function TextareaState(panels, isInitialState) { // Aliases var stateObj = this; var inputArea = panels.input; this.init = function () { if (!util.isVisible(inputArea)) { return; } if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box return; } this.setInputAreaSelectionStartEnd(); this.scrollTop = inputArea.scrollTop; if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) { this.text = inputArea.value; } } // Sets the selected text in the input box after we've performed an // operation. this.setInputAreaSelection = function () { if (!util.isVisible(inputArea)) { return; } if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) { inputArea.focus(); inputArea.selectionStart = stateObj.start; inputArea.selectionEnd = stateObj.end; inputArea.scrollTop = stateObj.scrollTop; } else if (doc.selection) { if (doc.activeElement && doc.activeElement !== inputArea) { return; } inputArea.focus(); var range = inputArea.createTextRange(); range.moveStart("character", -inputArea.value.length); range.moveEnd("character", -inputArea.value.length); range.moveEnd("character", stateObj.end); range.moveStart("character", stateObj.start); range.select(); } }; this.setInputAreaSelectionStartEnd = function () { if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) { stateObj.start = inputArea.selectionStart; stateObj.end = inputArea.selectionEnd; } else if (doc.selection) { stateObj.text = util.fixEolChars(inputArea.value); // IE loses the selection in the textarea when buttons are // clicked. On IE we cache the selection. Here, if something is cached, // we take it. var range = panels.ieCachedRange || doc.selection.createRange(); var fixedRange = util.fixEolChars(range.text); var marker = "\x07"; var markedRange = marker + fixedRange + marker; range.text = markedRange; var inputText = util.fixEolChars(inputArea.value); range.moveStart("character", -markedRange.length); range.text = fixedRange; stateObj.start = inputText.indexOf(marker); stateObj.end = inputText.lastIndexOf(marker) - marker.length; var len = stateObj.text.length - util.fixEolChars(inputArea.value).length; if (len) { range.moveStart("character", -fixedRange.length); while (len--) { fixedRange += "\n"; stateObj.end += 1; } range.text = fixedRange; } if (panels.ieCachedRange) stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange panels.ieCachedRange = null; this.setInputAreaSelection(); } }; // Restore this state into the input area. this.restore = function () { if (stateObj.text != undefined && stateObj.text != inputArea.value) { inputArea.value = stateObj.text; } this.setInputAreaSelection(); inputArea.scrollTop = stateObj.scrollTop; }; // Gets a collection of HTML chunks from the inptut textarea. this.getChunks = function () { var chunk = new Chunks(); chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start)); chunk.startTag = ""; chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end)); chunk.endTag = ""; chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end)); chunk.scrollTop = stateObj.scrollTop; return chunk; }; // Sets the TextareaState properties given a chunk of markdown. this.setChunks = function (chunk) { chunk.before = chunk.before + chunk.startTag; chunk.after = chunk.endTag + chunk.after; this.start = chunk.before.length; this.end = chunk.before.length + chunk.selection.length; this.text = chunk.before + chunk.selection + chunk.after; this.scrollTop = chunk.scrollTop; }; this.init(); }; function PreviewManager(converter, panels, previewRefreshCallback) { var managerObj = this; var timeout; var elapsedTime; var oldInputText; var maxDelay = 3000; var startType = "delayed"; // The other legal value is "manual" // Adds event listeners to elements var setupEvents = function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }; var getDocScrollTop = function () { var result = 0; if (window.innerHeight) { result = window.pageYOffset; } else if (doc.documentElement && doc.documentElement.scrollTop) { result = doc.documentElement.scrollTop; } else if (doc.body) { result = doc.body.scrollTop; } return result; }; var makePreviewHtml = function () { // If there is no registered preview panel // there is nothing to do. if (!panels.preview) return; var text = panels.input.value; if (text && text == oldInputText) { return; // Input text hasn't changed. } else { oldInputText = text; } var prevTime = new Date().getTime(); text = converter.makeHtml(text); // Calculate the processing time of the HTML creation. // It's used as the delay time in the event listener. var currTime = new Date().getTime(); elapsedTime = currTime - prevTime; pushPreviewHtml(text); }; // setTimeout is already used. Used as an event listener. var applyTimeout = function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }; var getScaleFactor = function (panel) { if (panel.scrollHeight <= panel.clientHeight) { return 1; } return panel.scrollTop / (panel.scrollHeight - panel.clientHeight); }; var setPanelScrollTops = function () { if (panels.preview) { panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview); } }; this.refresh = function (requiresRefresh) { if (requiresRefresh) { oldInputText = ""; makePreviewHtml(); } else { applyTimeout(); } }; this.processingTime = function () { return elapsedTime; }; var isFirstTimeFilled = true; // IE doesn't let you use innerHTML if the element is contained somewhere in a table // (which is the case for inline editing) -- in that case, detach the element, set the // value, and reattach. Yes, that *is* ridiculous. var ieSafePreviewSet = function (text) { var preview = panels.preview; var parent = preview.parentNode; var sibling = preview.nextSibling; parent.removeChild(preview); preview.innerHTML = text; if (!sibling) parent.appendChild(preview); else parent.insertBefore(preview, sibling); } var nonSuckyBrowserPreviewSet = function (text) { panels.preview.innerHTML = text; } var previewSetter; var previewSet = function (text) { if (previewSetter) return previewSetter(text); try { nonSuckyBrowserPreviewSet(text); previewSetter = nonSuckyBrowserPreviewSet; } catch (e) { previewSetter = ieSafePreviewSet; previewSetter(text); } }; var pushPreviewHtml = function (text) { var emptyTop = position.getTop(panels.input) - getDocScrollTop(); if (panels.preview) { previewSet(text); previewRefreshCallback(); } setPanelScrollTops(); if (isFirstTimeFilled) { isFirstTimeFilled = false; return; } var fullTop = position.getTop(panels.input) - getDocScrollTop(); if (uaSniffed.isIE) { setTimeout(function () { window.scrollBy(0, fullTop - emptyTop); }, 0); } else { window.scrollBy(0, fullTop - emptyTop); } }; var init = function () { setupEvents(panels.input, applyTimeout); makePreviewHtml(); if (panels.preview) { panels.preview.scrollTop = 0; } }; init(); }; // Creates the background behind the hyperlink text entry box. // And download dialog // Most of this has been moved to CSS but the div creation and // browser-specific hacks remain here. ui.createBackground = function () { var background = doc.createElement("div"), style = background.style; background.className = "wmd-prompt-background"; style.position = "absolute"; style.top = "0"; style.zIndex = "1000"; if (uaSniffed.isIE) { style.filter = "alpha(opacity=50)"; } else { style.opacity = "0.5"; } var pageSize = position.getPageSize(); style.height = pageSize[1] + "px"; if (uaSniffed.isIE) { style.left = doc.documentElement.scrollLeft; style.width = doc.documentElement.clientWidth; } else { style.left = "0"; style.width = "100%"; } doc.body.appendChild(background); return background; }; // This simulates a modal dialog box and asks for the URL when you // click the hyperlink or image buttons. // // text: The html for the input box. // defaultInputText: The default value that appears in the input box. // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel. // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel // was chosen). ui.prompt = function (text, defaultInputText, callback) { // These variables need to be declared at this level since they are used // in multiple functions. var dialog; // The dialog box. var input; // The text box where you enter the hyperlink. if (defaultInputText === undefined) { defaultInputText = ""; } // Used as a keydown event handler. Esc dismisses the prompt. // Key code 27 is ESC. var checkEscape = function (key) { var code = (key.charCode || key.keyCode); if (code === 27) { close(true); } }; // Dismisses the hyperlink input box. // isCancel is true if we don't care about the input text. // isCancel is false if we are going to keep the text. var close = function (isCancel) { util.removeEvent(doc.body, "keydown", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }; // Create the text input box form/window. var createDialog = function () { // The main dialog box. dialog = doc.createElement("div"); dialog.className = "wmd-prompt-dialog"; dialog.style.padding = "10px;"; dialog.style.position = "fixed"; dialog.style.width = "400px"; dialog.style.zIndex = "1001"; // The dialog text. var question = doc.createElement("div"); question.innerHTML = text; question.style.padding = "5px"; dialog.appendChild(question); // The web form container for the text box and buttons. var form = doc.createElement("form"), style = form.style; form.onsubmit = function () { return close(false); }; style.padding = "0"; style.margin = "0"; style.cssFloat = "left"; style.width = "100%"; style.textAlign = "center"; style.position = "relative"; dialog.appendChild(form); // The input text box input = doc.createElement("input"); input.type = "text"; input.value = defaultInputText; style = input.style; style.display = "block"; style.width = "80%"; style.marginLeft = style.marginRight = "auto"; form.appendChild(input); // The ok button var okButton = doc.createElement("input"); okButton.type = "button"; okButton.onclick = function () { return close(false); }; okButton.value = "OK"; style = okButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; // The cancel button var cancelButton = doc.createElement("input"); cancelButton.type = "button"; cancelButton.onclick = function () { return close(true); }; cancelButton.value = "Cancel"; style = cancelButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; form.appendChild(okButton); form.appendChild(cancelButton); util.addEvent(doc.body, "keydown", checkEscape); dialog.style.top = "50%"; dialog.style.left = "50%"; dialog.style.display = "block"; if (uaSniffed.isIE_5or6) { dialog.style.position = "absolute"; dialog.style.top = doc.documentElement.scrollTop + 200 + "px"; dialog.style.left = "50%"; } doc.body.appendChild(dialog); // This has to be done AFTER adding the dialog to the form if you // want it to be centered. dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px"; dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px"; }; // Why is this in a zero-length timeout? // Is it working around a browser bug? setTimeout(function () { createDialog(); var defTextLen = defaultInputText.length; if (input.selectionStart !== undefined) { input.selectionStart = 0; input.selectionEnd = defTextLen; } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(false); range.moveStart("character", -defTextLen); range.moveEnd("character", defTextLen); range.select(); } input.focus(); }, 0); }; function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions) { var inputBox = panels.input, buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements. makeSpritedButtonRow(); var keyEvent = "keydown"; if (uaSniffed.isOpera) { keyEvent = "keypress"; } util.addEvent(inputBox, keyEvent, function (key) { // Check to see if we have a button key and, if so execute the callback. if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) { var keyCode = key.charCode || key.keyCode; var keyCodeStr = String.fromCharCode(keyCode).toLowerCase(); switch (keyCodeStr) { case "b": doClick(buttons.bold); break; case "i": doClick(buttons.italic); break; case "l": doClick(buttons.link); break; case "q": doClick(buttons.quote); break; case "k": doClick(buttons.code); break; case "g": doClick(buttons.image); break; case "o": doClick(buttons.olist); break; case "u": doClick(buttons.ulist); break; case "h": doClick(buttons.heading); break; case "r": doClick(buttons.hr); break; case "y": doClick(buttons.redo); break; case "z": if (key.shiftKey) { doClick(buttons.redo); } else { doClick(buttons.undo); } break; default: return; } if (key.preventDefault) { key.preventDefault(); } if (window.event) { window.event.returnValue = false; } } }); // Auto-indent on shift-enter util.addEvent(inputBox, "keyup", function (key) { if (key.shiftKey && !key.ctrlKey && !key.metaKey) { var keyCode = key.charCode || key.keyCode; // Character 13 is Enter if (keyCode === 13) { var fakeButton = {}; fakeButton.textOp = bindCommand("doAutoindent"); doClick(fakeButton); } } }); // special handler because IE clears the context of the textbox on ESC if (uaSniffed.isIE) { util.addEvent(inputBox, "keydown", function (key) { var code = key.keyCode; if (code === 27) { return false; } }); } // Perform the button's action. function doClick(button) { inputBox.focus(); if (button.textOp) { if (undoManager) { undoManager.setCommandMode(); } var state = new TextareaState(panels); if (!state) { return; } var chunks = state.getChunks(); // Some commands launch a "modal" prompt dialog. Javascript // can't really make a modal dialog box and the WMD code // will continue to execute while the dialog is displayed. // This prevents the dialog pattern I'm used to and means // I can't do something like this: // // var link = CreateLinkDialog(); // makeMarkdownLink(link); // // Instead of this straightforward method of handling a // dialog I have to pass any code which would execute // after the dialog is dismissed (e.g. link creation) // in a function parameter. // // Yes this is awkward and I think it sucks, but there's // no real workaround. Only the image and link code // create dialogs and require the function pointers. var fixupInputArea = function () { inputBox.focus(); if (chunks) { state.setChunks(chunks); } state.restore(); previewManager.refresh(); }; var noCleanup = button.textOp(chunks, fixupInputArea); if (!noCleanup) { fixupInputArea(); } } if (button.execute) { button.execute(undoManager); } }; function setupButton(button, isEnabled) { var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var image = button.getElementsByTagName("span")[0]; if (isEnabled) { image.style.backgroundPosition = button.XShift + " " + normalYShift; button.onmouseover = function () { image.style.backgroundPosition = this.XShift + " " + highlightYShift; }; button.onmouseout = function () { image.style.backgroundPosition = this.XShift + " " + normalYShift; }; // IE tries to select the background image "button" text (it's // implemented in a list item) so we have to cache the selection // on mousedown. if (uaSniffed.isIE) { button.onmousedown = function () { if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection return; } panels.ieCachedRange = document.selection.createRange(); panels.ieCachedScrollTop = panels.input.scrollTop; }; } if (!button.isHelp) { button.onclick = function () { if (this.onmouseout) { this.onmouseout(); } doClick(this); return false; } } } else { image.style.backgroundPosition = button.XShift + " " + disabledYShift; button.onmouseover = button.onmouseout = button.onclick = function () { }; } } function bindCommand(method) { if (typeof method === "string") method = commandManager[method]; return function () { method.apply(commandManager, arguments); } } function makeSpritedButtonRow() { var buttonBar = panels.buttonBar; var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var buttonRow = document.createElement("ul"); buttonRow.id = "wmd-button-row" + postfix; buttonRow.className = 'wmd-button-row'; buttonRow = buttonBar.appendChild(buttonRow); var xPosition = 0; var makeButton = function (id, title, XShift, textOp) { var button = document.createElement("li"); button.className = "wmd-button"; button.style.left = xPosition + "px"; xPosition += 25; var buttonImage = document.createElement("span"); button.id = id + postfix; button.appendChild(buttonImage); button.title = title; button.XShift = XShift; if (textOp) button.textOp = textOp; setupButton(button, true); buttonRow.appendChild(button); return button; }; var makeSpacer = function (num) { var spacer = document.createElement("li"); spacer.className = "wmd-spacer wmd-spacer" + num; spacer.id = "wmd-spacer" + num + postfix; buttonRow.appendChild(spacer); xPosition += 25; } buttons.bold = makeButton("wmd-bold-button", "Strong <strong> Ctrl+B", "0px", bindCommand("doBold")); buttons.italic = makeButton("wmd-italic-button", "Emphasis <em> Ctrl+I", "-20px", bindCommand("doItalic")); makeSpacer(1); buttons.link = makeButton("wmd-link-button", "Hyperlink <a> Ctrl+L", "-40px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, false); })); buttons.quote = makeButton("wmd-quote-button", "Blockquote <blockquote> Ctrl+Q", "-60px", bindCommand("doBlockquote")); buttons.code = makeButton("wmd-code-button", "Code Sample <pre><code> Ctrl+K", "-80px", bindCommand("doCode")); buttons.image = makeButton("wmd-image-button", "Image <img> Ctrl+G", "-100px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, true); })); makeSpacer(2); buttons.olist = makeButton("wmd-olist-button", "Numbered List <ol> Ctrl+O", "-120px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, true); })); buttons.ulist = makeButton("wmd-ulist-button", "Bulleted List <ul> Ctrl+U", "-140px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, false); })); buttons.heading = makeButton("wmd-heading-button", "Heading <h1>/<h2> Ctrl+H", "-160px", bindCommand("doHeading")); buttons.hr = makeButton("wmd-hr-button", "Horizontal Rule <hr> Ctrl+R", "-180px", bindCommand("doHorizontalRule")); makeSpacer(3); buttons.undo = makeButton("wmd-undo-button", "Undo - Ctrl+Z", "-200px", null); buttons.undo.execute = function (manager) { if (manager) manager.undo(); }; var redoTitle = /win/.test(nav.platform.toLowerCase()) ? "Redo - Ctrl+Y" : "Redo - Ctrl+Shift+Z"; // mac and other non-Windows platforms buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null); buttons.redo.execute = function (manager) { if (manager) manager.redo(); }; if (helpOptions) { var helpButton = document.createElement("li"); var helpButtonImage = document.createElement("span"); helpButton.appendChild(helpButtonImage); helpButton.className = "wmd-button wmd-help-button"; helpButton.id = "wmd-help-button" + postfix; helpButton.XShift = "-240px"; helpButton.isHelp = true; helpButton.style.right = "0px"; helpButton.title = helpOptions.title || defaultHelpHoverTitle; helpButton.onclick = helpOptions.handler; setupButton(helpButton, true); buttonRow.appendChild(helpButton); buttons.help = helpButton; } setUndoRedoButtonStates(); } function setUndoRedoButtonStates() { if (undoManager) { setupButton(buttons.undo, undoManager.canUndo()); setupButton(buttons.redo, undoManager.canRedo()); } }; this.setUndoRedoButtonStates = setUndoRedoButtonStates; } function CommandManager(pluginHooks) { this.hooks = pluginHooks; } var commandProto = CommandManager.prototype; // The markdown symbols - 4 spaces = code, > = blockquote, etc. commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)"; // Remove markdown symbols from the chunk selection. commandProto.unwrap = function (chunk) { var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g"); chunk.selection = chunk.selection.replace(txt, "$1 $2"); }; commandProto.wrap = function (chunk, len) { this.unwrap(chunk); var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"), that = this; chunk.selection = chunk.selection.replace(regex, function (line, marked) { if (new re("^" + that.prefixes, "").test(line)) { return line; } return marked + "\n"; }); chunk.selection = chunk.selection.replace(/\s+$/, ""); }; commandProto.doBold = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 2, "strong text"); }; commandProto.doItalic = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 1, "emphasized text"); }; // chunk: The selected region that will be enclosed with */** // nStars: 1 for italics, 2 for bold // insertText: If you just click the button without highlighting text, this gets inserted commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) { // Get rid of whitespace and fixup newlines. chunk.trimWhitespace(); chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n"); // Look for stars before and after. Is the chunk already marked up? // note that these regex matches cannot fail var starsBefore = /(\**$)/.exec(chunk.before)[0]; var starsAfter = /(^\**)/.exec(chunk.after)[0]; var prevStars = Math.min(starsBefore.length, starsAfter.length); // Remove stars if we have to since the button acts as a toggle. if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) { chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), ""); chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), ""); } else if (!chunk.selection && starsAfter) { // It's not really clear why this code is necessary. It just moves // some arbitrary stuff around. chunk.after = chunk.after.replace(/^([*_]*)/, ""); chunk.before = chunk.before.replace(/(\s?)$/, ""); var whitespace = re.$1; chunk.before = chunk.before + starsAfter + whitespace; } else { // In most cases, if you don't have any selected text and click the button // you'll get a selected, marked up region with the default text inserted. if (!chunk.selection && !starsAfter) { chunk.selection = insertText; } // Add the true markup. var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ? chunk.before = chunk.before + markup; chunk.after = markup + chunk.after; } return; }; commandProto.stripLinkDefs = function (text, defsToAdd) { text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm, function (totalMatch, id, link, newlines, title) { defsToAdd[id] = totalMatch.replace(/\s*$/, ""); if (newlines) { // Strip the title and return that separately. defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, ""); return newlines + title; } return ""; }); return text; }; commandProto.addLinkDef = function (chunk, linkDef) { var refNumber = 0; // The current reference number var defsToAdd = {}; // // Start with a clean slate by removing all previous link definitions. chunk.before = this.stripLinkDefs(chunk.before, defsToAdd); chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd); chunk.after = this.stripLinkDefs(chunk.after, defsToAdd); var defs = ""; var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g; var addDefNumber = function (def) { refNumber++; def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:"); defs += "\n" + def; }; // note that // a) the recursive call to getLink cannot go infinite, because by definition // of regex, inner is always a proper substring of wholeMatch, and // b) more than one level of nesting is neither supported by the regex // nor making a lot of sense (the only use case for nesting is a linked image) var getLink = function (wholeMatch, before, inner, afterInner, id, end) { inner = inner.replace(regex, getLink); if (defsToAdd[id]) { addDefNumber(defsToAdd[id]); return before + inner + afterInner + refNumber + end; } return wholeMatch; }; chunk.before = chunk.before.replace(regex, getLink); if (linkDef) { addDefNumber(linkDef); } else { chunk.selection = chunk.selection.replace(regex, getLink); } var refOut = refNumber; chunk.after = chunk.after.replace(regex, getLink); if (chunk.after) { chunk.after = chunk.after.replace(/\n*$/, ""); } if (!chunk.after) { chunk.selection = chunk.selection.replace(/\n*$/, ""); } chunk.after += "\n\n" + defs; return refOut; }; // takes the line as entered into the add link/as image dialog and makes // sure the URL and the optinal title are "nice". function properlyEncoded(linkdef) { return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) { link = link.replace(/\?.*$/, function (querypart) { return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical }); link = decodeURIComponent(link); // unencode first, to prevent double encoding link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29'); link = link.replace(/\?.*$/, function (querypart) { return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded }); if (title) { title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, ""); title = $.trim(title).replace(/"/g, "quot;").replace(/\(/g, "&#40;").replace(/\)/g, "&#41;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } return title ? link + ' "' + title + '"' : link; }); } commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) { chunk.trimWhitespace(); chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/); var background; if (chunk.endTag.length > 1 && chunk.startTag.length > 0) { chunk.startTag = chunk.startTag.replace(/!?\[/, ""); chunk.endTag = ""; this.addLinkDef(chunk, null); } else { // We're moving start and end tag back into the selection, since (as we're in the else block) we're not // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the // link text. linkEnteredCallback takes care of escaping any brackets. chunk.selection = chunk.startTag + chunk.selection + chunk.endTag; chunk.startTag = chunk.endTag = ""; if (/\n\n/.test(chunk.selection)) { this.addLinkDef(chunk, null); return; } var that = this; // The function to be executed when you enter a link and press OK or Cancel. // Marks up the link and adds the ref. var linkEnteredCallback = function (link) { background.parentNode.removeChild(background); if (link !== null) { // ( $1 // [^\\] anything that's not a backslash // (?:\\\\)* an even number (this includes zero) of backslashes // ) // (?= followed by // [[\]] an opening or closing bracket // ) // // In other words, a non-escaped bracket. These have to be escaped now to make sure they // don't count as the end of the link or similar. // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets), // the bracket in one match may be the "not a backslash" character in the next match, so it // should not be consumed by the first match. // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the // start of the string, so this also works if the selection begins with a bracket. We cannot solve // this by anchoring with ^, because in the case that the selection starts with two brackets, this // would mean a zero-width match at the start. Since zero-width matches advance the string position, // the first bracket could then not act as the "not a backslash" for the second. chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1); var linkDef = " [999]: " + properlyEncoded(link); var num = that.addLinkDef(chunk, linkDef); chunk.startTag = isImage ? "![" : "["; chunk.endTag = "][" + num + "]"; if (!chunk.selection) { if (isImage) { chunk.selection = "enter image description here"; } else { chunk.selection = "enter link description here"; } } } postProcessing(); }; background = ui.createBackground(); if (isImage) { if (!this.hooks.insertImageDialog(linkEnteredCallback)) ui.prompt(imageDialogText, imageDefaultText, linkEnteredCallback); } else { ui.prompt(linkDialogText, linkDefaultText, linkEnteredCallback); } return true; } }; // When making a list, hitting shift-enter will put your cursor on the next line // at the current indent level. commandProto.doAutoindent = function (chunk, postProcessing) { var commandMgr = this, fakeSelection = false; chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n"); // There's no selection, end the cursor wasn't at the end of the line: // The user wants to split the current list item / code line / blockquote line // (for the latter it doesn't really matter) in two. Temporarily select the // (rest of the) line to achieve this. if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) { chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) { chunk.selection = wholeMatch; return ""; }); fakeSelection = true; } if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doList) { commandMgr.doList(chunk); } } if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doBlockquote) { commandMgr.doBlockquote(chunk); } } if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { if (commandMgr.doCode) { commandMgr.doCode(chunk); } } if (fakeSelection) { chunk.after = chunk.selection + chunk.after; chunk.selection = ""; } }; commandProto.doBlockquote = function (chunk, postProcessing) { chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/, function (totalMatch, newlinesBefore, text, newlinesAfter) { chunk.before += newlinesBefore; chunk.after = newlinesAfter + chunk.after; return text; }); chunk.before = chunk.before.replace(/(>[ \t]*)$/, function (totalMatch, blankLine) { chunk.selection = blankLine + chunk.selection; return ""; }); chunk.selection = chunk.selection.replace(/^(\s|>)+$/, ""); chunk.selection = chunk.selection || "Blockquote"; // The original code uses a regular expression to find out how much of the // text *directly before* the selection already was a blockquote: /* if (chunk.before) { chunk.before = chunk.before.replace(/\n?$/, "\n"); } chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/, function (totalMatch) { chunk.startTag = totalMatch; return ""; }); */ // This comes down to: // Go backwards as many lines a possible, such that each line // a) starts with ">", or // b) is almost empty, except for whitespace, or // c) is preceeded by an unbroken chain of non-empty lines // leading up to a line that starts with ">" and at least one more character // and in addition // d) at least one line fulfills a) // // Since this is essentially a backwards-moving regex, it's susceptible to // catstrophic backtracking and can cause the browser to hang; // see e.g. http://meta.stackoverflow.com/questions/9807. // // Hence we replaced this by a simple state machine that just goes through the // lines and checks for a), b), and c). var match = "", leftOver = "", line; if (chunk.before) { var lines = chunk.before.replace(/\n$/, "").split("\n"); var inChain = false; for (var i = 0; i < lines.length; i++) { var good = false; line = lines[i]; inChain = inChain && line.length > 0; // c) any non-empty line continues the chain if (/^>/.test(line)) { // a) good = true; if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain inChain = true; } else if (/^[ \t]*$/.test(line)) { // b) good = true; } else { good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain } if (good) { match += line + "\n"; } else { leftOver += match + line; match = "\n"; } } if (!/(^|\n)>/.test(match)) { // d) leftOver += match; match = ""; } } chunk.startTag = match; chunk.before = leftOver; // end of change if (chunk.after) { chunk.after = chunk.after.replace(/^\n?/, "\n"); } chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/, function (totalMatch) { chunk.endTag = totalMatch; return ""; } ); var replaceBlanksInTags = function (useBracket) { var replacement = useBracket ? "> " : ""; if (chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } if (chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } }; if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) { this.wrap(chunk, SETTINGS.lineLength - 2); chunk.selection = chunk.selection.replace(/^/gm, "> "); replaceBlanksInTags(true); chunk.skipLines(); } else { chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, ""); this.unwrap(chunk); replaceBlanksInTags(false); if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n"); } if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n"); } } chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection); if (!/\n/.test(chunk.selection)) { chunk.selection = chunk.selection.replace(/^(> *)/, function (wholeMatch, blanks) { chunk.startTag += blanks; return ""; }); } }; commandProto.doCode = function (chunk, postProcessing) { var hasTextBefore = /\S[ ]*$/.test(chunk.before); var hasTextAfter = /^[ ]*\S/.test(chunk.after); // Use 'four space' markdown if the selection is on its own // line or is multiline. if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) { chunk.before = chunk.before.replace(/[ ]{4}$/, function (totalMatch) { chunk.selection = totalMatch + chunk.selection; return ""; }); var nLinesBack = 1; var nLinesForward = 1; if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { nLinesBack = 0; } if (/^\n(\t|[ ]{4,})/.test(chunk.after)) { nLinesForward = 0; } chunk.skipLines(nLinesBack, nLinesForward); if (!chunk.selection) { chunk.startTag = " "; chunk.selection = "enter code here"; } else { if (/^[ ]{0,3}\S/m.test(chunk.selection)) { if (/\n/.test(chunk.selection)) chunk.selection = chunk.selection.replace(/^/gm, " "); else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior chunk.before += " "; } else { chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, ""); } } } else { // Use backticks (`) to delimit the code block. chunk.trimWhitespace(); chunk.findTags(/`/, /`/); if (!chunk.startTag && !chunk.endTag) { chunk.startTag = chunk.endTag = "`"; if (!chunk.selection) { chunk.selection = "enter code here"; } } else if (chunk.endTag && !chunk.startTag) { chunk.before += chunk.endTag; chunk.endTag = ""; } else { chunk.startTag = chunk.endTag = ""; } } }; commandProto.doList = function (chunk, postProcessing, isNumberedList) { // These are identical except at the very beginning and end. // Should probably use the regex extension function to make this clearer. var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/; var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/; // The default bullet is a dash but others are possible. // This has nothing to do with the particular HTML bullet, // it's just a markdown bullet. var bullet = "-"; // The number in a numbered list. var num = 1; // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list. var getItemPrefix = function () { var prefix; if (isNumberedList) { prefix = " " + num + ". "; num++; } else { prefix = " " + bullet + " "; } return prefix; }; // Fixes the prefixes of the other list items. var getPrefixedItem = function (itemText) { // The numbering flag is unset when called by autoindent. if (isNumberedList === undefined) { isNumberedList = /^\s*\d/.test(itemText); } // Renumber/bullet the list element. itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm, function (_) { return getItemPrefix(); }); return itemText; }; chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null); if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) { chunk.before += chunk.startTag; chunk.startTag = ""; } if (chunk.startTag) { var hasDigits = /\d+[.]/.test(chunk.startTag); chunk.startTag = ""; chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n"); this.unwrap(chunk); chunk.skipLines(); if (hasDigits) { // Have to renumber the bullet points if this is a numbered list. chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem); } if (isNumberedList == hasDigits) { return; } } var nLinesUp = 1; chunk.before = chunk.before.replace(previousItemsRegex, function (itemText) { if (/^\s*([*+-])/.test(itemText)) { bullet = re.$1; } nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); if (!chunk.selection) { chunk.selection = "List item"; } var prefix = getItemPrefix(); var nLinesDown = 1; chunk.after = chunk.after.replace(nextItemsRegex, function (itemText) { nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); chunk.trimWhitespace(true); chunk.skipLines(nLinesUp, nLinesDown, true); chunk.startTag = prefix; var spaces = prefix.replace(/./g, " "); this.wrap(chunk, SETTINGS.lineLength - spaces.length); chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces); }; commandProto.doHeading = function (chunk, postProcessing) { // Remove leading/trailing whitespace and reduce internal spaces to single spaces. chunk.selection = chunk.selection.replace(/\s+/g, " "); chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, ""); // If we clicked the button with no selected text, we just // make a level 2 hash header around some default text. if (!chunk.selection) { chunk.startTag = "## "; chunk.selection = "Heading"; chunk.endTag = " ##"; return; } var headerLevel = 0; // The existing header level of the selected text. // Remove any existing hash heading markdown and save the header level. chunk.findTags(/#+[ ]*/, /[ ]*#+/); if (/#+/.test(chunk.startTag)) { headerLevel = re.lastMatch.length; } chunk.startTag = chunk.endTag = ""; // Try to get the current header level by looking for - and = in the line // below the selection. chunk.findTags(null, /\s?(-+|=+)/); if (/=+/.test(chunk.endTag)) { headerLevel = 1; } if (/-+/.test(chunk.endTag)) { headerLevel = 2; } // Skip to the next line so we can create the header markdown. chunk.startTag = chunk.endTag = ""; chunk.skipLines(1, 1); // We make a level 2 header if there is no current header. // If there is a header level, we substract one from the header level. // If it's already a level 1 header, it's removed. var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1; if (headerLevelToCreate > 0) { // The button only creates level 1 and 2 underline headers. // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner? var headerChar = headerLevelToCreate >= 2 ? "-" : "="; var len = chunk.selection.length; if (len > SETTINGS.lineLength) { len = SETTINGS.lineLength; } chunk.endTag = "\n"; while (len--) { chunk.endTag += headerChar; } } }; commandProto.doHorizontalRule = function (chunk, postProcessing) { chunk.startTag = "----------\n"; chunk.selection = ""; chunk.skipLines(2, 1, true); } })();
MitchellMcKenna/LifePress
public/scripts/pagedown/Markdown.Editor.js
JavaScript
gpl-3.0
80,757
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Tue Feb 24 12:30:37 EET 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package jtodo.domain (jTODO R1.0 API)</title> <meta name="date" content="2015-02-24"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package jtodo.domain (jTODO R1.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?jtodo/domain/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package jtodo.domain" class="title">Uses of Package<br>jtodo.domain</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#jtodo.domain">jtodo.domain</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#jtodo.managers">jtodo.managers</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#jtodo.ui">jtodo.ui</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="jtodo.domain"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a> used by <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/AbstractListItem.html#jtodo.domain">AbstractListItem</a> <div class="block">Defines items (Task/Category) in a a TaskList</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Category.html#jtodo.domain">Category</a> <div class="block">Category used to separate different Tasks</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Deadline.html#jtodo.domain">Deadline</a> <div class="block">Defines a deadline for a Task</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/ListItemColor.html#jtodo.domain">ListItemColor</a> <div class="block">Defines a highlight color for AbstractListItem.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Month.html#jtodo.domain">Month</a> <div class="block">Defines a month.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Priority.html#jtodo.domain">Priority</a> <div class="block">Priority given to a Task</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Task.html#jtodo.domain">Task</a> <div class="block">Defines a Task that the user wants to accomplish.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="jtodo.managers"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a> used by <a href="../../jtodo/managers/package-summary.html">jtodo.managers</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Category.html#jtodo.managers">Category</a> <div class="block">Category used to separate different Tasks</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Task.html#jtodo.managers">Task</a> <div class="block">Defines a Task that the user wants to accomplish.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="jtodo.ui"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a> used by <a href="../../jtodo/ui/package-summary.html">jtodo.ui</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Category.html#jtodo.ui">Category</a> <div class="block">Category used to separate different Tasks</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../jtodo/domain/class-use/Task.html#jtodo.ui">Task</a> <div class="block">Defines a Task that the user wants to accomplish.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?jtodo/domain/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015. All rights reserved.</small></p> </body> </html>
Ooppa/jTODO
dokumentointi/apidocs/jtodo/domain/package-use.html
HTML
gpl-3.0
8,526
package de.jdellert.iwsa.sequence; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * Symbol table for mapping IPA segments to integers for efficient internal * representation. The first two integers are always used for special symbols: 0 * ~ #: the word boundary symbol 1 ~ -: the gap symbol * */ public class PhoneticSymbolTable implements Serializable { private static final long serialVersionUID = -8825447220839372572L; private String[] idToSymbol; private Map<String, Integer> symbolToID; public PhoneticSymbolTable(Collection<String> symbols) { this.idToSymbol = new String[symbols.size() + 2]; this.symbolToID = new TreeMap<String, Integer>(); idToSymbol[0] = "#"; idToSymbol[1] = "-"; symbolToID.put("#", 0); symbolToID.put("-", 1); int nextID = 2; for (String symbol : symbols) { idToSymbol[nextID] = symbol; symbolToID.put(symbol, nextID); nextID++; } } public Integer toInt(String symbol) { return symbolToID.get(symbol); } public String toSymbol(int id) { return idToSymbol[id]; } public int[] encode(String[] segments) { int[] segmentIDs = new int[segments.length]; for (int idx = 0; idx < segments.length; idx++) { segmentIDs[idx] = symbolToID.get(segments[idx]); } return segmentIDs; } public String[] decode(int[] segmentIDs) { String[] segments = new String[segmentIDs.length]; for (int idx = 0; idx < segmentIDs.length; idx++) { segments[idx] = idToSymbol[segmentIDs[idx]]; } return segments; } public Set<String> getDefinedSymbols() { return new TreeSet<String>(symbolToID.keySet()); } public int getSize() { return idToSymbol.length; } public String toSymbolPair(int symbolPairID) { return "(" + toSymbol(symbolPairID / idToSymbol.length) + "," + toSymbol(symbolPairID % idToSymbol.length) + ")"; } public String toString() { StringBuilder line1 = new StringBuilder(); StringBuilder line2 = new StringBuilder(); for (int i = 0; i < idToSymbol.length; i++) { line1.append(i + "\t"); line2.append(idToSymbol[i] + "\t"); } return line1 + "\n" + line2; } }
jdellert/iwsa
src/de/jdellert/iwsa/sequence/PhoneticSymbolTable.java
Java
gpl-3.0
2,258
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('hq-category', { // Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'] }); test('it renders', function(assert) { assert.expect(2); // Creates the component instance var component = this.subject(); assert.equal(component._state, 'preRender'); // Renders the component to the page this.render(); assert.equal(component._state, 'inDOM'); });
hugoruscitti/huayra-quotes
tests/unit/components/hq-category-test.js
JavaScript
gpl-3.0
487
/* * GNU LESSER GENERAL PUBLIC LICENSE * Version 3, 29 June 2007 * * Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> * Everyone is permitted to copy and distribute verbatim copies * of this license document, but changing it is not allowed. * * You can view LICENCE file for details. * * @author The Dragonet Team */ package org.dragonet.proxy.network.translator; import java.util.Iterator; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.spacehq.mc.protocol.data.message.Message; public final class MessageTranslator { public static String translate(Message message) { String ret = message.getFullText(); /* * It is a JSON message? */ try { /* * Do not ask me why, but json strings has colors. * Changing this allows colors in plain texts! yay! */ JSONObject jObject = null; if (message.getFullText().startsWith("{") && message.getFullText().endsWith("}")) { jObject = new JSONObject(message.getFullText()); } else { jObject = new JSONObject(message.toJsonString()); } /* * Let's iterate! */ ret = handleKeyObject(jObject); } catch (JSONException e) { /* * If any exceptions happens, then: * * The JSON message is buggy or * * It isn't a JSON message * * So, if any exceptions happens, we send the original message */ } return ret; } public static String handleKeyObject(JSONObject jObject) throws JSONException { String chatMessage = ""; Iterator<String> iter = jObject.keys(); while (iter.hasNext()) { String key = iter.next(); try { if (key.equals("color")) { String color = jObject.getString(key); if (color.equals("light_purple")) { chatMessage = chatMessage + "§d"; } if (color.equals("blue")) { chatMessage = chatMessage + "§9"; } if (color.equals("aqua")) { chatMessage = chatMessage + "§b"; } if (color.equals("gold")) { chatMessage = chatMessage + "§6"; } if (color.equals("green")) { chatMessage = chatMessage + "§a"; } if (color.equals("white")) { chatMessage = chatMessage + "§f"; } if (color.equals("yellow")) { chatMessage = chatMessage + "§e"; } if (color.equals("gray")) { chatMessage = chatMessage + "§7"; } if (color.equals("red")) { chatMessage = chatMessage + "§c"; } if (color.equals("black")) { chatMessage = chatMessage + "§0"; } if (color.equals("dark_green")) { chatMessage = chatMessage + "§2"; } if (color.equals("dark_gray")) { chatMessage = chatMessage + "§8"; } if (color.equals("dark_red")) { chatMessage = chatMessage + "§4"; } if (color.equals("dark_blue")) { chatMessage = chatMessage + "§1"; } if (color.equals("dark_aqua")) { chatMessage = chatMessage + "§3"; } if (color.equals("dark_purple")) { chatMessage = chatMessage + "§5"; } } if (key.equals("bold")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§l"; } } if (key.equals("italic")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§o"; } } if (key.equals("underlined")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§n"; } } if (key.equals("strikethrough")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§m"; } } if (key.equals("obfuscated")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§k"; } } if (key.equals("text")) { /* * We only need the text message from the JSON. */ String jsonMessage = jObject.getString(key); chatMessage = chatMessage + jsonMessage; continue; } if (jObject.get(key) instanceof JSONArray) { chatMessage += handleKeyArray(jObject.getJSONArray(key)); } if (jObject.get(key) instanceof JSONObject) { chatMessage += handleKeyObject(jObject.getJSONObject(key)); } } catch (JSONException e) { } } return chatMessage; } public static String handleKeyArray(JSONArray jObject) throws JSONException { String chatMessage = ""; JSONObject jsonObject = jObject.toJSONObject(jObject); Iterator<String> iter = jsonObject.keys(); while (iter.hasNext()) { String key = iter.next(); try { /* * We only need the text message from the JSON. */ if (key.equals("text")) { String jsonMessage = jsonObject.getString(key); chatMessage = chatMessage + jsonMessage; continue; } if (jsonObject.get(key) instanceof JSONArray) { handleKeyArray(jsonObject.getJSONArray(key)); } if (jsonObject.get(key) instanceof JSONObject) { handleKeyObject(jsonObject.getJSONObject(key)); } } catch (JSONException e) { } } return chatMessage; } }
WeaveMN/DragonProxy
src/main/java/org/dragonet/proxy/network/translator/MessageTranslator.java
Java
gpl-3.0
7,266
// BOINC Sentinels. // https://projects.romwnet.org/boincsentinels // Copyright (C) 2009-2014 Rom Walton // // BOINC Sentinels is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC Sentinels is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC Sentinels. If not, see <http://www.gnu.org/licenses/>. // #ifndef _NOTIFICATIONMANAGER_H_ #define _NOTIFICATIONMANAGER_H_ class CNotificationManager: public wxObject { DECLARE_NO_COPY_CLASS(CNotificationManager) public: CNotificationManager(); virtual ~CNotificationManager(); bool IsRead(CBSLNotification& bslNotification); bool IsDeleted(CBSLNotification& bslNotification); bool MarkRead(CBSLNotification& bslNotification, bool bValue); bool MarkDeleted(CBSLNotification& bslNotification, bool bValue); private: wxString DeterminePath(CBSLNotification& bslNotification); bool GetConfigValue(wxString strSubComponent, wxString strValueName, long dwDefaultValue, long* pdwValue); bool SetConfigValue(wxString strSubComponent, wxString strValueName, long dwValue); }; #endif
romw/boincsentinels
valkyrie/NotificationManager.h
C
gpl-3.0
1,549
/* * LBFGS.java * * Copyright (C) 2016 Pavel Prokhorov ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.interactiverobotics.ml.optimization; import static org.interactiverobotics.ml.optimization.OptimizationResult.Status.*; import org.apache.log4j.Logger; import org.interactiverobotics.math.Vector; import java.util.Objects; /** * Limited-memory BFGS. * * https://en.wikipedia.org/wiki/Limited-memory_BFGS * * Liu, D. C.; Nocedal, J. (1989). "On the Limited Memory Method for Large Scale Optimization". * Mathematical Programming B. 45 (3): 503–528. doi:10.1007/BF01589116. * */ public final class LBFGS extends AbstractOptimizer implements Optimizer { private static final Logger LOG = Logger.getLogger(LBFGS.class); public LBFGS(final OptimizableFunction function) { this.function = Objects.requireNonNull(function); } private final OptimizableFunction function; /** * Maximum number of iterations. */ private int maxIterations = 100; /** * The number of corrections to approximate the inverse Hessian matrix. */ private int m = 6; /** * Epsilon for convergence test. * Controls the accuracy of with which the solution is to be found. */ private double epsilon = 1.0E-5; /** * Distance (in iterations) to calculate the rate of decrease of the function. * Used in delta convergence test. */ private int past = 3; /** * Minimum rate of decrease of the function. * Used in delta convergence test. */ private double delta = 1.0E-5; /** * Maximum number of line search iterations. */ private int maxLineSearchIterations = 100; /** * Continue optimization if line search returns {@code MAX_ITERATION_REACHED}. */ private boolean continueOnMaxLineSearchIterations = false; public int getMaxIterations() { return maxIterations; } public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public int getM() { return m; } public void setM(int m) { this.m = m; } public double getEpsilon() { return epsilon; } public void setEpsilon(double epsilon) { this.epsilon = epsilon; } public int getPast() { return past; } public void setPast(int past) { this.past = past; } public double getDelta() { return delta; } public void setDelta(double delta) { this.delta = delta; } public int getMaxLineSearchIterations() { return maxLineSearchIterations; } public void setMaxLineSearchIterations(int maxLineSearchIterations) { this.maxLineSearchIterations = maxLineSearchIterations; } public boolean isContinueOnMaxLineSearchIterations() { return continueOnMaxLineSearchIterations; } public void setContinueOnMaxLineSearchIterations(boolean continueOnMaxLineSearchIterations) { this.continueOnMaxLineSearchIterations = continueOnMaxLineSearchIterations; } @Override public OptimizationResult optimize() { LOG.debug("Limited-memory BFGS optimize..."); final BacktrackingLineSearch lineSearch = new BacktrackingLineSearch(function); lineSearch.setMaxIterations(maxLineSearchIterations); final State[] states = new State[m]; for (int i = 0; i < m; i ++) { states[i] = new State(); } int currentStateIndex = 0; final double[] pastValues; if (past > 0) { pastValues = new double[past]; pastValues[0] = function.getValue(); } else { pastValues = null; } Vector parameters = function.getParameters(); Vector gradient = function.getValueGradient(); final double initialGradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0); LOG.debug("Initial gradient norm = " + initialGradientNorm); if (initialGradientNorm <= epsilon) { LOG.debug("Already minimized"); return new OptimizationResult(ALREADY_MINIMIZED, parameters, function.getValue(), 0); } Vector direction = gradient.copy().neg(); double step = Vector.dotProduct(direction, direction); Vector prevParameters, prevGradient; OptimizationResult.Status status = MAX_ITERATION_REACHED; int iteration; for (iteration = 1; iteration <= maxIterations; iteration ++) { LOG.debug("Iteration " + iteration); // save previous Parameters and Gradient prevParameters = parameters.copy(); prevGradient = gradient.copy(); // search for optimal Step LOG.debug("Direction: " + direction + " Step = " + step); lineSearch.setDirection(direction); lineSearch.setInitialStep(step); final OptimizationResult lineSearchResult = lineSearch.optimize(); if (!lineSearchResult.hasConverged()) { LOG.error("Line search not converged: " + lineSearchResult.getStatus()); final boolean continueOptimization = (lineSearchResult.getStatus() == MAX_ITERATION_REACHED) && continueOnMaxLineSearchIterations; if (!continueOptimization) { // step back function.setParameters(prevParameters); status = lineSearchResult.getStatus(); break; } } parameters = function.getParameters(); gradient = function.getValueGradient(); final double value = function.getValue(); final boolean stop = fireOptimizerStep(parameters, value, direction, iteration); if (stop) { LOG.debug("Stop"); status = STOP; break; } // test for convergence final double gradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0); LOG.debug("Gradient norm = " + gradientNorm); if (gradientNorm <= epsilon) { LOG.debug("Success"); status = SUCCESS; break; } // delta convergence test if (past > 0) { if (iteration > past) { // relative improvement from the past final double rate = (pastValues[iteration % past] - value) / value; if (rate < delta) { status = STOP; break; } } pastValues[iteration % past] = value; } // update S and Y final State currentState = states[currentStateIndex]; currentState.s = parameters.copy().sub(prevParameters); currentState.y = gradient.copy().sub(prevGradient); final double ys = Vector.dotProduct(currentState.y, currentState.s); final double yy = Vector.dotProduct(currentState.y, currentState.y); currentState.ys = ys; currentStateIndex = (currentStateIndex + 1) % m; // update Direction direction = gradient.copy(); int availableStates = Math.min(iteration, m); LOG.debug("Available states = " + availableStates); int j = currentStateIndex; for (int i = 0; i < availableStates; i ++) { j = (j + m - 1) % m; final State t = states[j]; t.alpha = Vector.dotProduct(t.s, direction) / t.ys; direction.sub(t.y.copy().scale(t.alpha)); } direction.scale(ys / yy); for (int i = 0; i < availableStates; i ++) { final State t = states[j]; final double beta = Vector.dotProduct(t.y, direction) / t.ys; direction.add(t.s.copy().scale(t.alpha - beta)); j = (j + 1) % m; } direction.neg(); step = 1.0; } final Vector finalParameters = function.getParameters(); final double finalValue = function.getValue(); LOG.debug("Status = " + status + " Final Value = " + finalValue + " Parameters: " + finalParameters + " Iteration = " + iteration); return new OptimizationResult(status, finalParameters, finalValue, iteration); } private static class State { public double alpha; public Vector s; public Vector y; public double ys; } }
pavelvpster/Math
src/main/java/org/interactiverobotics/ml/optimization/LBFGS.java
Java
gpl-3.0
9,413
package cn.bjsxt.oop.staticInitBlock; public class Parent001 /*extends Object*/ { static int aa; static { System.out.println(" 静态初始化Parent001"); aa=200; } }
yangweijun213/Java
J2SE300/28_51OO/src/cn/bjsxt/oop/staticInitBlock/Parent001.java
Java
gpl-3.0
184
using Fallout4Checklist.Entities; namespace Fallout4Checklist.ViewModels { public class WeaponStatsViewModel { public WeaponStatsViewModel(Weapon weapon) { Weapon = weapon; } public Weapon Weapon { get; set; } } }
street1030/Fallout4Checklist
Fallout4Checklist/ViewModels/AreaDetail/WeaponStatsViewModel.cs
C#
gpl-3.0
275
import inspect import re import pytest from robottelo.logging import collection_logger as logger IMPORTANCE_LEVELS = [] def pytest_addoption(parser): """Add CLI options related to Testimony token based mark collection""" parser.addoption( '--importance', help='Comma separated list of importance levels to include in test collection', ) parser.addoption( '--component', help='Comma separated list of component names to include in test collection', ) parser.addoption( '--assignee', help='Comma separated list of assignees to include in test collection', ) def pytest_configure(config): """Register markers related to testimony tokens""" for marker in [ 'importance: CaseImportance testimony token, use --importance to filter', 'component: Component testimony token, use --component to filter', 'assignee: Assignee testimony token, use --assignee to filter', ]: config.addinivalue_line("markers", marker) component_regex = re.compile( # To match :CaseComponent: FooBar r'\s*:CaseComponent:\s*(?P<component>\S*)', re.IGNORECASE, ) importance_regex = re.compile( # To match :CaseImportance: Critical r'\s*:CaseImportance:\s*(?P<importance>\S*)', re.IGNORECASE, ) assignee_regex = re.compile( # To match :Assignee: jsmith r'\s*:Assignee:\s*(?P<assignee>\S*)', re.IGNORECASE, ) @pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(session, items, config): """Add markers for testimony tokens""" # split the option string and handle no option, single option, multiple # config.getoption(default) doesn't work like you think it does, hence or '' importance = [i for i in (config.getoption('importance') or '').split(',') if i != ''] component = [c for c in (config.getoption('component') or '').split(',') if c != ''] assignee = [a for a in (config.getoption('assignee') or '').split(',') if a != ''] selected = [] deselected = [] logger.info('Processing test items to add testimony token markers') for item in items: if item.nodeid.startswith('tests/robottelo/'): # Unit test, no testimony markers continue # apply the marks for importance, component, and assignee # Find matches from docstrings starting at smallest scope item_docstrings = [ d for d in map(inspect.getdoc, (item.function, getattr(item, 'cls', None), item.module)) if d is not None ] item_mark_names = [m.name for m in item.iter_markers()] for docstring in item_docstrings: # Add marker starting at smallest docstring scope # only add the mark if it hasn't already been applied at a lower scope doc_component = component_regex.findall(docstring) if doc_component and 'component' not in item_mark_names: item.add_marker(pytest.mark.component(doc_component[0])) doc_importance = importance_regex.findall(docstring) if doc_importance and 'importance' not in item_mark_names: item.add_marker(pytest.mark.importance(doc_importance[0])) doc_assignee = assignee_regex.findall(docstring) if doc_assignee and 'assignee' not in item_mark_names: item.add_marker(pytest.mark.assignee(doc_assignee[0])) # exit early if no filters were passed if importance or component or assignee: # Filter test collection based on CLI options for filtering # filters should be applied together # such that --component Repository --importance Critical --assignee jsmith # only collects tests which have all three of these marks # https://github.com/pytest-dev/pytest/issues/1373 Will make this way easier # testimony requires both importance and component, this will blow up if its forgotten importance_marker = item.get_closest_marker('importance').args[0] if importance and importance_marker not in importance: logger.debug( f'Deselected test {item.nodeid} due to "--importance {importance}",' f'test has importance mark: {importance_marker}' ) deselected.append(item) continue component_marker = item.get_closest_marker('component').args[0] if component and component_marker not in component: logger.debug( f'Deselected test {item.nodeid} due to "--component {component}",' f'test has component mark: {component_marker}' ) deselected.append(item) continue assignee_marker = item.get_closest_marker('assignee').args[0] if assignee and assignee_marker not in assignee: logger.debug( f'Deselected test {item.nodeid} due to "--assignee {assignee}",' f'test has assignee mark: {assignee_marker}' ) deselected.append(item) continue selected.append(item) # selected will be empty if no filter option was passed, defaulting to full items list items[:] = selected if deselected else items config.hook.pytest_deselected(items=deselected)
jyejare/robottelo
pytest_plugins/testimony_markers.py
Python
gpl-3.0
5,447
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE AS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa.Impl.Uql { /** * @author Taha BEN SALAH <[email protected]> * @creationdate 11/19/12 7:22 PM */ public interface ExpressionDeclarationList { System.Collections.Generic.IList<Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration> GetExportedDeclarations(); void ExportDeclaration(string name, Net.TheVpc.Upa.Impl.Uql.DecObjectType type, object referrerName, object referrerParentId); System.Collections.Generic.IList<Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration> GetDeclarations(string alias); Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration GetDeclaration(string name); } }
thevpc/upa
upa-impl-core/src/main/csharp/Sources/Auto/Uql/ExpressionDeclarationList.cs
C#
gpl-3.0
1,258
/* * Copyright (C) 2018 Johan Dykstrom * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package se.dykstrom.jcc.common.ast; import java.util.Objects; /** * Abstract base class for different types of jump statements, such as GOTO or GOSUB. * * @author Johan Dykstrom */ public abstract class AbstractJumpStatement extends AbstractNode implements Statement { private final String jumpLabel; protected AbstractJumpStatement(int line, int column, String jumpLabel) { super(line, column); this.jumpLabel = jumpLabel; } /** * Returns the label to jump to. */ public String getJumpLabel() { return jumpLabel; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractJumpStatement that = (AbstractJumpStatement) o; return Objects.equals(jumpLabel, that.jumpLabel); } @Override public int hashCode() { return Objects.hash(jumpLabel); } }
dykstrom/jcc
src/main/java/se/dykstrom/jcc/common/ast/AbstractJumpStatement.java
Java
gpl-3.0
1,652
class Block { constructor(x, y, width, colour) { this.x = x; this.y = y; this.width = width; this.colour = colour; this.occupied = false; } draw() { fill(this.colour); rect(this.x, this.y, this.width, this.width); } }
DanielGilchrist/p5.js-snake
classes/block.js
JavaScript
gpl-3.0
255
/* * Copyright (C) 2012 MineStar.de * * This file is part of Contao. * * Contao is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * Contao is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Contao. If not, see <http://www.gnu.org/licenses/>. */ package de.minestar.contao.manager; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.bukkit.entity.Player; import de.minestar.contao.core.Settings; import de.minestar.contao.data.ContaoGroup; import de.minestar.contao.data.User; import de.minestar.core.MinestarCore; import de.minestar.core.units.MinestarPlayer; public class PlayerManager { private Map<String, User> onlineUserMap = new HashMap<String, User>(); private Map<ContaoGroup, TreeSet<User>> groupMap = new HashMap<ContaoGroup, TreeSet<User>>(); public PlayerManager() { for (ContaoGroup cGroup : ContaoGroup.values()) { groupMap.put(cGroup, new TreeSet<User>()); } } public void addUser(User user) { onlineUserMap.put(user.getMinecraftNickname().toLowerCase(), user); groupMap.get(user.getGroup()).add(user); } public void removeUser(String userName) { User user = onlineUserMap.remove(userName.toLowerCase()); groupMap.get(user.getGroup()).remove(user); } public User getUser(Player player) { return getUser(player.getName()); } public User getUser(String userName) { return onlineUserMap.get(userName.toLowerCase()); } public String getGroupAsString(ContaoGroup contaoGroup) { Set<User> groupMember = groupMap.get(contaoGroup); if (groupMember.isEmpty()) return null; StringBuilder sBuilder = new StringBuilder(); // BUILD HEAD sBuilder.append(Settings.getColor(contaoGroup)); sBuilder.append(contaoGroup.getDisplayName()); sBuilder.append('('); sBuilder.append(getGroupSize(contaoGroup)); sBuilder.append(") : "); // ADD USER for (User user : groupMember) { sBuilder.append(user.getMinecraftNickname()); sBuilder.append(", "); } // DELETE THE LAST COMMATA sBuilder.delete(0, sBuilder.length() - 2); return sBuilder.toString(); } public int getGroupSize(ContaoGroup contaoGroup) { return groupMap.get(contaoGroup).size(); } public void changeGroup(User user, ContaoGroup newGroup) { groupMap.get(user.getGroup()).remove(user); groupMap.get(newGroup).add(user); setGroup(user, newGroup); } public void setGroup(User user, ContaoGroup newGroup) { MinestarPlayer mPlayer = MinestarCore.getPlayer(user.getMinecraftNickname()); if (mPlayer != null) { mPlayer.setGroup(newGroup.getMinestarGroup()); } } public boolean canBeFree(User probeUser) { // TODO: Implement requirements return false; } }
Minestar/Contao
src/main/java/de/minestar/contao/manager/PlayerManager.java
Java
gpl-3.0
3,520
package org.grovecity.drizzlesms.jobs.requirements; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import org.grovecity.drizzlesms.service.KeyCachingService; import org.whispersystems.jobqueue.requirements.RequirementListener; import org.whispersystems.jobqueue.requirements.RequirementProvider; public class MasterSecretRequirementProvider implements RequirementProvider { private final BroadcastReceiver newKeyReceiver; private RequirementListener listener; public MasterSecretRequirementProvider(Context context) { this.newKeyReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (listener != null) { listener.onRequirementStatusChanged(); } } }; IntentFilter filter = new IntentFilter(KeyCachingService.NEW_KEY_EVENT); context.registerReceiver(newKeyReceiver, filter, KeyCachingService.KEY_PERMISSION, null); } @Override public void setListener(RequirementListener listener) { this.listener = listener; } }
DrizzleSuite/DrizzleSMS
src/org/grovecity/drizzlesms/jobs/requirements/MasterSecretRequirementProvider.java
Java
gpl-3.0
1,144
/* * Copyright (C) 2017 Josua Frank * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package dfmaster.general; import dfmaster.json.JSONValue; import dfmaster.xml.XMLDocument; import dfmaster.xml.XMLElement; /** * This is the abstract type for all data that can be created or parsed. This * could be as example a {@link JSONValue}, a {@link XMLDocument} or a * {@link XMLElement} * * @author Josua Frank */ public class AData { }
Sharknoon/dfMASTER
dfMASTER/src/main/java/dfmaster/general/AData.java
Java
gpl-3.0
1,113
<?php namespace EasyAjax; /** * EasyAjax\FrontInterface interface * * @package EasyAjax * @author Giuseppe Mazzapica * */ interface FrontInterface { /** * Check the request for valid EasyAjax * * @return bool true if current request is a valid EasyAjax ajax request * @access public */ function is_valid_ajax(); /** * Setup the EasyAjax Instance * * @param object $scope the object scope that will execute action if given * @param string $where can be 'priv', 'nopriv' or 'both'. Limit actions to logged in users or not * @param array $allowed list of allowed actions * @return null * @access public */ function setup( $scope = '', $where = '', $allowed = [ ] ); /** * Check the request and launch EasyAjax\Proxy setup if required * * @return null * @access public */ function register(); }
Giuseppe-Mazzapica/EasyAjax
src/EasyAjax/FrontInterface.php
PHP
gpl-3.0
915
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_Workflows_Workflow_Step_General { /// <summary> /// editElem control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Workflows_Controls_UI_WorkflowStep_Edit editElem; }
CCChapel/ccchapel.com
CMS/CMSModules/Workflows/Workflow_Step_General.aspx.designer.cs
C#
gpl-3.0
731
package io.valhala.javamon.pokemon.skeleton; import io.valhala.javamon.pokemon.Pokemon; import io.valhala.javamon.pokemon.type.Type; public abstract class Paras extends Pokemon { public Paras() { super("Paras", 35, 70, 55, 25, 55, true, 46,Type.BUG,Type.GRASS); // TODO Auto-generated constructor stub } }
mirgantrophy/Pokemon
src/io/valhala/javamon/pokemon/skeleton/Paras.java
Java
gpl-3.0
316
define(['backbone', 'underscore'], function (Backbone, _) { return Backbone.Model.extend({ idAttribute: 'username', defaults: { persona: { personaPnombre: '', personaSnombre: '', personaApaterno: '', personaAmaterno: '', dni: '' } }, validate: function (attrs, options) { console.log('persona', attrs.persona); if (_.isUndefined(attrs.persona)) { return { field: 'persona', error: 'Debe definir una persona' }; } if (_.isUndefined(attrs.persona.personaDni) || _.isEmpty(attrs.persona.personaDni.trim()) || attrs.persona.personaDni.trim().length != 8) { return { field: 'persona-personaDni', error: 'El dni es un campo obligatorio y debe tener 8 caracteres.' }; } if (_.isUndefined(attrs.persona.personaPnombre) || _.isEmpty(attrs.persona.personaPnombre.trim())) { return { field: 'persona-personaPnombre', error: 'El primer nombre es un campo obligatorio.' }; } if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) { return { field: 'persona-personaApaterno', error: 'El apellido paterno es un campo obligatorio.' }; } if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) { return { field: 'persona-personaAmaterno', error: 'El apellido materno es un campo obligatorio.' }; } } }); });
jaxkodex/edu-stat
src/main/webapp/resources/js/app/models/docente-model.js
JavaScript
gpl-3.0
1,442
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009-2010 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_PRODUCTBASE_H #define EIGEN_PRODUCTBASE_H namespace Eigen { /** \class ProductBase * \ingroup Core_Module * */ namespace internal { template<typename Derived, typename _Lhs, typename _Rhs> struct traits<ProductBase<Derived,_Lhs,_Rhs> > { typedef MatrixXpr XprKind; typedef typename remove_all<_Lhs>::type Lhs; typedef typename remove_all<_Rhs>::type Rhs; typedef typename scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType Scalar; typedef typename promote_storage_type<typename traits<Lhs>::StorageKind, typename traits<Rhs>::StorageKind>::ret StorageKind; typedef typename promote_index_type<typename traits<Lhs>::Index, typename traits<Rhs>::Index>::type Index; enum { RowsAtCompileTime = traits<Lhs>::RowsAtCompileTime, ColsAtCompileTime = traits<Rhs>::ColsAtCompileTime, MaxRowsAtCompileTime = traits<Lhs>::MaxRowsAtCompileTime, MaxColsAtCompileTime = traits<Rhs>::MaxColsAtCompileTime, Flags = (MaxRowsAtCompileTime==1 ? RowMajorBit : 0) | EvalBeforeNestingBit | EvalBeforeAssigningBit | NestByRefBit, // Note that EvalBeforeNestingBit and NestByRefBit // are not used in practice because nested is overloaded for products CoeffReadCost = 0 // FIXME why is it needed ? }; }; } #define EIGEN_PRODUCT_PUBLIC_INTERFACE(Derived) \ typedef ProductBase<Derived, Lhs, Rhs > Base; \ EIGEN_DENSE_PUBLIC_INTERFACE(Derived) \ typedef typename Base::LhsNested LhsNested; \ typedef typename Base::_LhsNested _LhsNested; \ typedef typename Base::LhsBlasTraits LhsBlasTraits; \ typedef typename Base::ActualLhsType ActualLhsType; \ typedef typename Base::_ActualLhsType _ActualLhsType; \ typedef typename Base::RhsNested RhsNested; \ typedef typename Base::_RhsNested _RhsNested; \ typedef typename Base::RhsBlasTraits RhsBlasTraits; \ typedef typename Base::ActualRhsType ActualRhsType; \ typedef typename Base::_ActualRhsType _ActualRhsType; \ using Base::m_lhs; \ using Base::m_rhs; template<typename Derived, typename Lhs, typename Rhs> class ProductBase : public MatrixBase<Derived> { public: typedef MatrixBase<Derived> Base; EIGEN_DENSE_PUBLIC_INTERFACE(ProductBase) typedef typename Lhs::Nested LhsNested; typedef typename internal::remove_all<LhsNested>::type _LhsNested; typedef internal::blas_traits<_LhsNested> LhsBlasTraits; typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; typedef typename internal::remove_all<ActualLhsType>::type _ActualLhsType; typedef typename internal::traits<Lhs>::Scalar LhsScalar; typedef typename Rhs::Nested RhsNested; typedef typename internal::remove_all<RhsNested>::type _RhsNested; typedef internal::blas_traits<_RhsNested> RhsBlasTraits; typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; typedef typename internal::remove_all<ActualRhsType>::type _ActualRhsType; typedef typename internal::traits<Rhs>::Scalar RhsScalar; // Diagonal of a product: no need to evaluate the arguments because they are going to be evaluated only once typedef CoeffBasedProduct<LhsNested, RhsNested, 0> FullyLazyCoeffBaseProductType; public: typedef typename Base::PlainObject PlainObject; ProductBase(const Lhs& a_lhs, const Rhs& a_rhs) : m_lhs(a_lhs), m_rhs(a_rhs) { eigen_assert(a_lhs.cols() == a_rhs.rows() && "invalid matrix product" && "if you wanted a coeff-wise or a dot product use the respective explicit functions"); } inline Index rows() const { return m_lhs.rows(); } inline Index cols() const { return m_rhs.cols(); } template<typename Dest> inline void evalTo(Dest& dst) const { dst.setZero(); scaleAndAddTo(dst,Scalar(1)); } template<typename Dest> inline void addTo(Dest& dst) const { scaleAndAddTo(dst,Scalar(1)); } template<typename Dest> inline void subTo(Dest& dst) const { scaleAndAddTo(dst,Scalar(-1)); } template<typename Dest> inline void scaleAndAddTo(Dest& dst,Scalar alpha) const { derived().scaleAndAddTo(dst,alpha); } const _LhsNested& lhs() const { return m_lhs; } const _RhsNested& rhs() const { return m_rhs; } // Implicit conversion to the nested type (trigger the evaluation of the product) operator const PlainObject& () const { m_result.resize(m_lhs.rows(), m_rhs.cols()); derived().evalTo(m_result); return m_result; } const Diagonal<const FullyLazyCoeffBaseProductType,0> diagonal() const { return FullyLazyCoeffBaseProductType(m_lhs, m_rhs); } template<int Index> const Diagonal<FullyLazyCoeffBaseProductType,Index> diagonal() const { return FullyLazyCoeffBaseProductType(m_lhs, m_rhs); } const Diagonal<FullyLazyCoeffBaseProductType,Dynamic> diagonal(Index index) const { return FullyLazyCoeffBaseProductType(m_lhs, m_rhs).diagonal(index); } // restrict coeff accessors to 1x1 expressions. No need to care about mutators here since this isnt a Lvalue expression typename Base::CoeffReturnType coeff(Index row, Index col) const { #ifdef EIGEN2_SUPPORT return lhs().row(row).cwiseProduct(rhs().col(col).transpose()).sum(); #else EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) eigen_assert(this->rows() == 1 && this->cols() == 1); Matrix<Scalar,1,1> result = *this; return result.coeff(row,col); #endif } typename Base::CoeffReturnType coeff(Index i) const { EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) eigen_assert(this->rows() == 1 && this->cols() == 1); Matrix<Scalar,1,1> result = *this; return result.coeff(i); } const Scalar& coeffRef(Index row, Index col) const { EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) eigen_assert(this->rows() == 1 && this->cols() == 1); return derived().coeffRef(row,col); } const Scalar& coeffRef(Index i) const { EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) eigen_assert(this->rows() == 1 && this->cols() == 1); return derived().coeffRef(i); } protected: LhsNested m_lhs; RhsNested m_rhs; mutable PlainObject m_result; }; // here we need to overload the nested rule for products // such that the nested type is a const reference to a plain matrix namespace internal { template<typename Lhs, typename Rhs, int Mode, int N, typename PlainObject> struct nested<GeneralProduct<Lhs,Rhs,Mode>, N, PlainObject> { typedef PlainObject const& type; }; } template<typename NestedProduct> class ScaledProduct; // Note that these two operator* functions are not defined as member // functions of ProductBase, because, otherwise we would have to // define all overloads defined in MatrixBase. Furthermore, Using // "using Base::operator*" would not work with MSVC. // // Also note that here we accept any compatible scalar types template<typename Derived,typename Lhs,typename Rhs> const ScaledProduct<Derived> operator*(const ProductBase<Derived,Lhs,Rhs>& prod, typename Derived::Scalar x) { return ScaledProduct<Derived>(prod.derived(), x); } template<typename Derived,typename Lhs,typename Rhs> typename internal::enable_if<!internal::is_same<typename Derived::Scalar,typename Derived::RealScalar>::value, const ScaledProduct<Derived> >::type operator*(const ProductBase<Derived,Lhs,Rhs>& prod, const typename Derived::RealScalar& x) { return ScaledProduct<Derived>(prod.derived(), x); } template<typename Derived,typename Lhs,typename Rhs> const ScaledProduct<Derived> operator*(typename Derived::Scalar x,const ProductBase<Derived,Lhs,Rhs>& prod) { return ScaledProduct<Derived>(prod.derived(), x); } template<typename Derived,typename Lhs,typename Rhs> typename internal::enable_if<!internal::is_same<typename Derived::Scalar,typename Derived::RealScalar>::value, const ScaledProduct<Derived> >::type operator*(const typename Derived::RealScalar& x,const ProductBase<Derived,Lhs,Rhs>& prod) { return ScaledProduct<Derived>(prod.derived(), x); } namespace internal { template<typename NestedProduct> struct traits<ScaledProduct<NestedProduct> > : traits<ProductBase<ScaledProduct<NestedProduct>, typename NestedProduct::_LhsNested, typename NestedProduct::_RhsNested> > { typedef typename traits<NestedProduct>::StorageKind StorageKind; }; } template<typename NestedProduct> class ScaledProduct : public ProductBase<ScaledProduct<NestedProduct>, typename NestedProduct::_LhsNested, typename NestedProduct::_RhsNested> { public: typedef ProductBase<ScaledProduct<NestedProduct>, typename NestedProduct::_LhsNested, typename NestedProduct::_RhsNested> Base; typedef typename Base::Scalar Scalar; typedef typename Base::PlainObject PlainObject; // EIGEN_PRODUCT_PUBLIC_INTERFACE(ScaledProduct) ScaledProduct(const NestedProduct& prod, Scalar x) : Base(prod.lhs(),prod.rhs()), m_prod(prod), m_alpha(x) {} template<typename Dest> inline void evalTo(Dest& dst) const { dst.setZero(); scaleAndAddTo(dst, Scalar(1)); } template<typename Dest> inline void addTo(Dest& dst) const { scaleAndAddTo(dst, Scalar(1)); } template<typename Dest> inline void subTo(Dest& dst) const { scaleAndAddTo(dst, Scalar(-1)); } template<typename Dest> inline void scaleAndAddTo(Dest& dst,Scalar a_alpha) const { m_prod.derived().scaleAndAddTo(dst,a_alpha * m_alpha); } const Scalar& alpha() const { return m_alpha; } protected: const NestedProduct& m_prod; Scalar m_alpha; }; /** \internal * Overloaded to perform an efficient C = (A*B).lazy() */ template<typename Derived> template<typename ProductDerived, typename Lhs, typename Rhs> Derived& MatrixBase<Derived>::lazyAssign(const ProductBase<ProductDerived, Lhs,Rhs>& other) { other.derived().evalTo(derived()); return derived(); } } // end namespace Eigen #endif // EIGEN_PRODUCTBASE_H
anders-dc/cppfem
eigen/Eigen/src/Core/ProductBase.h
C
gpl-3.0
10,519
package de.unikiel.inf.comsys.neo4j.inference.sail; /* * #%L * neo4j-sparql-extension * %% * Copyright (C) 2014 Niclas Hoyer * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import de.unikiel.inf.comsys.neo4j.inference.QueryRewriter; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.parser.ParsedBooleanQuery; import org.openrdf.repository.sail.SailBooleanQuery; import org.openrdf.repository.sail.SailRepositoryConnection; /** * A subclass of {@link SailBooleanQuery} with a public constructor to * pass in a boolean query containing a tuple expression. * * The original constructor of {@link SailBooleanQuery} is protected, thus * it is not possible to create a new boolean query from a parsed query * that is used to create a query from a {@link TupleExpr}. * * @see QueryRewriter */ public class SailBooleanExprQuery extends SailBooleanQuery { public SailBooleanExprQuery(ParsedBooleanQuery booleanQuery, SailRepositoryConnection sailConnection) { super(booleanQuery, sailConnection); } }
niclashoyer/neo4j-sparql-extension
src/main/java/de/unikiel/inf/comsys/neo4j/inference/sail/SailBooleanExprQuery.java
Java
gpl-3.0
1,670
#!/usr/bin/perl # Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, # Circulation and User's Management. It's written in Perl, and uses Apache2 # Web-Server, MySQL database and Sphinx 2 indexing. # Copyright (C) 2009-2015 Grupo de desarrollo de Meran CeSPI-UNLP # <[email protected]> # # This file is part of Meran. # # Meran is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Meran is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Meran. If not, see <http://www.gnu.org/licenses/>. use C4::AR::Nivel3; use C4::Context; use C4::Modelo::CatRegistroMarcN1; use C4::Modelo::CatRegistroMarcN1::Manager; use C4::Modelo::CatRegistroMarcN2; use C4::Modelo::CatRegistroMarcN2::Manager; use C4::Modelo::CatRegistroMarcN3; use C4::Modelo::CatRegistroMarcN3::Manager; my $ui = $ARGV[0] || "DEO"; my $tipo = $ARGV[1] || "LIB"; my $desde = $ARGV[2] || "00001"; my @head=( 'FECHA', 'INVENTARIO', 'AUTOR', 'TÍTULO', 'EDICIÓN', 'EDITOR', 'AÑO'); print join('#', @head); print "\n"; my $ejemplares = C4::Modelo::CatRegistroMarcN3::Manager->get_cat_registro_marc_n3( query => [ codigo_barra => { ge => $ui."-".$tipo."-".$desde }, codigo_barra => { like => $ui."-".$tipo."-%"}, ], sort_by => 'codigo_barra ASC' ); foreach my $nivel3 (@$ejemplares){ my @ejemplar=(); $ejemplar[0] = $nivel3->getCreatedAt_format(); $ejemplar[1] = $nivel3->getCodigoBarra(); $ejemplar[2] = $nivel3->nivel1->getAutor(); $ejemplar[3] = $nivel3->nivel1->getTitulo(); $ejemplar[4] = $nivel3->nivel2->getEdicion(); $ejemplar[5] = $nivel3->nivel2->getEditor(); $ejemplar[6] = $nivel3->nivel2->getAnio_publicacion(); print join('#', @ejemplar); print "\n"; } 1;
Javier-Acosta/meran
intranet/scripts/reporte_inventario.pl
Perl
gpl-3.0
2,611
require 'spec_helper' describe SessionsController do render_views context "#create" do it "should redirect to patterns path if user is authenticated" it "should redirect to new_user if user doesn't exist" it "should redirect to new_user if password is incorrect" end end
feministy/appy
spec/controllers/sessions_spec.rb
Ruby
gpl-3.0
290
#include <math.h> #include <stdlib.h> #include "camp_judge.h" #include "game_event.h" #include "monster_ai.h" #include "monster_manager.h" #include "path_algorithm.h" #include "player_manager.h" #include "time_helper.h" #include "partner.h" #include "check_range.h" #include "cached_hit_effect.h" #include "count_skill_damage.h" #include "msgid.h" #include "buff.h" // ▲ 攻击优先级1:攻击范围内,距离伙伴最近的正在攻击主人的所有目标>远一些的正在攻击主人的所有目标>距离伙伴最近的正在攻击伙伴自身的所有目标>远一些的正在攻击伙伴自身的所有目标>主人正在攻击的目标 static unit_struct *choose_target(partner_struct *partner) { unit_struct *ret = NULL; double distance; uint64_t now = time_helper::get_cached_time(); uint64_t t = now - 60 * 1000; struct position *cur_pos = partner->get_pos(); distance = 0xffffffff; for (int i = 0; i < MAX_PARTNER_ATTACK_UNIT; ++i) { if (partner->attack_owner[i].uuid == 0) continue; if (partner->attack_owner[i].time <= t) { partner->attack_owner[i].uuid = 0; continue; } if (!partner->is_unit_in_sight(partner->attack_owner[i].uuid)) continue; unit_struct *target = unit_struct::get_unit_by_uuid(partner->attack_owner[i].uuid); if (!target || !target->is_avaliable() || !target->is_alive()) { partner->attack_owner[i].uuid = 0; continue; } struct position *pos = target->get_pos(); float x = pos->pos_x - cur_pos->pos_x; float z = pos->pos_z - cur_pos->pos_z; if (x * x + z * z <= distance) { distance = x * x + z * z; ret = target; } } if (ret) return ret; for (int i = 0; i < MAX_PARTNER_ATTACK_UNIT; ++i) { if (partner->attack_partner[i].uuid == 0) continue; if (partner->attack_partner[i].time <= t) { partner->attack_partner[i].uuid = 0; continue; } if (!partner->is_unit_in_sight(partner->attack_partner[i].uuid)) continue; unit_struct *target = unit_struct::get_unit_by_uuid(partner->attack_partner[i].uuid); if (!target || !target->is_avaliable() || !target->is_alive()) { partner->attack_partner[i].uuid = 0; continue; } struct position *pos = target->get_pos(); float x = pos->pos_x - cur_pos->pos_x; float z = pos->pos_z - cur_pos->pos_z; if (x * x + z * z <= distance) { distance = x * x + z * z; ret = target; } } if (ret) return ret; for (int i = 0; i < MAX_PARTNER_ATTACK_UNIT; ++i) { if (partner->owner_attack[i].uuid == 0) continue; if (partner->owner_attack[i].time <= t) { partner->owner_attack[i].uuid = 0; continue; } if (!partner->is_unit_in_sight(partner->owner_attack[i].uuid)) continue; unit_struct *target = unit_struct::get_unit_by_uuid(partner->owner_attack[i].uuid); if (!target || !target->is_avaliable() || !target->is_alive()) { partner->owner_attack[i].uuid = 0; continue; } struct position *pos = target->get_pos(); float x = pos->pos_x - cur_pos->pos_x; float z = pos->pos_z - cur_pos->pos_z; if (x * x + z * z <= distance) { distance = x * x + z * z; ret = target; } } if (ret) return ret; return NULL; } int partner_ai_tick_1(partner_struct *partner) { if (partner->data->skill_id != 0 && partner->ai_state == AI_ATTACK_STATE) { partner->do_normal_attack(); partner->data->skill_id = 0; partner->ai_state = AI_PATROL_STATE; return 1; } int skill_index; uint32_t skill_id = partner->choose_skill(&skill_index); if (skill_id == 0) return 1; if (partner->try_friend_skill(skill_id, skill_index)) { return (0); } unit_struct *target = choose_target(partner); if (!target) return 0; return partner->attack_target(skill_id, skill_index, target); // struct position *my_pos = partner->get_pos(); // struct position *his_pos = target->get_pos(); // struct SkillTable *config = get_config_by_id(skill_id, &skill_config); // if (config == NULL) // { // LOG_ERR("%s: partner can not find skill[%u] config", __FUNCTION__, skill_id); // return 1; // } // if (!check_distance_in_range(my_pos, his_pos, config->SkillRange)) // { // //追击 // partner->reset_pos(); // if (get_circle_random_position_v2(partner->scene, my_pos, his_pos, config->SkillRange, &partner->data->move_path.pos[1])) // { // partner->send_patrol_move(); // } // else // { // return (0); // } // partner->data->ontick_time += random() % 1000; // return 1; // } // //主动技能 // if (config->SkillType == 2) // { // struct ActiveSkillTable *act_config = get_config_by_id(config->SkillAffectId, &active_skill_config); // if (!act_config) // { // LOG_ERR("%s: can not find skillaffectid[%lu] config", __FUNCTION__, config->SkillAffectId); // return 1; // } // if (act_config->ActionTime > 0) // { // uint64_t now = time_helper::get_cached_time(); // partner->data->ontick_time = now + act_config->ActionTime;// + 1500; // partner->data->skill_id = skill_id; // partner->data->angle = -(pos_to_angle(his_pos->pos_x - my_pos->pos_x, his_pos->pos_z - my_pos->pos_z)); // // LOG_DEBUG("jacktang: mypos[%.2f][%.2f] hispos[%.2f][%.2f]", my_pos->pos_x, my_pos->pos_z, his_pos->pos_x, his_pos->pos_z); // partner->ai_state = AI_ATTACK_STATE; // partner->m_target = target; // partner->reset_pos(); // partner->cast_skill_to_target(skill_id, target); // return 1; // } // } // partner->reset_pos(); // partner->cast_immediate_skill_to_target(skill_id, target); // //被反弹死了 // if (!partner->data) // return 1; // partner->data->skill_id = 0; // //计算硬直时间 // partner->data->ontick_time += count_skill_delay_time(config); // return 1; } struct partner_ai_interface partner_ai_1_interface = { .on_tick = partner_ai_tick_1, .choose_target = choose_target, };
tsdfsetatata/xserver
Server/game_srv/so_game_srv/partner_ai_1.cpp
C++
gpl-3.0
5,862
#!/bin/sh yum update
Taywee/dod-stig-scripts
linux/V-38481/fix.sh
Shell
gpl-3.0
23
package redsgreens.Pigasus; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEntityEvent; /** * Handle events for all Player related events * @author redsgreens */ public class PigasusPlayerListener implements Listener { private final Pigasus plugin; public PigasusPlayerListener(Pigasus instance) { plugin = instance; } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteractEntity(PlayerInteractEntityEvent event) // catch player+entity events, looking for wand usage on an entity { Entity entity = event.getRightClicked(); // return if something not allowed was clicked if(plugin.Config.getHoveringChance(entity) == -1) return; Player player = event.getPlayer(); // return if the click was with something other than the wand if(player.getItemInHand().getType() != plugin.Config.WandItem) return; // check for permission if(!plugin.isAuthorized(player, "wand") && !plugin.isAuthorized(player, "wand." + PigasusFlyingEntity.getType(entity).name().toLowerCase())) { if(plugin.Config.ShowErrorsInClient) player.sendMessage("§cErr: " + plugin.Name + ": you don't have permission."); return; } // checks passed, make this pig fly! plugin.Manager.addEntity(entity); } }
redsgreens/Pigasus
src/redsgreens/Pigasus/PigasusPlayerListener.java
Java
gpl-3.0
1,558
\section{Discussão} \begin{itemize} \item Consideração sobre comportamento e peculiaridades do Clang \item Pressuposto uma vulnerabilidade por arquivo \item Percentual baixo, porém comum \item Maioria dos arquivos não obtiveram report \end{itemize} As vulnerabilidades e suas nomenclaturas identificadas pela ferramenta \"scan-build\" (presente na ferramenta Clang) não estão alinhadas com as determinadas pelo NIST, sendo necessária, para este trabalho, uma aproximação. Foi levantada a hipotése de existência de apenas uma vulnerabilidade por arquivo de teste. Deste modo, há a possibilidade de que a quantidade de ocorrências de vulnerabilidades esperadas não corresponda à real. Entretanto, o modo de abordagem utilizado diminui o impacto dessa possível discrepância. O percentual de vulnerabilidades encontradas equivalentes as esperadas foi relativamente baixo, contudo, não foi uma surpresa, já que a grande maioria das ferramentas possuem tal desempenho. O fato de não ter encontrado nenhuma vulnerabilidade na grande maioria dos casos de teste influenciou bastante para o baixo percentual obtido, não estando, este fato, relacionado a uma interpretação errônea, realmente apresentando um mal desempenho da ferramenta. No contexto dos casos de testes que foram identificadas vulnerabilidades, pode ou não ter inconsistências, dependendo da acurácia da hipótese levantada. No espaço amostral das arquivos que foram encontradas vulnerabilidades, cerca de um quinto das vulnerabilidades encontradas foram equivalentes as esperadas, o que pode-se dizer satisfatório.
Analizo-UnB/security_report
artigo-latex/discussao.tex
TeX
gpl-3.0
1,580
/* Original code by Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TINYXML2_INCLUDED #define TINYXML2_INCLUDED #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) # include <ctype.h> # include <limits.h> # include <stdio.h> # include <stdlib.h> # include <string.h> # if defined(__PS3__) # include <stddef.h> # endif #else # include <cctype> # include <climits> # include <cstdio> # include <cstdlib> # include <cstring> #endif #include <stdint.h> /* TODO: intern strings instead of allocation. */ /* gcc: g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe Formatting, Artistic Style: AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h */ #if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__) # ifndef DEBUG # define DEBUG # endif #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4251) #endif #ifdef _WIN32 # ifdef TINYXML2_EXPORT # define TINYXML2_LIB __declspec(dllexport) # elif defined(TINYXML2_IMPORT) # define TINYXML2_LIB __declspec(dllimport) # else # define TINYXML2_LIB # endif #elif __GNUC__ >= 4 # define TINYXML2_LIB __attribute__((visibility("default"))) #else # define TINYXML2_LIB #endif #if defined(DEBUG) # if defined(_MSC_VER) # // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like # define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } # elif defined (ANDROID_NDK) # include <android/log.h> # define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } # else # include <assert.h> # define TIXMLASSERT assert # endif #else # define TIXMLASSERT( x ) {} #endif /* Versioning, past 1.0.14: http://semver.org/ */ static const int TIXML2_MAJOR_VERSION = 4; static const int TIXML2_MINOR_VERSION = 0; static const int TIXML2_PATCH_VERSION = 1; namespace tinyxml2 { class XMLDocument; class XMLElement; class XMLAttribute; class XMLComment; class XMLText; class XMLDeclaration; class XMLUnknown; class XMLPrinter; /* A class that wraps strings. Normally stores the start and end pointers into the XML file itself, and will apply normalization and entity translation if actually read. Can also store (and memory manage) a traditional char[] */ class StrPair { public: enum { NEEDS_ENTITY_PROCESSING = 0x01, NEEDS_NEWLINE_NORMALIZATION = 0x02, NEEDS_WHITESPACE_COLLAPSING = 0x04, TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, ATTRIBUTE_NAME = 0, ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, COMMENT = NEEDS_NEWLINE_NORMALIZATION }; StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} ~StrPair(); void Set( char* start, char* end, int flags ) { TIXMLASSERT( start ); TIXMLASSERT( end ); Reset(); _start = start; _end = end; _flags = flags | NEEDS_FLUSH; } const char* GetStr(); bool Empty() const { return _start == _end; } void SetInternedStr( const char* str ) { Reset(); _start = const_cast<char*>(str); } void SetStr( const char* str, int flags=0 ); char* ParseText( char* in, const char* endTag, int strFlags ); char* ParseName( char* in ); void TransferTo( StrPair* other ); void Reset(); private: void CollapseWhitespace(); enum { NEEDS_FLUSH = 0x100, NEEDS_DELETE = 0x200 }; int _flags; char* _start; char* _end; StrPair( const StrPair& other ); // not supported void operator=( StrPair& other ); // not supported, use TransferTo() }; /* A dynamic array of Plain Old Data. Doesn't support constructors, etc. Has a small initial memory pool, so that low or no usage will not cause a call to new/delete */ template <class T, int INITIAL_SIZE> class DynArray { public: DynArray() { _mem = _pool; _allocated = INITIAL_SIZE; _size = 0; } ~DynArray() { if ( _mem != _pool ) { delete [] _mem; } } void Clear() { _size = 0; } void Push( T t ) { TIXMLASSERT( _size < INT_MAX ); EnsureCapacity( _size+1 ); _mem[_size] = t; ++_size; } T* PushArr( int count ) { TIXMLASSERT( count >= 0 ); TIXMLASSERT( _size <= INT_MAX - count ); EnsureCapacity( _size+count ); T* ret = &_mem[_size]; _size += count; return ret; } T Pop() { TIXMLASSERT( _size > 0 ); --_size; return _mem[_size]; } void PopArr( int count ) { TIXMLASSERT( _size >= count ); _size -= count; } bool Empty() const { return _size == 0; } T& operator[](int i) { TIXMLASSERT( i>= 0 && i < _size ); return _mem[i]; } const T& operator[](int i) const { TIXMLASSERT( i>= 0 && i < _size ); return _mem[i]; } const T& PeekTop() const { TIXMLASSERT( _size > 0 ); return _mem[ _size - 1]; } int Size() const { TIXMLASSERT( _size >= 0 ); return _size; } int Capacity() const { TIXMLASSERT( _allocated >= INITIAL_SIZE ); return _allocated; } const T* Mem() const { TIXMLASSERT( _mem ); return _mem; } T* Mem() { TIXMLASSERT( _mem ); return _mem; } private: DynArray( const DynArray& ); // not supported void operator=( const DynArray& ); // not supported void EnsureCapacity( int cap ) { TIXMLASSERT( cap > 0 ); if ( cap > _allocated ) { TIXMLASSERT( cap <= INT_MAX / 2 ); int newAllocated = cap * 2; T* newMem = new T[newAllocated]; memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs if ( _mem != _pool ) { delete [] _mem; } _mem = newMem; _allocated = newAllocated; } } T* _mem; T _pool[INITIAL_SIZE]; int _allocated; // objects allocated int _size; // number objects in use }; /* Parent virtual class of a pool for fast allocation and deallocation of objects. */ class MemPool { public: MemPool() {} virtual ~MemPool() {} virtual int ItemSize() const = 0; virtual void* Alloc() = 0; virtual void Free( void* ) = 0; virtual void SetTracked() = 0; virtual void Clear() = 0; }; /* Template child class to create pools of the correct type. */ template< int ITEM_SIZE > class MemPoolT : public MemPool { public: MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} ~MemPoolT() { Clear(); } void Clear() { // Delete the blocks. while( !_blockPtrs.Empty()) { Block* b = _blockPtrs.Pop(); delete b; } _root = 0; _currentAllocs = 0; _nAllocs = 0; _maxAllocs = 0; _nUntracked = 0; } virtual int ItemSize() const { return ITEM_SIZE; } int CurrentAllocs() const { return _currentAllocs; } virtual void* Alloc() { if ( !_root ) { // Need a new block. Block* block = new Block(); _blockPtrs.Push( block ); Item* blockItems = block->items; for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { blockItems[i].next = &(blockItems[i + 1]); } blockItems[ITEMS_PER_BLOCK - 1].next = 0; _root = blockItems; } Item* const result = _root; TIXMLASSERT( result != 0 ); _root = _root->next; ++_currentAllocs; if ( _currentAllocs > _maxAllocs ) { _maxAllocs = _currentAllocs; } ++_nAllocs; ++_nUntracked; return result; } virtual void Free( void* mem ) { if ( !mem ) { return; } --_currentAllocs; Item* item = static_cast<Item*>( mem ); #ifdef DEBUG memset( item, 0xfe, sizeof( *item ) ); #endif item->next = _root; _root = item; } void Trace( const char* name ) { printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); } void SetTracked() { --_nUntracked; } int Untracked() const { return _nUntracked; } // This number is perf sensitive. 4k seems like a good tradeoff on my machine. // The test file is large, 170k. // Release: VS2010 gcc(no opt) // 1k: 4000 // 2k: 4000 // 4k: 3900 21000 // 16k: 5200 // 32k: 4300 // 64k: 4000 21000 // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK // in private part if ITEMS_PER_BLOCK is private enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; private: MemPoolT( const MemPoolT& ); // not supported void operator=( const MemPoolT& ); // not supported union Item { Item* next; char itemData[ITEM_SIZE]; }; struct Block { Item items[ITEMS_PER_BLOCK]; }; DynArray< Block*, 10 > _blockPtrs; Item* _root; int _currentAllocs; int _nAllocs; int _maxAllocs; int _nUntracked; }; /** Implements the interface to the "Visitor pattern" (see the Accept() method.) If you call the Accept() method, it requires being passed a XMLVisitor class to handle callbacks. For nodes that contain other nodes (Document, Element) you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs are simply called with Visit(). If you return 'true' from a Visit method, recursive parsing will continue. If you return false, <b>no children of this node or its siblings</b> will be visited. All flavors of Visit methods have a default implementation that returns 'true' (continue visiting). You need to only override methods that are interesting to you. Generally Accept() is called on the XMLDocument, although all nodes support visiting. You should never change the document from a callback. @sa XMLNode::Accept() */ class TINYXML2_LIB XMLVisitor { public: virtual ~XMLVisitor() {} /// Visit a document. virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { return true; } /// Visit a document. virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; } /// Visit an element. virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { return true; } /// Visit an element. virtual bool VisitExit( const XMLElement& /*element*/ ) { return true; } /// Visit a declaration. virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { return true; } /// Visit a text node. virtual bool Visit( const XMLText& /*text*/ ) { return true; } /// Visit a comment node. virtual bool Visit( const XMLComment& /*comment*/ ) { return true; } /// Visit an unknown node. virtual bool Visit( const XMLUnknown& /*unknown*/ ) { return true; } }; // WARNING: must match XMLDocument::_errorNames[] enum XMLError { XML_SUCCESS = 0, XML_NO_ATTRIBUTE, XML_WRONG_ATTRIBUTE_TYPE, XML_ERROR_FILE_NOT_FOUND, XML_ERROR_FILE_COULD_NOT_BE_OPENED, XML_ERROR_FILE_READ_ERROR, XML_ERROR_ELEMENT_MISMATCH, XML_ERROR_PARSING_ELEMENT, XML_ERROR_PARSING_ATTRIBUTE, XML_ERROR_IDENTIFYING_TAG, XML_ERROR_PARSING_TEXT, XML_ERROR_PARSING_CDATA, XML_ERROR_PARSING_COMMENT, XML_ERROR_PARSING_DECLARATION, XML_ERROR_PARSING_UNKNOWN, XML_ERROR_EMPTY_DOCUMENT, XML_ERROR_MISMATCHED_ELEMENT, XML_ERROR_PARSING, XML_CAN_NOT_CONVERT_TEXT, XML_NO_TEXT_NODE, XML_ERROR_COUNT }; /* Utility functionality. */ class XMLUtil { public: static const char* SkipWhiteSpace( const char* p ) { TIXMLASSERT( p ); while( IsWhiteSpace(*p) ) { ++p; } TIXMLASSERT( p ); return p; } static char* SkipWhiteSpace( char* p ) { return const_cast<char*>( SkipWhiteSpace( const_cast<const char*>(p) ) ); } // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't // correct, but simple, and usually works. static bool IsWhiteSpace( char p ) { return !IsUTF8Continuation(p) && isspace( static_cast<unsigned char>(p) ); } inline static bool IsNameStartChar( unsigned char ch ) { if ( ch >= 128 ) { // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() return true; } if ( isalpha( ch ) ) { return true; } return ch == ':' || ch == '_'; } inline static bool IsNameChar( unsigned char ch ) { return IsNameStartChar( ch ) || isdigit( ch ) || ch == '.' || ch == '-'; } inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { if ( p == q ) { return true; } return strncmp( p, q, nChar ) == 0; } inline static bool IsUTF8Continuation( char p ) { return ( p & 0x80 ) != 0; } static const char* ReadBOM( const char* p, bool* hasBOM ); // p is the starting location, // the UTF-8 value of the entity will be placed in value, and length filled in. static const char* GetCharacterRef( const char* p, char* value, int* length ); static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); // converts primitive types to strings static void ToStr( int v, char* buffer, int bufferSize ); static void ToStr( unsigned v, char* buffer, int bufferSize ); static void ToStr( bool v, char* buffer, int bufferSize ); static void ToStr( float v, char* buffer, int bufferSize ); static void ToStr( double v, char* buffer, int bufferSize ); static void ToStr(int64_t v, char* buffer, int bufferSize); // converts strings to primitive types static bool ToInt( const char* str, int* value ); static bool ToUnsigned( const char* str, unsigned* value ); static bool ToBool( const char* str, bool* value ); static bool ToFloat( const char* str, float* value ); static bool ToDouble( const char* str, double* value ); static bool ToInt64(const char* str, int64_t* value); }; /** XMLNode is a base class for every object that is in the XML Document Object Model (DOM), except XMLAttributes. Nodes have siblings, a parent, and children which can be navigated. A node is always in a XMLDocument. The type of a XMLNode can be queried, and it can be cast to its more defined type. A XMLDocument allocates memory for all its Nodes. When the XMLDocument gets deleted, all its Nodes will also be deleted. @verbatim A Document can contain: Element (container or leaf) Comment (leaf) Unknown (leaf) Declaration( leaf ) An Element can contain: Element (container or leaf) Text (leaf) Attributes (not on tree) Comment (leaf) Unknown (leaf) @endverbatim */ class TINYXML2_LIB XMLNode { friend class XMLDocument; friend class XMLElement; public: /// Get the XMLDocument that owns this XMLNode. const XMLDocument* GetDocument() const { TIXMLASSERT( _document ); return _document; } /// Get the XMLDocument that owns this XMLNode. XMLDocument* GetDocument() { TIXMLASSERT( _document ); return _document; } /// Safely cast to an Element, or null. virtual XMLElement* ToElement() { return 0; } /// Safely cast to Text, or null. virtual XMLText* ToText() { return 0; } /// Safely cast to a Comment, or null. virtual XMLComment* ToComment() { return 0; } /// Safely cast to a Document, or null. virtual XMLDocument* ToDocument() { return 0; } /// Safely cast to a Declaration, or null. virtual XMLDeclaration* ToDeclaration() { return 0; } /// Safely cast to an Unknown, or null. virtual XMLUnknown* ToUnknown() { return 0; } virtual const XMLElement* ToElement() const { return 0; } virtual const XMLText* ToText() const { return 0; } virtual const XMLComment* ToComment() const { return 0; } virtual const XMLDocument* ToDocument() const { return 0; } virtual const XMLDeclaration* ToDeclaration() const { return 0; } virtual const XMLUnknown* ToUnknown() const { return 0; } /** The meaning of 'value' changes for the specific type. @verbatim Document: empty (NULL is returned, not an empty string) Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim */ const char* Value() const; /** Set the Value of an XML node. @sa Value() */ void SetValue( const char* val, bool staticMem=false ); /// Get the parent of this node on the DOM. const XMLNode* Parent() const { return _parent; } XMLNode* Parent() { return _parent; } /// Returns true if this node has no children. bool NoChildren() const { return !_firstChild; } /// Get the first child node, or null if none exists. const XMLNode* FirstChild() const { return _firstChild; } XMLNode* FirstChild() { return _firstChild; } /** Get the first child element, or optionally the first child element with the specified name. */ const XMLElement* FirstChildElement( const char* name = 0 ) const; XMLElement* FirstChildElement( const char* name = 0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( name )); } /// Get the last child node, or null if none exists. const XMLNode* LastChild() const { return _lastChild; } XMLNode* LastChild() { return _lastChild; } /** Get the last child element or optionally the last child element with the specified name. */ const XMLElement* LastChildElement( const char* name = 0 ) const; XMLElement* LastChildElement( const char* name = 0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(name) ); } /// Get the previous (left) sibling node of this node. const XMLNode* PreviousSibling() const { return _prev; } XMLNode* PreviousSibling() { return _prev; } /// Get the previous (left) sibling element of this node, with an optionally supplied name. const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; XMLElement* PreviousSiblingElement( const char* name = 0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( name ) ); } /// Get the next (right) sibling node of this node. const XMLNode* NextSibling() const { return _next; } XMLNode* NextSibling() { return _next; } /// Get the next (right) sibling element of this node, with an optionally supplied name. const XMLElement* NextSiblingElement( const char* name = 0 ) const; XMLElement* NextSiblingElement( const char* name = 0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement( name ) ); } /** Add a child node as the last (right) child. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document. */ XMLNode* InsertEndChild( XMLNode* addThis ); XMLNode* LinkEndChild( XMLNode* addThis ) { return InsertEndChild( addThis ); } /** Add a child node as the first (left) child. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document. */ XMLNode* InsertFirstChild( XMLNode* addThis ); /** Add a node after the specified child node. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the afterThis node is not a child of this node, or if the node does not belong to the same document. */ XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); /** Delete all the children of this node. */ void DeleteChildren(); /** Delete a child of this node. */ void DeleteChild( XMLNode* node ); /** Make a copy of this node, but not its children. You may pass in a Document pointer that will be the owner of the new Node. If the 'document' is null, then the node returned will be allocated from the current Document. (this->GetDocument()) Note: if called on a XMLDocument, this will return null. */ virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; /** Test if 2 nodes are the same, but don't test children. The 2 nodes do not need to be in the same Document. Note: if called on a XMLDocument, this will return false. */ virtual bool ShallowEqual( const XMLNode* compare ) const = 0; /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the XML tree will be conditionally visited and the host will be called back via the XMLVisitor interface. This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this interface versus any other.) The interface has been based on ideas from: - http://www.saxproject.org/ - http://c2.com/cgi/wiki?HierarchicalVisitorPattern Which are both good references for "visiting". An example of using Accept(): @verbatim XMLPrinter printer; tinyxmlDoc.Accept( &printer ); const char* xmlcstr = printer.CStr(); @endverbatim */ virtual bool Accept( XMLVisitor* visitor ) const = 0; /** Set user data into the XMLNode. TinyXML-2 in no way processes or interprets user data. It is initially 0. */ void SetUserData(void* userData) { _userData = userData; } /** Get user data set into the XMLNode. TinyXML-2 in no way processes or interprets user data. It is initially 0. */ void* GetUserData() const { return _userData; } protected: XMLNode( XMLDocument* ); virtual ~XMLNode(); virtual char* ParseDeep( char*, StrPair* ); XMLDocument* _document; XMLNode* _parent; mutable StrPair _value; XMLNode* _firstChild; XMLNode* _lastChild; XMLNode* _prev; XMLNode* _next; void* _userData; private: MemPool* _memPool; void Unlink( XMLNode* child ); static void DeleteNode( XMLNode* node ); void InsertChildPreamble( XMLNode* insertThis ) const; XMLNode( const XMLNode& ); // not supported XMLNode& operator=( const XMLNode& ); // not supported }; /** XML text. Note that a text node can have child element nodes, for example: @verbatim <root>This is <b>bold</b></root> @endverbatim A text node can have 2 ways to output the next. "normal" output and CDATA. It will default to the mode it was parsed from the XML file and you generally want to leave it alone, but you can change the output mode with SetCData() and query it with CData(). */ class TINYXML2_LIB XMLText : public XMLNode { friend class XMLDocument; public: virtual bool Accept( XMLVisitor* visitor ) const; virtual XMLText* ToText() { return this; } virtual const XMLText* ToText() const { return this; } /// Declare whether this should be CDATA or standard text. void SetCData( bool isCData ) { _isCData = isCData; } /// Returns true if this is a CDATA text element. bool CData() const { return _isCData; } virtual XMLNode* ShallowClone( XMLDocument* document ) const; virtual bool ShallowEqual( const XMLNode* compare ) const; protected: XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} virtual ~XMLText() {} char* ParseDeep( char*, StrPair* endTag ); private: bool _isCData; XMLText( const XMLText& ); // not supported XMLText& operator=( const XMLText& ); // not supported }; /** An XML Comment. */ class TINYXML2_LIB XMLComment : public XMLNode { friend class XMLDocument; public: virtual XMLComment* ToComment() { return this; } virtual const XMLComment* ToComment() const { return this; } virtual bool Accept( XMLVisitor* visitor ) const; virtual XMLNode* ShallowClone( XMLDocument* document ) const; virtual bool ShallowEqual( const XMLNode* compare ) const; protected: XMLComment( XMLDocument* doc ); virtual ~XMLComment(); char* ParseDeep( char*, StrPair* endTag ); private: XMLComment( const XMLComment& ); // not supported XMLComment& operator=( const XMLComment& ); // not supported }; /** In correct XML the declaration is the first entry in the file. @verbatim <?xml version="1.0" standalone="yes"?> @endverbatim TinyXML-2 will happily read or write files without a declaration, however. The text of the declaration isn't interpreted. It is parsed and written as a string. */ class TINYXML2_LIB XMLDeclaration : public XMLNode { friend class XMLDocument; public: virtual XMLDeclaration* ToDeclaration() { return this; } virtual const XMLDeclaration* ToDeclaration() const { return this; } virtual bool Accept( XMLVisitor* visitor ) const; virtual XMLNode* ShallowClone( XMLDocument* document ) const; virtual bool ShallowEqual( const XMLNode* compare ) const; protected: XMLDeclaration( XMLDocument* doc ); virtual ~XMLDeclaration(); char* ParseDeep( char*, StrPair* endTag ); private: XMLDeclaration( const XMLDeclaration& ); // not supported XMLDeclaration& operator=( const XMLDeclaration& ); // not supported }; /** Any tag that TinyXML-2 doesn't recognize is saved as an unknown. It is a tag of text, but should not be modified. It will be written back to the XML, unchanged, when the file is saved. DTD tags get thrown into XMLUnknowns. */ class TINYXML2_LIB XMLUnknown : public XMLNode { friend class XMLDocument; public: virtual XMLUnknown* ToUnknown() { return this; } virtual const XMLUnknown* ToUnknown() const { return this; } virtual bool Accept( XMLVisitor* visitor ) const; virtual XMLNode* ShallowClone( XMLDocument* document ) const; virtual bool ShallowEqual( const XMLNode* compare ) const; protected: XMLUnknown( XMLDocument* doc ); virtual ~XMLUnknown(); char* ParseDeep( char*, StrPair* endTag ); private: XMLUnknown( const XMLUnknown& ); // not supported XMLUnknown& operator=( const XMLUnknown& ); // not supported }; /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @note The attributes are not XMLNodes. You may only query the Next() attribute in a list. */ class TINYXML2_LIB XMLAttribute { friend class XMLElement; public: /// The name of the attribute. const char* Name() const; /// The value of the attribute. const char* Value() const; /// The next attribute in the list. const XMLAttribute* Next() const { return _next; } /** IntValue interprets the attribute as an integer, and returns the value. If the value isn't an integer, 0 will be returned. There is no error checking; use QueryIntValue() if you need error checking. */ int IntValue() const { int i = 0; QueryIntValue(&i); return i; } int64_t Int64Value() const { int64_t i = 0; QueryInt64Value(&i); return i; } /// Query as an unsigned integer. See IntValue() unsigned UnsignedValue() const { unsigned i=0; QueryUnsignedValue( &i ); return i; } /// Query as a boolean. See IntValue() bool BoolValue() const { bool b=false; QueryBoolValue( &b ); return b; } /// Query as a double. See IntValue() double DoubleValue() const { double d=0; QueryDoubleValue( &d ); return d; } /// Query as a float. See IntValue() float FloatValue() const { float f=0; QueryFloatValue( &f ); return f; } /** QueryIntValue interprets the attribute as an integer, and returns the value in the provided parameter. The function will return XML_SUCCESS on success, and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. */ XMLError QueryIntValue( int* value ) const; /// See QueryIntValue XMLError QueryUnsignedValue( unsigned int* value ) const; /// See QueryIntValue XMLError QueryInt64Value(int64_t* value) const; /// See QueryIntValue XMLError QueryBoolValue( bool* value ) const; /// See QueryIntValue XMLError QueryDoubleValue( double* value ) const; /// See QueryIntValue XMLError QueryFloatValue( float* value ) const; /// Set the attribute to a string value. void SetAttribute( const char* value ); /// Set the attribute to value. void SetAttribute( int value ); /// Set the attribute to value. void SetAttribute( unsigned value ); /// Set the attribute to value. void SetAttribute(int64_t value); /// Set the attribute to value. void SetAttribute( bool value ); /// Set the attribute to value. void SetAttribute( double value ); /// Set the attribute to value. void SetAttribute( float value ); private: enum { BUF_SIZE = 200 }; XMLAttribute() : _next( 0 ), _memPool( 0 ) {} virtual ~XMLAttribute() {} XMLAttribute( const XMLAttribute& ); // not supported void operator=( const XMLAttribute& ); // not supported void SetName( const char* name ); char* ParseDeep( char* p, bool processEntities ); mutable StrPair _name; mutable StrPair _value; XMLAttribute* _next; MemPool* _memPool; }; /** The element is a container class. It has a value, the element name, and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ class TINYXML2_LIB XMLElement : public XMLNode { friend class XMLDocument; public: /// Get the name of an element (which is the Value() of the node.) const char* Name() const { return Value(); } /// Set the name of the element. void SetName( const char* str, bool staticMem=false ) { SetValue( str, staticMem ); } virtual XMLElement* ToElement() { return this; } virtual const XMLElement* ToElement() const { return this; } virtual bool Accept( XMLVisitor* visitor ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. For example: @verbatim const char* value = ele->Attribute( "foo" ); @endverbatim The 'value' parameter is normally null. However, if specified, the attribute will only be returned if the 'name' and 'value' match. This allow you to write code: @verbatim if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); @endverbatim rather than: @verbatim if ( ele->Attribute( "foo" ) ) { if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); } @endverbatim */ const char* Attribute( const char* name, const char* value=0 ) const; /** Given an attribute name, IntAttribute() returns the value of the attribute interpreted as an integer. 0 will be returned if there is an error. For a method with error checking, see QueryIntAttribute() */ int IntAttribute( const char* name ) const { int i=0; QueryIntAttribute( name, &i ); return i; } /// See IntAttribute() unsigned UnsignedAttribute( const char* name ) const { unsigned i=0; QueryUnsignedAttribute( name, &i ); return i; } /// See IntAttribute() int64_t Int64Attribute(const char* name) const { int64_t i = 0; QueryInt64Attribute(name, &i); return i; } /// See IntAttribute() bool BoolAttribute( const char* name ) const { bool b=false; QueryBoolAttribute( name, &b ); return b; } /// See IntAttribute() double DoubleAttribute( const char* name ) const { double d=0; QueryDoubleAttribute( name, &d ); return d; } /// See IntAttribute() float FloatAttribute( const char* name ) const { float f=0; QueryFloatAttribute( name, &f ); return f; } /** Given an attribute name, QueryIntAttribute() returns XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion can't be performed, or XML_NO_ATTRIBUTE if the attribute doesn't exist. If successful, the result of the conversion will be written to 'value'. If not successful, nothing will be written to 'value'. This allows you to provide default value: @verbatim int value = 10; QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 @endverbatim */ XMLError QueryIntAttribute( const char* name, int* value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) { return XML_NO_ATTRIBUTE; } return a->QueryIntValue( value ); } /// See QueryIntAttribute() XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) { return XML_NO_ATTRIBUTE; } return a->QueryUnsignedValue( value ); } /// See QueryIntAttribute() XMLError QueryInt64Attribute(const char* name, int64_t* value) const { const XMLAttribute* a = FindAttribute(name); if (!a) { return XML_NO_ATTRIBUTE; } return a->QueryInt64Value(value); } /// See QueryIntAttribute() XMLError QueryBoolAttribute( const char* name, bool* value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) { return XML_NO_ATTRIBUTE; } return a->QueryBoolValue( value ); } /// See QueryIntAttribute() XMLError QueryDoubleAttribute( const char* name, double* value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) { return XML_NO_ATTRIBUTE; } return a->QueryDoubleValue( value ); } /// See QueryIntAttribute() XMLError QueryFloatAttribute( const char* name, float* value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) { return XML_NO_ATTRIBUTE; } return a->QueryFloatValue( value ); } /** Given an attribute name, QueryAttribute() returns XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion can't be performed, or XML_NO_ATTRIBUTE if the attribute doesn't exist. It is overloaded for the primitive types, and is a generally more convenient replacement of QueryIntAttribute() and related functions. If successful, the result of the conversion will be written to 'value'. If not successful, nothing will be written to 'value'. This allows you to provide default value: @verbatim int value = 10; QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 @endverbatim */ int QueryAttribute( const char* name, int* value ) const { return QueryIntAttribute( name, value ); } int QueryAttribute( const char* name, unsigned int* value ) const { return QueryUnsignedAttribute( name, value ); } int QueryAttribute(const char* name, int64_t* value) const { return QueryInt64Attribute(name, value); } int QueryAttribute( const char* name, bool* value ) const { return QueryBoolAttribute( name, value ); } int QueryAttribute( const char* name, double* value ) const { return QueryDoubleAttribute( name, value ); } int QueryAttribute( const char* name, float* value ) const { return QueryFloatAttribute( name, value ); } /// Sets the named attribute to value. void SetAttribute( const char* name, const char* value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( value ); } /// Sets the named attribute to value. void SetAttribute( const char* name, int value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( value ); } /// Sets the named attribute to value. void SetAttribute( const char* name, unsigned value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( value ); } /// Sets the named attribute to value. void SetAttribute(const char* name, int64_t value) { XMLAttribute* a = FindOrCreateAttribute(name); a->SetAttribute(value); } /// Sets the named attribute to value. void SetAttribute( const char* name, bool value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( value ); } /// Sets the named attribute to value. void SetAttribute( const char* name, double value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( value ); } /// Sets the named attribute to value. void SetAttribute( const char* name, float value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( value ); } /** Delete an attribute. */ void DeleteAttribute( const char* name ); /// Return the first attribute in the list. const XMLAttribute* FirstAttribute() const { return _rootAttribute; } /// Query a specific attribute in the list. const XMLAttribute* FindAttribute( const char* name ) const; /** Convenience function for easy access to the text inside an element. Although easy and concise, GetText() is limited compared to getting the XMLText child and accessing it directly. If the first child of 'this' is a XMLText, the GetText() returns the character string of the Text node, else null is returned. This is a convenient method for getting the text of simple contained text: @verbatim <foo>This is text</foo> const char* str = fooElement->GetText(); @endverbatim 'str' will be a pointer to "This is text". Note that this function can be misleading. If the element foo was created from this XML: @verbatim <foo><b>This is text</b></foo> @endverbatim then the value of str would be null. The first child node isn't a text node, it is another element. From this XML: @verbatim <foo>This is <b>text</b></foo> @endverbatim GetText() will return "This is ". */ const char* GetText() const; /** Convenience function for easy access to the text inside an element. Although easy and concise, SetText() is limited compared to creating an XMLText child and mutating it directly. If the first child of 'this' is a XMLText, SetText() sets its value to the given string, otherwise it will create a first child that is an XMLText. This is a convenient method for setting the text of simple contained text: @verbatim <foo>This is text</foo> fooElement->SetText( "Hullaballoo!" ); <foo>Hullaballoo!</foo> @endverbatim Note that this function can be misleading. If the element foo was created from this XML: @verbatim <foo><b>This is text</b></foo> @endverbatim then it will not change "This is text", but rather prefix it with a text element: @verbatim <foo>Hullaballoo!<b>This is text</b></foo> @endverbatim For this XML: @verbatim <foo /> @endverbatim SetText() will generate @verbatim <foo>Hullaballoo!</foo> @endverbatim */ void SetText( const char* inText ); /// Convenience method for setting text inside an element. See SetText() for important limitations. void SetText( int value ); /// Convenience method for setting text inside an element. See SetText() for important limitations. void SetText( unsigned value ); /// Convenience method for setting text inside an element. See SetText() for important limitations. void SetText(int64_t value); /// Convenience method for setting text inside an element. See SetText() for important limitations. void SetText( bool value ); /// Convenience method for setting text inside an element. See SetText() for important limitations. void SetText( double value ); /// Convenience method for setting text inside an element. See SetText() for important limitations. void SetText( float value ); /** Convenience method to query the value of a child text node. This is probably best shown by example. Given you have a document is this form: @verbatim <point> <x>1</x> <y>1.4</y> </point> @endverbatim The QueryIntText() and similar functions provide a safe and easier way to get to the "value" of x and y. @verbatim int x = 0; float y = 0; // types of x and y are contrived for example const XMLElement* xElement = pointElement->FirstChildElement( "x" ); const XMLElement* yElement = pointElement->FirstChildElement( "y" ); xElement->QueryIntText( &x ); yElement->QueryFloatText( &y ); @endverbatim @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. */ XMLError QueryIntText( int* ival ) const; /// See QueryIntText() XMLError QueryUnsignedText( unsigned* uval ) const; /// See QueryIntText() XMLError QueryInt64Text(int64_t* uval) const; /// See QueryIntText() XMLError QueryBoolText( bool* bval ) const; /// See QueryIntText() XMLError QueryDoubleText( double* dval ) const; /// See QueryIntText() XMLError QueryFloatText( float* fval ) const; // internal: enum { OPEN, // <foo> CLOSED, // <foo/> CLOSING // </foo> }; int ClosingType() const { return _closingType; } virtual XMLNode* ShallowClone( XMLDocument* document ) const; virtual bool ShallowEqual( const XMLNode* compare ) const; protected: char* ParseDeep( char* p, StrPair* endTag ); private: XMLElement( XMLDocument* doc ); virtual ~XMLElement(); XMLElement( const XMLElement& ); // not supported void operator=( const XMLElement& ); // not supported XMLAttribute* FindAttribute( const char* name ) { return const_cast<XMLAttribute*>(const_cast<const XMLElement*>(this)->FindAttribute( name )); } XMLAttribute* FindOrCreateAttribute( const char* name ); //void LinkAttribute( XMLAttribute* attrib ); char* ParseAttributes( char* p ); static void DeleteAttribute( XMLAttribute* attribute ); enum { BUF_SIZE = 200 }; int _closingType; // The attribute list is ordered; there is no 'lastAttribute' // because the list needs to be scanned for dupes before adding // a new attribute. XMLAttribute* _rootAttribute; }; enum Whitespace { PRESERVE_WHITESPACE, COLLAPSE_WHITESPACE }; /** A Document binds together all the functionality. It can be saved, loaded, and printed to the screen. All Nodes are connected and allocated to a Document. If the Document is deleted, all its Nodes are also deleted. */ class TINYXML2_LIB XMLDocument : public XMLNode { friend class XMLElement; public: /// constructor XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE ); ~XMLDocument(); virtual XMLDocument* ToDocument() { TIXMLASSERT( this == _document ); return this; } virtual const XMLDocument* ToDocument() const { TIXMLASSERT( this == _document ); return this; } /** Parse an XML file from a character string. Returns XML_SUCCESS (0) on success, or an errorID. You may optionally pass in the 'nBytes', which is the number of bytes which will be parsed. If not specified, TinyXML-2 will assume 'xml' points to a null terminated string. */ XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); /** Load an XML file from disk. Returns XML_SUCCESS (0) on success, or an errorID. */ XMLError LoadFile( const char* filename ); /** Load an XML file from disk. You are responsible for providing and closing the FILE*. NOTE: The file should be opened as binary ("rb") not text in order for TinyXML-2 to correctly do newline normalization. Returns XML_SUCCESS (0) on success, or an errorID. */ XMLError LoadFile( FILE* ); /** Save the XML file to disk. Returns XML_SUCCESS (0) on success, or an errorID. */ XMLError SaveFile( const char* filename, bool compact = false ); /** Save the XML file to disk. You are responsible for providing and closing the FILE*. Returns XML_SUCCESS (0) on success, or an errorID. */ XMLError SaveFile( FILE* fp, bool compact = false ); bool ProcessEntities() const { return _processEntities; } Whitespace WhitespaceMode() const { return _whitespace; } /** Returns true if this document has a leading Byte Order Mark of UTF8. */ bool HasBOM() const { return _writeBOM; } /** Sets whether to write the BOM when writing the file. */ void SetBOM( bool useBOM ) { _writeBOM = useBOM; } /** Return the root element of DOM. Equivalent to FirstChildElement(). To get the first node, use FirstChild(). */ XMLElement* RootElement() { return FirstChildElement(); } const XMLElement* RootElement() const { return FirstChildElement(); } /** Print the Document. If the Printer is not provided, it will print to stdout. If you provide Printer, this can print to a file: @verbatim XMLPrinter printer( fp ); doc.Print( &printer ); @endverbatim Or you can use a printer to print to memory: @verbatim XMLPrinter printer; doc.Print( &printer ); // printer.CStr() has a const char* to the XML @endverbatim */ void Print( XMLPrinter* streamer=0 ) const; virtual bool Accept( XMLVisitor* visitor ) const; /** Create a new Element associated with this Document. The memory for the Element is managed by the Document. */ XMLElement* NewElement( const char* name ); /** Create a new Comment associated with this Document. The memory for the Comment is managed by the Document. */ XMLComment* NewComment( const char* comment ); /** Create a new Text associated with this Document. The memory for the Text is managed by the Document. */ XMLText* NewText( const char* text ); /** Create a new Declaration associated with this Document. The memory for the object is managed by the Document. If the 'text' param is null, the standard declaration is used.: @verbatim <?xml version="1.0" encoding="UTF-8"?> @endverbatim */ XMLDeclaration* NewDeclaration( const char* text=0 ); /** Create a new Unknown associated with this Document. The memory for the object is managed by the Document. */ XMLUnknown* NewUnknown( const char* text ); /** Delete a node associated with this document. It will be unlinked from the DOM. */ void DeleteNode( XMLNode* node ); void SetError( XMLError error, const char* str1, const char* str2 ); /// Return true if there was an error parsing the document. bool Error() const { return _errorID != XML_SUCCESS; } /// Return the errorID. XMLError ErrorID() const { return _errorID; } const char* ErrorName() const; /// Return a possibly helpful diagnostic location or string. const char* GetErrorStr1() const { return _errorStr1.GetStr(); } /// Return a possibly helpful secondary diagnostic location or string. const char* GetErrorStr2() const { return _errorStr2.GetStr(); } /// If there is an error, print it to stdout. void PrintError() const; /// Clear the document, resetting it to the initial state. void Clear(); // internal char* Identify( char* p, XMLNode** node ); virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { return 0; } virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { return false; } private: XMLDocument( const XMLDocument& ); // not supported void operator=( const XMLDocument& ); // not supported bool _writeBOM; bool _processEntities; XMLError _errorID; Whitespace _whitespace; mutable StrPair _errorStr1; mutable StrPair _errorStr2; char* _charBuffer; MemPoolT< sizeof(XMLElement) > _elementPool; MemPoolT< sizeof(XMLAttribute) > _attributePool; MemPoolT< sizeof(XMLText) > _textPool; MemPoolT< sizeof(XMLComment) > _commentPool; static const char* _errorNames[XML_ERROR_COUNT]; void Parse(); }; /** A XMLHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 DOM structure. It is a separate utility class. Take an example: @verbatim <Document> <Element attributeA = "valueA"> <Child attributeB = "value1" /> <Child attributeB = "value2" /> </Element> </Document> @endverbatim Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim XMLElement* root = document.FirstChildElement( "Document" ); if ( root ) { XMLElement* element = root->FirstChildElement( "Element" ); if ( element ) { XMLElement* child = element->FirstChildElement( "Child" ); if ( child ) { XMLElement* child2 = child->NextSiblingElement( "Child" ); if ( child2 ) { // Finally do something useful. @endverbatim And that doesn't even cover "else" cases. XMLHandle addresses the verbosity of such code. A XMLHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim XMLHandle docHandle( &document ); XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); if ( child2 ) { // do something useful @endverbatim Which is MUCH more concise and useful. It is also safe to copy handles - internally they are nothing more than node pointers. @verbatim XMLHandle handleCopy = handle; @endverbatim See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. */ class TINYXML2_LIB XMLHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. XMLHandle( XMLNode* node ) { _node = node; } /// Create a handle from a node. XMLHandle( XMLNode& node ) { _node = &node; } /// Copy constructor XMLHandle( const XMLHandle& ref ) { _node = ref._node; } /// Assignment XMLHandle& operator=( const XMLHandle& ref ) { _node = ref._node; return *this; } /// Get the first child of this handle. XMLHandle FirstChild() { return XMLHandle( _node ? _node->FirstChild() : 0 ); } /// Get the first child element of this handle. XMLHandle FirstChildElement( const char* name = 0 ) { return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); } /// Get the last child of this handle. XMLHandle LastChild() { return XMLHandle( _node ? _node->LastChild() : 0 ); } /// Get the last child element of this handle. XMLHandle LastChildElement( const char* name = 0 ) { return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); } /// Get the previous sibling of this handle. XMLHandle PreviousSibling() { return XMLHandle( _node ? _node->PreviousSibling() : 0 ); } /// Get the previous sibling element of this handle. XMLHandle PreviousSiblingElement( const char* name = 0 ) { return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); } /// Get the next sibling of this handle. XMLHandle NextSibling() { return XMLHandle( _node ? _node->NextSibling() : 0 ); } /// Get the next sibling element of this handle. XMLHandle NextSiblingElement( const char* name = 0 ) { return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); } /// Safe cast to XMLNode. This can return null. XMLNode* ToNode() { return _node; } /// Safe cast to XMLElement. This can return null. XMLElement* ToElement() { return ( ( _node == 0 ) ? 0 : _node->ToElement() ); } /// Safe cast to XMLText. This can return null. XMLText* ToText() { return ( ( _node == 0 ) ? 0 : _node->ToText() ); } /// Safe cast to XMLUnknown. This can return null. XMLUnknown* ToUnknown() { return ( ( _node == 0 ) ? 0 : _node->ToUnknown() ); } /// Safe cast to XMLDeclaration. This can return null. XMLDeclaration* ToDeclaration() { return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() ); } private: XMLNode* _node; }; /** A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the same in all regards, except for the 'const' qualifiers. See XMLHandle for API. */ class TINYXML2_LIB XMLConstHandle { public: XMLConstHandle( const XMLNode* node ) { _node = node; } XMLConstHandle( const XMLNode& node ) { _node = &node; } XMLConstHandle( const XMLConstHandle& ref ) { _node = ref._node; } XMLConstHandle& operator=( const XMLConstHandle& ref ) { _node = ref._node; return *this; } const XMLConstHandle FirstChild() const { return XMLConstHandle( _node ? _node->FirstChild() : 0 ); } const XMLConstHandle FirstChildElement( const char* name = 0 ) const { return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); } const XMLConstHandle LastChild() const { return XMLConstHandle( _node ? _node->LastChild() : 0 ); } const XMLConstHandle LastChildElement( const char* name = 0 ) const { return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); } const XMLConstHandle PreviousSibling() const { return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); } const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); } const XMLConstHandle NextSibling() const { return XMLConstHandle( _node ? _node->NextSibling() : 0 ); } const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); } const XMLNode* ToNode() const { return _node; } const XMLElement* ToElement() const { return ( ( _node == 0 ) ? 0 : _node->ToElement() ); } const XMLText* ToText() const { return ( ( _node == 0 ) ? 0 : _node->ToText() ); } const XMLUnknown* ToUnknown() const { return ( ( _node == 0 ) ? 0 : _node->ToUnknown() ); } const XMLDeclaration* ToDeclaration() const { return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() ); } private: const XMLNode* _node; }; /** Printing functionality. The XMLPrinter gives you more options than the XMLDocument::Print() method. It can: -# Print to memory. -# Print to a file you provide. -# Print XML without a XMLDocument. Print to Memory @verbatim XMLPrinter printer; doc.Print( &printer ); SomeFunction( printer.CStr() ); @endverbatim Print to a File You provide the file pointer. @verbatim XMLPrinter printer( fp ); doc.Print( &printer ); @endverbatim Print without a XMLDocument When loading, an XML parser is very useful. However, sometimes when saving, it just gets in the way. The code is often set up for streaming, and constructing the DOM is just overhead. The Printer supports the streaming case. The following code prints out a trivially simple XML file without ever creating an XML document. @verbatim XMLPrinter printer( fp ); printer.OpenElement( "foo" ); printer.PushAttribute( "foo", "bar" ); printer.CloseElement(); @endverbatim */ class TINYXML2_LIB XMLPrinter : public XMLVisitor { public: /** Construct the printer. If the FILE* is specified, this will print to the FILE. Else it will print to memory, and the result is available in CStr(). If 'compact' is set to true, then output is created with only required whitespace and newlines. */ XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); virtual ~XMLPrinter() {} /** If streaming, write the BOM and declaration. */ void PushHeader( bool writeBOM, bool writeDeclaration ); /** If streaming, start writing an element. The element must be closed with CloseElement() */ void OpenElement( const char* name, bool compactMode=false ); /// If streaming, add an attribute to an open element. void PushAttribute( const char* name, const char* value ); void PushAttribute( const char* name, int value ); void PushAttribute( const char* name, unsigned value ); void PushAttribute(const char* name, int64_t value); void PushAttribute( const char* name, bool value ); void PushAttribute( const char* name, double value ); /// If streaming, close the Element. virtual void CloseElement( bool compactMode=false ); /// Add a text node. void PushText( const char* text, bool cdata=false ); /// Add a text node from an integer. void PushText( int value ); /// Add a text node from an unsigned. void PushText( unsigned value ); /// Add a text node from an unsigned. void PushText(int64_t value); /// Add a text node from a bool. void PushText( bool value ); /// Add a text node from a float. void PushText( float value ); /// Add a text node from a double. void PushText( double value ); /// Add a comment void PushComment( const char* comment ); void PushDeclaration( const char* value ); void PushUnknown( const char* value ); virtual bool VisitEnter( const XMLDocument& /*doc*/ ); virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; } virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); virtual bool VisitExit( const XMLElement& element ); virtual bool Visit( const XMLText& text ); virtual bool Visit( const XMLComment& comment ); virtual bool Visit( const XMLDeclaration& declaration ); virtual bool Visit( const XMLUnknown& unknown ); /** If in print to memory mode, return a pointer to the XML file in memory. */ const char* CStr() const { return _buffer.Mem(); } /** If in print to memory mode, return the size of the XML file in memory. (Note the size returned includes the terminating null.) */ int CStrSize() const { return _buffer.Size(); } /** If in print to memory mode, reset the buffer to the beginning. */ void ClearBuffer() { _buffer.Clear(); _buffer.Push(0); } protected: virtual bool CompactMode( const XMLElement& ) { return _compactMode; } /** Prints out the space before an element. You may override to change the space and tabs used. A PrintSpace() override should call Print(). */ virtual void PrintSpace( int depth ); void Print( const char* format, ... ); void SealElementIfJustOpened(); bool _elementJustOpened; DynArray< const char*, 10 > _stack; private: void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. bool _firstElement; FILE* _fp; int _depth; int _textDepth; bool _processEntities; bool _compactMode; enum { ENTITY_RANGE = 64, BUF_SIZE = 200 }; bool _entityFlag[ENTITY_RANGE]; bool _restrictedEntityFlag[ENTITY_RANGE]; DynArray< char, 20 > _buffer; }; } // tinyxml2 #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // TINYXML2_INCLUDED
alex-mitrevski/delta-execution-models
MT_UseCases/Source/MT_UseCases/external/tinyxml2.h
C
gpl-3.0
63,328
package fi.metatavu.edelphi.jsons.queries; import java.util.Locale; import fi.metatavu.edelphi.smvcj.SmvcRuntimeException; import fi.metatavu.edelphi.smvcj.controllers.JSONRequestContext; import fi.metatavu.edelphi.DelfoiActionName; import fi.metatavu.edelphi.EdelfoiStatusCode; import fi.metatavu.edelphi.dao.querydata.QueryReplyDAO; import fi.metatavu.edelphi.dao.querylayout.QueryPageDAO; import fi.metatavu.edelphi.dao.users.UserDAO; import fi.metatavu.edelphi.domainmodel.actions.DelfoiActionScope; import fi.metatavu.edelphi.domainmodel.querydata.QueryReply; import fi.metatavu.edelphi.domainmodel.querylayout.QueryPage; import fi.metatavu.edelphi.domainmodel.resources.Query; import fi.metatavu.edelphi.domainmodel.resources.QueryState; import fi.metatavu.edelphi.domainmodel.users.User; import fi.metatavu.edelphi.i18n.Messages; import fi.metatavu.edelphi.jsons.JSONController; import fi.metatavu.edelphi.query.QueryPageHandler; import fi.metatavu.edelphi.query.QueryPageHandlerFactory; import fi.metatavu.edelphi.utils.ActionUtils; import fi.metatavu.edelphi.utils.QueryDataUtils; public class SaveQueryAnswersJSONRequestController extends JSONController { public SaveQueryAnswersJSONRequestController() { super(); setAccessAction(DelfoiActionName.ACCESS_PANEL, DelfoiActionScope.PANEL); } @Override public void process(JSONRequestContext jsonRequestContext) { UserDAO userDAO = new UserDAO(); QueryPageDAO queryPageDAO = new QueryPageDAO(); QueryReplyDAO queryReplyDAO = new QueryReplyDAO(); Long queryPageId = jsonRequestContext.getLong("queryPageId"); QueryPage queryPage = queryPageDAO.findById(queryPageId); Query query = queryPage.getQuerySection().getQuery(); Messages messages = Messages.getInstance(); Locale locale = jsonRequestContext.getRequest().getLocale(); if (query.getState() == QueryState.CLOSED) throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_CLOSED, messages.getText(locale, "exception.1027.cannotSaveReplyQueryClosed")); if (query.getState() == QueryState.EDIT) { if (!ActionUtils.hasPanelAccess(jsonRequestContext, DelfoiActionName.MANAGE_DELFOI_MATERIALS.toString())) throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_IN_EDIT_STATE, messages.getText(locale, "exception.1028.cannotSaveReplyQueryInEditState")); } else { User loggedUser = null; if (jsonRequestContext.isLoggedIn()) loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId()); QueryReply queryReply = QueryDataUtils.findQueryReply(jsonRequestContext, loggedUser, query); if (queryReply == null) { throw new SmvcRuntimeException(EdelfoiStatusCode.UNKNOWN_REPLICANT, messages.getText(locale, "exception.1026.unknownReplicant")); } queryReplyDAO.updateLastModified(queryReply, loggedUser); QueryDataUtils.storeQueryReplyId(jsonRequestContext.getRequest().getSession(), queryReply); QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType()); queryPageHandler.saveAnswers(jsonRequestContext, queryPage, queryReply); } } }
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/jsons/queries/SaveQueryAnswersJSONRequestController.java
Java
gpl-3.0
3,237
package org.craftercms.studio.api.dto; public class UserTest { public void testGetUserId() throws Exception { } public void testSetUserId() throws Exception { } public void testGetPassword() throws Exception { } public void testSetPassword() throws Exception { } }
craftercms/studio3
api/src/test/java/org/craftercms/studio/api/dto/UserTest.java
Java
gpl-3.0
305
## Versioning All core-utils will remain `0.1.0` until the entirety of core-utils reaches `1.0.0`. ## Issues If a particular utility is at issue please prepend with issue with its name as such: `"dd: not implemented"` ## Style Standard Rust indentation is used. No use of globs, and use of namespaces must be explicit, this rule does not apply for structures or enumerations, returns must be explicit. External crates must be imported before any `use`s. For example: ```Rust // Bad (set_exit_status is a function) use std::env::* use std::env::{set_exit_status}; extern crate common; use common::{Status}; // Good extern crate common; use common::{Status}; use std::env; use std::path::{PathBuf}; ``` Feel free to take a look at some of the source for the general structure of a util ## Help, Versions When writing help menus for any util, use the following structure: ``` $ util --help Usage: util [OPTION...] [FILE...] Useful utilitiy for doing things Options: -v --verbose Print things -f --function Do things Example: util -vf file.txt Does and prints a thing ``` Append an elipses if the program takes more than one option/file For printing versions use [`Prog.copyright`](lib/lib.rs). ## Commits Commits must be well documented, and signed off on. See [commits](https://github.com/0X1A/core-utils/commits/master) for examples ## License All files must be prepended with: ``` // Copyright (C) YEAR, CONTRIBUTER <CONTRIBUTER EMAIL> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. ```
0X1A/core-utils
CONTRIBUTING.md
Markdown
gpl-3.0
1,612
// -*- C++ -*- // // generated by wxGlade 0.7.2 // // Example for compiling a single file project under Linux using g++: // g++ MyApp.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp // // Example for compiling a multi file project under Linux using g++: // g++ main.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp Dialog1.cpp Frame1.cpp // #ifndef DIALOGEVTCMDCHANGELEVEL_H #define DIALOGEVTCMDCHANGELEVEL_H #include <wx/wx.h> #include <wx/image.h> #include <wx/intl.h> #ifndef APP_CATALOG #define APP_CATALOG "appEditor" // replace with the appropriate catalog name #endif // begin wxGlade: ::dependencies #include <wx/spinctrl.h> // end wxGlade // begin wxGlade: ::extracode // end wxGlade class DialogEvtCmdChangeLevel: public wxDialog { public: // begin wxGlade: DialogEvtCmdChangeLevel::ids // end wxGlade DialogEvtCmdChangeLevel(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos=wxDefaultPosition, const wxSize& size=wxDefaultSize, long style=wxDEFAULT_DIALOG_STYLE); private: // begin wxGlade: DialogEvtCmdChangeLevel::methods void set_properties(); void do_layout(); // end wxGlade protected: // begin wxGlade: DialogEvtCmdChangeLevel::attributes wxRadioButton* rbtnTargetParty; wxRadioButton* rbtnTargetFixed; wxChoice* chTargetFixed; wxRadioButton* rbtnTargetVariable; wxTextCtrl* tcTargetVariable; wxButton* btnTargetVariable; wxRadioBox* rbOperation; wxRadioButton* rbtnOperandConstant; wxSpinCtrl* spinOperandConstant; wxRadioButton* rbtnOperandVariable; wxTextCtrl* tcOperandVariable; wxButton* btnOperandVariable; wxCheckBox* chbShowMessage; wxButton* btnOK; wxButton* btnCancel; wxButton* btnHelp; // end wxGlade }; // wxGlade: end class #endif // DIALOGEVTCMDCHANGELEVEL_H
fdelapena/easyrpg-editor-wx
src/DialogEvtCmdChangeLevel.h
C
gpl-3.0
1,774
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera ([email protected]) L. Sánchez ([email protected]) J. Alcalá-Fdez ([email protected]) S. García ([email protected]) A. Fernández ([email protected]) J. Luengo ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.Genetic_Rule_Learning.RMini; import java.util.StringTokenizer; import org.core.Fichero; import java.util.StringTokenizer; /** * <p>Title: Main Class of the Program</p> * * <p>Description: It reads the configuration file (data-set files and parameters) and launch the algorithm</p> * * <p>Company: KEEL</p> * * @author Jesús Jiménez * @version 1.0 */ public class Main { private parseParameters parameters; /** Default Constructor */ public Main() { } /** * It launches the algorithm * @param confFile String it is the filename of the configuration file. */ private void execute(String confFile) { parameters = new parseParameters(); parameters.parseConfigurationFile(confFile); RMini method = new RMini(parameters); method.execute(); } /** * Main Program * @param args It contains the name of the configuration file<br/> * Format:<br/> * <em>algorith = &lt;algorithm name></em><br/> * <em>inputData = "&lt;training file&gt;" "&lt;validation file&gt;" "&lt;test file&gt;"</em> ...<br/> * <em>outputData = "&lt;training file&gt;" "&lt;test file&gt;"</em> ...<br/> * <br/> * <em>seed = value</em> (if used)<br/> * <em>&lt;Parameter1&gt; = &lt;value1&gt;</em><br/> * <em>&lt;Parameter2&gt; = &lt;value2&gt;</em> ... <br/> */ public static void main(String args[]) { Main program = new Main(); System.out.println("Executing Algorithm."); program.execute(args[0]); } }
SCI2SUGR/KEEL
src/keel/Algorithms/Genetic_Rule_Learning/RMini/Main.java
Java
gpl-3.0
2,637
/* DreamChess ** ** DreamChess is the legal property of its developers, whose names are too ** numerous to list here. Please refer to the AUTHORS.txt file distributed ** with this source distribution. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GAMEGUI_SIGNAL_H #define GAMEGUI_SIGNAL_H #include <gamegui/queue.h> #include <gamegui/system.h> typedef int gg_signal_t; gg_signal_t gg_signal_lookup(gg_class_id class, char *name); int gg_signal_register(gg_class_id class, char *name); void gg_signal_init(void); void gg_signal_exit(void); #endif
dreamchess/dreamchess
dreamchess/src/include/gamegui/signal.h
C
gpl-3.0
1,179
import { Component } from '@angular/core' @Component({ selector: 'gallery', templateUrl: 'app/home/gallery.component.html' }) export class GalleryComponent { }
PoojaM0267/BTMVDemo
BTMV_ng2/app/home/gallery.component.ts
TypeScript
gpl-3.0
172
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::globalPoints Description Calculates points shared by more than two processor patches or cyclic patches. Is used in globalMeshData. (this info is needed for point-edge communication where you do all but these shared points with patch to patch communication but need to do a reduce on these shared points) Works purely topological and using local communication only. Needs: - domain to be one single domain (i.e. all faces can be reached through face-cell walk). - patch face ordering to be ok - f[0] ordering on patch faces to be ok. Works by constructing equivalence lists for all the points on processor patches. These list are procPointList and give processor and meshPoint label on that processor. E.g. @verbatim ((7 93)(4 731)(3 114)) @endverbatim means point 93 on proc7 is connected to point 731 on proc4 and 114 on proc3. It then gets the lowest numbered processor (the 'master') to request a sharedPoint label from processor0 and it redistributes this label back to the other processors in the equivalence list. Algorithm: - get meshPoints of all my points on processor patches and initialize equivalence lists to this. loop - send to all neighbours in relative form: - patchFace - index in face - receive and convert into meshPoints. Add to to my equivalence lists. - mark meshPoints for which information changed. - send data for these meshPoints again endloop until nothing changes At this point one will have complete point-point connectivity for all points on processor patches. Now - remove point equivalences of size 2. These are just normal points shared between two neighbouring procPatches. - collect on each processor points for which it is the master - request number of sharedPointLabels from the Pstream::master. This information gets redistributed to all processors in a similar way as that in which the equivalence lists were collected: - initialize the indices of shared points I am the master for loop - send my known sharedPoints + meshPoints to all neighbours - receive from all neighbour. Find which meshPoint on my processor the sharedpoint is connected to - mark indices for which information has changed endloop until nothing changes. SourceFiles globalPoints.C \*---------------------------------------------------------------------------*/ #ifndef globalPoints_H #define globalPoints_H #include <OpenFOAM/DynamicList.H> #include <OpenFOAM/Map.H> #include <OpenFOAM/labelList.H> #include <OpenFOAM/FixedList.H> #include <OpenFOAM/primitivePatch.H> #include <OpenFOAM/className.H> #include <OpenFOAM/edgeList.H> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of classes class polyMesh; class polyBoundaryMesh; class cyclicPolyPatch; /*---------------------------------------------------------------------------*\ Class globalPoints Declaration \*---------------------------------------------------------------------------*/ class globalPoints { // Private classes //- Define procPointList as holding a list of meshPoint/processor labels typedef FixedList<label, 2> procPoint; typedef List<procPoint> procPointList; // Private data //- Mesh reference const polyMesh& mesh_; //- Sum of points on processor patches (unfiltered, point on 2 patches // counts as 2) const label nPatchPoints_; //- All points on boundaries and their corresponding connected points // on other processors. DynamicList<procPointList> procPoints_; //- Map from mesh point to index in procPoints Map<label> meshToProcPoint_; //- Shared points used by this processor (= global point number) labelList sharedPointAddr_; //- My meshpoints corresponding to the shared points labelList sharedPointLabels_; //- Total number of shared points. label nGlobalPoints_; // Private Member Functions //- Count all points on processorPatches. Is all points for which // information is collected. static label countPatchPoints(const polyBoundaryMesh&); //- Add information about patchPointI in relative indices to send // buffers (patchFaces, indexInFace etc.) static void addToSend ( const primitivePatch&, const label patchPointI, const procPointList&, DynamicList<label>& patchFaces, DynamicList<label>& indexInFace, DynamicList<procPointList>& allInfo ); //- Merge info from neighbour into my data static bool mergeInfo ( const procPointList& nbrInfo, procPointList& myInfo ); //- Store (and merge) info for meshPointI bool storeInfo(const procPointList& nbrInfo, const label meshPointI); //- Initialize procPoints_ to my patch points. allPoints = true: // seed with all patch points, = false: only boundaryPoints(). void initOwnPoints(const bool allPoints, labelHashSet& changedPoints); //- Send subset of procPoints to neighbours void sendPatchPoints(const labelHashSet& changedPoints) const; //- Receive neighbour points and merge into my procPoints. void receivePatchPoints(labelHashSet& changedPoints); //- Remove entries of size 2 where meshPoint is in provided Map. // Used to remove normal face-face connected points. void remove(const Map<label>&); //- Get indices of point for which I am master (lowest numbered proc) labelList getMasterPoints() const; //- Send subset of shared points to neighbours void sendSharedPoints(const labelList& changedIndices) const; //- Receive shared points and update subset. void receiveSharedPoints(labelList& changedIndices); //- Should move into cyclicPolyPatch but some ordering problem // keeps on giving problems. static edgeList coupledPoints(const cyclicPolyPatch&); //- Disallow default bitwise copy construct globalPoints(const globalPoints&); //- Disallow default bitwise assignment void operator=(const globalPoints&); public: //- Declare name of the class and its debug switch ClassName("globalPoints"); // Constructors //- Construct from mesh globalPoints(const polyMesh& mesh); // Member Functions // Access label nPatchPoints() const { return nPatchPoints_; } const Map<label>& meshToProcPoint() const { return meshToProcPoint_; } //- shared points used by this processor (= global point number) const labelList& sharedPointAddr() const { return sharedPointAddr_; } //- my meshpoints corresponding to the shared points const labelList& sharedPointLabels() const { return sharedPointLabels_; } label nGlobalPoints() const { return nGlobalPoints_; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************ vim: set sw=4 sts=4 et: ************************ //
themiwi/freefoam-debian
src/OpenFOAM/meshes/polyMesh/globalMeshData/globalPoints.H
C++
gpl-3.0
8,920
/* * Multi2Sim * Copyright (C) 2012 Rafael Ubal ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <assert.h> #include <lib/mhandle/mhandle.h> #include <lib/util/debug.h> #include <lib/util/linked-list.h> #include "opencl-repo.h" #include "opencl-command-queue.h" #include "opencl-context.h" #include "opencl-device.h" #include "opencl-event.h" #include "opencl-kernel.h" #include "opencl-mem.h" #include "opencl-platform.h" #include "opencl-program.h" #include "opencl-sampler.h" struct si_opencl_repo_t { struct linked_list_t *object_list; }; struct si_opencl_repo_t *si_opencl_repo_create(void) { struct si_opencl_repo_t *repo; /* Initialize */ repo = xcalloc(1, sizeof(struct si_opencl_repo_t)); repo->object_list = linked_list_create(); /* Return */ return repo; } void si_opencl_repo_free(struct si_opencl_repo_t *repo) { linked_list_free(repo->object_list); free(repo); } void si_opencl_repo_add_object(struct si_opencl_repo_t *repo, void *object) { struct linked_list_t *object_list = repo->object_list; /* Check that object does not exist */ linked_list_find(object_list, object); if (!object_list->error_code) fatal("%s: object already exists", __FUNCTION__); /* Insert */ linked_list_add(object_list, object); } void si_opencl_repo_remove_object(struct si_opencl_repo_t *repo, void *object) { struct linked_list_t *object_list = repo->object_list; /* Check that object exists */ linked_list_find(object_list, object); if (object_list->error_code) fatal("%s: object does not exist", __FUNCTION__); /* Remove */ linked_list_remove(object_list); } /* Look for an object in the repository. The first field of every OpenCL object * is its identifier. */ void *si_opencl_repo_get_object(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type, unsigned int object_id) { struct linked_list_t *object_list = repo->object_list; void *object; unsigned int current_object_id; /* Upper 16-bits represent the type of the object */ if (object_id >> 16 != type) fatal("%s: requested OpenCL object of incorrect type", __FUNCTION__); /* Search object */ LINKED_LIST_FOR_EACH(object_list) { object = linked_list_get(object_list); assert(object); current_object_id = * (unsigned int *) object; if (current_object_id == object_id) return object; } /* Not found */ fatal("%s: requested OpenCL does not exist (id=0x%x)", __FUNCTION__, object_id); return NULL; } /* Get the oldest created OpenCL object of the specified type */ void *si_opencl_repo_get_object_of_type(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type) { struct linked_list_t *object_list = repo->object_list; void *object; unsigned int object_id; /* Find object. Upper 16-bits of identifier contain its type. */ LINKED_LIST_FOR_EACH(object_list) { object = linked_list_get(object_list); assert(object); object_id = * (unsigned int *) object; if (object_id >> 16 == type) return object; } /* No object found */ return NULL; } /* Assignment of OpenCL object identifiers * An identifier is a 32-bit value, whose 16 most significant bits represent the * object type, while the 16 least significant bits represent a unique object ID. */ unsigned int si_opencl_repo_new_object_id(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type) { static unsigned int si_opencl_object_id_counter; unsigned int object_id; object_id = (type << 16) | si_opencl_object_id_counter; si_opencl_object_id_counter++; if (si_opencl_object_id_counter > 0xffff) fatal("%s: limit of OpenCL objects exceeded\n", __FUNCTION__); return object_id; } void si_opencl_repo_free_all_objects(struct si_opencl_repo_t *repo) { void *object; /* Platforms */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_platform))) si_opencl_platform_free((struct si_opencl_platform_t *) object); /* Devices */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_device))) si_opencl_device_free((struct si_opencl_device_t *) object); /* Contexts */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_context))) si_opencl_context_free((struct si_opencl_context_t *) object); /* Command queues */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_command_queue))) si_opencl_command_queue_free((struct si_opencl_command_queue_t *) object); /* Programs */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_program))) si_opencl_program_free((struct si_opencl_program_t *) object); /* Kernels */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_kernel))) si_opencl_kernel_free((struct si_opencl_kernel_t *) object); /* Mems */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_mem))) si_opencl_mem_free((struct si_opencl_mem_t *) object); /* Events */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_event))) si_opencl_event_free((struct si_opencl_event_t *) object); /* Samplers */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_sampler))) si_opencl_sampler_free((struct si_opencl_sampler_t *) object); /* Any object left */ if (linked_list_count(repo->object_list)) panic("%s: not all objects were freed", __FUNCTION__); }
filippo-ceid/multi2sim
src/arch/southern-islands/emu/opencl-repo.c
C
gpl-3.0
6,076
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; class ParityBackground extends Component { static propTypes = { style: PropTypes.object.isRequired, children: PropTypes.node, className: PropTypes.string, onClick: PropTypes.func }; render () { const { children, className, style, onClick } = this.props; return ( <div className={ className } style={ style } onTouchTap={ onClick }> { children } </div> ); } } function mapStateToProps (_, initProps) { const { gradient, seed, muiTheme } = initProps; let _seed = seed; let _props = { style: muiTheme.parity.getBackgroundStyle(gradient, seed) }; return (state, props) => { const { backgroundSeed } = state.settings; const { seed } = props; const newSeed = seed || backgroundSeed; if (newSeed === _seed) { return _props; } _seed = newSeed; _props = { style: muiTheme.parity.getBackgroundStyle(gradient, newSeed) }; return _props; }; } export default connect( mapStateToProps )(ParityBackground);
pdaian/parity
js/src/ui/ParityBackground/parityBackground.js
JavaScript
gpl-3.0
1,825
/** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ (function ($, require) { var exports = require('piwik/UI'); /** * Creates a new notifications. * * Example: * var UI = require('piwik/UI'); * var notification = new UI.Notification(); * notification.show('My Notification Message', {title: 'Low space', context: 'warning'}); */ var Notification = function () { this.$node = null; }; /** * Makes the notification visible. * * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} [options] * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {bool} [options.animate=true] If enabled, the notification will be faded in. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} * @param {string} [options.placeat] By default, the notification will be displayed in the "stats bar". * You can specify any other CSS selector to place the notifications * wherever you want. */ Notification.prototype.show = function (message, options) { checkMessage(message); options = checkOptions(options); var template = generateNotificationHtmlMarkup(options, message); this.$node = placeNotification(template, options); }; /** * Removes a previously shown notification having the given notification id. * * * @param {string} notificationId The id of a notification that was previously registered. */ Notification.prototype.remove = function (notificationId) { $('[piwik-notification][notification-id=' + notificationId + ']').remove(); }; Notification.prototype.scrollToNotification = function () { if (this.$node) { piwikHelper.lazyScrollTo(this.$node, 250); } }; /** * Shows a notification at a certain point with a quick upwards animation. * * TODO: if the materializecss version matomo uses is updated, should use their toasts. * * @type {Notification} * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} options * @param {string} options.placeat Where to place the notification. Required. * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} */ Notification.prototype.toast = function (message, options) { checkMessage(message); options = checkOptions(options); var $placeat = $(options.placeat); if (!$placeat.length) { throw new Error("A valid selector is required for the placeat option when using Notification.toast()."); } var $template = $(generateNotificationHtmlMarkup(options, message)).hide(); $('body').append($template); compileNotification($template); $template.css({ position: 'absolute', left: $placeat.offset().left, top: $placeat.offset().top }); setTimeout(function () { $template.animate( { top: $placeat.offset().top - $template.height() }, { duration: 300, start: function () { $template.show(); } } ); }); }; exports.Notification = Notification; function generateNotificationHtmlMarkup(options, message) { var attributeMapping = { id: 'notification-id', title: 'notification-title', context: 'context', type: 'type', noclear: 'noclear', class: 'class', toastLength: 'toast-length' }, html = '<div piwik-notification'; for (var key in attributeMapping) { if (attributeMapping.hasOwnProperty(key) && options[key] ) { html += ' ' + attributeMapping[key] + '="' + options[key].toString().replace(/"/g, "&quot;") + '"'; } } html += '>' + message + '</div>'; return html; } function compileNotification($node) { angular.element(document).injector().invoke(function ($compile, $rootScope) { $compile($node)($rootScope.$new(true)); }); } function placeNotification(template, options) { var $notificationNode = $(template); // compile the template in angular compileNotification($notificationNode); if (options.style) { $notificationNode.css(options.style); } var notificationPosition = '#notificationContainer'; var method = 'append'; if (options.placeat) { notificationPosition = options.placeat; } else { // If a modal is open, we want to make sure the error message is visible and therefore show it within the opened modal var modalSelector = '.modal.open .modal-content'; var modalOpen = $(modalSelector); if (modalOpen.length) { notificationPosition = modalSelector; method = 'prepend'; } } $notificationNode = $notificationNode.hide(); $(notificationPosition)[method]($notificationNode); if (false === options.animate) { $notificationNode.show(); } else { $notificationNode.fadeIn(1000); } return $notificationNode; } function checkMessage(message) { if (!message) { throw new Error('No message given, cannot display notification'); } } function checkOptions(options) { if (options && !$.isPlainObject(options)) { throw new Error('Options has the wrong format, cannot display notification'); } else if (!options) { options = {}; } return options; } })(jQuery, require);
piwik/piwik
plugins/CoreHome/javascripts/notification.js
JavaScript
gpl-3.0
7,980
PREP(initCBASettings); PREP(postInit);
Jamesadamar/OPT
[J]OPT.Altis/uav/XEH_PREP.hpp
C++
gpl-3.0
39
/* * Jinx is Copyright 2010-2020 by Jeremy Brooks and Contributors * * Jinx is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jinx is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jinx. If not, see <http://www.gnu.org/licenses/>. */ package net.jeremybrooks.jinx.api; import net.jeremybrooks.jinx.Jinx; import net.jeremybrooks.jinx.JinxException; import net.jeremybrooks.jinx.JinxUtils; import net.jeremybrooks.jinx.response.Response; import net.jeremybrooks.jinx.response.photos.notes.Note; import java.util.Map; import java.util.TreeMap; /** * Provides access to the flickr.photos.notes API methods. * * @author Jeremy Brooks * @see <a href="https://www.flickr.com/services/api/">Flickr API documentation</a> for more details. */ public class PhotosNotesApi { private Jinx jinx; public PhotosNotesApi(Jinx jinx) { this.jinx = jinx; } /** * Add a note to a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages. * <br> * This method requires authentication with 'write' permission. * * @param photoId (Required) The id of the photo to add a note to. * @param noteX (Required) The left coordinate of the note. * @param noteY (Required) The top coordinate of the note. * @param noteWidth (Required) The width of the note. * @param noteHeight (Required) The height of the note. * @param noteText (Required) The text of the note. * @return object with the ID for the newly created note. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.add.html">flickr.photos.notes.add</a> */ public Note add(String photoId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(photoId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.add"); params.put("photo_id", photoId); params.put("note_x", Integer.toString(noteX)); params.put("note_y", Integer.toString(noteY)); params.put("note_w", Integer.toString(noteWidth)); params.put("note_h", Integer.toString(noteHeight)); params.put("note_text", noteText); return jinx.flickrPost(params, Note.class); } /** * Edit a note on a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages. * <br> * This method requires authentication with 'write' permission. * * @param noteId (Required) The id of the note to edit. * @param noteX (Required) The left coordinate of the note. * @param noteY (Required) The top coordinate of the note. * @param noteWidth (Required) The width of the note. * @param noteHeight (Required) The height of the note. * @param noteText (Required) The text of the note. * @return object with the status of the requested operation. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.edit.html">flickr.photos.notes.edit</a> */ public Response edit(String noteId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(noteId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.edit"); params.put("note_id", noteId); params.put("note_x", Integer.toString(noteX)); params.put("note_y", Integer.toString(noteY)); params.put("note_w", Integer.toString(noteWidth)); params.put("note_h", Integer.toString(noteHeight)); params.put("note_text", noteText); return jinx.flickrPost(params, Response.class); } /** * Delete a note from a photo. * <br> * This method requires authentication with 'write' permission. * * @param noteId (Required) The id of the note to delete. * @return object with the status of the requested operation. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.delete.html">flickr.photos.notes.delete</a> */ public Response delete(String noteId) throws JinxException { JinxUtils.validateParams(noteId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.delete"); params.put("note_id", noteId); return jinx.flickrPost(params, Response.class); } }
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosNotesApi.java
Java
gpl-3.0
5,049
<?php /** * PHPUnit * * Copyright (c) 2002-2009, Sebastian Bergmann <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category Testing * @package PHPUnit * @author Jan Borsodi <[email protected]> * @author Sebastian Bergmann <[email protected]> * @copyright 2002-2009 Sebastian Bergmann <[email protected]> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version SVN: $Id: Parameters.php 4403 2008-12-31 09:26:51Z sb $ * @link http://www.phpunit.de/ * @since File available since Release 3.0.0 */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Util/Filter.php'; require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; require_once 'PHPUnit/Framework/MockObject/Invocation.php'; PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); /** * Invocation matcher which looks for specific parameters in the invocations. * * Checks the parameters of all incoming invocations, the parameter list is * checked against the defined constraints in $parameters. If the constraint * is met it will return true in matches(). * * @category Testing * @package PHPUnit * @author Jan Borsodi <[email protected]> * @author Sebastian Bergmann <[email protected]> * @copyright 2002-2009 Sebastian Bergmann <[email protected]> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version Release: 3.4.0beta1 * @link http://www.phpunit.de/ * @since Class available since Release 3.0.0 */ class PHPUnit_Framework_MockObject_Matcher_Parameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation { protected $parameters = array(); protected $invocation; public function __construct($parameters) { foreach($parameters as $parameter) { if (!($parameter instanceof PHPUnit_Framework_Constraint)) { $parameter = new PHPUnit_Framework_Constraint_IsEqual($parameter); } $this->parameters[] = $parameter; } } public function toString() { $text = 'with parameter'; foreach($this->parameters as $index => $parameter) { if ($index > 0) { $text .= ' and'; } $text .= ' ' . $index . ' ' . $parameter->toString(); } return $text; } public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) { $this->invocation = $invocation; $this->verify(); return count($invocation->parameters) < count($this->parameters); } public function verify() { if ($this->invocation === NULL) { throw new PHPUnit_Framework_ExpectationFailedException( 'Mocked method does not exist.' ); } if (count($this->invocation->parameters) < count($this->parameters)) { throw new PHPUnit_Framework_ExpectationFailedException( sprintf( 'Parameter count for invocation %s is too low.', $this->invocation->toString() ) ); } foreach ($this->parameters as $i => $parameter) { if (!$parameter->evaluate($this->invocation->parameters[$i])) { $parameter->fail( $this->invocation->parameters[$i], sprintf( 'Parameter %s for invocation %s does not match expected value.', $i, $this->invocation->toString() ) ); } } } } ?>
manusis/dblite
test/lib/phpunit/PHPUnit/Framework/MockObject/Matcher/Parameters.php
PHP
gpl-3.0
5,341
<?php /** * * @version 1.0.9 June 24, 2016 * @package Get Bible API * @author Llewellyn van der Merwe <[email protected]> * @copyright Copyright (C) 2013 Vast Development Method <http://www.vdm.io> * @license GNU General Public License <http://www.gnu.org/copyleft/gpl.html> * **/ defined( '_JEXEC' ) or die( 'Restricted access' ); //Import filesystem libraries. Perhaps not necessary, but does not hurt jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.application.component.helper'); class GetbibleModelImport extends JModelLegacy { protected $user; protected $dateSql; protected $book_counter; protected $app_params; protected $local = false; protected $curlError = false; public $availableVersions; public $availableVersionsList; public $installedVersions; public function __construct() { parent::__construct(); // get params $this->app_params = JComponentHelper::getParams('com_getbible'); // get user data $this->user = JFactory::getUser(); // get todays date $this->dateSql = JFactory::getDate()->toSql(); // we need a loger execution time if (ini_set('max_execution_time', 300) === false) { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_INCREASE_EXECUTION_TIME'), 'error'); return false; } // load available verstions $this->getVersionAvailable(); // get installed versions $this->getInstalledVersions(); } protected function populateState() { parent::populateState(); // Get the input data $jinput = JFactory::getApplication()->input; $source = $jinput->post->get('translation', NULL, 'STRING'); $translation = (string) preg_replace('/[^A-Z0-9_\)\(-]/i', '', $source); // Set to state $this->setState('translation', $translation); } public function getVersions() { // reload version list for app $available = $this->availableVersionsList; $alreadyin = $this->installedVersions; if($available){ if ($alreadyin){ $result = array_diff($available, $alreadyin); } else { $result = $available; } if($result){ $setVersions = array(); $setVersions[] = JHtml::_('select.option', '', JText::_('COM_GETBIBLE_PLEASE_SELECT')); foreach ($this->availableVersions as $key => $values){ if(in_array($key, $result)){ $name = $values["versionName"]. ' ('.$values["versionLang"].')'; $setVersions[] = JHtml::_('select.option', $values["fileName"], $name); } } return $setVersions; } JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_ALL_BIBLES_ALREADY_INSTALLED'), 'success'); return false; } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } public function rutime($ru, $rus, $index) { return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000)) - ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000)); } public function getImport() { if ($this->getState('translation')){ // set version $versionFileName = $this->getState('translation'); $versionfix = str_replace("___", "'", $versionFileName); list($versionLang,$versionName,$versionCode,$bidi) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $version = $versionCode; //check input if ($this->checkTranslation($version) && $this->checkFileName($versionFileName)){ // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); if($installOptions){ // get the file $filename = 'https://getbible.net/scriptureinstall/'.$versionFileName.'.txt'; } else { // get localInstallFolder set in params $filename = JPATH_ROOT.'/'.rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/').'/'.$versionFileName.'.txt'; } // load the file $file = new SplFileObject($filename); // start up database $db = JFactory::getDbo(); // load all books $books = $this->setBooks($version); $i = 1; // build query to save if (is_object($file)) { while (! $file->eof()) { $verse = explode("||",$file->fgets()); $found = false; // rename books foreach ($books as $book){ $verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0])); if ($book['nr'] <= 39) { if (strpos($verse[0],'O') !== false) { $search_value = sprintf("%02s", $book['nr']).'O'; } else { $search_value = sprintf("%02s", $book['nr']); } } else { if (strpos($verse[0],'N') !== false) { $search_value = $book['nr'].'N'; } else { $search_value = $book['nr']; } } if ($verse[0] == $search_value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $book_name = $book['name']; $found = true; break; } } if(!$found){ foreach ($books as $book){ $verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0])); foreach($book['book_names'] as $key => $value){ if ($value){ $value = strtoupper(preg_replace('/\s+/', '', $value)); if ($verse[0] == $value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $book_name = $book['name']; $found = true; break; } } } } } if(!$found){ // load all books again as KJV $books = $this->setBooks($version, true); foreach ($books as $book){ foreach($book['book_names'] as $key => $value){ if ($value){ $value = strtoupper(preg_replace('/\s+/', '', $value)); if ($verse[0] == $value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $found = true; break; } } } } } // set data if(isset($verse[3]) && $verse[3]){ $Bible[$verse[0]][$verse[1]][$verse[2]] = $verse[3]; // Create a new query object for this verse. $versObject = new stdClass(); $versObject->version = $version; $versObject->book_nr = $book_nr; $versObject->chapter_nr = $verse[1]; $versObject->verse_nr = $verse[2]; $versObject->verse = $verse[3]; $versObject->access = 1; $versObject->published = 1; $versObject->created_by = $this->user->id; $versObject->created_on = $this->dateSql; // Insert the object into the verses table. $result = JFactory::getDbo()->insertObject('#__getbible_verses', $versObject); } } } // clear from memory unset($file); // save complete books & chapters foreach ($books as $book) { if (isset($book["nr"]) && isset($Bible[$book["nr"]])) { $this->saveChapter($version, $book["nr"], $Bible[$book["nr"]]); $this->saveBooks($version, $book["nr"], $Bible[$book["nr"]]); } } // clear from memory unset($books); // Set version details if(is_array($this->book_counter)){ if(in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){ $testament = 'OT&NT'; } elseif(in_array(1,$this->book_counter) && !in_array(66,$this->book_counter)){ $testament = 'OT'; } elseif(!in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){ $testament = 'NT'; } else { $testament = 'NOT'; } $book_counter = json_encode($this->book_counter); } else { $book_counter = 'error'; $testament = 'error'; } // Create a new query object for this Version. $versionObject = new stdClass(); $versionObject->name = $versionName; $versionObject->bidi = $bidi; $versionObject->language = $versionLang; $versionObject->books_nr = $book_counter; $versionObject->testament = $testament; $versionObject->version = $version; $versionObject->link = $filename; $versionObject->installed = 1; $versionObject->access = 1; $versionObject->published = 1; $versionObject->created_by = $this->user->id; $versionObject->created_on = $this->dateSql; // Insert the object into the versions table. $result = JFactory::getDbo()->insertObject('#__getbible_versions', $versionObject); JFactory::getApplication()->enqueueMessage(JText::sprintf('COM_GETBIBLE_MESSAGE_BIBLE_INSTALLED_SUCCESSFULLY', $versionName)); // reset the local version list. $this->_cpanel(); // if first Bible is installed change the application to load localy with that Bible as the default $this->setLocal(); // clean cache to insure the dropdown removes this installed version. $this->cleanCache('_system'); return true; } else { return false; } } else { return false; } } protected function checkTranslation($version) { // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); $available = $this->availableVersionsList; $alreadyin = $this->installedVersions; if ($available){ if(in_array($version, $available)){ if ($alreadyin){ if(in_array($version, $alreadyin)){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_ALREADY_INSTALLED'), 'error'); return false; }return true; }return true; } JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_NOT_FOUND_ON_GETBIBLE'), 'error'); return false; } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } protected function checkFileName($versionFileName) { $available = $this->availableVersions; $found = false; if ($available){ foreach($available as $file){ if (in_array($versionFileName, $file)){ $found = true; break; } else { $found = false; } } if(!$found){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_NOT_FOUND_ON_GETBIBLE'), 'error'); return false; } else { return $found; } } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } protected function saveChapter($version, $book_nr, $chapters) { if ( $chapters ){ // start up database $db = JFactory::getDbo(); // Create a new query object for this verstion $query = $db->getQuery(true); // set chapter number $chapter_nr = 1; $values = ''; // set the data foreach ($chapters as $chapter) { $setup = NULL; $text = NULL; $ver = 1; foreach($chapter as $verse) { $text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse); $ver++; } $setup = array('chapter'=>$text); $scripture = json_encode($setup); // Insert values. $values[] = $db->quote($version).', '.(int)$book_nr.', '.(int)$chapter_nr.', '.$db->quote($scripture).', 1, 1, '.$this->user->id.', '.$db->quote($this->dateSql); $chapter_nr++; } // clear from memory unset($chapters); // Insert columns. $columns = array( 'version', 'book_nr', 'chapter_nr', 'chapter', 'access', 'published', 'created_by', 'created_on' ); // Prepare the insert query. $query->insert($db->quoteName('#__getbible_chapters')); $query->columns($db->quoteName($columns)); $query->values($values); // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->query(); } return true; } protected function saveBooks($version, $book_nr, $book) { if (is_array($book) && count($book)){ //set book number $this->book_counter[] = $book_nr; // start up database $db = JFactory::getDbo(); // Create a new query object for this verstion $query = $db->getQuery(true); // set chapter number $chapter_nr = 1; $values = ''; // set the data foreach ($book as $chapter) { $setup = NULL; $text = NULL; $ver = 1; foreach($chapter as $verse) { $text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse); $ver++; } $setupChapter[$chapter_nr] = array('chapter_nr'=>$chapter_nr,'chapter'=>$text); $chapter_nr++; } // clear from memory unset($book); $setup = array('book'=>$setupChapter); $saveBook = json_encode($setup); // Create a new query object for this verstion $query = $db->getQuery(true); // Insert columns. $columns = array('version', 'book_nr', 'book', 'access', 'published', 'created_by', 'created_on'); // Insert values. $values = array($db->quote($version), (int) $book_nr, $db->quote($saveBook), 1, 1, $this->user->id, $db->quote($this->dateSql)); // Prepare the insert query. $query ->insert($db->quoteName('#__getbible_books')) ->columns($db->quoteName($columns)) ->values(implode(',', $values)); //echo nl2br(str_replace('#__','api_',$query)); die; // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->query(); } return true; } protected function getInstalledVersions() { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName('version')); $query->from($db->quoteName('#__getbible_versions')); $query->order('version ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadColumn(); if ($results){ $this->installedVersions = $results; return true; } return false; } protected function setLocalXML() { jimport( 'joomla.filesystem.folder' ); // get localInstallFolder set in params $path = rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/'); // creat folder JFolder::create(JPATH_ROOT.'/'.$path.'/xml'); // set the file name $filepath = JPATH_ROOT.'/'.$path.'/xml/version.xml.php'; // set folder path $folderpath = JPATH_ROOT.'/'.$path; $fh = fopen($filepath, "w"); if (!is_resource($fh)) { return false; } $data = $this->setPHPforXML($folderpath); if(!fwrite($fh, $data)){ // close file. fclose($fh); return false; } // close file. fclose($fh); // return local file path return JURI::root().$path.'/xml/version.xml.php/versions.xml'; } protected function setPHPforXML($path) { return "<?php foreach (glob(\"".$path."/*.txt\") as \$filename) { \$available[] = str_replace('.txt', '', basename(\$filename)); // do something with \$filename } \$xml = new SimpleXMLElement('<versions/>'); foreach (\$available as \$version) { \$xml->addChild('name', \$version); } header('Content-type: text/xml'); header('Pragma: public'); header('Cache-control: private'); header('Expires: -1'); print(\$xml->asXML()); ?>"; } protected function getVersionAvailable() { // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); if(!$installOptions){ $xml = $this->setLocalXML(); $this->local = true; } else { // check the available versions on getBible $xml = 'https://getbible.net/scriptureinstall/xml/version.xml.php/versions.xml'; } if(@fopen($xml, 'r')){ if (($response_xml_data = file_get_contents($xml))===false){ $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { libxml_use_internal_errors(true); $data = simplexml_load_string($response_xml_data); if (!$data) { $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { foreach ($data->name as $version){ $versionfix = str_replace("___", "'", $version); list($versionLang,$versionName,$versionCode) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $versions[$versionCode]['fileName'] = $version; $versions[$versionCode]['versionName'] = $versionName; $versions[$versionCode]['versionLang'] = $versionLang; $versions[$versionCode]['versionCode'] = $versionCode; $version_list[] = $versionCode; } $this->availableVersions = $versions; $this->availableVersionsList = $version_list; return true; } } } elseif(function_exists('curl_init')){ $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL,$xml); $response_xml_data = curl_exec($ch); if(curl_error($ch)){ $this->curlError = curl_error($ch); } curl_close($ch); $data = simplexml_load_string($response_xml_data); // echo'<pre>';var_dump($data);exit; if (!$data) { $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { foreach ($data->name as $version){ $versionfix = str_replace("___", "'", $version); list($versionLang,$versionName,$versionCode) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $versions[$versionCode]['fileName'] = $version; $versions[$versionCode]['versionName'] = $versionName; $versions[$versionCode]['versionLang'] = $versionLang; $versions[$versionCode]['versionCode'] = $versionCode; $version_list[] = $versionCode; } $this->availableVersions = $versions; $this->availableVersionsList = $version_list; return true; } } else { $this->availableVersions = false; $this->availableVersionsList = false; return false; } } protected function setBooks($version = NULL, $retry = false, $default = 'kjv') { // Get a db connection. $db = JFactory::getDbo(); if ($version){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($version)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); if($results){ foreach ($results as $book){ $books[$book['book_nr']]['nr'] = $book['book_nr']; $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); // if retry do't change name $books[$book['book_nr']]['name'] = $book['book_name']; } } } if(!isset($books)){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($default)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); foreach ($results as $book){ $books[$book['book_nr']]['nr'] = $book['book_nr']; $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); $books[$book['book_nr']]['name'] = $book['book_name']; } } if($retry){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($default)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); foreach ($results as $book){ if(!$books[$book['book_nr']]['nr']){ $books[$book['book_nr']]['nr'] = $book['book_nr']; } $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); if(!$books[$book['book_nr']]['name']){ $books[$book['book_nr']]['name'] = $book['book_name']; } } } return $books; } protected function _cpanel() { // Base this model on the backend version. require_once JPATH_ADMINISTRATOR.'/components/com_getbible/models/cpanel.php'; $cpanel_model = new GetbibleModelCpanel; return $cpanel_model->setCpanel(); } protected function setLocal() { $this->getInstalledVersions(); $versions = $this->installedVersions; $number = count($versions); // only change to local API on install of first Bible if ($number == 1){ // get default Book Name $defaultStartBook = $this->app_params->get('defaultStartBook'); // make sure it is set to the correct name avaliable in this new default version // first get book number $book_nr = $this->getLocalBookNR($defaultStartBook, $versions[0]); // second check if this version has this book and return the book number it has $book_nr = $this->checkVersionBookNR($book_nr, $versions[0]); // third set the book name $defaultStartBook = $this->getLocalDefaultBook($defaultStartBook, $versions[0], $book_nr); // Update Global Settings $params = JComponentHelper::getParams('com_getbible'); $params->set('defaultStartVersion', $versions[0]); $params->set('defaultStartBook', $defaultStartBook); $params->set('jsonQueryOptions', 1); // Get a new database query instance $db = JFactory::getDBO(); $query = $db->getQuery(true); // Build the query $query->update('#__extensions AS a'); $query->set('a.params = ' . $db->quote((string)$params)); $query->where('a.element = "com_getbible"'); // Execute the query // echo nl2br(str_replace('#__','api_',$query)); die; $db->setQuery($query); $db->query(); return true; } return false; } protected function getLocalBookNR($defaultStartBook,$version,$retry = false) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_setbooks AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($version)); $query->where($db->quoteName('a.book_name') . ' = ' . $db->quote($defaultStartBook)); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $db->loadResult(); } else { // fall back on default if($retry){ return 43; } return $this->getLocalBookNR($defaultStartBook,'kjv',true); } } protected function checkVersionBookNR($book_nr, $defaultVersion) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_books AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $book_nr; } else { // Run the default // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_books AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadColumn(); // set book array $results = array_unique($results); // set book for Old Testament (Psalms) or New Testament (John) if (in_array(43,$results)){ return 43; } elseif(in_array(19,$results)) { return 19; } return false; } } protected function getLocalDefaultBook($defaultStartBook,$defaultVersion,$book_nr,$tryAgain = false) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_name'); $query->from('#__getbible_setbooks AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); if($tryAgain){ $query->where($db->quoteName('a.version') . ' = ' . $db->quote($tryAgain)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); } else { $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); } // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $db->loadResult(); } else { // fall back on default return $this->getLocalDefaultBook($defaultStartBook,$defaultVersion,$book_nr,'kjv'); } } }
getbible/Joomla-3-Component
admin/models/import.php
PHP
gpl-3.0
27,659
# recette_la42 la bière qui répond à la question sur la vie, l'univers et le reste Recette Bière de Blé Libre 4.2° - Blanche ## Ingrédients pour 100 litres * 15kg Malt Pils ardèche (Malteur Echos) * 10kg Malt Blé ardèche (Malteur Echos) * 2,5kg Flocon de blé (Celnat Haute Loire) ## Méthode * MONOPALIER * Empâtage 65.5° : 1h30 * Houblonnage : * Opal 20g Infusion 75mn * Opal 100g 1mn + pendant le transfert * Brewers gold 100g 1mn + pendant le transfert * Houblonnage à cru 7 jours entre 10 et 15° * OPAL 100g * Brewers gold 100g
Alolise/recette_la42
README.md
Markdown
gpl-3.0
578
/* Multiple Lua Programming Language : Intermediate Code Generator * Copyright(C) 2014 Cheryl Natsu * This file is part of multiple - Multiple Paradigm Language Interpreter * multiple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * multiple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "selfcheck.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "multiple_ir.h" #include "multiply.h" #include "multiply_assembler.h" #include "multiply_str_aux.h" #include "multiple_misc.h" #include "multiple_err.h" #include "vm_predef.h" #include "vm_opcode.h" #include "vm_types.h" #include "mlua_lexer.h" #include "mlua_ast.h" #include "mlua_icg.h" #include "mlua_icg_aux.h" #include "mlua_icg_fcb.h" #include "mlua_icg_context.h" #include "mlua_icg_expr.h" #include "mlua_icg_stmt.h" #include "mlua_icg_built_in_proc.h" #include "mlua_icg_built_in_table.h" /* Declaration */ int mlua_icodegen_statement_list(struct multiple_error *err, \ struct mlua_icg_context *context, \ struct mlua_icg_fcb_block *icg_fcb_block, \ struct mlua_map_offset_label_list *map_offset_label_list, \ struct mlua_ast_statement_list *list, \ struct multiply_offset_item_pack *offset_pack_break); static int mlua_icodegen_merge_blocks(struct multiple_error *err, \ struct mlua_icg_context *context) { int ret = 0; struct mlua_icg_fcb_block *icg_fcb_block_cur; struct mlua_icg_fcb_line *icg_fcb_line_cur; uint32_t instrument_number; struct multiple_ir_export_section_item *export_section_item_cur; struct multiple_ir_text_section_item *text_section_item_cur; uint32_t offset_start; uint32_t fcb_size = 0; uint32_t count; /* Do not disturb the instrument produced by other way */ offset_start = (uint32_t)(context->icode->text_section->size); export_section_item_cur = context->icode->export_section->begin; icg_fcb_block_cur = context->icg_fcb_block_list->begin; while (icg_fcb_block_cur != NULL) { icg_fcb_line_cur = icg_fcb_block_cur->begin; /* Record the absolute instrument number */ instrument_number = (uint32_t)context->icode->text_section->size; if (export_section_item_cur == NULL) { MULTIPLE_ERROR_INTERNAL(); ret = -MULTIPLE_ERR_INTERNAL; goto fail; } export_section_item_cur->instrument_number = instrument_number; while (icg_fcb_line_cur != NULL) { switch (icg_fcb_line_cur->type) { case MLUA_ICG_FCB_LINE_TYPE_NORMAL: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_PC: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, instrument_number + icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK: /* Operand of this instrument here is the index number of lambda */ if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_BLTIN_PROC_MK: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; } fcb_size += 1; icg_fcb_line_cur = icg_fcb_line_cur->next; } icg_fcb_block_cur = icg_fcb_block_cur->next; export_section_item_cur = export_section_item_cur->next; } /* 2nd pass, dealing with lambdas */ icg_fcb_block_cur = context->icg_fcb_block_list->begin; /* Skip text body of built-in procedures at the beginning part */ text_section_item_cur = context->icode->text_section->begin; while (offset_start-- > 0) { text_section_item_cur = text_section_item_cur->next; } /* Process lambda mks */ while (icg_fcb_block_cur != NULL) { icg_fcb_line_cur = icg_fcb_block_cur->begin; while (icg_fcb_line_cur != NULL) { if (icg_fcb_line_cur->type == MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK) { /* Locate to the export section item */ count = icg_fcb_line_cur->operand; export_section_item_cur = context->icode->export_section->begin; while ((export_section_item_cur != NULL) && (count != 0)) { count--; export_section_item_cur = export_section_item_cur->next; } if (export_section_item_cur == NULL) { MULTIPLE_ERROR_INTERNAL(); ret = -MULTIPLE_ERR_INTERNAL; goto fail; } text_section_item_cur->operand = export_section_item_cur->instrument_number; } text_section_item_cur = text_section_item_cur->next; icg_fcb_line_cur = icg_fcb_line_cur->next; } icg_fcb_block_cur = icg_fcb_block_cur->next; } goto done; fail: done: return ret; } static int mlua_icodegen_special(struct multiple_error *err, \ struct multiple_ir *icode, \ struct multiply_resource_id_pool *res_id, \ struct mlua_icg_fcb_block_list *icg_fcb_block_list, \ struct mlua_icg_fcb_block *icg_fcb_block, \ const char *name, const size_t name_len) { int ret = 0; uint32_t id; struct multiple_ir_export_section_item *new_export_section_item = NULL; new_export_section_item = multiple_ir_export_section_item_new(); if (new_export_section_item == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_export_section_item->args_count = 0; new_export_section_item->args = NULL; new_export_section_item->args_types = NULL; /* Return */ if ((ret = mlua_icg_fcb_block_append_with_configure(icg_fcb_block, OP_RETNONE, 0)) != 0) { goto fail; } /* Append block */ if ((ret = mlua_icg_fcb_block_list_append(icg_fcb_block_list, icg_fcb_block)) != 0) { MULTIPLE_ERROR_INTERNAL(); goto fail; } /* Append export section item */ if ((ret = multiply_resource_get_id( \ err, \ icode, \ res_id, \ &id, \ name, name_len)) != 0) { goto fail; } new_export_section_item->name = id; new_export_section_item->instrument_number = (uint32_t)icode->export_section->size; multiple_ir_export_section_append(icode->export_section, new_export_section_item); goto done; fail: if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item); done: return ret; } static int mlua_icodegen_program(struct multiple_error *err, \ struct mlua_icg_context *context, \ struct mlua_ast_program *program) { int ret = 0; struct mlua_icg_fcb_block *new_icg_fcb_block_autorun = NULL; struct mlua_map_offset_label_list *new_map_offset_label_list = NULL; uint32_t id; struct multiple_ir_export_section_item *new_export_section_item = NULL; uint32_t instrument_number_insert_point_built_in_proc; uint32_t instrument_count_built_in_proc; new_icg_fcb_block_autorun = mlua_icg_fcb_block_new(); if (new_icg_fcb_block_autorun == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_map_offset_label_list = mlua_map_offset_label_list_new(); if (new_map_offset_label_list == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_export_section_item = multiple_ir_export_section_item_new(); if (new_export_section_item == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } /* def in .text section */ if ((ret = multiply_resource_get_id( \ err, \ context->icode, \ context->res_id, \ &id, \ VM_PREDEF_MODULE_AUTORUN, \ VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } if ((ret = mlua_icg_fcb_block_append_with_configure(new_icg_fcb_block_autorun, OP_DEF, id)) != 0) { goto fail; } new_export_section_item->name = id; new_export_section_item->args_count = 0; new_export_section_item->args = NULL; new_export_section_item->args_types = NULL; instrument_number_insert_point_built_in_proc = mlua_icg_fcb_block_get_instrument_number(new_icg_fcb_block_autorun); /* Statements of top level */ if ((ret = mlua_icodegen_statement_list(err, context, \ new_icg_fcb_block_autorun, \ new_map_offset_label_list, \ program->stmts, NULL)) != 0) { goto fail; } /* Apply goto to label */ if ((ret = mlua_icodegen_statement_list_apply_goto(err, \ context, \ new_icg_fcb_block_autorun, \ new_map_offset_label_list)) != 0) { goto fail; } /* Pop a label offset pack */ multiply_offset_item_pack_stack_pop(context->offset_item_pack_stack); /* Put built-in procedures directly into icode, * and put initialize code into '__autorun__' */ if ((ret = mlua_icg_add_built_in_procs(err, \ context->icode, \ context->res_id, \ new_icg_fcb_block_autorun, \ context->customizable_built_in_procedure_list, \ instrument_number_insert_point_built_in_proc, &instrument_count_built_in_proc)) != 0) { goto fail; } /* Put built-in 'tables' directly into icode, * and put initialize code into '__autorun__' */ if ((ret = mlua_icg_add_built_in_tables(err, \ context->icode, \ context->res_id, \ new_icg_fcb_block_autorun, \ context->stdlibs, \ instrument_number_insert_point_built_in_proc, &instrument_count_built_in_proc)) != 0) { goto fail; } /* '__autorun__' subroutine */ if ((ret = mlua_icodegen_special( \ err, \ context->icode, \ context->res_id, \ context->icg_fcb_block_list, new_icg_fcb_block_autorun, \ VM_PREDEF_MODULE_AUTORUN, VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } new_icg_fcb_block_autorun = NULL; /* Append export section item */ if ((ret = multiply_resource_get_id( \ err, \ context->icode, \ context->res_id, \ &id, \ VM_PREDEF_MODULE_AUTORUN, \ VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } new_export_section_item->name = id; goto done; fail: if (new_icg_fcb_block_autorun != NULL) mlua_icg_fcb_block_destroy(new_icg_fcb_block_autorun); done: if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item); if (new_map_offset_label_list != NULL) mlua_map_offset_label_list_destroy(new_map_offset_label_list); return ret; } int mlua_irgen(struct multiple_error *err, \ struct multiple_ir **icode_out, \ struct mlua_ast_program *program, \ int verbose) { int ret = 0; struct mlua_icg_context context; struct mlua_icg_fcb_block_list *new_icg_fcb_block_list = NULL; struct multiple_ir *new_icode = NULL; struct multiply_resource_id_pool *new_res_id = NULL; struct mlua_icg_customizable_built_in_procedure_list *new_customizable_built_in_procedure_list = NULL; struct multiply_offset_item_pack_stack *new_offset_item_pack_stack = NULL; struct mlua_icg_stdlib_table_list *new_table_list = NULL; (void)verbose; if ((new_customizable_built_in_procedure_list = mlua_icg_customizable_built_in_procedure_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_icg_fcb_block_list = mlua_icg_fcb_block_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_offset_item_pack_stack = multiply_offset_item_pack_stack_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_table_list = mlua_icg_stdlib_table_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_icode = multiple_ir_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_res_id = multiply_resource_id_pool_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } mlua_icg_context_init(&context); context.icg_fcb_block_list = new_icg_fcb_block_list; context.icode = new_icode; context.res_id = new_res_id; context.customizable_built_in_procedure_list = new_customizable_built_in_procedure_list; context.offset_item_pack_stack = new_offset_item_pack_stack; context.stdlibs = new_table_list; /* Generating icode for '__init__' */ if ((ret = mlua_icodegen_program(err, \ &context, \ program)) != 0) { goto fail; } /* Merge blocks */ if ((ret = mlua_icodegen_merge_blocks(err, \ &context)) != 0) { goto fail; } *icode_out = new_icode; ret = 0; goto done; fail: if (new_icode != NULL) multiple_ir_destroy(new_icode); done: if (new_res_id != NULL) multiply_resource_id_pool_destroy(new_res_id); if (new_icg_fcb_block_list != NULL) mlua_icg_fcb_block_list_destroy(new_icg_fcb_block_list); if (new_customizable_built_in_procedure_list != NULL) \ { mlua_icg_customizable_built_in_procedure_list_destroy(new_customizable_built_in_procedure_list); } if (new_offset_item_pack_stack != NULL) { multiply_offset_item_pack_stack_destroy(new_offset_item_pack_stack); } if (new_table_list != NULL) { mlua_icg_stdlib_table_list_destroy(new_table_list); } return ret; }
zooxyt/lua
mlua_icg.c
C
gpl-3.0
15,534
package de.jotschi.geo.osm.tags; import org.w3c.dom.Node; public class OsmMember { String type, ref, role; public OsmMember(Node node) { ref = node.getAttributes().getNamedItem("ref").getNodeValue(); role = node.getAttributes().getNamedItem("role").getNodeValue(); type = node.getAttributes().getNamedItem("type").getNodeValue(); } public String getType() { return type; } public String getRef() { return ref; } public String getRole() { return role; } }
Jotschi/libTinyOSM
src/main/java/de/jotschi/geo/osm/tags/OsmMember.java
Java
gpl-3.0
490
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Library\CommandLine\AbstractCommandLineController | Library</title> <link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="../../css/sami.css"> <script src="../../js/jquery-1.11.1.min.js"></script> <script src="../../js/bootstrap.min.js"></script> <script src="../../js/typeahead.min.js"></script> <script src="../../sami.js"></script> <meta name="MobileOptimized" content="width"> <meta name="HandheldFriendly" content="true"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"> </head> <body id="class" data-name="class:Library_CommandLine_AbstractCommandLineController" data-root-path="../../"> <div id="content"> <div id="left-column"> <div id="control-panel"> <form id="search-form" action="../../search.html" method="GET"> <span class="glyphicon glyphicon-search"></span> <input name="search" class="typeahead form-control" type="search" placeholder="Search"> </form> </div> <div id="api-tree"></div> </div> <div id="right-column"> <nav id="site-nav" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../index.html">Library</a> </div> <div class="collapse navbar-collapse" id="navbar-elements"> <ul class="nav navbar-nav"> <li><a href="../../classes.html">Classes</a></li> <li><a href="../../namespaces.html">Namespaces</a></li> <li><a href="../../interfaces.html">Interfaces</a></li> <li><a href="../../traits.html">Traits</a></li> <li><a href="../../doc-index.html">Index</a></li> <li><a href="../../search.html">Search</a></li> </ul> </div> </div> </nav> <div class="namespace-breadcrumbs"> <ol class="breadcrumb"> <li><span class="label label-default">class</span></li> <li><a href="../../Library.html">Library</a></li> <li><a href="../../Library/CommandLine.html">CommandLine</a></li> <li>AbstractCommandLineController</li> </ol> </div> <div id="page-content"> <div class="page-header"> <h1>AbstractCommandLineController</h1> </div> <p> class <strong>AbstractCommandLineController</strong> implements <a href="../../Library/CommandLine/CommandLineControllerInterface.html"><abbr title="Library\CommandLine\CommandLineControllerInterface">CommandLineControllerInterface</abbr></a> </p> <div class="description"> <p>Basic command line controller</p> <p>Any command line controller must extend this abstract class.</p> <p>It defines some basic command line options that you must not overwrite in your child class:</p> <ul> <li>"h | help" : get a usage information,</li> <li>"v | verbose" : increase verbosity of the execution (written strings must be handled in your scripts),</li> <li>"x | debug" : execute the script in "debug" mode (must write actions before executing them),</li> <li>"q | quiet" : turn verbosity totally off during the execution (only errors and informations will be written),</li> <li>"f | force" : force some actions (avoid interactions),</li> <li>"i | interactive" : increase interactivity of the execution,</li> <li>"version" : get some version information about running environment.</li> </ul> </p> </div> <h2>Properties</h2> <table class="table table-condensed"> <tr> <td class="type" id="property__name"> static string </td> <td>$_name</td> <td class="last">This must be over-written in any child class</td> <td></td> </tr> <tr> <td class="type" id="property__version"> static string </td> <td>$_version</td> <td class="last">This must be over-written in any child class</td> <td></td> </tr> </table> <h2>Methods</h2> <div class="container-fluid underlined"> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method___construct">__construct</a>( array $options = array()) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method___toString">__toString</a>() <p>Magic distribution when printing object</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_distribute">distribute</a>() <p>Distribution of the work</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <a href="../../Library/CommandLine/AbstractCommandLineController.html"><abbr title="Library\CommandLine\AbstractCommandLineController">AbstractCommandLineController</abbr></a> </div> <div class="col-md-8 type"> <a href="#method_setDebug">setDebug</a>( bool $dbg = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setVerbose">setVerbose</a>( bool $vbr = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setForce">setForce</a>( bool $frc = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setInteractive">setInteractive</a>( bool $frc = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setQuiet">setQuiet</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_addDoneMethod">addDoneMethod</a>( string $_cls_meth) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> array </div> <div class="col-md-8 type"> <a href="#method_getDoneMethods">getDoneMethods</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_setScript">setScript</a>( string $script_name) <p>Set the current command line script called</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string|null </div> <div class="col-md-8 type"> <a href="#method_getScript">getScript</a>() <p>Get the current command line script called</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_setParameters">setParameters</a>( array $params) <p>Set the command line parameters</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> array </div> <div class="col-md-8 type"> <a href="#method_getParameters">getParameters</a>() <p>Get the parameters collection</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runHelpCommand">runHelpCommand</a>($opt = null) <p>List of all options and features of the command line tool ; for some commands, a specific help can be available, running <var>--command --help</var> Some command examples are purposed running <var>--console --help</var></p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runVerboseCommand">runVerboseCommand</a>() <p>Run the command line in <bold>verbose</bold> mode, writing some information on screen (default is <option>OFF</option>)</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runQuietCommand">runQuietCommand</a>() <p>Run the command line in <bold>quiet</bold> mode, trying to not write anything on screen (default is <option>OFF</option>)</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runDebugCommand">runDebugCommand</a>() <p>Run the command line in <bold>debug</bold> mode, writing some scripts information during runtime (default is <option>OFF</option>)</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runForceCommand">runForceCommand</a>() <p>Run the command line in <bold>forced</bold> mode ; any choice will be set on default value if so</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runInteractiveCommand">runInteractiveCommand</a>() <p>Run the command line in <bold>interactive</bold> mode ; any choice will be prompted if possible</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runVersionCommand">runVersionCommand</a>() <p>Get versions of system environment</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_write">write</a>( null $str = null, bool $new_line = true) <p>Format and write a string to STDOUT</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_error">error</a>( null $str = null, int $status = 1, bool $new_line = true) <p>Format and write an error message to STDOUT (or STDERR) and exits with status <code>$status</code></p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_parseAndWrite">parseAndWrite</a>( string $str, null $type = null, bool $spaced = false) <p>Parse, format and write a message to STDOUT</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeError">writeError</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeThinError">writeThinError</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeInfo">writeInfo</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeComment">writeComment</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeHighlight">writeHighlight</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeBreak">writeBreak</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeStop">writeStop</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_verboseWrite">verboseWrite</a>( null $str = null, bool $new_line = true) <p>Write a string only in verbose mode</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_debugWrite">debugWrite</a>( null $str = null, bool $new_line = true) <p>Write a string only in debug mode</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method_prompt">prompt</a>( string|null $str = null, mixed|null $default = null) <p>Prompt user input</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method_getPrompt">getPrompt</a>() <p>Get last user input</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_writeIntro">writeIntro</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getVersionString">getVersionString</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_writeNothingToDo">writeNothingToDo</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runArgumentHelp">runArgumentHelp</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_usage">usage</a>($opt = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getopt">getopt</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getOptionMethod">getOptionMethod</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getOptionDescription">getOptionDescription</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getOptionHelp">getOptionHelp</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> </div> <h2>Details</h2> <div id="method-details"> <div class="method-item"> <h3 id="method___construct"> <div class="location">at line 175</div> <code> <strong>__construct</strong>( array $options = array())</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> array</td> <td>$options</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method___toString"> <div class="location">at line 219</div> <code> string <strong>__toString</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Magic distribution when printing object</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_distribute"> <div class="location">at line 228</div> <code> <strong>distribute</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Distribution of the work</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_setDebug"> <div class="location">at line 248</div> <code> <a href="../../Library/CommandLine/AbstractCommandLineController.html"><abbr title="Library\CommandLine\AbstractCommandLineController">AbstractCommandLineController</abbr></a> <strong>setDebug</strong>( bool $dbg = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$dbg</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <a href="../../Library/CommandLine/AbstractCommandLineController.html"><abbr title="Library\CommandLine\AbstractCommandLineController">AbstractCommandLineController</abbr></a></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setVerbose"> <div class="location">at line 259</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setVerbose</strong>( bool $vbr = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$vbr</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setForce"> <div class="location">at line 269</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setForce</strong>( bool $frc = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$frc</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setInteractive"> <div class="location">at line 279</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setInteractive</strong>( bool $frc = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$frc</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setQuiet"> <div class="location">at line 290</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setQuiet</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> <h4>See also</h4> <table class="table table-condensed"> <tr> <td>self::setVerbose()</td> <td></td> </tr> <tr> <td>self::setDebug()</td> <td></td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_addDoneMethod"> <div class="location">at line 301</div> <code> <strong>addDoneMethod</strong>( string $_cls_meth)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$_cls_meth</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getDoneMethods"> <div class="location">at line 310</div> <code> array <strong>getDoneMethods</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> array</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setScript"> <div class="location">at line 321</div> <code> <strong>setScript</strong>( string $script_name)</code> </h3> <div class="details"> <div class="method-description"> <p>Set the current command line script called</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$script_name</td> <td>The script name</td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getScript"> <div class="location">at line 332</div> <code> string|null <strong>getScript</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get the current command line script called</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string|null</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setParameters"> <div class="location">at line 343</div> <code> <strong>setParameters</strong>( array $params)</code> </h3> <div class="details"> <div class="method-description"> <p>Set the command line parameters</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> array</td> <td>$params</td> <td>The collection of parameters</td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getParameters"> <div class="location">at line 354</div> <code> array <strong>getParameters</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get the parameters collection</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> array</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_runHelpCommand"> <div class="location">at line 368</div> <code> <strong>runHelpCommand</strong>($opt = null)</code> </h3> <div class="details"> <div class="method-description"> <p>List of all options and features of the command line tool ; for some commands, a specific help can be available, running <var>--command --help</var> Some command examples are purposed running <var>--console --help</var></p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$opt</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_runVerboseCommand"> <div class="location">at line 391</div> <code> <strong>runVerboseCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>verbose</bold> mode, writing some information on screen (default is <option>OFF</option>)</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runQuietCommand"> <div class="location">at line 399</div> <code> <strong>runQuietCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>quiet</bold> mode, trying to not write anything on screen (default is <option>OFF</option>)</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runDebugCommand"> <div class="location">at line 407</div> <code> <strong>runDebugCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>debug</bold> mode, writing some scripts information during runtime (default is <option>OFF</option>)</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runForceCommand"> <div class="location">at line 415</div> <code> <strong>runForceCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>forced</bold> mode ; any choice will be set on default value if so</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runInteractiveCommand"> <div class="location">at line 423</div> <code> <strong>runInteractiveCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>interactive</bold> mode ; any choice will be prompted if possible</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runVersionCommand"> <div class="location">at line 431</div> <code> <strong>runVersionCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get versions of system environment</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_write"> <div class="location">at line 460</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>write</strong>( null $str = null, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Format and write a string to STDOUT</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_error"> <div class="location">at line 474</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>error</strong>( null $str = null, int $status = 1, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Format and write an error message to STDOUT (or STDERR) and exits with status <code>$status</code></p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> int</td> <td>$status</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_parseAndWrite"> <div class="location">at line 488</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>parseAndWrite</strong>( string $str, null $type = null, bool $spaced = false)</code> </h3> <div class="details"> <div class="method-description"> <p>Parse, format and write a message to STDOUT</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> <tr> <td> null</td> <td>$type</td> <td> </td> </tr> <tr> <td> bool</td> <td>$spaced</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeError"> <div class="location">at line 503</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeError</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeThinError"> <div class="location">at line 514</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeThinError</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeInfo"> <div class="location">at line 526</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeInfo</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeComment"> <div class="location">at line 536</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeComment</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeHighlight"> <div class="location">at line 547</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeHighlight</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeBreak"> <div class="location">at line 556</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeBreak</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeStop"> <div class="location">at line 565</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeStop</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_verboseWrite"> <div class="location">at line 585</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>verboseWrite</strong>( null $str = null, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Write a string only in verbose mode</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_debugWrite"> <div class="location">at line 598</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>debugWrite</strong>( null $str = null, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Write a string only in debug mode</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_prompt"> <div class="location">at line 611</div> <code> string <strong>prompt</strong>( string|null $str = null, mixed|null $default = null)</code> </h3> <div class="details"> <div class="method-description"> <p>Prompt user input</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string|null</td> <td>$str</td> <td> </td> </tr> <tr> <td> mixed|null</td> <td>$default</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getPrompt"> <div class="location">at line 624</div> <code> string <strong>getPrompt</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get last user input</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeIntro"> <div class="location">at line 641</div> <code> <strong>writeIntro</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_getVersionString"> <div class="location">at line 651</div> <code> <strong>getVersionString</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_writeNothingToDo"> <div class="location">at line 664</div> <code> <strong>writeNothingToDo</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runArgumentHelp"> <div class="location">at line 671</div> <code> <strong>runArgumentHelp</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_usage"> <div class="location">at line 684</div> <code> <strong>usage</strong>($opt = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$opt</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getopt"> <div class="location">at line 788</div> <code> <strong>getopt</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_getOptionMethod"> <div class="location">at line 795</div> <code> <strong>getOptionMethod</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getOptionDescription"> <div class="location">at line 802</div> <code> <strong>getOptionDescription</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getOptionHelp"> <div class="location">at line 807</div> <code> <strong>getOptionHelp</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/">Sami, the API Documentation Generator</a>. </div> </div> </div> </body> </html>
atelierspierrot/library
phpdoc/Library/CommandLine/AbstractCommandLineController.html
HTML
gpl-3.0
63,915
/********************* * bio_tune_menu.cpp * *********************/ /**************************************************************************** * Written By Mark Pelletier 2017 - Aleph Objects, Inc. * * Written By Marcio Teixeira 2018 - Aleph Objects, Inc. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * To view a copy of the GNU General Public License, go to the following * * location: <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "../config.h" #if ENABLED(TOUCH_UI_FTDI_EVE) && defined(TOUCH_UI_LULZBOT_BIO) #include "screens.h" using namespace FTDI; using namespace Theme; using namespace ExtUI; void TuneMenu::onRedraw(draw_mode_t what) { #define GRID_ROWS 8 #define GRID_COLS 2 if (what & BACKGROUND) { CommandProcessor cmd; cmd.cmd(CLEAR_COLOR_RGB(bg_color)) .cmd(CLEAR(true,true,true)) .cmd(COLOR_RGB(bg_text_enabled)) .tag(0) .font(font_large) .text( BTN_POS(1,1), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_MENU)); } if (what & FOREGROUND) { CommandProcessor cmd; cmd.colors(normal_btn) .font(font_medium) .enabled( isPrinting()).tag(2).button( BTN_POS(1,2), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_SPEED)) .tag(3).button( BTN_POS(1,3), BTN_SIZE(2,1), GET_TEXT_F(MSG_BED_TEMPERATURE)) .enabled(TERN_(BABYSTEPPING, true)) .tag(4).button( BTN_POS(1,4), BTN_SIZE(2,1), GET_TEXT_F(MSG_NUDGE_NOZZLE)) .enabled(!isPrinting()).tag(5).button( BTN_POS(1,5), BTN_SIZE(2,1), GET_TEXT_F(MSG_MOVE_TO_HOME)) .enabled(!isPrinting()).tag(6).button( BTN_POS(1,6), BTN_SIZE(2,1), GET_TEXT_F(MSG_RAISE_PLUNGER)) .enabled(!isPrinting()).tag(7).button( BTN_POS(1,7), BTN_SIZE(2,1), GET_TEXT_F(MSG_RELEASE_XY_AXIS)) .colors(action_btn) .tag(1).button( BTN_POS(1,8), BTN_SIZE(2,1), GET_TEXT_F(MSG_BACK)); } #undef GRID_COLS #undef GRID_ROWS } bool TuneMenu::onTouchEnd(uint8_t tag) { switch (tag) { case 1: GOTO_PREVIOUS(); break; case 2: GOTO_SCREEN(FeedratePercentScreen); break; case 3: GOTO_SCREEN(TemperatureScreen); break; case 4: GOTO_SCREEN(NudgeNozzleScreen); break; case 5: GOTO_SCREEN(BioConfirmHomeXYZ); break; case 6: SpinnerDialogBox::enqueueAndWait_P(F("G0 E0 F120")); break; case 7: StatusScreen::unlockMotors(); break; default: return false; } return true; } #endif // TOUCH_UI_FTDI_EVE
tetious/Marlin
Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/screens/bio_tune_menu.cpp
C++
gpl-3.0
3,525
/* * Copyright (C) 2006-2010 - Frictional Games * * This file is part of HPL1 Engine. * * HPL1 Engine is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HPL1 Engine is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HPL1 Engine. If not, see <http://www.gnu.org/licenses/>. */ #include "scene/Entity3D.h" #include "scene/Node3D.h" #include "math/Math.h" #include "graphics/RenderList.h" #include "system/LowLevelSystem.h" #include "scene/PortalContainer.h" namespace hpl { ////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- iEntity3D::iEntity3D(tString asName) : iEntity(asName) { m_mtxLocalTransform = cMatrixf::Identity; m_mtxWorldTransform = cMatrixf::Identity; mbTransformUpdated = true; mlCount = 0; mlGlobalRenderCount = cRenderList::GetGlobalRenderCount(); msSourceFile = ""; mbApplyTransformToBV = true; mbUpdateBoundingVolume = true; mpParent = NULL; mlIteratorCount =-1; mpCurrentSector = NULL; } iEntity3D::~iEntity3D() { if(mpParent) mpParent->RemoveChild(this); for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it) { iEntity3D *pChild = *it; pChild->mpParent = NULL; } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- cVector3f iEntity3D::GetLocalPosition() { return m_mtxLocalTransform.GetTranslation(); } //----------------------------------------------------------------------- cMatrixf& iEntity3D::GetLocalMatrix() { return m_mtxLocalTransform; } //----------------------------------------------------------------------- cVector3f iEntity3D::GetWorldPosition() { UpdateWorldTransform(); return m_mtxWorldTransform.GetTranslation(); } //----------------------------------------------------------------------- cMatrixf& iEntity3D::GetWorldMatrix() { UpdateWorldTransform(); return m_mtxWorldTransform; } //----------------------------------------------------------------------- void iEntity3D::SetPosition(const cVector3f& avPos) { m_mtxLocalTransform.m[0][3] = avPos.x; m_mtxLocalTransform.m[1][3] = avPos.y; m_mtxLocalTransform.m[2][3] = avPos.z; SetTransformUpdated(); } //----------------------------------------------------------------------- void iEntity3D::SetMatrix(const cMatrixf& a_mtxTransform) { m_mtxLocalTransform = a_mtxTransform; SetTransformUpdated(); } //----------------------------------------------------------------------- void iEntity3D::SetWorldPosition(const cVector3f& avWorldPos) { if(mpParent) { SetPosition(avWorldPos - mpParent->GetWorldPosition()); } else { SetPosition(avWorldPos); } } //----------------------------------------------------------------------- void iEntity3D::SetWorldMatrix(const cMatrixf& a_mtxWorldTransform) { if(mpParent) { SetMatrix(cMath::MatrixMul(cMath::MatrixInverse(mpParent->GetWorldMatrix()), a_mtxWorldTransform)); } else { SetMatrix(a_mtxWorldTransform); } } //----------------------------------------------------------------------- void iEntity3D::SetTransformUpdated(bool abUpdateCallbacks) { mbTransformUpdated = true; mlCount++; //Perhaps not update this yet? This is baaaad! if(mbApplyTransformToBV) mBoundingVolume.SetTransform(GetWorldMatrix()); mbUpdateBoundingVolume = true; //Update children for(tEntity3DListIt EntIt = mlstChildren.begin(); EntIt != mlstChildren.end();++EntIt) { iEntity3D *pChild = *EntIt; pChild->SetTransformUpdated(true); } //Update callbacks if(mlstCallbacks.empty() || abUpdateCallbacks==false) return; tEntityCallbackListIt it = mlstCallbacks.begin(); for(; it!= mlstCallbacks.end(); ++it) { iEntityCallback* pCallback = *it; pCallback->OnTransformUpdate(this); } } //----------------------------------------------------------------------- bool iEntity3D::GetTransformUpdated() { return mbTransformUpdated; } //----------------------------------------------------------------------- int iEntity3D::GetTransformUpdateCount() { return mlCount; } //----------------------------------------------------------------------- void iEntity3D::AddCallback(iEntityCallback *apCallback) { mlstCallbacks.push_back(apCallback); } //----------------------------------------------------------------------- void iEntity3D::RemoveCallback(iEntityCallback *apCallback) { STLFindAndDelete(mlstCallbacks, apCallback); } //----------------------------------------------------------------------- void iEntity3D::AddChild(iEntity3D *apEntity) { if(apEntity==NULL)return; if(apEntity->mpParent != NULL) return; mlstChildren.push_back(apEntity); apEntity->mpParent = this; apEntity->SetTransformUpdated(true); } void iEntity3D::RemoveChild(iEntity3D *apEntity) { for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();) { iEntity3D *pChild = *it; if(pChild == apEntity) { pChild->mpParent = NULL; it = mlstChildren.erase(it); } else { ++it; } } } bool iEntity3D::IsChild(iEntity3D *apEntity) { for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it) { iEntity3D *pChild = *it; if(pChild == apEntity) return true; } return false; } iEntity3D * iEntity3D::GetEntityParent() { return mpParent; } //----------------------------------------------------------------------- bool iEntity3D::IsInSector(cSector *apSector) { //Log("-- %s --\n",msName.c_str()); //bool bShouldReturnTrue = false; if(apSector == GetCurrentSector()) { //Log("Should return true\n"); //bShouldReturnTrue = true; return true; } tRenderContainerDataList *pDataList = GetRenderContainerDataList(); tRenderContainerDataListIt it = pDataList->begin(); for(; it != pDataList->end(); ++it) { iRenderContainerData *pRenderContainerData = *it; cSector *pSector = static_cast<cSector*>(pRenderContainerData); //Log("%s (%d) vs %s (%d)\n",pSector->GetId().c_str(),pSector, apSector->GetId().c_str(),apSector); if(pSector == apSector) { //Log("return true!\n"); return true; } } //if(bShouldReturnTrue)Log(" %s should have returned true. Sectors: %d\n",msName.c_str(), mlstRenderContainerData.size()); //Log("return false!\n"); return false; } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void iEntity3D::UpdateWorldTransform() { if(mbTransformUpdated) { mbTransformUpdated = false; //first check if there is a node parent if(mpParentNode) { cNode3D* pNode3D = static_cast<cNode3D*>(mpParentNode); m_mtxWorldTransform = cMath::MatrixMul(pNode3D->GetWorldMatrix(), m_mtxLocalTransform); } //If there is no node parent check for entity parent else if(mpParent) { m_mtxWorldTransform = cMath::MatrixMul(mpParent->GetWorldMatrix(), m_mtxLocalTransform); } else { m_mtxWorldTransform = m_mtxLocalTransform; } } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // SAVE OBJECT STUFF ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- kBeginSerializeVirtual(cSaveData_iEntity3D,cSaveData_iEntity) kSerializeVar(m_mtxLocalTransform,eSerializeType_Matrixf) kSerializeVar(mBoundingVolume,eSerializeType_Class) kSerializeVar(msSourceFile,eSerializeType_String) kSerializeVar(mlParentId,eSerializeType_Int32) kSerializeVarContainer(mlstChildren,eSerializeType_Int32) kEndSerialize() //----------------------------------------------------------------------- iSaveData* iEntity3D::CreateSaveData() { return NULL; } //----------------------------------------------------------------------- void iEntity3D::SaveToSaveData(iSaveData *apSaveData) { kSaveData_SaveToBegin(iEntity3D); //Log("-------- Saving %s --------------\n",msName.c_str()); kSaveData_SaveTo(m_mtxLocalTransform); kSaveData_SaveTo(mBoundingVolume); kSaveData_SaveTo(msSourceFile); kSaveData_SaveObject(mpParent,mlParentId); kSaveData_SaveIdList(mlstChildren,tEntity3DListIt,mlstChildren); /*if(mlstChildren.empty()==false) { Log("Children in '%s'/'%s': ",msName.c_str(),GetEntityType().c_str()); for(tEntity3DListIt it=mlstChildren.begin(); it != mlstChildren.end(); ++it) { iEntity3D *pEntity = *it; Log("('%d/%s'/'%s'), ",pEntity->GetSaveObjectId(),pEntity->GetName().c_str(),pEntity->GetEntityType().c_str()); } Log("\n"); }*/ } //----------------------------------------------------------------------- void iEntity3D::LoadFromSaveData(iSaveData *apSaveData) { kSaveData_LoadFromBegin(iEntity3D); //Log("-------- Loading %s --------------\n",msName.c_str()); SetMatrix(pData->m_mtxLocalTransform); //Not sure of this is needed: kSaveData_LoadFrom(mBoundingVolume); kSaveData_LoadFrom(msSourceFile); } //----------------------------------------------------------------------- void iEntity3D::SaveDataSetup(cSaveObjectHandler *apSaveObjectHandler, cGame *apGame) { kSaveData_SetupBegin(iEntity3D); //Log("-------- Setup %s --------------\n",msName.c_str()); //kSaveData_LoadObject(mpParent,mlParentId,iEntity3D*); //kSaveData_LoadIdList(mlstChildren,mlstChildren,iEntity3D*); if(pData->mlParentId!=-1 && mpParent == NULL) { iEntity3D *pParentEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(pData->mlParentId)); if(pParentEntity) pParentEntity->AddChild(this); else Error("Couldn't find parent entity id %d for '%s'\n",pData->mlParentId,GetName().c_str()); } cContainerListIterator<int> it = pData->mlstChildren.GetIterator(); while(it.HasNext()) { int mlId = it.Next(); if(mlId != -1) { iEntity3D *pChildEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(mlId)); if(pChildEntity) AddChild(pChildEntity); else Error("Couldn't find child entity id %d for '%s'\n",mlId,GetName().c_str()); } } SetTransformUpdated(true); } //----------------------------------------------------------------------- }
FrictionalGames/HPL1Engine
sources/scene/Entity3D.cpp
C++
gpl-3.0
11,350
from feeluown.utils.dispatch import Signal from feeluown.gui.widgets.my_music import MyMusicModel class MyMusicItem(object): def __init__(self, text): self.text = text self.clicked = Signal() class MyMusicUiManager: """ .. note:: 目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。 我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic 的上下文。 而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。 """ def __init__(self, app): self._app = app self._items = [] self.model = MyMusicModel(app) @classmethod def create_item(cls, text): return MyMusicItem(text) def add_item(self, item): self.model.add(item) self._items.append(item) def clear(self): self._items.clear() self.model.clear()
cosven/FeelUOwn
feeluown/gui/uimodels/my_music.py
Python
gpl-3.0
980
(function() { var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']); app.config(function($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }); app.directive('article', function () { var controller = function () { var vm = this; }; var getSelectionText = function() { if(window.getSelection) { return window.getSelection().toString(); } if(document.selection && document.selection.type != "Control") { return document.selection.createRange().text; } return ""; }; var link = function link(scope, element, attrs) { scope.toggleComments = function () { scope.$broadcast("event:toggle"); } scope.menuOptions = [['Copy', function ($itemScope) { }], null, // Dividier ['Comment', function ($itemScope) { scope.toggleComments(); }]]; }; return { restrict: 'EA', //Default for 1.3+ scope: { text: '@text', url: '@url' }, controller: controller, link: link, controllerAs: 'vm', bindToController: true, //required in 1.3+ with controllerAs templateUrl: '/article/article.html' }; }); }());
lowdev/Article-Annotater
src/main/resources/static/article/angular-article-directive.js
JavaScript
gpl-3.0
1,330
/******************************************************************************* * This file is part of RedReader. * * RedReader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RedReader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RedReader. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.quantumbadger.redreader.io; import org.quantumbadger.redreader.common.collections.WeakReferenceListManager; public class UpdatedVersionListenerNotifier<K, V extends WritableObject<K>> implements WeakReferenceListManager.ArgOperator<UpdatedVersionListener<K, V>, V> { @Override public void operate(final UpdatedVersionListener<K, V> listener, final V data) { listener.onUpdatedVersion(data); } }
QuantumBadger/RedReader
src/main/java/org/quantumbadger/redreader/io/UpdatedVersionListenerNotifier.java
Java
gpl-3.0
1,255
<?php /** * Copyright 2013 Android Holo Colors by Jérôme Van Der Linden * Copyright 2010 Android Asset Studio by Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require_once('common-fastscroll.php'); $color = $_GET['color']; $size = $_GET['size']; $holo = $_GET['holo']; $component = $_GET['component']; if (isset($color) && isset($size) && isset($holo) && isset($component)) { switch ($component) { case "fastscroll": $et = new Fastscroll(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; case "fastscroll-pressed": $et = new FastscrollPressed(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; default: $et = new Fastscroll(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; } $et->generate_image($color, $size, $holo); } ?>
Medialoha/MAB-LAB
libs/asset-studio-colors/widgets/fastscroll/fastscroll.php
PHP
gpl-3.0
1,370
# Only run if this is an interactive text bash session if [ -n "$PS1" ] && [ -n "$BASH_VERSION" ] && [ -z "$DISPLAY" ]; then echo "Press enter to activate this console" read answer # The user should have chosen their preferred keyboard layout # in tails-greeter by now. . /etc/default/locale . /etc/default/keyboard sudo setupcon fi
kolohe/amnesia
config/chroot_local-includes/etc/profile.d/setup_console.sh
Shell
gpl-3.0
354
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Sat Oct 28 21:24:43 CEST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class nxt.util.MiningPlot (burstcoin 1.3.6cg API)</title> <meta name="date" content="2017-10-28"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class nxt.util.MiningPlot (burstcoin 1.3.6cg API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../nxt/util/MiningPlot.html" title="class in nxt.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?nxt/util/class-use/MiningPlot.html" target="_top">Frames</a></li> <li><a href="MiningPlot.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class nxt.util.MiningPlot" class="title">Uses of Class<br>nxt.util.MiningPlot</h2> </div> <div class="classUseContainer">No usage of nxt.util.MiningPlot</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../nxt/util/MiningPlot.html" title="class in nxt.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?nxt/util/class-use/MiningPlot.html" target="_top">Frames</a></li> <li><a href="MiningPlot.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017. All rights reserved.</small></p> </body> </html>
dawallet/burstwindowswallet
burstcoin-1.3.6/html/ui/doc/nxt/util/class-use/MiningPlot.html
HTML
gpl-3.0
4,173
/* * This file is protected by Copyright. Please refer to the COPYRIGHT file * distributed with this source distribution. * * This file is part of GNUHAWK. * * GNUHAWK is free software: you can redistribute it and/or modify is under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see http://www.gnu.org/licenses/. */ #include "streams_to_stream_ff_1i_base.h" /******************************************************************************************* AUTO-GENERATED CODE. DO NOT MODIFY The following class functions are for the base class for the component class. To customize any of these functions, do not modify them here. Instead, overload them on the child class ******************************************************************************************/ streams_to_stream_ff_1i_base::streams_to_stream_ff_1i_base(const char *uuid, const char *label) : GnuHawkBlock(uuid, label), serviceThread(0), noutput_items(0), _maintainTimeStamp(false), _throttle(false) { construct(); } void streams_to_stream_ff_1i_base::construct() { Resource_impl::_started = false; loadProperties(); serviceThread = 0; sentEOS = false; inputPortOrder.resize(0);; outputPortOrder.resize(0); PortableServer::ObjectId_var oid; float_in = new bulkio::InFloatPort("float_in"); float_in->setNewStreamListener(this, &streams_to_stream_ff_1i_base::float_in_newStreamCallback); oid = ossie::corba::RootPOA()->activate_object(float_in); float_out = new bulkio::OutFloatPort("float_out"); oid = ossie::corba::RootPOA()->activate_object(float_out); registerInPort(float_in); inputPortOrder.push_back("float_in"); registerOutPort(float_out, float_out->_this()); outputPortOrder.push_back("float_out"); } /******************************************************************************************* Framework-level functions These functions are generally called by the framework to perform housekeeping. *******************************************************************************************/ void streams_to_stream_ff_1i_base::initialize() throw (CF::LifeCycle::InitializeError, CORBA::SystemException) { } void streams_to_stream_ff_1i_base::start() throw (CORBA::SystemException, CF::Resource::StartError) { boost::mutex::scoped_lock lock(serviceThreadLock); if (serviceThread == 0) { float_in->unblock(); serviceThread = new ProcessThread<streams_to_stream_ff_1i_base>(this, 0.1); serviceThread->start(); } if (!Resource_impl::started()) { Resource_impl::start(); } } void streams_to_stream_ff_1i_base::stop() throw (CORBA::SystemException, CF::Resource::StopError) { if ( float_in ) float_in->block(); { boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.clear(); } // release the child thread (if it exists) if (serviceThread != 0) { { boost::mutex::scoped_lock lock(serviceThreadLock); LOG_TRACE( streams_to_stream_ff_1i_base, "Stopping Service Function" ); serviceThread->stop(); } if ( !serviceThread->release()) { throw CF::Resource::StopError(CF::CF_NOTSET, "Processing thread did not die"); } boost::mutex::scoped_lock lock(serviceThreadLock); if ( serviceThread ) { delete serviceThread; } } serviceThread = 0; if (Resource_impl::started()) { Resource_impl::stop(); } LOG_TRACE( streams_to_stream_ff_1i_base, "COMPLETED STOP REQUEST" ); } CORBA::Object_ptr streams_to_stream_ff_1i_base::getPort(const char* _id) throw (CORBA::SystemException, CF::PortSupplier::UnknownPort) { std::map<std::string, Port_Provides_base_impl *>::iterator p_in = inPorts.find(std::string(_id)); if (p_in != inPorts.end()) { if (!strcmp(_id,"float_in")) { bulkio::InFloatPort *ptr = dynamic_cast<bulkio::InFloatPort *>(p_in->second); if (ptr) { return ptr->_this(); } } } std::map<std::string, CF::Port_var>::iterator p_out = outPorts_var.find(std::string(_id)); if (p_out != outPorts_var.end()) { return CF::Port::_duplicate(p_out->second); } throw (CF::PortSupplier::UnknownPort()); } void streams_to_stream_ff_1i_base::releaseObject() throw (CORBA::SystemException, CF::LifeCycle::ReleaseError) { // This function clears the component running condition so main shuts down everything try { stop(); } catch (CF::Resource::StopError& ex) { // TODO - this should probably be logged instead of ignored } // deactivate ports releaseInPorts(); releaseOutPorts(); delete(float_in); delete(float_out); Resource_impl::releaseObject(); } void streams_to_stream_ff_1i_base::loadProperties() { addProperty(item_size, 4, "item_size", "item_size", "readonly", "", "external", "configure"); addProperty(nstreams, 1, "nstreams", "nstreams", "readonly", "", "external", "configure"); } // // Allow for logging // PREPARE_LOGGING(streams_to_stream_ff_1i_base); inline static unsigned int round_up (unsigned int n, unsigned int multiple) { return ((n + multiple - 1) / multiple) * multiple; } inline static unsigned int round_down (unsigned int n, unsigned int multiple) { return (n / multiple) * multiple; } uint32_t streams_to_stream_ff_1i_base::getNOutputStreams() { return 0; } void streams_to_stream_ff_1i_base::setupIOMappings( ) { int ninput_streams = 0; int noutput_streams = 0; std::vector<std::string>::iterator pname; std::string sid(""); int inMode=RealMode; if ( !validGRBlock() ) return; ninput_streams = gr_sptr->get_max_input_streams(); gr_io_signature_sptr g_isig = gr_sptr->input_signature(); noutput_streams = gr_sptr->get_max_output_streams(); gr_io_signature_sptr g_osig = gr_sptr->output_signature(); LOG_DEBUG( streams_to_stream_ff_1i_base, "GNUHAWK IO MAPPINGS IN/OUT " << ninput_streams << "/" << noutput_streams ); // // Someone reset the GR Block so we need to clean up old mappings if they exists // we need to reset the io signatures and check the vlens // if ( _istreams.size() > 0 || _ostreams.size() > 0 ) { LOG_DEBUG( streams_to_stream_ff_1i_base, "RESET INPUT SIGNATURE SIZE:" << _istreams.size() ); IStreamList::iterator istream; for ( int idx=0 ; istream != _istreams.end(); idx++, istream++ ) { // re-add existing stream definitons LOG_DEBUG( streams_to_stream_ff_1i_base, "ADD READ INDEX TO GNU RADIO BLOCK"); if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // setup io signature istream->associate( gr_sptr ); } LOG_DEBUG( streams_to_stream_ff_1i_base, "RESET OUTPUT SIGNATURE SIZE:" << _ostreams.size() ); OStreamList::iterator ostream; for ( int idx=0 ; ostream != _ostreams.end(); idx++, ostream++ ) { // need to evaluate new settings...??? ostream->associate( gr_sptr ); } return; } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio input stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // Stream Identifiers will be pass along as they are received // LOG_TRACE( streams_to_stream_ff_1i_base, "setupIOMappings INPUT PORTS: " << inPorts.size() ); pname = inputPortOrder.begin(); for( int i=0; pname != inputPortOrder.end(); pname++ ) { // grab ports based on their order in the scd.xml file RH_ProvidesPortMap::iterator p_in = inPorts.find(*pname); if ( p_in != inPorts.end() ) { bulkio::InFloatPort *port = dynamic_cast< bulkio::InFloatPort * >(p_in->second); int mode = inMode; sid = ""; // need to add read index to GNU Radio Block for processing streams when max_input == -1 if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // check if we received SRI during setup BULKIO::StreamSRISequence_var sris = port->activeSRIs(); if ( sris->length() > 0 ) { BULKIO::StreamSRI sri = sris[sris->length()-1]; mode = sri.mode; } std::vector<int> in; io_mapping.push_back( in ); _istreams.push_back( gr_istream< bulkio::InFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( streams_to_stream_ff_1i_base, "ADDING INPUT MAP IDX:" << i << " SID:" << sid ); // increment port counter i++; } } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio output stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // LOG_TRACE( streams_to_stream_ff_1i_base, "setupIOMappings OutputPorts: " << outPorts.size() ); pname = outputPortOrder.begin(); for( int i=0; pname != outputPortOrder.end(); pname++ ) { // grab ports based on their order in the scd.xml file RH_UsesPortMap::iterator p_out = outPorts.find(*pname); if ( p_out != outPorts.end() ) { bulkio::OutFloatPort *port = dynamic_cast< bulkio::OutFloatPort * >(p_out->second); int idx = -1; BULKIO::StreamSRI sri = createOutputSRI( i, idx ); if (idx == -1) idx = i; if(idx < (int)io_mapping.size()) io_mapping[idx].push_back(i); int mode = sri.mode; sid = sri.streamID; _ostreams.push_back( gr_ostream< bulkio::OutFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( streams_to_stream_ff_1i_base, "ADDING OUTPUT MAP IDX:" << i << " SID:" << sid ); _ostreams[i].setSRI(sri, i ); // increment port counter i++; } } } void streams_to_stream_ff_1i_base::float_in_newStreamCallback( BULKIO::StreamSRI &sri ) { LOG_TRACE( streams_to_stream_ff_1i_base, "START NotifySRI port:stream " << float_in->getName() << "/" << sri.streamID); boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.push_back( std::make_pair( float_in, sri ) ); LOG_TRACE( streams_to_stream_ff_1i_base, "END NotifySRI QUEUE " << _sriQueue.size() << " port:stream " << float_in->getName() << "/" << sri.streamID); } void streams_to_stream_ff_1i_base::processStreamIdChanges() { boost::mutex::scoped_lock lock(_sriMutex); LOG_TRACE( streams_to_stream_ff_1i_base, "processStreamIDChanges QUEUE: " << _sriQueue.size() ); if ( _sriQueue.size() == 0 ) return; std::string sid(""); if ( validGRBlock() ) { IStreamList::iterator istream; int idx=0; std::string sid(""); int mode=0; SRIQueue::iterator item = _sriQueue.begin(); for ( ; item != _sriQueue.end(); item++ ) { idx = 0; sid = ""; mode= item->second.mode; sid = item->second.streamID; istream = _istreams.begin(); for ( ; istream != _istreams.end(); idx++, istream++ ) { if ( istream->port == item->first ) { LOG_DEBUG( streams_to_stream_ff_1i_base, " SETTING IN_STREAM ID/STREAM_ID :" << idx << "/" << sid ); istream->sri(true); istream->spe(mode); LOG_DEBUG( streams_to_stream_ff_1i_base, " SETTING OUT_STREAM ID/STREAM_ID :" << idx << "/" << sid ); setOutputStreamSRI( idx, item->second ); } } } _sriQueue.clear(); } else { LOG_WARN( streams_to_stream_ff_1i_base, " NEW STREAM ID, NO GNU RADIO BLOCK DEFINED, SRI QUEUE SIZE:" << _sriQueue.size() ); } } BULKIO::StreamSRI streams_to_stream_ff_1i_base::createOutputSRI( int32_t oidx ) { // for each output stream set the SRI context BULKIO::StreamSRI sri = BULKIO::StreamSRI(); sri.hversion = 1; sri.xstart = 0.0; sri.xdelta = 1; sri.xunits = BULKIO::UNITS_TIME; sri.subsize = 0; sri.ystart = 0.0; sri.ydelta = 0.0; sri.yunits = BULKIO::UNITS_NONE; sri.mode = 0; std::ostringstream t; t << naming_service_name.c_str() << "_" << oidx; std::string sid = t.str(); sri.streamID = CORBA::string_dup(sid.c_str()); return sri; } BULKIO::StreamSRI streams_to_stream_ff_1i_base::createOutputSRI( int32_t oidx, int32_t &in_idx) { return createOutputSRI( oidx ); } void streams_to_stream_ff_1i_base::adjustOutputRate(BULKIO::StreamSRI &sri ) { if ( validGRBlock() ) { double ret=sri.xdelta*gr_sptr->relative_rate(); /** ret = ret / gr_sptr->interpolation(); **/ LOG_TRACE( streams_to_stream_ff_1i_base, "ADJUSTING SRI.XDELTA FROM/TO: " << sri.xdelta << "/" << ret ); sri.xdelta = ret; } } streams_to_stream_ff_1i_base::TimeDuration streams_to_stream_ff_1i_base::getTargetDuration() { TimeDuration t_drate;; uint64_t samps=0; double xdelta=1.0; double trate=1.0; if ( _ostreams.size() > 0 ) { samps= _ostreams[0].nelems(); xdelta= _ostreams[0].sri.xdelta; } trate = samps*xdelta; uint64_t sec = (uint64_t)trunc(trate); uint64_t usec = (uint64_t)((trate-sec)*1e6); t_drate = boost::posix_time::seconds(sec) + boost::posix_time::microseconds(usec); LOG_TRACE( streams_to_stream_ff_1i_base, " SEC/USEC " << sec << "/" << usec << "\n" << " target_duration " << t_drate ); return t_drate; } streams_to_stream_ff_1i_base::TimeDuration streams_to_stream_ff_1i_base::calcThrottle( TimeMark &start_time, TimeMark &end_time ) { TimeDuration delta; TimeDuration target_duration = getTargetDuration(); if ( start_time.is_not_a_date_time() == false ) { TimeDuration s_dtime= end_time - start_time; delta = target_duration - s_dtime; delta /= 4; LOG_TRACE( streams_to_stream_ff_1i_base, " s_time/t_dime " << s_dtime << "/" << target_duration << "\n" << " delta " << delta ); } return delta; } template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int streams_to_stream_ff_1i_base::_transformerServiceFunction( typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams , typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams ) { typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList; typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList; boost::mutex::scoped_lock lock(serviceThreadLock); if ( validGRBlock() == false ) { // create our processing block, and setup property notifiers createBlock(); LOG_DEBUG( streams_to_stream_ff_1i_base, " FINISHED BUILDING GNU RADIO BLOCK"); } //process any Stream ID changes this could affect number of io streams processStreamIdChanges(); if ( !validGRBlock() || istreams.size() == 0 || ostreams.size() == 0 ) { LOG_WARN( streams_to_stream_ff_1i_base, "NO STREAMS ATTACHED TO BLOCK..." ); return NOOP; } _input_ready.resize( istreams.size() ); _ninput_items_required.resize( istreams.size() ); _ninput_items.resize( istreams.size() ); _input_items.resize( istreams.size() ); _output_items.resize( ostreams.size() ); // // RESOLVE: need to look at forecast strategy, // 1) see how many read items are necessary for N number of outputs // 2) read input data and see how much output we can produce // // // Grab available data from input streams // typename _OStreamList::iterator ostream; typename _IStreamList::iterator istream = istreams.begin(); int nitems=0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { // note this a blocking read that can cause deadlocks nitems = istream->read(); if ( istream->overrun() ) { LOG_WARN( streams_to_stream_ff_1i_base, " NOT KEEPING UP WITH STREAM ID:" << istream->streamID ); } if ( istream->sriChanged() ) { // RESOLVE - need to look at how SRI changes can affect Gnu Radio BLOCK state LOG_DEBUG( streams_to_stream_ff_1i_base, "SRI CHANGED, STREAMD IDX/ID: " << idx << "/" << istream->pkt->streamID ); setOutputStreamSRI( idx, istream->pkt->SRI ); } } LOG_TRACE( streams_to_stream_ff_1i_base, "READ NITEMS: " << nitems ); if ( nitems <= 0 && !_istreams[0].eos() ) { return NOOP; } bool eos = false; int nout = 0; bool workDone = false; while ( nout > -1 && serviceThread->threadRunning() ) { eos = false; nout = _forecastAndProcess( eos, istreams, ostreams ); if ( nout > -1 ) { workDone = true; // we chunked on data so move read pointer.. istream = istreams.begin(); for ( ; istream != istreams.end(); istream++ ) { int idx=std::distance( istreams.begin(), istream ); // if we processed data for this stream if ( _input_ready[idx] ) { size_t nitems = 0; try { nitems = gr_sptr->nitems_read( idx ); } catch(...){} if ( nitems > istream->nitems() ) { LOG_WARN( streams_to_stream_ff_1i_base, "WORK CONSUMED MORE DATA THAN AVAILABLE, READ/AVAILABLE " << nitems << "/" << istream->nitems() ); nitems = istream->nitems(); } istream->consume( nitems ); LOG_TRACE( streams_to_stream_ff_1i_base, " CONSUME READ DATA ITEMS/REMAIN " << nitems << "/" << istream->nitems()); } } gr_sptr->reset_read_index(); } // check for not enough data return if ( nout == -1 ) { // check for end of stream istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++) { if ( istream->eos() ) { eos=true; } } if ( eos ) { LOG_TRACE( streams_to_stream_ff_1i_base, "EOS SEEN, SENDING DOWNSTREAM " ); _forecastAndProcess( eos, istreams, ostreams); } } } if ( eos ) { istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++ ) { int idx=std::distance( istreams.begin(), istream ); LOG_DEBUG( streams_to_stream_ff_1i_base, " CLOSING INPUT STREAM IDX:" << idx ); istream->close(); } // close remaining output streams ostream = ostreams.begin(); for ( ; eos && ostream != ostreams.end(); ostream++ ) { int idx=std::distance( ostreams.begin(), ostream ); LOG_DEBUG( streams_to_stream_ff_1i_base, " CLOSING OUTPUT STREAM IDX:" << idx ); ostream->close(); } } // // set the read pointers of the GNU Radio Block to start at the beginning of the // supplied buffers // gr_sptr->reset_read_index(); LOG_TRACE( streams_to_stream_ff_1i_base, " END OF TRANSFORM SERVICE FUNCTION....." << noutput_items ); if ( nout == -1 && eos == false && !workDone ) { return NOOP; } else { return NORMAL; } } template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int streams_to_stream_ff_1i_base::_forecastAndProcess( bool &eos, typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams , typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams ) { typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList; typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList; typename _OStreamList::iterator ostream; typename _IStreamList::iterator istream = istreams.begin(); int nout = 0; bool dataReady = false; if ( !eos ) { uint64_t max_items_avail = 0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { LOG_TRACE( streams_to_stream_ff_1i_base, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" << istream->nitems() << "/" << istream->_data.size() ); max_items_avail = std::max( istream->nitems(), max_items_avail ); } if ( max_items_avail == 0 ) { LOG_TRACE( streams_to_stream_ff_1i_base, "DATA CHECK - MAX ITEMS NOUTPUT/MAX_ITEMS:" << noutput_items << "/" << max_items_avail); return -1; } // // calc number of output elements based on input items available // noutput_items = 0; if ( !gr_sptr->fixed_rate() ) { noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple()); LOG_TRACE( streams_to_stream_ff_1i_base, " VARIABLE FORECAST NOUTPUT == " << noutput_items ); } else { istream = istreams.begin(); for ( int i=0; istream != istreams.end(); i++, istream++ ) { int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( istream->nitems() ); if ( gr_sptr->output_multiple_set() ) { t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple()); } if ( t_noutput_items > 0 ) { if ( noutput_items == 0 ) { noutput_items = t_noutput_items; } if ( t_noutput_items <= noutput_items ) { noutput_items = t_noutput_items; } } } LOG_TRACE( streams_to_stream_ff_1i_base, " FIXED FORECAST NOUTPUT/output_multiple == " << noutput_items << "/" << gr_sptr->output_multiple()); } // // ask the block how much input they need to produce noutput_items... // if enough data is available to process then set the dataReady flag // int32_t outMultiple = gr_sptr->output_multiple(); while ( !dataReady && noutput_items >= outMultiple ) { // // ask the block how much input they need to produce noutput_items... // gr_sptr->forecast(noutput_items, _ninput_items_required); LOG_TRACE( streams_to_stream_ff_1i_base, "--> FORECAST IN/OUT " << _ninput_items_required[0] << "/" << noutput_items ); istream = istreams.begin(); uint32_t dr_cnt=0; for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) { // check if buffer has enough elements _input_ready[idx] = false; if ( istream->nitems() >= (uint64_t)_ninput_items_required[idx] ) { _input_ready[idx] = true; dr_cnt++; } LOG_TRACE( streams_to_stream_ff_1i_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << istream->nelems() << "/" << istream->nitems() << "/" << _ninput_items_required[idx] << "/" << _input_ready[idx]); } if ( dr_cnt < istreams.size() ) { if ( outMultiple > 1 ) { noutput_items -= outMultiple; } else { noutput_items /= 2; } } else { dataReady = true; } LOG_TRACE( streams_to_stream_ff_1i_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady ); } // check if data is ready... if ( !dataReady ) { LOG_TRACE( streams_to_stream_ff_1i_base, "DATA CHECK - NOT ENOUGH DATA AVAIL/REQ:" << _istreams[0].nitems() << "/" << _ninput_items_required[0] ); return -1; } // reset looping variables int ritems = 0; int nitems = 0; // reset caching vectors _output_items.clear(); _input_items.clear(); _ninput_items.clear(); istream = istreams.begin(); for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) { // check if the stream is ready if ( !_input_ready[idx] ) { continue; } // get number of items remaining try { ritems = gr_sptr->nitems_read( idx ); } catch(...){ // something bad has happened, we are missing an input stream LOG_ERROR( streams_to_stream_ff_1i_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" << istream->streamID ); return -2; } nitems = istream->nitems() - ritems; LOG_TRACE( streams_to_stream_ff_1i_base, " ISTREAM: IDX:" << idx << " ITEMS AVAIL/READ/REQ " << nitems << "/" << ritems << "/" << _ninput_items_required[idx] ); if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) { //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0; _ninput_items.push_back( nitems ); _input_items.push_back( (const void *) (istream->read_pointer(ritems)) ); } } // // setup output buffer vector based on noutput.. // ostream = ostreams.begin(); for( ; ostream != ostreams.end(); ostream++ ) { ostream->resize(noutput_items); _output_items.push_back((void*)(ostream->write_pointer()) ); } nout=0; if ( _input_items.size() != 0 && serviceThread->threadRunning() ) { LOG_TRACE( streams_to_stream_ff_1i_base, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems << " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size()); nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items); LOG_TRACE( streams_to_stream_ff_1i_base, "RETURN WORK ..... N_OUT:" << nout); } // check for stop condition from work method if ( nout < gr_block::WORK_DONE ) { LOG_WARN( streams_to_stream_ff_1i_base, "WORK RETURNED STOP CONDITION..." << nout ); nout=0; eos = true; } } if (nout != 0 or eos ) { noutput_items = nout; LOG_TRACE( streams_to_stream_ff_1i_base, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos); ostream = ostreams.begin(); typename IN_PORT_TYPE::dataTransfer *pkt=NULL; for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) { pkt=NULL; int inputIdx = idx; if ( (size_t)(inputIdx) >= istreams.size() ) { for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx--) { if ( istreams[inputIdx].pkt != NULL ) { pkt = istreams[inputIdx].pkt; break; } } } else { pkt = istreams[inputIdx].pkt; } LOG_TRACE( streams_to_stream_ff_1i_base, "PUSHING DATA ITEMS/STREAM_ID " << ostream->nitems() << "/" << ostream->streamID ); if ( _maintainTimeStamp ) { // set time stamp for output samples based on input time stamp if ( ostream->nelems() == 0 ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "SEED - TS SRI: xdelta:" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM WRITE: maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "SEED - TS frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif ostream->setTimeStamp( pkt->T, _maintainTimeStamp ); } // write out samples, and set next time stamp based on xdelta and noutput_items ostream->write ( noutput_items, eos ); } else { // use incoming packet's time stamp to forward if ( pkt ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "PKT - TS maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << pkt->T.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << pkt->T.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << pkt->T.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << pkt->T.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "PKT - TS frac:" << std::setprecision(12) << pkt->T.tfsec ); #endif ostream->write( noutput_items, eos, pkt->T ); } else { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM TOD maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM TOD frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif // use time of day as time stamp ostream->write( noutput_items, eos, _maintainTimeStamp ); } } } // for ostreams } return nout; }
RedhawkSDR/integration-gnuhawk
components/streams_to_stream_ff_1i/cpp/streams_to_stream_ff_1i_base.cpp
C++
gpl-3.0
31,922
/* Copyright (C) 2014 PencilBlue, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Interface for managing topics */ function ManageTopics() {} //inheritance util.inherits(ManageTopics, pb.BaseController); var SUB_NAV_KEY = 'manage_topics'; ManageTopics.prototype.render = function(cb) { var self = this; var dao = new pb.DAO(); dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) { if (util.isError(topics)) { //TODO handle this } //none to manage if(topics.length === 0) { self.redirect('/admin/content/topics/new', cb); return; } //currently, mongo cannot do case-insensitive sorts. We do it manually //until a solution for https://jira.mongodb.org/browse/SERVER-90 is merged. topics.sort(function(a, b) { var x = a.name.toLowerCase(); var y = b.name.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); var angularObjects = pb.js.getAngularObjects( { navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls), pills: pb.AdminSubnavService.get(SUB_NAV_KEY, self.ls, SUB_NAV_KEY), topics: topics }); self.setPageName(self.ls.get('MANAGE_TOPICS')); self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false)); self.ts.load('admin/content/topics/manage_topics', function(err, data) { var result = '' + data; cb({content: result}); }); }); }; ManageTopics.getSubNavItems = function(key, ls, data) { return [{ name: SUB_NAV_KEY, title: ls.get('MANAGE_TOPICS'), icon: 'refresh', href: '/admin/content/topics' }, { name: 'import_topics', title: '', icon: 'upload', href: '/admin/content/topics/import' }, { name: 'new_topic', title: '', icon: 'plus', href: '/admin/content/topics/new' }]; }; //register admin sub-nav pb.AdminSubnavService.registerFor(SUB_NAV_KEY, ManageTopics.getSubNavItems); //exports module.exports = ManageTopics;
shihokoui/pencilblue
plugins/pencilblue/controllers/admin/content/topics/manage_topics.js
JavaScript
gpl-3.0
2,715
-- -------------------------------------------------------- -- Host: spahost.es -- Versión del servidor: 5.1.70-cll - MySQL Community Server (GPL) -- SO del servidor: unknown-linux-gnu -- HeidiSQL Versión: 8.0.0.4396 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Volcando estructura de base de datos para spahost_lsb CREATE DATABASE IF NOT EXISTS `spahost_lsb` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `spahost_lsb`; -- Volcando estructura para tabla spahost_lsb.lb_cat CREATE TABLE IF NOT EXISTS `lb_cat` ( `id` int(11) NOT NULL AUTO_INCREMENT, `sub_id` int(11) DEFAULT NULL, `title` varchar(250) CHARACTER SET latin1 NOT NULL DEFAULT '', `description` text CHARACTER SET latin1 NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Categorias del blog'; -- Volcando estructura para tabla spahost_lsb.lb_config CREATE TABLE IF NOT EXISTS `lb_config` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(60) NOT NULL DEFAULT '', `subtitle` varchar(60) NOT NULL DEFAULT '', `description` varchar(255) NOT NULL DEFAULT '', `author` varchar(50) NOT NULL DEFAULT '', `email` varchar(100) NOT NULL DEFAULT '', `site_url` varchar(100) NOT NULL DEFAULT '', `lang` varchar(5) NOT NULL, `template` varchar(255) NOT NULL DEFAULT '', `mantenimiento` int(2) NOT NULL DEFAULT '0', `limit_home` int(2) NOT NULL DEFAULT '0', `limit_rss` int(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `user_login_key` (`title`), KEY `user_nicename` (`author`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Configuracion del blog'; -- Volcando datos para la tabla spahost_lsb.lb_config: 1 rows DELETE FROM `lb_config`; /*!40000 ALTER TABLE `lb_config` DISABLE KEYS */; INSERT INTO `lb_config` (`id`, `title`, `subtitle`, `description`, `author`, `email`, `site_url`, `lang`, `template`, `mantenimiento`, `limit_home`, `limit_rss`) VALUES (1, 'Nombre de Blog', 'Subtitulo de tu blog', 'descripcion de blog', 'tu nombre', 'tu email', 'http://www.tu-web.com', 'es', 'default', 0, 10, 25); /*!40000 ALTER TABLE `lb_config` ENABLE KEYS */; -- Volcando estructura para tabla spahost_lsb.lb_news CREATE TABLE IF NOT EXISTS `lb_news` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(250) CHARACTER SET latin1 NOT NULL DEFAULT '', `news` text CHARACTER SET latin1 NOT NULL, `news_extend` text CHARACTER SET latin1 NOT NULL, `author` varchar(99) CHARACTER SET latin1 NOT NULL DEFAULT '', `source` varchar(99) CHARACTER SET latin1 NOT NULL DEFAULT '', `views` int(11) NOT NULL DEFAULT '0', `category` int(11) NOT NULL DEFAULT '0', `image` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '', `link` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '', `oday` varchar(2) DEFAULT NULL, `omonth` varchar(2) DEFAULT NULL, `oyear` varchar(4) DEFAULT NULL, `ttime` int(10) NOT NULL, `lsttime` int(10) NOT NULL, PRIMARY KEY (`id`), FULLTEXT KEY `FULLTEXT` (`title`) ) ENGINE=MyISAM AUTO_INCREMENT=172 DEFAULT CHARSET=utf8; -- Volcando estructura para tabla spahost_lsb.lb_users CREATE TABLE IF NOT EXISTS `lb_users` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_login` varchar(60) NOT NULL DEFAULT '', `user_pass` varchar(64) NOT NULL DEFAULT '', `user_email` varchar(100) NOT NULL DEFAULT '', `user_url` varchar(100) NOT NULL DEFAULT '', `user_registered` int(10) NOT NULL, `user_activation_key` varchar(60) NOT NULL DEFAULT '', `user_status` int(11) NOT NULL DEFAULT '0', `display_name` varchar(250) NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `user_login_key` (`user_login`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Volcando datos para la tabla spahost_lsb.lb_users: 1 rows DELETE FROM `lb_users`; /*!40000 ALTER TABLE `lb_users` DISABLE KEYS */; INSERT INTO `lb_users` (`id`, `user_login`, `user_pass`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', '[email protected]', 'http://www.tu-web.com', 1, '', 0, 'Nick a mostrar'); /*!40000 ALTER TABLE `lb_users` ENABLE KEYS */; -- Volcando estructura para tabla spahost_lsb.lb_users_online CREATE TABLE IF NOT EXISTS `lb_users_online` ( `timestap` int(15) NOT NULL DEFAULT '0', `status` int(1) NOT NULL, `ttime` varchar(55) NOT NULL DEFAULT '', `username` varchar(55) NOT NULL DEFAULT '', `ip` varchar(40) NOT NULL DEFAULT '', `country` varchar(10) NOT NULL DEFAULT '', `file` varchar(100) NOT NULL DEFAULT '', `page_title` varchar(100) NOT NULL, `os` varchar(100) NOT NULL, `browser` varchar(100) NOT NULL, `browser_ver` varchar(100) NOT NULL, PRIMARY KEY (`timestap`), KEY `ip` (`ip`), KEY `file` (`file`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- Volcando datos para la tabla spahost_lsb.lb_users_online: 0 rows DELETE FROM `lb_users_online`; /*!40000 ALTER TABLE `lb_users_online` DISABLE KEYS */; /*!40000 ALTER TABLE `lb_users_online` ENABLE KEYS */; -- Volcando estructura para tabla spahost_lsb.vt_users_online CREATE TABLE IF NOT EXISTS `vt_users_online` ( `timestap` int(15) NOT NULL DEFAULT '0', `status` int(1) NOT NULL, `ttime` varchar(55) NOT NULL DEFAULT '', `username` varchar(55) NOT NULL DEFAULT '', `ip` varchar(40) NOT NULL DEFAULT '', `country` varchar(10) NOT NULL DEFAULT '', `file` varchar(100) NOT NULL DEFAULT '', `page_title` varchar(100) NOT NULL, `os` varchar(100) NOT NULL, `browser` varchar(100) NOT NULL, `browser_ver` varchar(100) NOT NULL, PRIMARY KEY (`timestap`), KEY `ip` (`ip`), KEY `file` (`file`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- Volcando datos para la tabla spahost_lsb.vt_users_online: 0 rows DELETE FROM `vt_users_online`; /*!40000 ALTER TABLE `vt_users_online` DISABLE KEYS */; /*!40000 ALTER TABLE `vt_users_online` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
SpaHost/libresocialblog
sql.sql
SQL
gpl-3.0
6,615
#include <shlobj.h> HRESULT CreateDataObject(FORMATETC *,STGMEDIUM *,IDataObject **,int);
linquize/explorerplus-custom
Explorer++/Helper/iDataObject.h
C
gpl-3.0
90
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Thu Oct 24 15:10:37 CEST 2013 --> <title>RmcpConstants</title> <meta name="date" content="2013-10-24"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="RmcpConstants"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/RmcpConstants.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpClassOfMessage.html" title="enum in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpDecoder.html" title="class in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html" target="_top">Frames</a></li> <li><a href="RmcpConstants.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.veraxsystems.vxipmi.coding.rmcp</div> <h2 title="Class RmcpConstants" class="title">Class RmcpConstants</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="strong">RmcpConstants</span> extends java.lang.Object</pre> <div class="block">Set of constants. Byte constants are encoded as pseudo unsigned bytes. RMCPConstants doesn't use <a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html" title="class in com.veraxsystems.vxipmi.common"><code>TypeConverter</code></a> because fields need to be runtime constants.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html#byteToInt(byte)"><code>TypeConverter.byteToInt(byte)</code></a>, <a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html#intToByte(int)"><code>TypeConverter.intToByte(int)</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#ASFIANA">ASFIANA</a></strong></code> <div class="block">IANA Enterprise Number = ASF IANA</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static byte</code></td> <td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#PRESENCE_PING">PRESENCE_PING</a></strong></code> <div class="block">ASF Message type = Presence Ping</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static byte</code></td> <td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#RMCP_V1_0">RMCP_V1_0</a></strong></code> <div class="block">RMCP version 1.0</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="RMCP_V1_0"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RMCP_V1_0</h4> <pre>public static final&nbsp;byte RMCP_V1_0</pre> <div class="block">RMCP version 1.0</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.RMCP_V1_0">Constant Field Values</a></dd></dl> </li> </ul> <a name="ASFIANA"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ASFIANA</h4> <pre>public static final&nbsp;int ASFIANA</pre> <div class="block">IANA Enterprise Number = ASF IANA</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.ASFIANA">Constant Field Values</a></dd></dl> </li> </ul> <a name="PRESENCE_PING"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PRESENCE_PING</h4> <pre>public static final&nbsp;byte PRESENCE_PING</pre> <div class="block">ASF Message type = Presence Ping</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.PRESENCE_PING">Constant Field Values</a></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/RmcpConstants.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpClassOfMessage.html" title="enum in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpDecoder.html" title="class in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html" target="_top">Frames</a></li> <li><a href="RmcpConstants.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
zhoujinl/jIPMI
doc/com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html
HTML
gpl-3.0
10,212
/* * LibrePCB - Professional EDA for everyone! * Copyright (C) 2013 LibrePCB Developers, see AUTHORS.md for contributors. * https://librepcb.org/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /******************************************************************************* * Includes ******************************************************************************/ #include <gtest/gtest.h> #include <librepcb/common/uuid.h> #include <QtCore> /******************************************************************************* * Namespace ******************************************************************************/ namespace librepcb { namespace tests { /******************************************************************************* * Test Data Type ******************************************************************************/ typedef struct { bool valid; QString uuid; } UuidTestData; /******************************************************************************* * Test Class ******************************************************************************/ class UuidTest : public ::testing::TestWithParam<UuidTestData> {}; /******************************************************************************* * Test Methods ******************************************************************************/ TEST_P(UuidTest, testCopyConstructor) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid source = Uuid::fromString(data.uuid); Uuid copy(source); EXPECT_TRUE(copy == source); EXPECT_EQ(source.toStr(), copy.toStr()); } } TEST_P(UuidTest, testToStr) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid = Uuid::fromString(data.uuid); EXPECT_EQ(data.uuid, uuid.toStr()); EXPECT_EQ(36, uuid.toStr().length()); } } TEST_P(UuidTest, testOperatorAssign) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid source = Uuid::fromString(data.uuid); Uuid destination = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID EXPECT_NE(source.toStr(), destination.toStr()); destination = source; EXPECT_EQ(source.toStr(), destination.toStr()); } } TEST_P(UuidTest, testOperatorEquals) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid1 = Uuid::fromString(data.uuid); Uuid uuid2 = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID EXPECT_FALSE(uuid2 == uuid1); EXPECT_FALSE(uuid1 == uuid2); uuid2 = uuid1; EXPECT_TRUE(uuid2 == uuid1); EXPECT_TRUE(uuid1 == uuid2); } } TEST_P(UuidTest, testOperatorNotEquals) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid1 = Uuid::fromString(data.uuid); Uuid uuid2 = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID EXPECT_TRUE(uuid2 != uuid1); EXPECT_TRUE(uuid1 != uuid2); uuid2 = uuid1; EXPECT_FALSE(uuid2 != uuid1); EXPECT_FALSE(uuid1 != uuid2); } } TEST_P(UuidTest, testOperatorComparisons) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid1 = Uuid::fromString(data.uuid); Uuid uuid2 = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID if (uuid1.toStr() == uuid2.toStr()) { EXPECT_FALSE((uuid2 < uuid1) || (uuid2 > uuid1)); EXPECT_FALSE((uuid1 < uuid2) || (uuid1 > uuid2)); EXPECT_TRUE((uuid2 <= uuid1) && (uuid2 >= uuid1)); EXPECT_TRUE((uuid1 <= uuid2) && (uuid1 >= uuid2)); } else { EXPECT_TRUE((uuid2 < uuid1) != (uuid2 > uuid1)); EXPECT_TRUE((uuid1 < uuid2) != (uuid1 > uuid2)); EXPECT_TRUE((uuid2 <= uuid1) != (uuid2 >= uuid1)); EXPECT_TRUE((uuid1 <= uuid2) != (uuid1 >= uuid2)); } EXPECT_EQ(uuid2.toStr() < uuid1.toStr(), uuid2 < uuid1); EXPECT_EQ(uuid1.toStr() < uuid2.toStr(), uuid1 < uuid2); EXPECT_EQ(uuid2.toStr() > uuid1.toStr(), uuid2 > uuid1); EXPECT_EQ(uuid1.toStr() > uuid2.toStr(), uuid1 > uuid2); EXPECT_EQ(uuid2.toStr() <= uuid1.toStr(), uuid2 <= uuid1); EXPECT_EQ(uuid1.toStr() <= uuid2.toStr(), uuid1 <= uuid2); EXPECT_EQ(uuid2.toStr() >= uuid1.toStr(), uuid2 >= uuid1); EXPECT_EQ(uuid1.toStr() >= uuid2.toStr(), uuid1 >= uuid2); } } TEST(UuidTest, testCreateRandom) { for (int i = 0; i < 1000; i++) { Uuid uuid = Uuid::createRandom(); EXPECT_FALSE(uuid.toStr().isEmpty()); EXPECT_EQ(QUuid::DCE, QUuid(uuid.toStr()).variant()); EXPECT_EQ(QUuid::Random, QUuid(uuid.toStr()).version()); } } TEST_P(UuidTest, testIsValid) { const UuidTestData& data = GetParam(); EXPECT_EQ(data.valid, Uuid::isValid(data.uuid)); } TEST_P(UuidTest, testFromString) { const UuidTestData& data = GetParam(); if (data.valid) { EXPECT_EQ(data.uuid, Uuid::fromString(data.uuid).toStr()); } else { EXPECT_THROW(Uuid::fromString(data.uuid), Exception); } } TEST_P(UuidTest, testTryFromString) { const UuidTestData& data = GetParam(); tl::optional<Uuid> uuid = Uuid::tryFromString(data.uuid); if (data.valid) { EXPECT_TRUE(uuid); EXPECT_EQ(data.uuid, uuid->toStr()); } else { EXPECT_FALSE(uuid); EXPECT_EQ(tl::nullopt, uuid); } } TEST_P(UuidTest, testSerializeToSExpression) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid = Uuid::fromString(data.uuid); EXPECT_EQ(data.uuid, serializeToSExpression(uuid).getStringOrToken()); EXPECT_EQ( data.uuid, serializeToSExpression(tl::make_optional(uuid)).getStringOrToken()); } } TEST_P(UuidTest, testDeserializeFromSExpression) { const UuidTestData& data = GetParam(); SExpression sexpr = SExpression::createToken(data.uuid); if (data.valid) { EXPECT_EQ(data.uuid, deserializeFromSExpression<Uuid>(sexpr, false).toStr()); EXPECT_EQ( data.uuid, deserializeFromSExpression<tl::optional<Uuid>>(sexpr, false)->toStr()); } else { EXPECT_THROW(deserializeFromSExpression<Uuid>(sexpr, false), Exception); EXPECT_THROW(deserializeFromSExpression<tl::optional<Uuid>>(sexpr, false), Exception); } } TEST(UuidTest, testSerializeOptionalToSExpression) { tl::optional<Uuid> uuid = tl::nullopt; EXPECT_EQ("none", serializeToSExpression(uuid).getStringOrToken()); } TEST(UuidTest, testDeserializeOptionalFromSExpression) { SExpression sexpr = SExpression::createToken("none"); EXPECT_EQ(tl::nullopt, deserializeFromSExpression<tl::optional<Uuid>>(sexpr, false)); } /******************************************************************************* * Test Data ******************************************************************************/ // Test UUIDs are generated with: // - https://www.uuidgenerator.net // - https://uuidgenerator.org/ // - https://www.famkruithof.net/uuid/uuidgen // - http://www.freecodeformat.com/uuid-guid.php // - https://de.wikipedia.org/wiki/Universally_Unique_Identifier // // clang-format off INSTANTIATE_TEST_SUITE_P(UuidTest, UuidTest, ::testing::Values( // DCE Version 4 (random, the only accepted UUID type for us) UuidTestData({true , "bdf7bea5-b88e-41b2-be85-c1604e8ddfca" }), UuidTestData({true , "587539af-1c39-40ed-9bdd-2ca2e6aeb18d" }), UuidTestData({true , "27556d27-fe33-4334-a8ee-b05b402a21d6" }), UuidTestData({true , "91172d44-bdcc-41b2-8e07-4f8cf44eb108" }), UuidTestData({true , "ecb3a5fe-1cbc-4a1b-bf8f-5d6e26deaee1" }), UuidTestData({true , "908f9c33-40be-46aa-97b4-be2cd7477881" }), UuidTestData({true , "74ca6127-e785-4355-8580-1ced4f0a0e9e" }), UuidTestData({true , "568eb40d-cd69-47a5-8932-4f5cc4b2d3fa" }), UuidTestData({true , "29401dcb-6cb6-47a1-8f7d-72dd7f9f4939" }), UuidTestData({true , "e367d539-3163-4530-ab47-3b4cb2df2a40" }), UuidTestData({true , "00000000-0000-4001-8000-000000000000" }), // DCE Version 1 (time based) UuidTestData({false, "15edb784-76df-11e6-8b77-86f30ca893d3" }), UuidTestData({false, "232872b8-76df-11e6-8b77-86f30ca893d3" }), UuidTestData({false, "1d5a3bd6-76e0-11e6-b25e-0401beb96201" }), UuidTestData({false, "F0CDE9F0-76DF-11E6-BDF4-0800200C9A66" }), UuidTestData({false, "EA9A1590-76DF-11E6-BDF4-0800200C9A66" }), // DCE Version 3 (name based, md5) UuidTestData({false, "1a32cba8-79ba-3f01-bd8a-46c5ae17ccd8" }), UuidTestData({false, "BBCB4DF8-95FB-38E8-A398-187EA35A1655" }), // DCE Version 5 (name based, sha1) UuidTestData({false, "74738ff5-5367-5958-9aee-98fffdcd1876" }), // Microsoft GUID UuidTestData({false, "00000000-0000-0000-C000-000000000046" }), // NULL UUID UuidTestData({false, "00000000-0000-0000-0000-000000000000" }), // Invalid UUIDs UuidTestData({false, "" }), // empty UuidTestData({false, " " }), // empty UuidTestData({false, QString()}), // null UuidTestData({false, "74CA6127-E785-4355-8580-1CED4F0A0E9E" }), // uppercase UuidTestData({false, "568EB40D-CD69-47A5-8932-4F5CC4B2D3FA" }), // uppercase UuidTestData({false, "29401DCB-6CB6-47A1-8F7D-72DD7F9F4939" }), // uppercase UuidTestData({false, "E367D539-3163-4530-AB47-3B4CB2DF2A40" }), // uppercase UuidTestData({false, "C56A4180-65AA-42EC-A945-5FD21DEC" }), // too short UuidTestData({false, "bdf7bea5-b88e-41b2-be85-c1604e8ddfca " }), // too long UuidTestData({false, " bdf7bea5-b88e-41b2-be85-c1604e8ddfca" }), // too long UuidTestData({false, "bdf7bea5b88e41b2be85c1604e8ddfca" }), // missing '-' UuidTestData({false, "{bdf7bea5-b88e-41b2-be85-c1604e8ddfca}"}), // '{', '}' UuidTestData({false, "bdf7bea5-b88g-41b2-be85-c1604e8ddfca" }), // 'g' UuidTestData({false, "bdf7bea5_b88e_41b2_be85_c1604e8ddfca" }), // '_' UuidTestData({false, "bdf7bea5 b88e 41b2 be85 c1604e8ddfca" }) // spaces )); // clang-format on /******************************************************************************* * End of File ******************************************************************************/ } // namespace tests } // namespace librepcb
rnestler/LibrePCB
tests/unittests/common/uuidtest.cpp
C++
gpl-3.0
10,872
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_01) on Sun Jul 03 07:12:39 ICT 2005 --> <TITLE> Uses of Package com.golden.gamedev.object.sprite (GTGE API v0.2.3) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Package com.golden.gamedev.object.sprite (GTGE API v0.2.3)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>GTGE API</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/golden/gamedev/object/sprite/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>com.golden.gamedev.object.sprite</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#com.golden.gamedev.object.sprite"><B>com.golden.gamedev.object.sprite</B></A></TD> <TD>Sprite implementation.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="com.golden.gamedev.object.sprite"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A> used by <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../com/golden/gamedev/object/sprite/class-use/AdvanceSprite.html#com.golden.gamedev.object.sprite"><B>AdvanceSprite</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>AdvanceSprite</code> class is animated sprite that has status and direction attributes, that way the animation is fully controlled by its status and direction.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>GTGE API</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/golden/gamedev/object/sprite/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2003-2005 Golden T Studios. All rights reserved. Use is subject to <a href=http://creativecommons.org/licenses/by/2.0/>license terms<a/>.<br><a target=_blank href=http://www.goldenstudios.or.id/>GoldenStudios.or.id</a></i> </BODY> </HTML>
idega/com.idega.games
docs/GTGE/docs/com/golden/gamedev/object/sprite/package-use.html
HTML
gpl-3.0
7,093
/* Copyright David Strachan Buchan 2013 * This file is part of BounceBallGame. BounceBallGame is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BounceBallGame is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with BounceBallGame. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.ashndave; import javax.swing.JFrame; import uk.co.ashndave.game.GameLoop; import uk.co.ashndave.game.Renderable; import uk.co.ashndave.game.Updateable; public class KeepyUppy { private static final String BriefLicence1 = "Copyright (C) 2013 David Strachan Buchan."; private static final String BriefLicence2 = "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>."; private static final String BriefLicence3 = "This is free software: you are free to change and redistribute it."; private static final String BriefLicence4 = "There is NO WARRANTY, to the extent permitted by law."; private static final String BriefLicence5 = "Written by David Strachan Buchan."; private static final String[] BriefLicence = new String[]{BriefLicence1, BriefLicence2,BriefLicence3,BriefLicence4,BriefLicence5}; private Thread animator; private GameLoop looper; private GamePanel gamePanel; private static KeepyUppy game; /** * @param args */ public static void main(String[] args) { printLicence(); game = new KeepyUppy(); javax.swing.SwingUtilities.invokeLater(new Runnable(){ public void run(){ game.createAndShowGUI(); } }); } private static void printLicence() { for(String licence : BriefLicence) { System.out.println(licence); } } protected void createAndShowGUI() { gamePanel = new GamePanel(); looper = new GameLoop(gamePanel, gamePanel); JFrame frame = new JFrame("Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gamePanel); frame.pack(); frame.setVisible(true); animator = new Thread(looper); animator.start(); } }
davidsbuchan/BounceBallGame
src/uk/co/ashndave/KeepyUppy.java
Java
gpl-3.0
2,378
/** ****************************************************************************** * @file Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c * @author MCD Application Team * @brief This example describes how to send/receive bytes over USART IP using * the STM32F0xx USART LL API in DMA mode. * Peripheral initialization done using LL unitary services functions. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F0xx_LL_Examples * @{ */ /** @addtogroup USART_Communication_TxRx_DMA * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint8_t ubButtonPress = 0; __IO uint8_t ubSend = 0; /* Buffer used for transmission */ const uint8_t aTxBuffer[] = "STM32F0xx USART LL API Example : TX/RX in DMA mode\r\nConfiguration UART 115200 bps, 8 data bit/1 stop bit/No parity/No HW flow control\r\nPlease enter 'END' string ...\r\n"; uint8_t ubNbDataToTransmit = sizeof(aTxBuffer); __IO uint8_t ubTransmissionComplete = 0; /* Buffer used for reception */ const uint8_t aStringToReceive[] = "END"; uint8_t ubNbDataToReceive = sizeof(aStringToReceive) - 1; uint8_t aRxBuffer[sizeof(aStringToReceive) - 1]; __IO uint8_t ubReceptionComplete = 0; /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); void Configure_DMA(void); void Configure_USART(void); void StartTransfers(void); void LED_Init(void); void LED_On(void); void LED_Blinking(uint32_t Period); void LED_Off(void); void UserButton_Init(void); void WaitForUserButtonPress(void); void WaitAndCheckEndOfTransfer(void); uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* Configure the system clock to 48 MHz */ SystemClock_Config(); /* Initialize LED2 */ LED_Init(); /* Initialize button in EXTI mode */ UserButton_Init(); /* Configure USARTx (USART IP configuration and related GPIO initialization) */ Configure_USART(); /* Configure DMA channels for USART instance */ Configure_DMA(); /* Wait for User push-button press to start transfer */ WaitForUserButtonPress(); /* Initiate DMA transfers */ StartTransfers(); /* Wait for the end of the transfer and check received data */ WaitAndCheckEndOfTransfer(); /* Infinite loop */ while (1) { } } /** * @brief This function configures the DMA Channels for TX and RX transfers * @note This function is used to : * -1- Enable DMA1 clock * -2- Configure NVIC for DMA transfer complete/error interrupts * -3- Configure DMA TX channel functional parameters * -4- Configure DMA RX channel functional parameters * -5- Enable transfer complete/error interrupts * @param None * @retval None */ void Configure_DMA(void) { /* DMA1 used for USART2 Transmission and Reception */ /* (1) Enable the clock of DMA1 */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1); /* (2) Configure NVIC for DMA transfer complete/error interrupts */ NVIC_SetPriority(DMA1_Channel4_5_6_7_IRQn, 0); NVIC_EnableIRQ(DMA1_Channel4_5_6_7_IRQn); /* (3) Configure the DMA functional parameters for transmission */ LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_4, LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE); LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_4, (uint32_t)aTxBuffer, LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_TRANSMIT), LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_4)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_4, ubNbDataToTransmit); /* (4) Configure the DMA functional parameters for reception */ LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_5, LL_DMA_DIRECTION_PERIPH_TO_MEMORY | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE); LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_5, LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_RECEIVE), (uint32_t)aRxBuffer, LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_5)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_5, ubNbDataToReceive); /* (5) Enable DMA transfer complete/error interrupts */ LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_4); LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_4); LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_5); LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_5); } /** * @brief This function configures USARTx Instance. * @note This function is used to : * -1- Enable GPIO clock and configures the USART2 pins. * -2- Enable the USART2 peripheral clock and clock source. * -3- Configure USART2 functional parameters. * -4- Enable USART2. * @note Peripheral configuration is minimal configuration from reset values. * Thus, some useless LL unitary functions calls below are provided as * commented examples - setting is default configuration from reset. * @param None * @retval None */ void Configure_USART(void) { /* (1) Enable GPIO clock and configures the USART pins **********************/ /* Enable the peripheral clock of GPIO Port */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA); /* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_2, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_2, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_2, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_2, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_2, LL_GPIO_PULL_UP); /* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_3, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_3, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_3, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_3, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_3, LL_GPIO_PULL_UP); /* (2) Enable USART2 peripheral clock and clock source ****************/ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART2); /* Set clock source */ LL_RCC_SetUSARTClockSource(LL_RCC_USART2_CLKSOURCE_PCLK1); /* (3) Configure USART2 functional parameters ********************************/ /* Disable USART prior modifying configuration registers */ /* Note: Commented as corresponding to Reset value */ // LL_USART_Disable(USART2); /* TX/RX direction */ LL_USART_SetTransferDirection(USART2, LL_USART_DIRECTION_TX_RX); /* 8 data bit, 1 start bit, 1 stop bit, no parity */ LL_USART_ConfigCharacter(USART2, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1); /* No Hardware Flow control */ /* Reset value is LL_USART_HWCONTROL_NONE */ // LL_USART_SetHWFlowCtrl(USART2, LL_USART_HWCONTROL_NONE); /* Oversampling by 16 */ /* Reset value is LL_USART_OVERSAMPLING_16 */ // LL_USART_SetOverSampling(USART2, LL_USART_OVERSAMPLING_16); /* Set Baudrate to 115200 using APB frequency set to 48000000 Hz */ /* Frequency available for USART peripheral can also be calculated through LL RCC macro */ /* Ex : Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance In this example, Peripheral Clock is expected to be equal to 48000000 Hz => equal to SystemCoreClock */ LL_USART_SetBaudRate(USART2, SystemCoreClock, LL_USART_OVERSAMPLING_16, 115200); /* (4) Enable USART2 **********************************************************/ LL_USART_Enable(USART2); /* Polling USART initialisation */ while((!(LL_USART_IsActiveFlag_TEACK(USART2))) || (!(LL_USART_IsActiveFlag_REACK(USART2)))) { } } /** * @brief This function initiates TX and RX DMA transfers by enabling DMA channels * @param None * @retval None */ void StartTransfers(void) { /* Enable DMA RX Interrupt */ LL_USART_EnableDMAReq_RX(USART2); /* Enable DMA TX Interrupt */ LL_USART_EnableDMAReq_TX(USART2); /* Enable DMA Channel Rx */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_5); /* Enable DMA Channel Tx */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_4); } /** * @brief Initialize LED2. * @param None * @retval None */ void LED_Init(void) { /* Enable the LED2 Clock */ LED2_GPIO_CLK_ENABLE(); /* Configure IO in output push-pull mode to drive external LED2 */ LL_GPIO_SetPinMode(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_MODE_OUTPUT); /* Reset value is LL_GPIO_OUTPUT_PUSHPULL */ //LL_GPIO_SetPinOutputType(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_OUTPUT_PUSHPULL); /* Reset value is LL_GPIO_SPEED_FREQ_LOW */ //LL_GPIO_SetPinSpeed(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_SPEED_FREQ_LOW); /* Reset value is LL_GPIO_PULL_NO */ //LL_GPIO_SetPinPull(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_PULL_NO); } /** * @brief Turn-on LED2. * @param None * @retval None */ void LED_On(void) { /* Turn LED2 on */ LL_GPIO_SetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Turn-off LED2. * @param None * @retval None */ void LED_Off(void) { /* Turn LED2 off */ LL_GPIO_ResetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Set LED2 to Blinking mode for an infinite loop (toggle period based on value provided as input parameter). * @param Period : Period of time (in ms) between each toggling of LED * This parameter can be user defined values. Pre-defined values used in that example are : * @arg LED_BLINK_FAST : Fast Blinking * @arg LED_BLINK_SLOW : Slow Blinking * @arg LED_BLINK_ERROR : Error specific Blinking * @retval None */ void LED_Blinking(uint32_t Period) { /* Toggle LED2 in an infinite loop */ while (1) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(Period); } } /** * @brief Configures User push-button in GPIO or EXTI Line Mode. * @param None * @retval None */ void UserButton_Init(void) { /* Enable the BUTTON Clock */ USER_BUTTON_GPIO_CLK_ENABLE(); /* Configure GPIO for BUTTON */ LL_GPIO_SetPinMode(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_MODE_INPUT); LL_GPIO_SetPinPull(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_PULL_NO); /* Connect External Line to the GPIO*/ USER_BUTTON_SYSCFG_SET_EXTI(); /* Enable a rising trigger EXTI_Line4_15 Interrupt */ USER_BUTTON_EXTI_LINE_ENABLE(); USER_BUTTON_EXTI_FALLING_TRIG_ENABLE(); /* Configure NVIC for USER_BUTTON_EXTI_IRQn */ NVIC_SetPriority(USER_BUTTON_EXTI_IRQn, 3); NVIC_EnableIRQ(USER_BUTTON_EXTI_IRQn); } /** * @brief Wait for User push-button press to start transfer. * @param None * @retval None */ /* */ void WaitForUserButtonPress(void) { while (ubButtonPress == 0) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(LED_BLINK_FAST); } /* Ensure that LED2 is turned Off */ LED_Off(); } /** * @brief Wait end of transfer and check if received Data are well. * @param None * @retval None */ void WaitAndCheckEndOfTransfer(void) { /* 1 - Wait end of transmission */ while (ubTransmissionComplete != 1) { } /* Disable DMA1 Tx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4); /* 2 - Wait end of reception */ while (ubReceptionComplete != 1) { } /* Disable DMA1 Rx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5); /* 3 - Compare received string to expected one */ if(Buffercmp8((uint8_t*)aStringToReceive, (uint8_t*)aRxBuffer, ubNbDataToReceive)) { /* Processing Error */ LED_Blinking(LED_BLINK_ERROR); } else { /* Turn On Led if data are well received */ LED_On(); } } /** * @brief Compares two 8-bit buffers and returns the comparison result. * @param pBuffer1: pointer to the source buffer to be compared to. * @param pBuffer2: pointer to the second source buffer to be compared to the first. * @param BufferLength: buffer's length. * @retval 0: Comparison is OK (the two Buffers are identical) * Value different from 0: Comparison is NOK (Buffers are different) */ uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength) { while (BufferLength--) { if (*pBuffer1 != *pBuffer2) { return 1; } pBuffer1++; pBuffer2++; } return 0; } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSI48) * SYSCLK(Hz) = 48000000 * HCLK(Hz) = 48000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * HSI Frequency(Hz) = 48000000 * PREDIV = 2 * PLLMUL = 2 * Flash Latency(WS) = 1 * @param None * @retval None */ void SystemClock_Config(void) { /* Set FLASH latency */ LL_FLASH_SetLatency(LL_FLASH_LATENCY_1); /* Enable HSI48 and wait for activation*/ LL_RCC_HSI48_Enable(); while(LL_RCC_HSI48_IsReady() != 1) { }; /* Main PLL configuration and activation */ LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSI48, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2); LL_RCC_PLL_Enable(); while(LL_RCC_PLL_IsReady() != 1) { }; /* Sysclk activation on the main PLL */ LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL); while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) { }; /* Set APB1 prescaler */ LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1); /* Set systick to 1ms in using frequency set to 48MHz */ /* This frequency can be calculated through LL RCC macro */ /* ex: __LL_RCC_CALC_PLLCLK_FREQ (HSI48_VALUE, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2) */ LL_Init1msTick(48000000); /* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */ LL_SetSystemCoreClock(48000000); } /******************************************************************************/ /* USER IRQ HANDLER TREATMENT Functions */ /******************************************************************************/ /** * @brief Function to manage User push-button * @param None * @retval None */ void UserButton_Callback(void) { /* Update User push-button variable : to be checked in waiting loop in main program */ ubButtonPress = 1; } /** * @brief Function called from DMA1 IRQ Handler when Tx transfer is completed * @param None * @retval None */ void DMA1_TransmitComplete_Callback(void) { /* DMA Tx transfer completed */ ubTransmissionComplete = 1; } /** * @brief Function called from DMA1 IRQ Handler when Rx transfer is completed * @param None * @retval None */ void DMA1_ReceiveComplete_Callback(void) { /* DMA Rx transfer completed */ ubReceptionComplete = 1; } /** * @brief Function called in case of error detected in USART IT Handler * @param None * @retval None */ void USART_TransferError_Callback(void) { /* Disable DMA1 Tx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4); /* Disable DMA1 Rx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5); /* Set LED2 to Blinking mode to indicate error occurs */ LED_Blinking(LED_BLINK_ERROR); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Fdepraetre/Handmouse
Software/Handmouse_STM/Lib_DL/STM32Cube_FW_F0_V1.8.0/Projects/STM32F072RB-Nucleo/Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c
C
gpl-3.0
19,128
/* * FuchsTracker.c Copyright (C) 1999 Sylvain "Asle" Chipaux * * Depacks Fuchs Tracker modules * * Modified in 2006,2007,2014 by Claudio Matsuoka */ #include <string.h> #include <stdlib.h> #include "prowiz.h" static int depack_fuchs(HIO_HANDLE *in, FILE *out) { uint8 *tmp; uint8 max_pat; /*int ssize;*/ uint8 data[1080]; unsigned smp_len[16]; unsigned loop_start[16]; unsigned pat_size; unsigned i; memset(smp_len, 0, 16 * 4); memset(loop_start, 0, 16 * 4); memset(data, 0, 1080); hio_read(data, 1, 10, in); /* read/write title */ /*ssize =*/ hio_read32b(in); /* read all sample data size */ /* read/write sample sizes */ for (i = 0; i < 16; i++) { smp_len[i] = hio_read16b(in); data[42 + i * 30] = smp_len[i] >> 9; data[43 + i * 30] = smp_len[i] >> 1; } /* read/write volumes */ for (i = 0; i < 16; i++) { data[45 + i * 30] = hio_read16b(in); } /* read/write loop start */ for (i = 0; i < 16; i++) { loop_start[i] = hio_read16b(in); data[46 + i * 30] = loop_start[i] >> 1; } /* write replen */ for (i = 0; i < 16; i++) { int loop_size; loop_size = smp_len[i] - loop_start[i]; if (loop_size == 0 || loop_start[i] == 0) { data[49 + i * 30] = 1; } else { data[48 + i * 30] = loop_size >> 9; data[49 + i * 30] = loop_size >> 1; } } /* fill replens up to 31st sample wiz $0001 */ for (i = 16; i < 31; i++) { data[49 + i * 30] = 1; } /* that's it for the samples ! */ /* now, the pattern list */ /* read number of pattern to play */ data[950] = hio_read16b(in); data[951] = 0x7f; /* read/write pattern list */ for (max_pat = i = 0; i < 40; i++) { uint8 pat = hio_read16b(in); data[952 + i] = pat; if (pat > max_pat) { max_pat = pat; } } /* write ptk's ID */ if (fwrite(data, 1, 1080, out) != 1080) { return -1; } write32b(out, PW_MOD_MAGIC); /* now, the pattern data */ /* bypass the "SONG" ID */ hio_read32b(in); /* read pattern data size */ pat_size = hio_read32b(in); /* Sanity check */ if (pat_size <= 0 || pat_size > 0x20000) return -1; /* read pattern data */ tmp = (uint8 *)malloc(pat_size); if (hio_read(tmp, 1, pat_size, in) != pat_size) { free(tmp); return -1; } /* convert shits */ for (i = 0; i < pat_size; i += 4) { /* convert fx C arg back to hex value */ if ((tmp[i + 2] & 0x0f) == 0x0c) { int x = tmp[i + 3]; tmp[i + 3] = 10 * (x >> 4) + (x & 0xf); } } /* write pattern data */ fwrite(tmp, pat_size, 1, out); free(tmp); /* read/write sample data */ hio_read32b(in); /* bypass "INST" Id */ for (i = 0; i < 16; i++) { if (smp_len[i] != 0) pw_move_data(out, in, smp_len[i]); } return 0; } static int test_fuchs (uint8 *data, char *t, int s) { int i; int ssize, hdr_ssize; #if 0 /* test #1 */ if (i < 192) { Test = BAD; return; } start = i - 192; #endif if (readmem32b(data + 192) != 0x534f4e47) /* SONG */ return -1; /* all sample size */ hdr_ssize = readmem32b(data + 10); if (hdr_ssize <= 2 || hdr_ssize >= 65535 * 16) return -1; /* samples descriptions */ ssize = 0; for (i = 0; i < 16; i++) { uint8 *d = data + i * 2; int len = readmem16b(d + 14); int start = readmem16b(d + 78); /* volumes */ if (d[46] > 0x40) return -1; if (len < start) return -1; ssize += len; } if (ssize <= 2 || ssize > hdr_ssize) return -1; /* get highest pattern number in pattern list */ /*max_pat = 0;*/ for (i = 0; i < 40; i++) { int pat = data[i * 2 + 113]; if (pat > 40) return -1; /*if (pat > max_pat) max_pat = pat;*/ } #if 0 /* input file not long enough ? */ max_pat++; max_pat *= 1024; PW_REQUEST_DATA (s, k + 200); #endif pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_fchs = { "Fuchs Tracker", test_fuchs, depack_fuchs };
DodgeeSoftware/OpenALWrapper
_dependencies/libxmp-4.4.0/src/loaders/prowizard/fuchs.c
C
gpl-3.0
3,794
#ifndef SDK_CONFIG_H #define SDK_CONFIG_H // <<< Use Configuration Wizard in Context Menu >>>\n #ifdef USE_APP_CONFIG #include "app_config.h" #endif // <h> Application //========================================================== // <o> ADV_INTERVAL - Advertising interval (in units of 0.625 ms) #ifndef ADV_INTERVAL #define ADV_INTERVAL 300 #endif // <s> DEVICE_NAME - Name of device. Will be included in the advertising data. #ifndef DEVICE_NAME #define DEVICE_NAME "Nordic_ATT_MTU" #endif // <o> NRF_BLE_CENTRAL_LINK_COUNT - Number of central links #ifndef NRF_BLE_CENTRAL_LINK_COUNT #define NRF_BLE_CENTRAL_LINK_COUNT 1 #endif // <o> NRF_BLE_PERIPHERAL_LINK_COUNT - Number of peripheral links #ifndef NRF_BLE_PERIPHERAL_LINK_COUNT #define NRF_BLE_PERIPHERAL_LINK_COUNT 1 #endif // <o> SCAN_INTERVAL - Scanning interval, determines scan interval in units of 0.625 millisecond. #ifndef SCAN_INTERVAL #define SCAN_INTERVAL 160 #endif // <o> SCAN_WINDOW - Scanning window, determines scan window in units of 0.625 millisecond. #ifndef SCAN_WINDOW #define SCAN_WINDOW 80 #endif // </h> //========================================================== // <h> nRF_BLE //========================================================== // <q> BLE_ADVERTISING_ENABLED - ble_advertising - Advertising module #ifndef BLE_ADVERTISING_ENABLED #define BLE_ADVERTISING_ENABLED 0 #endif // <q> BLE_DB_DISCOVERY_ENABLED - ble_db_discovery - Database discovery module #ifndef BLE_DB_DISCOVERY_ENABLED #define BLE_DB_DISCOVERY_ENABLED 1 #endif // <q> BLE_DTM_ENABLED - ble_dtm - Module for testing RF/PHY using DTM commands #ifndef BLE_DTM_ENABLED #define BLE_DTM_ENABLED 0 #endif // <q> BLE_RACP_ENABLED - ble_racp - Record Access Control Point library #ifndef BLE_RACP_ENABLED #define BLE_RACP_ENABLED 0 #endif // <e> NRF_BLE_GATT_ENABLED - nrf_ble_gatt - GATT module //========================================================== #ifndef NRF_BLE_GATT_ENABLED #define NRF_BLE_GATT_ENABLED 1 #endif #if NRF_BLE_GATT_ENABLED // <o> NRF_BLE_GATT_MAX_MTU_SIZE - Static maximum MTU size that is passed to the @ref sd_ble_enable function. #ifndef NRF_BLE_GATT_MAX_MTU_SIZE #define NRF_BLE_GATT_MAX_MTU_SIZE 247 #endif #endif //NRF_BLE_GATT_ENABLED // </e> // <q> NRF_BLE_QWR_ENABLED - nrf_ble_qwr - Queued writes support module (prepare/execute write) #ifndef NRF_BLE_QWR_ENABLED #define NRF_BLE_QWR_ENABLED 0 #endif // <q> PEER_MANAGER_ENABLED - peer_manager - Peer Manager #ifndef PEER_MANAGER_ENABLED #define PEER_MANAGER_ENABLED 0 #endif // </h> //========================================================== // <h> nRF_BLE_Services //========================================================== // <q> BLE_ANCS_C_ENABLED - ble_ancs_c - Apple Notification Service Client #ifndef BLE_ANCS_C_ENABLED #define BLE_ANCS_C_ENABLED 0 #endif // <q> BLE_ANS_C_ENABLED - ble_ans_c - Alert Notification Service Client #ifndef BLE_ANS_C_ENABLED #define BLE_ANS_C_ENABLED 0 #endif // <q> BLE_BAS_C_ENABLED - ble_bas_c - Battery Service Client #ifndef BLE_BAS_C_ENABLED #define BLE_BAS_C_ENABLED 0 #endif // <q> BLE_BAS_ENABLED - ble_bas - Battery Service #ifndef BLE_BAS_ENABLED #define BLE_BAS_ENABLED 0 #endif // <q> BLE_CSCS_ENABLED - ble_cscs - Cycling Speed and Cadence Service #ifndef BLE_CSCS_ENABLED #define BLE_CSCS_ENABLED 0 #endif // <q> BLE_CTS_C_ENABLED - ble_cts_c - Current Time Service Client #ifndef BLE_CTS_C_ENABLED #define BLE_CTS_C_ENABLED 0 #endif // <q> BLE_DIS_ENABLED - ble_dis - Device Information Service #ifndef BLE_DIS_ENABLED #define BLE_DIS_ENABLED 0 #endif // <q> BLE_GLS_ENABLED - ble_gls - Glucose Service #ifndef BLE_GLS_ENABLED #define BLE_GLS_ENABLED 0 #endif // <q> BLE_HIDS_ENABLED - ble_hids - Human Interface Device Service #ifndef BLE_HIDS_ENABLED #define BLE_HIDS_ENABLED 0 #endif // <e> BLE_HRS_C_ENABLED - ble_hrs_c - Heart Rate Service Client //========================================================== #ifndef BLE_HRS_C_ENABLED #define BLE_HRS_C_ENABLED 0 #endif #if BLE_HRS_C_ENABLED // <o> BLE_HRS_C_RR_INTERVALS_MAX_CNT - Maximum number of RR_INTERVALS per notification to be decoded #ifndef BLE_HRS_C_RR_INTERVALS_MAX_CNT #define BLE_HRS_C_RR_INTERVALS_MAX_CNT 30 #endif #endif //BLE_HRS_C_ENABLED // </e> // <q> BLE_HRS_ENABLED - ble_hrs - Heart Rate Service #ifndef BLE_HRS_ENABLED #define BLE_HRS_ENABLED 0 #endif // <q> BLE_HTS_ENABLED - ble_hts - Health Thermometer Service #ifndef BLE_HTS_ENABLED #define BLE_HTS_ENABLED 0 #endif // <q> BLE_IAS_C_ENABLED - ble_ias_c - Immediate Alert Service Client #ifndef BLE_IAS_C_ENABLED #define BLE_IAS_C_ENABLED 0 #endif // <q> BLE_IAS_ENABLED - ble_ias - Immediate Alert Service #ifndef BLE_IAS_ENABLED #define BLE_IAS_ENABLED 0 #endif // <q> BLE_LBS_C_ENABLED - ble_lbs_c - Nordic LED Button Service Client #ifndef BLE_LBS_C_ENABLED #define BLE_LBS_C_ENABLED 0 #endif // <q> BLE_LBS_ENABLED - ble_lbs - LED Button Service #ifndef BLE_LBS_ENABLED #define BLE_LBS_ENABLED 0 #endif // <q> BLE_LLS_ENABLED - ble_lls - Link Loss Service #ifndef BLE_LLS_ENABLED #define BLE_LLS_ENABLED 0 #endif // <q> BLE_NUS_C_ENABLED - ble_nus_c - Nordic UART Central Service #ifndef BLE_NUS_C_ENABLED #define BLE_NUS_C_ENABLED 0 #endif // <q> BLE_NUS_ENABLED - ble_nus - Nordic UART Service #ifndef BLE_NUS_ENABLED #define BLE_NUS_ENABLED 0 #endif // <q> BLE_RSCS_C_ENABLED - ble_rscs_c - Running Speed and Cadence Client #ifndef BLE_RSCS_C_ENABLED #define BLE_RSCS_C_ENABLED 0 #endif // <q> BLE_RSCS_ENABLED - ble_rscs - Running Speed and Cadence Service #ifndef BLE_RSCS_ENABLED #define BLE_RSCS_ENABLED 0 #endif // <q> BLE_TPS_ENABLED - ble_tps - TX Power Service #ifndef BLE_TPS_ENABLED #define BLE_TPS_ENABLED 0 #endif // </h> //========================================================== // <h> nRF_Drivers //========================================================== // <e> APP_USBD_ENABLED - app_usbd - USB Device library //========================================================== #ifndef APP_USBD_ENABLED #define APP_USBD_ENABLED 0 #endif #if APP_USBD_ENABLED // <o> APP_USBD_VID - Vendor ID <0x0000-0xFFFF> // <i> Vendor ID ordered from USB IF: http://www.usb.org/developers/vendor/ #ifndef APP_USBD_VID #define APP_USBD_VID 0 #endif // <o> APP_USBD_PID - Product ID <0x0000-0xFFFF> // <i> Selected Product ID #ifndef APP_USBD_PID #define APP_USBD_PID 0 #endif // <o> APP_USBD_DEVICE_VER_MAJOR - Device version, major part <0-99> // <i> Device version, will be converted automatically to BCD notation. Use just decimal values. #ifndef APP_USBD_DEVICE_VER_MAJOR #define APP_USBD_DEVICE_VER_MAJOR 1 #endif // <o> APP_USBD_DEVICE_VER_MINOR - Device version, minor part <0-99> // <i> Device version, will be converted automatically to BCD notation. Use just decimal values. #ifndef APP_USBD_DEVICE_VER_MINOR #define APP_USBD_DEVICE_VER_MINOR 0 #endif #endif //APP_USBD_ENABLED // </e> // <e> CLOCK_ENABLED - nrf_drv_clock - CLOCK peripheral driver //========================================================== #ifndef CLOCK_ENABLED #define CLOCK_ENABLED 1 #endif #if CLOCK_ENABLED // <o> CLOCK_CONFIG_XTAL_FREQ - HF XTAL Frequency // <0=> Default (64 MHz) #ifndef CLOCK_CONFIG_XTAL_FREQ #define CLOCK_CONFIG_XTAL_FREQ 0 #endif // <o> CLOCK_CONFIG_LF_SRC - LF Clock Source // <0=> RC // <1=> XTAL // <2=> Synth #ifndef CLOCK_CONFIG_LF_SRC #define CLOCK_CONFIG_LF_SRC 1 #endif // <o> CLOCK_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef CLOCK_CONFIG_IRQ_PRIORITY #define CLOCK_CONFIG_IRQ_PRIORITY 7 #endif // <e> CLOCK_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef CLOCK_CONFIG_LOG_ENABLED #define CLOCK_CONFIG_LOG_ENABLED 0 #endif #if CLOCK_CONFIG_LOG_ENABLED // <o> CLOCK_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef CLOCK_CONFIG_LOG_LEVEL #define CLOCK_CONFIG_LOG_LEVEL 3 #endif // <o> CLOCK_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef CLOCK_CONFIG_INFO_COLOR #define CLOCK_CONFIG_INFO_COLOR 0 #endif // <o> CLOCK_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef CLOCK_CONFIG_DEBUG_COLOR #define CLOCK_CONFIG_DEBUG_COLOR 0 #endif #endif //CLOCK_CONFIG_LOG_ENABLED // </e> #endif //CLOCK_ENABLED // </e> // <e> COMP_ENABLED - nrf_drv_comp - COMP peripheral driver //========================================================== #ifndef COMP_ENABLED #define COMP_ENABLED 0 #endif #if COMP_ENABLED // <o> COMP_CONFIG_REF - Reference voltage // <0=> Internal 1.2V // <1=> Internal 1.8V // <2=> Internal 2.4V // <4=> VDD // <7=> ARef #ifndef COMP_CONFIG_REF #define COMP_CONFIG_REF 1 #endif // <o> COMP_CONFIG_MAIN_MODE - Main mode // <0=> Single ended // <1=> Differential #ifndef COMP_CONFIG_MAIN_MODE #define COMP_CONFIG_MAIN_MODE 0 #endif // <o> COMP_CONFIG_SPEED_MODE - Speed mode // <0=> Low power // <1=> Normal // <2=> High speed #ifndef COMP_CONFIG_SPEED_MODE #define COMP_CONFIG_SPEED_MODE 2 #endif // <o> COMP_CONFIG_HYST - Hystheresis // <0=> No // <1=> 50mV #ifndef COMP_CONFIG_HYST #define COMP_CONFIG_HYST 0 #endif // <o> COMP_CONFIG_ISOURCE - Current Source // <0=> Off // <1=> 2.5 uA // <2=> 5 uA // <3=> 10 uA #ifndef COMP_CONFIG_ISOURCE #define COMP_CONFIG_ISOURCE 0 #endif // <o> COMP_CONFIG_INPUT - Analog input // <0=> 0 // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef COMP_CONFIG_INPUT #define COMP_CONFIG_INPUT 0 #endif // <o> COMP_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef COMP_CONFIG_IRQ_PRIORITY #define COMP_CONFIG_IRQ_PRIORITY 7 #endif // <e> COMP_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef COMP_CONFIG_LOG_ENABLED #define COMP_CONFIG_LOG_ENABLED 0 #endif #if COMP_CONFIG_LOG_ENABLED // <o> COMP_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef COMP_CONFIG_LOG_LEVEL #define COMP_CONFIG_LOG_LEVEL 3 #endif // <o> COMP_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMP_CONFIG_INFO_COLOR #define COMP_CONFIG_INFO_COLOR 0 #endif // <o> COMP_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMP_CONFIG_DEBUG_COLOR #define COMP_CONFIG_DEBUG_COLOR 0 #endif #endif //COMP_CONFIG_LOG_ENABLED // </e> #endif //COMP_ENABLED // </e> // <e> EGU_ENABLED - nrf_drv_swi - SWI(EGU) peripheral driver //========================================================== #ifndef EGU_ENABLED #define EGU_ENABLED 0 #endif #if EGU_ENABLED // <e> SWI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SWI_CONFIG_LOG_ENABLED #define SWI_CONFIG_LOG_ENABLED 0 #endif #if SWI_CONFIG_LOG_ENABLED // <o> SWI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SWI_CONFIG_LOG_LEVEL #define SWI_CONFIG_LOG_LEVEL 3 #endif // <o> SWI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SWI_CONFIG_INFO_COLOR #define SWI_CONFIG_INFO_COLOR 0 #endif // <o> SWI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SWI_CONFIG_DEBUG_COLOR #define SWI_CONFIG_DEBUG_COLOR 0 #endif #endif //SWI_CONFIG_LOG_ENABLED // </e> #endif //EGU_ENABLED // </e> // <e> GPIOTE_ENABLED - nrf_drv_gpiote - GPIOTE peripheral driver //========================================================== #ifndef GPIOTE_ENABLED #define GPIOTE_ENABLED 1 #endif #if GPIOTE_ENABLED // <o> GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS - Number of lower power input pins #ifndef GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS #define GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS 4 #endif // <o> GPIOTE_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef GPIOTE_CONFIG_IRQ_PRIORITY #define GPIOTE_CONFIG_IRQ_PRIORITY 7 #endif // <e> GPIOTE_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef GPIOTE_CONFIG_LOG_ENABLED #define GPIOTE_CONFIG_LOG_ENABLED 0 #endif #if GPIOTE_CONFIG_LOG_ENABLED // <o> GPIOTE_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef GPIOTE_CONFIG_LOG_LEVEL #define GPIOTE_CONFIG_LOG_LEVEL 3 #endif // <o> GPIOTE_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef GPIOTE_CONFIG_INFO_COLOR #define GPIOTE_CONFIG_INFO_COLOR 0 #endif // <o> GPIOTE_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef GPIOTE_CONFIG_DEBUG_COLOR #define GPIOTE_CONFIG_DEBUG_COLOR 0 #endif #endif //GPIOTE_CONFIG_LOG_ENABLED // </e> #endif //GPIOTE_ENABLED // </e> // <e> I2S_ENABLED - nrf_drv_i2s - I2S peripheral driver //========================================================== #ifndef I2S_ENABLED #define I2S_ENABLED 0 #endif #if I2S_ENABLED // <o> I2S_CONFIG_SCK_PIN - SCK pin <0-31> #ifndef I2S_CONFIG_SCK_PIN #define I2S_CONFIG_SCK_PIN 31 #endif // <o> I2S_CONFIG_LRCK_PIN - LRCK pin <1-31> #ifndef I2S_CONFIG_LRCK_PIN #define I2S_CONFIG_LRCK_PIN 30 #endif // <o> I2S_CONFIG_MCK_PIN - MCK pin #ifndef I2S_CONFIG_MCK_PIN #define I2S_CONFIG_MCK_PIN 255 #endif // <o> I2S_CONFIG_SDOUT_PIN - SDOUT pin <0-31> #ifndef I2S_CONFIG_SDOUT_PIN #define I2S_CONFIG_SDOUT_PIN 29 #endif // <o> I2S_CONFIG_SDIN_PIN - SDIN pin <0-31> #ifndef I2S_CONFIG_SDIN_PIN #define I2S_CONFIG_SDIN_PIN 28 #endif // <o> I2S_CONFIG_MASTER - Mode // <0=> Master // <1=> Slave #ifndef I2S_CONFIG_MASTER #define I2S_CONFIG_MASTER 0 #endif // <o> I2S_CONFIG_FORMAT - Format // <0=> I2S // <1=> Aligned #ifndef I2S_CONFIG_FORMAT #define I2S_CONFIG_FORMAT 0 #endif // <o> I2S_CONFIG_ALIGN - Alignment // <0=> Left // <1=> Right #ifndef I2S_CONFIG_ALIGN #define I2S_CONFIG_ALIGN 0 #endif // <o> I2S_CONFIG_SWIDTH - Sample width (bits) // <0=> 8 // <1=> 16 // <2=> 24 #ifndef I2S_CONFIG_SWIDTH #define I2S_CONFIG_SWIDTH 1 #endif // <o> I2S_CONFIG_CHANNELS - Channels // <0=> Stereo // <1=> Left // <2=> Right #ifndef I2S_CONFIG_CHANNELS #define I2S_CONFIG_CHANNELS 1 #endif // <o> I2S_CONFIG_MCK_SETUP - MCK behavior // <0=> Disabled // <2147483648=> 32MHz/2 // <1342177280=> 32MHz/3 // <1073741824=> 32MHz/4 // <805306368=> 32MHz/5 // <671088640=> 32MHz/6 // <536870912=> 32MHz/8 // <402653184=> 32MHz/10 // <369098752=> 32MHz/11 // <285212672=> 32MHz/15 // <268435456=> 32MHz/16 // <201326592=> 32MHz/21 // <184549376=> 32MHz/23 // <142606336=> 32MHz/30 // <138412032=> 32MHz/31 // <134217728=> 32MHz/32 // <100663296=> 32MHz/42 // <68157440=> 32MHz/63 // <34340864=> 32MHz/125 #ifndef I2S_CONFIG_MCK_SETUP #define I2S_CONFIG_MCK_SETUP 536870912 #endif // <o> I2S_CONFIG_RATIO - MCK/LRCK ratio // <0=> 32x // <1=> 48x // <2=> 64x // <3=> 96x // <4=> 128x // <5=> 192x // <6=> 256x // <7=> 384x // <8=> 512x #ifndef I2S_CONFIG_RATIO #define I2S_CONFIG_RATIO 2000 #endif // <o> I2S_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef I2S_CONFIG_IRQ_PRIORITY #define I2S_CONFIG_IRQ_PRIORITY 7 #endif // <e> I2S_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef I2S_CONFIG_LOG_ENABLED #define I2S_CONFIG_LOG_ENABLED 0 #endif #if I2S_CONFIG_LOG_ENABLED // <o> I2S_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef I2S_CONFIG_LOG_LEVEL #define I2S_CONFIG_LOG_LEVEL 3 #endif // <o> I2S_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef I2S_CONFIG_INFO_COLOR #define I2S_CONFIG_INFO_COLOR 0 #endif // <o> I2S_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef I2S_CONFIG_DEBUG_COLOR #define I2S_CONFIG_DEBUG_COLOR 0 #endif #endif //I2S_CONFIG_LOG_ENABLED // </e> #endif //I2S_ENABLED // </e> // <e> LPCOMP_ENABLED - nrf_drv_lpcomp - LPCOMP peripheral driver //========================================================== #ifndef LPCOMP_ENABLED #define LPCOMP_ENABLED 0 #endif #if LPCOMP_ENABLED // <o> LPCOMP_CONFIG_REFERENCE - Reference voltage // <0=> Supply 1/8 // <1=> Supply 2/8 // <2=> Supply 3/8 // <3=> Supply 4/8 // <4=> Supply 5/8 // <5=> Supply 6/8 // <6=> Supply 7/8 // <8=> Supply 1/16 (nRF52) // <9=> Supply 3/16 (nRF52) // <10=> Supply 5/16 (nRF52) // <11=> Supply 7/16 (nRF52) // <12=> Supply 9/16 (nRF52) // <13=> Supply 11/16 (nRF52) // <14=> Supply 13/16 (nRF52) // <15=> Supply 15/16 (nRF52) // <7=> External Ref 0 // <65543=> External Ref 1 #ifndef LPCOMP_CONFIG_REFERENCE #define LPCOMP_CONFIG_REFERENCE 3 #endif // <o> LPCOMP_CONFIG_DETECTION - Detection // <0=> Crossing // <1=> Up // <2=> Down #ifndef LPCOMP_CONFIG_DETECTION #define LPCOMP_CONFIG_DETECTION 2 #endif // <o> LPCOMP_CONFIG_INPUT - Analog input // <0=> 0 // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef LPCOMP_CONFIG_INPUT #define LPCOMP_CONFIG_INPUT 0 #endif // <q> LPCOMP_CONFIG_HYST - Hysteresis #ifndef LPCOMP_CONFIG_HYST #define LPCOMP_CONFIG_HYST 0 #endif // <o> LPCOMP_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef LPCOMP_CONFIG_IRQ_PRIORITY #define LPCOMP_CONFIG_IRQ_PRIORITY 7 #endif // <e> LPCOMP_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef LPCOMP_CONFIG_LOG_ENABLED #define LPCOMP_CONFIG_LOG_ENABLED 0 #endif #if LPCOMP_CONFIG_LOG_ENABLED // <o> LPCOMP_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef LPCOMP_CONFIG_LOG_LEVEL #define LPCOMP_CONFIG_LOG_LEVEL 3 #endif // <o> LPCOMP_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef LPCOMP_CONFIG_INFO_COLOR #define LPCOMP_CONFIG_INFO_COLOR 0 #endif // <o> LPCOMP_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef LPCOMP_CONFIG_DEBUG_COLOR #define LPCOMP_CONFIG_DEBUG_COLOR 0 #endif #endif //LPCOMP_CONFIG_LOG_ENABLED // </e> #endif //LPCOMP_ENABLED // </e> // <e> PDM_ENABLED - nrf_drv_pdm - PDM peripheral driver //========================================================== #ifndef PDM_ENABLED #define PDM_ENABLED 0 #endif #if PDM_ENABLED // <o> PDM_CONFIG_MODE - Mode // <0=> Stereo // <1=> Mono #ifndef PDM_CONFIG_MODE #define PDM_CONFIG_MODE 1 #endif // <o> PDM_CONFIG_EDGE - Edge // <0=> Left falling // <1=> Left rising #ifndef PDM_CONFIG_EDGE #define PDM_CONFIG_EDGE 0 #endif // <o> PDM_CONFIG_CLOCK_FREQ - Clock frequency // <134217728=> 1000k // <138412032=> 1032k (default) // <142606336=> 1067k #ifndef PDM_CONFIG_CLOCK_FREQ #define PDM_CONFIG_CLOCK_FREQ 138412032 #endif // <o> PDM_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef PDM_CONFIG_IRQ_PRIORITY #define PDM_CONFIG_IRQ_PRIORITY 7 #endif // <e> PDM_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef PDM_CONFIG_LOG_ENABLED #define PDM_CONFIG_LOG_ENABLED 0 #endif #if PDM_CONFIG_LOG_ENABLED // <o> PDM_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef PDM_CONFIG_LOG_LEVEL #define PDM_CONFIG_LOG_LEVEL 3 #endif // <o> PDM_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PDM_CONFIG_INFO_COLOR #define PDM_CONFIG_INFO_COLOR 0 #endif // <o> PDM_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PDM_CONFIG_DEBUG_COLOR #define PDM_CONFIG_DEBUG_COLOR 0 #endif #endif //PDM_CONFIG_LOG_ENABLED // </e> #endif //PDM_ENABLED // </e> // <e> PERIPHERAL_RESOURCE_SHARING_ENABLED - nrf_drv_common - Peripheral drivers common module //========================================================== #ifndef PERIPHERAL_RESOURCE_SHARING_ENABLED #define PERIPHERAL_RESOURCE_SHARING_ENABLED 0 #endif #if PERIPHERAL_RESOURCE_SHARING_ENABLED // <e> COMMON_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef COMMON_CONFIG_LOG_ENABLED #define COMMON_CONFIG_LOG_ENABLED 0 #endif #if COMMON_CONFIG_LOG_ENABLED // <o> COMMON_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef COMMON_CONFIG_LOG_LEVEL #define COMMON_CONFIG_LOG_LEVEL 3 #endif // <o> COMMON_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMMON_CONFIG_INFO_COLOR #define COMMON_CONFIG_INFO_COLOR 0 #endif // <o> COMMON_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMMON_CONFIG_DEBUG_COLOR #define COMMON_CONFIG_DEBUG_COLOR 0 #endif #endif //COMMON_CONFIG_LOG_ENABLED // </e> #endif //PERIPHERAL_RESOURCE_SHARING_ENABLED // </e> // <e> POWER_ENABLED - nrf_drv_power - POWER peripheral driver //========================================================== #ifndef POWER_ENABLED #define POWER_ENABLED 0 #endif #if POWER_ENABLED // <o> POWER_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef POWER_CONFIG_IRQ_PRIORITY #define POWER_CONFIG_IRQ_PRIORITY 7 #endif // <q> POWER_CONFIG_DEFAULT_DCDCEN - The default configuration of main DCDC regulator // <i> This settings means only that components for DCDC regulator are installed and it can be enabled. #ifndef POWER_CONFIG_DEFAULT_DCDCEN #define POWER_CONFIG_DEFAULT_DCDCEN 0 #endif // <q> POWER_CONFIG_DEFAULT_DCDCENHV - The default configuration of High Voltage DCDC regulator // <i> This settings means only that components for DCDC regulator are installed and it can be enabled. #ifndef POWER_CONFIG_DEFAULT_DCDCENHV #define POWER_CONFIG_DEFAULT_DCDCENHV 0 #endif #endif //POWER_ENABLED // </e> // <e> PPI_ENABLED - nrf_drv_ppi - PPI peripheral driver //========================================================== #ifndef PPI_ENABLED #define PPI_ENABLED 0 #endif #if PPI_ENABLED // <e> PPI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef PPI_CONFIG_LOG_ENABLED #define PPI_CONFIG_LOG_ENABLED 0 #endif #if PPI_CONFIG_LOG_ENABLED // <o> PPI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef PPI_CONFIG_LOG_LEVEL #define PPI_CONFIG_LOG_LEVEL 3 #endif // <o> PPI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PPI_CONFIG_INFO_COLOR #define PPI_CONFIG_INFO_COLOR 0 #endif // <o> PPI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PPI_CONFIG_DEBUG_COLOR #define PPI_CONFIG_DEBUG_COLOR 0 #endif #endif //PPI_CONFIG_LOG_ENABLED // </e> #endif //PPI_ENABLED // </e> // <e> PWM_ENABLED - nrf_drv_pwm - PWM peripheral driver //========================================================== #ifndef PWM_ENABLED #define PWM_ENABLED 0 #endif #if PWM_ENABLED // <o> PWM_DEFAULT_CONFIG_OUT0_PIN - Out0 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT0_PIN #define PWM_DEFAULT_CONFIG_OUT0_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_OUT1_PIN - Out1 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT1_PIN #define PWM_DEFAULT_CONFIG_OUT1_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_OUT2_PIN - Out2 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT2_PIN #define PWM_DEFAULT_CONFIG_OUT2_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_OUT3_PIN - Out3 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT3_PIN #define PWM_DEFAULT_CONFIG_OUT3_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_BASE_CLOCK - Base clock // <0=> 16 MHz // <1=> 8 MHz // <2=> 4 MHz // <3=> 2 MHz // <4=> 1 MHz // <5=> 500 kHz // <6=> 250 kHz // <7=> 125 MHz #ifndef PWM_DEFAULT_CONFIG_BASE_CLOCK #define PWM_DEFAULT_CONFIG_BASE_CLOCK 4 #endif // <o> PWM_DEFAULT_CONFIG_COUNT_MODE - Count mode // <0=> Up // <1=> Up and Down #ifndef PWM_DEFAULT_CONFIG_COUNT_MODE #define PWM_DEFAULT_CONFIG_COUNT_MODE 0 #endif // <o> PWM_DEFAULT_CONFIG_TOP_VALUE - Top value #ifndef PWM_DEFAULT_CONFIG_TOP_VALUE #define PWM_DEFAULT_CONFIG_TOP_VALUE 1000 #endif // <o> PWM_DEFAULT_CONFIG_LOAD_MODE - Load mode // <0=> Common // <1=> Grouped // <2=> Individual // <3=> Waveform #ifndef PWM_DEFAULT_CONFIG_LOAD_MODE #define PWM_DEFAULT_CONFIG_LOAD_MODE 0 #endif // <o> PWM_DEFAULT_CONFIG_STEP_MODE - Step mode // <0=> Auto // <1=> Triggered #ifndef PWM_DEFAULT_CONFIG_STEP_MODE #define PWM_DEFAULT_CONFIG_STEP_MODE 0 #endif // <o> PWM_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef PWM_DEFAULT_CONFIG_IRQ_PRIORITY #define PWM_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> PWM0_ENABLED - Enable PWM0 instance #ifndef PWM0_ENABLED #define PWM0_ENABLED 0 #endif // <q> PWM1_ENABLED - Enable PWM1 instance #ifndef PWM1_ENABLED #define PWM1_ENABLED 0 #endif // <q> PWM2_ENABLED - Enable PWM2 instance #ifndef PWM2_ENABLED #define PWM2_ENABLED 0 #endif // <e> PWM_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef PWM_CONFIG_LOG_ENABLED #define PWM_CONFIG_LOG_ENABLED 0 #endif #if PWM_CONFIG_LOG_ENABLED // <o> PWM_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef PWM_CONFIG_LOG_LEVEL #define PWM_CONFIG_LOG_LEVEL 3 #endif // <o> PWM_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PWM_CONFIG_INFO_COLOR #define PWM_CONFIG_INFO_COLOR 0 #endif // <o> PWM_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PWM_CONFIG_DEBUG_COLOR #define PWM_CONFIG_DEBUG_COLOR 0 #endif #endif //PWM_CONFIG_LOG_ENABLED // </e> // <e> PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 Anomaly 109 workaround for PWM. // <i> The workaround uses interrupts to wake up the CPU and ensure // <i> it is active when PWM is about to start a DMA transfer. For // <i> initial transfer, done when a playback is started via PPI, // <i> a specific EGU instance is used to generate the interrupt. // <i> During the playback, the PWM interrupt triggered on SEQEND // <i> event of a preceding sequence is used to protect the transfer // <i> done for the next sequence to be played. //========================================================== #ifndef PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #if PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED // <o> PWM_NRF52_ANOMALY_109_EGU_INSTANCE - EGU instance used by the nRF52 Anomaly 109 workaround for PWM. // <0=> EGU0 // <1=> EGU1 // <2=> EGU2 // <3=> EGU3 // <4=> EGU4 // <5=> EGU5 #ifndef PWM_NRF52_ANOMALY_109_EGU_INSTANCE #define PWM_NRF52_ANOMALY_109_EGU_INSTANCE 5 #endif #endif //PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED // </e> #endif //PWM_ENABLED // </e> // <e> QDEC_ENABLED - nrf_drv_qdec - QDEC peripheral driver //========================================================== #ifndef QDEC_ENABLED #define QDEC_ENABLED 0 #endif #if QDEC_ENABLED // <o> QDEC_CONFIG_REPORTPER - Report period // <0=> 10 Samples // <1=> 40 Samples // <2=> 80 Samples // <3=> 120 Samples // <4=> 160 Samples // <5=> 200 Samples // <6=> 240 Samples // <7=> 280 Samples #ifndef QDEC_CONFIG_REPORTPER #define QDEC_CONFIG_REPORTPER 0 #endif // <o> QDEC_CONFIG_SAMPLEPER - Sample period // <0=> 128 us // <1=> 256 us // <2=> 512 us // <3=> 1024 us // <4=> 2048 us // <5=> 4096 us // <6=> 8192 us // <7=> 16384 us #ifndef QDEC_CONFIG_SAMPLEPER #define QDEC_CONFIG_SAMPLEPER 7 #endif // <o> QDEC_CONFIG_PIO_A - A pin <0-31> #ifndef QDEC_CONFIG_PIO_A #define QDEC_CONFIG_PIO_A 31 #endif // <o> QDEC_CONFIG_PIO_B - B pin <0-31> #ifndef QDEC_CONFIG_PIO_B #define QDEC_CONFIG_PIO_B 31 #endif // <o> QDEC_CONFIG_PIO_LED - LED pin <0-31> #ifndef QDEC_CONFIG_PIO_LED #define QDEC_CONFIG_PIO_LED 31 #endif // <o> QDEC_CONFIG_LEDPRE - LED pre #ifndef QDEC_CONFIG_LEDPRE #define QDEC_CONFIG_LEDPRE 511 #endif // <o> QDEC_CONFIG_LEDPOL - LED polarity // <0=> Active low // <1=> Active high #ifndef QDEC_CONFIG_LEDPOL #define QDEC_CONFIG_LEDPOL 1 #endif // <q> QDEC_CONFIG_DBFEN - Debouncing enable #ifndef QDEC_CONFIG_DBFEN #define QDEC_CONFIG_DBFEN 0 #endif // <q> QDEC_CONFIG_SAMPLE_INTEN - Sample ready interrupt enable #ifndef QDEC_CONFIG_SAMPLE_INTEN #define QDEC_CONFIG_SAMPLE_INTEN 0 #endif // <o> QDEC_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef QDEC_CONFIG_IRQ_PRIORITY #define QDEC_CONFIG_IRQ_PRIORITY 7 #endif // <e> QDEC_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef QDEC_CONFIG_LOG_ENABLED #define QDEC_CONFIG_LOG_ENABLED 0 #endif #if QDEC_CONFIG_LOG_ENABLED // <o> QDEC_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef QDEC_CONFIG_LOG_LEVEL #define QDEC_CONFIG_LOG_LEVEL 3 #endif // <o> QDEC_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef QDEC_CONFIG_INFO_COLOR #define QDEC_CONFIG_INFO_COLOR 0 #endif // <o> QDEC_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef QDEC_CONFIG_DEBUG_COLOR #define QDEC_CONFIG_DEBUG_COLOR 0 #endif #endif //QDEC_CONFIG_LOG_ENABLED // </e> #endif //QDEC_ENABLED // </e> // <e> RNG_ENABLED - nrf_drv_rng - RNG peripheral driver //========================================================== #ifndef RNG_ENABLED #define RNG_ENABLED 0 #endif #if RNG_ENABLED // <q> RNG_CONFIG_ERROR_CORRECTION - Error correction #ifndef RNG_CONFIG_ERROR_CORRECTION #define RNG_CONFIG_ERROR_CORRECTION 0 #endif // <o> RNG_CONFIG_POOL_SIZE - Pool size #ifndef RNG_CONFIG_POOL_SIZE #define RNG_CONFIG_POOL_SIZE 32 #endif // <o> RNG_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef RNG_CONFIG_IRQ_PRIORITY #define RNG_CONFIG_IRQ_PRIORITY 7 #endif // <e> RNG_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef RNG_CONFIG_LOG_ENABLED #define RNG_CONFIG_LOG_ENABLED 0 #endif #if RNG_CONFIG_LOG_ENABLED // <o> RNG_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef RNG_CONFIG_LOG_LEVEL #define RNG_CONFIG_LOG_LEVEL 3 #endif // <o> RNG_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RNG_CONFIG_INFO_COLOR #define RNG_CONFIG_INFO_COLOR 0 #endif // <o> RNG_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RNG_CONFIG_DEBUG_COLOR #define RNG_CONFIG_DEBUG_COLOR 0 #endif // <q> RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED - Enables logging of random numbers. #ifndef RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED #define RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED 0 #endif #endif //RNG_CONFIG_LOG_ENABLED // </e> #endif //RNG_ENABLED // </e> // <e> RTC_ENABLED - nrf_drv_rtc - RTC peripheral driver //========================================================== #ifndef RTC_ENABLED #define RTC_ENABLED 1 #endif #if RTC_ENABLED // <o> RTC_DEFAULT_CONFIG_FREQUENCY - Frequency <16-32768> #ifndef RTC_DEFAULT_CONFIG_FREQUENCY #define RTC_DEFAULT_CONFIG_FREQUENCY 32768 #endif // <q> RTC_DEFAULT_CONFIG_RELIABLE - Ensures safe compare event triggering #ifndef RTC_DEFAULT_CONFIG_RELIABLE #define RTC_DEFAULT_CONFIG_RELIABLE 0 #endif // <o> RTC_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef RTC_DEFAULT_CONFIG_IRQ_PRIORITY #define RTC_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> RTC0_ENABLED - Enable RTC0 instance #ifndef RTC0_ENABLED #define RTC0_ENABLED 0 #endif // <q> RTC1_ENABLED - Enable RTC1 instance #ifndef RTC1_ENABLED #define RTC1_ENABLED 0 #endif // <q> RTC2_ENABLED - Enable RTC2 instance #ifndef RTC2_ENABLED #define RTC2_ENABLED 1 #endif // <o> NRF_MAXIMUM_LATENCY_US - Maximum possible time[us] in highest priority interrupt #ifndef NRF_MAXIMUM_LATENCY_US #define NRF_MAXIMUM_LATENCY_US 2000 #endif // <e> RTC_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef RTC_CONFIG_LOG_ENABLED #define RTC_CONFIG_LOG_ENABLED 0 #endif #if RTC_CONFIG_LOG_ENABLED // <o> RTC_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef RTC_CONFIG_LOG_LEVEL #define RTC_CONFIG_LOG_LEVEL 3 #endif // <o> RTC_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RTC_CONFIG_INFO_COLOR #define RTC_CONFIG_INFO_COLOR 0 #endif // <o> RTC_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RTC_CONFIG_DEBUG_COLOR #define RTC_CONFIG_DEBUG_COLOR 0 #endif #endif //RTC_CONFIG_LOG_ENABLED // </e> #endif //RTC_ENABLED // </e> // <e> SAADC_ENABLED - nrf_drv_saadc - SAADC peripheral driver //========================================================== #ifndef SAADC_ENABLED #define SAADC_ENABLED 0 #endif #if SAADC_ENABLED // <o> SAADC_CONFIG_RESOLUTION - Resolution // <0=> 8 bit // <1=> 10 bit // <2=> 12 bit // <3=> 14 bit #ifndef SAADC_CONFIG_RESOLUTION #define SAADC_CONFIG_RESOLUTION 1 #endif // <o> SAADC_CONFIG_OVERSAMPLE - Sample period // <0=> Disabled // <1=> 2x // <2=> 4x // <3=> 8x // <4=> 16x // <5=> 32x // <6=> 64x // <7=> 128x // <8=> 256x #ifndef SAADC_CONFIG_OVERSAMPLE #define SAADC_CONFIG_OVERSAMPLE 0 #endif // <q> SAADC_CONFIG_LP_MODE - Enabling low power mode #ifndef SAADC_CONFIG_LP_MODE #define SAADC_CONFIG_LP_MODE 0 #endif // <o> SAADC_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef SAADC_CONFIG_IRQ_PRIORITY #define SAADC_CONFIG_IRQ_PRIORITY 7 #endif // <e> SAADC_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SAADC_CONFIG_LOG_ENABLED #define SAADC_CONFIG_LOG_ENABLED 0 #endif #if SAADC_CONFIG_LOG_ENABLED // <o> SAADC_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SAADC_CONFIG_LOG_LEVEL #define SAADC_CONFIG_LOG_LEVEL 3 #endif // <o> SAADC_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SAADC_CONFIG_INFO_COLOR #define SAADC_CONFIG_INFO_COLOR 0 #endif // <o> SAADC_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SAADC_CONFIG_DEBUG_COLOR #define SAADC_CONFIG_DEBUG_COLOR 0 #endif #endif //SAADC_CONFIG_LOG_ENABLED // </e> #endif //SAADC_ENABLED // </e> // <e> SPIS_ENABLED - nrf_drv_spis - SPI Slave driver //========================================================== #ifndef SPIS_ENABLED #define SPIS_ENABLED 0 #endif #if SPIS_ENABLED // <o> SPIS_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef SPIS_DEFAULT_CONFIG_IRQ_PRIORITY #define SPIS_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <o> SPIS_DEFAULT_MODE - Mode // <0=> MODE_0 // <1=> MODE_1 // <2=> MODE_2 // <3=> MODE_3 #ifndef SPIS_DEFAULT_MODE #define SPIS_DEFAULT_MODE 0 #endif // <o> SPIS_DEFAULT_BIT_ORDER - SPIS default bit order // <0=> MSB first // <1=> LSB first #ifndef SPIS_DEFAULT_BIT_ORDER #define SPIS_DEFAULT_BIT_ORDER 0 #endif // <o> SPIS_DEFAULT_DEF - SPIS default DEF character <0-255> #ifndef SPIS_DEFAULT_DEF #define SPIS_DEFAULT_DEF 255 #endif // <o> SPIS_DEFAULT_ORC - SPIS default ORC character <0-255> #ifndef SPIS_DEFAULT_ORC #define SPIS_DEFAULT_ORC 255 #endif // <q> SPIS0_ENABLED - Enable SPIS0 instance #ifndef SPIS0_ENABLED #define SPIS0_ENABLED 0 #endif // <q> SPIS1_ENABLED - Enable SPIS1 instance #ifndef SPIS1_ENABLED #define SPIS1_ENABLED 0 #endif // <q> SPIS2_ENABLED - Enable SPIS2 instance #ifndef SPIS2_ENABLED #define SPIS2_ENABLED 0 #endif // <e> SPIS_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SPIS_CONFIG_LOG_ENABLED #define SPIS_CONFIG_LOG_ENABLED 0 #endif #if SPIS_CONFIG_LOG_ENABLED // <o> SPIS_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SPIS_CONFIG_LOG_LEVEL #define SPIS_CONFIG_LOG_LEVEL 3 #endif // <o> SPIS_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPIS_CONFIG_INFO_COLOR #define SPIS_CONFIG_INFO_COLOR 0 #endif // <o> SPIS_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPIS_CONFIG_DEBUG_COLOR #define SPIS_CONFIG_DEBUG_COLOR 0 #endif #endif //SPIS_CONFIG_LOG_ENABLED // </e> // <q> SPIS_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 Anomaly 109 workaround for SPIS. // <i> The workaround uses a GPIOTE channel to generate interrupts // <i> on falling edges detected on the CSN line. This will make // <i> the CPU active for the moment when SPIS starts DMA transfers, // <i> and this way the transfers will be protected. // <i> This workaround uses GPIOTE driver, so this driver must be // <i> enabled as well. #ifndef SPIS_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define SPIS_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #endif //SPIS_ENABLED // </e> // <e> SPI_ENABLED - nrf_drv_spi - SPI/SPIM peripheral driver //========================================================== #ifndef SPI_ENABLED #define SPI_ENABLED 0 #endif #if SPI_ENABLED // <o> SPI_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef SPI_DEFAULT_CONFIG_IRQ_PRIORITY #define SPI_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <e> SPI0_ENABLED - Enable SPI0 instance //========================================================== #ifndef SPI0_ENABLED #define SPI0_ENABLED 0 #endif #if SPI0_ENABLED // <q> SPI0_USE_EASY_DMA - Use EasyDMA #ifndef SPI0_USE_EASY_DMA #define SPI0_USE_EASY_DMA 1 #endif // <o> SPI0_DEFAULT_FREQUENCY - SPI frequency // <33554432=> 125 kHz // <67108864=> 250 kHz // <134217728=> 500 kHz // <268435456=> 1 MHz // <536870912=> 2 MHz // <1073741824=> 4 MHz // <2147483648=> 8 MHz #ifndef SPI0_DEFAULT_FREQUENCY #define SPI0_DEFAULT_FREQUENCY 1073741824 #endif #endif //SPI0_ENABLED // </e> // <e> SPI1_ENABLED - Enable SPI1 instance //========================================================== #ifndef SPI1_ENABLED #define SPI1_ENABLED 0 #endif #if SPI1_ENABLED // <q> SPI1_USE_EASY_DMA - Use EasyDMA #ifndef SPI1_USE_EASY_DMA #define SPI1_USE_EASY_DMA 1 #endif // <o> SPI1_DEFAULT_FREQUENCY - SPI frequency // <33554432=> 125 kHz // <67108864=> 250 kHz // <134217728=> 500 kHz // <268435456=> 1 MHz // <536870912=> 2 MHz // <1073741824=> 4 MHz // <2147483648=> 8 MHz #ifndef SPI1_DEFAULT_FREQUENCY #define SPI1_DEFAULT_FREQUENCY 1073741824 #endif #endif //SPI1_ENABLED // </e> // <e> SPI2_ENABLED - Enable SPI2 instance //========================================================== #ifndef SPI2_ENABLED #define SPI2_ENABLED 0 #endif #if SPI2_ENABLED // <q> SPI2_USE_EASY_DMA - Use EasyDMA #ifndef SPI2_USE_EASY_DMA #define SPI2_USE_EASY_DMA 1 #endif // <q> SPI2_DEFAULT_FREQUENCY - Use EasyDMA #ifndef SPI2_DEFAULT_FREQUENCY #define SPI2_DEFAULT_FREQUENCY 1 #endif #endif //SPI2_ENABLED // </e> // <e> SPI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SPI_CONFIG_LOG_ENABLED #define SPI_CONFIG_LOG_ENABLED 0 #endif #if SPI_CONFIG_LOG_ENABLED // <o> SPI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SPI_CONFIG_LOG_LEVEL #define SPI_CONFIG_LOG_LEVEL 3 #endif // <o> SPI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPI_CONFIG_INFO_COLOR #define SPI_CONFIG_INFO_COLOR 0 #endif // <o> SPI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPI_CONFIG_DEBUG_COLOR #define SPI_CONFIG_DEBUG_COLOR 0 #endif #endif //SPI_CONFIG_LOG_ENABLED // </e> // <q> SPIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 anomaly 109 workaround for SPIM. // <i> The workaround uses interrupts to wake up the CPU by catching // <i> a start event of zero-length transmission to start the clock. This // <i> ensures that the DMA transfer will be executed without issues and // <i> that the proper transfer will be started. See more in the Errata // <i> document or Anomaly 109 Addendum located at // <i> https://infocenter.nordicsemi.com/ #ifndef SPIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define SPIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #endif //SPI_ENABLED // </e> // <e> TIMER_ENABLED - nrf_drv_timer - TIMER periperal driver //========================================================== #ifndef TIMER_ENABLED #define TIMER_ENABLED 0 #endif #if TIMER_ENABLED // <o> TIMER_DEFAULT_CONFIG_FREQUENCY - Timer frequency if in Timer mode // <0=> 16 MHz // <1=> 8 MHz // <2=> 4 MHz // <3=> 2 MHz // <4=> 1 MHz // <5=> 500 kHz // <6=> 250 kHz // <7=> 125 kHz // <8=> 62.5 kHz // <9=> 31.25 kHz #ifndef TIMER_DEFAULT_CONFIG_FREQUENCY #define TIMER_DEFAULT_CONFIG_FREQUENCY 0 #endif // <o> TIMER_DEFAULT_CONFIG_MODE - Timer mode or operation // <0=> Timer // <1=> Counter #ifndef TIMER_DEFAULT_CONFIG_MODE #define TIMER_DEFAULT_CONFIG_MODE 0 #endif // <o> TIMER_DEFAULT_CONFIG_BIT_WIDTH - Timer counter bit width // <0=> 16 bit // <1=> 8 bit // <2=> 24 bit // <3=> 32 bit #ifndef TIMER_DEFAULT_CONFIG_BIT_WIDTH #define TIMER_DEFAULT_CONFIG_BIT_WIDTH 0 #endif // <o> TIMER_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef TIMER_DEFAULT_CONFIG_IRQ_PRIORITY #define TIMER_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> TIMER0_ENABLED - Enable TIMER0 instance #ifndef TIMER0_ENABLED #define TIMER0_ENABLED 0 #endif // <q> TIMER1_ENABLED - Enable TIMER1 instance #ifndef TIMER1_ENABLED #define TIMER1_ENABLED 0 #endif // <q> TIMER2_ENABLED - Enable TIMER2 instance #ifndef TIMER2_ENABLED #define TIMER2_ENABLED 0 #endif // <q> TIMER3_ENABLED - Enable TIMER3 instance #ifndef TIMER3_ENABLED #define TIMER3_ENABLED 0 #endif // <q> TIMER4_ENABLED - Enable TIMER4 instance #ifndef TIMER4_ENABLED #define TIMER4_ENABLED 0 #endif // <e> TIMER_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef TIMER_CONFIG_LOG_ENABLED #define TIMER_CONFIG_LOG_ENABLED 0 #endif #if TIMER_CONFIG_LOG_ENABLED // <o> TIMER_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef TIMER_CONFIG_LOG_LEVEL #define TIMER_CONFIG_LOG_LEVEL 3 #endif // <o> TIMER_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TIMER_CONFIG_INFO_COLOR #define TIMER_CONFIG_INFO_COLOR 0 #endif // <o> TIMER_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TIMER_CONFIG_DEBUG_COLOR #define TIMER_CONFIG_DEBUG_COLOR 0 #endif #endif //TIMER_CONFIG_LOG_ENABLED // </e> #endif //TIMER_ENABLED // </e> // <e> TWIS_ENABLED - nrf_drv_twis - TWIS peripheral driver //========================================================== #ifndef TWIS_ENABLED #define TWIS_ENABLED 0 #endif #if TWIS_ENABLED // <o> TWIS_DEFAULT_CONFIG_ADDR0 - Address0 #ifndef TWIS_DEFAULT_CONFIG_ADDR0 #define TWIS_DEFAULT_CONFIG_ADDR0 0 #endif // <o> TWIS_DEFAULT_CONFIG_ADDR1 - Address1 #ifndef TWIS_DEFAULT_CONFIG_ADDR1 #define TWIS_DEFAULT_CONFIG_ADDR1 0 #endif // <o> TWIS_DEFAULT_CONFIG_SCL_PULL - SCL pin pull configuration // <0=> Disabled // <1=> Pull down // <3=> Pull up #ifndef TWIS_DEFAULT_CONFIG_SCL_PULL #define TWIS_DEFAULT_CONFIG_SCL_PULL 0 #endif // <o> TWIS_DEFAULT_CONFIG_SDA_PULL - SDA pin pull configuration // <0=> Disabled // <1=> Pull down // <3=> Pull up #ifndef TWIS_DEFAULT_CONFIG_SDA_PULL #define TWIS_DEFAULT_CONFIG_SDA_PULL 0 #endif // <o> TWIS_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef TWIS_DEFAULT_CONFIG_IRQ_PRIORITY #define TWIS_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> TWIS0_ENABLED - Enable TWIS0 instance #ifndef TWIS0_ENABLED #define TWIS0_ENABLED 0 #endif // <q> TWIS1_ENABLED - Enable TWIS1 instance #ifndef TWIS1_ENABLED #define TWIS1_ENABLED 0 #endif // <q> TWIS_ASSUME_INIT_AFTER_RESET_ONLY - Assume that any instance would be initialized only once // <i> Optimization flag. Registers used by TWIS are shared by other peripherals. Normally, during initialization driver tries to clear all registers to known state before doing the initialization itself. This gives initialization safe procedure, no matter when it would be called. If you activate TWIS only once and do never uninitialize it - set this flag to 1 what gives more optimal code. #ifndef TWIS_ASSUME_INIT_AFTER_RESET_ONLY #define TWIS_ASSUME_INIT_AFTER_RESET_ONLY 0 #endif // <q> TWIS_NO_SYNC_MODE - Remove support for synchronous mode // <i> Synchronous mode would be used in specific situations. And it uses some additional code and data memory to safely process state machine by polling it in status functions. If this functionality is not required it may be disabled to free some resources. #ifndef TWIS_NO_SYNC_MODE #define TWIS_NO_SYNC_MODE 0 #endif // <e> TWIS_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef TWIS_CONFIG_LOG_ENABLED #define TWIS_CONFIG_LOG_ENABLED 0 #endif #if TWIS_CONFIG_LOG_ENABLED // <o> TWIS_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef TWIS_CONFIG_LOG_LEVEL #define TWIS_CONFIG_LOG_LEVEL 3 #endif // <o> TWIS_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWIS_CONFIG_INFO_COLOR #define TWIS_CONFIG_INFO_COLOR 0 #endif // <o> TWIS_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWIS_CONFIG_DEBUG_COLOR #define TWIS_CONFIG_DEBUG_COLOR 0 #endif #endif //TWIS_CONFIG_LOG_ENABLED // </e> #endif //TWIS_ENABLED // </e> // <e> TWI_ENABLED - nrf_drv_twi - TWI/TWIM peripheral driver //========================================================== #ifndef TWI_ENABLED #define TWI_ENABLED 0 #endif #if TWI_ENABLED // <o> TWI_DEFAULT_CONFIG_FREQUENCY - Frequency // <26738688=> 100k // <67108864=> 250k // <104857600=> 400k #ifndef TWI_DEFAULT_CONFIG_FREQUENCY #define TWI_DEFAULT_CONFIG_FREQUENCY 26738688 #endif // <q> TWI_DEFAULT_CONFIG_CLR_BUS_INIT - Enables bus clearing procedure during init #ifndef TWI_DEFAULT_CONFIG_CLR_BUS_INIT #define TWI_DEFAULT_CONFIG_CLR_BUS_INIT 0 #endif // <q> TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT - Enables bus holding after uninit #ifndef TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT #define TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT 0 #endif // <o> TWI_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef TWI_DEFAULT_CONFIG_IRQ_PRIORITY #define TWI_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <e> TWI0_ENABLED - Enable TWI0 instance //========================================================== #ifndef TWI0_ENABLED #define TWI0_ENABLED 0 #endif #if TWI0_ENABLED // <q> TWI0_USE_EASY_DMA - Use EasyDMA (if present) #ifndef TWI0_USE_EASY_DMA #define TWI0_USE_EASY_DMA 0 #endif #endif //TWI0_ENABLED // </e> // <e> TWI1_ENABLED - Enable TWI1 instance //========================================================== #ifndef TWI1_ENABLED #define TWI1_ENABLED 0 #endif #if TWI1_ENABLED // <q> TWI1_USE_EASY_DMA - Use EasyDMA (if present) #ifndef TWI1_USE_EASY_DMA #define TWI1_USE_EASY_DMA 0 #endif #endif //TWI1_ENABLED // </e> // <e> TWI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef TWI_CONFIG_LOG_ENABLED #define TWI_CONFIG_LOG_ENABLED 0 #endif #if TWI_CONFIG_LOG_ENABLED // <o> TWI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef TWI_CONFIG_LOG_LEVEL #define TWI_CONFIG_LOG_LEVEL 3 #endif // <o> TWI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWI_CONFIG_INFO_COLOR #define TWI_CONFIG_INFO_COLOR 0 #endif // <o> TWI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWI_CONFIG_DEBUG_COLOR #define TWI_CONFIG_DEBUG_COLOR 0 #endif #endif //TWI_CONFIG_LOG_ENABLED // </e> // <q> TWIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 anomaly 109 workaround for TWIM. // <i> The workaround uses interrupts to wake up the CPU by catching // <i> the start event of zero-frequency transmission, clear the // <i> peripheral, set desired frequency, start the peripheral, and // <i> the proper transmission. See more in the Errata document or // <i> Anomaly 109 Addendum located at https://infocenter.nordicsemi.com/ #ifndef TWIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define TWIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #endif //TWI_ENABLED // </e> // <e> UART_ENABLED - nrf_drv_uart - UART/UARTE peripheral driver //========================================================== #ifndef UART_ENABLED #define UART_ENABLED 1 #endif #if UART_ENABLED // <o> UART_DEFAULT_CONFIG_HWFC - Hardware Flow Control // <0=> Disabled // <1=> Enabled #ifndef UART_DEFAULT_CONFIG_HWFC #define UART_DEFAULT_CONFIG_HWFC 0 #endif // <o> UART_DEFAULT_CONFIG_PARITY - Parity // <0=> Excluded // <14=> Included #ifndef UART_DEFAULT_CONFIG_PARITY #define UART_DEFAULT_CONFIG_PARITY 0 #endif // <o> UART_DEFAULT_CONFIG_BAUDRATE - Default Baudrate // <323584=> 1200 baud // <643072=> 2400 baud // <1290240=> 4800 baud // <2576384=> 9600 baud // <3862528=> 14400 baud // <5152768=> 19200 baud // <7716864=> 28800 baud // <10289152=> 38400 baud // <15400960=> 57600 baud // <20615168=> 76800 baud // <30801920=> 115200 baud // <61865984=> 230400 baud // <67108864=> 250000 baud // <121634816=> 460800 baud // <251658240=> 921600 baud // <268435456=> 57600 baud #ifndef UART_DEFAULT_CONFIG_BAUDRATE #define UART_DEFAULT_CONFIG_BAUDRATE 30801920 #endif // <o> UART_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef UART_DEFAULT_CONFIG_IRQ_PRIORITY #define UART_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> UART_EASY_DMA_SUPPORT - Driver supporting EasyDMA #ifndef UART_EASY_DMA_SUPPORT #define UART_EASY_DMA_SUPPORT 1 #endif // <q> UART_LEGACY_SUPPORT - Driver supporting Legacy mode #ifndef UART_LEGACY_SUPPORT #define UART_LEGACY_SUPPORT 1 #endif // <e> UART0_ENABLED - Enable UART0 instance //========================================================== #ifndef UART0_ENABLED #define UART0_ENABLED 1 #endif #if UART0_ENABLED // <q> UART0_CONFIG_USE_EASY_DMA - Default setting for using EasyDMA #ifndef UART0_CONFIG_USE_EASY_DMA #define UART0_CONFIG_USE_EASY_DMA 1 #endif #endif //UART0_ENABLED // </e> // <e> UART_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef UART_CONFIG_LOG_ENABLED #define UART_CONFIG_LOG_ENABLED 0 #endif #if UART_CONFIG_LOG_ENABLED // <o> UART_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef UART_CONFIG_LOG_LEVEL #define UART_CONFIG_LOG_LEVEL 3 #endif // <o> UART_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef UART_CONFIG_INFO_COLOR #define UART_CONFIG_INFO_COLOR 0 #endif // <o> UART_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef UART_CONFIG_DEBUG_COLOR #define UART_CONFIG_DEBUG_COLOR 0 #endif #endif //UART_CONFIG_LOG_ENABLED // </e> #endif //UART_ENABLED // </e> // <e> USBD_ENABLED - nrf_drv_usbd - USB driver //========================================================== #ifndef USBD_ENABLED #define USBD_ENABLED 0 #endif #if USBD_ENABLED // <o> USBD_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef USBD_CONFIG_IRQ_PRIORITY #define USBD_CONFIG_IRQ_PRIORITY 7 #endif // <o> NRF_DRV_USBD_DMASCHEDULER_MODE - USBD SMA scheduler working scheme // <0=> Prioritized access // <1=> Round Robin #ifndef NRF_DRV_USBD_DMASCHEDULER_MODE #define NRF_DRV_USBD_DMASCHEDULER_MODE 0 #endif // <q> NRF_USBD_DRV_LOG_ENABLED - Enable logging #ifndef NRF_USBD_DRV_LOG_ENABLED #define NRF_USBD_DRV_LOG_ENABLED 0 #endif #endif //USBD_ENABLED // </e> // <e> WDT_ENABLED - nrf_drv_wdt - WDT peripheral driver //========================================================== #ifndef WDT_ENABLED #define WDT_ENABLED 0 #endif #if WDT_ENABLED // <o> WDT_CONFIG_BEHAVIOUR - WDT behavior in CPU SLEEP or HALT mode // <1=> Run in SLEEP, Pause in HALT // <8=> Pause in SLEEP, Run in HALT // <9=> Run in SLEEP and HALT // <0=> Pause in SLEEP and HALT #ifndef WDT_CONFIG_BEHAVIOUR #define WDT_CONFIG_BEHAVIOUR 1 #endif // <o> WDT_CONFIG_RELOAD_VALUE - Reload value <15-4294967295> #ifndef WDT_CONFIG_RELOAD_VALUE #define WDT_CONFIG_RELOAD_VALUE 2000 #endif // <o> WDT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef WDT_CONFIG_IRQ_PRIORITY #define WDT_CONFIG_IRQ_PRIORITY 7 #endif // <e> WDT_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef WDT_CONFIG_LOG_ENABLED #define WDT_CONFIG_LOG_ENABLED 0 #endif #if WDT_CONFIG_LOG_ENABLED // <o> WDT_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef WDT_CONFIG_LOG_LEVEL #define WDT_CONFIG_LOG_LEVEL 3 #endif // <o> WDT_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef WDT_CONFIG_INFO_COLOR #define WDT_CONFIG_INFO_COLOR 0 #endif // <o> WDT_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef WDT_CONFIG_DEBUG_COLOR #define WDT_CONFIG_DEBUG_COLOR 0 #endif #endif //WDT_CONFIG_LOG_ENABLED // </e> #endif //WDT_ENABLED // </e> // </h> //========================================================== // <h> nRF_Libraries //========================================================== // <q> APP_GPIOTE_ENABLED - app_gpiote - GPIOTE events dispatcher #ifndef APP_GPIOTE_ENABLED #define APP_GPIOTE_ENABLED 0 #endif // <q> APP_PWM_ENABLED - app_pwm - PWM functionality #ifndef APP_PWM_ENABLED #define APP_PWM_ENABLED 0 #endif // <e> APP_SCHEDULER_ENABLED - app_scheduler - Events scheduler //========================================================== #ifndef APP_SCHEDULER_ENABLED #define APP_SCHEDULER_ENABLED 1 #endif #if APP_SCHEDULER_ENABLED // <q> APP_SCHEDULER_WITH_PAUSE - Enabling pause feature #ifndef APP_SCHEDULER_WITH_PAUSE #define APP_SCHEDULER_WITH_PAUSE 0 #endif // <q> APP_SCHEDULER_WITH_PROFILER - Enabling scheduler profiling #ifndef APP_SCHEDULER_WITH_PROFILER #define APP_SCHEDULER_WITH_PROFILER 0 #endif #endif //APP_SCHEDULER_ENABLED // </e> // <e> APP_TIMER_ENABLED - app_timer - Application timer functionality //========================================================== #ifndef APP_TIMER_ENABLED #define APP_TIMER_ENABLED 1 #endif #if APP_TIMER_ENABLED // <o> APP_TIMER_CONFIG_RTC_FREQUENCY - Configure RTC prescaler. // <0=> 32768 Hz // <1=> 16384 Hz // <3=> 8192 Hz // <7=> 4096 Hz // <15=> 2048 Hz // <31=> 1024 Hz #ifndef APP_TIMER_CONFIG_RTC_FREQUENCY #define APP_TIMER_CONFIG_RTC_FREQUENCY 0 #endif // <o> APP_TIMER_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef APP_TIMER_CONFIG_IRQ_PRIORITY #define APP_TIMER_CONFIG_IRQ_PRIORITY 7 #endif // <o> APP_TIMER_CONFIG_OP_QUEUE_SIZE - Capacity of timer requests queue. // <i> Size of the queue depends on how many timers are used // <i> in the system, how often timers are started and overall // <i> system latency. If queue size is too small app_timer calls // <i> will fail. #ifndef APP_TIMER_CONFIG_OP_QUEUE_SIZE #define APP_TIMER_CONFIG_OP_QUEUE_SIZE 10 #endif // <q> APP_TIMER_CONFIG_USE_SCHEDULER - Enable scheduling app_timer events to app_scheduler #ifndef APP_TIMER_CONFIG_USE_SCHEDULER #define APP_TIMER_CONFIG_USE_SCHEDULER 0 #endif // <q> APP_TIMER_WITH_PROFILER - Enable app_timer profiling #ifndef APP_TIMER_WITH_PROFILER #define APP_TIMER_WITH_PROFILER 0 #endif // <q> APP_TIMER_KEEPS_RTC_ACTIVE - Enable RTC always on // <i> If option is enabled RTC is kept running even if there is no active timers. // <i> This option can be used when app_timer is used for timestamping. #ifndef APP_TIMER_KEEPS_RTC_ACTIVE #define APP_TIMER_KEEPS_RTC_ACTIVE 0 #endif // <o> APP_TIMER_CONFIG_SWI_NUMBER - Configure SWI instance used. // <0=> 0 // <1=> 1 #ifndef APP_TIMER_CONFIG_SWI_NUMBER #define APP_TIMER_CONFIG_SWI_NUMBER 0 #endif #endif //APP_TIMER_ENABLED // </e> // <q> APP_TWI_ENABLED - app_twi - TWI transaction manager #ifndef APP_TWI_ENABLED #define APP_TWI_ENABLED 0 #endif // <e> APP_UART_ENABLED - app_uart - UART driver //========================================================== #ifndef APP_UART_ENABLED #define APP_UART_ENABLED 0 #endif #if APP_UART_ENABLED // <o> APP_UART_DRIVER_INSTANCE - UART instance used // <0=> 0 #ifndef APP_UART_DRIVER_INSTANCE #define APP_UART_DRIVER_INSTANCE 0 #endif #endif //APP_UART_ENABLED // </e> // <q> APP_USBD_CLASS_AUDIO_ENABLED - app_usbd_audio - USB AUDIO class #ifndef APP_USBD_CLASS_AUDIO_ENABLED #define APP_USBD_CLASS_AUDIO_ENABLED 0 #endif // <q> APP_USBD_CLASS_HID_ENABLED - app_usbd_hid - USB HID class #ifndef APP_USBD_CLASS_HID_ENABLED #define APP_USBD_CLASS_HID_ENABLED 0 #endif // <q> APP_USBD_HID_GENERIC_ENABLED - app_usbd_hid_generic - USB HID generic #ifndef APP_USBD_HID_GENERIC_ENABLED #define APP_USBD_HID_GENERIC_ENABLED 0 #endif // <q> APP_USBD_HID_KBD_ENABLED - app_usbd_hid_kbd - USB HID keyboard #ifndef APP_USBD_HID_KBD_ENABLED #define APP_USBD_HID_KBD_ENABLED 0 #endif // <q> APP_USBD_HID_MOUSE_ENABLED - app_usbd_hid_mouse - USB HID mouse #ifndef APP_USBD_HID_MOUSE_ENABLED #define APP_USBD_HID_MOUSE_ENABLED 0 #endif // <q> BUTTON_ENABLED - app_button - buttons handling module #ifndef BUTTON_ENABLED #define BUTTON_ENABLED 1 #endif // <q> CRC16_ENABLED - crc16 - CRC16 calculation routines #ifndef CRC16_ENABLED #define CRC16_ENABLED 0 #endif // <q> CRC32_ENABLED - crc32 - CRC32 calculation routines #ifndef CRC32_ENABLED #define CRC32_ENABLED 0 #endif // <q> ECC_ENABLED - ecc - Elliptic Curve Cryptography Library #ifndef ECC_ENABLED #define ECC_ENABLED 0 #endif // <e> FDS_ENABLED - fds - Flash data storage module //========================================================== #ifndef FDS_ENABLED #define FDS_ENABLED 0 #endif #if FDS_ENABLED // <o> FDS_OP_QUEUE_SIZE - Size of the internal queue. #ifndef FDS_OP_QUEUE_SIZE #define FDS_OP_QUEUE_SIZE 4 #endif // <o> FDS_CHUNK_QUEUE_SIZE - Determines how many @ref fds_record_chunk_t structures can be buffered at any time. #ifndef FDS_CHUNK_QUEUE_SIZE #define FDS_CHUNK_QUEUE_SIZE 8 #endif // <o> FDS_MAX_USERS - Maximum number of callbacks that can be registered. #ifndef FDS_MAX_USERS #define FDS_MAX_USERS 8 #endif // <o> FDS_VIRTUAL_PAGES - Number of virtual flash pages to use. // <i> One of the virtual pages is reserved by the system for garbage collection. // <i> Therefore, the minimum is two virtual pages: one page to store data and // <i> one page to be used by the system for garbage collection. The total amount // <i> of flash memory that is used by FDS amounts to @ref FDS_VIRTUAL_PAGES // <i> @ref FDS_VIRTUAL_PAGE_SIZE * 4 bytes. #ifndef FDS_VIRTUAL_PAGES #define FDS_VIRTUAL_PAGES 3 #endif // <o> FDS_VIRTUAL_PAGE_SIZE - The size of a virtual page of flash memory, expressed in number of 4-byte words. // <i> By default, a virtual page is the same size as a physical page. // <i> The size of a virtual page must be a multiple of the size of a physical page. // <1024=> 1024 // <2048=> 2048 #ifndef FDS_VIRTUAL_PAGE_SIZE #define FDS_VIRTUAL_PAGE_SIZE 1024 #endif #endif //FDS_ENABLED // </e> // <e> FSTORAGE_ENABLED - fstorage - Flash storage module //========================================================== #ifndef FSTORAGE_ENABLED #define FSTORAGE_ENABLED 0 #endif #if FSTORAGE_ENABLED // <o> FS_QUEUE_SIZE - Configures the size of the internal queue. // <i> Increase this if there are many users, or if it is likely that many // <i> operation will be queued at once without waiting for the previous operations // <i> to complete. In general, increase the queue size if you frequently receive // <i> @ref FS_ERR_QUEUE_FULL errors when calling @ref fs_store or @ref fs_erase. #ifndef FS_QUEUE_SIZE #define FS_QUEUE_SIZE 4 #endif // <o> FS_OP_MAX_RETRIES - Number attempts to execute an operation if the SoftDevice fails. // <i> Increase this value if events return the @ref FS_ERR_OPERATION_TIMEOUT // <i> error often. The SoftDevice may fail to schedule flash access due to high BLE activity. #ifndef FS_OP_MAX_RETRIES #define FS_OP_MAX_RETRIES 3 #endif // <o> FS_MAX_WRITE_SIZE_WORDS - Maximum number of words to be written to flash in a single operation. // <i> Tweaking this value can increase the chances of the SoftDevice being // <i> able to fit flash operations in between radio activity. This value is bound by the // <i> maximum number of words which the SoftDevice can write to flash in a single call to // <i> @ref sd_flash_write, which is 256 words for nRF51 ICs and 1024 words for nRF52 ICs. #ifndef FS_MAX_WRITE_SIZE_WORDS #define FS_MAX_WRITE_SIZE_WORDS 1024 #endif #endif //FSTORAGE_ENABLED // </e> // <q> HARDFAULT_HANDLER_ENABLED - hardfault_default - HardFault default handler for debugging and release #ifndef HARDFAULT_HANDLER_ENABLED #define HARDFAULT_HANDLER_ENABLED 0 #endif // <e> HCI_MEM_POOL_ENABLED - hci_mem_pool - memory pool implementation used by HCI //========================================================== #ifndef HCI_MEM_POOL_ENABLED #define HCI_MEM_POOL_ENABLED 0 #endif #if HCI_MEM_POOL_ENABLED // <o> HCI_TX_BUF_SIZE - TX buffer size in bytes. #ifndef HCI_TX_BUF_SIZE #define HCI_TX_BUF_SIZE 600 #endif // <o> HCI_RX_BUF_SIZE - RX buffer size in bytes. #ifndef HCI_RX_BUF_SIZE #define HCI_RX_BUF_SIZE 600 #endif // <o> HCI_RX_BUF_QUEUE_SIZE - RX buffer queue size. #ifndef HCI_RX_BUF_QUEUE_SIZE #define HCI_RX_BUF_QUEUE_SIZE 4 #endif #endif //HCI_MEM_POOL_ENABLED // </e> // <e> HCI_SLIP_ENABLED - hci_slip - SLIP protocol implementation used by HCI //========================================================== #ifndef HCI_SLIP_ENABLED #define HCI_SLIP_ENABLED 0 #endif #if HCI_SLIP_ENABLED // <o> HCI_UART_BAUDRATE - Default Baudrate // <323584=> 1200 baud // <643072=> 2400 baud // <1290240=> 4800 baud // <2576384=> 9600 baud // <3862528=> 14400 baud // <5152768=> 19200 baud // <7716864=> 28800 baud // <10289152=> 38400 baud // <15400960=> 57600 baud // <20615168=> 76800 baud // <30801920=> 115200 baud // <61865984=> 230400 baud // <67108864=> 250000 baud // <121634816=> 460800 baud // <251658240=> 921600 baud // <268435456=> 57600 baud #ifndef HCI_UART_BAUDRATE #define HCI_UART_BAUDRATE 30801920 #endif // <o> HCI_UART_FLOW_CONTROL - Hardware Flow Control // <0=> Disabled // <1=> Enabled #ifndef HCI_UART_FLOW_CONTROL #define HCI_UART_FLOW_CONTROL 0 #endif // <o> HCI_UART_RX_PIN - UART RX pin #ifndef HCI_UART_RX_PIN #define HCI_UART_RX_PIN 8 #endif // <o> HCI_UART_TX_PIN - UART TX pin #ifndef HCI_UART_TX_PIN #define HCI_UART_TX_PIN 6 #endif // <o> HCI_UART_RTS_PIN - UART RTS pin #ifndef HCI_UART_RTS_PIN #define HCI_UART_RTS_PIN 5 #endif // <o> HCI_UART_CTS_PIN - UART CTS pin #ifndef HCI_UART_CTS_PIN #define HCI_UART_CTS_PIN 7 #endif #endif //HCI_SLIP_ENABLED // </e> // <e> HCI_TRANSPORT_ENABLED - hci_transport - HCI transport //========================================================== #ifndef HCI_TRANSPORT_ENABLED #define HCI_TRANSPORT_ENABLED 0 #endif #if HCI_TRANSPORT_ENABLED // <o> HCI_MAX_PACKET_SIZE_IN_BITS - Maximum size of a single application packet in bits. #ifndef HCI_MAX_PACKET_SIZE_IN_BITS #define HCI_MAX_PACKET_SIZE_IN_BITS 8000 #endif #endif //HCI_TRANSPORT_ENABLED // </e> // <q> LED_SOFTBLINK_ENABLED - led_softblink - led_softblink module #ifndef LED_SOFTBLINK_ENABLED #define LED_SOFTBLINK_ENABLED 0 #endif // <q> LOW_POWER_PWM_ENABLED - low_power_pwm - low_power_pwm module #ifndef LOW_POWER_PWM_ENABLED #define LOW_POWER_PWM_ENABLED 0 #endif // <e> MEM_MANAGER_ENABLED - mem_manager - Dynamic memory allocator //========================================================== #ifndef MEM_MANAGER_ENABLED #define MEM_MANAGER_ENABLED 0 #endif #if MEM_MANAGER_ENABLED // <o> MEMORY_MANAGER_SMALL_BLOCK_COUNT - Size of each memory blocks identified as 'small' block. <0-255> #ifndef MEMORY_MANAGER_SMALL_BLOCK_COUNT #define MEMORY_MANAGER_SMALL_BLOCK_COUNT 1 #endif // <o> MEMORY_MANAGER_SMALL_BLOCK_SIZE - Size of each memory blocks identified as 'small' block. // <i> Size of each memory blocks identified as 'small' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_SMALL_BLOCK_SIZE #define MEMORY_MANAGER_SMALL_BLOCK_SIZE 32 #endif // <o> MEMORY_MANAGER_MEDIUM_BLOCK_COUNT - Size of each memory blocks identified as 'medium' block. <0-255> #ifndef MEMORY_MANAGER_MEDIUM_BLOCK_COUNT #define MEMORY_MANAGER_MEDIUM_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_MEDIUM_BLOCK_SIZE - Size of each memory blocks identified as 'medium' block. // <i> Size of each memory blocks identified as 'medium' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_MEDIUM_BLOCK_SIZE #define MEMORY_MANAGER_MEDIUM_BLOCK_SIZE 256 #endif // <o> MEMORY_MANAGER_LARGE_BLOCK_COUNT - Size of each memory blocks identified as 'large' block. <0-255> #ifndef MEMORY_MANAGER_LARGE_BLOCK_COUNT #define MEMORY_MANAGER_LARGE_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_LARGE_BLOCK_SIZE - Size of each memory blocks identified as 'large' block. // <i> Size of each memory blocks identified as 'large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_LARGE_BLOCK_SIZE #define MEMORY_MANAGER_LARGE_BLOCK_SIZE 256 #endif // <o> MEMORY_MANAGER_XLARGE_BLOCK_COUNT - Size of each memory blocks identified as 'extra large' block. <0-255> #ifndef MEMORY_MANAGER_XLARGE_BLOCK_COUNT #define MEMORY_MANAGER_XLARGE_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XLARGE_BLOCK_SIZE - Size of each memory blocks identified as 'extra large' block. // <i> Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XLARGE_BLOCK_SIZE #define MEMORY_MANAGER_XLARGE_BLOCK_SIZE 1320 #endif // <o> MEMORY_MANAGER_XXLARGE_BLOCK_COUNT - Size of each memory blocks identified as 'extra extra large' block. <0-255> #ifndef MEMORY_MANAGER_XXLARGE_BLOCK_COUNT #define MEMORY_MANAGER_XXLARGE_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XXLARGE_BLOCK_SIZE - Size of each memory blocks identified as 'extra extra large' block. // <i> Size of each memory blocks identified as 'extra extra large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XXLARGE_BLOCK_SIZE #define MEMORY_MANAGER_XXLARGE_BLOCK_SIZE 3444 #endif // <o> MEMORY_MANAGER_XSMALL_BLOCK_COUNT - Size of each memory blocks identified as 'extra small' block. <0-255> #ifndef MEMORY_MANAGER_XSMALL_BLOCK_COUNT #define MEMORY_MANAGER_XSMALL_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XSMALL_BLOCK_SIZE - Size of each memory blocks identified as 'extra small' block. // <i> Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XSMALL_BLOCK_SIZE #define MEMORY_MANAGER_XSMALL_BLOCK_SIZE 64 #endif // <o> MEMORY_MANAGER_XXSMALL_BLOCK_COUNT - Size of each memory blocks identified as 'extra extra small' block. <0-255> #ifndef MEMORY_MANAGER_XXSMALL_BLOCK_COUNT #define MEMORY_MANAGER_XXSMALL_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XXSMALL_BLOCK_SIZE - Size of each memory blocks identified as 'extra extra small' block. // <i> Size of each memory blocks identified as 'extra extra small' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XXSMALL_BLOCK_SIZE #define MEMORY_MANAGER_XXSMALL_BLOCK_SIZE 32 #endif // <q> MEM_MANAGER_ENABLE_LOGS - Enable debug trace in the module. #ifndef MEM_MANAGER_ENABLE_LOGS #define MEM_MANAGER_ENABLE_LOGS 0 #endif // <q> MEM_MANAGER_DISABLE_API_PARAM_CHECK - Disable API parameter checks in the module. #ifndef MEM_MANAGER_DISABLE_API_PARAM_CHECK #define MEM_MANAGER_DISABLE_API_PARAM_CHECK 0 #endif #endif //MEM_MANAGER_ENABLED // </e> // <e> NRF_CSENSE_ENABLED - nrf_csense - Capacitive sensor module //========================================================== #ifndef NRF_CSENSE_ENABLED #define NRF_CSENSE_ENABLED 0 #endif #if NRF_CSENSE_ENABLED // <o> NRF_CSENSE_PAD_HYSTERESIS - Minimum value of change required to determine that a pad was touched. #ifndef NRF_CSENSE_PAD_HYSTERESIS #define NRF_CSENSE_PAD_HYSTERESIS 15 #endif // <o> NRF_CSENSE_PAD_DEVIATION - Minimum value measured on a pad required to take it into account while calculating the step. #ifndef NRF_CSENSE_PAD_DEVIATION #define NRF_CSENSE_PAD_DEVIATION 70 #endif // <o> NRF_CSENSE_MIN_PAD_VALUE - Minimum normalized value on a pad required to take its value into account. #ifndef NRF_CSENSE_MIN_PAD_VALUE #define NRF_CSENSE_MIN_PAD_VALUE 20 #endif // <o> NRF_CSENSE_MAX_PADS_NUMBER - Maximum number of pads used for one instance. #ifndef NRF_CSENSE_MAX_PADS_NUMBER #define NRF_CSENSE_MAX_PADS_NUMBER 20 #endif // <o> NRF_CSENSE_MAX_VALUE - Maximum normalized value obtained from measurement. #ifndef NRF_CSENSE_MAX_VALUE #define NRF_CSENSE_MAX_VALUE 1000 #endif // <o> NRF_CSENSE_OUTPUT_PIN - Output pin used by the low-level module. // <i> This is used when capacitive sensor does not use COMP. #ifndef NRF_CSENSE_OUTPUT_PIN #define NRF_CSENSE_OUTPUT_PIN 26 #endif #endif //NRF_CSENSE_ENABLED // </e> // <e> NRF_DRV_CSENSE_ENABLED - nrf_drv_csense - Capacitive sensor low-level module //========================================================== #ifndef NRF_DRV_CSENSE_ENABLED #define NRF_DRV_CSENSE_ENABLED 0 #endif #if NRF_DRV_CSENSE_ENABLED // <e> USE_COMP - Use the comparator to implement the capacitive sensor driver. // <i> Due to Anomaly 84, COMP I_SOURCE is not functional. It has too high a varation. //========================================================== #ifndef USE_COMP #define USE_COMP 0 #endif #if USE_COMP // <o> TIMER0_FOR_CSENSE - First TIMER instance used by the driver (not used on nRF51). #ifndef TIMER0_FOR_CSENSE #define TIMER0_FOR_CSENSE 1 #endif // <o> TIMER1_FOR_CSENSE - Second TIMER instance used by the driver (not used on nRF51). #ifndef TIMER1_FOR_CSENSE #define TIMER1_FOR_CSENSE 2 #endif // <o> MEASUREMENT_PERIOD - Single measurement period. // <i> Time of a single measurement can be calculated as // <i> T = (1/2)*MEASUREMENT_PERIOD*(1/f_OSC) where f_OSC = I_SOURCE / (2C*(VUP-VDOWN) ). // <i> I_SOURCE, VUP, and VDOWN are values used to initialize COMP and C is the capacitance of the used pad. #ifndef MEASUREMENT_PERIOD #define MEASUREMENT_PERIOD 20 #endif #endif //USE_COMP // </e> #endif //NRF_DRV_CSENSE_ENABLED // </e> // <q> NRF_QUEUE_ENABLED - nrf_queue - Queue module #ifndef NRF_QUEUE_ENABLED #define NRF_QUEUE_ENABLED 0 #endif // <q> NRF_STRERROR_ENABLED - nrf_strerror - Library for converting error code to string. #ifndef NRF_STRERROR_ENABLED #define NRF_STRERROR_ENABLED 1 #endif // <q> SLIP_ENABLED - slip - SLIP encoding and decoding #ifndef SLIP_ENABLED #define SLIP_ENABLED 0 #endif // <h> app_usbd_cdc_acm - USB CDC ACM class //========================================================== // <q> APP_USBD_CLASS_CDC_ACM_ENABLED - Enabling USBD CDC ACM Class library #ifndef APP_USBD_CLASS_CDC_ACM_ENABLED #define APP_USBD_CLASS_CDC_ACM_ENABLED 0 #endif // <q> APP_USBD_CDC_ACM_LOG_ENABLED - Enables logging in the module. #ifndef APP_USBD_CDC_ACM_LOG_ENABLED #define APP_USBD_CDC_ACM_LOG_ENABLED 0 #endif // </h> //========================================================== // <h> app_usbd_msc - USB MSC class //========================================================== // <q> APP_USBD_CLASS_MSC_ENABLED - Enabling USBD MSC Class library #ifndef APP_USBD_CLASS_MSC_ENABLED #define APP_USBD_CLASS_MSC_ENABLED 0 #endif // <q> APP_USBD_MSC_CLASS_LOG_ENABLED - Enables logging in the module. #ifndef APP_USBD_MSC_CLASS_LOG_ENABLED #define APP_USBD_MSC_CLASS_LOG_ENABLED 0 #endif // </h> //========================================================== // </h> //========================================================== // <h> nRF_Log //========================================================== // <e> NRF_LOG_ENABLED - nrf_log - Logging //========================================================== #ifndef NRF_LOG_ENABLED #define NRF_LOG_ENABLED 1 #endif #if NRF_LOG_ENABLED // <e> NRF_LOG_USES_COLORS - If enabled then ANSI escape code for colors is prefixed to every string //========================================================== #ifndef NRF_LOG_USES_COLORS #define NRF_LOG_USES_COLORS 0 #endif #if NRF_LOG_USES_COLORS // <o> NRF_LOG_COLOR_DEFAULT - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef NRF_LOG_COLOR_DEFAULT #define NRF_LOG_COLOR_DEFAULT 0 #endif // <o> NRF_LOG_ERROR_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef NRF_LOG_ERROR_COLOR #define NRF_LOG_ERROR_COLOR 0 #endif // <o> NRF_LOG_WARNING_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef NRF_LOG_WARNING_COLOR #define NRF_LOG_WARNING_COLOR 0 #endif #endif //NRF_LOG_USES_COLORS // </e> // <o> NRF_LOG_DEFAULT_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef NRF_LOG_DEFAULT_LEVEL #define NRF_LOG_DEFAULT_LEVEL 3 #endif // <e> NRF_LOG_DEFERRED - Enable deffered logger. // <i> Log data is buffered and can be processed in idle. //========================================================== #ifndef NRF_LOG_DEFERRED #define NRF_LOG_DEFERRED 1 #endif #if NRF_LOG_DEFERRED // <o> NRF_LOG_DEFERRED_BUFSIZE - Size of the buffer for logs in words. // <i> Must be power of 2 #ifndef NRF_LOG_DEFERRED_BUFSIZE #define NRF_LOG_DEFERRED_BUFSIZE 256 #endif #endif //NRF_LOG_DEFERRED // </e> // <q> NRF_LOG_USES_TIMESTAMP - Enable timestamping // <i> Function for getting the timestamp is provided by the user #ifndef NRF_LOG_USES_TIMESTAMP #define NRF_LOG_USES_TIMESTAMP 0 #endif #endif //NRF_LOG_ENABLED // </e> // <h> nrf_log_backend - Logging sink //========================================================== // <o> NRF_LOG_BACKEND_MAX_STRING_LENGTH - Buffer for storing single output string // <i> Logger backend RAM usage is determined by this value. #ifndef NRF_LOG_BACKEND_MAX_STRING_LENGTH #define NRF_LOG_BACKEND_MAX_STRING_LENGTH 256 #endif // <o> NRF_LOG_TIMESTAMP_DIGITS - Number of digits for timestamp // <i> If higher resolution timestamp source is used it might be needed to increase that #ifndef NRF_LOG_TIMESTAMP_DIGITS #define NRF_LOG_TIMESTAMP_DIGITS 8 #endif // <e> NRF_LOG_BACKEND_SERIAL_USES_UART - If enabled data is printed over UART //========================================================== #ifndef NRF_LOG_BACKEND_SERIAL_USES_UART #define NRF_LOG_BACKEND_SERIAL_USES_UART 1 #endif #if NRF_LOG_BACKEND_SERIAL_USES_UART // <o> NRF_LOG_BACKEND_SERIAL_UART_BAUDRATE - Default Baudrate // <323584=> 1200 baud // <643072=> 2400 baud // <1290240=> 4800 baud // <2576384=> 9600 baud // <3862528=> 14400 baud // <5152768=> 19200 baud // <7716864=> 28800 baud // <10289152=> 38400 baud // <15400960=> 57600 baud // <20615168=> 76800 baud // <30801920=> 115200 baud // <61865984=> 230400 baud // <67108864=> 250000 baud // <121634816=> 460800 baud // <251658240=> 921600 baud // <268435456=> 57600 baud #ifndef NRF_LOG_BACKEND_SERIAL_UART_BAUDRATE #define NRF_LOG_BACKEND_SERIAL_UART_BAUDRATE 30801920 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_TX_PIN - UART TX pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_TX_PIN #define NRF_LOG_BACKEND_SERIAL_UART_TX_PIN 6 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_RX_PIN - UART RX pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_RX_PIN #define NRF_LOG_BACKEND_SERIAL_UART_RX_PIN 8 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_RTS_PIN - UART RTS pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_RTS_PIN #define NRF_LOG_BACKEND_SERIAL_UART_RTS_PIN 5 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_CTS_PIN - UART CTS pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_CTS_PIN #define NRF_LOG_BACKEND_SERIAL_UART_CTS_PIN 7 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_FLOW_CONTROL - Hardware Flow Control // <0=> Disabled // <1=> Enabled #ifndef NRF_LOG_BACKEND_SERIAL_UART_FLOW_CONTROL #define NRF_LOG_BACKEND_SERIAL_UART_FLOW_CONTROL 0 #endif // <o> NRF_LOG_BACKEND_UART_INSTANCE - UART instance used // <0=> 0 #ifndef NRF_LOG_BACKEND_UART_INSTANCE #define NRF_LOG_BACKEND_UART_INSTANCE 0 #endif #endif //NRF_LOG_BACKEND_SERIAL_USES_UART // </e> // <e> NRF_LOG_BACKEND_SERIAL_USES_RTT - If enabled data is printed using RTT //========================================================== #ifndef NRF_LOG_BACKEND_SERIAL_USES_RTT #define NRF_LOG_BACKEND_SERIAL_USES_RTT 0 #endif #if NRF_LOG_BACKEND_SERIAL_USES_RTT // <o> NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE - RTT output buffer size. // <i> Should be equal or bigger than \ref NRF_LOG_BACKEND_MAX_STRING_LENGTH. // <i> This value is used in Segger RTT configuration to set the buffer size // <i> if it is bigger than default RTT buffer size. #ifndef NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE #define NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE 512 #endif #endif //NRF_LOG_BACKEND_SERIAL_USES_RTT // </e> // </h> //========================================================== // </h> //========================================================== // <h> nRF_Segger_RTT //========================================================== // <h> segger_rtt - SEGGER RTT //========================================================== // <o> SEGGER_RTT_CONFIG_BUFFER_SIZE_UP - Size of upstream buffer. // <i> Note that either @ref NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE // <i> or this value is actually used. It depends on which one is bigger. #ifndef SEGGER_RTT_CONFIG_BUFFER_SIZE_UP #define SEGGER_RTT_CONFIG_BUFFER_SIZE_UP 64 #endif // <o> SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS - Size of upstream buffer. #ifndef SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS #define SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS 2 #endif // <o> SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN - Size of upstream buffer. #ifndef SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN #define SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN 16 #endif // <o> SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS - Size of upstream buffer. #ifndef SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS #define SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS 2 #endif // <o> SEGGER_RTT_CONFIG_DEFAULT_MODE - RTT behavior if the buffer is full. // <i> The following modes are supported: // <i> - SKIP - Do not block, output nothing. // <i> - TRIM - Do not block, output as much as fits. // <i> - BLOCK - Wait until there is space in the buffer. // <0=> SKIP // <1=> TRIM // <2=> BLOCK_IF_FIFO_FULL #ifndef SEGGER_RTT_CONFIG_DEFAULT_MODE #define SEGGER_RTT_CONFIG_DEFAULT_MODE 0 #endif // </h> //========================================================== // </h> //========================================================== // <<< end of configuration section >>> #endif //SDK_CONFIG_H
jogosa/flip_dot_clock_fw301
MODIFIED_SDK_13.0.0_04a0bfd/examples/ble_central_and_peripheral/experimental/ble_app_att_mtu_throughput/pca10040/s132/config/sdk_config.h
C
gpl-3.0
88,630
<?php namespace spf\swoole\worker; interface IWebSocketWorker { public function onStart($server, $workerId); public function onShutdown($server, $workerId); public function onTask($server, $taskId, $fromId, $data); public function onFinish($server, $taskId, $data); public function onOpen($server, $request); public function onClose(); public function onMessage($server, $frame); }
zhangjunlei26/spf
vendor/spf/swoole/worker/IWebSocketWorker.php
PHP
gpl-3.0
419
// // UDPConnection.hpp for server in /home/galibe_s/rendu/Spider/server/core // // Made by stephane galibert // Login <[email protected]> // // Started on Sun Nov 6 17:00:50 2016 stephane galibert // Last update Thu Nov 10 12:34:21 2016 stephane galibert // #pragma once #include <iostream> #include <string> #include <queue> #include <memory> #include <boost/bind.hpp> #include "AConnection.hpp" class ConnectionManager; class UDPConnection : public AConnection { public: UDPConnection(boost::asio::io_service &io_service, RequestHandler &reqHandler, PluginManager &pluginManager, ConnectionManager &cm, ServerConfig &config, int port); virtual ~UDPConnection(void); virtual void start(void); virtual void write(Packet *packet); virtual void addLog(std::string const& toadd); virtual void connectDB(void); virtual void disconnectDB(void); virtual void broadcast(std::string const& msg); virtual void kill(void); protected: virtual void do_write(boost::system::error_code const& ec, size_t len); virtual void do_read(boost::system::error_code const& ec, size_t len); virtual void do_handshake(boost::system::error_code const& ec); void write(void); void read(void); boost::asio::ip::udp::socket _socket; boost::asio::ip::udp::endpoint _endpoint; boost::asio::streambuf _read; std::queue<Packet *> _toWrites; };
Stephouuu/Spider
server/core/UDPConnection.hpp
C++
gpl-3.0
1,378
#pagefrog-big-logo { width: 200px; margin-top:20px; } #pagefrog-settings-container { padding:15px; margin-right:20px; } #pagefrog-settings-box, .white-settings-box { background: white; border-color: #ddd; border-width: 1px; border-style: solid; border-radius: 5px; } #pagefrog-logo-button > span { color:#aaa; } .pagefrog-font-selector { width:80%; } .row { margin-left: -15px; margin-right: -15px; display:block; } @media (min-width: 400px) { .col-xs-8 { width: 60.66666667%; } .col-xs-4 { width: 34.33333333%; } .col-xs-10 { width: 83.66666667%; } .col-xs-12 { width: 100%; } .col-xs-1 { width: 8.33333333%; } .col-xs-2 { width: 16.5%; } .col-xs-3 { width: 25%; } .col-xs-6 { width: 50%; } .col-xs-8, .col-xs-4, .col-xs-12, .col-xs-1, .col-xs-3, .col-xs-6 { float:left; } } @media (min-width: 768px) { .col-sm-8 { width: 60.66666667%; } .col-sm-4 { width: 34.33333333%; } .col-sm-10 { width: 83.66666667%; } .col-sm-12 { width: 100%; } .col-sm-1 { width: 8.33333333%; } .col-sm-2 { width: 16.5%; } .col-sm-3 { width: 25%; } .col-sm-6 { width: 50%; } .col-sm-7 { width: 58.33333333%; } .col-sm-9 { width: 75%; } .col-sm-8, .col-sm-4, .col-sm-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-6, .col-sm-7, .col-sm-9 { float:left; } } .col-sm-8, .col-sm-10, .col-sm-4, .col-sm-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-6, .col-sm-7, .col-sm-9 { min-height: 1px; position: relative; padding-left: 15px; padding-right: 15px; } .nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover { cursor: default; background-color: #fff; border: 1px solid #ddd; border-bottom-color: transparent; box-shadow: none; -webkit-box-shadow: none; } .nav-tabs>li>a { margin-right: 2px; line-height: 1.42857143; border: 1px solid transparent; border-radius: 4px 4px 0 0; text-decoration: none; color: #555; } .nav>li>a { position: relative; display: block; padding: 10px 15px; border: 1px solid #ddd; } .nav-tabs>li { float: left; margin-bottom: -1px; } .nav>li { position: relative; display: block; top: 0px; z-index: 99; } .nav { padding-left: 0; margin-bottom: 0; list-style: none; } .tab-content>.tab-pane { display: none; } .tab-content>.active { display: block; } .padding-container { padding-left:15px; padding-right:15px; } .input-group { position: relative; display: table; border-collapse: separate; } .input-group .form-control:first-child { border-bottom-right-radius: 0; border-top-right-radius: 0; } .input-group .form-control { position: relative; z-index: 2; float: left; width:100%; margin-bottom: 0px; } .input-group-button, .input-group .form-control { display: table-cell; } .input-group-button { position: relative; font-size: 0; white-space: nowrap; width: 1%; white-space: nowrap; vertical-align: middle; } .input-group-button > .button { height:35px; border-top-left-radius: 0; border-bottom-left-radius: 0; } textarea.form-control { height:auto; } .form-control { display: block; width: 100%; height: 36px; padding: 7px 12px; font-size: 13px; line-height: 1.5384616; color: #333; background-color: #fff; background-image: none; border: 1px solid #ddd; border-radius: 3px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } .margin-top-bottom { margin-top: 9px; margin-bottom: 10px; } .margin-top { margin-top: 10px; } .margin-bottom { margin-bottom: 10px; } .big-margin-bottom { margin-bottom: 50px; } .small-margin-top { margin-top:5px; } .no-margin { margin:0; } :after, :before, * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing:border-box; } .row:before, .row:after { display: table; content: " "; clear:both; } .colorpicker-container { float:right; } .smaller-text { font-size: 10px; } .wide-selector { width:100%; } .pagefrog-rules .with-border { border: 1px solid #ddd; border-radius: 10px; border-top-right-radius: 0px; border-top-left-radius: 0px; padding-left:10px; padding-right:10px; } .pagefrog-rules-explanation ul { list-style: disc outside none; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px; -webkit-padding-start: 40px; } #pagefrog-preview-format { margin-bottom: 0px; line-height: 0.5em; } .pagefrog-preview-phone-frame-wrapper { width:100%; display:inline-block; position: relative; max-width: 300px; text-align: initial; } .pagefrog-preview-phone-frame-wrapper:after { padding-top: 180%; /* aspect ratio of phone: (627px + phone frame top padding + phone frame bottom padding) / (375px + phone frame left padding + phone frame right padding) (627 + 35 + 50) / 375 + 10 + 10) = 180% */ display:block; content: ''; } .pagefrog-preview-phone-frame { position: absolute; top: 0; bottom: 0; right: 0; left: 0; border: 1px solid #e5e5e5; border-radius: 40px; padding-top:50px; padding-bottom: 35px; padding-left: 10px; padding-right: 10px; background: #f1f1f1; } .pagefrog-preview-container { height: 97.7%; position: relative; width: 100%; border: 1px solid #e5e5e5; overflow: hidden; } .pagefrog-preview-container > iframe { height: 100%; width: 100%; background-color: black; transform: scale(1, 1); /* this should be updated on the preview setup in the javascript */ transform-origin: top left; } .wide-selector { width:100%; } .pull-right { float:right; } h3 .button { position: relative; top:-5px; } .button.block { width:100%; text-align: center; } .well { min-height: 20px; padding:19px; background-color: #f5f5f5; border: 1px solid #e3e3e3; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05); box-shadow: inset 0 1px 1px rgba(0,0,0,.05); } .fullwidth { width: 100%; } .logo-max-width { max-width: 100px; margin:auto; display: block; } .button.button-lg { padding-left:20px; padding-right: 20px; padding-top: 10px; padding-bottom: 10px; display: inline; font-size: 20px; height:auto; } .button.yellow, .button.yellow:focus { background-color: #ffba00; border-color: #ffba00; color: white; box-shadow: 0 1px 0 #edb20f; } .button.yellow:hover { background-color: #E0A500; border-color: #E0A500; color:white; } .button.pink, .button.pink:focus { background-color: #f289b1; border-color: #f289b1; color: white; } .button.pink:hover { background-color: #ea6ca0; border-color: #ea6ca0; color:white; } .button.blackoutline, .button.blackoutline:disabled { background-color: #ffffff!important; border-color: #494949!important; color: #494949!important; } .button.greenoutline, .button.greenoutline:disabled { background-color: #ffffff!important; border-color: #44bb66!important; color: #44bb66!important; } .button.green, .button.green:focus { background-color: #44bb66; border-color: #44bb66; color: white; } .button.green:hover { background-color: #3fad5e; border-color: #3fad5e; color:white; } .button.green:active { background-color: #3a9e56; border-color: #3a9e56; color:white; } .button.blue, .button.blue:focus { background-color: #527dbf; border-color: #527dbf; color: white; } .button.blue:hover { background-color: #416498; border-color: #416498; color: white; } .text-center { text-align: center; } .green-text { color: #44bb66; } .circled.green { color:#3fad5e; border-color:#3fad5e; } .circled { height: 40px; width: 40px; -moz-border-radius: 50%; border-radius: 50%; font-size: 30px; border-width: 2px; border-style: solid; padding-top: 4px; padding-right: 4px; display: inline-block; } .pagefrog-status-toggle:disabled, label.disabled { cursor: not-allowed; } .alert { padding:10px; border-color:#eee; border-width: 1px; border-style: solid; border-left-width: 4px; } .alert.yellow { border-left-color: #ffba00; } .alert.green { border-left-color: #44bb66; } .alert.red { border-left-color: #ff4542; } .required { color:#888; font-size: 10px; } .pagefrog-status-circle { margin-left: 14px; margin-top: 5px; height: 15px; width: 15px; background-color: #a1a1a1; display: inline-block; border-radius: 10px; overflow: hidden; cursor: pointer; } .pagefrog-status-circle.small { height:10px; width:10px; } .pagefrog-status-circle-inner { width: 100%; height:100%; display: block; border-radius: 10px; } .pagefrog-status-circle-inner.empty { width:0; } .pagefrog-status-circle-inner.half { width: 50%; border-radius: 0px; border-color: white; } .pagefrog-status-circle-inner.green { background-color: #44bb66; } .pagefrog-status-circle-inner.yellow { background-color: #ffba00; } .pagefrog-status-circle-inner.grey { background-color: #aaa; } .hover-cursor { cursor: pointer; } .grey-background { background-color: #f1f1f1; } .grey-bottom-border { border-bottom-color: #dddddd; border-bottom-style: solid; border-bottom-width: 2px; } .padding-box { padding:20px; padding-bottom: 0px; } #pagefrog-settings-box table.form-table { display:none; } .alert.error-box p { margin-top:0; margin-bottom:0; } .alert.error-box { position: relative; top:29px; padding-bottom: 5px; padding-top: 5px; } .fb-like { transform: scale(1.4); -ms-transform: scale(1.4); -webkit-transform: scale(1.4); -o-transform: scale(1.4); -moz-transform: scale(1.4); } .fb_iframe_widget { height: 60px; }
rolandinsh/smcmobilewp
admin/css/pagefrog-admin.css
CSS
gpl-3.0
10,626
<?php /* * Central de conhecimento FEJESP * Contato: [email protected] * Autor: Guilherme de Oliveira Souza (http://sitegui.com.br) * Data: 07/08/2013 */ // Retorna a árvore inicial para um dado caminho $caminho = @$_GET['caminho']; $pastas = preg_split('@/@', $caminho, -1, PREG_SPLIT_NO_EMPTY); $arvore = array('' => NULL); $nivelAtual = &$arvore['']; $pai = 0; for ($i=0; $i<count($pastas); $i++) { // Carrega cada nível da árvore, a partir da raiz $nivelAtual = array(); $subpastas = Query::query(false, NULL, 'SELECT id, nome, visibilidade, criador FROM pastas WHERE pai=? AND id!=0 ORDER BY nome', $pai); $achou = false; foreach ($subpastas as $dados) if (verificarVisibilidade('pasta', $dados['id'], $dados['visibilidade'], $dados['criador'])) { $nivelAtual[$dados['nome']] = NULL; if ($dados['nome'] == $pastas[$i]) { $achou = true; $pai = $dados['id']; } } // Verifica se a pasta está no caminho if (!$achou) retornarErro(); $nivelAtual = &$nivelAtual[$pastas[$i]]; } retornar($arvore);
fejesp/centralConhecimento
ajax/getArvoreInicial.php
PHP
gpl-3.0
1,039
<?php namespace Test\Deserializer; use Test\Serializer\EntityNode\Vehicle; class VehicleChecker { public function acceptAndReturnVehicle(Vehicle $vehicle) { return $vehicle; } }
barryosull/valueobjects
test/Deserializer/VehicleChecker.php
PHP
gpl-3.0
199
function print_last_modif_date(v) { document.write("Last updated " + v.substr(7, 19)); }
francois-a/fastqtl
doc/script/print_last_modif_date.js
JavaScript
gpl-3.0
89
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.common; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.Pair; /** * A wrapper that exposes a read-only {@link Map} access to the system * properties. Any attempt to modify it will throw {@link UnsupportedOperationException}. * The mapper uses the {@link #SYSPROPS_MAPPED_PREFIX} to filter and access' * only these properties, ignoring all others * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public final class SyspropsMapWrapper implements Map<String, Object> { /** * Prefix of properties used by the mapper to identify SSHD related settings */ public static final String SYSPROPS_MAPPED_PREFIX = "org.apache.sshd.config"; /** * The one and only wrapper instance */ public static final SyspropsMapWrapper INSTANCE = new SyspropsMapWrapper(); /** * A {@link PropertyResolver} with no parent that exposes the system properties */ public static final PropertyResolver SYSPROPS_RESOLVER = new PropertyResolver() { @Override public Map<String, Object> getProperties() { return SyspropsMapWrapper.INSTANCE; } @Override public PropertyResolver getParentPropertyResolver() { return null; } @Override public String toString() { return "SYSPROPS"; } }; private SyspropsMapWrapper() { super(); } @Override public void clear() { throw new UnsupportedOperationException("sysprops#clear() N/A"); } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { // not the most efficient implementation, but we do not expect it to be called much Properties props = System.getProperties(); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (Objects.equals(v, value)) { return true; } } return false; } @Override public Set<Entry<String, Object>> entrySet() { Properties props = System.getProperties(); // return a copy in order to avoid concurrent modifications Set<Entry<String, Object>> entries = new TreeSet<Entry<String, Object>>(Pair.<String, Object>byKeyEntryComparator()); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (v != null) { entries.add(new Pair<>(getUnmappedSyspropKey(key), v)); } } return entries; } @Override public Object get(Object key) { return (key instanceof String) ? System.getProperty(getMappedSyspropKey(key)) : null; } @Override public boolean isEmpty() { return GenericUtils.isEmpty(keySet()); } @Override public Set<String> keySet() { Properties props = System.getProperties(); Set<String> keys = new TreeSet<>(); // filter out any non-SSHD properties for (String key : props.stringPropertyNames()) { if (isMappedSyspropKey(key)) { keys.add(getUnmappedSyspropKey(key)); } } return keys; } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("sysprops#put(" + key + ")[" + value + "] N/A"); } @Override public void putAll(Map<? extends String, ? extends Object> m) { throw new UnsupportedOperationException("sysprops#putAll(" + m + ") N/A"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("sysprops#remove(" + key + ") N/A"); } @Override public int size() { return GenericUtils.size(keySet()); } @Override public Collection<Object> values() { Properties props = System.getProperties(); // return a copy in order to avoid concurrent modifications List<Object> values = new ArrayList<>(props.size()); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (v != null) { values.add(v); } } return values; } @Override public String toString() { return Objects.toString(System.getProperties(), null); } /** * @param key Key to be tested * @return {@code true} if key starts with {@link #SYSPROPS_MAPPED_PREFIX} * and continues with a dot followed by some characters */ public static boolean isMappedSyspropKey(String key) { return (GenericUtils.length(key) > (SYSPROPS_MAPPED_PREFIX.length() + 1)) && key.startsWith(SYSPROPS_MAPPED_PREFIX) && (key.charAt(SYSPROPS_MAPPED_PREFIX.length()) == '.'); } /** * @param key Key to be transformed * @return The &quot;pure&quot; key name if a mapped one, same as input otherwise * @see #isMappedSyspropKey(String) */ public static String getUnmappedSyspropKey(Object key) { String s = Objects.toString(key); return isMappedSyspropKey(s) ? s.substring(SYSPROPS_MAPPED_PREFIX.length() + 1 /* skip dot */) : s; } /** * @param key The original key * @return A key prefixed by {@link #SYSPROPS_MAPPED_PREFIX} * @see #isMappedSyspropKey(String) */ public static String getMappedSyspropKey(Object key) { return SYSPROPS_MAPPED_PREFIX + "." + key; } }
Niky4000/UsefulUtils
projects/ssh/apache_mina/apache-sshd-1.2.0/sshd-core/src/main/java/org/apache/sshd/common/SyspropsMapWrapper.java
Java
gpl-3.0
6,908
package com.baeldung.jhipster5.web.rest; import com.baeldung.jhipster5.BookstoreApp; import com.baeldung.jhipster5.config.Constants; import com.baeldung.jhipster5.domain.Authority; import com.baeldung.jhipster5.domain.User; import com.baeldung.jhipster5.repository.AuthorityRepository; import com.baeldung.jhipster5.repository.UserRepository; import com.baeldung.jhipster5.security.AuthoritiesConstants; import com.baeldung.jhipster5.service.MailService; import com.baeldung.jhipster5.service.UserService; import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; import com.baeldung.jhipster5.service.dto.UserDTO; import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the AccountResource REST controller. * * @see AccountResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) public class AccountResourceIntTest { @Autowired private UserRepository userRepository; @Autowired private AuthorityRepository authorityRepository; @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private HttpMessageConverter<?>[] httpMessageConverters; @Autowired private ExceptionTranslator exceptionTranslator; @Mock private UserService mockUserService; @Mock private MailService mockMailService; private MockMvc restMvc; private MockMvc restUserMockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService); this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) .setMessageConverters(httpMessageConverters) .setControllerAdvice(exceptionTranslator) .build(); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) .setControllerAdvice(exceptionTranslator) .build(); } @Test public void testNonAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); } @Test public void testAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser("test"); return request; }) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("test")); } @Test public void testGetExistingAccount() throws Exception { Set<Authority> authorities = new HashSet<>(); Authority authority = new Authority(); authority.setName(AuthoritiesConstants.ADMIN); authorities.add(authority); User user = new User(); user.setLogin("test"); user.setFirstName("john"); user.setLastName("doe"); user.setEmail("[email protected]"); user.setImageUrl("http://placehold.it/50x50"); user.setLangKey("en"); user.setAuthorities(authorities); when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.login").value("test")) .andExpect(jsonPath("$.firstName").value("john")) .andExpect(jsonPath("$.lastName").value("doe")) .andExpect(jsonPath("$.email").value("[email protected]")) .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) .andExpect(jsonPath("$.langKey").value("en")) .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); } @Test public void testGetUnknownAccount() throws Exception { when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isInternalServerError()); } @Test @Transactional public void testRegisterValid() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("test-register-valid"); validUser.setPassword("password"); validUser.setFirstName("Alice"); validUser.setLastName("Test"); validUser.setEmail("[email protected]"); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); } @Test @Transactional public void testRegisterInvalidLogin() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("funky-log!n");// <-- invalid invalidUser.setPassword("password"); invalidUser.setFirstName("Funky"); invalidUser.setLastName("One"); invalidUser.setEmail("[email protected]"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByEmailIgnoreCase("[email protected]"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidEmail() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("password"); invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("invalid");// <-- invalid invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("123");// password with only 3 digits invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("[email protected]"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterNullPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword(null);// invalid null password invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("[email protected]"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterDuplicateLogin() throws Exception { // First registration ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("alice"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Something"); firstUser.setEmail("[email protected]"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Duplicate login, different email ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin(firstUser.getLogin()); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail("[email protected]"); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setCreatedBy(firstUser.getCreatedBy()); secondUser.setCreatedDate(firstUser.getCreatedDate()); secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // First user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); // Second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("[email protected]"); assertThat(testUser.isPresent()).isTrue(); testUser.get().setActivated(true); userRepository.save(testUser.get()); // Second (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterDuplicateEmail() throws Exception { // First user ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("test-register-duplicate-email"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Test"); firstUser.setEmail("[email protected]"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Register first user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser1.isPresent()).isTrue(); // Duplicate email, different login ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin("test-register-duplicate-email-2"); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail(firstUser.getEmail()); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser2.isPresent()).isFalse(); Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); assertThat(testUser3.isPresent()).isTrue(); // Duplicate email - with uppercase email address ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); userWithUpperCaseEmail.setId(firstUser.getId()); userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); userWithUpperCaseEmail.setPassword(firstUser.getPassword()); userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); userWithUpperCaseEmail.setLastName(firstUser.getLastName()); userWithUpperCaseEmail.setEmail("[email protected]"); userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register third (not activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) .andExpect(status().isCreated()); Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); assertThat(testUser4.isPresent()).isTrue(); assertThat(testUser4.get().getEmail()).isEqualTo("[email protected]"); testUser4.get().setActivated(true); userService.updateUser((new UserDTO(testUser4.get()))); // Register 4th (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterAdminIsIgnored() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("badguy"); validUser.setPassword("password"); validUser.setFirstName("Bad"); validUser.setLastName("Guy"); validUser.setEmail("[email protected]"); validUser.setActivated(true); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); Optional<User> userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup.isPresent()).isTrue(); assertThat(userDup.get().getAuthorities()).hasSize(1) .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @Test @Transactional public void testActivateAccount() throws Exception { final String activationKey = "some activation key"; User user = new User(); user.setLogin("activate-account"); user.setEmail("[email protected]"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(false); user.setActivationKey(activationKey); userRepository.saveAndFlush(user); restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) .andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); } @Test @Transactional public void testActivateAccountWithWrongKey() throws Exception { restMvc.perform(get("/api/activate?key=wrongActivationKey")) .andExpect(status().isInternalServerError()); } @Test @Transactional @WithMockUser("save-account") public void testSaveAccount() throws Exception { User user = new User(); user.setLogin("save-account"); user.setEmail("[email protected]"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("[email protected]"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); assertThat(updatedUser.getActivated()).isEqualTo(true); assertThat(updatedUser.getAuthorities()).isEmpty(); } @Test @Transactional @WithMockUser("save-invalid-email") public void testSaveInvalidEmail() throws Exception { User user = new User(); user.setLogin("save-invalid-email"); user.setEmail("[email protected]"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("invalid email"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @Test @Transactional @WithMockUser("save-existing-email") public void testSaveExistingEmail() throws Exception { User user = new User(); user.setLogin("save-existing-email"); user.setEmail("[email protected]"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); User anotherUser = new User(); anotherUser.setLogin("save-existing-email2"); anotherUser.setEmail("[email protected]"); anotherUser.setPassword(RandomStringUtils.random(60)); anotherUser.setActivated(true); userRepository.saveAndFlush(anotherUser); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("[email protected]"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("[email protected]"); } @Test @Transactional @WithMockUser("save-existing-email-and-login") public void testSaveExistingEmailAndLogin() throws Exception { User user = new User(); user.setLogin("save-existing-email-and-login"); user.setEmail("[email protected]"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("[email protected]"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("[email protected]"); } @Test @Transactional @WithMockUser("change-password-wrong-existing-password") public void testChangePasswordWrongExistingPassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-wrong-existing-password"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password") public void testChangePassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password-too-small") public void testChangePasswordTooSmall() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-small"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-too-long") public void testChangePasswordTooLong() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-long"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-empty") public void testChangePasswordEmpty() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-empty"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional public void testRequestPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("[email protected]")) .andExpect(status().isOk()); } @Test @Transactional public void testRequestPasswordResetUpperCaseEmail() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("[email protected]"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("[email protected]")) .andExpect(status().isOk()); } @Test public void testRequestPasswordResetWrongEmail() throws Exception { restMvc.perform( post("/api/account/reset-password/init") .content("[email protected]")) .andExpect(status().isBadRequest()); } @Test @Transactional public void testFinishPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset"); user.setEmail("[email protected]"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); } @Test @Transactional public void testFinishPasswordResetTooSmall() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset-too-small"); user.setEmail("[email protected]"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key too small"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("foo"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); } @Test @Transactional public void testFinishPasswordResetWrongKey() throws Exception { KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey("wrong reset key"); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isInternalServerError()); } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java
Java
gpl-3.0
34,406
import { defineMessages } from 'react-intl'; export default defineMessages({ save: { id: 'cboard.components.FormDialog.save', defaultMessage: 'Save' }, cancel: { id: 'cboard.components.FormDialog.cancel', defaultMessage: 'Cancel' } });
shayc/cboard
src/components/UI/FormDialog/FormDialog.messages.js
JavaScript
gpl-3.0
261
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines various restore steps that will be used by common tasks in restore * * @package core_backup * @subpackage moodle2 * @category backup * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * delete old directories and conditionally create backup_temp_ids table */ class restore_create_and_clean_temp_stuff extends restore_execution_step { protected function define_execution() { $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally // If the table already exists, it's because restore_prechecks have been executed in the same // request (without problems) and it already contains a bunch of preloaded information (users...) // that we aren't going to execute again if ($exists) { // Inform plan about preloaded information $this->task->set_preloaded_information(); } // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_contextid(); $newitemid = context_course::instance($this->get_courseid())->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_system_contextid(); $newitemid = context_system::instance()->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-course-id to new-course-id mapping, we need that available since the beginning $itemid = $this->task->get_old_courseid(); $newitemid = $this->get_courseid(); restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid); } } /** * delete the temp dir used by backup/restore (conditionally), * delete old directories and drop temp ids table */ class restore_drop_and_clean_temp_stuff extends restore_execution_step { protected function define_execution() { global $CFG; restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table $progress = $this->task->get_progress(); $progress->start_progress('Deleting backup dir'); backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress); // Delete > 1 week old temp dirs. if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir } $progress->end_progress(); } } /** * Restore calculated grade items, grade categories etc */ class restore_gradebook_structure_step extends restore_structure_step { /** * To conditionally decide if this step must be executed * Note the "settings" conditions are evaluated in the * corresponding task. Here we check for other conditions * not being restore settings (files, site settings...) */ protected function execute_condition() { global $CFG, $DB; if ($this->get_courseid() == SITEID) { return false; } // No gradebook info found, don't execute $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Some module present in backup file isn't available to restore // in this site, don't execute if ($this->task->is_missing_modules()) { return false; } // Some activity has been excluded to be restored, don't execute if ($this->task->is_excluding_activities()) { return false; } // There should only be one grade category (the 1 associated with the course itself) // If other categories already exist we're restoring into an existing course. // Restoring categories into a course with an existing category structure is unlikely to go well $category = new stdclass(); $category->courseid = $this->get_courseid(); $catcount = $DB->count_records('grade_categories', (array)$category); if ($catcount>1) { return false; } // Arrived here, execute the step return true; } protected function define_structure() { $paths = array(); $userinfo = $this->task->get_setting_value('users'); $paths[] = new restore_path_element('gradebook', '/gradebook'); $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category'); $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item'); if ($userinfo) { $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade'); } $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter'); $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting'); return $paths; } protected function process_gradebook($data) { } protected function process_grade_item($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->courseid = $this->get_courseid(); if ($data->itemtype=='manual') { // manual grade items store category id in categoryid $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL); // if mapping failed put in course's grade category if (NULL == $data->categoryid) { $coursecat = grade_category::fetch_course_category($this->get_courseid()); $data->categoryid = $coursecat->id; } } else if ($data->itemtype=='course') { // course grade item stores their category id in iteminstance $coursecat = grade_category::fetch_course_category($this->get_courseid()); $data->iteminstance = $coursecat->id; } else if ($data->itemtype=='category') { // category grade items store their category id in iteminstance $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL); } else { throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype); } $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL); $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL); $data->locktime = $this->apply_date_offset($data->locktime); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $coursecategory = $newitemid = null; //course grade item should already exist so updating instead of inserting if($data->itemtype=='course') { //get the ID of the already created grade item $gi = new stdclass(); $gi->courseid = $this->get_courseid(); $gi->itemtype = $data->itemtype; //need to get the id of the grade_category that was automatically created for the course $category = new stdclass(); $category->courseid = $this->get_courseid(); $category->parent = null; //course category fullname starts out as ? but may be edited //$category->fullname = '?'; $coursecategory = $DB->get_record('grade_categories', (array)$category); $gi->iteminstance = $coursecategory->id; $existinggradeitem = $DB->get_record('grade_items', (array)$gi); if (!empty($existinggradeitem)) { $data->id = $newitemid = $existinggradeitem->id; $DB->update_record('grade_items', $data); } } else if ($data->itemtype == 'manual') { // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists. $gi = array( 'itemtype' => $data->itemtype, 'courseid' => $data->courseid, 'itemname' => $data->itemname, 'categoryid' => $data->categoryid, ); $newitemid = $DB->get_field('grade_items', 'id', $gi); } if (empty($newitemid)) { //in case we found the course category but still need to insert the course grade item if ($data->itemtype=='course' && !empty($coursecategory)) { $data->iteminstance = $coursecategory->id; } $newitemid = $DB->insert_record('grade_items', $data); } $this->set_mapping('grade_item', $oldid, $newitemid); } protected function process_grade_grade($data) { global $DB; $data = (object)$data; $oldid = $data->id; $olduserid = $data->userid; $data->itemid = $this->get_new_parentid('grade_item'); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->locktime = $this->apply_date_offset($data->locktime); // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? $data->overridden = $this->apply_date_offset($data->overridden); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid)); if ($gradeexists) { $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } else { $newitemid = $DB->insert_record('grade_grades', $data); $this->set_mapping('grade_grades', $oldid, $newitemid); } } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } protected function process_grade_category($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->courseid = $data->course; $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $newitemid = null; //no parent means a course level grade category. That may have been created when the course was created if(empty($data->parent)) { //parent was being saved as 0 when it should be null $data->parent = null; //get the already created course level grade category $category = new stdclass(); $category->courseid = $this->get_courseid(); $category->parent = null; $coursecategory = $DB->get_record('grade_categories', (array)$category); if (!empty($coursecategory)) { $data->id = $newitemid = $coursecategory->id; $DB->update_record('grade_categories', $data); } } // Add a warning about a removed setting. if (!empty($data->aggregatesubcats)) { set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1); } //need to insert a course category if (empty($newitemid)) { $newitemid = $DB->insert_record('grade_categories', $data); } $this->set_mapping('grade_category', $oldid, $newitemid); } protected function process_grade_letter($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->contextid = context_course::instance($this->get_courseid())->id; $gradeletter = (array)$data; unset($gradeletter['id']); if (!$DB->record_exists('grade_letters', $gradeletter)) { $newitemid = $DB->insert_record('grade_letters', $data); } else { $newitemid = $data->id; } $this->set_mapping('grade_letter', $oldid, $newitemid); } protected function process_grade_setting($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->courseid = $this->get_courseid(); if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) { $newitemid = $DB->insert_record('grade_settings', $data); } else { $newitemid = $data->id; } $this->set_mapping('grade_setting', $oldid, $newitemid); } /** * put all activity grade items in the correct grade category and mark all for recalculation */ protected function after_execute() { global $DB; $conditions = array( 'backupid' => $this->get_restoreid(), 'itemname' => 'grade_item'//, //'itemid' => $itemid ); $rs = $DB->get_recordset('backup_ids_temp', $conditions); // We need this for calculation magic later on. $mappings = array(); if (!empty($rs)) { foreach($rs as $grade_item_backup) { // Store the oldid with the new id. $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid; $updateobj = new stdclass(); $updateobj->id = $grade_item_backup->newitemid; //if this is an activity grade item that needs to be put back in its correct category if (!empty($grade_item_backup->parentitemid)) { $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null); if (!is_null($oldcategoryid)) { $updateobj->categoryid = $oldcategoryid; $DB->update_record('grade_items', $updateobj); } } else { //mark course and category items as needing to be recalculated $updateobj->needsupdate=1; $DB->update_record('grade_items', $updateobj); } } } $rs->close(); // We need to update the calculations for calculated grade items that may reference old // grade item ids using ##gi\d+##. // $mappings can be empty, use 0 if so (won't match ever) list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0); $sql = "SELECT gi.id, gi.calculation FROM {grade_items} gi WHERE gi.id {$sql} AND calculation IS NOT NULL"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $gradeitem) { // Collect all of the used grade item id references if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) { // This calculation doesn't reference any other grade items... EASY! continue; } // For this next bit we are going to do the replacement of id's in two steps: // 1. We will replace all old id references with a special mapping reference. // 2. We will replace all mapping references with id's // Why do we do this? // Because there potentially there will be an overlap of ids within the query and we // we substitute the wrong id.. safest way around this is the two step system $calculationmap = array(); $mapcount = 0; foreach ($matches[1] as $match) { // Check that the old id is known to us, if not it was broken to begin with and will // continue to be broken. if (!array_key_exists($match, $mappings)) { continue; } // Our special mapping key $mapping = '##MAPPING'.$mapcount.'##'; // The old id that exists within the calculation now $oldid = '##gi'.$match.'##'; // The new id that we want to replace the old one with. $newid = '##gi'.$mappings[$match].'##'; // Replace in the special mapping key $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation); // And record the mapping $calculationmap[$mapping] = $newid; $mapcount++; } // Iterate all special mappings for this calculation and replace in the new id's foreach ($calculationmap as $mapping => $newid) { $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation); } // Update the calculation now that its being remapped $DB->update_record('grade_items', $gradeitem); } $rs->close(); // Need to correct the grade category path and parent $conditions = array( 'courseid' => $this->get_courseid() ); $rs = $DB->get_recordset('grade_categories', $conditions); // Get all the parents correct first as grade_category::build_path() loads category parents from the DB foreach ($rs as $gc) { if (!empty($gc->parent)) { $grade_category = new stdClass(); $grade_category->id = $gc->id; $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent); $DB->update_record('grade_categories', $grade_category); } } $rs->close(); // Now we can rebuild all the paths $rs = $DB->get_recordset('grade_categories', $conditions); foreach ($rs as $gc) { $grade_category = new stdClass(); $grade_category->id = $gc->id; $grade_category->path = grade_category::build_path($gc); $grade_category->depth = substr_count($grade_category->path, '/') - 1; $DB->update_record('grade_categories', $grade_category); } $rs->close(); // Restore marks items as needing update. Update everything now. grade_regrade_final_grades($this->get_courseid()); } } /** * Step in charge of restoring the grade history of a course. * * The execution conditions are itendical to {@link restore_gradebook_structure_step} because * we do not want to restore the history if the gradebook and its content has not been * restored. At least for now. */ class restore_grade_history_structure_step extends restore_structure_step { protected function execute_condition() { global $CFG, $DB; if ($this->get_courseid() == SITEID) { return false; } // No gradebook info found, don't execute. $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Some module present in backup file isn't available to restore in this site, don't execute. if ($this->task->is_missing_modules()) { return false; } // Some activity has been excluded to be restored, don't execute. if ($this->task->is_excluding_activities()) { return false; } // There should only be one grade category (the 1 associated with the course itself). $category = new stdclass(); $category->courseid = $this->get_courseid(); $catcount = $DB->count_records('grade_categories', (array)$category); if ($catcount > 1) { return false; } // Arrived here, execute the step. return true; } protected function define_structure() { $paths = array(); // Settings to use. $userinfo = $this->get_setting_value('users'); $history = $this->get_setting_value('grade_histories'); if ($userinfo && $history) { $paths[] = new restore_path_element('grade_grade', '/grade_history/grade_grades/grade_grade'); } return $paths; } protected function process_grade_grade($data) { global $DB; $data = (object)($data); $olduserid = $data->userid; unset($data->id); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { // Do not apply the date offsets as this is history. $data->itemid = $this->get_mappingid('grade_item', $data->itemid); $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); $DB->insert_record('grade_grades_history', $data); } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } } /** * decode all the interlinks present in restored content * relying 100% in the restore_decode_processor that handles * both the contents to modify and the rules to be applied */ class restore_decode_interlinks extends restore_execution_step { protected function define_execution() { // Get the decoder (from the plan) $decoder = $this->task->get_decoder(); restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules // And launch it, everything will be processed $decoder->execute(); } } /** * first, ensure that we have no gaps in section numbers * and then, rebuid the course cache */ class restore_rebuild_course_cache extends restore_execution_step { protected function define_execution() { global $DB; // Although there is some sort of auto-recovery of missing sections // present in course/formats... here we check that all the sections // from 0 to MAX(section->section) exist, creating them if necessary $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid())); // Iterate over all sections for ($i = 0; $i <= $maxsection; $i++) { // If the section $i doesn't exist, create it if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) { $sectionrec = array( 'course' => $this->get_courseid(), 'section' => $i); $DB->insert_record('course_sections', $sectionrec); // missing section created } } // Rebuild cache now that all sections are in place rebuild_course_cache($this->get_courseid()); cache_helper::purge_by_event('changesincourse'); cache_helper::purge_by_event('changesincoursecat'); } } /** * Review all the tasks having one after_restore method * executing it to perform some final adjustments of information * not available when the task was executed. */ class restore_execute_after_restore extends restore_execution_step { protected function define_execution() { // Simply call to the execute_after_restore() method of the task // that always is the restore_final_task $this->task->launch_execute_after_restore(); } } /** * Review all the (pending) block positions in backup_ids, matching by * contextid, creating positions as needed. This is executed by the * final task, once all the contexts have been created */ class restore_review_pending_block_positions extends restore_execution_step { protected function define_execution() { global $DB; // Get all the block_position objects pending to match $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); // Process block positions, creating them or accumulating for final step foreach($rs as $posrec) { // Get the complete position object out of the info field. $position = backup_controller_dbops::decode_backup_temp_info($posrec->info); // If position is for one already mapped (known) contextid // process it now, creating the position, else nothing to // do, position finally discarded if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) { $position->contextid = $newctx->newitemid; // Create the block position $DB->insert_record('block_positions', $position); } } $rs->close(); } } /** * Updates the availability data for course modules and sections. * * Runs after the restore of all course modules, sections, and grade items has * completed. This is necessary in order to update IDs that have changed during * restore. * * @package core_backup * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_update_availability extends restore_execution_step { protected function define_execution() { global $CFG, $DB; // Note: This code runs even if availability is disabled when restoring. // That will ensure that if you later turn availability on for the site, // there will be no incorrect IDs. (It doesn't take long if the restored // data does not contain any availability information.) // Get modinfo with all data after resetting cache. rebuild_course_cache($this->get_courseid(), true); $modinfo = get_fast_modinfo($this->get_courseid()); // Get the date offset for this restore. $dateoffset = $this->apply_date_offset(1) - 1; // Update all sections that were restored. $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); $sectionsbyid = null; foreach ($rs as $rec) { if (is_null($sectionsbyid)) { $sectionsbyid = array(); foreach ($modinfo->get_section_info_all() as $section) { $sectionsbyid[$section->id] = $section; } } if (!array_key_exists($rec->newitemid, $sectionsbyid)) { // If the section was not fully restored for some reason // (e.g. due to an earlier error), skip it. $this->get_logger()->process('Section not fully restored: id ' . $rec->newitemid, backup::LOG_WARNING); continue; } $section = $sectionsbyid[$rec->newitemid]; if (!is_null($section->availability)) { $info = new \core_availability\info_section($section); $info->update_after_restore($this->get_restoreid(), $this->get_courseid(), $this->get_logger(), $dateoffset); } } $rs->close(); // Update all modules that were restored. $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); foreach ($rs as $rec) { if (!array_key_exists($rec->newitemid, $modinfo->cms)) { // If the module was not fully restored for some reason // (e.g. due to an earlier error), skip it. $this->get_logger()->process('Module not fully restored: id ' . $rec->newitemid, backup::LOG_WARNING); continue; } $cm = $modinfo->get_cm($rec->newitemid); if (!is_null($cm->availability)) { $info = new \core_availability\info_module($cm); $info->update_after_restore($this->get_restoreid(), $this->get_courseid(), $this->get_logger(), $dateoffset); } } $rs->close(); } } /** * Process legacy module availability records in backup_ids. * * Matches course modules and grade item id once all them have been already restored. * Only if all matchings are satisfied the availability condition will be created. * At the same time, it is required for the site to have that functionality enabled. * * This step is included only to handle legacy backups (2.6 and before). It does not * do anything for newer backups. * * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ class restore_process_course_modules_availability extends restore_execution_step { protected function define_execution() { global $CFG, $DB; // Site hasn't availability enabled if (empty($CFG->enableavailability)) { return; } // Do both modules and sections. foreach (array('module', 'section') as $table) { // Get all the availability objects to process. $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); // Process availabilities, creating them if everything matches ok. foreach ($rs as $availrec) { $allmatchesok = true; // Get the complete legacy availability object. $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info); // Note: This code used to update IDs, but that is now handled by the // current code (after restore) instead of this legacy code. // Get showavailability option. $thingid = ($table === 'module') ? $availability->coursemoduleid : $availability->coursesectionid; $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), $table . '_showavailability', $thingid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availability object is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_' . $table . 's', 'availability', array('id' => $thingid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_condition( $currentvalue, $availability, $show); $DB->set_field('course_' . $table . 's', 'availability', $newvalue, array('id' => $thingid)); } } $rs->close(); } } /* * Execution step that, *conditionally* (if there isn't preloaded information) * will load the inforef files for all the included course/section/activity tasks * to backup_temp_ids. They will be stored with "xxxxref" as itemname */ class restore_load_included_inforef_records extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } // Get all the included tasks $tasks = restore_dbops::get_included_tasks($this->get_restoreid()); $progress = $this->task->get_progress(); $progress->start_progress($this->get_name(), count($tasks)); foreach ($tasks as $task) { // Load the inforef.xml file if exists $inforefpath = $task->get_taskbasepath() . '/inforef.xml'; if (file_exists($inforefpath)) { // Load each inforef file to temp_ids. restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress); } } $progress->end_progress(); } } /* * Execution step that will load all the needed files into backup_files_temp * - info: contains the whole original object (times, names...) * (all them being original ids as loaded from xml) */ class restore_load_included_files extends restore_structure_step { protected function define_structure() { $file = new restore_path_element('file', '/files/file'); return array($file); } /** * Process one <file> element from files.xml * * @param array $data the element data */ public function process_file($data) { $data = (object)$data; // handy // load it if needed: // - it it is one of the annotated inforef files (course/section/activity/block) // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever) // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use, // but then we'll need to change it to load plugins itself (because this is executed too early in restore) $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id); $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' || $data->component == 'grouping' || $data->component == 'grade' || $data->component == 'question' || substr($data->component, 0, 5) == 'qtype'); if ($isfileref || $iscomponent) { restore_dbops::set_backup_files_record($this->get_restoreid(), $data); } } } /** * Execution step that, *conditionally* (if there isn't preloaded information), * will load all the needed roles to backup_temp_ids. They will be stored with * "role" itemname. Also it will perform one automatic mapping to roles existing * in the target site, based in permissions of the user performing the restore, * archetypes and other bits. At the end, each original role will have its associated * target role or 0 if it's going to be skipped. Note we wrap everything over one * restore_dbops method, as far as the same stuff is going to be also executed * by restore prechecks */ class restore_load_and_map_roles extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded return; } $file = $this->get_basepath() . '/roles.xml'; // Load needed toles to temp_ids restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file); // Process roles, mapping/skipping. Any error throws exception // Note we pass controller's info because it can contain role mapping information // about manual mappings performed by UI restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * and users have been selected in settings, will load all the needed users * to backup_temp_ids. They will be stored with "user" itemname and with * their original contextid as paremitemid */ class restore_load_included_users extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do return; } $file = $this->get_basepath() . '/users.xml'; // Load needed users to temp_ids. restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress()); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * and users have been selected in settings, will process all the needed users * in order to decide and perform any action with them (create / map / error) * Note: Any error will cause exception, as far as this is the same processing * than the one into restore prechecks (that should have stopped process earlier) */ class restore_process_included_users extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do return; } restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress()); } } /** * Execution step that will create all the needed users as calculated * by @restore_process_included_users (those having newiteind = 0) */ class restore_create_included_users extends restore_execution_step { protected function define_execution() { restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid(), $this->task->get_progress()); } } /** * Structure step that will create all the needed groups and groupings * by loading them from the groups.xml file performing the required matches. * Note group members only will be added if restoring user info */ class restore_groups_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('group', '/groups/group'); $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping'); $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group'); return $paths; } // Processing functions go here public function process_group($data) { global $DB; $data = (object)$data; // handy $data->courseid = $this->get_courseid(); // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another a group in the same course $context = context_course::instance($data->courseid); if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) { unset($data->idnumber); } } else { unset($data->idnumber); } $oldid = $data->id; // need this saved for later $restorefiles = false; // Only if we end creating the group // Search if the group already exists (by name & description) in the target course $description_clause = ''; $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); if (!empty($data->description)) { $description_clause = ' AND ' . $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); $params['description'] = $data->description; } if (!$groupdb = $DB->get_record_sql("SELECT * FROM {groups} WHERE courseid = :courseid AND name = :grname $description_clause", $params)) { // group doesn't exist, create $newitemid = $DB->insert_record('groups', $data); $restorefiles = true; // We'll restore the files } else { // group exists, use it $newitemid = $groupdb->id; } // Save the id mapping $this->set_mapping('group', $oldid, $newitemid, $restorefiles); // Invalidate the course group data cache just in case. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); } public function process_grouping($data) { global $DB; $data = (object)$data; // handy $data->courseid = $this->get_courseid(); // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another a grouping in the same course $context = context_course::instance($data->courseid); if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) { unset($data->idnumber); } } else { unset($data->idnumber); } $oldid = $data->id; // need this saved for later $restorefiles = false; // Only if we end creating the grouping // Search if the grouping already exists (by name & description) in the target course $description_clause = ''; $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); if (!empty($data->description)) { $description_clause = ' AND ' . $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); $params['description'] = $data->description; } if (!$groupingdb = $DB->get_record_sql("SELECT * FROM {groupings} WHERE courseid = :courseid AND name = :grname $description_clause", $params)) { // grouping doesn't exist, create $newitemid = $DB->insert_record('groupings', $data); $restorefiles = true; // We'll restore the files } else { // grouping exists, use it $newitemid = $groupingdb->id; } // Save the id mapping $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles); // Invalidate the course group data cache just in case. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); } public function process_grouping_group($data) { global $CFG; require_once($CFG->dirroot.'/group/lib.php'); $data = (object)$data; groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded); } protected function after_execute() { // Add group related files, matching with "group" mappings $this->add_related_files('group', 'icon', 'group'); $this->add_related_files('group', 'description', 'group'); // Add grouping related files, matching with "grouping" mappings $this->add_related_files('grouping', 'description', 'grouping'); // Invalidate the course group data. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid())); } } /** * Structure step that will create all the needed group memberships * by loading them from the groups.xml file performing the required matches. */ class restore_groups_members_structure_step extends restore_structure_step { protected $plugins = null; protected function define_structure() { $paths = array(); // Add paths here if ($this->get_setting_value('users')) { $paths[] = new restore_path_element('group', '/groups/group'); $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member'); } return $paths; } public function process_group($data) { $data = (object)$data; // handy // HACK ALERT! // Not much to do here, this groups mapping should be already done from restore_groups_structure_step. // Let's fake internal state to make $this->get_new_parentid('group') work. $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id)); } public function process_member($data) { global $DB, $CFG; require_once("$CFG->dirroot/group/lib.php"); // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled. $data = (object)$data; // handy // get parent group->id $data->groupid = $this->get_new_parentid('group'); // map user newitemid and insert if not member already if ($data->userid = $this->get_mappingid('user', $data->userid)) { if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) { // Check the component, if any, exists. if (empty($data->component)) { groups_add_member($data->groupid, $data->userid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment groups - ignore the component and just find out the instance via new id, // it is possible that enrolment was restored using different plugin type. if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid); } } } } else { $dir = core_component::get_component_directory($data->component); if ($dir and is_dir($dir)) { if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) { return; } } // Bad luck, plugin could not restore the data, let's add normal membership. groups_add_member($data->groupid, $data->userid); $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead."; $this->log($message, backup::LOG_WARNING); } } } } } /** * Structure step that will create all the needed scales * by loading them from the scales.xml */ class restore_scales_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('scale', '/scales_definition/scale'); return $paths; } protected function process_scale($data) { global $DB; $data = (object)$data; $restorefiles = false; // Only if we end creating the group $oldid = $data->id; // need this saved for later // Look for scale (by 'scale' both in standard (course=0) and current course // with priority to standard scales (ORDER clause) // scale is not course unique, use get_record_sql to suppress warning // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc'); $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale); if (!$scadb = $DB->get_record_sql("SELECT * FROM {scale} WHERE courseid IN (0, :courseid) AND $compare_scale_clause ORDER BY courseid", $params, IGNORE_MULTIPLE)) { // Remap the user if possible, defaut to user performing the restore if not $userid = $this->get_mappingid('user', $data->userid); $data->userid = $userid ? $userid : $this->task->get_userid(); // Remap the course if course scale $data->courseid = $data->courseid ? $this->get_courseid() : 0; // If global scale (course=0), check the user has perms to create it // falling to course scale if not $systemctx = context_system::instance(); if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } // scale doesn't exist, create $newitemid = $DB->insert_record('scale', $data); $restorefiles = true; // We'll restore the files } else { // scale exists, use it $newitemid = $scadb->id; } // Save the id mapping (with files support at system context) $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); } protected function after_execute() { // Add scales related files, matching with "scale" mappings $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid()); } } /** * Structure step that will create all the needed outocomes * by loading them from the outcomes.xml */ class restore_outcomes_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome'); return $paths; } protected function process_outcome($data) { global $DB; $data = (object)$data; $restorefiles = false; // Only if we end creating the group $oldid = $data->id; // need this saved for later // Look for outcome (by shortname both in standard (courseid=null) and current course // with priority to standard outcomes (ORDER clause) // outcome is not course unique, use get_record_sql to suppress warning $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname); if (!$outdb = $DB->get_record_sql('SELECT * FROM {grade_outcomes} WHERE shortname = :shortname AND (courseid = :courseid OR courseid IS NULL) ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) { // Remap the user $userid = $this->get_mappingid('user', $data->usermodified); $data->usermodified = $userid ? $userid : $this->task->get_userid(); // Remap the scale $data->scaleid = $this->get_mappingid('scale', $data->scaleid); // Remap the course if course outcome $data->courseid = $data->courseid ? $this->get_courseid() : null; // If global outcome (course=null), check the user has perms to create it // falling to course outcome if not $systemctx = context_system::instance(); if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } // outcome doesn't exist, create $newitemid = $DB->insert_record('grade_outcomes', $data); $restorefiles = true; // We'll restore the files } else { // scale exists, use it $newitemid = $outdb->id; } // Set the corresponding grade_outcomes_courses record $outcourserec = new stdclass(); $outcourserec->courseid = $this->get_courseid(); $outcourserec->outcomeid = $newitemid; if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) { $DB->insert_record('grade_outcomes_courses', $outcourserec); } // Save the id mapping (with files support at system context) $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); } protected function after_execute() { // Add outcomes related files, matching with "outcome" mappings $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid()); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * will load all the question categories and questions (header info only) * to backup_temp_ids. They will be stored with "question_category" and * "question" itemnames and with their original contextid and question category * id as paremitemids */ class restore_load_categories_and_questions extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } $file = $this->get_basepath() . '/questions.xml'; restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file); } } /** * Execution step that, *conditionally* (if there isn't preloaded information) * will process all the needed categories and questions * in order to decide and perform any action with them (create / map / error) * Note: Any error will cause exception, as far as this is the same processing * than the one into restore prechecks (that should have stopped process earlier) */ class restore_process_categories_and_questions extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite()); } } /** * Structure step that will read the section.xml creating/updating sections * as needed, rebuilding course cache and other friends */ class restore_section_structure_step extends restore_structure_step { protected function define_structure() { global $CFG; $paths = array(); $section = new restore_path_element('section', '/section'); $paths[] = $section; if ($CFG->enableavailability) { $paths[] = new restore_path_element('availability', '/section/availability'); $paths[] = new restore_path_element('availability_field', '/section/availability_field'); } $paths[] = new restore_path_element('course_format_options', '/section/course_format_options'); // Apply for 'format' plugins optional paths at section level $this->add_plugin_structure('format', $section); // Apply for 'local' plugins optional paths at section level $this->add_plugin_structure('local', $section); return $paths; } public function process_section($data) { global $CFG, $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later $restorefiles = false; // Look for the section $section = new stdclass(); $section->course = $this->get_courseid(); $section->section = $data->number; // Section doesn't exist, create it with all the info from backup if (!$secrec = $DB->get_record('course_sections', (array)$section)) { $section->name = $data->name; $section->summary = $data->summary; $section->summaryformat = $data->summaryformat; $section->sequence = ''; $section->visible = $data->visible; if (empty($CFG->enableavailability)) { // Process availability information only if enabled. $section->availability = null; } else { $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null; // Include legacy [<2.7] availability data if provided. if (is_null($section->availability)) { $section->availability = \core_availability\info::convert_legacy_fields( $data, true); } } $newitemid = $DB->insert_record('course_sections', $section); $restorefiles = true; // Section exists, update non-empty information } else { $section->id = $secrec->id; if ((string)$secrec->name === '') { $section->name = $data->name; } if (empty($secrec->summary)) { $section->summary = $data->summary; $section->summaryformat = $data->summaryformat; $restorefiles = true; } // Don't update availability (I didn't see a useful way to define // whether existing or new one should take precedence). $DB->update_record('course_sections', $section); $newitemid = $secrec->id; } // Annotate the section mapping, with restorefiles option if needed $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles); // set the new course_section id in the task $this->task->set_sectionid($newitemid); // If there is the legacy showavailability data, store this for later use. // (This data is not present when restoring 'new' backups.) if (isset($data->showavailability)) { // Cache the showavailability flag using the backup_ids data field. restore_dbops::set_backup_ids_record($this->get_restoreid(), 'section_showavailability', $newitemid, 0, null, (object)array('showavailability' => $data->showavailability)); } // Commented out. We never modify course->numsections as far as that is used // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x) // Note: We keep the code here, to know about and because of the possibility of making this // optional based on some setting/attribute in the future // If needed, adjust course->numsections //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) { // if ($numsections < $section->section) { // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid())); // } //} } /** * Process the legacy availability table record. This table does not exist * in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ public function process_availability($data) { $data = (object)$data; // Simply going to store the whole availability record now, we'll process // all them later in the final task (once all activities have been restored) // Let's call the low level one to be able to store the whole object. $data->coursesectionid = $this->task->get_sectionid(); restore_dbops::set_backup_ids_record($this->get_restoreid(), 'section_availability', $data->id, 0, null, $data); } /** * Process the legacy availability fields table record. This table does not * exist in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ public function process_availability_field($data) { global $DB; $data = (object)$data; // Mark it is as passed by default $passed = true; $customfieldid = null; // If a customfield has been used in order to pass we must be able to match an existing // customfield by name (data->customfield) and type (data->customfieldtype) if (is_null($data->customfield) xor is_null($data->customfieldtype)) { // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. // If one is null but the other isn't something clearly went wrong and we'll skip this condition. $passed = false; } else if (!is_null($data->customfield)) { $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); $customfieldid = $DB->get_field('user_info_field', 'id', $params); $passed = ($customfieldid !== false); } if ($passed) { // Create the object to insert into the database $availfield = new stdClass(); $availfield->coursesectionid = $this->task->get_sectionid(); $availfield->userfield = $data->userfield; $availfield->customfieldid = $customfieldid; $availfield->operator = $data->operator; $availfield->value = $data->value; // Get showavailability option. $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'section_showavailability', $availfield->coursesectionid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availfield object is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_sections', 'availability', array('id' => $availfield->coursesectionid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_field_condition( $currentvalue, $availfield, $show); $DB->set_field('course_sections', 'availability', $newvalue, array('id' => $availfield->coursesectionid)); } } public function process_course_format_options($data) { global $DB; $data = (object)$data; $oldid = $data->id; unset($data->id); $data->sectionid = $this->task->get_sectionid(); $data->courseid = $this->get_courseid(); $newid = $DB->insert_record('course_format_options', $data); $this->set_mapping('course_format_options', $oldid, $newid); } protected function after_execute() { // Add section related files, with 'course_section' itemid to match $this->add_related_files('course', 'section', 'course_section'); } } /** * Structure step that will read the course.xml file, loading it and performing * various actions depending of the site/restore settings. Note that target * course always exist before arriving here so this step will be updating * the course record (never inserting) */ class restore_course_structure_step extends restore_structure_step { /** * @var bool this gets set to true by {@link process_course()} if we are * restoring an old coures that used the legacy 'module security' feature. * If so, we have to do more work in {@link after_execute()}. */ protected $legacyrestrictmodules = false; /** * @var array Used when {@link $legacyrestrictmodules} is true. This is an * array with array keys the module names ('forum', 'quiz', etc.). These are * the modules that are allowed according to the data in the backup file. * In {@link after_execute()} we then have to prevent adding of all the other * types of activity. */ protected $legacyallowedmodules = array(); protected function define_structure() { $course = new restore_path_element('course', '/course'); $category = new restore_path_element('category', '/course/category'); $tag = new restore_path_element('tag', '/course/tags/tag'); $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module'); // Apply for 'format' plugins optional paths at course level $this->add_plugin_structure('format', $course); // Apply for 'theme' plugins optional paths at course level $this->add_plugin_structure('theme', $course); // Apply for 'report' plugins optional paths at course level $this->add_plugin_structure('report', $course); // Apply for 'course report' plugins optional paths at course level $this->add_plugin_structure('coursereport', $course); // Apply for plagiarism plugins optional paths at course level $this->add_plugin_structure('plagiarism', $course); // Apply for local plugins optional paths at course level $this->add_plugin_structure('local', $course); return array($course, $category, $tag, $allowed_module); } /** * Processing functions go here * * @global moodledatabase $DB * @param stdClass $data */ public function process_course($data) { global $CFG, $DB; $data = (object)$data; $fullname = $this->get_setting_value('course_fullname'); $shortname = $this->get_setting_value('course_shortname'); $startdate = $this->get_setting_value('course_startdate'); // Calculate final course names, to avoid dupes list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname); // Need to change some fields before updating the course record $data->id = $this->get_courseid(); $data->fullname = $fullname; $data->shortname= $shortname; // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another course on this site. $context = context::instance_by_id($this->task->get_contextid()); if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) && $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) { // Do not reset idnumber. } else { $data->idnumber = ''; } // Any empty value for course->hiddensections will lead to 0 (default, show collapsed). // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532 if (empty($data->hiddensections)) { $data->hiddensections = 0; } // Set legacyrestrictmodules to true if the course was resticting modules. If so // then we will need to process restricted modules after execution. $this->legacyrestrictmodules = !empty($data->restrictmodules); $data->startdate= $this->apply_date_offset($data->startdate); if ($data->defaultgroupingid) { $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid); } if (empty($CFG->enablecompletion)) { $data->enablecompletion = 0; $data->completionstartonenrol = 0; $data->completionnotify = 0; } $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search if (!array_key_exists($data->lang, $languages)) { $data->lang = ''; } $themes = get_list_of_themes(); // Get themes for quick search later if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) { $data->theme = ''; } // Check if this is an old SCORM course format. if ($data->format == 'scorm') { $data->format = 'singleactivity'; $data->activitytype = 'scorm'; } // Course record ready, update it $DB->update_record('course', $data); course_get_format($data)->update_course_format_options($data); // Role name aliases restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid()); } public function process_category($data) { // Nothing to do with the category. UI sets it before restore starts } public function process_tag($data) { global $CFG, $DB; $data = (object)$data; if (!empty($CFG->usetags)) { // if enabled in server // TODO: This is highly inneficient. Each time we add one tag // we fetch all the existing because tag_set() deletes them // so everything must be reinserted on each call $tags = array(); $existingtags = tag_get_tags('course', $this->get_courseid()); // Re-add all the existitng tags foreach ($existingtags as $existingtag) { $tags[] = $existingtag->rawname; } // Add the one being restored $tags[] = $data->rawname; // Send all the tags back to the course tag_set('course', $this->get_courseid(), $tags, 'core', context_course::instance($this->get_courseid())->id); } } public function process_allowed_module($data) { $data = (object)$data; // Backwards compatiblity support for the data that used to be in the // course_allowed_modules table. if ($this->legacyrestrictmodules) { $this->legacyallowedmodules[$data->modulename] = 1; } } protected function after_execute() { global $DB; // Add course related files, without itemid to match $this->add_related_files('course', 'summary', null); $this->add_related_files('course', 'overviewfiles', null); // Deal with legacy allowed modules. if ($this->legacyrestrictmodules) { $context = context_course::instance($this->get_courseid()); list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities'); list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config'); foreach ($managerroleids as $roleid) { unset($roleids[$roleid]); } foreach (core_component::get_plugin_list('mod') as $modname => $notused) { if (isset($this->legacyallowedmodules[$modname])) { // Module is allowed, no worries. continue; } $capability = 'mod/' . $modname . ':addinstance'; foreach ($roleids as $roleid) { assign_capability($capability, CAP_PREVENT, $roleid, $context); } } } } } /** * Execution step that will migrate legacy files if present. */ class restore_course_legacy_files_step extends restore_execution_step { public function define_execution() { global $DB; // Do a check for legacy files and skip if there are none. $sql = 'SELECT count(*) FROM {backup_files_temp} WHERE backupid = ? AND contextid = ? AND component = ? AND filearea = ?'; $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy'); if ($DB->count_records_sql($sql, $params)) { $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid())); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course', 'legacy', $this->task->get_old_contextid(), $this->task->get_userid()); } } } /* * Structure step that will read the roles.xml file (at course/activity/block levels) * containing all the role_assignments and overrides for that context. If corresponding to * one mapped role, they will be applied to target context. Will observe the role_assignments * setting to decide if ras are restored. * * Note: this needs to be executed after all users are enrolled. */ class restore_ras_and_caps_structure_step extends restore_structure_step { protected $plugins = null; protected function define_structure() { $paths = array(); // Observe the role_assignments setting if ($this->get_setting_value('role_assignments')) { $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment'); } $paths[] = new restore_path_element('override', '/roles/role_overrides/override'); return $paths; } /** * Assign roles * * This has to be called after enrolments processing. * * @param mixed $data * @return void */ public function process_assignment($data) { global $DB; $data = (object)$data; // Check roleid, userid are one of the mapped ones if (!$newroleid = $this->get_mappingid('role', $data->roleid)) { return; } if (!$newuserid = $this->get_mappingid('user', $data->userid)) { return; } if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) { // Only assign roles to not deleted users return; } if (!$contextid = $this->task->get_contextid()) { return; } if (empty($data->component)) { // assign standard manual roles // TODO: role_assign() needs one userid param to be able to specify our restore userid role_assign($newroleid, $newuserid, $contextid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment roles - ignore the component and just find out the instance via new id, // it is possible that enrolment was restored using different plugin type. if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid); } } } } else { $data->roleid = $newroleid; $data->userid = $newuserid; $data->contextid = $contextid; $dir = core_component::get_component_directory($data->component); if ($dir and is_dir($dir)) { if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) { return; } } // Bad luck, plugin could not restore the data, let's add normal membership. role_assign($data->roleid, $data->userid, $data->contextid); $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead."; $this->log($message, backup::LOG_WARNING); } } public function process_override($data) { $data = (object)$data; // Check roleid is one of the mapped ones $newroleid = $this->get_mappingid('role', $data->roleid); // If newroleid and context are valid assign it via API (it handles dupes and so on) if ($newroleid && $this->task->get_contextid()) { // TODO: assign_capability() needs one userid param to be able to specify our restore userid // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ??? assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid()); } } } /** * If no instances yet add default enrol methods the same way as when creating new course in UI. */ class restore_default_enrolments_step extends restore_execution_step { public function define_execution() { global $DB; // No enrolments in front page. if ($this->get_courseid() == SITEID) { return; } $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST); if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) { // Something already added instances, do not add default instances. $plugins = enrol_get_plugins(true); foreach ($plugins as $plugin) { $plugin->restore_sync_course($course); } } else { // Looks like a newly created course. enrol_course_updated(true, $course, null); } } } /** * This structure steps restores the enrol plugins and their underlying * enrolments, performing all the mappings and/or movements required */ class restore_enrolments_structure_step extends restore_structure_step { protected $enrolsynced = false; protected $plugins = null; protected $originalstatus = array(); /** * Conditionally decide if this step should be executed. * * This function checks the following parameter: * * 1. the course/enrolments.xml file exists * * @return bool true is safe to execute, false otherwise */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore enrolments info return false; } return true; } protected function define_structure() { $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol'); $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment'); // Attach local plugin stucture to enrol element. $this->add_plugin_structure('enrol', $enrol); return array($enrol, $enrolment); } /** * Create enrolment instances. * * This has to be called after creation of roles * and before adding of role assignments. * * @param mixed $data * @return void */ public function process_enrol($data) { global $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later. unset($data->id); $this->originalstatus[$oldid] = $data->status; if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) { $this->set_mapping('enrol', $oldid, 0); return; } if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if (!$this->enrolsynced) { // Make sure that all plugin may create instances and enrolments automatically // before the first instance restore - this is suitable especially for plugins // that synchronise data automatically using course->idnumber or by course categories. foreach ($this->plugins as $plugin) { $plugin->restore_sync_course($courserec); } $this->enrolsynced = true; } // Map standard fields - plugin has to process custom fields manually. $data->roleid = $this->get_mappingid('role', $data->roleid); $data->courseid = $courserec->id; if ($this->get_setting_value('enrol_migratetomanual')) { unset($data->sortorder); // Remove useless sortorder from <2.4 backups. if (!enrol_is_enabled('manual')) { $this->set_mapping('enrol', $oldid, 0); return; } if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) { $instance = reset($instances); $this->set_mapping('enrol', $oldid, $instance->id); } else { if ($data->enrol === 'manual') { $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data); } else { $instanceid = $this->plugins['manual']->add_default_instance($courserec); } $this->set_mapping('enrol', $oldid, $instanceid); } } else { if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) { $this->set_mapping('enrol', $oldid, 0); $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments"; $this->log($message, backup::LOG_WARNING); return; } if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) { // Let's keep the sortorder in old backups. } else { // Prevent problems with colliding sortorders in old backups, // new 2.4 backups do not need sortorder because xml elements are ordered properly. unset($data->sortorder); } // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type. $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid); } } /** * Create user enrolments. * * This has to be called after creation of enrolment instances * and before adding of role assignments. * * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards. * * @param mixed $data * @return void */ public function process_enrolment($data) { global $DB; if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } $data = (object)$data; // Process only if parent instance have been mapped. if ($enrolid = $this->get_new_parentid('enrol')) { $oldinstancestatus = ENROL_INSTANCE_ENABLED; $oldenrolid = $this->get_old_parentid('enrol'); if (isset($this->originalstatus[$oldenrolid])) { $oldinstancestatus = $this->originalstatus[$oldenrolid]; } if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { // And only if user is a mapped one. if ($userid = $this->get_mappingid('user', $data->userid)) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus); } } } } } } /** * Make sure the user restoring the course can actually access it. */ class restore_fix_restorer_access_step extends restore_execution_step { protected function define_execution() { global $CFG, $DB; if (!$userid = $this->task->get_userid()) { return; } if (empty($CFG->restorernewroleid)) { // Bad luck, no fallback role for restorers specified return; } $courseid = $this->get_courseid(); $context = context_course::instance($courseid); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Current user may access the course (admin, category manager or restored teacher enrolment usually) return; } // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled role_assign($CFG->restorernewroleid, $userid, $context); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Extra role is enough, yay! return; } // The last chance is to create manual enrol if it does not exist and and try to enrol the current user, // hopefully admin selected suitable $CFG->restorernewroleid ... if (!enrol_is_enabled('manual')) { return; } if (!$enrol = enrol_get_plugin('manual')) { return; } if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) { $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0)); $enrol->add_instance($course, $fields); } enrol_try_internal_enrol($courseid, $userid); } } /** * This structure steps restores the filters and their configs */ class restore_filters_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active'); $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config'); return $paths; } public function process_active($data) { $data = (object)$data; if (strpos($data->filter, 'filter/') === 0) { $data->filter = substr($data->filter, 7); } else if (strpos($data->filter, '/') !== false) { // Unsupported old filter. return; } if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do return; } filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active); } public function process_config($data) { $data = (object)$data; if (strpos($data->filter, 'filter/') === 0) { $data->filter = substr($data->filter, 7); } else if (strpos($data->filter, '/') !== false) { // Unsupported old filter. return; } if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do return; } filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value); } } /** * This structure steps restores the comments * Note: Cannot use the comments API because defaults to USER->id. * That should change allowing to pass $userid */ class restore_comments_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('comment', '/comments/comment'); return $paths; } public function process_comment($data) { global $DB; $data = (object)$data; // First of all, if the comment has some itemid, ask to the task what to map $mapping = false; if ($data->itemid) { $mapping = $this->task->get_comment_mapping_itemname($data->commentarea); $data->itemid = $this->get_mappingid($mapping, $data->itemid); } // Only restore the comment if has no mapping OR we have found the matching mapping if (!$mapping || $data->itemid) { // Only if user mapping and context $data->userid = $this->get_mappingid('user', $data->userid); if ($data->userid && $this->task->get_contextid()) { $data->contextid = $this->task->get_contextid(); // Only if there is another comment with same context/user/timecreated $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated); if (!$DB->record_exists('comments', $params)) { $DB->insert_record('comments', $data); } } } } } /** * This structure steps restores the badges and their configs */ class restore_badges_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks the following parameters: * * 1. Badges and course badges are enabled on the site. * 2. The course/badges.xml file exists. * 3. All modules are restorable. * 4. All modules are marked for restore. * * @return bool True is safe to execute, false otherwise */ protected function execute_condition() { global $CFG; // First check is badges and course level badges are enabled on this site. if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) { // Disabled, don't restore course badges. return false; } // Check if badges.xml is included in the backup. $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course badges. return false; } // Check we are able to restore all backed up modules. if ($this->task->is_missing_modules()) { return false; } // Finally check all modules within the backup are being restored. if ($this->task->is_excluding_activities()) { return false; } return true; } protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('badge', '/badges/badge'); $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion'); $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter'); $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award'); return $paths; } public function process_badge($data) { global $DB, $CFG; require_once($CFG->libdir . '/badgeslib.php'); $data = (object)$data; $data->usercreated = $this->get_mappingid('user', $data->usercreated); if (empty($data->usercreated)) { $data->usercreated = $this->task->get_userid(); } $data->usermodified = $this->get_mappingid('user', $data->usermodified); if (empty($data->usermodified)) { $data->usermodified = $this->task->get_userid(); } // We'll restore the badge image. $restorefiles = true; $courseid = $this->get_courseid(); $params = array( 'name' => $data->name, 'description' => $data->description, 'timecreated' => $this->apply_date_offset($data->timecreated), 'timemodified' => $this->apply_date_offset($data->timemodified), 'usercreated' => $data->usercreated, 'usermodified' => $data->usermodified, 'issuername' => $data->issuername, 'issuerurl' => $data->issuerurl, 'issuercontact' => $data->issuercontact, 'expiredate' => $this->apply_date_offset($data->expiredate), 'expireperiod' => $data->expireperiod, 'type' => BADGE_TYPE_COURSE, 'courseid' => $courseid, 'message' => $data->message, 'messagesubject' => $data->messagesubject, 'attachment' => $data->attachment, 'notification' => $data->notification, 'status' => BADGE_STATUS_INACTIVE, 'nextcron' => $this->apply_date_offset($data->nextcron) ); $newid = $DB->insert_record('badge', $params); $this->set_mapping('badge', $data->id, $newid, $restorefiles); } public function process_criterion($data) { global $DB; $data = (object)$data; $params = array( 'badgeid' => $this->get_new_parentid('badge'), 'criteriatype' => $data->criteriatype, 'method' => $data->method ); $newid = $DB->insert_record('badge_criteria', $params); $this->set_mapping('criterion', $data->id, $newid); } public function process_parameter($data) { global $DB, $CFG; require_once($CFG->libdir . '/badgeslib.php'); $data = (object)$data; $criteriaid = $this->get_new_parentid('criterion'); // Parameter array that will go to database. $params = array(); $params['critid'] = $criteriaid; $oldparam = explode('_', $data->name); if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) { $module = $this->get_mappingid('course_module', $oldparam[1]); $params['name'] = $oldparam[0] . '_' . $module; $params['value'] = $oldparam[0] == 'module' ? $module : $data->value; } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) { $params['name'] = $oldparam[0] . '_' . $this->get_courseid(); $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value; } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) { $role = $this->get_mappingid('role', $data->value); if (!empty($role)) { $params['name'] = 'role_' . $role; $params['value'] = $role; } else { return; } } if (!$DB->record_exists('badge_criteria_param', $params)) { $DB->insert_record('badge_criteria_param', $params); } } public function process_manual_award($data) { global $DB; $data = (object)$data; $role = $this->get_mappingid('role', $data->issuerrole); if (!empty($role)) { $award = array( 'badgeid' => $this->get_new_parentid('badge'), 'recipientid' => $this->get_mappingid('user', $data->recipientid), 'issuerid' => $this->get_mappingid('user', $data->issuerid), 'issuerrole' => $role, 'datemet' => $this->apply_date_offset($data->datemet) ); // Skip the manual award if recipient or issuer can not be mapped to. if (empty($award['recipientid']) || empty($award['issuerid'])) { return; } $DB->insert_record('badge_manual_award', $award); } } protected function after_execute() { // Add related files. $this->add_related_files('badges', 'badgeimage', 'badge'); } } /** * This structure steps restores the calendar events */ class restore_calendarevents_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('calendarevents', '/events/event'); return $paths; } public function process_calendarevents($data) { global $DB, $SITE, $USER; $data = (object)$data; $oldid = $data->id; $restorefiles = true; // We'll restore the files // Find the userid and the groupid associated with the event. $data->userid = $this->get_mappingid('user', $data->userid); if ($data->userid === false) { // Blank user ID means that we are dealing with module generated events such as quiz starting times. // Use the current user ID for these events. $data->userid = $USER->id; } if (!empty($data->groupid)) { $data->groupid = $this->get_mappingid('group', $data->groupid); if ($data->groupid === false) { return; } } // Handle events with empty eventtype //MDL-32827 if(empty($data->eventtype)) { if ($data->courseid == $SITE->id) { // Site event $data->eventtype = "site"; } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) { // Course assingment event $data->eventtype = "due"; } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event $data->eventtype = "course"; } else if ($data->groupid) { // Group event $data->eventtype = "group"; } else if ($data->userid) { // User event $data->eventtype = "user"; } else { return; } } $params = array( 'name' => $data->name, 'description' => $data->description, 'format' => $data->format, 'courseid' => $this->get_courseid(), 'groupid' => $data->groupid, 'userid' => $data->userid, 'repeatid' => $data->repeatid, 'modulename' => $data->modulename, 'eventtype' => $data->eventtype, 'timestart' => $this->apply_date_offset($data->timestart), 'timeduration' => $data->timeduration, 'visible' => $data->visible, 'uuid' => $data->uuid, 'sequence' => $data->sequence, 'timemodified' => $this->apply_date_offset($data->timemodified)); if ($this->name == 'activity_calendar') { $params['instance'] = $this->task->get_activityid(); } else { $params['instance'] = 0; } $sql = "SELECT id FROM {event} WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . " AND courseid = ? AND repeatid = ? AND modulename = ? AND timestart = ? AND timeduration = ? AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255); $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']); $result = $DB->record_exists_sql($sql, $arg); if (empty($result)) { $newitemid = $DB->insert_record('event', $params); $this->set_mapping('event', $oldid, $newitemid); $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles); } } protected function after_execute() { // Add related files $this->add_related_files('calendar', 'event_description', 'event_description'); } } class restore_course_completion_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks parameters that are not immediate settings to ensure * that the enviroment is suitable for the restore of course completion info. * * This function checks the following four parameters: * * 1. Course completion is enabled on the site * 2. The backup includes course completion information * 3. All modules are restorable * 4. All modules are marked for restore. * * @return bool True is safe to execute, false otherwise */ protected function execute_condition() { global $CFG; // First check course completion is enabled on this site if (empty($CFG->enablecompletion)) { // Disabled, don't restore course completion return false; } // No course completion on the front page. if ($this->get_courseid() == SITEID) { return false; } // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course completion return false; } // Check we are able to restore all backed up modules if ($this->task->is_missing_modules()) { return false; } // Finally check all modules within the backup are being restored. if ($this->task->is_excluding_activities()) { return false; } return true; } /** * Define the course completion structure * * @return array Array of restore_path_element */ protected function define_structure() { // To know if we are including user completion info $userinfo = $this->get_setting_value('userscompletion'); $paths = array(); $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria'); $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd'); if ($userinfo) { $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl'); $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions'); } return $paths; } /** * Process course completion criteria * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_criteria($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); // Apply the date offset to the time end field $data->timeend = $this->apply_date_offset($data->timeend); // Map the role from the criteria if (!empty($data->role)) { $data->role = $this->get_mappingid('role', $data->role); } $skipcriteria = false; // If the completion criteria is for a module we need to map the module instance // to the new module id. if (!empty($data->moduleinstance) && !empty($data->module)) { $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance); if (empty($data->moduleinstance)) { $skipcriteria = true; } } else { $data->module = null; $data->moduleinstance = null; } // We backup the course shortname rather than the ID so that we can match back to the course if (!empty($data->courseinstanceshortname)) { $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname)); if (!$courseinstanceid) { $skipcriteria = true; } } else { $courseinstanceid = null; } $data->courseinstance = $courseinstanceid; if (!$skipcriteria) { $params = array( 'course' => $data->course, 'criteriatype' => $data->criteriatype, 'enrolperiod' => $data->enrolperiod, 'courseinstance' => $data->courseinstance, 'module' => $data->module, 'moduleinstance' => $data->moduleinstance, 'timeend' => $data->timeend, 'gradepass' => $data->gradepass, 'role' => $data->role ); $newid = $DB->insert_record('course_completion_criteria', $params); $this->set_mapping('course_completion_criteria', $data->id, $newid); } } /** * Processes course compltion criteria complete records * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_crit_compl($data) { global $DB; $data = (object)$data; // This may be empty if criteria could not be restored $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid); $data->course = $this->get_courseid(); $data->userid = $this->get_mappingid('user', $data->userid); if (!empty($data->criteriaid) && !empty($data->userid)) { $params = array( 'userid' => $data->userid, 'course' => $data->course, 'criteriaid' => $data->criteriaid, 'timecompleted' => $this->apply_date_offset($data->timecompleted) ); if (isset($data->gradefinal)) { $params['gradefinal'] = $data->gradefinal; } if (isset($data->unenroled)) { $params['unenroled'] = $data->unenroled; } $DB->insert_record('course_completion_crit_compl', $params); } } /** * Process course completions * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completions($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); $data->userid = $this->get_mappingid('user', $data->userid); if (!empty($data->userid)) { $params = array( 'userid' => $data->userid, 'course' => $data->course, 'timeenrolled' => $this->apply_date_offset($data->timeenrolled), 'timestarted' => $this->apply_date_offset($data->timestarted), 'timecompleted' => $this->apply_date_offset($data->timecompleted), 'reaggregate' => $data->reaggregate ); $existing = $DB->get_record('course_completions', array( 'userid' => $data->userid, 'course' => $data->course )); // MDL-46651 - If cron writes out a new record before we get to it // then we should replace it with the Truth data from the backup. // This may be obsolete after MDL-48518 is resolved if ($existing) { $params['id'] = $existing->id; $DB->update_record('course_completions', $params); } else { $DB->insert_record('course_completions', $params); } } } /** * Process course completion aggregate methods * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_aggr_methd($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); // Only create the course_completion_aggr_methd records if // the target course has not them defined. MDL-28180 if (!$DB->record_exists('course_completion_aggr_methd', array( 'course' => $data->course, 'criteriatype' => $data->criteriatype))) { $params = array( 'course' => $data->course, 'criteriatype' => $data->criteriatype, 'method' => $data->method, 'value' => $data->value, ); $DB->insert_record('course_completion_aggr_methd', $params); } } } /** * This structure step restores course logs (cmid = 0), delegating * the hard work to the corresponding {@link restore_logs_processor} passing the * collection of {@link restore_log_rule} rules to be observed as they are defined * by the task. Note this is only executed based in the 'logs' setting. * * NOTE: This is executed by final task, to have all the activities already restored * * NOTE: Not all course logs are being restored. For now only 'course' and 'user' * records are. There are others like 'calendar' and 'upload' that will be handled * later. * * NOTE: All the missing actions (not able to be restored) are sent to logs for * debugging purposes */ class restore_course_logs_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks the following parameter: * * 1. the course/logs.xml file exists * * @return bool true is safe to execute, false otherwise */ protected function execute_condition() { // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course logs return false; } return true; } protected function define_structure() { $paths = array(); // Simple, one plain level of information contains them $paths[] = new restore_path_element('log', '/logs/log'); return $paths; } protected function process_log($data) { global $DB; $data = (object)($data); $data->time = $this->apply_date_offset($data->time); $data->userid = $this->get_mappingid('user', $data->userid); $data->course = $this->get_courseid(); $data->cmid = 0; // For any reason user wasn't remapped ok, stop processing this if (empty($data->userid)) { return; } // Everything ready, let's delegate to the restore_logs_processor // Set some fixed values that will save tons of DB requests $values = array( 'course' => $this->get_courseid()); // Get instance and process log record $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); // If we have data, insert it, else something went wrong in the restore_logs_processor if ($data) { if (empty($data->url)) { $data->url = ''; } if (empty($data->info)) { $data->info = ''; } // Store the data in the legacy log table if we are still using it. $manager = get_log_manager(); if (method_exists($manager, 'legacy_add_to_log')) { $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, $data->info, $data->cmid, $data->userid); } } } } /** * This structure step restores activity logs, extending {@link restore_course_logs_structure_step} * sharing its same structure but modifying the way records are handled */ class restore_activity_logs_structure_step extends restore_course_logs_structure_step { protected function process_log($data) { global $DB; $data = (object)($data); $data->time = $this->apply_date_offset($data->time); $data->userid = $this->get_mappingid('user', $data->userid); $data->course = $this->get_courseid(); $data->cmid = $this->task->get_moduleid(); // For any reason user wasn't remapped ok, stop processing this if (empty($data->userid)) { return; } // Everything ready, let's delegate to the restore_logs_processor // Set some fixed values that will save tons of DB requests $values = array( 'course' => $this->get_courseid(), 'course_module' => $this->task->get_moduleid(), $this->task->get_modulename() => $this->task->get_activityid()); // Get instance and process log record $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); // If we have data, insert it, else something went wrong in the restore_logs_processor if ($data) { if (empty($data->url)) { $data->url = ''; } if (empty($data->info)) { $data->info = ''; } // Store the data in the legacy log table if we are still using it. $manager = get_log_manager(); if (method_exists($manager, 'legacy_add_to_log')) { $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, $data->info, $data->cmid, $data->userid); } } } } /** * Defines the restore step for advanced grading methods attached to the activity module */ class restore_activity_grading_structure_step extends restore_structure_step { /** * This step is executed only if the grading file is present */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } return true; } /** * Declares paths in the grading.xml file we are interested in */ protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); $area = new restore_path_element('grading_area', '/areas/area'); $paths[] = $area; // attach local plugin stucture to $area element $this->add_plugin_structure('local', $area); $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition'); $paths[] = $definition; $this->add_plugin_structure('gradingform', $definition); // attach local plugin stucture to $definition element $this->add_plugin_structure('local', $definition); if ($userinfo) { $instance = new restore_path_element('grading_instance', '/areas/area/definitions/definition/instances/instance'); $paths[] = $instance; $this->add_plugin_structure('gradingform', $instance); // attach local plugin stucture to $intance element $this->add_plugin_structure('local', $instance); } return $paths; } /** * Processes one grading area element * * @param array $data element data */ protected function process_grading_area($data) { global $DB; $task = $this->get_task(); $data = (object)$data; $oldid = $data->id; $data->component = 'mod_'.$task->get_modulename(); $data->contextid = $task->get_contextid(); $newid = $DB->insert_record('grading_areas', $data); $this->set_mapping('grading_area', $oldid, $newid); } /** * Processes one grading definition element * * @param array $data element data */ protected function process_grading_definition($data) { global $DB; $task = $this->get_task(); $data = (object)$data; $oldid = $data->id; $data->areaid = $this->get_new_parentid('grading_area'); $data->copiedfromid = null; $data->timecreated = time(); $data->usercreated = $task->get_userid(); $data->timemodified = $data->timecreated; $data->usermodified = $data->usercreated; $newid = $DB->insert_record('grading_definitions', $data); $this->set_mapping('grading_definition', $oldid, $newid, true); } /** * Processes one grading form instance element * * @param array $data element data */ protected function process_grading_instance($data) { global $DB; $data = (object)$data; // new form definition id $newformid = $this->get_new_parentid('grading_definition'); // get the name of the area we are restoring to $sql = "SELECT ga.areaname FROM {grading_definitions} gd JOIN {grading_areas} ga ON gd.areaid = ga.id WHERE gd.id = ?"; $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST); // get the mapped itemid - the activity module is expected to define the mappings // for each gradable area $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid); $oldid = $data->id; $data->definitionid = $newformid; $data->raterid = $this->get_mappingid('user', $data->raterid); $data->itemid = $newitemid; $newid = $DB->insert_record('grading_instances', $data); $this->set_mapping('grading_instance', $oldid, $newid); } /** * Final operations when the database records are inserted */ protected function after_execute() { // Add files embedded into the definition description $this->add_related_files('grading', 'description', 'grading_definition'); } } /** * This structure step restores the grade items associated with one activity * All the grade items are made child of the "course" grade item but the original * categoryid is saved as parentitemid in the backup_ids table, so, when restoring * the complete gradebook (categories and calculations), that information is * available there */ class restore_activity_grades_structure_step extends restore_structure_step { /** * No grades in front page. * @return bool */ protected function execute_condition() { return ($this->get_courseid() != SITEID); } protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item'); $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter'); if ($userinfo) { $paths[] = new restore_path_element('grade_grade', '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade'); } return $paths; } protected function process_grade_item($data) { global $DB; $data = (object)($data); $oldid = $data->id; // We'll need these later $oldparentid = $data->categoryid; $courseid = $this->get_courseid(); // make sure top course category exists, all grade items will be associated // to it. Later, if restoring the whole gradebook, categories will be introduced $coursecat = grade_category::fetch_course_category($courseid); $coursecatid = $coursecat->id; // Get the categoryid to be used $idnumber = null; if (!empty($data->idnumber)) { // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop) // so the best is to keep the ones already in the gradebook // Potential problem: duplicates if same items are restored more than once. :-( // This needs to be fixed in some way (outcomes & activities with multiple items) // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber; // In any case, verify always for uniqueness $sql = "SELECT cm.id FROM {course_modules} cm WHERE cm.course = :courseid AND cm.idnumber = :idnumber AND cm.id <> :cmid"; $params = array( 'courseid' => $courseid, 'idnumber' => $data->idnumber, 'cmid' => $this->task->get_moduleid() ); if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) { $idnumber = $data->idnumber; } } unset($data->id); $data->categoryid = $coursecatid; $data->courseid = $this->get_courseid(); $data->iteminstance = $this->task->get_activityid(); $data->idnumber = $idnumber; $data->scaleid = $this->get_mappingid('scale', $data->scaleid); $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $gradeitem = new grade_item($data, false); $gradeitem->insert('restore'); //sortorder is automatically assigned when inserting. Re-instate the previous sortorder $gradeitem->sortorder = $data->sortorder; $gradeitem->update('restore'); // Set mapping, saving the original category id into parentitemid // gradebook restore (final task) will need it to reorganise items $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid); } protected function process_grade_grade($data) { $data = (object)($data); $olduserid = $data->userid; $oldid = $data->id; unset($data->id); $data->itemid = $this->get_new_parentid('grade_item'); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? $data->overridden = $this->apply_date_offset($data->overridden); $grade = new grade_grade($data, false); $grade->insert('restore'); $this->set_mapping('grade_grades', $oldid, $grade->id); } else { debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"); } } /** * process activity grade_letters. Note that, while these are possible, * because grade_letters are contextid based, in practice, only course * context letters can be defined. So we keep here this method knowing * it won't be executed ever. gradebook restore will restore course letters. */ protected function process_grade_letter($data) { global $DB; $data['contextid'] = $this->task->get_contextid(); $gradeletter = (object)$data; // Check if it exists before adding it unset($data['id']); if (!$DB->record_exists('grade_letters', $data)) { $newitemid = $DB->insert_record('grade_letters', $gradeletter); } // no need to save any grade_letter mapping } public function after_restore() { // Fix grade item's sortorder after restore, as it might have duplicates. $courseid = $this->get_task()->get_courseid(); grade_item::fix_duplicate_sortorder($courseid); } } /** * Step in charge of restoring the grade history of an activity. * * This step is added to the task regardless of the setting 'grade_histories'. * The reason is to allow for a more flexible step in case the logic needs to be * split accross different settings to control the history of items and/or grades. */ class restore_activity_grade_history_structure_step extends restore_structure_step { /** * This step is executed only if the grade history file is present. */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } return true; } protected function define_structure() { $paths = array(); // Settings to use. $userinfo = $this->get_setting_value('userinfo'); $history = $this->get_setting_value('grade_histories'); if ($userinfo && $history) { $paths[] = new restore_path_element('grade_grade', '/grade_history/grade_grades/grade_grade'); } return $paths; } protected function process_grade_grade($data) { global $DB; $data = (object) $data; $olduserid = $data->userid; unset($data->id); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { // Do not apply the date offsets as this is history. $data->itemid = $this->get_mappingid('grade_item', $data->itemid); $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); $DB->insert_record('grade_grades_history', $data); } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } } /** * This structure steps restores one instance + positions of one block * Note: Positions corresponding to one existing context are restored * here, but all the ones having unknown contexts are sent to backup_ids * for a later chance to be restored at the end (final task) */ class restore_block_instance_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position'); return $paths; } public function process_block($data) { global $DB, $CFG; $data = (object)$data; // Handy $oldcontextid = $data->contextid; $oldid = $data->id; $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array(); // Look for the parent contextid if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) { throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid); } // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple() // If there is already one block of that type in the parent context // and the block is not multiple, stop processing // Use blockslib loader / method executor if (!$bi = block_instance($data->blockname)) { return false; } if (!$bi->instance_allow_multiple()) { // The block cannot be added twice, so we will check if the same block is already being // displayed on the same page. For this, rather than mocking a page and using the block_manager // we use a similar query to the one in block_manager::load_blocks(), this will give us // a very good idea of the blocks already displayed in the context. $params = array( 'blockname' => $data->blockname ); // Context matching test. $context = context::instance_by_id($data->parentcontextid); $contextsql = 'bi.parentcontextid = :contextid'; $params['contextid'] = $context->id; $parentcontextids = $context->get_parent_context_ids(); if ($parentcontextids) { list($parentcontextsql, $parentcontextparams) = $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED); $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))"; $params = array_merge($params, $parentcontextparams); } // Page type pattern test. $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern); list($pagetypepatternsql, $pagetypepatternparams) = $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED); $params = array_merge($params, $pagetypepatternparams); // Sub page pattern test. $subpagepatternsql = 'bi.subpagepattern IS NULL'; if ($data->subpagepattern !== null) { $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)"; $params['subpagepattern'] = $data->subpagepattern; } $exists = $DB->record_exists_sql("SELECT bi.id FROM {block_instances} bi JOIN {block} b ON b.name = bi.blockname WHERE bi.blockname = :blockname AND $contextsql AND bi.pagetypepattern $pagetypepatternsql AND $subpagepatternsql", $params); if ($exists) { // There is at least one very similar block visible on the page where we // are trying to restore the block. In these circumstances the block API // would not allow the user to add another instance of the block, so we // apply the same rule here. return false; } } // If there is already one block of that type in the parent context // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata // stop processing $params = array( 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion); if ($birecs = $DB->get_records('block_instances', $params)) { foreach($birecs as $birec) { if ($birec->configdata == $data->configdata) { return false; } } } // Set task old contextid, blockid and blockname once we know them $this->task->set_old_contextid($oldcontextid); $this->task->set_old_blockid($oldid); $this->task->set_blockname($data->blockname); // Let's look for anything within configdata neededing processing // (nulls and uses of legacy file.php) if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) { $configdata = (array)unserialize(base64_decode($data->configdata)); foreach ($configdata as $attribute => $value) { if (in_array($attribute, $attrstotransform)) { $configdata[$attribute] = $this->contentprocessor->process_cdata($value); } } $data->configdata = base64_encode(serialize((object)$configdata)); } // Create the block instance $newitemid = $DB->insert_record('block_instances', $data); // Save the mapping (with restorefiles support) $this->set_mapping('block_instance', $oldid, $newitemid, true); // Create the block context $newcontextid = context_block::instance($newitemid)->id; // Save the block contexts mapping and sent it to task $this->set_mapping('context', $oldcontextid, $newcontextid); $this->task->set_contextid($newcontextid); $this->task->set_blockid($newitemid); // Restore block fileareas if declared $component = 'block_' . $this->task->get_blockname(); foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed $this->add_related_files($component, $filearea, null); } // Process block positions, creating them or accumulating for final step foreach($positions as $position) { $position = (object)$position; $position->blockinstanceid = $newitemid; // The instance is always the restored one // If position is for one already mapped (known) contextid // process it now, creating the position if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) { $position->contextid = $newpositionctxid; // Create the block position $DB->insert_record('block_positions', $position); // The position belongs to an unknown context, send it to backup_ids // to process them as part of the final steps of restore. We send the // whole $position object there, hence use the low level method. } else { restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position); } } } } /** * Structure step to restore common course_module information * * This step will process the module.xml file for one activity, in order to restore * the corresponding information to the course_modules table, skipping various bits * of information based on CFG settings (groupings, completion...) in order to fullfill * all the reqs to be able to create the context to be used by all the rest of steps * in the activity restore task */ class restore_module_structure_step extends restore_structure_step { protected function define_structure() { global $CFG; $paths = array(); $module = new restore_path_element('module', '/module'); $paths[] = $module; if ($CFG->enableavailability) { $paths[] = new restore_path_element('availability', '/module/availability_info/availability'); $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field'); } // Apply for 'format' plugins optional paths at module level $this->add_plugin_structure('format', $module); // Apply for 'plagiarism' plugins optional paths at module level $this->add_plugin_structure('plagiarism', $module); // Apply for 'local' plugins optional paths at module level $this->add_plugin_structure('local', $module); return $paths; } protected function process_module($data) { global $CFG, $DB; $data = (object)$data; $oldid = $data->id; $this->task->set_old_moduleversion($data->version); $data->course = $this->task->get_courseid(); $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename)); // Map section (first try by course_section mapping match. Useful in course and section restores) $data->section = $this->get_mappingid('course_section', $data->sectionid); if (!$data->section) { // mapping failed, try to get section by sectionnumber matching $params = array( 'course' => $this->get_courseid(), 'section' => $data->sectionnumber); $data->section = $DB->get_field('course_sections', 'id', $params); } if (!$data->section) { // sectionnumber failed, try to get first section in course $params = array( 'course' => $this->get_courseid()); $data->section = $DB->get_field('course_sections', 'MIN(id)', $params); } if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1 $sectionrec = array( 'course' => $this->get_courseid(), 'section' => 0); $DB->insert_record('course_sections', $sectionrec); // section 0 $sectionrec = array( 'course' => $this->get_courseid(), 'section' => 1); $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1 } $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness $data->idnumber = ''; } if (empty($CFG->enablecompletion)) { // completion $data->completion = 0; $data->completiongradeitemnumber = null; $data->completionview = 0; $data->completionexpected = 0; } else { $data->completionexpected = $this->apply_date_offset($data->completionexpected); } if (empty($CFG->enableavailability)) { $data->availability = null; } // Backups that did not include showdescription, set it to default 0 // (this is not totally necessary as it has a db default, but just to // be explicit). if (!isset($data->showdescription)) { $data->showdescription = 0; } $data->instance = 0; // Set to 0 for now, going to create it soon (next step) if (empty($data->availability)) { // If there are legacy availablility data fields (and no new format data), // convert the old fields. $data->availability = \core_availability\info::convert_legacy_fields( $data, false); } else if (!empty($data->groupmembersonly)) { // There is current availability data, but it still has groupmembersonly // as well (2.7 backups), convert just that part. require_once($CFG->dirroot . '/lib/db/upgradelib.php'); $data->availability = upgrade_group_members_only($data->groupingid, $data->availability); } // course_module record ready, insert it $newitemid = $DB->insert_record('course_modules', $data); // save mapping $this->set_mapping('course_module', $oldid, $newitemid); // set the new course_module id in the task $this->task->set_moduleid($newitemid); // we can now create the context safely $ctxid = context_module::instance($newitemid)->id; // set the new context id in the task $this->task->set_contextid($ctxid); // update sequence field in course_section if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) { $sequence .= ',' . $newitemid; } else { $sequence = $newitemid; } $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section)); // If there is the legacy showavailability data, store this for later use. // (This data is not present when restoring 'new' backups.) if (isset($data->showavailability)) { // Cache the showavailability flag using the backup_ids data field. restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_showavailability', $newitemid, 0, null, (object)array('showavailability' => $data->showavailability)); } } /** * Process the legacy availability table record. This table does not exist * in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ protected function process_availability($data) { $data = (object)$data; // Simply going to store the whole availability record now, we'll process // all them later in the final task (once all activities have been restored) // Let's call the low level one to be able to store the whole object $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data); } /** * Process the legacy availability fields table record. This table does not * exist in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ protected function process_availability_field($data) { global $DB; $data = (object)$data; // Mark it is as passed by default $passed = true; $customfieldid = null; // If a customfield has been used in order to pass we must be able to match an existing // customfield by name (data->customfield) and type (data->customfieldtype) if (!empty($data->customfield) xor !empty($data->customfieldtype)) { // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. // If one is null but the other isn't something clearly went wrong and we'll skip this condition. $passed = false; } else if (!empty($data->customfield)) { $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); $customfieldid = $DB->get_field('user_info_field', 'id', $params); $passed = ($customfieldid !== false); } if ($passed) { // Create the object to insert into the database $availfield = new stdClass(); $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid $availfield->userfield = $data->userfield; $availfield->customfieldid = $customfieldid; $availfield->operator = $data->operator; $availfield->value = $data->value; // Get showavailability option. $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_showavailability', $availfield->coursemoduleid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availfieldobject is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_modules', 'availability', array('id' => $availfield->coursemoduleid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_field_condition( $currentvalue, $availfield, $show); $DB->set_field('course_modules', 'availability', $newvalue, array('id' => $availfield->coursemoduleid)); } } } /** * Structure step that will process the user activity completion * information if all these conditions are met: * - Target site has completion enabled ($CFG->enablecompletion) * - Activity includes completion info (file_exists) */ class restore_userscompletion_structure_step extends restore_structure_step { /** * To conditionally decide if this step must be executed * Note the "settings" conditions are evaluated in the * corresponding task. Here we check for other conditions * not being restore settings (files, site settings...) */ protected function execute_condition() { global $CFG; // Completion disabled in this site, don't execute if (empty($CFG->enablecompletion)) { return false; } // No completion on the front page. if ($this->get_courseid() == SITEID) { return false; } // No user completion info found, don't execute $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Arrived here, execute the step return true; } protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('completion', '/completions/completion'); return $paths; } protected function process_completion($data) { global $DB; $data = (object)$data; $data->coursemoduleid = $this->task->get_moduleid(); $data->userid = $this->get_mappingid('user', $data->userid); $data->timemodified = $this->apply_date_offset($data->timemodified); // Find the existing record $existing = $DB->get_record('course_modules_completion', array( 'coursemoduleid' => $data->coursemoduleid, 'userid' => $data->userid), 'id, timemodified'); // Check we didn't already insert one for this cmid and userid // (there aren't supposed to be duplicates in that field, but // it was possible until MDL-28021 was fixed). if ($existing) { // Update it to these new values, but only if the time is newer if ($existing->timemodified < $data->timemodified) { $data->id = $existing->id; $DB->update_record('course_modules_completion', $data); } } else { // Normal entry where it doesn't exist already $DB->insert_record('course_modules_completion', $data); } } } /** * Abstract structure step, parent of all the activity structure steps. Used to suuport * the main <activity ...> tag and process it. Also provides subplugin support for * activities. */ abstract class restore_activity_structure_step extends restore_structure_step { protected function add_subplugin_structure($subplugintype, $element) { global $CFG; // Check the requested subplugintype is a valid one $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php'; if (!file_exists($subpluginsfile)) { throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename()); } include($subpluginsfile); if (!array_key_exists($subplugintype, $subplugins)) { throw new restore_step_exception('incorrect_subplugin_type', $subplugintype); } // Get all the restore path elements, looking across all the subplugin dirs $subpluginsdirs = core_component::get_plugin_list($subplugintype); foreach ($subpluginsdirs as $name => $subpluginsdir) { $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin'; $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoresubplugin = new $classname($subplugintype, $name, $this); // Add subplugin paths to the step $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element)); } } } /** * As far as activity restore steps are implementing restore_subplugin stuff, they need to * have the parent task available for wrapping purposes (get course/context....) * @return restore_task */ public function get_task() { return $this->task; } /** * Adds support for the 'activity' path that is common to all the activities * and will be processed globally here */ protected function prepare_activity_structure($paths) { $paths[] = new restore_path_element('activity', '/activity'); return $paths; } /** * Process the activity path, informing the task about various ids, needed later */ protected function process_activity($data) { $data = (object)$data; $this->task->set_old_contextid($data->contextid); // Save old contextid in task $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping $this->task->set_old_activityid($data->id); // Save old activityid in task } /** * This must be invoked immediately after creating the "module" activity record (forum, choice...) * and will adjust the new activity id (the instance) in various places */ protected function apply_activity_instance($newitemid) { global $DB; $this->task->set_activityid($newitemid); // Save activity id in task // Apply the id to course_sections->instanceid $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid())); // Do the mapping for modulename, preparing it for files by oldcontext $modulename = $this->task->get_modulename(); $oldid = $this->task->get_old_activityid(); $this->set_mapping($modulename, $oldid, $newitemid, true); } } /** * Structure step in charge of creating/mapping all the qcats and qs * by parsing the questions.xml file and checking it against the * results calculated by {@link restore_process_categories_and_questions} * and stored in backup_ids_temp */ class restore_create_categories_and_questions extends restore_structure_step { /** @var array $cachecategory store a question category */ protected $cachedcategory = null; protected function define_structure() { $category = new restore_path_element('question_category', '/question_categories/question_category'); $question = new restore_path_element('question', '/question_categories/question_category/questions/question'); $hint = new restore_path_element('question_hint', '/question_categories/question_category/questions/question/question_hints/question_hint'); $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag'); // Apply for 'qtype' plugins optional paths at question level $this->add_plugin_structure('qtype', $question); // Apply for 'local' plugins optional paths at question level $this->add_plugin_structure('local', $question); return array($category, $question, $hint, $tag); } protected function process_question_category($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Check we have one mapping for this category if (!$mapping = $this->get_mapping('question_category', $oldid)) { return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped } // Check we have to create the category (newitemid = 0) if ($mapping->newitemid) { return; // newitemid != 0, this category is going to be mapped. Nothing to do } // Arrived here, newitemid = 0, we need to create the category // we'll do it at parentitemid context, but for CONTEXT_MODULE // categories, that will be created at CONTEXT_COURSE and moved // to module context later when the activity is created if ($mapping->info->contextlevel == CONTEXT_MODULE) { $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid()); } $data->contextid = $mapping->parentitemid; // Let's create the question_category and save mapping $newitemid = $DB->insert_record('question_categories', $data); $this->set_mapping('question_category', $oldid, $newitemid); // Also annotate them as question_category_created, we need // that later when remapping parents $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid); } protected function process_question($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Check we have one mapping for this question if (!$questionmapping = $this->get_mapping('question', $oldid)) { return; // No mapping = this question doesn't need to be created/mapped } // Get the mapped category (cannot use get_new_parentid() because not // all the categories have been created, so it is not always available // Instead we get the mapping for the question->parentitemid because // we have loaded qcatids there for all parsed questions $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid); // In the past, there were some very sloppy values of penalty. Fix them. if ($data->penalty >= 0.33 && $data->penalty <= 0.34) { $data->penalty = 0.3333333; } if ($data->penalty >= 0.66 && $data->penalty <= 0.67) { $data->penalty = 0.6666667; } if ($data->penalty >= 1) { $data->penalty = 1; } $userid = $this->get_mappingid('user', $data->createdby); $data->createdby = $userid ? $userid : $this->task->get_userid(); $userid = $this->get_mappingid('user', $data->modifiedby); $data->modifiedby = $userid ? $userid : $this->task->get_userid(); // With newitemid = 0, let's create the question if (!$questionmapping->newitemid) { $newitemid = $DB->insert_record('question', $data); $this->set_mapping('question', $oldid, $newitemid); // Also annotate them as question_created, we need // that later when remapping parents (keeping the old categoryid as parentid) $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid); } else { // By performing this set_mapping() we make get_old/new_parentid() to work for all the // children elements of the 'question' one (so qtype plugins will know the question they belong to) $this->set_mapping('question', $oldid, $questionmapping->newitemid); } // Note, we don't restore any question files yet // as far as the CONTEXT_MODULE categories still // haven't their contexts to be restored to // The {@link restore_create_question_files}, executed in the final step // step will be in charge of restoring all the question files } protected function process_question_hint($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Detect if the question is created or mapped $oldquestionid = $this->get_old_parentid('question'); $newquestionid = $this->get_new_parentid('question'); $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false; // If the question has been created by restore, we need to create its question_answers too if ($questioncreated) { // Adjust some columns $data->questionid = $newquestionid; // Insert record $newitemid = $DB->insert_record('question_hints', $data); // The question existed, we need to map the existing question_hints } else { // Look in question_hints by hint text matching $sql = 'SELECT id FROM {question_hints} WHERE questionid = ? AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255); $params = array($newquestionid, $data->hint); $newitemid = $DB->get_field_sql($sql, $params); // Not able to find the hint, let's try cleaning the hint text // of all the question's hints in DB as slower fallback. MDL-33863. if (!$newitemid) { $potentialhints = $DB->get_records('question_hints', array('questionid' => $newquestionid), '', 'id, hint'); foreach ($potentialhints as $potentialhint) { // Clean in the same way than {@link xml_writer::xml_safe_utf8()}. $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars. $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending. if ($cleanhint === $data->hint) { $newitemid = $data->id; } } } // If we haven't found the newitemid, something has gone really wrong, question in DB // is missing hints, exception if (!$newitemid) { $info = new stdClass(); $info->filequestionid = $oldquestionid; $info->dbquestionid = $newquestionid; $info->hint = $data->hint; throw new restore_step_exception('error_question_hint_missing_in_db', $info); } } // Create mapping (I'm not sure if this is really needed?) $this->set_mapping('question_hint', $oldid, $newitemid); } protected function process_tag($data) { global $CFG, $DB; $data = (object)$data; $newquestion = $this->get_new_parentid('question'); if (!empty($CFG->usetags)) { // if enabled in server // TODO: This is highly inefficient. Each time we add one tag // we fetch all the existing because tag_set() deletes them // so everything must be reinserted on each call $tags = array(); $existingtags = tag_get_tags('question', $newquestion); // Re-add all the existitng tags foreach ($existingtags as $existingtag) { $tags[] = $existingtag->rawname; } // Add the one being restored $tags[] = $data->rawname; // Get the category, so we can then later get the context. $categoryid = $this->get_new_parentid('question_category'); if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) { $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid)); } // Send all the tags back to the question tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid); } } protected function after_execute() { global $DB; // First of all, recode all the created question_categories->parent fields $qcats = $DB->get_records('backup_ids_temp', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_category_created')); foreach ($qcats as $qcat) { $newparent = 0; $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid)); // Get new parent (mapped or created, so we look in quesiton_category mappings) if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_category', 'itemid' => $dbcat->parent))) { // contextids must match always, as far as we always include complete qbanks, just check it $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent)); if ($dbcat->contextid == $newparentctxid) { $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id)); } else { $newparent = 0; // No ctx match for both cats, no parent relationship } } // Here with $newparent empty, problem with contexts or remapping, set it to top cat if (!$newparent) { $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id)); } } // Now, recode all the created question->parent fields $qs = $DB->get_records('backup_ids_temp', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_created')); foreach ($qs as $q) { $newparent = 0; $dbq = $DB->get_record('question', array('id' => $q->newitemid)); // Get new parent (mapped or created, so we look in question mappings) if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question', 'itemid' => $dbq->parent))) { $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id)); } } // Note, we don't restore any question files yet // as far as the CONTEXT_MODULE categories still // haven't their contexts to be restored to // The {@link restore_create_question_files}, executed in the final step // step will be in charge of restoring all the question files } } /** * Execution step that will move all the CONTEXT_MODULE question categories * created at early stages of restore in course context (because modules weren't * created yet) to their target module (matching by old-new-contextid mapping) */ class restore_move_module_questions_categories extends restore_execution_step { protected function define_execution() { global $DB; $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE); foreach ($contexts as $contextid => $contextlevel) { // Only if context mapping exists (i.e. the module has been restored) if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) { // Update all the qcats having their parentitemid set to the original contextid $modulecats = $DB->get_records_sql("SELECT itemid, newitemid FROM {backup_ids_temp} WHERE backupid = ? AND itemname = 'question_category' AND parentitemid = ?", array($this->get_restoreid(), $contextid)); foreach ($modulecats as $modulecat) { $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid)); // And set new contextid also in question_category mapping (will be // used by {@link restore_create_question_files} later restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid); } } } } } /** * Execution step that will create all the question/answers/qtype-specific files for the restored * questions. It must be executed after {@link restore_move_module_questions_categories} * because only then each question is in its final category and only then the * contexts can be determined. */ class restore_create_question_files extends restore_execution_step { /** @var array Question-type specific component items cache. */ private $qtypecomponentscache = array(); /** * Preform the restore_create_question_files step. */ protected function define_execution() { global $DB; // Track progress, as this task can take a long time. $progress = $this->task->get_progress(); $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE); // Parentitemids of question_createds in backup_ids_temp are the category it is in. // MUST use a recordset, as there is no unique key in the first (or any) column. $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype FROM {backup_ids_temp} bi JOIN {question} q ON q.id = bi.newitemid WHERE bi.backupid = ? AND bi.itemname = 'question_created' ORDER BY categoryid ASC", array($this->get_restoreid())); $currentcatid = -1; foreach ($catqtypes as $categoryid => $row) { $qtype = $row->qtype; // Check if we are in a new category. if ($currentcatid !== $categoryid) { // Report progress for each category. $progress->progress(); if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $categoryid)) { // Something went really wrong, cannot find the question_category for the question_created records. debugging('Error fetching target context for question', DEBUG_DEVELOPER); continue; } // Calculate source and target contexts. $oldctxid = $qcatmapping->info->contextid; $newctxid = $qcatmapping->parentitemid; $this->send_common_files($oldctxid, $newctxid, $progress); $currentcatid = $categoryid; } $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress); } $catqtypes->close(); $progress->end_progress(); } /** * Send the common question files to a new context. * * @param int $oldctxid Old context id. * @param int $newctxid New context id. * @param \core\progress $progress Progress object to use. */ private function send_common_files($oldctxid, $newctxid, $progress) { // Add common question files (question and question_answer ones). restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer', $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback', $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint', $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); } /** * Send the question type specific files to a new context. * * @param text $qtype The qtype name to send. * @param int $oldctxid Old context id. * @param int $newctxid New context id. * @param \core\progress $progress Progress object to use. */ private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) { if (!isset($this->qtypecomponentscache[$qtype])) { $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype); } $components = $this->qtypecomponentscache[$qtype]; foreach ($components as $component => $fileareas) { foreach ($fileareas as $filearea => $mapping) { restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea, $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress); } } } } /** * Try to restore aliases and references to external files. * * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}. * We expect that all regular (non-alias) files have already been restored. Make sure * there is no restore step executed after this one that would call send_files_to_pool() again. * * You may notice we have hardcoded support for Server files, Legacy course files * and user Private files here at the moment. This could be eventually replaced with a set of * callbacks in the future if needed. * * @copyright 2012 David Mudrak <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_process_file_aliases_queue extends restore_execution_step { /** @var array internal cache for {@link choose_repository()} */ private $cachereposbyid = array(); /** @var array internal cache for {@link choose_repository()} */ private $cachereposbytype = array(); /** * What to do when this step is executed. */ protected function define_execution() { global $DB; $this->log('processing file aliases queue', backup::LOG_DEBUG); $fs = get_file_storage(); // Load the queue. $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'), '', 'info'); // Iterate over aliases in the queue. foreach ($rs as $record) { $info = backup_controller_dbops::decode_backup_temp_info($record->info); // Try to pick a repository instance that should serve the alias. $repository = $this->choose_repository($info); if (is_null($repository)) { $this->notify_failure($info, 'unable to find a matching repository instance'); continue; } if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') { // Aliases to Server files and Legacy course files may refer to a file // contained in the backup file or to some existing file (if we are on the // same site). try { $reference = file_storage::unpack_reference($info->oldfile->reference); } catch (Exception $e) { $this->notify_failure($info, 'invalid reference field format'); continue; } // Let's see if the referred source file was also included in the backup. $candidates = $DB->get_recordset('backup_files_temp', array( 'backupid' => $this->get_restoreid(), 'contextid' => $reference['contextid'], 'component' => $reference['component'], 'filearea' => $reference['filearea'], 'itemid' => $reference['itemid'], ), '', 'info, newcontextid, newitemid'); $source = null; foreach ($candidates as $candidate) { $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info); if ($candidateinfo->filename === $reference['filename'] and $candidateinfo->filepath === $reference['filepath'] and !is_null($candidate->newcontextid) and !is_null($candidate->newitemid) ) { $source = $candidateinfo; $source->contextid = $candidate->newcontextid; $source->itemid = $candidate->newitemid; break; } } $candidates->close(); if ($source) { // We have an alias that refers to another file also included in // the backup. Let us change the reference field so that it refers // to the restored copy of the original file. $reference = file_storage::pack_reference($source); // Send the new alias to the filepool. $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { // This is a reference to some moodle file that was not contained in the backup // file. If we are restoring to the same site, keep the reference untouched // and restore the alias as is if the referenced file exists. if ($this->task->is_samesite()) { if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) { $reference = file_storage::pack_reference($reference); $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { $this->notify_failure($info, 'referenced file not found'); continue; } // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'referenced file not included'); continue; } } } else if ($info->oldfile->repositorytype === 'user') { if ($this->task->is_samesite()) { // For aliases to user Private files at the same site, we have a chance to check // if the referenced file still exists. try { $reference = file_storage::unpack_reference($info->oldfile->reference); } catch (Exception $e) { $this->notify_failure($info, 'invalid reference field format'); continue; } if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) { $reference = file_storage::pack_reference($reference); $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { $this->notify_failure($info, 'referenced file not found'); continue; } // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'restoring at another site'); continue; } } else { // This is a reference to some external file such as in boxnet or dropbox. // If we are restoring to the same site, keep the reference untouched and // restore the alias as is. if ($this->task->is_samesite()) { $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference); $this->notify_success($info); continue; // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'restoring at another site'); continue; } } } $rs->close(); } /** * Choose the repository instance that should handle the alias. * * At the same site, we can rely on repository instance id and we just * check it still exists. On other site, try to find matching Server files or * Legacy course files repository instance. Return null if no matching * repository instance can be found. * * @param stdClass $info * @return repository|null */ private function choose_repository(stdClass $info) { global $DB, $CFG; require_once($CFG->dirroot.'/repository/lib.php'); if ($this->task->is_samesite()) { // We can rely on repository instance id. if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) { return $this->cachereposbyid[$info->oldfile->repositoryid]; } $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1); try { $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID); return $this->cachereposbyid[$info->oldfile->repositoryid]; } catch (Exception $e) { $this->cachereposbyid[$info->oldfile->repositoryid] = null; return null; } } else { // We can rely on repository type only. if (empty($info->oldfile->repositorytype)) { return null; } if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) { return $this->cachereposbytype[$info->oldfile->repositorytype]; } $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1); // Both Server files and Legacy course files repositories have a single // instance at the system context to use. Let us try to find it. if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') { $sql = "SELECT ri.id FROM {repository} r JOIN {repository_instances} ri ON ri.typeid = r.id WHERE r.type = ? AND ri.contextid = ?"; $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID)); if (empty($ris)) { return null; } $repoids = array_keys($ris); $repoid = reset($repoids); try { $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID); return $this->cachereposbytype[$info->oldfile->repositorytype]; } catch (Exception $e) { $this->cachereposbytype[$info->oldfile->repositorytype] = null; return null; } } $this->cachereposbytype[$info->oldfile->repositorytype] = null; return null; } } /** * Let the user know that the given alias was successfully restored * * @param stdClass $info */ private function notify_success(stdClass $info) { $filedesc = $this->describe_alias($info); $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1); } /** * Let the user know that the given alias can't be restored * * @param stdClass $info * @param string $reason detailed reason to be logged */ private function notify_failure(stdClass $info, $reason = '') { $filedesc = $this->describe_alias($info); if ($reason) { $reason = ' ('.$reason.')'; } $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1); $this->add_result_item('file_aliases_restore_failures', $filedesc); } /** * Return a human readable description of the alias file * * @param stdClass $info * @return string */ private function describe_alias(stdClass $info) { $filedesc = $this->expected_alias_location($info->newfile); if (!is_null($info->oldfile->source)) { $filedesc .= ' ('.$info->oldfile->source.')'; } return $filedesc; } /** * Return the expected location of a file * * Please note this may and may not work as a part of URL to pluginfile.php * (depends on how the given component/filearea deals with the itemid). * * @param stdClass $filerecord * @return string */ private function expected_alias_location($filerecord) { $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea; if (!is_null($filerecord->itemid)) { $filedesc .= '/'.$filerecord->itemid; } $filedesc .= $filerecord->filepath.$filerecord->filename; return $filedesc; } /** * Append a value to the given resultset * * @param string $name name of the result containing a list of values * @param mixed $value value to add as another item in that result */ private function add_result_item($name, $value) { $results = $this->task->get_results(); if (isset($results[$name])) { if (!is_array($results[$name])) { throw new coding_exception('Unable to append a result item into a non-array structure.'); } $current = $results[$name]; $current[] = $value; $this->task->add_result(array($name => $current)); } else { $this->task->add_result(array($name => array($value))); } } } /** * Abstract structure step, to be used by all the activities using core questions stuff * (like the quiz module), to support qtype plugins, states and sessions */ abstract class restore_questions_activity_structure_step extends restore_activity_structure_step { /** @var array question_attempt->id to qtype. */ protected $qtypes = array(); /** @var array question_attempt->id to questionid. */ protected $newquestionids = array(); /** * Attach below $element (usually attempts) the needed restore_path_elements * to restore question_usages and all they contain. * * If you use the $nameprefix parameter, then you will need to implement some * extra methods in your class, like * * protected function process_{nameprefix}question_attempt($data) { * $this->restore_question_usage_worker($data, '{nameprefix}'); * } * protected function process_{nameprefix}question_attempt($data) { * $this->restore_question_attempt_worker($data, '{nameprefix}'); * } * protected function process_{nameprefix}question_attempt_step($data) { * $this->restore_question_attempt_step_worker($data, '{nameprefix}'); * } * * @param restore_path_element $element the parent element that the usages are stored inside. * @param array $paths the paths array that is being built. * @param string $nameprefix should match the prefix passed to the corresponding * backup_questions_activity_structure_step::add_question_usages call. */ protected function add_question_usages($element, &$paths, $nameprefix = '') { // Check $element is restore_path_element if (! $element instanceof restore_path_element) { throw new restore_step_exception('element_must_be_restore_path_element', $element); } // Check $paths is one array if (!is_array($paths)) { throw new restore_step_exception('paths_must_be_array', $paths); } $paths[] = new restore_path_element($nameprefix . 'question_usage', $element->get_path() . "/{$nameprefix}question_usage"); $paths[] = new restore_path_element($nameprefix . 'question_attempt', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt"); $paths[] = new restore_path_element($nameprefix . 'question_attempt_step', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step", true); $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable"); } /** * Process question_usages */ protected function process_question_usage($data) { $this->restore_question_usage_worker($data, ''); } /** * Process question_attempts */ protected function process_question_attempt($data) { $this->restore_question_attempt_worker($data, ''); } /** * Process question_attempt_steps */ protected function process_question_attempt_step($data) { $this->restore_question_attempt_step_worker($data, ''); } /** * This method does the acutal work for process_question_usage or * process_{nameprefix}_question_usage. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_usage_worker($data, $nameprefix) { global $DB; // Clear our caches. $this->qtypes = array(); $this->newquestionids = array(); $data = (object)$data; $oldid = $data->id; $oldcontextid = $this->get_task()->get_old_contextid(); $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid()); // Everything ready, insert (no mapping needed) $newitemid = $DB->insert_record('question_usages', $data); $this->inform_new_usage_id($newitemid); $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false); } /** * When process_question_usage creates the new usage, it calls this method * to let the activity link to the new usage. For example, the quiz uses * this method to set quiz_attempts.uniqueid to the new usage id. * @param integer $newusageid */ abstract protected function inform_new_usage_id($newusageid); /** * This method does the acutal work for process_question_attempt or * process_{nameprefix}_question_attempt. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_attempt_worker($data, $nameprefix) { global $DB; $data = (object)$data; $oldid = $data->id; $question = $this->get_mapping('question', $data->questionid); $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage'); $data->questionid = $question->newitemid; if (!property_exists($data, 'variant')) { $data->variant = 1; } $data->timemodified = $this->apply_date_offset($data->timemodified); if (!property_exists($data, 'maxfraction')) { $data->maxfraction = 1; } $newitemid = $DB->insert_record('question_attempts', $data); $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid); $this->qtypes[$newitemid] = $question->info->qtype; $this->newquestionids[$newitemid] = $data->questionid; } /** * This method does the acutal work for process_question_attempt_step or * process_{nameprefix}_question_attempt_step. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_attempt_step_worker($data, $nameprefix) { global $DB; $data = (object)$data; $oldid = $data->id; // Pull out the response data. $response = array(); if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) { foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) { $response[$variable['name']] = $variable['value']; } } unset($data->response); $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt'); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->userid = $this->get_mappingid('user', $data->userid); // Everything ready, insert and create mapping (needed by question_sessions) $newitemid = $DB->insert_record('question_attempt_steps', $data); $this->set_mapping('question_attempt_step', $oldid, $newitemid, true); // Now process the response data. $response = $this->questions_recode_response_data( $this->qtypes[$data->questionattemptid], $this->newquestionids[$data->questionattemptid], $data->sequencenumber, $response); foreach ($response as $name => $value) { $row = new stdClass(); $row->attemptstepid = $newitemid; $row->name = $name; $row->value = $value; $DB->insert_record('question_attempt_step_data', $row, false); } } /** * Recode the respones data for a particular step of an attempt at at particular question. * @param string $qtype the question type. * @param int $newquestionid the question id. * @param int $sequencenumber the sequence number. * @param array $response the response data to recode. */ public function questions_recode_response_data( $qtype, $newquestionid, $sequencenumber, array $response) { $qtyperestorer = $this->get_qtype_restorer($qtype); if ($qtyperestorer) { $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response); } return $response; } /** * Given a list of question->ids, separated by commas, returns the * recoded list, with all the restore question mappings applied. * Note: Used by quiz->questions and quiz_attempts->layout * Note: 0 = page break (unconverted) */ protected function questions_recode_layout($layout) { // Extracts question id from sequence if ($questionids = explode(',', $layout)) { foreach ($questionids as $id => $questionid) { if ($questionid) { // If it is zero then this is a pagebreak, don't translate $newquestionid = $this->get_mappingid('question', $questionid); $questionids[$id] = $newquestionid; } } } return implode(',', $questionids); } /** * Get the restore_qtype_plugin subclass for a specific question type. * @param string $qtype e.g. multichoice. * @return restore_qtype_plugin instance. */ protected function get_qtype_restorer($qtype) { // Build one static cache to store {@link restore_qtype_plugin} // while we are needing them, just to save zillions of instantiations // or using static stuff that will break our nice API static $qtypeplugins = array(); if (!isset($qtypeplugins[$qtype])) { $classname = 'restore_qtype_' . $qtype . '_plugin'; if (class_exists($classname)) { $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this); } else { $qtypeplugins[$qtype] = null; } } return $qtypeplugins[$qtype]; } protected function after_execute() { parent::after_execute(); // Restore any files belonging to responses. foreach (question_engine::get_all_response_file_areas() as $filearea) { $this->add_related_files('question', $filearea, 'question_attempt_step'); } } /** * Attach below $element (usually attempts) the needed restore_path_elements * to restore question attempt data from Moodle 2.0. * * When using this method, the parent element ($element) must be defined with * $grouped = true. Then, in that elements process method, you must call * {@link process_legacy_attempt_data()} with the groupded data. See, for * example, the usage of this method in {@link restore_quiz_activity_structure_step}. * @param restore_path_element $element the parent element. (E.g. a quiz attempt.) * @param array $paths the paths array that is being built to describe the * structure. */ protected function add_legacy_question_attempt_data($element, &$paths) { global $CFG; require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php'); // Check $element is restore_path_element if (!($element instanceof restore_path_element)) { throw new restore_step_exception('element_must_be_restore_path_element', $element); } // Check $paths is one array if (!is_array($paths)) { throw new restore_step_exception('paths_must_be_array', $paths); } $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state'); $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session'); } protected function get_attempt_upgrader() { if (empty($this->attemptupgrader)) { $this->attemptupgrader = new question_engine_attempt_upgrader(); $this->attemptupgrader->prepare_to_restore(); } return $this->attemptupgrader; } /** * Process the attempt data defined by {@link add_legacy_question_attempt_data()}. * @param object $data contains all the grouped attempt data to process. * @param pbject $quiz data about the activity the attempts belong to. Required * fields are (basically this only works for the quiz module): * oldquestions => list of question ids in this activity - using old ids. * preferredbehaviour => the behaviour to use for questionattempts. */ protected function process_legacy_quiz_attempt_data($data, $quiz) { global $DB; $upgrader = $this->get_attempt_upgrader(); $data = (object)$data; $layout = explode(',', $data->layout); $newlayout = $layout; // Convert each old question_session into a question_attempt. $qas = array(); foreach (explode(',', $quiz->oldquestions) as $questionid) { if ($questionid == 0) { continue; } $newquestionid = $this->get_mappingid('question', $questionid); if (!$newquestionid) { throw new restore_step_exception('questionattemptreferstomissingquestion', $questionid, $questionid); } $question = $upgrader->load_question($newquestionid, $quiz->id); foreach ($layout as $key => $qid) { if ($qid == $questionid) { $newlayout[$key] = $newquestionid; } } list($qsession, $qstates) = $this->find_question_session_and_states( $data, $questionid); if (empty($qsession) || empty($qstates)) { throw new restore_step_exception('questionattemptdatamissing', $questionid, $questionid); } list($qsession, $qstates) = $this->recode_legacy_response_data( $question, $qsession, $qstates); $data->layout = implode(',', $newlayout); $qas[$newquestionid] = $upgrader->convert_question_attempt( $quiz, $data, $question, $qsession, $qstates); } // Now create a new question_usage. $usage = new stdClass(); $usage->component = 'mod_quiz'; $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid()); $usage->preferredbehaviour = $quiz->preferredbehaviour; $usage->id = $DB->insert_record('question_usages', $usage); $this->inform_new_usage_id($usage->id); $data->uniqueid = $usage->id; $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas, $this->questions_recode_layout($quiz->oldquestions)); } protected function find_question_session_and_states($data, $questionid) { $qsession = null; foreach ($data->sessions['session'] as $session) { if ($session['questionid'] == $questionid) { $qsession = (object) $session; break; } } $qstates = array(); foreach ($data->states['state'] as $state) { if ($state['question'] == $questionid) { // It would be natural to use $state['seq_number'] as the array-key // here, but it seems that buggy behaviour in 2.0 and early can // mean that that is not unique, so we use id, which is guaranteed // to be unique. $qstates[$state['id']] = (object) $state; } } ksort($qstates); $qstates = array_values($qstates); return array($qsession, $qstates); } /** * Recode any ids in the response data * @param object $question the question data * @param object $qsession the question sessions. * @param array $qstates the question states. */ protected function recode_legacy_response_data($question, $qsession, $qstates) { $qsession->questionid = $question->id; foreach ($qstates as &$state) { $state->question = $question->id; $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype); } return array($qsession, $qstates); } /** * Recode the legacy answer field. * @param object $state the state to recode the answer of. * @param string $qtype the question type. */ public function restore_recode_legacy_answer($state, $qtype) { $restorer = $this->get_qtype_restorer($qtype); if ($restorer) { return $restorer->recode_legacy_state_answer($state); } else { return $state->answer; } } }
jrchamp/moodle
backup/moodle2/restore_stepslib.php
PHP
gpl-3.0
202,518
package CGRB::BLASTDB; # $Id: BLASTDB.pm,v 1.4 2004/11/16 21:38:43 givans Exp $ use warnings; use strict; use Carp; use CGRB::CGRBDB; use vars qw/ @ISA /; @ISA = qw/ CGRBDB /; 1; sub new { my $pkg = shift; my $user = shift; my $psswd = shift; $user = 'gcg' unless ($user); $psswd = 'sequences' unless ($psswd); # print "using user=$user, passwd=$psswd\n"; my $self = $pkg->generate('seq_databases',$user,$psswd); return $self; } sub availDB { my $self = shift; my $db = shift; my $avail = shift; $avail ? $self->_set_availDB($db,$avail) : $self->_get_availDB($db); } sub _set_availDB { my $self = shift; my $db = shift; my $avail = shift;# should be T or F my $dbh = $self->dbh(); my ($sth,$rslt); my $dbFile = $self->dbFile($db);# dbFile will be name of DB if ($avail ne 'T' && $avail ne 'F') { return "database available should be either 'T' or 'F'"; } $sth = $dbh->prepare("update DB set Avail = ? where db_file = ?"); $sth->bind_param(1,$avail); $sth->bind_param(2,$dbFile); $rslt = $self->_dbAction($dbh,$sth,3); if (ref $rslt eq 'ARRAY') { return $rslt->[0]->[0]; } else { return 0; } } sub _get_availDB { my $self = shift; my $db = shift; my $dbh = $self->dbh(); my ($sth,$rslt); my $dbFile = $self->dbFile($db); $sth = $dbh->prepare("select Avail from DB where db_file = ?"); $sth->bind_param(1,$dbFile); $rslt = $self->_dbAction($dbh,$sth,2); if (ref $rslt eq 'ARRAY') { return $rslt->[0]->[0]; } else { return 0; } } sub availDB_byType { my $self = shift; my $dbType = shift; my $avail = shift; $avail ? $self->_set_availDB_byType($dbType,$avail) : $self->_get_availDB_byType($dbType); } sub _set_availDB_byType { warn("setting DB availability by type no yet implemented"); } sub _get_availDB_byType { my $self = shift; my $dbType = shift; my $dbh = $self->dbh(); my ($sth,$rslt); $sth = $dbh->prepare("select db_name from DB where db_type = ? and Avail = 'F'"); $sth->bind_param(1, $dbType); $rslt = $self->_dbAction($dbh,$sth,2); if (ref $rslt eq 'ARRAY') { if ($rslt->[0]->[0]) { return 'F'; } else { return 'T'; } } else { return 0; } } sub dbFile { my $self = shift; my $db = shift; my $file = shift; $file ? $self->_set_dbFile($db,$file) : $self->_get_dbFile($db); } sub _set_dbFile { warn("setting db file not yet implemented"); } sub _get_dbFile { my $self = shift; my $db = shift; my $dbh = $self->dbh(); my ($sth,$rslt); $sth = $dbh->prepare("select db_file from DB where db_name = ?"); $sth->bind_param(1,$db); $rslt = $self->_dbAction($dbh,$sth,2); if (ref $rslt eq 'ARRAY') { return $rslt->[0]->[0]; } else { return 0; } } sub dbInfo { my $self = shift; my $dbh = $self->dbh(); my ($sth,$dates,%date); $sth = $dbh->prepare("select D.displayName, D.dwnld_date, D.description, T.type, D.displayOrder, D.db_name from DB D, DBType T where D.db_type = T.number AND D.displayOrder > 0"); $dates = $self->_dbAction($dbh,$sth,2); if (ref $dates eq 'ARRAY') { foreach my $ref (@$dates) { # print "Dababase: '$ref->[0]', Date: '$ref->[1]'<br>"; $date{$ref->[0]} = [$ref->[1], $ref->[2], $ref->[3], $ref->[4], $ref->[5]]; } return \%date; } else { return 0; } }
sgivan/jobQ
BLASTDB.pm
Perl
gpl-3.0
3,365
<!DOCTYPE html > <html> <head> <title>BigDecimalStringConverter - ScalaFX API 8.0.0-R4 - scalafx.util.converter.BigDecimalStringConverter</title> <meta name="description" content="BigDecimalStringConverter - ScalaFX API 8.0.0 - R4 - scalafx.util.converter.BigDecimalStringConverter" /> <meta name="keywords" content="BigDecimalStringConverter ScalaFX API 8.0.0 R4 scalafx.util.converter.BigDecimalStringConverter" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'scalafx.util.converter.BigDecimalStringConverter'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <a href="BigDecimalStringConverter$.html" title="Go to companion"><img src="../../../lib/class_to_object_big.png" /></a> <p id="owner"><a href="../../package.html" class="extype" name="scalafx">scalafx</a>.<a href="../package.html" class="extype" name="scalafx.util">util</a>.<a href="package.html" class="extype" name="scalafx.util.converter">converter</a></p> <h1><a href="BigDecimalStringConverter$.html" title="Go to companion">BigDecimalStringConverter</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">BigDecimalStringConverter</span><span class="result"> extends <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a>[<span class="extype" name="java.math.BigDecimal">BigDecimal</span>, <span class="extype" name="scala.BigDecimal">BigDecimal</span>, <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>]</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a>[<span class="extype" name="java.math.BigDecimal">BigDecimal</span>, <span class="extype" name="scala.BigDecimal">BigDecimal</span>, <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>], <a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a>[<span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>], <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a>[<span class="extype" name="scala.BigDecimal">BigDecimal</span>], <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="scalafx.util.converter.BigDecimalStringConverter"><span>BigDecimalStringConverter</span></li><li class="in" name="scalafx.util.converter.StringConverterDelegate"><span>StringConverterDelegate</span></li><li class="in" name="scalafx.delegate.SFXDelegate"><span>SFXDelegate</span></li><li class="in" name="scalafx.util.StringConverter"><span>StringConverter</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="scalafx.util.converter.BigDecimalStringConverter#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(delegate:javafx.util.converter.BigDecimalStringConverter):scalafx.util.converter.BigDecimalStringConverter"></a> <a id="&lt;init&gt;:BigDecimalStringConverter"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">BigDecimalStringConverter</span><span class="params">(<span name="delegate">delegate: <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span> = <span class="symbol">new jfxuc.BigDecimalStringConverter</span></span>)</span> </span> </h4> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scalafx.util.converter.StringConverterDelegate#delegate" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="delegate:C"></a> <a id="delegate:javafx.util.converter.BigDecimalStringConverter"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">delegate</span><span class="result">: <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span></span> </span> </h4> <p class="shortcomment cmt">JavaFx StringConverter to be wrapped.</p><div class="fullcomment"><div class="comment cmt"><p>JavaFx StringConverter to be wrapped. </p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a> → <a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a></dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.delegate.SFXDelegate#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(ref:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="ref">ref: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt">Verifies if a object is equals to this delegate.</p><div class="fullcomment"><div class="comment cmt"><p>Verifies if a object is equals to this delegate. </p></div><dl class="paramcmts block"><dt class="param">ref</dt><dd class="cmt"><p>Object to be compared.</p></dd><dt>returns</dt><dd class="cmt"><p>if the other object is equals to this delegate or not. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scalafx.util.converter.BigDecimalStringConverter#fromString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fromString(s:String):BigDecimal"></a> <a id="fromString(String):BigDecimal"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">fromString</span><span class="params">(<span name="s">s: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.BigDecimal">BigDecimal</span></span> </span> </h4> <p class="shortcomment cmt">Converts the string provided into an object defined by the specific converter.</p><div class="fullcomment"><div class="comment cmt"><p>Converts the string provided into an object defined by the specific converter. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>A new T instance generated from argument. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="scalafx.util.converter.BigDecimalStringConverter">BigDecimalStringConverter</a> → <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a> → <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a></dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scalafx.delegate.SFXDelegate#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>The delegate hashcode </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.util.converter.BigDecimalStringConverter#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString(b:BigDecimal):String"></a> <a id="toString(BigDecimal):String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">(<span name="b">b: <span class="extype" name="scala.BigDecimal">BigDecimal</span></span>)</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span> </span> </h4> <p class="shortcomment cmt">Converts the object provided into its string form.</p><div class="fullcomment"><div class="comment cmt"><p>Converts the object provided into its string form. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>String version of argument. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="scalafx.util.converter.BigDecimalStringConverter">BigDecimalStringConverter</a> → <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a> → <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a></dd></dl></div> </li><li name="scalafx.delegate.SFXDelegate#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>Returns the original delegate's <code>toString()</code> adding a <code>[SFX]</code> prefix. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scalafx.util.converter.StringConverterDelegate"> <h3>Inherited from <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a>[<span class="extype" name="java.math.BigDecimal">BigDecimal</span>, <span class="extype" name="scala.BigDecimal">BigDecimal</span>, <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>]</h3> </div><div class="parent" name="scalafx.delegate.SFXDelegate"> <h3>Inherited from <a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a>[<span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>]</h3> </div><div class="parent" name="scalafx.util.StringConverter"> <h3>Inherited from <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a>[<span class="extype" name="scala.BigDecimal">BigDecimal</span>]</h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
TarmoA/ProjectAsteroid
Documents/ohjelmointistuff/ProjectAsteroid/docs/scalafx/util/converter/BigDecimalStringConverter.html
HTML
gpl-3.0
29,240
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package xmv.solutions.IT2JZ.Jira; /** * * @author David Koller XMV Solutions GmbH */ public class JiraTestcaseStep { /** * Name of Step (e.g. "Step 1") */ private String stepName; /** * Action to give in actual step (e.g. "Press red button") */ private String testData; /** * Expected result of action for current step (e.g. "Popup is shown saying 'Done!'") */ private String expectedResult; public String getStepName() { return stepName; } public void setStepName(String stepName) { this.stepName = stepName; } public String getTestData() { return testData; } public void setTestData(String testData) { this.testData = testData; } public String getExpectedResult() { return expectedResult; } public void setExpectedResult(String expectedResult) { this.expectedResult = expectedResult; } }
XMV-Solutions/ImportTestcases2JiraZephyr
src/main/java/xmv/solutions/IT2JZ/Jira/JiraTestcaseStep.java
Java
gpl-3.0
1,034
/* package de.elxala.langutil (c) Copyright 2006 Alejandro Xalabarder Aulet This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* //(o) WelcomeGastona_source_javaj_layout EVALAYOUT ======================================================================================== ================ documentation for WelcomeGastona.gast ================================= ======================================================================================== #gastonaDoc# <docType> javaj_layout <name> EVALAYOUT <groupInfo> <javaClass> de.elxala.Eva.layout.EvaLayout <importance> 10 <desc> //A fexible grid layout <help> // // Eva layout is the most powerful layout used by Javaj. The components are laid out in a grid // and it is possible to define very accurately which cells of the grid occupy each one, which // size has to have and if they are expandable or not. // // Syntax: // // <layout of NAME> // EVALAYOUT, marginX, marginY, gapX, gapY // // --grid-- , header col1, ... , header colN // header row1, cell 1 1 , ... , cell 1 N // ... , ... , ... , ... // header rowM, cell M 1 , ... , cell M N // // The first row starts with "EVALAYOUT" or simply "EVA", then optionally the following values // in pixels for the whole grid // // marginX : horizontal margins for both left and right sides // marginY : vertical margins for both top and bottom areas // gapX : horizontal space between columns // gapY : vertical space between rows // // The rest of rows defines a grid with arbitrary N columns and M rows, the minimum for both M // and N is 1. To define a grid M x N we will need M+1 rows and a maximum of N+1 columns, this // is because the header types given in rows and columns. These header values may be one of: // // header // value meaning // ------- -------- // A Adapt (default). The row or column will adapt its size to the bigest default // size of all components that start in this row or column. // X Expand. The row or column is expandable, when the the frame is resized all // expandable row or columns will share the remaining space equally. // a number A fix size in pixels for the row or column // // Note that the very first header ("--grid--") acctually does not correspond with a row or a // column of the grid and therefore it is ignored by EvaLayout. // // Finally the cells are used to place and expand the components. If we want the component to // ocupy just one cell then we place it in that cell. If we want the component to ocupy more // cells then we place the component on the left-top cell of the rectangle of cells to be // ocupped, we fill the rest of top cells with "-" to the right and the rest of left cells with // the symbol "+" to the bottom, the rest of cells (neither top or left cells) might be left in // blank. // // Example: // // let's say we want to lay-out the following form // // ---------------------------------------------- // | label1 | field -------> | button1 | // ---------------------------------------------- // | label2 | text -------> | button2 | // ------------| | |---------- // | | | button3 | // | V |---------- // | | // ------------------------ // // representing this as grid of cells can be done at least in these two ways // // // Adapt Adapt Expand Adapt Adapt Expand Adapt // ------------------------------------- ----------------------------- // Adapt | label1 | field | - | button1 | Adapt | label1 | field | button1 | // |---------|-------|-------|---------| |---------|-------|---------| // Adapt | label2 | text | - | button2 | Adapt | label2 | text | button2 | // |---------|------ |-------|---------| |---------|------ |---------| // Adapt | | + | | button3 | Adapt | | + | button3 | // |---------|------ |-------|---------| |---------|------ |---------| // Expand | | + | | | Expand | | + | | // ------------------------------------- ----------------------------- // // the implementation of the second one as Evalayout would be // // <layout of myFirstLayout> // // EVALAYOUT // // grid, A , X , A // A, label1 , field , button1 // A, label2 , text , button2 // A, , + , button3 // X, , + , // // NOTE: While columns and rows of type expandable or fixed size might be empty of components, // this does not make sense for columns and rows of type adaptable (A), since in this // case there is nothing to adapt. These columns or rows has to be avoided because // might produce undefined results. // <...> // NOTE: EvaLayout is also available for C++ development with Windows Api and MFC, // see as reference the article http://www.codeproject.com/KB/dialog/EvaLayout.aspx // <examples> gastSample eva layout example1 eva layout example2 eva layout example3 eva layout complet eva layout centering eva layout percenting <eva layout example1> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example layout EVALAYOUT" // // <layout of F> // // EVALAYOUT, 10, 10, 5, 5 // // grid, , X , // , lLabel1 , eField1 , bButton1 // , lLabel2 , xText1 , bButton2 // , , + , bButton3 // X , , + , <eva layout example2> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example 2 layout EVALAYOUT" // // <layout of F> // // EVA, 10, 10, 5, 5 // // --- , 75 , X , A , // , bButton , xMemo , - , // , bBoton , + , , // , bKnopf , + , , // X , , + , , // , eCamp , - , bBotó maco , <eva layout example3> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example 2 bis layout EVALAYOUT" // // <layout of F> // EVALAYOUT, 15, 15, 5, 5 // // , , X , // 50, bBoton1 , - , - // , bBoton4 , eField , bBoton2 // X , + , xText , + // 50, bBoton3 , - , + <eva layout complet> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example complex layout" // // <layout of F> // EVALAYOUT, 15, 15, 5, 5 // // ---, 80 , X , 110 // , lLabel1 , eEdit1 , - // , lLabel2 , cCombo , lLabel3 // , lLabel4 , xMemo , iLista // , bBoton1 , + , + // , bBoton2 , + , + // X , , + , + // , layOwner , - , + // , , , bBoton4 // // <layout of layOwner> // PANEL, Y, Owner Info // // LayFields // // <layout of LayFields> // EVALAYOUT, 5, 5, 5, 5 // // ---, , X // , lName , eName // , lPhone , ePhone // <eva layout centering> //#gastona# // // <PAINT LAYOUT> // //#javaj# // // <frames> // Fmain, Centering with EvaLayout demo // // <layout of Fmain> // EVA // // , X, A , X // X , // A , , bCentered // X , <eva layout percenting> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // Fmain, Percenting with EvaLayout demo, 300, 300 // // <layout of Fmain> // EVA, 10, 10, 7, 7 // // , X , X , X , X // X , b11 , b13 , - , - // X , b22 , - , b23 , - // X , + , , + , // X , b12 , - , + , // //#data# // // <b11> 25% x 25% // <b13> 75% horizontally 25% vertically // <b22> fifty-fifty // <b12> 50% x 25% y // <b23> half and 3/4 #**FIN_EVA# */ package de.elxala.Eva.layout; import java.util.Vector; import java.util.Hashtable; import java.util.Enumeration; // to traverse the HashTable ... import java.awt.*; import de.elxala.Eva.*; import de.elxala.langutil.*; import de.elxala.zServices.*; /** @author Alejandro Xalabarder @date 11.04.2006 22:32 Example: <pre> import java.awt.*; import javax.swing.*; import de.elxala.Eva.*; import de.elxala.Eva.layout.*; public class sampleEvaLayout { public static void main (String [] aa) { JFrame frame = new JFrame ("sampleEvaLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = frame.getContentPane (); Eva lay = new Eva(); // set margins lay.addLine (new EvaLine ("EvaLayout, 15, 15, 5, 5")); // set grid lay.addLine (new EvaLine ("RxC, , 100 , X ,")); lay.addLine (new EvaLine (" , lname , eName , ,")); lay.addLine (new EvaLine (" , lobserv, xObs , - ,")); lay.addLine (new EvaLine (" X, , + , ,")); pane.setLayout (new EvaLayout(lay)); pane.add ("lname", new JLabel("Name")); pane.add ("lobserv", new JLabel("Notes")); pane.add ("eName", new JTextField()); pane.add ("xObs", new JTextPane()); frame.pack(); frame.setSize (new Dimension (300, 200)); frame.show(); } } </pre> */ public class EvaLayout implements LayoutManager2 { private static logger log = new logger (null, "de.elxala.Eva.EvaLayout", null); //19.10.2010 20:31 // Note : Limits introduced in change (bildID) 11088 on 2010-09-20 01:47:25 // named "FIX problema en layout (LOW LEVEL BUG 2!)" // But today the problem (without limits) cannot be reproduced! (?) // Limits set as aproximation, these can be reviewed and changed // private static int MAX_SIZE_DX = 10000; private static int MAX_SIZE_DY = 10000; protected static final int HEADER_EXPAND = 10; protected static final int HEADER_ORIGINAL = 11; protected static final int HEADER_NUMERIC = 12; protected static final String EXPAND_HORIZONTAL = "-"; protected static final String EXPAND_VERTICAL = "+"; // variables for pre-calculated layout // private boolean isPrecalculated = false; protected int Hmargin; protected int Vmargin; protected int Hgap; protected int Vgap; private int mnCols = -1; // note : this is a cached value and might be call before precalculation! private int mnRows = -1; // note : this is a cached value and might be call before precalculation! private int fijoH = 0; private int fijoV = 0; public int [] HdimMin = new int [0]; public int [] HdimPref = new int [0]; // for preferred instead of minimum public int [] Hpos = new int [0]; public int [] VdimMin = new int [0]; public int [] VdimPref = new int [0]; // for preferred instead of minimum public int [] Vpos = new int [0]; private Eva lay = null; private Hashtable componentHTable = new Hashtable(); protected class widgetInfo { public widgetInfo (String nam, Component com) { name = nam; comp = com; } public String name; // name of the component in the layout array public Component comp; // component info public boolean isLaidOut; // if the component has been found in the layout array // and therefore if indxPos is a valid calculated field // place in the layout array mesured in array indices public int posCol0; // first column that the widget occupies public int posRow0; // first row public int posCol1; // last column public int posRow1; // last row } Vector columnsReparto = new Vector (); Vector rowsReparto = new Vector (); public EvaLayout() { this(new Eva()); } public EvaLayout(Eva layarray) { log.dbg (2, "EvaLayout", "create EvaLayout " + layarray.getName ()); lay = layarray; } /** Switches to another layout : note that the components used in this new layout has to exists (added to the layout using add method) */ public void switchLayout(Eva layarray) { log.dbg (2, "switchLayout", "switch new layout info " + layarray.getName ()); lay = layarray; invalidatePreCalc (); } private int headType (String str) { if (str.length () == 0 || str.equalsIgnoreCase ("a")) return HEADER_ORIGINAL; if (str.equalsIgnoreCase ("x")) return HEADER_EXPAND; return HEADER_NUMERIC; // it should } private void precalculateAll () { if (isPrecalculated) return; log.dbg (2, "precalculateAll", "layout " + lay.getName () + " perform precalculation."); Hmargin = Math.max (0, stdlib.atoi (lay.getValue (0,1))); Vmargin = Math.max (0, stdlib.atoi (lay.getValue (0,2))); Hgap = Math.max (0, stdlib.atoi (lay.getValue (0,3))); Vgap = Math.max (0, stdlib.atoi (lay.getValue (0,4))); log.dbg (4, "precalculateAll", nColumns() + " columns x " + nRows() + " rows"); log.dbg (4, "precalculateAll", "margins xm=" + Hmargin + ", ym=" + Vmargin + ", yg=" + Hgap + ", yg=" + Vgap); mnCols = -1; // reset cached number of cols mnRows = -1; // reset cached number of rows HdimMin = new int [nColumns()]; HdimPref = new int [nColumns()]; Hpos = new int [nColumns()]; VdimMin = new int [nRows()]; VdimPref = new int [nRows()]; Vpos = new int [nRows()]; columnsReparto = new Vector (); rowsReparto = new Vector (); // for all components ... Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); ((widgetInfo) componentHTable.get(key)).isLaidOut = false; } // compute Vdim (Note: it might be precalculated if needed) fijoV = Vmargin; for (int rr = 0; rr < nRows(); rr ++) { String heaRow = rowHeader(rr); int typ = headType(heaRow); int gap = (rr == 0) ? 0: Vgap; if (typ == HEADER_ORIGINAL) { // maximum-minimum of the row VdimPref[rr] = minHeightOfRow(rr, true); VdimMin[rr] = minHeightOfRow(rr, false); log.dbg (2, "precalculateAll", "Adaption... VdimPref[rr] = " + VdimPref[rr]); } else if (typ == HEADER_EXPAND) { rowsReparto.add (new int [] { rr }); // compute later log.dbg (2, "precalculateAll", "Expand... VdimPref[rr] = " + VdimPref[rr]); } else { // indicated size VdimPref[rr] = VdimMin[rr] = stdlib.atoi(heaRow); log.dbg (2, "precalculateAll", "Explicit... VdimPref[rr] = " + VdimPref[rr]); } Vpos[rr] = fijoV + gap; fijoV += VdimPref[rr]; fijoV += gap; } fijoV += Vmargin; log.dbg (2, "precalculateAll", "fijoV = " + fijoV + " Vmargin = " + Vmargin + " Vgap = " + Vgap); //DEBUG .... if (log.isDebugging (2)) { String vertical = "Vertical array (posY/prefHeight/minHeight)"; for (int rr = 0; rr < Vpos.length; rr++) vertical += " " + rr + ") " + Vpos[rr] + "/" + VdimPref[rr] + "/" + VdimMin[rr]; log.dbg (2, "precalculateAll", vertical); } // compute Hdim (Note: it might be precalculated if needed) fijoH = Hmargin; for (int cc = 0; cc < nColumns(); cc ++) { String heaCol = columnHeader(cc); int typ = headType(heaCol); int gap = (cc == 0) ? 0: Hgap; if (typ == HEADER_ORIGINAL) { // maximum-minimum of the column HdimPref[cc] = minWidthOfColumn(cc, true); HdimMin[cc] = minWidthOfColumn(cc, false); } else if (typ == HEADER_EXPAND) columnsReparto.add (new int [] { cc }); // compute later else HdimPref[cc] = HdimMin[cc] = stdlib.atoi(heaCol); // indicated size Hpos[cc] = fijoH + gap; fijoH += HdimPref[cc]; fijoH += gap; } fijoH += Hmargin; log.dbg (2, "precalculateAll", "fijoH = " + fijoH); //DEBUG .... if (log.isDebugging (2)) { String horizontal = "Horizontal array (posX/prefWidth/minWidth)"; for (int cc = 0; cc < Hpos.length; cc++) horizontal += " " + cc + ") " + Hpos[cc] + "/" + HdimPref[cc] + "/" + HdimMin[cc]; log.dbg (2, "precalculateAll", horizontal); } // finding all components in the layout array for (int cc = 0; cc < nColumns(); cc ++) { for (int rr = 0; rr < nRows(); rr ++) { String name = widgetAt(rr, cc); widgetInfo wid = theComponent (name); if (wid == null) continue; // set position x,y wid.posCol0 = cc; wid.posRow0 = rr; // set position x2,y2 int ava = cc; while (ava+1 < nColumns() && widgetAt(rr, ava+1).equals (EXPAND_HORIZONTAL)) ava ++; wid.posCol1 = ava; ava = rr; while (ava+1 < nRows() && widgetAt(ava+1, cc).equals (EXPAND_VERTICAL)) ava ++; wid.posRow1 = ava; wid.isLaidOut = true; //DEBUG .... if (log.isDebugging (2)) { log.dbg (2, "precalculateAll", wid.name + " leftTop (" + wid.posCol0 + ", " + wid.posRow0 + ") rightBottom (" + wid.posCol1 + ", " + wid.posRow1 + ")"); } } } isPrecalculated = true; } protected int nColumns () { // OLD // return Math.max(0, lay.cols(1) - 1); if (mnCols != -1) return mnCols; // has to be calculated, // the maximum n of cols of header or rows // for (int ii = 1; ii < lay.rows (); ii ++) if (mnCols < Math.max(0, lay.cols(ii) - 1)) mnCols = Math.max(0, lay.cols(ii) - 1); mnCols = Math.max(0, mnCols); return mnCols; } protected int nRows () { // OLD // return Math.max(0, lay.rows() - 2); if (mnRows != -1) return mnRows; mnRows = Math.max(0, lay.rows() - 2); return mnRows; } public Eva getEva () { return lay; } public String [] getWidgets () { java.util.Vector vecWidg = new java.util.Vector (); for (int rr = 0; rr < nRows(); rr ++) for (int cc = 0; cc < nColumns(); cc ++) { String name = widgetAt (rr, cc); if (name.length() > 0 && !name.equals(EXPAND_HORIZONTAL) && !name.equals(EXPAND_VERTICAL)) vecWidg.add (name); } // pasarlo a array String [] arrWidg = new String [vecWidg.size ()]; for (int ii = 0; ii < arrWidg.length; ii ++) arrWidg[ii] = (String) vecWidg.get (ii); return arrWidg; } /** * Adds the specified component with the specified name */ public void addLayoutComponent(String name, Component comp) { log.dbg (2, "addLayoutComponent", name + " compName (" + comp.getName () + ")"); componentHTable.put(name, new widgetInfo (name, comp)); isPrecalculated = false; } /** * Removes the specified component from the layout. * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { // componentHTable.remove(comp); } /** * Calculates the preferred size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out */ public Dimension preferredLayoutSize(Container parent) { ///*EXPERIMENT!!!*/invalidatePreCalc (); Dimension di = getLayoutSize(parent, true); log.dbg (2, "preferredLayoutSize", lay.getName() + " preferredLayoutSize (" + di.width + ", " + di.height + ")"); //(o) TODO_javaj_layingOut Problem: preferredLayoutSize //19.04.2009 19:50 Problem: preferredLayoutSize is called when pack and after that no more // layouts data dependent like slider (don't know if horizontal or vertical) have problems // Note: this is not just a problem of EvaLayout but of all layout managers //log.severe ("SEVERINIO!"); return di; } /** * Calculates the minimum size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out */ public Dimension minimumLayoutSize(Container parent) { Dimension di = getLayoutSize(parent, false); log.dbg (2, "minimumLayoutSize", lay.getName() + " minimumLayoutSize (" + di.width + ", " + di.height + ")"); return di; } /** *calculating layout size (minimum or preferred). */ protected Dimension getLayoutSize(Container parent, boolean isPreferred) { log.dbg (2, "getLayoutSize", lay.getName()); precalculateAll (); // In precalculateAll the methods minWidthOfColumn and minHeightOfRow // does not evaluate expandable components since these might use other columns. // But in order to calculate the minimum or preferred total size we need this information. // In these cases we have to calculate following : if the sum of the sizes of the // columns that the component occupies is less that the minimum/preferred size of // the component then we add the difference to the total width // We evaluate this ONLY for those components that could be expanded! // for example // // NO COMPONENT HAS TO COMPONENTS comp1 and comp3 // BE RECALCULED HAS TO BE RECALCULED // --------------------- ------------------------ // grid, 160 , A grid, 160 , X // A , comp1 , - A , comp1 , - // A , comp2 , comp3 X , comp2 , comp3 // int [] extraCol = new int [nColumns ()]; int [] extraRow = new int [nRows ()]; int [] Hdim = isPreferred ? HdimPref: HdimMin; int [] Vdim = isPreferred ? VdimPref: VdimMin; //System.err.println ("PARLANT DE " + lay.getName () + " !!!"); // for all components ... Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { boolean someExpan = false; String key = (String) enu.nextElement(); widgetInfo wi = (widgetInfo) componentHTable.get(key); if (! wi.isLaidOut) continue; Dimension csiz = (isPreferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); log.dbg (2, "getLayoutSize", wi.name + " dim (" + csiz.width + ", " + csiz.height + ")"); // some column expandable ? // someExpan = false; for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) if (headType(columnHeader(cc)) == HEADER_EXPAND) { someExpan = true; break; } if (someExpan) { // sum of all columns that this component occupy int sum = 0; for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) sum += (Hdim[cc] + extraCol[cc]); // distribute it in all columns to be salomonic int resto = csiz.width - sum; if (resto > 0) { if (wi.posCol0 == wi.posCol1) { // System.err.println ("Resto X " + resto + " de " + wi.name + " en la " + wi.posCol0 + " veniendo de csiz.width " + csiz.width + " y sum " + sum + " que repahartimos en " + (1 + wi.posCol1 - wi.posCol0) + " parates tenahamos una estra de " + extraCol[wi.posCol0]); } for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) extraCol[cc] = resto / (1 + wi.posCol1 - wi.posCol0); } } // some row expandable ? // someExpan = false; for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) if (headType(rowHeader(rr)) == HEADER_EXPAND) { someExpan = true; break; } if (someExpan) { // sum of all height (rows) that this component occupy int sum = 0; for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) sum += (Vdim[rr] + extraRow[rr]); // distribute it in all columns to be salomonic int resto = csiz.height - sum; if (resto > 0) { for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) extraRow[rr] = resto / (1 + wi.posRow1 - wi.posRow0); } } } int tot_width = 0; for (int cc = 0; cc < nColumns(); cc ++) { tot_width += (Hdim[cc] + extraCol[cc]); } int tot_height = 0; for (int rr = 0; rr < nRows(); rr ++) { tot_height += Vdim[rr] + extraRow[rr]; } Insets insets = (parent != null) ? parent.getInsets(): new Insets(0,0,0,0); tot_width += Hgap * (nColumns() - 1) + insets.left + insets.right + 2 * Hmargin; tot_height += Vgap * (nRows() - 1) + insets.top + insets.bottom + 2 * Vmargin; log.dbg (2, "getLayoutSize", "returning tot_width " + tot_width + ", tot_height " + tot_height); // System.out.println ("getLayoutSize pref=" + isPreferred + " nos sale (" + tot_width + ", " + tot_height + ")"); return new Dimension (tot_width, tot_height); } private String columnHeader(int ncol) { return lay.getValue(1, ncol + 1).toUpperCase (); } private String rowHeader(int nrow) { return lay.getValue(2 + nrow, 0).toUpperCase (); } private String widgetAt(int nrow, int ncol) { return lay.getValue (nrow + 2, ncol + 1); } private widgetInfo theComponent(String cellName) { if (cellName.length() == 0 || cellName.equals(EXPAND_HORIZONTAL) || cellName.equals(EXPAND_VERTICAL)) return null; widgetInfo wi = (widgetInfo) componentHTable.get(cellName); if (wi == null) log.severe ("theComponent", "Component " + cellName + " not found in the container laying out " + lay.getName () + "!"); return wi; } private int minWidthOfColumn (int ncol, boolean preferred) { // el componente ma's ancho de la columna int maxwidth = 0; for (int rr = 0; rr < nRows(); rr ++) { String name = widgetAt (rr, ncol); widgetInfo wi = theComponent (name); if (wi != null) { if (widgetAt (rr, ncol+1).equals(EXPAND_HORIZONTAL)) continue; // widget occupies more columns so do not compute it Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); maxwidth = Math.max (maxwidth, csiz.width); } } //19.09.2010 Workaround //in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail! return maxwidth > MAX_SIZE_DX ? MAX_SIZE_DX : maxwidth; } private int minHeightOfRow (int nrow, boolean preferred) { // el componente ma's alto de la columna int maxheight = 0; for (int cc = 0; cc < nColumns(); cc ++) { String name = widgetAt (nrow, cc); widgetInfo wi = theComponent (name); if (wi != null) { if (widgetAt (nrow+1, cc).equals(EXPAND_VERTICAL)) continue; // widget occupies more rows so do not compute it Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); maxheight = Math.max (maxheight, csiz.height); } } //19.09.2010 Workaround //in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail! return maxheight > MAX_SIZE_DY ? MAX_SIZE_DY : maxheight; } /** * Lays out the container in the specified container. * @param parent the component which needs to be laid out */ public void layoutContainer(Container parent) { //isPrecalculated = false; if (log.isDebugging(4)) log.dbg (4, "layoutContainer", lay.getName ()); precalculateAll (); synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); //if (log.isDebugging(4)) // log.dbg (4, "layoutContainer", "insets left right =" + insets.left + ", " + insets.right + " top bottom " + insets.top + ", " + insets.bottom); // Total parent dimensions Dimension size = parent.getSize(); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "parent size =" + size.width + ", " + size.height); int repartH = size.width - (insets.left + insets.right) - fijoH; int repartV = size.height - (insets.top + insets.bottom) - fijoV; int [] HextraPos = new int [HdimPref.length]; int [] VextraPos = new int [VdimPref.length]; if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "repartH=" + repartH + " repartV=" + repartV); // repartir H if (columnsReparto.size() > 0) { repartH /= columnsReparto.size(); for (int ii = 0; ii < columnsReparto.size(); ii ++) { int indx = ((int []) columnsReparto.get (ii))[0]; HdimPref[indx] = repartH; for (int res = indx+1; res < nColumns(); res ++) HextraPos[res] += repartH; } } // repartir V if (rowsReparto.size() > 0) { repartV /= rowsReparto.size(); for (int ii = 0; ii < rowsReparto.size(); ii ++) { int indx = ((int []) rowsReparto.get (ii))[0]; VdimPref[indx] = repartV; for (int res = indx+1; res < nRows(); res ++) VextraPos[res] += repartV; } } // // for all components ... for (int ii = 0; ii < componentArray.size(); ii ++) // java.util.Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); widgetInfo wi = (widgetInfo) componentHTable.get(key); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "element [" + key + "]"); // System.out.println ("componente " + wi.name); if (! wi.isLaidOut) continue; // System.out.println (" indices " + wi.posCol0 + " (" + Hpos[wi.posCol0] + " extras " + HextraPos[wi.posCol0] + ")"); int x = Hpos[wi.posCol0] + HextraPos[wi.posCol0]; int y = Vpos[wi.posRow0] + VextraPos[wi.posRow0]; int dx = 0; int dy = 0; //if (log.isDebugging(4)) // log.dbg (4, "SIGUEY", "1) y = " + y + " Vpos[wi.posRow0] = " + Vpos[wi.posRow0] + " VextraPos[wi.posRow0] = " + VextraPos[wi.posRow0]); for (int mm = wi.posCol0; mm <= wi.posCol1; mm ++) { if (mm != wi.posCol0) dx += Hgap; dx += HdimPref[mm]; } for (int mm = wi.posRow0; mm <= wi.posRow1; mm ++) { if (mm != wi.posRow0) dy += Vgap; dy += VdimPref[mm]; } if (x < 0 || y < 0 || dx < 0 || dy < 0) { //Disable this warning because it happens very often when minimizing the window etc //log.warn ("layoutContainer", "component not laid out! [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")"); continue; } wi.comp.setBounds(x, y, dx, dy); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "vi.name [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")"); } } // end synchronized } // LayoutManager2 ///////////////////////////////////////////////////////// /** * This method make no sense in this layout, the constraints are not per component * but per column and rows. Since this method is called when adding components through * the method add(String, Component) we implement it as if constraints were the name */ public void addLayoutComponent(Component comp, Object constraints) { addLayoutComponent((String) constraints, comp); } /** * Returns the maximum size of this component. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Returns the alignment along the x axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentX(Container target) { return 0.5f; } /** * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentY(Container target) { return 0.5f; } /** * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. */ public void invalidateLayout(Container target) { invalidatePreCalc(); } public void invalidatePreCalc() { isPrecalculated = false; } }
wakeupthecat/gastona
pc/src/de/elxala/Eva/layout/EvaLayout.java
Java
gpl-3.0
36,814
pizzasys ======== A system for pizzerias
mntnorv/pizzasys
README.md
Markdown
gpl-3.0
42
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <[email protected]>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h"
emsrc/pycornetto
bin/cornetto-client.py
Python
gpl-3.0
6,265
package tempconv // CToF converts a Celsius temperature to Fahrenheit func CToF(c Celsius) Fahrenheit { return Fahrenheit(c * 9 / 5 + 32) } // FToC converts s Fahrenheit temperature to Celsius func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
ptdecker/gobasics
src/ch02/tempconv/conv.go
GO
gpl-3.0
273
const { nativeImage } = require('electron') const { resolve } = require('path') exports.size16 = nativeImage.createFromPath(resolve(__dirname, '../icon16.png')) exports.size16.setTemplateImage(true)
Gerhut/Meibo
lib/icon.js
JavaScript
gpl-3.0
201
package yio.tro.antiyoy.menu.customizable_list; import com.badlogic.gdx.graphics.g2d.BitmapFont; import yio.tro.antiyoy.gameplay.diplomacy.DiplomaticEntity; import yio.tro.antiyoy.menu.render.AbstractRenderCustomListItem; import yio.tro.antiyoy.menu.render.MenuRender; import yio.tro.antiyoy.menu.scenes.Scenes; import yio.tro.antiyoy.menu.scenes.gameplay.choose_entity.IDipEntityReceiver; import yio.tro.antiyoy.stuff.Fonts; import yio.tro.antiyoy.stuff.GraphicsYio; public class SimpleDipEntityItem extends AbstractSingleLineItem{ public DiplomaticEntity diplomaticEntity; public int backgroundColor; @Override protected BitmapFont getTitleFont() { return Fonts.smallerMenuFont; } @Override protected double getHeight() { return 0.07f * GraphicsYio.height; } @Override protected void onClicked() { Scenes.sceneChooseDiplomaticEntity.onDiplomaticEntityChosen(diplomaticEntity); } public void setDiplomaticEntity(DiplomaticEntity diplomaticEntity) { this.diplomaticEntity = diplomaticEntity; backgroundColor = getGameController().colorsManager.getColorByFraction(diplomaticEntity.fraction); setTitle("" + diplomaticEntity.capitalName); } @Override public AbstractRenderCustomListItem getRender() { return MenuRender.renderSimpleDipEntityItem; } }
yiotro/Antiyoy
core/src/yio/tro/antiyoy/menu/customizable_list/SimpleDipEntityItem.java
Java
gpl-3.0
1,380
// ==++== // // Copyright (C) 2019 Matthias Fussenegger // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // ==--== namespace SimpleZIP_UI.Presentation.View.Model { /// <summary> /// Represents a list box item for the <see cref="MessageDigestPage"/>. /// </summary> public class MessageDigestModel { /// <summary> /// The name of the file whose hash value is to be displayed. /// </summary> public string FileName { get; } /// <summary> /// The physical location (full path) of the file. /// </summary> public string Location { get; } /// <summary> /// The calculated hash value of the file. /// </summary> public string HashValue { get; internal set; } /// <summary> /// Displays the location in the model if set to true. /// </summary> public BooleanModel IsDisplayLocation { get; set; } = false; /// <summary> /// Sets the color brush of the <see cref="FileName"/>. /// </summary> public SolidColorBrushModel FileNameColorBrush { get; set; } /// <summary> /// Constructs a new model for the ListBox in <see cref="MessageDigestPage"/>. /// </summary> /// <param name="fileName">The name of the file to be displayed.</param> /// <param name="location">The location of the file to be displayed.</param> /// <param name="hashValue">The hash value of the file to be displayed.</param> public MessageDigestModel(string fileName, string location, string hashValue) { FileName = fileName; Location = location; HashValue = hashValue; } } }
turbolocust/SimpleZIP
SimpleZIP_UI/Presentation/View/Model/MessageDigestModel.cs
C#
gpl-3.0
2,339
#Region "Microsoft.VisualBasic::556146eee1abd2c1147f33071a728ef4, CLI_tools\eggHTS\CLI\Samples\LabelFree.vb" ' Author: ' ' asuka ([email protected]) ' xie ([email protected]) ' xieguigang ([email protected]) ' ' Copyright (c) 2018 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program. If not, see <http://www.gnu.org/licenses/>. ' /********************************************************************************/ ' Summaries: ' Module CLI ' ' Function: ExtractMatrix, LabelFreeMatrix, LabelFreeMatrixSplit, labelFreeTtest, MajorityProteinIDs ' matrixByInternal, matrixByUniprot, MatrixColRenames, MatrixNormalize, PerseusStatics ' PerseusTable ' ' ' /********************************************************************************/ #End Region Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic.CommandLine Imports Microsoft.VisualBasic.CommandLine.Reflection Imports Microsoft.VisualBasic.Data.csv Imports Microsoft.VisualBasic.Data.csv.IO Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Math.DataFrame.Impute Imports Microsoft.VisualBasic.MIME.Office.Excel Imports Microsoft.VisualBasic.Scripting.Runtime Imports Microsoft.VisualBasic.Text Imports SMRUCC.genomics.Analysis.HTS.Proteomics Imports SMRUCC.genomics.GCModeller.Workbench.ExperimentDesigner Imports csv = Microsoft.VisualBasic.Data.csv.IO.File Partial Module CLI ''' <summary> ''' 将perseus软件的输出转换为csv文档并且导出uniprot编号以方便进行注释 ''' </summary> ''' <param name="args"></param> ''' <returns></returns> <ExportAPI("/Perseus.Table")> <Usage("/Perseus.Table /in <proteinGroups.txt> [/out <out.csv>]")> <Group(CLIGroups.Samples_CLI)> Public Function PerseusTable(args As CommandLine) As Integer Dim [in] As String = args("/in") Dim out As String = args.GetValue("/out", [in].TrimSuffix & ".csv") Dim data As Perseus() = [in].LoadTsv(Of Perseus) Dim idlist As String() = data _ .Select(Function(prot) prot.ProteinIDs) _ .IteratesALL _ .Distinct _ .ToArray Dim uniprotIDs$() = idlist _ .Select(Function(s) s.Split("|"c, ":"c)(1)) _ .Distinct _ .ToArray Call idlist.SaveTo(out.TrimSuffix & ".proteinIDs.txt") Call uniprotIDs.SaveTo(out.TrimSuffix & ".uniprotIDs.txt") Return data.SaveTo(out).CLICode End Function <ExportAPI("/Perseus.Stat")> <Usage("/Perseus.Stat /in <proteinGroups.txt> [/out <out.csv>]")> <Group(CLIGroups.Samples_CLI)> Public Function PerseusStatics(args As CommandLine) As Integer Dim in$ = args("/in") Dim out As String = args.GetValue("/out", [in].TrimSuffix & ".perseus.Stat.csv") Dim data As Perseus() = [in].LoadTsv(Of Perseus) Dim csv As New csv Call csv.AppendLine({"MS/MS", CStr(Perseus.TotalMSDivideMS(data))}) Call csv.AppendLine({"Peptides", CStr(Perseus.TotalPeptides(data))}) Call csv.AppendLine({"ProteinGroups", CStr(data.Length)}) Return csv.Save(out, Encodings.ASCII).CLICode End Function <ExportAPI("/Perseus.MajorityProteinIDs")> <Usage("/Perseus.MajorityProteinIDs /in <table.csv> [/out <out.txt>]")> <Description("Export the uniprot ID list from ``Majority Protein IDs`` row and generates a text file for batch search of the uniprot database.")> Public Function MajorityProteinIDs(args As CommandLine) As Integer With args <= "/in" Dim out$ = (args <= "/out") Or (.TrimSuffix & "-uniprotID.txt").AsDefault Dim table As Perseus() = .LoadCsv(Of Perseus) Dim major$() = table _ .Select(Function(protein) Return protein.Majority_proteinIDs End Function) _ .IteratesALL _ .Distinct _ .ToArray Return major _ .FlushAllLines(out) _ .CLICode End With End Function <ExportAPI("/labelFree.matrix")> <Usage("/labelFree.matrix /in <*.csv/*.xlsx> [/sheet <default=proteinGroups> /intensity /uniprot <uniprot.Xml> /organism <scientificName> /out <out.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function LabelFreeMatrix(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim isIntensity As Boolean = args("/intensity") Dim uniprot$ = args("/uniprot") Dim organism$ = args("/organism") Dim out$ = args("/out") Or $"{[in].TrimSuffix}.{If(isIntensity, "intensity", "iBAQ")}.csv" Dim table As EntityObject() = EntityObject _ .LoadDataSet([in].ReadTableAuto(args("/sheet") Or "proteinGroups")) _ .ToArray If uniprot.FileExists Then Return table.matrixByUniprot(uniprot, organism, isIntensity) _ .SaveTo(out) _ .CLICode Else ' 没有额外的信息,则尝试使用内部的注释信息来完成 Return table.matrixByInternal(isIntensity) _ .SaveTo(out) _ .CLICode End If End Function <Extension> Private Function matrixByInternal(table As EntityObject(), isIntensity As Boolean) As DataSet() Dim getID As Func(Of EntityObject, String) If table(0).Properties.ContainsKey("Fasta headers") Then getID = Function(x) Dim headerID = x("Fasta headers").Split("|"c).ElementAtOrDefault(1) If headerID.StringEmpty Then Return x.ID.StringSplit("\s*;\s*")(0) Else Return headerID End If End Function Else getID = Function(x) x.ID.StringSplit("\s*;\s*")(0) End If Return table.ExtractMatrix(getID, isIntensity) End Function <Extension> Private Function ExtractMatrix(table As EntityObject(), getID As Func(Of EntityObject, String), isIntensity As Boolean) As DataSet() Dim keyPrefix$ = "iBAQ " Or "Intensity ".When(isIntensity) Dim projectDataSet = Function(x As EntityObject) As DataSet Dim id As String = getID(x) Dim data = x.Properties _ .Where(Function(c) Return InStr(c.Key, keyPrefix) > 0 End Function) _ .ToDictionary _ .AsNumeric Return New DataSet With { .ID = id, .Properties = data } End Function Return table.Select(projectDataSet).ToArray End Function <Extension> Private Function matrixByUniprot(table As EntityObject(), xml$, organism$, isIntensity As Boolean) As DataSet() Throw New NotImplementedException End Function ''' <summary> ''' 计算差异蛋白 ''' </summary> ''' <param name="args"></param> ''' <returns></returns> <ExportAPI("/labelFree.t.test")> <Usage("/labelFree.t.test /in <matrix.csv> /sampleInfo <sampleInfo.csv> /control <groupName> /treatment <groupName> [/significant <t.test/AB, default=t.test> /level <default=1.5> /p.value <default=0.05> /FDR <default=0.05> /out <out.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function labelFreeTtest(args As CommandLine) As Integer Dim data As DataSet() = DataSet.LoadDataSet(args <= "/in") _ .SimulateMissingValues(byRow:=False, infer:=InferMethods.Min) _ .TotalSumNormalize _ .ToArray Dim level# = args.GetValue("/level", 1.5) Dim pvalue# = args.GetValue("/p.value", 0.05) Dim FDR# = args.GetValue("/FDR", 0.05) Dim out$ = args.GetValue("/out", (args <= "/in").TrimSuffix & ".log2FC.t.test.csv") Dim sampleInfo As SampleInfo() = (args <= "/sampleInfo").LoadCsv(Of SampleInfo) Dim designer As New AnalysisDesigner With { .Controls = args <= "/control", .Treatment = args <= "/treatment" } Dim usingSignificantAB As Boolean = (args("/significant") Or "t.test") = "AB" Dim DEPs As DEP_iTraq() = data.logFCtest(designer, sampleInfo, level, pvalue, FDR, significantA:=usingSignificantAB) Return DEPs _ .ToArray _ .SaveDataSet(out) _ .CLICode End Function <ExportAPI("/labelFree.matrix.split")> <Usage("/labelFree.matrix.split /in <matrix.csv> /sampleInfo <sampleInfo.csv> /designer <analysis_designer.csv> [/out <directory>]")> <Group(CLIGroups.LabelFreeTool)> Public Function LabelFreeMatrixSplit(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim out$ = args("/out") Or $"{[in].TrimSuffix}.matrix/" Dim matrix As DataSet() = DataSet.LoadDataSet([in]).ToArray Dim sampleInfo As SampleInfo() = (args <= "/sampleInfo").LoadCsv(Of SampleInfo) Dim designer As AnalysisDesigner() = (args <= "/designer").LoadCsv(Of AnalysisDesigner) For Each analysis As AnalysisDesigner In designer Dim controls = sampleInfo.SampleIDs(analysis.Controls) Dim treatments = sampleInfo.SampleIDs(analysis.Treatment) Dim subMatrix As DataSet() = Iterator Function(projection As String()) As IEnumerable(Of DataSet) For Each protein In matrix Yield protein.SubSet(projection) Next End Function(controls + treatments).ToArray Dim controlGroup = sampleInfo.TakeGroup(analysis.Controls).AsList Dim treatmentGroup As SampleInfo() = sampleInfo.TakeGroup(analysis.Treatment) Names(subMatrix) = controlGroup + treatmentGroup Call subMatrix.SaveTo($"{out}/{analysis.Title}.csv") Next Return 0 End Function <ExportAPI("/names")> <Usage("/names /in <matrix.csv> /sampleInfo <sampleInfo.csv> [/out <out.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function MatrixColRenames(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim out$ = args("/out") Or $"{[in].TrimSuffix}.sample_name.csv" Dim matrix As DataSet() = DataSet.LoadDataSet([in]).ToArray Dim sampleInfo As SampleInfo() = (args <= "/sampleInfo").LoadCsv(Of SampleInfo) Names(matrix) = sampleInfo Return matrix.SaveTo(out).CLICode End Function <ExportAPI("/Matrix.Normalization")> <Usage("/Matrix.Normalization /in <matrix.csv> /infer <min/avg, default=min> [/out <normalized.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function MatrixNormalize(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim infer$ = args("/infer") Or "min" Dim out$ = args("/out") Or $"{[in].TrimSuffix}.normalized.csv" Dim matrix As DataSet() = DataSet.LoadDataSet([in]).ToArray Dim method As InferMethods If infer.TextEquals("min") Then method = InferMethods.Min Else method = InferMethods.Average End If matrix = matrix _ .SimulateMissingValues(byRow:=False, infer:=method) _ .TotalSumNormalize _ .ToArray Return matrix.SaveTo(out).CLICode End Function End Module
xieguigang/GCModeller
src/GCModeller/CLI_tools/eggHTS/CLI/Samples/LabelFree.vb
Visual Basic
gpl-3.0
12,560