repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
cmsdaq/hltd
lib/SOAPpy-py3-0.52.24/tests/Bug916265.py
839
""" Check handing of unicode. """ import sys sys.path.insert(1, "..") from SOAPpy import * # Uncomment to see outgoing HTTP headers and SOAP and incoming #Config.debug = 1 #Config.dumpHeadersIn = 1 #Config.dumpSOAPIn = 1 #Config.dumpSOAPOut = 1 # ask for returned SOAP responses to be converted to basic python types Config.simplify_objects = 0 #Config.BuildWithNoType = 1 #Config.BuildWithNoNamespacePrefix = 1 server = SOAPProxy("http://localhost:9900/") x = 'uMOO' # Single unicode string y = server.echo_simple((x,)) assert( x==y[0] ) x = ['uMoo1','uMoo2'] # array of unicode strings y = server.echo_simple(x) assert( x[0] == y[0] ) assert( x[1] == y[1] ) x = { 'A':1, 'B':'B', 'C':'C', 'D':'D' } y = server.echo_simple(x) for key in list(x.keys()): assert( x[key] == y[0][key] ) print("Success")
lgpl-3.0
Allors/allors.testing.webforms
Allors.Testing.Webforms.Tests.WebApplication/CheckBoxListPage.aspx.designer.cs
2087
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Allors.Testing.Webforms.Tests { public partial class CheckBoxListPage { /// <summary> /// form control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form; /// <summary> /// CheckBoxList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBoxList CheckBoxList; /// <summary> /// Button control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button; /// <summary> /// AutoPostBackCheckBoxList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBoxList AutoPostBackCheckBoxList; /// <summary> /// Label control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label; } }
lgpl-3.0
gchq/stroom-stats
stroom-stats-service/src/test/java/stroom/stats/schema/SerialisationTest.java
3031
/* * Copyright 2017 Crown Copyright * * This file is part of Stroom-Stats. * * Stroom-Stats 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. * * Stroom-Stats 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 Stroom-Stats. If not, see <http://www.gnu.org/licenses/>. */ package stroom.stats.schema; import org.junit.Test; import stroom.stats.schema.v4.Statistics; import stroom.stats.schema.v4.StatisticsMarshaller; import javax.xml.bind.JAXBException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class SerialisationTest { private final String RESOURCES_DIR = "src/test/resources"; private final String PACKAGE_NAME = "/stroom/stats/schema/"; private final String EXAMPLE_XML_01 = RESOURCES_DIR + PACKAGE_NAME + "SerialisationTest_testDererialisation.xml"; private final String STATISTICS_FROM_STROOM_01 = RESOURCES_DIR + PACKAGE_NAME + "StatisticsFromStroom_01.xml"; private final StatisticsMarshaller statisticsMarshaller; public SerialisationTest() { this.statisticsMarshaller = new StatisticsMarshaller(); } @Test public void testDeserialisation() throws IOException, JAXBException { String xmlStr = new String(Files.readAllBytes(Paths.get(EXAMPLE_XML_01)), StandardCharsets.UTF_8); Statistics statistics = statisticsMarshaller.unMarshallFromXml(xmlStr); // Check the number of stats is right assertThat(statistics.getStatistic().size(), equalTo(3)); // Check some other things assertThat(statistics.getStatistic().get(0).getCount(), equalTo(2l)); assertThat(statistics.getStatistic().get(1).getCount(), equalTo(1l)); assertThat(statistics.getStatistic().get(2).getCount(), equalTo(null)); assertThat(statistics.getStatistic().get(2).getValue(), equalTo(99.9)); assertThat(statistics.getStatistic().get(0).getTags().getTag().get(0).getName(), equalTo("department")); assertThat(statistics.getStatistic().get(0).getTags().getTag().get(1).getValue(), equalTo("jbloggs")); } @Test public void testPostStatisticsFromStroom_01() throws JAXBException, IOException { String fileString = new String(Files.readAllBytes(Paths.get(STATISTICS_FROM_STROOM_01))); Statistics statistics = statisticsMarshaller.unMarshallFromXml(fileString); assertThat(statistics.getStatistic().size(), equalTo(99)); } }
lgpl-3.0
rsksmart/rskj
rskj-core/src/main/java/org/ethereum/core/BlockHeader.java
23188
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>) * * This program 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.core; import co.rsk.config.RskMiningConstants; import co.rsk.core.BlockDifficulty; import co.rsk.core.Coin; import co.rsk.core.RskAddress; import co.rsk.crypto.Keccak256; import co.rsk.util.ListArrayUtil; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import org.ethereum.crypto.HashUtil; import org.ethereum.util.RLP; import org.ethereum.util.Utils; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import static java.lang.System.arraycopy; import static org.ethereum.crypto.HashUtil.EMPTY_TRIE_HASH; import static org.ethereum.util.ByteUtil.toHexStringOrEmpty; /** * Block header is a value object containing * the basic information of a block */ public class BlockHeader { private static final int HASH_FOR_MERGED_MINING_PREFIX_LENGTH = 20; private static final int FORK_DETECTION_DATA_LENGTH = 12; private static final int UMM_LEAVES_LENGTH = 20; /* The SHA3 256-bit hash of the parent block, in its entirety */ private final byte[] parentHash; /* The SHA3 256-bit hash of the uncles list portion of this block */ private final byte[] unclesHash; /* The 160-bit address to which all fees collected from the * successful mining of this block be transferred; formally */ private final RskAddress coinbase; /* The SHA3 256-bit hash of the root node of the state trie, * after all transactions are executed and finalisations applied */ private byte[] stateRoot; /* The SHA3 256-bit hash of the root node of the trie structure * populated with each transaction in the transaction * list portion, the trie is populate by [key, val] --> [rlp(index), rlp(tx_recipe)] * of the block */ private byte[] txTrieRoot; /* The SHA3 256-bit hash of the root node of the trie structure * populated with each transaction recipe in the transaction recipes * list portion, the trie is populate by [key, val] --> [rlp(index), rlp(tx_recipe)] * of the block */ private byte[] receiptTrieRoot; /* The bloom filter for the logs of the block */ private byte[] logsBloom; /** * A scalar value corresponding to the difficulty level of this block. * This can be calculated from the previous block’s difficulty level * and the timestamp. */ private BlockDifficulty difficulty; /* A scalar value equalBytes to the reasonable output of Unix's time() * at this block's inception */ private final long timestamp; /* A scalar value equalBytes to the number of ancestor blocks. * The genesis block has a number of zero */ private final long number; /* A scalar value equalBytes to the current limit of gas expenditure per block */ private final byte[] gasLimit; /* A scalar value equalBytes to the total gas used in transactions in this block */ private long gasUsed; /* A scalar value equalBytes to the total paid fees in transactions in this block */ private Coin paidFees; /* An arbitrary byte array containing data relevant to this block. * With the exception of the genesis block, this must be 32 bytes or fewer */ private final byte[] extraData; /* The 80-byte bitcoin block header for merged mining */ private byte[] bitcoinMergedMiningHeader; /* The bitcoin merkle proof of coinbase tx for merged mining */ private byte[] bitcoinMergedMiningMerkleProof; /* The bitcoin protobuf serialized coinbase tx for merged mining */ private byte[] bitcoinMergedMiningCoinbaseTransaction; private byte[] miningForkDetectionData; private final byte[] ummRoot; /** * The mgp for a tx to be included in the block. */ private final Coin minimumGasPrice; private final int uncleCount; /* Indicates if this block header cannot be changed */ private volatile boolean sealed; /* Holds calculated block hash */ private Keccak256 hash; /* Indicates if the block was mined according to RSKIP-92 rules */ private final boolean useRskip92Encoding; /* Indicates if Block hash for merged mining should have the format described in RSKIP-110 */ private final boolean includeForkDetectionData; public BlockHeader(byte[] parentHash, byte[] unclesHash, RskAddress coinbase, byte[] stateRoot, byte[] txTrieRoot, byte[] receiptTrieRoot, byte[] logsBloom, BlockDifficulty difficulty, long number, byte[] gasLimit, long gasUsed, long timestamp, byte[] extraData, Coin paidFees, byte[] bitcoinMergedMiningHeader, byte[] bitcoinMergedMiningMerkleProof, byte[] bitcoinMergedMiningCoinbaseTransaction, byte[] mergedMiningForkDetectionData, Coin minimumGasPrice, int uncleCount, boolean sealed, boolean useRskip92Encoding, boolean includeForkDetectionData, byte[] ummRoot) { this.parentHash = parentHash; this.unclesHash = unclesHash; this.coinbase = coinbase; this.stateRoot = stateRoot; this.txTrieRoot = txTrieRoot; this.receiptTrieRoot = receiptTrieRoot; this.logsBloom = logsBloom; this.difficulty = difficulty; this.number = number; this.gasLimit = gasLimit; this.gasUsed = gasUsed; this.timestamp = timestamp; this.extraData = extraData; this.minimumGasPrice = minimumGasPrice; this.uncleCount = uncleCount; this.paidFees = paidFees; this.bitcoinMergedMiningHeader = bitcoinMergedMiningHeader; this.bitcoinMergedMiningMerkleProof = bitcoinMergedMiningMerkleProof; this.bitcoinMergedMiningCoinbaseTransaction = bitcoinMergedMiningCoinbaseTransaction; this.miningForkDetectionData = Arrays.copyOf(mergedMiningForkDetectionData, mergedMiningForkDetectionData.length); this.sealed = sealed; this.useRskip92Encoding = useRskip92Encoding; this.includeForkDetectionData = includeForkDetectionData; this.ummRoot = ummRoot != null ? Arrays.copyOf(ummRoot, ummRoot.length) : null; } @VisibleForTesting public boolean isSealed() { return this.sealed; } public void seal() { this.sealed = true; } public boolean isGenesis() { return this.getNumber() == Genesis.NUMBER; } public Keccak256 getParentHash() { return new Keccak256(parentHash); } public int getUncleCount() { return uncleCount; } public byte[] getUnclesHash() { return unclesHash; } public RskAddress getCoinbase() { return this.coinbase; } public byte[] getStateRoot() { return stateRoot; } public void setStateRoot(byte[] stateRoot) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter state root"); } this.hash = null; this.stateRoot = stateRoot; } public byte[] getTxTrieRoot() { return txTrieRoot; } public void setReceiptsRoot(byte[] receiptTrieRoot) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter receipts root"); } this.hash = null; this.receiptTrieRoot = receiptTrieRoot; } public byte[] getReceiptsRoot() { return receiptTrieRoot; } public void setTransactionsRoot(byte[] stateRoot) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter transactions root"); } this.hash = null; this.txTrieRoot = stateRoot; } public byte[] getLogsBloom() { return logsBloom; } public BlockDifficulty getDifficulty() { // some blocks have zero encoded as null, but if we altered the internal field then re-encoding the value would // give a different value than the original. if (difficulty == null) { return BlockDifficulty.ZERO; } return difficulty; } public void setDifficulty(BlockDifficulty difficulty) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter difficulty"); } this.hash = null; this.difficulty = difficulty; } public long getTimestamp() { return timestamp; } public long getNumber() { return number; } public byte[] getGasLimit() { return gasLimit; } public long getGasUsed() { return gasUsed; } public void setPaidFees(Coin paidFees) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter paid fees"); } this.hash = null; this.paidFees = paidFees; } public Coin getPaidFees() { return this.paidFees; } public void setGasUsed(long gasUsed) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter gas used"); } this.hash = null; this.gasUsed = gasUsed; } public byte[] getExtraData() { return extraData; } public void setLogsBloom(byte[] logsBloom) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter logs bloom"); } this.hash = null; this.logsBloom = logsBloom; } public Keccak256 getHash() { if (this.hash == null) { this.hash = new Keccak256(HashUtil.keccak256(getEncoded())); } return this.hash; } public byte[] getFullEncoded() { // the encoded block header must include all fields, even the bitcoin PMT and coinbase which are not used for // calculating RSKIP92 block hashes return this.getEncoded(true, true); } public byte[] getEncoded() { // the encoded block header used for calculating block hashes including RSKIP92 return this.getEncoded(true, !useRskip92Encoding); } @Nullable public Coin getMinimumGasPrice() { return this.minimumGasPrice; } public byte[] getEncoded(boolean withMergedMiningFields, boolean withMerkleProofAndCoinbase) { byte[] parentHash = RLP.encodeElement(this.parentHash); byte[] unclesHash = RLP.encodeElement(this.unclesHash); byte[] coinbase = RLP.encodeRskAddress(this.coinbase); byte[] stateRoot = RLP.encodeElement(this.stateRoot); if (txTrieRoot == null) { this.txTrieRoot = EMPTY_TRIE_HASH; } byte[] txTrieRoot = RLP.encodeElement(this.txTrieRoot); if (receiptTrieRoot == null) { this.receiptTrieRoot = EMPTY_TRIE_HASH; } byte[] receiptTrieRoot = RLP.encodeElement(this.receiptTrieRoot); byte[] logsBloom = RLP.encodeElement(this.logsBloom); byte[] difficulty = encodeBlockDifficulty(this.difficulty); byte[] number = RLP.encodeBigInteger(BigInteger.valueOf(this.number)); byte[] gasLimit = RLP.encodeElement(this.gasLimit); byte[] gasUsed = RLP.encodeBigInteger(BigInteger.valueOf(this.gasUsed)); byte[] timestamp = RLP.encodeBigInteger(BigInteger.valueOf(this.timestamp)); byte[] extraData = RLP.encodeElement(this.extraData); byte[] paidFees = RLP.encodeCoin(this.paidFees); byte[] mgp = RLP.encodeSignedCoinNonNullZero(this.minimumGasPrice); List<byte[]> fieldToEncodeList = Lists.newArrayList(parentHash, unclesHash, coinbase, stateRoot, txTrieRoot, receiptTrieRoot, logsBloom, difficulty, number, gasLimit, gasUsed, timestamp, extraData, paidFees, mgp); byte[] uncleCount = RLP.encodeBigInteger(BigInteger.valueOf(this.uncleCount)); fieldToEncodeList.add(uncleCount); if (this.ummRoot != null) { fieldToEncodeList.add(RLP.encodeElement(this.ummRoot)); } if (withMergedMiningFields && hasMiningFields()) { byte[] bitcoinMergedMiningHeader = RLP.encodeElement(this.bitcoinMergedMiningHeader); fieldToEncodeList.add(bitcoinMergedMiningHeader); if (withMerkleProofAndCoinbase) { byte[] bitcoinMergedMiningMerkleProof = RLP.encodeElement(this.bitcoinMergedMiningMerkleProof); fieldToEncodeList.add(bitcoinMergedMiningMerkleProof); byte[] bitcoinMergedMiningCoinbaseTransaction = RLP.encodeElement(this.bitcoinMergedMiningCoinbaseTransaction); fieldToEncodeList.add(bitcoinMergedMiningCoinbaseTransaction); } } return RLP.encodeList(fieldToEncodeList.toArray(new byte[][]{})); } /** * This is here to override specific non-minimal instances such as the mainnet Genesis */ protected byte[] encodeBlockDifficulty(BlockDifficulty difficulty) { return RLP.encodeBlockDifficulty(difficulty); } // Warning: This method does not use the object's attributes public static byte[] getUnclesEncodedEx(List<BlockHeader> uncleList) { byte[][] unclesEncoded = new byte[uncleList.size()][]; int i = 0; for (BlockHeader uncle : uncleList) { unclesEncoded[i] = uncle.getFullEncoded(); ++i; } return RLP.encodeList(unclesEncoded); } public boolean hasMiningFields() { if (this.bitcoinMergedMiningCoinbaseTransaction != null && this.bitcoinMergedMiningCoinbaseTransaction.length > 0) { return true; } if (this.bitcoinMergedMiningHeader != null && this.bitcoinMergedMiningHeader.length > 0) { return true; } if (this.bitcoinMergedMiningMerkleProof != null && this.bitcoinMergedMiningMerkleProof.length > 0) { return true; } return false; } public static byte[] getUnclesEncoded(List<BlockHeader> uncleList) { byte[][] unclesEncoded = new byte[uncleList.size()][]; int i = 0; for (BlockHeader uncle : uncleList) { unclesEncoded[i] = uncle.getFullEncoded(); ++i; } return RLP.encodeList(unclesEncoded); } public String toString() { return toStringWithSuffix("\n"); } private String toStringWithSuffix(final String suffix) { StringBuilder toStringBuff = new StringBuilder(); toStringBuff.append(" parentHash=").append(toHexStringOrEmpty(parentHash)).append(suffix); toStringBuff.append(" unclesHash=").append(toHexStringOrEmpty(unclesHash)).append(suffix); toStringBuff.append(" coinbase=").append(coinbase).append(suffix); toStringBuff.append(" stateRoot=").append(toHexStringOrEmpty(stateRoot)).append(suffix); toStringBuff.append(" txTrieHash=").append(toHexStringOrEmpty(txTrieRoot)).append(suffix); toStringBuff.append(" receiptsTrieHash=").append(toHexStringOrEmpty(receiptTrieRoot)).append(suffix); toStringBuff.append(" difficulty=").append(difficulty).append(suffix); toStringBuff.append(" number=").append(number).append(suffix); toStringBuff.append(" gasLimit=").append(toHexStringOrEmpty(gasLimit)).append(suffix); toStringBuff.append(" gasUsed=").append(gasUsed).append(suffix); toStringBuff.append(" timestamp=").append(timestamp).append(" (").append(Utils.longToDateTime(timestamp)).append(")").append(suffix); toStringBuff.append(" extraData=").append(toHexStringOrEmpty(extraData)).append(suffix); toStringBuff.append(" minGasPrice=").append(minimumGasPrice).append(suffix); return toStringBuff.toString(); } public String toFlatString() { return toStringWithSuffix(""); } public byte[] getBitcoinMergedMiningHeader() { return bitcoinMergedMiningHeader; } public void setBitcoinMergedMiningHeader(byte[] bitcoinMergedMiningHeader) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter bitcoin merged mining header"); } this.hash = null; this.bitcoinMergedMiningHeader = bitcoinMergedMiningHeader; } public byte[] getBitcoinMergedMiningMerkleProof() { return bitcoinMergedMiningMerkleProof; } public void setBitcoinMergedMiningMerkleProof(byte[] bitcoinMergedMiningMerkleProof) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter bitcoin merged mining merkle proof"); } this.hash = null; this.bitcoinMergedMiningMerkleProof = bitcoinMergedMiningMerkleProof; } public byte[] getBitcoinMergedMiningCoinbaseTransaction() { return bitcoinMergedMiningCoinbaseTransaction; } public void setBitcoinMergedMiningCoinbaseTransaction(byte[] bitcoinMergedMiningCoinbaseTransaction) { /* A sealed block header is immutable, cannot be changed */ if (this.sealed) { throw new SealedBlockHeaderException("trying to alter bitcoin merged mining coinbase transaction"); } this.hash = null; this.bitcoinMergedMiningCoinbaseTransaction = bitcoinMergedMiningCoinbaseTransaction; } public String getPrintableHashForMergedMining() { return HashUtil.toPrintableHash(getHashForMergedMining()); } public boolean isUMMBlock() { return this.ummRoot != null && this.ummRoot.length != 0; } public byte[] getHashForMergedMining() { byte[] hashForMergedMining = this.getBaseHashForMergedMining(); if (includeForkDetectionData) { byte[] mergedMiningForkDetectionData = hasMiningFields() ? getMiningForkDetectionData() : miningForkDetectionData; arraycopy( mergedMiningForkDetectionData, 0, hashForMergedMining, HASH_FOR_MERGED_MINING_PREFIX_LENGTH, FORK_DETECTION_DATA_LENGTH ); } return hashForMergedMining; } private byte[] getHashRootForMergedMining(byte[] leftHash) { if (ummRoot.length != UMM_LEAVES_LENGTH){ throw new IllegalStateException( String.format("UMM Root length must be either 0 or 20. Found: %d", ummRoot.length) ); } byte[] leftRight = Arrays.copyOf(leftHash, leftHash.length + ummRoot.length); arraycopy(ummRoot, 0, leftRight, leftHash.length, ummRoot.length); byte[] root256 = HashUtil.keccak256(leftRight); return root256; } public String getPrintableHash() { return HashUtil.toPrintableHash(getHash().getBytes()); } public String getParentPrintableHash() { return HashUtil.toPrintableHash(getParentHash().getBytes()); } public byte[] getMiningForkDetectionData() { if(includeForkDetectionData) { if (hasMiningFields() && miningForkDetectionData.length == 0) { byte[] hashForMergedMining = getBaseHashForMergedMining(); byte[] coinbaseTransaction = getBitcoinMergedMiningCoinbaseTransaction(); byte[] mergeMiningTagPrefix = Arrays.copyOf(RskMiningConstants.RSK_TAG, RskMiningConstants.RSK_TAG.length + HASH_FOR_MERGED_MINING_PREFIX_LENGTH); arraycopy(hashForMergedMining, 0, mergeMiningTagPrefix, RskMiningConstants.RSK_TAG.length, HASH_FOR_MERGED_MINING_PREFIX_LENGTH); int position = ListArrayUtil.lastIndexOfSubList(coinbaseTransaction, mergeMiningTagPrefix); if (position == -1) { throw new IllegalStateException( String.format("Mining fork detection data could not be found. Header: %s", getPrintableHash()) ); } int from = position + RskMiningConstants.RSK_TAG.length + HASH_FOR_MERGED_MINING_PREFIX_LENGTH; int to = from + FORK_DETECTION_DATA_LENGTH; if (coinbaseTransaction.length < to) { throw new IllegalStateException( String.format( "Invalid fork detection data length. Expected: %d. Got: %d. Header: %s", FORK_DETECTION_DATA_LENGTH, coinbaseTransaction.length - from, getPrintableHash() ) ); } miningForkDetectionData = Arrays.copyOfRange(coinbaseTransaction, from, to); } return Arrays.copyOf(miningForkDetectionData, miningForkDetectionData.length); } return new byte[0]; } /** * Compute the base hash for merged mining, taking into account whether the block is a umm block. * This base hash is later modified to include the forkdetectiondata in its last 12 bytes * * @return The computed hash for merged mining */ private byte[] getBaseHashForMergedMining() { byte[] encodedBlock = getEncoded(false, false); byte[] hashForMergedMining = HashUtil.keccak256(encodedBlock); if (isUMMBlock()) { byte[] leftHash = Arrays.copyOfRange(hashForMergedMining, 0, UMM_LEAVES_LENGTH); hashForMergedMining = getHashRootForMergedMining(leftHash); } return hashForMergedMining; } public boolean isParentOf(BlockHeader header) { return this.getHash().equals(header.getParentHash()); } public byte[] getUmmRoot() { return ummRoot != null ? Arrays.copyOf(ummRoot, ummRoot.length) : null; } }
lgpl-3.0
kveratis/GameCode4
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/wxLua/modules/wxlua/src/wxlcallb.cpp
13805
///////////////////////////////////////////////////////////////////////////// // Name: wxlcallb.cpp // Purpose: wxLuaEventCallback and wxLuaWinDestroyCallback // Author: Francis Irving, John Labenski // Created: 11/05/2002 // Copyright: (c) 2002 Creature Labs. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif // WX_PRECOMP #include "wxlua/include/wxlcallb.h" //----------------------------------------------------------------------------- // wxLuaEventCallback //----------------------------------------------------------------------------- IMPLEMENT_ABSTRACT_CLASS(wxLuaEventCallback, wxObject) wxLuaEventCallback::wxLuaEventCallback() : m_luafunc_ref(0), //m_wxlState(wxNullLuaState), m_evtHandler(NULL), m_id(wxID_ANY), m_last_id(wxID_ANY), m_wxlBindEvent(NULL) { } wxLuaEventCallback::~wxLuaEventCallback() { // Remove the reference to the Lua function that we call if (m_wxlState.Ok()) { m_wxlState.wxluaR_Unref(m_luafunc_ref, &wxlua_lreg_refs_key); // delete the reference to this handler m_wxlState.RemoveTrackedEventCallback(this); } } wxString wxLuaEventCallback::Connect(const wxLuaState& wxlState, int lua_func_stack_idx, wxWindowID win_id, wxWindowID last_id, wxEventType eventType, wxEvtHandler *evtHandler) { // Assert too since these errors are serious and not just bad Lua code. wxCHECK_MSG(evtHandler != NULL, wxT("Invalid wxEvtHandler in wxLuaEventCallback::Connect()"), wxT("Invalid wxEvtHandler in wxLuaEventCallback::Connect()")); wxCHECK_MSG((m_evtHandler == NULL) && (m_luafunc_ref == 0), wxT("Attempting to reconnect a wxLuaEventCallback"), wxT("Attempting to reconnect a wxLuaEventCallback")); wxCHECK_MSG(wxlState.Ok(), wxT("Invalid wxLuaState"), wxT("Invalid wxLuaState")); // We must always be installed into the main lua_State, never a coroutine // 1) It will be called only when the lua_State is suspended or dead // 2) We have no way of tracking when the coroutine state is garbage collected/dead if (lua_pushthread(wxlState.GetLuaState()) != 1) { wxlState.lua_Pop(1); return wxT("wxLua: Creating a callback function in a coroutine is not allowed since it will only be called when the thread is either suspended or dead."); } wxlState.lua_Pop(1); m_wxlState = wxlState; m_evtHandler = evtHandler; m_id = win_id; m_last_id = last_id; // NOTE: FIXME? We look for the wxLuaBindEvent in all of the bindings, but it // may not have actually been installed if someone had modified the bindings. // It should be ok since it will error out soon enough without crashing. m_wxlBindEvent = wxLuaBinding::FindBindEvent(eventType); // Do not install this invalid or unknown event type since we won't know // what wxEvent type class to use and someone probably made a mistake. if (m_wxlBindEvent == NULL) { return wxString::Format(wxT("wxLua: Invalid or unknown wxEventType %d for wxEvtHandler::Connect(). winIds %d, %d."), (int)eventType, win_id, last_id); } m_wxlState.AddTrackedEventCallback(this); // create a reference to the Lua event handler function if (lua_func_stack_idx != WXLUAEVENTCALLBACK_NOROUTINE) m_luafunc_ref = m_wxlState.wxluaR_Ref(lua_func_stack_idx, &wxlua_lreg_refs_key); // Note: We use the callback userdata and not the event sink since the event sink // requires a wxEvtHandler object which is a fairly large class. // The userdata (i.e. this) is also deleted for us which makes our life easier. m_evtHandler->Connect(win_id, last_id, eventType, (wxObjectEventFunction)&wxLuaEventCallback::OnAllEvents, this); return wxEmptyString; } void wxLuaEventCallback::ClearwxLuaState() { m_wxlState.UnRef(); // ok if it's not Ok() } wxString wxLuaEventCallback::GetInfo() const { return wxString::Format(wxT("%s(%d) -> wxLuaEventCallback(%p, ids %d, %d)|wxEvtHandler(%p) -> %s : %s"), lua2wx(m_wxlBindEvent ? m_wxlBindEvent->name : "?NULL?").c_str(), (int)GetEventType(), this, m_id, m_last_id, m_evtHandler, m_evtHandler ? m_evtHandler->GetClassInfo()->GetClassName() : wxT("?NULL?"), m_wxlState.GetwxLuaTypeName(m_wxlBindEvent ? *m_wxlBindEvent->wxluatype : WXLUA_TUNKNOWN).c_str()); } void wxLuaEventCallback::OnAllEvents(wxEvent& event) { wxEventType evtType = event.GetEventType(); // Get the wxLuaEventCallback instance to use which is NOT "this" since // "this" is a central event handler function. i.e. this != theCallback wxLuaEventCallback *theCallback = (wxLuaEventCallback *)event.m_callbackUserData; wxCHECK_RET(theCallback != NULL, wxT("Invalid wxLuaEventCallback in wxEvent user data")); if (theCallback != NULL) { // Not an error if !Ok(), the wxLuaState is cleared during shutdown or after a destroy event. wxLuaState wxlState(theCallback->GetwxLuaState()); if (wxlState.Ok()) { wxlState.SetInEventType(evtType); theCallback->OnEvent(&event); wxlState.SetInEventType(wxEVT_NULL); } } // we want the wxLuaWinDestroyCallback to get this too if (evtType == wxEVT_DESTROY) event.Skip(true); } void wxLuaEventCallback::OnEvent(wxEvent *event) { static wxClassInfo* wxSpinEvent_ClassInfo = wxClassInfo::FindClass(wxT("wxSpinEvent")); static wxClassInfo* wxScrollEvent_ClassInfo = wxClassInfo::FindClass(wxT("wxScrollEvent")); // Cannot call it if Lua is gone or the interpreter has been destroyed // This can happen when the program exits since windows may be destroyed // after Lua has been deleted. if (!m_wxlState.Ok()) return; // ref the state in case this generates a wxEVT_DESTROY which clears us wxLuaState wxlState(m_wxlState); // initialize to the generic wxluatype_wxEvent int event_wxl_type = *p_wxluatype_wxEvent; // inits to wxluatype_TUNKNOWN == WXLUA_TUNKNOWN // If !m_wxlBindEvent, we would have errored in Connect(), but don't crash... if (m_wxlBindEvent != NULL) { event_wxl_type = *m_wxlBindEvent->wxluatype; // These wxEventTypes can be wxScrollEvents or wxSpinEvents - FIXME could this be cleaner? // wxEVT_SCROLL_LINEUP, wxEVT_SCROLL_LINEDOWN, wxEVT_SCROLL_THUMBTRACK if ((*m_wxlBindEvent->wxluatype == *p_wxluatype_wxScrollEvent) && event->GetClassInfo()->IsKindOf(wxSpinEvent_ClassInfo)) { if (*p_wxluatype_wxSpinEvent != WXLUA_TUNKNOWN) event_wxl_type = *p_wxluatype_wxSpinEvent; else event_wxl_type = *p_wxluatype_wxEvent; // get the generic wxluatype_wxEvent } else if ((*m_wxlBindEvent->wxluatype == *p_wxluatype_wxSpinEvent) && event->GetClassInfo()->IsKindOf(wxScrollEvent_ClassInfo)) { if (*p_wxluatype_wxScrollEvent != WXLUA_TUNKNOWN) event_wxl_type = *p_wxluatype_wxScrollEvent; else event_wxl_type = *p_wxluatype_wxEvent; // get the generic wxluatype_wxEvent } } // Should know our event type, but error out in case we don't wxCHECK_RET(event_wxl_type != WXLUA_TUNKNOWN, wxT("Unknown wxEvent wxLua tag for : ") + wxString(event->GetClassInfo()->GetClassName())); wxlState.lua_CheckStack(LUA_MINSTACK); int oldTop = wxlState.lua_GetTop(); if (wxlState.wxluaR_GetRef(m_luafunc_ref, &wxlua_lreg_refs_key)) { wxlState.lua_PushValue(LUA_GLOBALSINDEX); if (wxlState.lua_SetFenv(-2) != 0) { // Don't track the wxEvent since we don't own it and tracking it // causes clashes in the object registry table since many can be // created and deleted and the mem address is resused by C++. wxlState.wxluaT_PushUserDataType(event, event_wxl_type, false); wxlState.LuaPCall(1, 0); // one input no returns } else wxlState.wxlua_Error("wxLua: wxEvtHandler::Connect() in wxLuaEventCallback::OnEvent(), callback function is not a Lua function."); } else wxlState.wxlua_Error("wxLua: wxEvtHandler::Connect() in wxLuaEventCallback::OnEvent(), callback function to call is not refed."); wxlState.lua_SetTop(oldTop); // pop function and error message from the stack (if they're there) } // ---------------------------------------------------------------------------- // wxLuaWinDestroyCallback // ---------------------------------------------------------------------------- IMPLEMENT_ABSTRACT_CLASS(wxLuaWinDestroyCallback, wxObject) wxLuaWinDestroyCallback::wxLuaWinDestroyCallback(const wxLuaState& wxlState, wxWindow* win) :m_wxlState(wxlState), m_window(win) { wxCHECK_RET(m_wxlState.Ok(), wxT("Invalid wxLuaState")); wxCHECK_RET(m_window != NULL, wxT("Invalid wxWindow")); m_wxlState.AddTrackedWinDestroyCallback(this); // connect the event handler and set this as the callback user data m_window->Connect(m_window->GetId(), wxEVT_DESTROY, (wxObjectEventFunction)&wxLuaWinDestroyCallback::OnAllDestroyEvents, this); } wxLuaWinDestroyCallback::~wxLuaWinDestroyCallback() { if (m_wxlState.Ok()) { m_wxlState.RemoveTrackedWinDestroyCallback(this); m_wxlState.RemoveTrackedWindow(m_window); } } void wxLuaWinDestroyCallback::ClearwxLuaState() { m_wxlState.UnRef(); // ok if it's not Ok() } wxString wxLuaWinDestroyCallback::GetInfo() const { wxString winName(wxT("wxWindow?")); if (m_window && m_window->GetClassInfo()) winName = m_window->GetClassInfo()->GetClassName(); return wxString::Format(wxT("%s(%p, id=%d)|wxLuaDestroyCallback(%p)"), winName.c_str(), m_window, m_window ? m_window->GetId() : -1, this); } void wxLuaWinDestroyCallback::OnAllDestroyEvents(wxWindowDestroyEvent& event) { // Central handler for events, forward to the specific instance wxLuaWinDestroyCallback *theCallback = (wxLuaWinDestroyCallback *)event.m_callbackUserData; if (theCallback && (((wxWindow*)event.GetEventObject()) == theCallback->m_window)) { theCallback->OnDestroy(event); } else event.Skip(); } void wxLuaWinDestroyCallback::OnDestroy(wxWindowDestroyEvent& event) { event.Skip(); // FIXME - Is it an error to receive an event after you've deleted Lua? // probably not if Lua is getting shutdown // Note: do not remove from wxLuaState's destroyHandlerList here, wait 'till destructor if (m_wxlState.Ok()) { lua_State* L = m_wxlState.GetLuaState(); // clear the metatable for all userdata we're tracking. wxluaO_untrackweakobject(L, NULL, m_window); wxlua_removederivedmethods(L, m_window); // Clear our own pointer to this window wxluaW_removetrackedwindow(L, m_window); wxEvtHandler* evtHandler = m_window->GetEventHandler(); // Finally, clear out the wxLuaEventCallbacks for the very odd cases where // (activation) events can be sent during destruction. These can happen // if you pop up a modal dialog (asking if they want to save perhaps) // and when the dialog is closed the frame below sends an activation event, // but we're right in the middle of being destroyed and we crash. lua_pushlightuserdata(L, &wxlua_lreg_evtcallbacks_key); // push key lua_rawget(L, LUA_REGISTRYINDEX); // pop key, push value (table) lua_pushnil(L); while (lua_next(L, -2) != 0) { // value = -1, key = -2, table = -3 wxLuaEventCallback* wxlCallback = (wxLuaEventCallback*)lua_touserdata(L, -2); wxCHECK_RET(wxlCallback, wxT("Invalid wxLuaEventCallback")); if ((wxlCallback->GetEvtHandler() == evtHandler) || (wxlCallback->GetEvtHandler() == (wxEvtHandler*)m_window)) { // remove the ref to the routine since we're clearing the wxLuaState // See ~wxLuaEventCallback wxluaR_unref(L, wxlCallback->GetLuaFuncRef(), &wxlua_lreg_refs_key); wxlCallback->ClearwxLuaState(); lua_pop(L, 1); // pop value // The code below is the equivalent of this, but works while iterating // "m_wxlState.RemoveTrackedEventCallback(wxlCallback);" lua_pushvalue(L, -1); // copy key for next iteration lua_pushnil(L); lua_rawset(L, -4); // set t[key] = nil to remove it } else lua_pop(L, 1); // pop value, lua_next will pop key at end } lua_pop(L, 1); // pop table } }
lgpl-3.0
osbitools/OsBiToolsSpringWs
OsBiWsCoreShared/src/main/java/com/osbitools/ws/core/shared/proc/DataSetProcessor.java
2968
/* * Open Source Business Intelligence Tools - http://www.osbitools.com/ * * Copyright 2014-2018 IvaLab Inc. and by respective contributors (see below). * * Released under the LGPL v3 or higher * See http://www.gnu.org/licenses/lgpl-3.0.html * * Date: 2014-11-07 * * Contributors: * * Igor Peonte <igor.144@gmail.com> * */ package com.osbitools.ws.core.shared.proc; import java.util.*; import com.osbitools.ws.core.shared.config.CoreWsConfig; import com.osbitools.ws.core.shared.daemons.DsDescrResource; import com.osbitools.ws.core.shared.daemons.DsExtResource; import com.osbitools.ws.core.shared.daemons.LsFilesCheck; import com.osbitools.ws.core.shared.model.*; import com.osbitools.ws.shared.WsSrvException; import com.osbitools.ws.shared.service.RequestLogger; import com.osbitools.ws.shared.binding.ds.DataSetDescr; /** * Abstract JSON DataSet producer * * @author "Igor Peonte <igor.144@gmail.com>" * */ public class DataSetProcessor extends AbstractDataSetProc { // Handle for active DataSet producer AbstractDataSetProc _dsp; public DataSetProcessor(DsDescrResource dsr, HashMap<String, Object> requestParameters, RequestLogger log) throws WsSrvException { super(null, requestParameters, log); setDsDescrResource(dsr); DataSetDescr dsd = dsr.getResource(); if (dsd.getGroupData() != null) { _dsp = new GroupDataSetProc(new DsExtResource(dsd), requestParameters, getLogger()); } else if (dsd.getStaticData() != null) { _dsp = new StaticDataSetProc(new DsExtResource(dsd), requestParameters, getLogger()); } else if (dsd.getCsvData() != null) { _dsp = new CsvDataSetProc(new DsExtResource(dsd), requestParameters, getLogger()); } else if (dsd.getSqlData() != null) { _dsp = new SqlDataSetProc(new DsExtResource(dsd), requestParameters, getLogger()); } else if (dsd.getXmlData() != null) { _dsp = new XmlDataSetProc(new DsExtResource(dsd), requestParameters, getLogger()); } if (_dsp == null) //-- 105 throw new WsSrvException(105, "DataSet processor is not defined"); _dsp.setDsDescrResource(dsr); setDsExtResource(new DsExtResource(dsd)); } @Override boolean checkComplex() throws WsSrvException { return _dsp.checkComplex() || super.checkComplex(); } @Override public void initComplex() throws WsSrvException { super.initComplex(); if (isComplex()) // Propagate positive complex flag _dsp.setComplex(true); } @Override public void validateRequestParams(Map<String, String[]> params) throws WsSrvException { _dsp.validateRequestParams(params); } @Override public DataSet readDataSet(String name, String lang, TraceRecorder trace, List<String> warn, LsFilesCheck lcheck, CoreWsConfig cfg) throws WsSrvException { return _dsp.readDataSet(name, lang, trace, warn, lcheck, cfg); } public AbstractDataSetProc getDataSetProc() { return _dsp; } }
lgpl-3.0
dinusv/livecv
plugins/live/src/qstaticloaderproperty.cpp
1277
#include "qstaticloaderproperty.h" #include <QQmlEngine> #include <QtQml> /*! \class lcv::QStaticLoaderProperty \inmodule live_cpp \internal */ /*! \qmltype StaticLoaderProperty \instantiates lcv::QStaticLoaderProperty \inqmlmodule live \inherits QtObject \brief Stores a StaticLoader item property and manages it's lifetime (Owns the property if its an object) */ /*! \qmlproperty variant StaticLoaderProperty::value Value to store. */ QStaticLoaderProperty::QStaticLoaderProperty(QObject *parent) : QObject(parent) { } QStaticLoaderProperty::~QStaticLoaderProperty(){ if ( m_value.canConvert<QObject*>() ){ QObject* valueObj = m_value.value<QObject*>(); valueObj->deleteLater(); } } void QStaticLoaderProperty::setValue(const QVariant& value){ if (m_value == value) return; if ( m_value.canConvert<QObject*>() ){ QObject* valueObj = m_value.value<QObject*>(); qmlEngine(this)->setObjectOwnership(valueObj, QQmlEngine::JavaScriptOwnership); } if ( value.canConvert<QObject*>() ){ QObject* valueObj = value.value<QObject*>(); qmlEngine(this)->setObjectOwnership(valueObj, QQmlEngine::CppOwnership); } m_value = value; emit valueChanged(); }
lgpl-3.0
InfectedLan/InfectedAPI
objects/page.php
1247
<?php /** * This file is part of InfectedAPI. * * Copyright (C) 2017 Infected <http://infected.no/>. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ require_once 'objects/databaseobject.php'; class Page extends DatabaseObject { private $name; private $title; private $content; /* * Returns the name of this page. */ public function getName(): string { return $this->name; } /* * Returns the title of this page. */ public function getTitle(): string { return $this->title; } /* * Returns the content of this page. */ public function getContent(): string { return $this->content; } }
lgpl-3.0
laz2727/TinkersEnergistics
src/main/java/princess/tenergistics/modifiers/RTGModifier.java
942
package princess.tenergistics.modifiers; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import princess.tenergistics.tools.PoweredTool; import slimeknights.tconstruct.library.modifiers.Modifier; import slimeknights.tconstruct.library.tools.nbt.IModifierToolStack; public class RTGModifier extends Modifier { private static final int ENERGY_PER_SECOND = 10; public RTGModifier() { super(0xffff00); } @Override public int getPriority() { return -666; } @Override public void onInventoryTick(IModifierToolStack tool, int level, World world, LivingEntity holder, int itemSlot, boolean isSelected, boolean isCorrectSlot, ItemStack stack) { if (!world.isRemote && holder.ticksExisted % 20 == 0) { PoweredTool.setEnergy(tool, Math .min(PoweredTool.getMaxEnergy(tool), PoweredTool.getEnergy(tool) + ENERGY_PER_SECOND * level)); } } }
lgpl-3.0
phlib/beanstalk
tests/Command/StatsTraitTest.php
2878
<?php declare(strict_types=1); namespace Phlib\Beanstalk\Command; use Phlib\Beanstalk\Exception\CommandException; use Phlib\Beanstalk\Exception\NotFoundException; use PHPUnit\Framework\MockObject\MockObject; class StatsTraitTest extends CommandTestCase { public function testWhenStatusNotFound(): void { $this->expectException(NotFoundException::class); $this->socket->expects(static::any()) ->method('read') ->willReturn('NOT_FOUND'); $this->getMockStat() ->process($this->socket); } public function testWhenStatusUnknown(): void { $this->expectException(CommandException::class); $this->socket->expects(static::any()) ->method('read') ->willReturn('UNKNOWN_STATUS data'); $this->getMockStat() ->process($this->socket); } /** * @dataProvider yamlFormatIsDecodedDataProvider */ public function testYamlFormatIsDecoded(string $yaml, array $expectedOutput): void { $this->socket->expects(static::any()) ->method('read') ->willReturnOnConsecutiveCalls("OK 1234\r\n", "---\n{$yaml}\r\n"); $stat = $this->getMockStat(); static::assertSame($expectedOutput, $stat->process($this->socket)); } public function yamlFormatIsDecodedDataProvider(): array { return [ [ '- value', [ 0 => 'value', ], ], [ "- value1\r\n- value2", [ 0 => 'value1', 1 => 'value2', ], ], [ '- 321', [ 0 => 321, ], ], [ 'key1: value1', [ 'key1' => 'value1', ], ], [ "key1: value1\r\nkey2: value2", [ 'key1' => 'value1', 'key2' => 'value2', ], ], [ 'key1: 123', [ 'key1' => 123, ], ], [ "key1: value1\r\nkey2: \r\nkey3: value3", [ 'key1' => 'value1', 'key2' => '', 'key3' => 'value3', ], ], ]; } /** * @return StatsTrait|MockObject */ private function getMockStat(): MockObject { $mock = $this->getMockBuilder(StatsTrait::class) ->addMethods(['getCommand']) ->getMockForTrait(); $mock->method('getCommand') ->willReturn('stats'); return $mock; } }
lgpl-3.0
kveratis/GameCode4
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/penlight/lua/pl/permute.lua
1654
--- Permutation operations. -- @class module -- @name pl.permute local tablex = require 'pl.tablex' local utils = require 'pl.utils' local copy = tablex.deepcopy local append = table.insert local coroutine = coroutine local resume = coroutine.resume local assert_arg = utils.assert_arg --[[ module ('pl.permute',utils._module) ]] local permute = {} -- PiL, 9.3 local permgen permgen = function (a, n, fn) if n == 0 then fn(a) else for i=1,n do -- put i-th element as the last one a[n], a[i] = a[i], a[n] -- generate all permutations of the other elements permgen(a, n - 1, fn) -- restore i-th element a[n], a[i] = a[i], a[n] end end end --- an iterator over all permutations of the elements of a list. -- Please note that the same list is returned each time, so do not keep references! -- @param a list-like table -- @return an iterator which provides the next permutation as a list function permute.iter (a) assert_arg(1,a,'table') local n = #a local co = coroutine.create(function () permgen(a, n, coroutine.yield) end) return function () -- iterator local code, res = resume(co) return res end end --- construct a table containing all the permutations of a list. -- @param a list-like table -- @return a table of tables -- @usage permute.table {1,2,3} --> {{2,3,1},{3,2,1},{3,1,2},{1,3,2},{2,1,3},{1,2,3}} function permute.table (a) assert_arg(1,a,'table') local res = {} local n = #a permgen(a,n,function(t) append(res,copy(t)) end) return res end return permute
lgpl-3.0
icedman/kludgets
kludget.cpp
19267
#include "config.h" #include "kludget.h" #include "kclient.h" #include "kdocument.h" #include "ksettings.h" #include "kwindow.h" #include "kview.h" #include "ksystem.h" #include "knetwork.h" #include "klog.h" #include "version.h" #include "prefwindow.h" #include "installwindow.h" #include <QtXml> #include <QUrl> #include <QFileDialog> Kludget::Kludget(KClient *parent) : QObject(parent), client(parent), window(new KWindow), settings(new KSettings(this)), system(new KSystem(this)), prefWindow(0), aboutWindow(0), firstShow(true) { setObjectName("Kludget"); settings->setRootKey("kludget"); connect(system, SIGNAL(execUpdate(long)), this, SLOT(onSystemExecUpdate(long))); connect(system, SIGNAL(execFinish(long)), this, SLOT(onSystemExecFinish(long))); connect(window, SIGNAL(destroyed()), this, SLOT(onWindowDestroyed())); connect(window, SIGNAL(onShow()), this, SLOT(onShow())); connect(window, SIGNAL(onHide()), this, SLOT(onHide())); connect(window, SIGNAL(onStartDrag()), this, SLOT(onStartDrag())); connect(window, SIGNAL(onEndDrag()), this, SLOT(onEndDrag())); connect(window, SIGNAL(onSettingsChanged()), this, SLOT(onSettingsChanged())); connect(window->view(), SIGNAL(contextMenuRequested()), this, SLOT(onContextMenu())); connect(window->view(), SIGNAL(urlReceived(const QUrl*)), this, SLOT(onUrlReceived(const QUrl*))); connect(window->view()->page(), SIGNAL(loadFinished(bool)), this, SLOT(show())); connect(window->view()->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(onJavaScriptWindowObjectCleared())); connect(window->view()->page(), SIGNAL(frameCreated(QWebFrame*)), this, SLOT(onFrameCreated(QWebFrame*))); connect(this, SIGNAL(evaluate(const QString &)), this, SLOT(onEvaluate(const QString &))); connect(&customMenuMapper, SIGNAL(mapped(const QString &)), this, SIGNAL(evaluate(const QString &))); connect(&ipcClient, SIGNAL(messageReceived(QString,QString,QString)), this, SLOT(messageReceived(QString,QString,QString))); KLog::log("Kludget::created"); } Kludget::~Kludget() { if (prefWindow) delete prefWindow; KLog::log("Kludget::destroyed"); } Kludget* Kludget::create(KClient *client, const KludgetInfo &i) { Kludget *k = new Kludget(client); if (!k->loadSettings(i, true)) { delete k; k = 0; } return k; } bool Kludget::loadSettings(const KludgetInfo &i, bool loadPage) { info = i; #if 1 qDebug("path: %s", qPrintable(info.path)); qDebug("name: %s", qPrintable(info.name)); qDebug("config: %s", qPrintable(info.configFile)); qDebug("instance config: %s", qPrintable(info.instancePreferenceFile)); qDebug("storage: %s", qPrintable(info.storagePath)); qDebug("contentSrc: %s", qPrintable(info.contentSrc)); #endif if (!QFile::exists(info.configFile)) { KLog::log("Kludget::load fail"); KLog::log("config file not found"); return false; } window->setWindowTitle(info.id + ":" + QString::number(QApplication::applicationPid())); // access KDocument access; access.openDocument(info.storagePath + "/access.xml"); bool accessLocal = access.getValue("kludget/access/local", "0").toInt(); bool accessNetwork = access.getValue("kludget/access/network", "0").toInt(); bool accessPlugins = access.getValue("kludget/access/plugins", "0").toInt(); bool accessSystem = access.getValue("kludget/access/system", "0").toInt(); // engine KDocument engine; engine.openDocument(QStandardPaths::locate(QStandardPaths::DataLocation, "", QStandardPaths::LocateDirectory) + "/" + ENGINE_CONFIG_FILE); // instance settings settings->setPath(info.instancePreferenceFile); #if defined(WIN32) settings->loadPreferences(":resources/xml/widgetPreferences.xml"); #else settings->loadPreferences(":resources/xml/widgetPreferences_linux.xml"); #endif settings->loadPreferences(info.configFile); settings->loadPreferences(info.path + "/" + PREFERENCE_FILE); // position int x = settings->read("kludget/x", window->x()).toInt(); int y = settings->read("kludget/y", window->y()).toInt(); window->move(x, y); resize(settings->read("kludget/width", info.width).toInt(), settings->read("kludget/height", info.height).toInt()); window->setOpacity(settings->read("kludget/opacity", 200).toInt()); window->setIgnoreDrag(settings->read("kludget/ignoreDrag", "0").toInt()); window->setIgnoreMouse(settings->read("kludget/ignoreMouse", "0").toInt()); window->setWindowLevel(settings->read("kludget/windowLevel", "0").toInt()); window->setSnapToScreen(settings->read("kludget/snapToScreen", "0").toInt()); window->view()->setGrayed(settings->read("kludget/grayScaled", "0").toInt()); #if 0 window->view()->setTinted(settings->read("kludget/tinted", "0").toInt()); window->view()->setTintColor(QColor(settings->read("kludget/tintColor", "#c0c0c0").toString())); window->view()->setTintMode(settings->read("kludget/tintMode", "14").toInt()); #endif // zoom window->setZoomFactor(settings->read("kludget/zoom", 1).toDouble()); window->view()->page()->setViewportSize(window->view()->page()->viewportSize()); window->autoSize(true); setProperty("identifier", info.id); setProperty("instance", info.instance); setupContextMenu(); QWebSettings *webSettings = window->view()->page()->settings(); #if 0 webSettings->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true); webSettings->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true); webSettings->setOfflineStoragePath(info.storagePath); webSettings->setOfflineStorageDefaultQuota(5000000); #endif webSettings->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); webSettings->setAttribute(QWebSettings::PluginsEnabled, accessPlugins); webSettings->setWebGraphic(QWebSettings::MissingImageGraphic, QPixmap()); webSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true); webSettings->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, true); webSettings->setUserStyleSheetUrl(QUrl::fromLocalFile(":resources/style/widget.css")); // network settings KNetwork *net = KNetwork::instance(); net->loadSettings(); net->setAccess(accessNetwork, accessLocal, QUrl::fromLocalFile(QFileInfo(info.contentSrc).absolutePath())); // system settings system->setEnableCommands(accessSystem); if (engine.getValue("kludget/general/runInShell", "0").toInt()) system->setShellPath(engine.getValue("kludget/general/shellPath", "")); // plugin KLog::log("plugin"); if (!plugin.isLoaded() && accessPlugins && info.pluginPath != "") { plugin.setFileName(info.pluginPath + "/" + info.pluginExecutable); KLog::log(QString("loading %1").arg(plugin.fileName())); if (plugin.load()) { typedef void (*initWithWebView)(QWebView*); initWithWebView init = (initWithWebView)plugin.resolve("initWithWebView"); if (init) { init((QWebView*)window->view()); KLog::log(QString("plugin loaded %1").arg(plugin.fileName())); } } else { KLog::log(QString("unable to load %1").arg(plugin.fileName())); } } // drop window->view()->setAcceptDrops(true); if (loadPage) { window->hide(); QUrl url = QUrl::fromLocalFile(info.contentSrc); if (!QFile::exists(info.contentSrc)) { url = QUrl(info.contentSrc); if (url.scheme().toLower() == "http") { window->view()->load(url); } else if (info.contentHtml == "") { KLog::log("Kludget::load fail"); KLog::log(QString("content source not found. ") + info.contentSrc); return false; } } if (info.contentHtml != "") window->view()->setHtml(info.contentHtml); else window->view()->load(url); KLog::log(QString("Kludget::load ") + info.id); #if 0 QString defaultBg = info.path + "/Default.png"; if (QFile::exists(defaultBg)) //window->view()->setTransitionLayer(QImage(defaultBg)); #endif } ipcClient.connectToServer(); return true; } void Kludget::saveSettings() { // position settings->write("kludget/x", window->x()); settings->write("kludget/y", window->y()); } void Kludget::addJavaScriptWindowObjects(QWebFrame* frame) { frame->addToJavaScriptWindowObject("Kludget", this); frame->addToJavaScriptWindowObject("System", system); runJavaScriptFile(frame, ":resources/scripts/json2.js"); runJavaScriptFile(frame, ":resources/scripts/system.js"); runJavaScriptFile(frame, ":resources/scripts/widget.js"); runJavaScriptFile(frame, ":resources/scripts/debug.js"); // dashboard widget specific runJavaScriptFile(frame, ":resources/scripts/macoswidgets.js"); // add plugin here if (plugin.isLoaded()) { typedef void (*windowScriptObjectAvailable)(QWebFrame*); windowScriptObjectAvailable wsoAvailable = (windowScriptObjectAvailable)plugin.resolve("windowScriptObjectAvailable"); if (wsoAvailable) { KLog::log("plugin::windowScriptObjectAvailable"); wsoAvailable(frame); } } } void Kludget::runJavaScriptFile(QWebFrame* frame, const QString &p) { QFile scriptFile(p); if (scriptFile.open(QIODevice::ReadOnly)) { QString script = QTextStream(&scriptFile).readAll(); frame->evaluateJavaScript(script); } } void Kludget::setupContextMenu() { contextMenu.clear(); #if defined(WIN32) loadMenuFile(":resources/xml/widgetContextMenu.xml"); #else loadMenuFile(":resources/xml/widgetContextMenu_linux.xml"); #endif } void Kludget::loadMenuFile(const QString &path) { QFile fmenu(path); if (fmenu.exists()) { fmenu.open(QIODevice::ReadOnly); QString content = fmenu.readAll(); fmenu.close(); QDomDocument dom; dom.setContent(content); QDomNodeList menuList = dom.elementsByTagName("menu"); if (menuList.length() > 0) { QDomNodeList menuItemList = menuList.item(0).childNodes(); for (int i = 0; i < menuItemList.length(); i++) { QDomElement menuItem = menuItemList.item(i).toElement(); QString name = menuItem.firstChild().nodeValue(); QString script = menuItem.attributes().namedItem("action").nodeValue(); if (menuItem.nodeName().toLower() == "custom_menu") { loadMenuFile(info.configFile); loadMenuFile(info.path + "/" + MENU_FILE); continue; } if (menuItem.nodeName().toLower() == "separator") { contextMenu.insertSeparator(0); continue; } if (script == "") continue; QAction *action = contextMenu.addAction(name); connect(action, SIGNAL(triggered()), &customMenuMapper, SLOT(map())); customMenuMapper.setMapping(action, script); } } } } void Kludget::onShow() { qDebug("onShow"); onEvaluate("Kludget.onShow()"); } void Kludget::onHide() { qDebug("onHide"); onEvaluate("Kludget.onHide()"); } void Kludget::onStartDrag() { qDebug("onStartDrag"); onEvaluate("Kludget.onStartDrag()"); } void Kludget::onEndDrag() { qDebug("onEndDrag"); saveSettings(); onEvaluate("Kludget.onEndDrag()"); } void Kludget::onRemove() { qDebug("onRemove"); onEvaluate("Kludget.onRemove()"); } void Kludget::onSettingsChanged() { KLog::instance()->loadSettings(); loadSettings(info); onEvaluate("Kludget.onSettingsChanged()"); } void Kludget::onEvaluate(const QString &command) { QString script = QString("try { ") + command + "; } catch(e) { try { " + command.toLower() + "; } catch(e) { alert('" + command + "' + e) } }"; window->view()->page()->mainFrame()->evaluateJavaScript(script); } void Kludget::onWindowDestroyed() { deleteLater(); } void Kludget::onPreferencesClosed() { prefWindow = 0; aboutWindow = 0; } void Kludget::onContextMenu() { onEvaluate("getSelection().empty()"); contextMenu.popup(QCursor::pos()); } void Kludget::onJavaScriptWindowObjectCleared() { addJavaScriptWindowObjects(window->view()->page()->mainFrame()); } void Kludget::onFrameCreated(QWebFrame *frame) { addJavaScriptWindowObjects(frame); // todo attach javaScriptWindowObjectCleared signal to this frame } void Kludget::onUrlReceived(const QUrl *url) { qDebug("onUrlReceived: %s", qPrintable(url->toString())); onEvaluate(QString("Kludget.onUrlReceived(") + url->toString() + ")"); } void Kludget::onSystemExecUpdate(long id) { QString obj = QString("_syscmd_") + QString::number(id); onEvaluate(obj + ".update()"); } void Kludget::onSystemExecFinish(long id) { QString obj = QString("_syscmd_") + QString::number(id); onEvaluate(obj + ".onfinish()"); } void Kludget::screenshot(QString path) { if (path == "") { path = QFileDialog::getSaveFileName(0, "Save Image", QStandardPaths::locate(QStandardPaths::HomeLocation, "", QStandardPaths::LocateDirectory), "Image Files (*.png *.jpg *.bmp)"); if (path == "") return; } window->view()->screenshot(path); QDesktopServices::openUrl(QUrl(path)); } void Kludget::show() { onShow(); window->show(); } void Kludget::hide() { onHide(); window->hide(); } void Kludget::close() { onRemove(); window->hide(); window->close(); #if 1 // forcefully remove preference file settings->sync(); settings->clear(); #endif } void Kludget::inspect() { window->view()->page()->triggerAction(QWebPage::InspectElement); } void Kludget::reload() { window->view()->page()->triggerAction(QWebPage::Reload); } void Kludget::about() { if (aboutWindow) { aboutWindow->raise(); aboutWindow->show(); return ; } aboutWindow = new AboutWindow(info); aboutWindow->setAttribute(Qt::WA_DeleteOnClose); aboutWindow->setWindowTitle("About - " + info.name); aboutWindow->buildPreferenceMap(":resources/xml/accessPreferences.xml", false); aboutWindow->setupUI(); aboutWindow->show(); connect(aboutWindow, SIGNAL(settingsChanged()), this, SLOT(onSettingsChanged())); connect(aboutWindow, SIGNAL(destroyed()), this, SLOT(onPreferencesClosed())); } void Kludget::configure(QString cat) { saveSettings(); if (prefWindow) { prefWindow->raise(); prefWindow->show(); return ; } prefWindow = new PreferenceWindow(settings); prefWindow->setAttribute(Qt::WA_DeleteOnClose); prefWindow->setWindowTitle("Preferences - " + info.name); prefWindow->buildPreferenceMap(info.configFile); prefWindow->buildPreferenceMap(info.path + "/" + PREFERENCE_FILE); #if defined(WIN32) prefWindow->buildPreferenceMap(":resources/xml/widgetPreferences.xml"); #else prefWindow->buildPreferenceMap(":resources/xml/widgetPreferences_linux.xml"); #endif prefWindow->setupUI(); prefWindow->show(); connect(prefWindow, SIGNAL(settingsChanged()), this, SLOT(onSettingsChanged())); connect(prefWindow, SIGNAL(destroyed()), this, SLOT(onPreferencesClosed())); } void Kludget::createInstance(QString instance) { client->createInstance(instance); } void Kludget::move(int x, int y) { window->move(x, y); } void Kludget::resize(int w, int h) { if (w > 0 && h > 0) window->setMinimumSize(QSize(w, h)); window->resize(w, h); } void Kludget::resizeAndMoveTo(int x, int y, int w, int h) { resize(w,h); move(x,y); } int Kludget::opacity() { return window->opacity(); } int Kludget::windowLevel() { return window->windowLevel(); } int Kludget::x() { return window->x(); } int Kludget::y() { return window->y(); } int Kludget::width() { return window->width(); } int Kludget::height() { return window->height(); } void Kludget::renderLayer(QString layer) { int z = -1; if (layer.indexOf("back") != -1) z = KView::Background; else if (layer.indexOf("fore") != -1) z = KView::Foreground; if (z != -1) window->view()->renderLayer(z); } void Kludget::prepareForTransition(QString transition) { //qDebug("prepareForTransition: %s", qPrintable(transition)); int t = KView::Transition; if (transition.indexOf("Back") != -1) t = KView::ToBack; else if (transition.indexOf("Front") != -1) t = KView::ToFront; window->view()->setTransition(t); window->view()->renderLayer(KView::Transition); window->view()->setFrozen(true); } void Kludget::performTransition() { window->view()->beginTransition(); } void Kludget::messageReceived(QString message, QString id, QString instance) { if (instance != "") { if (info.instance != instance) return; } if (message == "ping") { ipcClient.sendMessage("pong", info.id, info.instance); return; } KLog::log(QString("kludget messageReceived: %1").arg(message)); int messageId = message.toUInt(); switch (messageId) { case KIPC::ShowHUD: { window->moveToTop(); //window->updateMouseIgnore(false); break; } case KIPC::HideHUD: { //window->applySettings(); window->moveToBottom(); break; } case KIPC::ShowWindow: { show(); window->moveToTop(); window->applySettings(); break; } case KIPC::HideWindow: { hide(); break; } case KIPC::LowerWindow: { window->lower(); break; } case KIPC::SettingsChanged: { onSettingsChanged(); break; } case KIPC::ShowOptions: { onContextMenu(); break; } case KIPC::Configure: { configure(); break; } default: evaluate(message); break; } }
lgpl-3.0
pcolby/libqtaws
src/databasemigrationservice/movereplicationtaskrequest.cpp
4049
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "movereplicationtaskrequest.h" #include "movereplicationtaskrequest_p.h" #include "movereplicationtaskresponse.h" #include "databasemigrationservicerequest_p.h" namespace QtAws { namespace DatabaseMigrationService { /*! * \class QtAws::DatabaseMigrationService::MoveReplicationTaskRequest * \brief The MoveReplicationTaskRequest class provides an interface for DatabaseMigrationService MoveReplicationTask requests. * * \inmodule QtAwsDatabaseMigrationService * * <fullname>AWS Database Migration Service</fullname> * * AWS Database Migration Service (AWS DMS) can migrate your data to and from the most widely used commercial and * open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Redshift, MariaDB, Amazon Aurora, MySQL, * and SAP Adaptive Server Enterprise (ASE). The service supports homogeneous migrations such as Oracle to Oracle, as well * as heterogeneous migrations between different database platforms, such as Oracle to MySQL or SQL Server to * * PostgreSQL> * * For more information about AWS DMS, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html">What Is * AWS Database Migration Service?</a> in the <i>AWS Database Migration User Guide.</i> * * \sa DatabaseMigrationServiceClient::moveReplicationTask */ /*! * Constructs a copy of \a other. */ MoveReplicationTaskRequest::MoveReplicationTaskRequest(const MoveReplicationTaskRequest &other) : DatabaseMigrationServiceRequest(new MoveReplicationTaskRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a MoveReplicationTaskRequest object. */ MoveReplicationTaskRequest::MoveReplicationTaskRequest() : DatabaseMigrationServiceRequest(new MoveReplicationTaskRequestPrivate(DatabaseMigrationServiceRequest::MoveReplicationTaskAction, this)) { } /*! * \reimp */ bool MoveReplicationTaskRequest::isValid() const { return false; } /*! * Returns a MoveReplicationTaskResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * MoveReplicationTaskRequest::response(QNetworkReply * const reply) const { return new MoveReplicationTaskResponse(*this, reply); } /*! * \class QtAws::DatabaseMigrationService::MoveReplicationTaskRequestPrivate * \brief The MoveReplicationTaskRequestPrivate class provides private implementation for MoveReplicationTaskRequest. * \internal * * \inmodule QtAwsDatabaseMigrationService */ /*! * Constructs a MoveReplicationTaskRequestPrivate object for DatabaseMigrationService \a action, * with public implementation \a q. */ MoveReplicationTaskRequestPrivate::MoveReplicationTaskRequestPrivate( const DatabaseMigrationServiceRequest::Action action, MoveReplicationTaskRequest * const q) : DatabaseMigrationServiceRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the MoveReplicationTaskRequest * class' copy constructor. */ MoveReplicationTaskRequestPrivate::MoveReplicationTaskRequestPrivate( const MoveReplicationTaskRequestPrivate &other, MoveReplicationTaskRequest * const q) : DatabaseMigrationServiceRequestPrivate(other, q) { } } // namespace DatabaseMigrationService } // namespace QtAws
lgpl-3.0
spillai/procgraph
procgraph_packages.py
8946
# Autogenerated file -- do not modify. # This file is generated by "pgindex". # It lists the default ProcGraph packages and their dependencies # so that we can warn the user if some dependency is not found at # install time. ProcGraph's policy is to be very liberal; for example, # the `procgraph_cv' package is installed even though OpenCV is not found. # and an error will be thrown only if the user actually uses those blocks. index = {'packages': {'procgraph.components.debug_components': {'blocks': ['info', 'constant', '+', '*', '-', '/', 'gain', 'print', 'identity'], 'desc': 'Components used for debugging and unit tests.', 'requires': {}}, 'procgraph_cv': {'blocks': ['gradient', 'smooth'], 'desc': 'Blocks using the OpenCV library.', 'requires': {'cv': ['cv', 'opencv']}}, 'procgraph_foo': {'blocks': ['block_example'], 'desc': 'An example package for ProcGraph that shows how to organize your code. ', 'requires': {'pickle': ['cPickle', 'pickle']}}, 'procgraph_hdf': {'blocks': ['hdfread_many', 'hdfread_test', 'hdfread_many_test', 'hdfwrite', 'hdfread'], 'desc': 'This is a set of blocks to read and write logs in HDF_ format. ', 'requires': {'tables': ['tables']}}, 'procgraph_images': {'blocks': ['rgb2gray', 'compose', 'reshape2d', 'solid', 'blend', 'skim_top_and_bottom', 'posterize', 'gray2rgb', 'scale', 'grid', 'skim_top', 'posneg', 'border'], 'desc': 'Blocks for basic operations on images. ', 'requires': {}}, 'procgraph_io_misc': {'blocks': ['pickle_load', 'to_file', 'pickle', 'pickle_group', 'as_json'], 'desc': 'Miscellaneous functions to be better organized.', 'requires': {'json': ['simplejson']}}, 'procgraph_mpl': {'blocks': ['plot'], 'desc': 'Blocks using Matplotlib to display data.', 'requires': {'matplotlib': ['matplotlib'], 'matplotlib.pylab': ['matplotlib.pylab']}}, 'procgraph_mplayer': {'blocks': ['mplayer', 'mencoder'], 'desc': 'Blocks for encoding/decoding video based on MPlayer.', 'requires': {}}, 'procgraph_numpy_ops': {'blocks': ['smooth1d', 'square', 'sign', 'minimum', 'select', 'rad2deg', 'outer', 'log', 'sum', 'astype', 'arctan', 'abs', 'take', 'real', 'deg2rad', 'hstack', 'flipud', 'max', 'vstack', 'gradient1d', 'dstack', 'maximum', 'fliplr', 'normalize_Linf', 'mean'], 'desc': 'Various operations wrapping numpy functions.', 'requires': {}}, 'procgraph_pil': {'blocks': ['imread', 'text', 'resize'], 'desc': 'Blocks for image operations based on the PIL library', 'requires': {'PIL': ['PIL']}}, 'procgraph_robotics': {'blocks': ['pose2commands', 'laser_display', 'skim', 'organic_scale', 'pose2vel_', 'laser_dot_display'], 'desc': 'Some functions specific to robotics applications. ', 'requires': {'geometry': ['geometry']}}, 'procgraph_ros': {'blocks': ['bagread_test', 'ros2python', 'bagread'], 'desc': 'This is a set of blocks to read and write logs in ROS_ Bag format. ', 'requires': {'ros': ['ros']}}, 'procgraph_signals': {'blocks': ['derivative2', 'slice', 'two_step_difference', 'derivative', 'join', 'sync', 'fps_data_limit', 'history', 'historyt', 'forward_difference', 'low_pass', 'make_tuple', 'fps_limit', 'fps_print', 'last_n_samples', 'sieve', 'extract', 'any', 'wait'], 'desc': 'Blocks performing operations with a dynamic nature. ', 'requires': {}}, 'procgraph_statistics': {'blocks': ['cov2corr', 'normalize', 'expectation', 'covariance', 'soft_variance', 'variance'], 'desc': 'Blocks for common statistical operations.', 'requires': {}}, 'procgraph_yaml': {'blocks': ['yaml2object'], 'desc': 'YAML conversions.', 'requires': {'yaml': ['yaml']}}}}
lgpl-3.0
ryanmrichard/ForceManII
Interfaces/FManIIPulsarAPI.hpp
1583
/* * Copyright (C) 2016 Ryan M. Richard <ryanmrichard1 at gmail.com>. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #pragma once #include<pulsar/modulebase/EnergyMethod.hpp> #include<pulsar/modulebase/PropertyCalculator.hpp> namespace FManII { class FFPulsar:public pulsar::EnergyMethod{ public: FFPulsar(ID_t id): EnergyMethod(id){} pulsar::DerivReturnType deriv_(size_t Order,const pulsar::Wavefunction& wfn); }; class FFTermPulsar:public pulsar::EnergyMethod{ public: FFTermPulsar(ID_t id): EnergyMethod(id){} pulsar::DerivReturnType deriv_(size_t Order,const pulsar::Wavefunction& wfn); }; class FFCharges:public pulsar::PropertyCalculator{ public: FFCharges(ID_t id): PropertyCalculator(id){} std::vector<double> calculate_(unsigned int deriv, const pulsar::Wavefunction & wfn); }; }//End namespace FManII
lgpl-3.0
SonarSource/sonarlint-visualstudio
src/Integration/ProfileConflicts/RuleSetInformation.cs
2668
/* * SonarLint for Visual Studio * Copyright (C) 2016-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections.Generic; using System.Linq; namespace SonarLint.VisualStudio.Integration.ProfileConflicts { /// <summary> /// Data-only class that represents aggregated rule set information. /// Same rule sets should be represented by the same instance of <see cref="RuleSetInformation"/> and have their <see cref="RuleSetDeclaration.ConfigurationContext"/> /// associated with the shared instance by adding them into <see cref="ConfigurationContexts"/>. /// </summary> /// <seealso cref="RuleSetDeclaration"/> public class RuleSetInformation { public RuleSetInformation(string projectFullName, string baselineRuleSet, string projectRuleSet, IEnumerable<string> ruleSetDirectories) { if (string.IsNullOrWhiteSpace(projectFullName)) { throw new ArgumentNullException(nameof(projectFullName)); } if (string.IsNullOrWhiteSpace(baselineRuleSet)) { throw new ArgumentNullException(nameof(baselineRuleSet)); } if (string.IsNullOrWhiteSpace(projectRuleSet)) { throw new ArgumentNullException(nameof(projectRuleSet)); } this.RuleSetProjectFullName = projectFullName; this.BaselineFilePath = baselineRuleSet; this.RuleSetFilePath = projectRuleSet; this.RuleSetDirectories = ruleSetDirectories?.ToArray() ?? new string[0]; } public string RuleSetProjectFullName { get; } public string BaselineFilePath { get; } public string RuleSetFilePath { get; } public string[] RuleSetDirectories { get; } public HashSet<string> ConfigurationContexts { get; } = new HashSet<string>(); } }
lgpl-3.0
pcolby/libqtaws
src/route53domains/route53domainsclient.cpp
34441
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "route53domainsclient.h" #include "route53domainsclient_p.h" #include "core/awssignaturev4.h" #include "acceptdomaintransferfromanotherawsaccountrequest.h" #include "acceptdomaintransferfromanotherawsaccountresponse.h" #include "canceldomaintransfertoanotherawsaccountrequest.h" #include "canceldomaintransfertoanotherawsaccountresponse.h" #include "checkdomainavailabilityrequest.h" #include "checkdomainavailabilityresponse.h" #include "checkdomaintransferabilityrequest.h" #include "checkdomaintransferabilityresponse.h" #include "deletetagsfordomainrequest.h" #include "deletetagsfordomainresponse.h" #include "disabledomainautorenewrequest.h" #include "disabledomainautorenewresponse.h" #include "disabledomaintransferlockrequest.h" #include "disabledomaintransferlockresponse.h" #include "enabledomainautorenewrequest.h" #include "enabledomainautorenewresponse.h" #include "enabledomaintransferlockrequest.h" #include "enabledomaintransferlockresponse.h" #include "getcontactreachabilitystatusrequest.h" #include "getcontactreachabilitystatusresponse.h" #include "getdomaindetailrequest.h" #include "getdomaindetailresponse.h" #include "getdomainsuggestionsrequest.h" #include "getdomainsuggestionsresponse.h" #include "getoperationdetailrequest.h" #include "getoperationdetailresponse.h" #include "listdomainsrequest.h" #include "listdomainsresponse.h" #include "listoperationsrequest.h" #include "listoperationsresponse.h" #include "listtagsfordomainrequest.h" #include "listtagsfordomainresponse.h" #include "registerdomainrequest.h" #include "registerdomainresponse.h" #include "rejectdomaintransferfromanotherawsaccountrequest.h" #include "rejectdomaintransferfromanotherawsaccountresponse.h" #include "renewdomainrequest.h" #include "renewdomainresponse.h" #include "resendcontactreachabilityemailrequest.h" #include "resendcontactreachabilityemailresponse.h" #include "retrievedomainauthcoderequest.h" #include "retrievedomainauthcoderesponse.h" #include "transferdomainrequest.h" #include "transferdomainresponse.h" #include "transferdomaintoanotherawsaccountrequest.h" #include "transferdomaintoanotherawsaccountresponse.h" #include "updatedomaincontactrequest.h" #include "updatedomaincontactresponse.h" #include "updatedomaincontactprivacyrequest.h" #include "updatedomaincontactprivacyresponse.h" #include "updatedomainnameserversrequest.h" #include "updatedomainnameserversresponse.h" #include "updatetagsfordomainrequest.h" #include "updatetagsfordomainresponse.h" #include "viewbillingrequest.h" #include "viewbillingresponse.h" #include <QNetworkAccessManager> #include <QNetworkRequest> /*! * \namespace QtAws::Route53Domains * \brief Contains classess for accessing Amazon Route 53 Domains. * * \inmodule QtAwsRoute53Domains * * @todo Move this to a separate template file. */ namespace QtAws { namespace Route53Domains { /*! * \class QtAws::Route53Domains::Route53DomainsClient * \brief The Route53DomainsClient class provides access to the Amazon Route 53 Domains service. * * \ingroup aws-clients * \inmodule QtAwsRoute53Domains * * Amazon Route 53 API actions let you register domain names and perform related */ /*! * \brief Constructs a Route53DomainsClient object. * * The new client object will \a region, \a credentials, and \a manager for * network operations. * * The new object will be owned by \a parent, if set. */ Route53DomainsClient::Route53DomainsClient( const QtAws::Core::AwsRegion::Region region, QtAws::Core::AwsAbstractCredentials * credentials, QNetworkAccessManager * const manager, QObject * const parent) : QtAws::Core::AwsAbstractClient(new Route53DomainsClientPrivate(this), parent) { Q_D(Route53DomainsClient); d->apiVersion = QStringLiteral("2014-05-15"); d->credentials = credentials; d->endpointPrefix = QStringLiteral("route53domains"); d->networkAccessManager = manager; d->region = region; d->serviceFullName = QStringLiteral("Amazon Route 53 Domains"); d->serviceName = QStringLiteral("route53domains"); } /*! * \overload Route53DomainsClient() * * This overload allows the caller to specify the specific \a endpoint to send * requests to. Typically, it is easier to use the alternative constructor, * which allows the caller to specify an AWS region instead, in which case this * client will determine the correct endpoint for the given region * automatically (via AwsEndpoint::getEndpoint). * * \sa QtAws::Core::AwsEndpoint::getEndpoint */ Route53DomainsClient::Route53DomainsClient( const QUrl &endpoint, QtAws::Core::AwsAbstractCredentials * credentials, QNetworkAccessManager * const manager, QObject * const parent) : QtAws::Core::AwsAbstractClient(new Route53DomainsClientPrivate(this), parent) { Q_D(Route53DomainsClient); d->apiVersion = QStringLiteral("2014-05-15"); d->credentials = credentials; d->endpoint = endpoint; d->endpointPrefix = QStringLiteral("route53domains"); d->networkAccessManager = manager; d->serviceFullName = QStringLiteral("Amazon Route 53 Domains"); d->serviceName = QStringLiteral("route53domains"); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * AcceptDomainTransferFromAnotherAwsAccountResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Accepts the transfer of a domain from another AWS account to the current AWS account. You initiate a transfer between * AWS accounts using <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>. * * </p * * Use either <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * to determine whether the operation succeeded. <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been * cancelled</code>. */ AcceptDomainTransferFromAnotherAwsAccountResponse * Route53DomainsClient::acceptDomainTransferFromAnotherAwsAccount(const AcceptDomainTransferFromAnotherAwsAccountRequest &request) { return qobject_cast<AcceptDomainTransferFromAnotherAwsAccountResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * CancelDomainTransferToAnotherAwsAccountResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Cancels the transfer of a domain from the current AWS account to another AWS account. You initiate a transfer between * AWS accounts using <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>. * * </p <b> * * You must cancel the transfer before the other AWS account accepts the transfer using <a * * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html">AcceptDomainTransferFromAnotherAwsAccount</a>> * </b> * * Use either <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * to determine whether the operation succeeded. <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been * cancelled</code>. */ CancelDomainTransferToAnotherAwsAccountResponse * Route53DomainsClient::cancelDomainTransferToAnotherAwsAccount(const CancelDomainTransferToAnotherAwsAccountRequest &request) { return qobject_cast<CancelDomainTransferToAnotherAwsAccountResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * CheckDomainAvailabilityResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation checks the availability of one domain name. Note that if the availability status of a domain is pending, * you must submit another request to determine the availability of the domain */ CheckDomainAvailabilityResponse * Route53DomainsClient::checkDomainAvailability(const CheckDomainAvailabilityRequest &request) { return qobject_cast<CheckDomainAvailabilityResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * CheckDomainTransferabilityResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Checks whether a domain name can be transferred to Amazon Route 53. */ CheckDomainTransferabilityResponse * Route53DomainsClient::checkDomainTransferability(const CheckDomainTransferabilityRequest &request) { return qobject_cast<CheckDomainTransferabilityResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * DeleteTagsForDomainResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation deletes the specified tags for a * * domain> * * All tag operations are eventually consistent; subsequent operations might not immediately represent all issued */ DeleteTagsForDomainResponse * Route53DomainsClient::deleteTagsForDomain(const DeleteTagsForDomainRequest &request) { return qobject_cast<DeleteTagsForDomainResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * DisableDomainAutoRenewResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation disables automatic renewal of domain registration for the specified */ DisableDomainAutoRenewResponse * Route53DomainsClient::disableDomainAutoRenew(const DisableDomainAutoRenewRequest &request) { return qobject_cast<DisableDomainAutoRenewResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * DisableDomainTransferLockResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation removes the transfer lock on the domain (specifically the <code>clientTransferProhibited</code> status) * to allow domain transfers. We recommend you refrain from performing this action unless you intend to transfer the domain * to a different registrar. Successful submission returns an operation ID that you can use to track the progress and * completion of the action. If the request is not completed successfully, the domain registrant will be notified by */ DisableDomainTransferLockResponse * Route53DomainsClient::disableDomainTransferLock(const DisableDomainTransferLockRequest &request) { return qobject_cast<DisableDomainTransferLockResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * EnableDomainAutoRenewResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation configures Amazon Route 53 to automatically renew the specified domain before the domain registration * expires. The cost of renewing your domain registration is billed to your AWS * * account> * * The period during which you can renew a domain name varies by TLD. For a list of TLDs and their renewal policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar-tld-list.html">Domains That You Can Register * with Amazon Route 53</a> in the <i>Amazon Route 53 Developer Guide</i>. Route 53 requires that you renew before the end * of the renewal period so we can complete processing before the */ EnableDomainAutoRenewResponse * Route53DomainsClient::enableDomainAutoRenew(const EnableDomainAutoRenewRequest &request) { return qobject_cast<EnableDomainAutoRenewResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * EnableDomainTransferLockResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation sets the transfer lock on the domain (specifically the <code>clientTransferProhibited</code> status) to * prevent domain transfers. Successful submission returns an operation ID that you can use to track the progress and * completion of the action. If the request is not completed successfully, the domain registrant will be notified by */ EnableDomainTransferLockResponse * Route53DomainsClient::enableDomainTransferLock(const EnableDomainTransferLockRequest &request) { return qobject_cast<EnableDomainTransferLockResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * GetContactReachabilityStatusResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * For operations that require confirmation that the email address for the registrant contact is valid, such as registering * a new domain, this operation returns information about whether the registrant contact has * * responded> * * If you want us to resend the email, use the <code>ResendContactReachabilityEmail</code> */ GetContactReachabilityStatusResponse * Route53DomainsClient::getContactReachabilityStatus(const GetContactReachabilityStatusRequest &request) { return qobject_cast<GetContactReachabilityStatusResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * GetDomainDetailResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation returns detailed information about a specified domain that is associated with the current AWS account. * Contact information for the domain is also returned as part of the */ GetDomainDetailResponse * Route53DomainsClient::getDomainDetail(const GetDomainDetailRequest &request) { return qobject_cast<GetDomainDetailResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * GetDomainSuggestionsResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * The GetDomainSuggestions operation returns a list of suggested domain */ GetDomainSuggestionsResponse * Route53DomainsClient::getDomainSuggestions(const GetDomainSuggestionsRequest &request) { return qobject_cast<GetDomainSuggestionsResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * GetOperationDetailResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation returns the current status of an operation that is not */ GetOperationDetailResponse * Route53DomainsClient::getOperationDetail(const GetOperationDetailRequest &request) { return qobject_cast<GetOperationDetailResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * ListDomainsResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation returns all the domain names registered with Amazon Route 53 for the current AWS */ ListDomainsResponse * Route53DomainsClient::listDomains(const ListDomainsRequest &request) { return qobject_cast<ListDomainsResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * ListOperationsResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Returns information about all of the operations that return an operation ID and that have ever been performed on domains * that were registered by the current account. */ ListOperationsResponse * Route53DomainsClient::listOperations(const ListOperationsRequest &request) { return qobject_cast<ListOperationsResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * ListTagsForDomainResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation returns all of the tags that are associated with the specified * * domain> * * All tag operations are eventually consistent; subsequent operations might not immediately represent all issued */ ListTagsForDomainResponse * Route53DomainsClient::listTagsForDomain(const ListTagsForDomainRequest &request) { return qobject_cast<ListTagsForDomainResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * RegisterDomainResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation registers a domain. Domains are registered either by Amazon Registrar (for .com, .net, and .org domains) * or by our registrar associate, Gandi (for all other domains). For some top-level domains (TLDs), this operation requires * extra * * parameters> * * When you register a domain, Amazon Route 53 does the * * following> <ul> <li> * * Creates a Route 53 hosted zone that has the same name as the domain. Route 53 assigns four name servers to your hosted * zone and automatically updates your domain registration with the names of these name * * servers> </li> <li> * * Enables autorenew, so your domain registration will renew automatically each year. We'll notify you in advance of the * renewal date so you can choose whether to renew the * * registration> </li> <li> * * Optionally enables privacy protection, so WHOIS queries return contact information either for Amazon Registrar (for * .com, .net, and .org domains) or for our registrar associate, Gandi (for all other TLDs). If you don't enable privacy * protection, WHOIS queries return the information that you entered for the registrant, admin, and tech * * contacts> </li> <li> * * If registration is successful, returns an operation ID that you can use to track the progress and completion of the * action. If the request is not completed successfully, the domain registrant is notified by * * email> </li> <li> * * Charges your AWS account an amount based on the top-level domain. For more information, see <a * href="http://aws.amazon.com/route53/pricing/">Amazon Route 53 */ RegisterDomainResponse * Route53DomainsClient::registerDomain(const RegisterDomainRequest &request) { return qobject_cast<RegisterDomainResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * RejectDomainTransferFromAnotherAwsAccountResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Rejects the transfer of a domain from another AWS account to the current AWS account. You initiate a transfer between * AWS accounts using <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>. * * </p * * Use either <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * to determine whether the operation succeeded. <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been * cancelled</code>. */ RejectDomainTransferFromAnotherAwsAccountResponse * Route53DomainsClient::rejectDomainTransferFromAnotherAwsAccount(const RejectDomainTransferFromAnotherAwsAccountRequest &request) { return qobject_cast<RejectDomainTransferFromAnotherAwsAccountResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * RenewDomainResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation renews a domain for the specified number of years. The cost of renewing your domain is billed to your AWS * * account> * * We recommend that you renew your domain several weeks before the expiration date. Some TLD registries delete domains * before the expiration date if you haven't renewed far enough in advance. For more information about renewing domain * registration, see <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-renew.html">Renewing * Registration for a Domain</a> in the <i>Amazon Route 53 Developer */ RenewDomainResponse * Route53DomainsClient::renewDomain(const RenewDomainRequest &request) { return qobject_cast<RenewDomainResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * ResendContactReachabilityEmailResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * For operations that require confirmation that the email address for the registrant contact is valid, such as registering * a new domain, this operation resends the confirmation email to the current email address for the registrant */ ResendContactReachabilityEmailResponse * Route53DomainsClient::resendContactReachabilityEmail(const ResendContactReachabilityEmailRequest &request) { return qobject_cast<ResendContactReachabilityEmailResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * RetrieveDomainAuthCodeResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation returns the AuthCode for the domain. To transfer a domain to another registrar, you provide this value to * the new */ RetrieveDomainAuthCodeResponse * Route53DomainsClient::retrieveDomainAuthCode(const RetrieveDomainAuthCodeRequest &request) { return qobject_cast<RetrieveDomainAuthCodeResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * TransferDomainResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Transfers a domain from another registrar to Amazon Route 53. When the transfer is complete, the domain is registered * either with Amazon Registrar (for .com, .net, and .org domains) or with our registrar associate, Gandi (for all other * * TLDs)> * * For more information about transferring domains, see the following * * topics> <ul> <li> * * For transfer requirements, a detailed procedure, and information about viewing the status of a domain that you're * transferring to Route 53, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-to-route-53.html">Transferring * Registration for a Domain to Amazon Route 53</a> in the <i>Amazon Route 53 Developer * * Guide</i>> </li> <li> * * For information about how to transfer a domain from one AWS account to another, see <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>. * * </p </li> <li> * * For information about how to transfer a domain to another domain registrar, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-from-route-53.html">Transferring a * Domain from Amazon Route 53 to Another Registrar</a> in the <i>Amazon Route 53 Developer * * Guide</i>> </li> </ul> * * If the registrar for your domain is also the DNS service provider for the domain, we highly recommend that you transfer * your DNS service to Route 53 or to another DNS service provider before you transfer your registration. Some registrars * provide free DNS service when you purchase a domain registration. When you transfer the registration, the previous * registrar will not renew your domain registration and could end your DNS service at any * * time> <b> * * If the registrar for your domain is also the DNS service provider for the domain and you don't transfer DNS service to * another provider, your website, email, and the web applications associated with the domain might become * * unavailable> </b> * * If the transfer is successful, this method returns an operation ID that you can use to track the progress and completion * of the action. If the transfer doesn't complete successfully, the domain registrant will be notified by */ TransferDomainResponse * Route53DomainsClient::transferDomain(const TransferDomainRequest &request) { return qobject_cast<TransferDomainResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * TransferDomainToAnotherAwsAccountResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Transfers a domain from the current AWS account to another AWS account. Note the * * following> <ul> <li> * * The AWS account that you're transferring the domain to must accept the transfer. If the other account doesn't accept the * transfer within 3 days, we cancel the transfer. See <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html">AcceptDomainTransferFromAnotherAwsAccount</a>. * * </p </li> <li> * * You can cancel the transfer before the other account accepts it. See <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_CancelDomainTransferToAnotherAwsAccount.html">CancelDomainTransferToAnotherAwsAccount</a>. * * </p </li> <li> * * The other account can reject the transfer. See <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_RejectDomainTransferFromAnotherAwsAccount.html">RejectDomainTransferFromAnotherAwsAccount</a>. * * </p </li> </ul> <b> * * When you transfer a domain from one AWS account to another, Route 53 doesn't transfer the hosted zone that is associated * with the domain. DNS resolution isn't affected if the domain and the hosted zone are owned by separate accounts, so * transferring the hosted zone is optional. For information about transferring the hosted zone to another AWS account, see * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-migrating.html">Migrating a Hosted Zone * to a Different AWS Account</a> in the <i>Amazon Route 53 Developer * * Guide</i>> </b> * * Use either <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * to determine whether the operation succeeded. <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been * cancelled</code>. */ TransferDomainToAnotherAwsAccountResponse * Route53DomainsClient::transferDomainToAnotherAwsAccount(const TransferDomainToAnotherAwsAccountRequest &request) { return qobject_cast<TransferDomainToAnotherAwsAccountResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * UpdateDomainContactResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation updates the contact information for a particular domain. You must specify information for at least one * contact: registrant, administrator, or * * technical> * * If the update is successful, this method returns an operation ID that you can use to track the progress and completion * of the action. If the request is not completed successfully, the domain registrant will be notified by */ UpdateDomainContactResponse * Route53DomainsClient::updateDomainContact(const UpdateDomainContactRequest &request) { return qobject_cast<UpdateDomainContactResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * UpdateDomainContactPrivacyResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation updates the specified domain contact's privacy setting. When privacy protection is enabled, contact * information such as email address is replaced either with contact information for Amazon Registrar (for .com, .net, and * .org domains) or with contact information for our registrar associate, * * Gandi> * * This operation affects only the contact information for the specified contact type (registrant, administrator, or tech). * If the request succeeds, Amazon Route 53 returns an operation ID that you can use with <a * href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a> * to track the progress and completion of the action. If the request doesn't complete successfully, the domain registrant * will be notified by * * email> <b> * * By disabling the privacy service via API, you consent to the publication of the contact information provided for this * domain via the public WHOIS database. You certify that you are the registrant of this domain name and have the authority * to make this decision. You may withdraw your consent at any time by enabling privacy protection using either * <code>UpdateDomainContactPrivacy</code> or the Route 53 console. Enabling privacy protection removes the contact * information provided for this domain from the WHOIS database. For more information on our privacy practices, see <a */ UpdateDomainContactPrivacyResponse * Route53DomainsClient::updateDomainContactPrivacy(const UpdateDomainContactPrivacyRequest &request) { return qobject_cast<UpdateDomainContactPrivacyResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * UpdateDomainNameserversResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation replaces the current set of name servers for the domain with the specified set of name servers. If you * use Amazon Route 53 as your DNS service, specify the four name servers in the delegation set for the hosted zone for the * * domain> * * If successful, this operation returns an operation ID that you can use to track the progress and completion of the * action. If the request is not completed successfully, the domain registrant will be notified by */ UpdateDomainNameserversResponse * Route53DomainsClient::updateDomainNameservers(const UpdateDomainNameserversRequest &request) { return qobject_cast<UpdateDomainNameserversResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * UpdateTagsForDomainResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * This operation adds or updates tags for a specified * * domain> * * All tag operations are eventually consistent; subsequent operations might not immediately represent all issued */ UpdateTagsForDomainResponse * Route53DomainsClient::updateTagsForDomain(const UpdateTagsForDomainRequest &request) { return qobject_cast<UpdateTagsForDomainResponse *>(send(request)); } /*! * Sends \a request to the Route53DomainsClient service, and returns a pointer to an * ViewBillingResponse object to track the result. * * \note The caller is to take responsbility for the resulting pointer. * * Returns all the domain-related billing records for the current AWS account for a specified */ ViewBillingResponse * Route53DomainsClient::viewBilling(const ViewBillingRequest &request) { return qobject_cast<ViewBillingResponse *>(send(request)); } /*! * \class QtAws::Route53Domains::Route53DomainsClientPrivate * \brief The Route53DomainsClientPrivate class provides private implementation for Route53DomainsClient. * \internal * * \ingroup aws-clients * \inmodule QtAwsRoute53Domains */ /*! * Constructs a Route53DomainsClientPrivate object with public implementation \a q. */ Route53DomainsClientPrivate::Route53DomainsClientPrivate(Route53DomainsClient * const q) : QtAws::Core::AwsAbstractClientPrivate(q) { signature = new QtAws::Core::AwsSignatureV4(); } } // namespace Route53Domains } // namespace QtAws
lgpl-3.0
hermelin/hermelin-universal
hermelin-gir/hermelin.py
14778
# -*- coding: UTF-8 -*- # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: '''Hermelin @author: U{Shellex Wei <5h3ll3x@gmail.com>} @license: LGPLv3+ ''' import os import sys import threading import time import config import gi gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') gi.require_version('GdkX11', '3.0') gi.require_version('WebKit', '3.0') from gi.repository import Gtk, Gdk, GObject, GdkPixbuf, GLib import utils, agent, view class Hermelin: def __init__(self): self.is_sign_in = False self.active_profile = 'default' self.protocol = '' self.build_gui() self.trayicon_pixbuf = [None, None] self.state = { 'unread_count': 0 } self.inblinking = False import dbusservice self.dbus_service = dbusservice.DbusService(self) if os.environ.get('DESKTOP_SESSION') not in ('ubuntu', 'ubuntu-2d'): self.has_indicator = False else: try: from gi.repository import AppIndicator3 as AppIndicator except ImportError: self.has_indicator = False else: self.has_indicator = True if self.has_indicator: self.indicator = AppIndicator.Indicator.new('hermelin', 'hermelin', AppIndicator.IndicatorCategory.COMMUNICATIONS) self.indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE) self.indicator.set_icon_theme_path(utils.get_ui_object('image/')) self.indicator.set_icon_full('ic24_hermelin_mono_light', 'hermelin') self.indicator.set_attention_icon_full('ic24_hermelin_mono_light_blink', 'hermelin') self.indicator.set_menu(self.traymenu) self.indicatorStatus = AppIndicator.IndicatorStatus else: self.create_trayicon() def build_gui(self): self.window = Gtk.Window() self.window.set_default_icon_from_file( utils.get_ui_object('image/ic128_hermelin.png')) self.window.set_icon_from_file( utils.get_ui_object('image/ic128_hermelin.png')) self.window.set_title(_("Hermelin")) self.window.set_position(Gtk.WindowPosition.CENTER) self.window.connect('delete-event', self.on_window_delete) # self.window.connect('size-allocate', self.on_window_size_allocate) self.window.connect('show', self.on_window_show_or_hide) self.window.connect('hide', self.on_window_show_or_hide) vbox = Gtk.VBox() scrollw = Gtk.ScrolledWindow() self.webv = view.MainView(scrollw) agent.view = self.webv scrollw.add(self.webv) vbox.pack_start(scrollw, True, True, 0) vbox.show_all() self.window.add(vbox) self.traymenu = Gtk.Menu() mitem_resume = Gtk.MenuItem.new_with_mnemonic(_("_Show")) mitem_resume.connect('activate', self.on_mitem_show_activate); self.traymenu.append(mitem_resume) mitem_resume = Gtk.MenuItem.new_with_mnemonic(_("_Hide")) mitem_resume.connect('activate', self.on_mitem_hide_activate); self.traymenu.append(mitem_resume) mitem_compose = Gtk.MenuItem.new_with_mnemonic(_("_Compose")) mitem_compose.connect('activate', self.on_mitem_compose); self.traymenu.append(mitem_compose) if (config.ENABLE_INSPECTOR): mitem_inspector = Gtk.ImageMenuItem.new_with_mnemonic(_("_Inspector")) mitem_inspector.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_FIND, Gtk.IconSize.MENU)) mitem_inspector.connect('activate', self.on_mitem_inspector_activate) self.traymenu.append(mitem_inspector) mitem_prefs = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_PREFERENCES, None) mitem_prefs.connect('activate', self.on_mitem_prefs_activate); self.traymenu.append(mitem_prefs) mitem_about = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_ABOUT, None) mitem_about.connect('activate', self.on_mitem_about_activate); self.traymenu.append(mitem_about) mitem_quit = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_QUIT, None) mitem_quit.connect('activate', self.on_mitem_quit_activate); self.traymenu.append(mitem_quit) self.traymenu.show_all() ## support for ubuntu unity indicator-appmenu self.menubar = Gtk.MenuBar() menuitem_file = Gtk.MenuItem.new_with_mnemonic(_("_File")) menuitem_file_menu = Gtk.Menu() mitem_resume = Gtk.MenuItem.new_with_mnemonic(_("_Show")) mitem_resume.connect('activate', self.on_mitem_show_activate) menuitem_file_menu.append(mitem_resume) mitem_compose = Gtk.MenuItem.new_with_mnemonic(_("_Compose")) mitem_compose.connect('activate', self.on_mitem_compose) menuitem_file_menu.append(mitem_compose) mitem_prefs = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_PREFERENCES, None) mitem_prefs.connect('activate', self.on_mitem_prefs_activate) menuitem_file_menu.append(mitem_prefs) if (config.ENABLE_INSPECTOR): mitem_inspector = Gtk.ImageMenuItem.new_with_mnemonic(_("_Inspector")) mitem_inspector.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_FIND, 16)) mitem_inspector.connect('activate', self.on_mitem_inspector_activate) menuitem_file_menu.append(mitem_inspector) menuitem_quit = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_QUIT, None) menuitem_quit.connect("activate", self.quit) menuitem_file_menu.append(menuitem_quit) menuitem_file.set_submenu(menuitem_file_menu) self.menubar.append(menuitem_file) menuitem_help = Gtk.MenuItem.new_with_mnemonic(_("_Help")) menuitem_help_menu = Gtk.Menu() menuitem_about = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_ABOUT, None) menuitem_about.connect("activate", self.on_mitem_about_activate) menuitem_help_menu.append(menuitem_about) menuitem_help.set_submenu(menuitem_help_menu) self.menubar.append(menuitem_help) self.menubar.set_size_request(0, 0) self.menubar.show_all() self.menubar.hide() vport = Gtk.Viewport() vport.set_size_request(0, 0) vport.add(self.menubar) vbox.pack_start(vport, False, False, False) ## geometry = Gdk.Geometry() geometry.min_height = 400 geometry.min_width = 460 self.window.set_geometry_hints(self.window, geometry, Gdk.WindowHints.MIN_SIZE) self.window.show() def update_status(self, text): self.webv.execute_script('update_status("%s")' % text) def unread_alert(self, count=0): if count > 0: self.start_blinking() else: self.stop_blinking() if not self.has_indicator: self.trayicon.set_tooltip_text("Hermelin: %d unread tweets/messages." % count if count > 0 else _("Hermelin: Click to Active.")) self.state['unread_count'] = count def start_blinking(self): if self.inblinking: return def blink_proc(): flag = 0 while self.inblinking: if self.has_indicator: self.indicator.set_status(self.indicatorStatus.ATTENTION if flag else self.indicatorStatus.ACTIVE) else: self.trayicon.set_from_pixbuf(self.trayicon_pixbuf[flag]) flag ^= 1 time.sleep(1) if self.has_indicator: self.indicator.set_status(self.indicatorStatus.ACTIVE) else: self.trayicon.set_from_pixbuf(self.trayicon_pixbuf[0]) self.inblinking = True th = threading.Thread(target = blink_proc) th.start() def stop_blinking(self): self.inblinking = False def on_window_delete(self, widget, event): if 'close_to_exit' in config.settings and config.settings['close_to_exit']: self.quit() else: return widget.hide_on_delete() def on_window_size_allocate(self, widget, allocation): x, y = self.window.get_position() script = 'if (typeof conf!=="undefined"){conf.settings.pos_x=%d; \ conf.settings.pos_y=%d;}' % (x, y) GObject.idle_add(self.webv.execute_script, script) def on_window_show_or_hide(self, widget): menuitems = self.traymenu.get_children() if self.window.get_visible(): menuitems[0].hide(); menuitems[1].show(); else: menuitems[1].hide(); menuitems[0].show(); def on_mitem_show_activate(self, item): self.window.present() def on_mitem_hide_activate(self, item): self.window.hide() def on_mitem_inspector_activate(self, item): inspector = self.webv.get_inspector() inspector.show() def on_mitem_prefs_activate(self, item): agent.execute_script(''' ui.PrefsDlg.load_settings(conf.settings); ui.PrefsDlg.load_prefs(); globals.prefs_dialog.open();'''); self.window.present() def on_mitem_compose(self, item): if self.is_sign_in: agent.execute_script('ui.StatusBox.open();') self.window.present() def on_mitem_about_activate(self, item): agent.execute_script('globals.about_dialog.open();'); self.window.present() def on_mitem_quit_activate(self, item): self.quit() def quit(self, *args): self.release_hotkey() self.stop_blinking() self.window.destroy() Gtk.main_quit() def apply_settings(self): # init hotkey self.init_hotkey() # resize window self.window.set_gravity(Gdk.Gravity.CENTER) self.window.resize( config.settings['size_w'] , config.settings['size_h']) # apply proxy self.apply_proxy_setting() # starts minimized if config.settings['starts_minimized']: self.window.hide() def apply_proxy_setting(self): proxy_type = agent.get_prefs('proxy_type') if proxy_type == 'http': proxy_host = agent.get_prefs('proxy_host') proxy_port = agent.get_prefs('proxy_port') proxy_scheme = 'https' if agent.get_prefs('proxy_auth'): auth_user = agent.get_prefs('proxy_auth_name') auth_pass = agent.get_prefs('proxy_auth_password') utils.webkit_set_proxy_uri(proxy_scheme, proxy_host, proxy_port, auth_user, auth_pass) else: utils.webkit_set_proxy_uri(proxy_scheme, proxy_host, proxy_port) elif proxy_type == 'system': if 'HTTP_PROXY' in os.environ and os.environ["HTTP_PROXY"]: url = os.environ["HTTP_PROXY"] elif 'http_proxy' in os.environ and os.environ["http_proxy"]: url = os.environ["http_proxy"] else: url = None utils.webkit_set_proxy_uri(url) elif proxy_type == 'socks': # TODO not implemented yet utils.webkit_set_proxy_uri() else: utils.webkit_set_proxy_uri() # workaround for a BUG of webkitgtk/soupsession # proxy authentication agent.execute_script(''' new Image().src='http://google.com/';'''); def init_hotkey(self): try: import xhotkey xhk = xhotkey.XHotKey() keydesc = config.settings['shortcut_summon_hermelin'] keycode, modifiers = xhk.parse(keydesc) if keycode is None: print "cannot register hotkey: %s" % keydesc else: xhk.bind(keycode, modifiers, self.on_hotkey_compose) xhk.start() self.xhk = xhk; except ImportError: print "python-xlib was not installed, global hotkey disabled." pass def release_hotkey(self): if hasattr(self, "xhk"): self.xhk.clear() self.xhk.stop() def create_trayicon(self): """ Create status icon and connect signals """ self.trayicon = Gtk.StatusIcon() self.trayicon.connect('activate', self.on_trayicon_activate) self.trayicon.connect('popup-menu', self.on_trayicon_popup_menu) self.trayicon.set_tooltip_text(_("Hermelin: Click to Active.")) self.trayicon_pixbuf[0] = GdkPixbuf.Pixbuf.new_from_file( utils.get_ui_object('image/ic24_hermelin_mono_light.svg')) self.trayicon_pixbuf[1] = GdkPixbuf.Pixbuf.new_from_file( utils.get_ui_object('image/ic24_hermelin_mono_light_blink.svg')) self.trayicon.set_from_pixbuf(self.trayicon_pixbuf[0]) self.trayicon.set_visible(True) def on_trayicon_activate(self, icon): GObject.idle_add(self._on_trayicon_activate, icon) def _on_trayicon_activate(self, icon): if self.window.get_visible(): self.window.hide() else: self.stop_blinking() self.window.present() def on_trayicon_popup_menu(self, icon, button, activate_time): self.traymenu.popup(None, None , None, None, button=button , activate_time=activate_time) def on_hotkey_compose(self, event): GObject.idle_add(self._on_hotkey_compose) def _on_hotkey_compose(self): if not self.webv.is_focus(): self.window.hide() self.window.present() self.webv.grab_focus() def on_sign_in(self): self.is_sign_in = True #self.window.set_title('Hermelin | %s' % '$') def on_sign_out(self): self.is_sign_in = False def usage(): print '''Usage: hermelin [OPTION...] -d, --dev enable hermelin inspector -h, --help display this help''' def main(): for opt in sys.argv[1:]: if opt in ('-h', '--help'): usage() return elif opt in ('-d', '--dev'): config.ENABLE_INSPECTOR = True else: print "hermelin: unrecognized option '%s'" % opt usage() sys.exit(1) try: import i18n except: from gettext import gettext as _ try: import prctl prctl.set_name('hermelin') except: pass #g_thread_init has been deprecated since version 2.32 if GLib.check_version(2, 32, 0): GObject.threads_init() Gdk.threads_init() Gtk.init(None) config.init(); agent.app = Hermelin() Gdk.threads_enter() Gtk.main() Gdk.threads_leave() if __name__ == '__main__': main()
lgpl-3.0
Francis1993Z/UltraShooter
include/ShrapnelWeapon.hpp
341
#ifndef SHRAPNELWEAPON_HPP_INCLUDED #define SHRAPNELWEAPON_HPP_INCLUDED #include "Weapon.hpp" class ShrapnelWeapon : public Weapon { public: ShrapnelWeapon(Entity const& my_user, bool p_tirIllimity, unsigned int p_ammunitions, sf::Vector2f pos); void fire(); sf::Sprite* getSymbole(); }; #endif // SHRAPNELWEAPON_HPP_INCLUDED
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/screenplays/tasks/booto_lubble.lua
2281
booto_lubble_missions = { { missionType = "confiscate", primarySpawns = { { npcTemplate = "luhin_jinnor", planetName = "rori", npcName = "Warrant Officer Luhin Jinnor" } }, secondarySpawns = { { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" }, { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" }, { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/booto_lubble_q1_needed.iff", itemName = "" } }, rewards = { { rewardType = "credits", amount = 50 } } }, { missionType = "confiscate", primarySpawns = { { npcTemplate = "rohd_gostervek", planetName = "rori", npcName = "Captain Rohd Gostervek" } }, secondarySpawns = { { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" }, { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" }, { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" }, { npcTemplate = "stormtrooper", planetName = "rori", npcName = "" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/booto_lubble_q2_needed.iff", itemName = "" } }, rewards = { { rewardType = "credits", amount = 50 }, { rewardType = "faction", faction = "rebel", amount = 10 } } }, } npcMapBootoLubble = { { spawnData = { planetName = "rori", npcTemplate = "booto_lubble", x = 4.0, z = 0.7, y = 0.5, direction = 170, cellID = 4505791, position = STAND }, worldPosition = { x = 3701, y = -6488 }, npcNumber = 1, stfFile = "@static_npc/rori/rori_rebeloutpost_booto_lubble", missions = booto_lubble_missions }, } BootoLubble = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapBootoLubble, permissionMap = {}, className = "BootoLubble", screenPlayState = "booto_lubble_quest", distance = 800, missionDescriptionStf = "", missionCompletionMessageStf = "@theme_park/messages:static_completion_message", faction = FACTIONREBEL } registerScreenPlay("BootoLubble", true) booto_lubble_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = BootoLubble } booto_lubble_mission_target_conv_handler = mission_target_conv_handler:new { themePark = BootoLubble }
lgpl-3.0
gsauthof/libgrammar
grammar/tsort.hh
907
// Copyright 2015, Georg Sauthoff <mail@georg.so> /* {{{ LGPLv3 This file is part of libgrammar. libgrammar 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. libgrammar 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 libgrammar. If not, see <http://www.gnu.org/licenses/>. }}} */ #ifndef GRAMMAR_TSORT_HH #define GRAMMAR_TSORT_HH namespace grammar { class Grammar; void tsort(Grammar &g); } #endif
lgpl-3.0
coenbijlsma/dashboard-backend
src/backend/Domain/Core/RequestScope.php
665
<?php namespace Dashboard\Backend\Domain\Core; class RequestScope { private static $instance = null; private $data; private function __construct() { $this->data = new \stdClass; } public static function instance() { if (self::$instance === null) { self::$instance = new RequestScope(); } return self::$instance; } public function isDefined(string $key): bool { return isset($this->data->{$key}); } public function get(string $key) { return $this->data->{$key}; } public function set(string $key, $value) { $this->data->{$key} = $value; } }
lgpl-3.0
ashutoshvt/psi4
psi4/share/psi4/databases/A24.py
29689
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2021 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 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, version 3. # # Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # """ | Database (Hobza) of interaction energies for bimolecular complexes. | Geometries from <Reference>. | Reference interaction energies from Rezac and Hobza, JCTC (in press). - **cp** ``'off'`` <erase this comment and after unless on is a valid option> || ``'on'`` - **rlxd** ``'off'`` <erase this comment and after unless on is valid option> || ``'on'`` - **benchmark** - ``'<benchmark_name>'`` <Reference>. - |dl| ``'<default_benchmark_name>'`` |dr| <Reference>. - **subset** - ``'small'`` <members_description> - ``'large'`` <members_description> - ``'<subset>'`` <members_description> """ import re import qcdb # <<< A24 Database Module >>> dbse = 'A24' # <<< Database Members >>> HRXN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] HRXN_SM = [] HRXN_LG = [] # <<< Chemical Systems Involved >>> RXNM = {} # reaction matrix of reagent contributions per reaction ACTV = {} # order of active reagents per reaction ACTV_CP = {} # order of active reagents per counterpoise-corrected reaction ACTV_SA = {} # order of active reagents for non-supermolecular calculations for rxn in HRXN: RXNM[ '%s-%s' % (dbse, rxn)] = {'%s-%s-dimer' % (dbse, rxn) : +1, '%s-%s-monoA-CP' % (dbse, rxn) : -1, '%s-%s-monoB-CP' % (dbse, rxn) : -1, '%s-%s-monoA-unCP' % (dbse, rxn) : -1, '%s-%s-monoB-unCP' % (dbse, rxn) : -1 } ACTV_SA['%s-%s' % (dbse, rxn)] = ['%s-%s-dimer' % (dbse, rxn) ] ACTV_CP['%s-%s' % (dbse, rxn)] = ['%s-%s-dimer' % (dbse, rxn), '%s-%s-monoA-CP' % (dbse, rxn), '%s-%s-monoB-CP' % (dbse, rxn) ] ACTV[ '%s-%s' % (dbse, rxn)] = ['%s-%s-dimer' % (dbse, rxn), '%s-%s-monoA-unCP' % (dbse, rxn), '%s-%s-monoB-unCP' % (dbse, rxn) ] # <<< Reference Values [kcal/mol] from Rezac and Hobza dx.doi.org/10.1021/ct400057w >>> BIND = {} BIND['%s-%s' % (dbse, 1 )] = -6.524 BIND['%s-%s' % (dbse, 2 )] = -5.014 BIND['%s-%s' % (dbse, 3 )] = -4.749 BIND['%s-%s' % (dbse, 4 )] = -4.572 BIND['%s-%s' % (dbse, 5 )] = -3.157 BIND['%s-%s' % (dbse, 6 )] = -1.679 BIND['%s-%s' % (dbse, 7 )] = -0.779 BIND['%s-%s' % (dbse, 8 )] = -0.672 BIND['%s-%s' % (dbse, 9 )] = -4.474 BIND['%s-%s' % (dbse, 10 )] = -2.578 BIND['%s-%s' % (dbse, 11 )] = -1.629 BIND['%s-%s' % (dbse, 12 )] = -1.537 BIND['%s-%s' % (dbse, 13 )] = -1.389 BIND['%s-%s' % (dbse, 14 )] = -1.110 BIND['%s-%s' % (dbse, 15 )] = -0.514 BIND['%s-%s' % (dbse, 16 )] = -1.518 BIND['%s-%s' % (dbse, 17 )] = -0.837 BIND['%s-%s' % (dbse, 18 )] = -0.615 BIND['%s-%s' % (dbse, 19 )] = -0.538 BIND['%s-%s' % (dbse, 20 )] = -0.408 BIND['%s-%s' % (dbse, 21 )] = -0.370 BIND['%s-%s' % (dbse, 22 )] = 0.784 BIND['%s-%s' % (dbse, 23 )] = 0.897 BIND['%s-%s' % (dbse, 24 )] = 1.075 # <<< Comment Lines >>> TAGL = {} TAGL['%s-%s' % (dbse, 1)] = """ water_ammonia_Cs """ TAGL['%s-%s-dimer' % (dbse, 1)] = """Dimer from water_ammonia_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 1)] = """Monomer A water_ammonia_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 1)] = """Monomer B water_ammonia_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 1)] = """Monomer A water_ammonia_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 1)] = """Monomer B water_ammonia_Cs """ TAGL['%s-%s' % (dbse, 2)] = """ water_water_Cs """ TAGL['%s-%s-dimer' % (dbse, 2)] = """Dimer from water_water_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 2)] = """Monomer A from water_water_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 2)] = """Monomer B from water_water_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 2)] = """Monomer A from water_water_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 2)] = """Monomer B from water_water_Cs """ TAGL['%s-%s' % (dbse, 3)] = """ HCN_HCN_Cxv """ TAGL['%s-%s-dimer' % (dbse, 3)] = """Dimer from HCN_HCN_Cxv """ TAGL['%s-%s-monoA-CP' % (dbse, 3)] = """Monomer A from HCN_HCN_Cxv """ TAGL['%s-%s-monoB-CP' % (dbse, 3)] = """Monomer B from HCN_HCN_Cxv """ TAGL['%s-%s-monoA-unCP' % (dbse, 3)] = """Monomer A from HCN_HCN_Cxv """ TAGL['%s-%s-monoB-unCP' % (dbse, 3)] = """Monomer B from HCN_HCN_Cxv """ TAGL['%s-%s' % (dbse, 4)] = """ HF_HF_Cs """ TAGL['%s-%s-dimer' % (dbse, 4)] = """Dimer from HF_HF_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 4)] = """Monomer A from HF_HF_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 4)] = """Monomer B from HF_HF_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 4)] = """Monomer A from HF_HF_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 4)] = """Monomer B from HF_HF_Cs """ TAGL['%s-%s' % (dbse, 5)] = """ ammonia_ammonia_C2h """ TAGL['%s-%s-dimer' % (dbse, 5)] = """Dimer from ammonia_ammonia_C2h """ TAGL['%s-%s-monoA-CP' % (dbse, 5)] = """Monomer A from ammonia_ammonia_C2h """ TAGL['%s-%s-monoB-CP' % (dbse, 5)] = """Monomer B from ammonia_ammonia_C2h """ TAGL['%s-%s-monoA-unCP' % (dbse, 5)] = """Monomer A from ammonia_ammonia_C2h """ TAGL['%s-%s-monoB-unCP' % (dbse, 5)] = """Monomer B from ammonia_ammonia_C2h """ TAGL['%s-%s' % (dbse, 6)] = """ methane_HF_C3v """ TAGL['%s-%s-dimer' % (dbse, 6)] = """Dimer from methane_HF_C3v """ TAGL['%s-%s-monoA-CP' % (dbse, 6)] = """Monomer A from methane_HF_C3v """ TAGL['%s-%s-monoB-CP' % (dbse, 6)] = """Monomer B from methane_HF_C3v """ TAGL['%s-%s-monoA-unCP' % (dbse, 6)] = """Monomer A from methane_HF_C3v """ TAGL['%s-%s-monoB-unCP' % (dbse, 6)] = """Monomer B from methane_HF_C3v """ TAGL['%s-%s' % (dbse, 7)] = """ ammmonia_methane_C3v """ TAGL['%s-%s-dimer' % (dbse, 7)] = """Dimer from ammmonia_methane_C3v """ TAGL['%s-%s-monoA-CP' % (dbse, 7)] = """Monomer A from ammmonia_methane_C3v """ TAGL['%s-%s-monoB-CP' % (dbse, 7)] = """Monomer B from ammmonia_methane_C3v """ TAGL['%s-%s-monoA-unCP' % (dbse, 7)] = """Monomer A from ammmonia_methane_C3v """ TAGL['%s-%s-monoB-unCP' % (dbse, 7)] = """Monomer B from ammmonia_methane_C3v """ TAGL['%s-%s' % (dbse, 8)] = """ methane_water_Cs """ TAGL['%s-%s-dimer' % (dbse, 8)] = """Dimer from methane_water_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 8)] = """Monomer A from methane_water_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 8)] = """Monomer B from methane_water_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 8)] = """Monomer A from methane_water_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 8)] = """Monomer B from methane_water_Cs """ TAGL['%s-%s' % (dbse, 9)] = """ formaldehyde_formaldehyde_Cs """ TAGL['%s-%s-dimer' % (dbse, 9)] = """Dimer from formaldehyde_formaldehyde_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 9)] = """Monomer A from formaldehyde_formaldehyde_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 9)] = """Monomer B from formaldehyde_formaldehyde_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 9)] = """Monomer A from formaldehyde_formaldehyde_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 9)] = """Monomer B from formaldehyde_formaldehyde_Cs """ TAGL['%s-%s' % (dbse, 10)] = """ ethene_wat_Cs """ TAGL['%s-%s-dimer' % (dbse, 10)] = """Dimer from ethene_wat_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 10)] = """Monomer A from ethene_wat_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 10)] = """Monomer B from ethene_wat_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 10)] = """Monomer A from ethene_wat_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 10)] = """Monomer B from ethene_wat_Cs """ TAGL['%s-%s' % (dbse, 11)] = """ ethene_formaldehyde_Cs """ TAGL['%s-%s-dimer' % (dbse, 11)] = """Dimer from ethene_formaldehyde_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 11)] = """Monomer A from ethene_formaldehyde_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 11)] = """Monomer B from ethene_formaldehyde_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 11)] = """Monomer A from ethene_formaldehyde_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 11)] = """Monomer B from ethene_formaldehyde_Cs """ TAGL['%s-%s' % (dbse, 12)] = """ ethyne_ethyne_C2v """ TAGL['%s-%s-dimer' % (dbse, 12)] = """Dimer from ethyne_ethyne_C2v """ TAGL['%s-%s-monoA-CP' % (dbse, 12)] = """Monomer A from ethyne_ethyne_C2v """ TAGL['%s-%s-monoB-CP' % (dbse, 12)] = """Monomer B from ethyne_ethyne_C2v """ TAGL['%s-%s-monoA-unCP' % (dbse, 12)] = """Monomer A from ethyne_ethyne_C2v """ TAGL['%s-%s-monoB-unCP' % (dbse, 12)] = """Monomer B from ethyne_ethyne_C2v """ TAGL['%s-%s' % (dbse, 13)] = """ ethene_ammonia_Cs """ TAGL['%s-%s-dimer' % (dbse, 13)] = """Dimer from ethene_ammonia_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 13)] = """Monomer A from ethene_ammonia_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 13)] = """Monomer B from ethene_ammonia_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 13)] = """Monomer A from ethene_ammonia_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 13)] = """Monomer B from ethene_ammonia_Cs """ TAGL['%s-%s' % (dbse, 14)] = """ ethene_ethene_C2v """ TAGL['%s-%s-dimer' % (dbse, 14)] = """Dimer from ethene_ethene_C2v """ TAGL['%s-%s-monoA-CP' % (dbse, 14)] = """Monomer A from ethene_ethene_C2v """ TAGL['%s-%s-monoB-CP' % (dbse, 14)] = """Monomer B from ethene_ethene_C2v """ TAGL['%s-%s-monoA-unCP' % (dbse, 14)] = """Monomer A from ethene_ethene_C2v """ TAGL['%s-%s-monoB-unCP' % (dbse, 14)] = """Monomer B from ethene_ethene_C2v """ TAGL['%s-%s' % (dbse, 15)] = """ methane_ethene_Cs """ TAGL['%s-%s-dimer' % (dbse, 15)] = """Dimer from methane_ethene_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 15)] = """Monomer A from methane_ethene_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 15)] = """Monomer B from methane_ethene_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 15)] = """Monomer A from methane_ethene_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 15)] = """Monomer B from methane_ethene_Cs """ TAGL['%s-%s' % (dbse, 16)] = """ borane_methane_Cs """ TAGL['%s-%s-dimer' % (dbse, 16)] = """Dimer from borane_methane_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 16)] = """Monomer A from borane_methane_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 16)] = """Monomer B from borane_methane_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 16)] = """Monomer A from borane_methane_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 16)] = """Monomer B from borane_methane_Cs """ TAGL['%s-%s' % (dbse, 17)] = """ methane_ethane_Cs """ TAGL['%s-%s-dimer' % (dbse, 17)] = """Dimer from methane_ethane_Cs """ TAGL['%s-%s-monoA-CP' % (dbse, 17)] = """Monomer A from methane_ethane_Cs """ TAGL['%s-%s-monoB-CP' % (dbse, 17)] = """Monomer B from methane_ethane_Cs """ TAGL['%s-%s-monoA-unCP' % (dbse, 17)] = """Monomer A from methane_ethane_Cs """ TAGL['%s-%s-monoB-unCP' % (dbse, 17)] = """Monomer B from methane_ethane_Cs """ TAGL['%s-%s' % (dbse, 18)] = """ methane_ethane_C3 """ TAGL['%s-%s-dimer' % (dbse, 18)] = """Dimer from methane_ethane_C3 """ TAGL['%s-%s-monoA-CP' % (dbse, 18)] = """Monomer A from methane_ethane_C3 """ TAGL['%s-%s-monoB-CP' % (dbse, 18)] = """Monomer B from methane_ethane_C3 """ TAGL['%s-%s-monoA-unCP' % (dbse, 18)] = """Monomer A from methane_ethane_C3 """ TAGL['%s-%s-monoB-unCP' % (dbse, 18)] = """Monomer B from methane_ethane_C3 """ TAGL['%s-%s' % (dbse, 19)] = """ methane_methane_D3d """ TAGL['%s-%s-dimer' % (dbse, 19)] = """Dimer from methane_methane_D3d """ TAGL['%s-%s-monoA-CP' % (dbse, 19)] = """Monomer A from methane_methane_D3d """ TAGL['%s-%s-monoB-CP' % (dbse, 19)] = """Monomer B from methane_methane_D3d """ TAGL['%s-%s-monoA-unCP' % (dbse, 19)] = """Monomer A from methane_methane_D3d """ TAGL['%s-%s-monoB-unCP' % (dbse, 19)] = """Monomer B from methane_methane_D3d """ TAGL['%s-%s' % (dbse, 20)] = """ methane_Ar_C3v """ TAGL['%s-%s-dimer' % (dbse, 20)] = """Dimer from methane_Ar_C3v """ TAGL['%s-%s-monoA-CP' % (dbse, 20)] = """Monomer A from methane_Ar_C3v """ TAGL['%s-%s-monoB-CP' % (dbse, 20)] = """Monomer B from methane_Ar_C3v """ TAGL['%s-%s-monoA-unCP' % (dbse, 20)] = """Monomer A from methane_Ar_C3v """ TAGL['%s-%s-monoB-unCP' % (dbse, 20)] = """Monomer B from methane_Ar_C3v """ TAGL['%s-%s' % (dbse, 21)] = """ ethene_Ar_C2v """ TAGL['%s-%s-dimer' % (dbse, 21)] = """Dimer from ethene_Ar_C2v """ TAGL['%s-%s-monoA-CP' % (dbse, 21)] = """Monomer A from ethene_Ar_C2v """ TAGL['%s-%s-monoB-CP' % (dbse, 21)] = """Monomer B from ethene_Ar_C2v """ TAGL['%s-%s-monoA-unCP' % (dbse, 21)] = """Monomer A from ethene_Ar_C2v """ TAGL['%s-%s-monoB-unCP' % (dbse, 21)] = """Monomer B from ethene_Ar_C2v """ TAGL['%s-%s' % (dbse, 22)] = """ ethene_ethyne_C2v """ TAGL['%s-%s-dimer' % (dbse, 22)] = """Dimer from ethene_ethyne_C2v """ TAGL['%s-%s-monoA-CP' % (dbse, 22)] = """Monomer A from ethene_ethyne_C2v """ TAGL['%s-%s-monoB-CP' % (dbse, 22)] = """Monomer B from ethene_ethyne_C2v """ TAGL['%s-%s-monoA-unCP' % (dbse, 22)] = """Monomer A from ethene_ethyne_C2v """ TAGL['%s-%s-monoB-unCP' % (dbse, 22)] = """Monomer B from ethene_ethyne_C2v """ TAGL['%s-%s' % (dbse, 23)] = """ ethene_ethene_D2h """ TAGL['%s-%s-dimer' % (dbse, 23)] = """Dimer from ethene_ethene_D2h """ TAGL['%s-%s-monoA-CP' % (dbse, 23)] = """Monomer A from ethene_ethene_D2h """ TAGL['%s-%s-monoB-CP' % (dbse, 23)] = """Monomer B from ethene_ethene_D2h """ TAGL['%s-%s-monoA-unCP' % (dbse, 23)] = """Monomer A from ethene_ethene_D2h """ TAGL['%s-%s-monoB-unCP' % (dbse, 23)] = """Monomer B from ethene_ethene_D2h """ TAGL['%s-%s' % (dbse, 24)] = """ ethyne_ethyne_D2h """ TAGL['%s-%s-dimer' % (dbse, 24)] = """Dimer from ethyne_ethyne_D2h """ TAGL['%s-%s-monoA-CP' % (dbse, 24)] = """Monomer A from ethyne_ethyne_D2h """ TAGL['%s-%s-monoB-CP' % (dbse, 24)] = """Monomer B from ethyne_ethyne_D2h """ TAGL['%s-%s-monoA-unCP' % (dbse, 24)] = """Monomer A from ethyne_ethyne_D2h """ TAGL['%s-%s-monoB-unCP' % (dbse, 24)] = """Monomer B from ethyne_ethyne_D2h """ # <<< Geometry Specification Strings >>> GEOS = {} GEOS['%s-%s-dimer' % (dbse, '1')] = qcdb.Molecule(""" 0 1 O 0.00000000 -0.05786571 -1.47979303 H 0.00000000 0.82293384 -1.85541474 H 0.00000000 0.07949567 -0.51934253 -- 0 1 N 0.00000000 0.01436394 1.46454628 H 0.00000000 -0.98104857 1.65344779 H -0.81348351 0.39876776 1.92934049 H 0.81348351 0.39876776 1.92934049 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '2')] = qcdb.Molecule(""" 0 1 O -0.06699914 0.00000000 1.49435474 H 0.81573427 0.00000000 1.86586639 H 0.06885510 0.00000000 0.53914277 -- 0 1 O 0.06254775 0.00000000 -1.42263208 H -0.40696540 -0.76017841 -1.77174450 H -0.40696540 0.76017841 -1.77174450 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '3')] = qcdb.Molecule(""" 0 1 H 0.00000000 0.00000000 3.85521306 C 0.00000000 0.00000000 2.78649976 N 0.00000000 0.00000000 1.63150791 -- 0 1 H 0.00000000 0.00000000 -0.59377492 C 0.00000000 0.00000000 -1.66809824 N 0.00000000 0.00000000 -2.82525056 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '4')] = qcdb.Molecule(""" 0 1 H 0.00000000 0.80267982 1.69529329 F 0.00000000 -0.04596666 1.34034818 -- 0 1 H 0.00000000 -0.12040787 -0.49082840 F 0.00000000 0.00976945 -1.40424978 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '5')] = qcdb.Molecule(""" 0 1 N -0.04998129 -1.58709323 0.00000000 H 0.12296265 -2.16846018 0.81105976 H 0.12296265 -2.16846018 -0.81105976 H 0.65988580 -0.86235298 0.00000000 -- 0 1 N 0.04998129 1.58709323 0.00000000 H -0.12296265 2.16846018 0.81105976 H -0.65988580 0.86235298 0.00000000 H -0.12296265 2.16846018 -0.81105976 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '6')] = qcdb.Molecule(""" 0 1 C 0.00000000 -0.00000000 1.77071609 H 0.51593378 -0.89362352 1.42025061 H -0.00000000 0.00000000 2.85805859 H 0.51593378 0.89362352 1.42025061 H -1.03186756 0.00000000 1.42025061 -- 0 1 H -0.00000000 0.00000000 -0.54877328 F -0.00000000 0.00000000 -1.46803256 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '7')] = qcdb.Molecule(""" 0 1 N -0.00000000 0.00000000 1.84833659 H 0.93730979 -0.00000000 2.23206741 H -0.46865489 -0.81173409 2.23206741 H -0.46865489 0.81173409 2.23206741 -- 0 1 H 0.00000000 -0.00000000 -0.94497174 C 0.00000000 -0.00000000 -2.03363752 H 0.51251439 0.88770096 -2.40095125 H 0.51251439 -0.88770096 -2.40095125 H -1.02502878 0.00000000 -2.40095125 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '8')] = qcdb.Molecule(""" 0 1 C 0.00069016 0.00000000 -1.99985520 H -0.50741740 0.88759452 -2.37290605 H 1.03052749 0.00000000 -2.35282982 H -0.01314396 0.00000000 -0.91190852 H -0.50741740 -0.88759452 -2.37290605 -- 0 1 O -0.00472553 0.00000000 1.71597466 H 0.03211863 0.75755459 2.30172044 H 0.03211863 -0.75755459 2.30172044 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '9')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.60123980 -1.35383976 O 0.00000000 -0.59301814 -1.55209021 H 0.93542250 1.17427624 -1.26515132 H -0.93542250 1.17427624 -1.26515132 -- 0 1 C 0.00000000 -0.60200476 1.55228866 O 0.00000000 0.59238638 1.35511328 H 0.00000000 -1.00937982 2.57524635 H 0.00000000 -1.32002906 0.71694997 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '10')] = qcdb.Molecule(""" 0 1 C 0.01058825 -0.66806246 1.29820809 C 0.01058825 0.66806246 1.29820809 H 0.86863216 1.23267933 0.95426815 H -0.84608285 1.23258495 1.64525385 H -0.84608285 -1.23258495 1.64525385 H 0.86863216 -1.23267933 0.95426815 -- 0 1 H -0.79685627 0.00000000 -2.50911038 O 0.04347445 0.00000000 -2.04834054 H -0.19067546 0.00000000 -1.11576944 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '11')] = qcdb.Molecule(""" 0 1 C 0.00000000 -0.59797089 1.47742864 C 0.00000000 0.42131196 2.33957848 H 0.92113351 -1.02957102 1.10653516 H -0.92113351 -1.02957102 1.10653516 H -0.92393815 0.85124826 2.70694633 H 0.92393815 0.85124826 2.70694633 -- 0 1 O 0.00000000 -0.51877334 -1.82845679 C 0.00000000 0.68616220 -1.73709412 H 0.00000000 1.33077474 -2.63186355 H 0.00000000 1.18902807 -0.75645498 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '12')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.60356400 -2.18173438 H 0.00000000 1.66847581 -2.18429610 C 0.00000000 -0.60356400 -2.18173438 H 0.00000000 -1.66847581 -2.18429610 -- 0 1 C -0.00000000 0.00000000 1.57829513 H -0.00000000 0.00000000 0.51136193 C -0.00000000 0.00000000 2.78576543 H -0.00000000 0.00000000 3.85017859 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '13')] = qcdb.Molecule(""" 0 1 C 0.00000000 -0.59662248 1.58722206 C 0.00000000 0.68258238 1.20494642 H 0.92312147 1.22423658 1.04062463 H -0.92312147 1.22423658 1.04062463 H -0.92388993 -1.13738548 1.75121281 H 0.92388993 -1.13738548 1.75121281 -- 0 1 N 0.00000000 -0.00401379 -2.31096701 H -0.81122549 -0.45983060 -2.71043881 H 0.00000000 -0.22249432 -1.32128161 H 0.81122549 -0.45983060 -2.71043881 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '14')] = qcdb.Molecule(""" 0 1 H 0.92444510 -1.23172221 -1.90619313 H -0.92444510 -1.23172221 -1.90619313 H -0.92444510 1.23172221 -1.90619313 H 0.92444510 1.23172221 -1.90619313 C 0.00000000 0.66728778 -1.90556520 C 0.00000000 -0.66728778 -1.90556520 -- 0 1 H -0.00000000 1.23344948 2.82931792 H 0.00000000 1.22547148 0.97776199 H -0.00000000 -1.22547148 0.97776199 H -0.00000000 -1.23344948 2.82931792 C -0.00000000 -0.66711698 1.90601042 C -0.00000000 0.66711698 1.90601042 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '15')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.64634385 -1.60849815 C 0.00000000 -0.67914355 -1.45381675 H -0.92399961 -1.24016223 -1.38784883 H 0.92399961 -1.24016223 -1.38784883 H 0.92403607 1.20737602 -1.67357285 H -0.92403607 1.20737602 -1.67357285 -- 0 1 H 0.00000000 0.08295411 1.59016711 C 0.00000000 0.02871509 2.67711785 H 0.88825459 0.52261990 3.06664029 H -0.88825459 0.52261990 3.06664029 H 0.00000000 -1.01394800 2.98955227 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '16')] = qcdb.Molecule(""" 0 1 C 0.00346000 0.00000000 1.38045208 H 0.84849635 0.00000000 0.68958651 H 0.39513333 0.00000000 2.39584935 H -0.60268447 -0.88994299 1.22482674 H -0.60268447 0.88994299 1.22482674 -- 0 1 B -0.00555317 0.00000000 -1.59887976 H 0.58455128 -1.03051800 -1.67949525 H 0.58455128 1.03051800 -1.67949525 H -1.18903148 0.00000000 -1.47677217 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '17')] = qcdb.Molecule(""" 0 1 C 0.00000000 -0.06374421 2.42054090 H 0.00000000 1.02169396 2.34238038 H 0.88828307 -0.46131911 1.93307194 H -0.88828307 -0.46131911 1.93307194 H 0.00000000 -0.35363606 3.46945195 -- 0 1 C 0.00000000 0.78133572 -1.13543912 H 0.00000000 1.37465349 -2.05114442 H -0.88043002 1.06310554 -0.55580918 C 0.00000000 -0.71332890 -1.44723686 H 0.88043002 1.06310554 -0.55580918 H 0.00000000 -1.30641812 -0.53140693 H -0.88100343 -0.99533072 -2.02587154 H 0.88100343 -0.99533072 -2.02587154 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '18')] = qcdb.Molecule(""" 0 1 C -0.00000000 0.00000000 -2.85810471 H 0.39304720 -0.94712229 -2.49369739 H 0.62370837 0.81395000 -2.49369739 H -1.01675556 0.13317229 -2.49369739 H 0.00000000 -0.00000000 -3.94634214 -- 0 1 C 0.00000000 -0.00000000 0.76143405 C -0.00000000 -0.00000000 2.28821715 H -0.61711193 -0.80824397 0.36571527 H -0.39140385 0.93855659 0.36571527 H 1.00851577 -0.13031262 0.36571527 H -1.00891703 0.13031295 2.68258296 H 0.39160418 -0.93890425 2.68258296 H 0.61731284 0.80859130 2.68258296 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '19')] = qcdb.Molecule(""" 0 1 C -0.00000000 0.00000000 1.81901457 H 0.51274115 0.88809373 1.45476743 H 0.51274115 -0.88809373 1.45476743 H -1.02548230 0.00000000 1.45476743 H 0.00000000 -0.00000000 2.90722072 -- 0 1 C 0.00000000 -0.00000000 -1.81901457 H -0.00000000 0.00000000 -2.90722072 H -0.51274115 0.88809373 -1.45476743 H -0.51274115 -0.88809373 -1.45476743 H 1.02548230 -0.00000000 -1.45476743 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '20')] = qcdb.Molecule(""" 0 1 C -0.00000000 0.00000000 -2.62458428 H 0.51286762 0.88831278 -2.26110195 H 0.51286762 -0.88831278 -2.26110195 H -0.00000000 0.00000000 -3.71273928 H -1.02573525 0.00000000 -2.26110195 -- 0 1 AR -0.00000000 0.00000000 1.05395172 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '21')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.66718073 -2.29024825 C 0.00000000 -0.66718073 -2.29024825 H -0.92400768 1.23202333 -2.28975239 H 0.92400768 1.23202333 -2.28975239 H -0.92400768 -1.23202333 -2.28975239 H 0.92400768 -1.23202333 -2.28975239 -- 0 1 AR -0.00000000 0.00000000 1.60829261 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '22')] = qcdb.Molecule(""" 0 1 H -0.92396100 1.23195600 -1.68478123 H 0.92396100 1.23195600 -1.68478123 H 0.92396100 -1.23195600 -1.68478123 H -0.92396100 -1.23195600 -1.68478123 C 0.00000000 0.66717600 -1.68478123 C 0.00000000 -0.66717600 -1.68478123 -- 0 1 H -0.00000000 -1.66786500 1.81521877 H -0.00000000 1.66786500 1.81521877 C -0.00000000 -0.60339700 1.81521877 C -0.00000000 0.60339700 1.81521877 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '23')] = qcdb.Molecule(""" 0 1 H -0.92396100 1.23195600 -1.75000000 H 0.92396100 1.23195600 -1.75000000 H 0.92396100 -1.23195600 -1.75000000 H -0.92396100 -1.23195600 -1.75000000 C 0.00000000 0.66717600 -1.75000000 C -0.00000000 -0.66717600 -1.75000000 -- 0 1 H -0.92396100 1.23195600 1.75000000 H 0.92396100 1.23195600 1.75000000 H 0.92396100 -1.23195600 1.75000000 H -0.92396100 -1.23195600 1.75000000 C 0.00000000 0.66717600 1.75000000 C -0.00000000 -0.66717600 1.75000000 units angstrom """) GEOS['%s-%s-dimer' % (dbse, '24')] = qcdb.Molecule(""" 0 1 H -0.00000000 -1.66786500 -1.75000000 H 0.00000000 1.66786500 -1.75000000 C -0.00000000 -0.60339700 -1.75000000 C 0.00000000 0.60339700 -1.75000000 -- 0 1 H -0.00000000 -1.66786500 1.75000000 H 0.00000000 1.66786500 1.75000000 C -0.00000000 -0.60339700 1.75000000 C 0.00000000 0.60339700 1.75000000 units angstrom """) # <<< Derived Geometry Strings >>> for rxn in HRXN: GEOS['%s-%s-monoA-unCP' % (dbse, rxn)] = GEOS['%s-%s-dimer' % (dbse, rxn)].extract_fragments(1) GEOS['%s-%s-monoB-unCP' % (dbse, rxn)] = GEOS['%s-%s-dimer' % (dbse, rxn)].extract_fragments(2) GEOS['%s-%s-monoA-CP' % (dbse, rxn)] = GEOS['%s-%s-dimer' % (dbse, rxn)].extract_fragments(1, 2) GEOS['%s-%s-monoB-CP' % (dbse, rxn)] = GEOS['%s-%s-dimer' % (dbse, rxn)].extract_fragments(2, 1)
lgpl-3.0
SergeR/webasyst-framework
wa-plugins/shipping/flatrate/lib/flatrateShipping.class.php
6391
<?php /** * Flat-rate shipping plugin. * * @property-read float $cost * @property-read string $currency * @property-read string $delivery * @property-read bool $prompt_address * @package wa-plugin/shipping * */ class flatrateShipping extends waShipping { /** * Main shipping rate calculation method. * Returns array of estimated shipping rates and transit times. * or error message to be displayed to customer, * or false, if this shipping option must not be available under certain conditions. * * @example <pre> * //return array of shipping options * return array( * 'option_id_1' => array( * 'name' => $this->_w('...'), * 'description' => $this->_w('...'), * 'est_delivery' => '...', * 'currency' => $this->currency, * 'rate' => $this->cost, * ), * ... * ); * * //return error message * return 'Для расчета стоимости доставки укажите регион доставки'; * * //shipping option is unavailable * return false;</pre> * * Useful parent class (waShipping) methods to be used in calculate() method: * * <pre> * // total package price * $price = $this->getTotalPrice(); * * // total package weight * $weight = $this->getTotalWeight(); * * // order items array * $items = $this->getItems(); * * // obtain either full address info array or specified address field value * $address = $this->getAddress($field = null);</pre> * * @return mixed */ public function calculate() { if ($this->delivery === '') { $est_delivery = null; } else { $est_delivery = waDateTime::format('humandate', strtotime($this->delivery)); } return array( 'ground' => array( 'name' => $this->_w('Ground shipping'), 'description' => '', 'est_delivery' => $est_delivery, //string 'currency' => $this->currency, 'rate' => $this->cost, ), ); } /** * Returns ISO3 code of the currency (or array of ISO3 codes) this plugin supports. * * @see waShipping::allowedCurrency() * @return array|string */ public function allowedCurrency() { // return array('USD', 'EUR') or simple string: 'USD' return $this->currency; } /** * Returns the weight unit (or array of weight units) this plugin supports. * * @see waShipping::allowedWeightUnit() * @return array|string */ public function allowedWeightUnit() { // return array('kg','lbs') or simple string: 'kg' return 'kg'; } /** * Returns general tracking information (HTML). * * @see waShipping::tracking() * @example return _wp('Online shipment tracking: <a href="link">link</a>.'); * @param string $tracking_id Optional tracking id specified by user. * @return string */ public function tracking($tracking_id = null) { // this shipping plugin does not provide shipping tracking information return ''; } /** * Returns array of printable forms this plugin offers * * @example return <pre>array( * 'form_id' => array( * 'name' => _wp('Printform name'), * 'description' => _wp('Printform description'), * ), * );</pre> * @param waOrder $order Object containing order data * @return array */ public function getPrintForms(waOrder $order = null) { // this shipping plugin does not generate printable forms return array(); } /** * Returns HTML code of specified printable form. * * @param string $id Printform id as defined in method getPrintForms() * @param waOrder $order Order data object * @param array $params Optional parameters to be passed to printform generation template * @throws waException * @return string Printform HTML */ public function displayPrintForm($id, waOrder $order, $params = array()) { if ('flatrate_form' == $id) { $view = wa()->getView(); $view->assign('order', $order); $view->assign('params', $params); $view->assign('plugin', $this); return $view->fetch($this->path.'/templates/form.html'); } else { throw new waException($this->_w('Printable form not found')); } } /** * Limits the range of customer addresses to allow shipping to. * * @example <pre>return array( * 'country' => 'usa', # or array('usa', 'can') * 'region' => 'NY', * # or array('NY', 'PA', 'CT'); * # or omit 'region' item if you do not want to limit shipping to certain regions * );</pre> * @return array Return array() to allow shipping anywhere */ public function allowedAddress() { //this plugin allows shipping orders to any addresses without limitations return array(); } /** * Returns array of shipping address fields which must be requested during checkout. * * @see waShipping::requestedAddressFields() * @example <pre>return array( * #requested field * 'zip' => array(), * * #hidden field with pre-defined value; * 'country' => array('hidden' => true, 'value' => 'rus', 'cost' => true), * * #'cost' parameter means that field is used for calculation of approximate shipping cost during checkout * 'region' => array('cost' => true), * 'city' => array(), * * #field is not requested * 'street' => false, * );</pre> * @return array|bool Return false if plugin does not request any fields during checkout; * return array() if all address fields must be requested */ public function requestedAddressFields() { //request either all or no address fields depending on the value of the corresponding plugin settings option return $this->prompt_address ? array() : false; } }
lgpl-3.0
SAMPProjects/Open-SAMP-API
src/Open-SAMP-API/Game/GTA/World.hpp
232
#pragma once namespace Game { namespace GTA { bool ScreenToWorld(float screenX, float screenY, float &worldX, float &worldY, float &worldZ); bool WorldToScreen(float x, float y, float z, float &screenX, float &screenY); } }
lgpl-3.0
pauloremoli/terrama2
webapp/public/javascripts/angular/countries/services/countries.js
1939
define(function() { /** * It handles the available countries languages supported by TerraMA² * @param {angular.IHttp} $http - Angular HTTP module * @param {angular.IQ} $q - Angular Promiser module * @returns {Object} */ function TerraMA2Countries($http, $q) { /** * Remote host url * @type {string} */ var targetUrl = "/javascripts/angular/countries/data.json"; /** * It defines a cached countries * @private data * @type {Object[]} */ var data = []; /** * It defines a selected country * @todo Validate it. * @type {Object} */ var selected = null; return { /** * It initializes TerraMA2Countries factory to retrieve countries from remote host and cache them * * @returns {angular.IPromise<Object[]>} */ init: function() { var defer = $q.defer(); $http.get(targetUrl, {}) .then(function(output) { data = output.data; return defer.resolve(output); }) .catch(function(response) { return defer.reject(response.data); }); return defer.promise; }, /** * It changes current url context. Once changed, it must be initialized again * * @param {string} url - A target url to change */ setUrl: function(url) { targetUrl = url || targetUrl; }, /** * Retrieve cached countries * * @returns {Object[]} */ getData: function() { return data; }, /** * It sets current selected country * @todo Validate it. * @param {string} country - A selected country in list. */ select: function(country) { return $http.post("/languages", {locale: country}); } }; } TerraMA2Countries.$inject = ["$http", "$q"]; return TerraMA2Countries; });
lgpl-3.0
BackupTheBerlios/digilib
text/src/main/java/digilib/conf/TextServletConfiguration.java
3898
package digilib.conf; /* * #%L * * TextServletConfiguration -- Holding all parameters for text servlet. * * Digital Image Library servlet components * %% * Copyright (C) 2003 - 2013 MPIWG Berlin * %% * This program 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. * * 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% * Author: Robert Casties (robcast@berlios.de) * Created on 3.1.2014 */ import java.io.File; import javax.servlet.ServletContext; import digilib.io.AliasingDocuDirCache; import digilib.io.DocuDirCache; import digilib.io.FileOps.FileClass; import digilib.servlet.ServletOps; /** * Class to hold the digilib servlet configuration parameters. The parameters * can be read from the digilib-config file and be passed to other servlets or * beans. * * @author casties * */ public class TextServletConfiguration extends DigilibServletConfiguration { public static final String TEXT_SERVLET_CONFIG_KEY = "digilib.text.servlet.configuration"; public static final String TEXT_DIR_CACHE_KEY = "text.servlet.dir.cache"; public static String getVersion() { return "2.3.0 txt"; } /** * Constructs DigilibServletConfiguration and defines all parameters and * their default values. */ public TextServletConfiguration() { super(); // text cache instance newParameter(TEXT_DIR_CACHE_KEY, null, null, 's'); } /* * (non-Javadoc) * * @see digilib.conf.DigilibServletConfiguration#configure(javax.servlet. * ServletContext) */ @Override public void configure(ServletContext context) { super.configure(context); DigilibServletConfiguration config = this; // set version setValue("servlet.version", TextServletConfiguration.getVersion()); try { // directory cache for text files String[] bd = (String[]) config.getValue("basedir-list"); DocuDirCache dirCache; if (config.getAsBoolean("use-mapping")) { // with mapping file File mapConf = ServletOps.getConfigFile((File) config.getValue("mapping-file"), context); dirCache = new AliasingDocuDirCache(bd, FileClass.TEXT, mapConf, config); config.setValue("mapping-file", mapConf); } else { // without mapping dirCache = new DocuDirCache(bd, FileClass.TEXT, this); } config.setValue(TEXT_DIR_CACHE_KEY, dirCache); } catch (Exception e) { logger.error("Error configuring digilib servlet:", e); } } /** * Sets the current DigilibConfiguration in the context. * @param context */ public void setCurrentConfig(ServletContext context) { context.setAttribute(TextServletConfiguration.TEXT_SERVLET_CONFIG_KEY, this); } /** * Returns the current TextServletConfiguration from the context. * * @param context * @return */ public static DigilibServletConfiguration getCurrentConfig(ServletContext context) { DigilibServletConfiguration config = (DigilibServletConfiguration) context .getAttribute(TextServletConfiguration.TEXT_SERVLET_CONFIG_KEY); return config; } }
lgpl-3.0
deib-polimi/SPF
framework/SPFWFDMid/src/it/polimi/deib/spf/wfd/ResponseHolder.java
1527
/* * Copyright 2014 Jacopo Aliprandi, Dario Archetti * * This file is part of SPF. * * SPF 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. * * SPF 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 SPF. If not, see <http://www.gnu.org/licenses/>. * */ package it.polimi.deib.spf.wfd; public class ResponseHolder { private final long REQ_TIMEOUT; private WfdMessage msg; private boolean threadWaiting = false; private long requestSequenceId = 0; public ResponseHolder(long timeout) { this.REQ_TIMEOUT = timeout; } public synchronized void set(WfdMessage msg) { long sequenceNum = msg.getTimestamp(); if (threadWaiting && sequenceNum == requestSequenceId) { this.msg = msg; notify(); } } public synchronized WfdMessage get() throws InterruptedException { if (msg == null) { threadWaiting = true; wait(REQ_TIMEOUT); WfdMessage _tmpMsg = msg; msg = null; threadWaiting = false; return _tmpMsg; } return null; } public long assignRequestSequenceId() { return ++requestSequenceId; } }
lgpl-3.0
mobmewireless/origami-pdf
lib/origami/graphics.rb
1115
=begin = File graphics.rb = Info This file is part of Origami, PDF manipulation framework for Ruby Copyright (C) 2010 Guillaume Delugré <guillaume@security-labs.org> All right reserved. Origami 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. Origami 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 Origami. If not, see <http://www.gnu.org/licenses/>. =end require 'origami/graphics/instruction' require 'origami/graphics/colors' require 'origami/graphics/path' require 'origami/graphics/xobject' require 'origami/graphics/patterns' require 'origami/graphics/text' require 'origami/graphics/state' require 'origami/graphics/render'
lgpl-3.0
unajPrSwGrupo1/OrgLogist2015
basic/controllers/RrhhController.php
4152
<?php namespace app\controllers; use Yii; use app\models\Rrhh; use app\models\RrhhSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * RrhhController implements the CRUD actions for Rrhh model. */ class RrhhController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all Rrhh models. * @return mixed */ public function actionIndex() { $searchModel = new RrhhSearch(); $searchModel->setTableMode1(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } public function actionInactiv() { $searchModel = new RrhhSearch(); $searchModel->setTableMode0(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Rrhh model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Rrhh model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Rrhh(); $model->activate = 1; $model->descript = ""; if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->descript=$model->Apellido.", ".$model->Nombre.", ".$model->Edad." años"; $model->save(); return $this->redirect(['view', 'id' => $model->idRRHH]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Rrhh model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->idRRHH]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Rrhh model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $desactiv=$this->findActiv($id); $desactiv->activate = 0; if ($desactiv->update()!== false){ return $this->redirect(['index']); } else{ echo "Ha ocurrido un error al realizar el registro, redireccionando ..."; echo "<meta http-equiv='refresh' content='8; ".Url::toRoute("rrhh")."'>"; } } /** * Finds the Rrhh model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Rrhh the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Rrhh::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } protected function findActiv($id) { if (($model = Rrhh::find()->where("idRRHH=:idRRHH",[":idRRHH" => $id] ) ->andWhere("activate=:activate",[":activate" => 1])->one()) !== null) { return $model; } else { throw new NotFoundHttpException('Persona desactivada del sistema.'); } } }
lgpl-3.0
jphuynh/Aikau
aikau/src/main/resources/alfresco/pickers/DocumentListPicker.js
13578
/** * Copyright (C) 2005-2016 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ /** * <p>This extends the standard [document list]{@link module:alfresco/documentlibrary/AlfDocumentList} to * define a document list specifically for selecting documents (e.g. for starting workflows, etc). It was * written to be used as part of a [picker]{@link module:alfresco/pickers/Picker} and specifically one that * is used as a form control.</p> * * @module alfresco/pickers/DocumentListPicker * @extends module:alfresco/documentlibrary/AlfDocumentList * @author Dave Draper */ define(["dojo/_base/declare", "alfresco/documentlibrary/AlfDocumentList", "dojo/_base/lang", "alfresco/core/ArrayUtils"], function(declare, AlfDocumentList, lang, arrayUtils) { return declare([AlfDocumentList], { /** * Overrides the [inherited value]{@link module:alfresco/lists/AlfList#waitForPageWidgets} to ensure that pickers * don't wait for the page to be loaded (as typically the page will be loaded long before the picker is opened). * This can still be overridden again in configuration when creating a new picker. * * @instance * @type {boolean} * @default */ waitForPageWidgets: false, /** * Overrides the [inherited value]{@link module:alfresco/lists/AlfHashList#useHash} to indicate that the location * should not be driven by changes to the browser URL hash * * @instance * @type {boolean} * @default */ useHash: false, /** * This nodeRefRef is used to limit navigation up the directory, to constrain the picker to the a certain path. * It can be passed in on config, but if not, it will be set the first time loadData is called. * * @instance * @type {String} * @default */ rootNodeRef: null, /** * Enable site mode. * In site mode the peer folders of the documentlibrary container are hidden and we skip straight to documentlibrary's children * * @instance * @type {Boolean} * @default */ siteMode: false, /** * This topic that is published when a document is picked. By default it is the topic that indicates * that the document has been selected. * * @instance * @type {string} * @default */ publishTopic: "ALF_ITEM_SELECTED", /** * This is the type of payload published when a document is picked. By default it is the current * item type. * * @instance * @type {string} * @default */ publishPayloadType: "CURRENT_ITEM", /** * This is the configured payload published when a document is picked. By default it is null * * @instance * @type {object} * @default */ publishPayload: null, /** * This indicates whether the current item should be mixed into the published payload. By * default this is false (because the default type is to just publish the current item) * * @instance * @type {boolean} * @default */ publishPayloadItemMixin: false, /** * The modifiers to apply to the publish payload. This should only be set if the * [publishPayloadType]{@link module:alfresco/pickers/DocumentListPicker#publishPayloadType} * is set to "PROCESS". * * @instance * @type {array} * @default */ publishPayloadModifiers: null, /** * Overrides the [inherited function]{@link module:alfresco/lists/AlfList#postCreate} to create the picker * view for selecting documents. * * @instance */ postCreate: function alfresco_pickers_DocumentListPicker__postCreate() { this.processObject(["processInstanceTokens"], this.widgets); this.processWidgets(this.widgets, this.itemsNode); }, /** * Override the default implementation to call [loadData]{@link module:alfresco/documentlibrary/AlfDocumentList#loadData} * with the currently selected folder node. * * @instance * @param {object} payload * @todo Refactor this code to accept the same payload format as {@link module:alfresco/documentlibrary/AlfDocumentList#onItemClick} */ onFolderClick: function alfresco_pickers_DocumentListPicker__onFolderClick(payload) { var targetNode = lang.getObject("item.nodeRef", false, payload) || lang.getObject("node.nodeRef", false, payload) || payload.nodeRef; if (targetNode) { this.nodeRef = targetNode; // Make sure we go back to page one when the new list is requested. this.resetPaginationData(); this.loadData(); } else { this.alfLog("warn", "A 'nodeRef' attribute was expected to be provided for a folder click", payload, this); } }, /** * Overrides inherited function to do a no-op. The pick action should be handled by a * [PublishAction widget]{@link module:alfresco/renderers/PublishAction}. * * @instance * @param {object} payload */ onDocumentClick: function alfresco_pickers_DocumentListPicker__onDocumentClick(payload) { // jshint unused:false // No action. }, /** * Extends [loadData]{@link module:alfresco/documentlibrary/AlfDocumentList#loadData} to store the rootNodeRef. * @instance */ loadData: function alfresco_pickers_DocumentListPicker__loadData() { if (!this.rootNodeRef) { this.rootNodeRef = this.nodeRef; } // Enable or disable the parent navigation if (this.nodeRef === this.rootNodeRef) { this.alfPublish("ALF_INVALID_CONTROL", {}); } else { this.alfPublish("ALF_VALID_CONTROL", {}); } this.inherited(arguments); }, /** * Overrides [onDataLoadSuccess]{@link module:alfresco/documentlibrary/AlfList#onDataLoadSuccess} to skip children. * * @instance * @param {object} payload */ onDataLoadSuccess: function alfresco_pickers_DocumentListPicker__onDataLoadSuccess(payload) { var parentType = lang.getObject("response.metadata.parent.type", false, payload); // Allow parent nav functionality to work when node information passed in was a well known node. if (this.rootNodeRef.indexOf("alfresco://") !== -1) { // If an alfresco:// prefixed path was passed in, we need to update it to the nodeRef now we have it var parentNodeRef = lang.getObject("response.metadata.parent.nodeRef", false, payload); if (parentNodeRef) { this.rootNodeRef = parentNodeRef; } else { this.alfLog("warn", "Couldn't retrieve parentNodeRef, this means the back parent nav button will appear when it shouldn't"); } } // If we're in site mode and the returned items are direct children of a site node, skip to the documentlibrary if (this.siteMode && parentType === "st:site") { // Find the "documentLibrary" node in the response items var items = lang.getObject("response.items", false, payload), doclibNode = arrayUtils.findInArray(items, "documentLibrary", "fileName"), doclibNodeRef = lang.getObject("node.nodeRef", false, doclibNode); if (doclibNodeRef) { // once we have the node ref, load it using the same mechanism as before. this.rootNodeRef = doclibNodeRef; this.onFolderClick({nodeRef: doclibNodeRef}); } else { this.alfLog("error", "Unable to retrieve nodeRef for documentLibrary folder."); } } else { this.inherited(arguments); } }, /** * The default widgets for the picker. This can be overridden at instantiation based on what is required to be * displayed in the picker. * * @instance * @type {array} */ widgets: [ { name: "alfresco/lists/views/AlfListView", config: { widgets: [ { name: "alfresco/lists/views/layouts/Row", config: { widgets: [ { name: "alfresco/lists/views/layouts/Cell", config: { width: "20px", widgets: [ { name: "alfresco/renderers/FileType", config: { size: "small", renderAsLink: true, publishTopic: "ALF_DOCLIST_NAV" } } ] } }, { name: "alfresco/lists/views/layouts/Cell", config: { widgets: [ { name: "alfresco/renderers/PropertyLink", config: { propertyToRender: "node.properties.cm:title", renderAsLink: true, publishTopic: "ALF_DOCLIST_NAV", renderFilter: [ { property: "node.type", values: ["st:site"] } ] } }, { name: "alfresco/renderers/PropertyLink", config: { propertyToRender: "node.properties.cm:name", renderAsLink: true, publishTopic: "ALF_DOCLIST_NAV", renderFilter: [ { property: "node.type", values: ["st:site"], negate: true } ] } } ] } }, { name: "alfresco/lists/views/layouts/Cell", config: { width: "20px", widgets: [ { name: "alfresco/renderers/PublishAction", config: { publishTopic: "{publishTopic}", publishPayloadType: "{publishPayloadType}", publishPayload: "{publishPayload}", publishPayloadItemMixin: "{publishPayloadItemMixin}", publishPayloadModifiers: "{publishPayloadModifiers}", renderFilter: [ { property: "node.isContainer", values: [false] } ] } } ] } } ] } } ] } } ] }); });
lgpl-3.0
clstoulouse/motu
motu-web/src/main/java/fr/cls/atoll/motu/web/usl/wcs/request/parameter/validator/RangeSubsetHTTPParameterValidator.java
1997
package fr.cls.atoll.motu.web.usl.wcs.request.parameter.validator; import fr.cls.atoll.motu.web.common.utils.StringUtils; import fr.cls.atoll.motu.web.usl.request.parameter.exception.InvalidHTTPParameterException; import fr.cls.atoll.motu.web.usl.request.parameter.validator.AbstractHTTPParameterValidator; /** * <br> * <br> * Copyright : Copyright (c) 2016 <br> * <br> * Société : CLS (Collecte Localisation Satellites) * * @author Sylvain MARTY * @version $Revision: 1.1 $ - $Date: 2007-05-22 16:56:28 $ */ public class RangeSubsetHTTPParameterValidator extends AbstractHTTPParameterValidator<String> { public RangeSubsetHTTPParameterValidator(String parameterName_, String parameterValue_) { super(parameterName_, parameterValue_); } public RangeSubsetHTTPParameterValidator(String parameterName_, String parameterValue_, String defaultValue_) { this(parameterName_, parameterValue_); if (StringUtils.isNullOrEmpty(parameterValue_)) { setParameterValue(defaultValue_); } } /** * . * */ @Override public String onValidateAction() throws InvalidHTTPParameterException { String rangeStr = getParameterValue(); if (isParameterOptional()) { if (rangeStr == null || !"".equals(rangeStr)) { return rangeStr; } else { throw new InvalidHTTPParameterException(getParameterName(), getParameterValue(), getParameterBoundaries()); } } else if (rangeStr == null || "".equals(rangeStr)) { throw new InvalidHTTPParameterException(getParameterName(), getParameterValue(), getParameterBoundaries()); } else { return rangeStr; } } @Override protected String getParameterBoundaries() { if (isParameterOptional()) { return "Optional but can not be empty if is provided"; } else { return "Can not be empty"; } } }
lgpl-3.0
twlostow/dsi-shield
hdl/rtl/fmlarb/Manifest.py
76
files = ["fmlarb_dack.v", "fmlarb.v", "fml_wb_bridge.v"];
lgpl-3.0
matthieu/go-ethereum
core/asm/asm.go
3625
// Copyright 2017 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // Provides support for dealing with EVM assembly instructions (e.g., disassembling them). package asm import ( "encoding/hex" "fmt" "github.com/matthieu/go-ethereum/core/vm" ) // Iterator for disassembled EVM instructions type instructionIterator struct { code []byte pc uint64 arg []byte op vm.OpCode error error started bool } // Create a new instruction iterator. func NewInstructionIterator(code []byte) *instructionIterator { it := new(instructionIterator) it.code = code return it } // Returns true if there is a next instruction and moves on. func (it *instructionIterator) Next() bool { if it.error != nil || uint64(len(it.code)) <= it.pc { // We previously reached an error or the end. return false } if it.started { // Since the iteration has been already started we move to the next instruction. if it.arg != nil { it.pc += uint64(len(it.arg)) } it.pc++ } else { // We start the iteration from the first instruction. it.started = true } if uint64(len(it.code)) <= it.pc { // We reached the end. return false } it.op = vm.OpCode(it.code[it.pc]) if it.op.IsPush() { a := uint64(it.op) - uint64(vm.PUSH1) + 1 u := it.pc + 1 + a if uint64(len(it.code)) <= it.pc || uint64(len(it.code)) < u { it.error = fmt.Errorf("incomplete push instruction at %v", it.pc) return false } it.arg = it.code[it.pc+1 : u] } else { it.arg = nil } return true } // Returns any error that may have been encountered. func (it *instructionIterator) Error() error { return it.error } // Returns the PC of the current instruction. func (it *instructionIterator) PC() uint64 { return it.pc } // Returns the opcode of the current instruction. func (it *instructionIterator) Op() vm.OpCode { return it.op } // Returns the argument of the current instruction. func (it *instructionIterator) Arg() []byte { return it.arg } // Pretty-print all disassembled EVM instructions to stdout. func PrintDisassembled(code string) error { script, err := hex.DecodeString(code) if err != nil { return err } it := NewInstructionIterator(script) for it.Next() { if it.Arg() != nil && 0 < len(it.Arg()) { fmt.Printf("%05x: %v 0x%x\n", it.PC(), it.Op(), it.Arg()) } else { fmt.Printf("%05x: %v\n", it.PC(), it.Op()) } } return it.Error() } // Return all disassembled EVM instructions in human-readable format. func Disassemble(script []byte) ([]string, error) { instrs := make([]string, 0) it := NewInstructionIterator(script) for it.Next() { if it.Arg() != nil && 0 < len(it.Arg()) { instrs = append(instrs, fmt.Sprintf("%05x: %v 0x%x\n", it.PC(), it.Op(), it.Arg())) } else { instrs = append(instrs, fmt.Sprintf("%05x: %v\n", it.PC(), it.Op())) } } if err := it.Error(); err != nil { return nil, err } return instrs, nil }
lgpl-3.0
LegumeFederation/intermine_legfed
legfed-geneticmap-file/main/src/org/intermine/bio/dataconversion/GeneticMapRecord.java
2520
package org.intermine.bio.dataconversion; /* * Copyright (C) 2015-2016 NCGR * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ /** * Encapsulates a single tab-delimited LinkageGroup file record of the form: * <pre> * Marker LG Type Pos (cM) QTL Traits * </pre> * Comparator is based on Linkage group, Position and Marker. * QTL and Traits associated are individually optional. * * @author Sam Hokin, NCGR */ public class GeneticMapRecord implements Comparable { String marker; int lg; String type; double position; String qtl; // optional String traits; // optional /** * Instantiate from a line from a LinkageGroup file. Do nothing if it's a header or comment line. */ public GeneticMapRecord(String line) { if (!line.startsWith("#") && !line.startsWith("Marker")) { try { // parse line String[] parts = line.split("\t"); marker = parts[0]; lg = Integer.parseInt(parts[1]); type = parts[2]; position = Double.parseDouble(parts[3]); if (parts.length>4) qtl = parts[4]; if (parts.length>5) traits = parts[5]; } catch (Exception ex) { throw new RuntimeException("Error parsing genetic map file line:\n"+ ex.toString()+"\n"+ line+"\n"+ "marker="+marker+"\n"+ "lg="+lg+"\n"+ "type="+type+"\n"+ "position="+position+"\n"+ "qtl="+qtl+"\n"+ "traits="+traits); } } } /** * For sorting by linkage group, position, marker. */ public int compareTo(Object o) { GeneticMapRecord that = (GeneticMapRecord)o; if (this.lg!=that.lg) { return this.lg - that.lg; } else if (this.position!=that.position) { return (int) ((this.position-that.position)*100); } else { return this.marker.compareTo(that.marker); } } }
lgpl-3.0
Wmaxlees/jarvis-os
Documentation/html/class_catch_1_1_ptr.js
1246
var class_catch_1_1_ptr = [ [ "Ptr", "class_catch_1_1_ptr.html#a6108f0195595ee9d7a411daea810beaf", null ], [ "Ptr", "class_catch_1_1_ptr.html#aacec063a79cd142e39040a31c6b3c40b", null ], [ "Ptr", "class_catch_1_1_ptr.html#ac629dd8ebe5763a37bb89e6c1d6a1771", null ], [ "~Ptr", "class_catch_1_1_ptr.html#ac96d3bb33adcfb983207385cfba5fe8a", null ], [ "get", "class_catch_1_1_ptr.html#a0123036c2fca74afceea9c0e3e5cc01b", null ], [ "get", "class_catch_1_1_ptr.html#abf6f4d2d554086d9a2606add07716a16", null ], [ "operator SafeBool::type", "class_catch_1_1_ptr.html#a27234c04feec43ffe0fd08e045557448", null ], [ "operator!", "class_catch_1_1_ptr.html#aea1a99ded6d62423ccb9173fab91b56e", null ], [ "operator*", "class_catch_1_1_ptr.html#a3a4c139032a8bd1bffa553103d5dbfd3", null ], [ "operator->", "class_catch_1_1_ptr.html#afaa13250d5e0ae5a440726d5e5aa7295", null ], [ "operator=", "class_catch_1_1_ptr.html#a9b08c868b447d679ed201921f5c94683", null ], [ "operator=", "class_catch_1_1_ptr.html#af42074444c1bc6a70ebdc406a8617708", null ], [ "reset", "class_catch_1_1_ptr.html#af8d0fa7a2cd20842830b354ac31dfe5c", null ], [ "swap", "class_catch_1_1_ptr.html#a172bf8b4e71e26a5a4d92f5b02158b50", null ] ];
lgpl-3.0
doge-search/webdoge
liqian/JHU/research/research/pipelines.py
1201
# -- coding: utf-8 -- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import os import urllib import xml.dom.minidom as minidom class xmlPipeline(object): def __init__(self): self.fout_xml = file('../JHU_research.xml', 'w') self.doc = minidom.Document() self.institution = self.doc.createElement("institution") self.doc.appendChild(self.institution) self.cnt = 0 def process_item(self, item, spider): research = self.doc.createElement("research") self.institution.appendChild(research) groupname = self.doc.createElement("groupname") groupname.appendChild(self.doc.createTextNode(item['groupname'].encode('utf-8'))) research.appendChild(groupname) for profname in item['proflist']: if not profname or not profname[0].strip(): continue namenode = self.doc.createElement("professorname") namenode.appendChild(self.doc.createTextNode(profname[0])) research.appendChild(namenode) self.cnt += 1 def close_spider(self, spider): print self.cnt self.doc.writexml(self.fout_xml, "\t", "\t", "\n", encoding="utf-8") self.fout_xml.close()
unlicense
clilystudio/NetBook
allsrc/cn/sharesdk/wechat/utils/WXMediaMessage$a.java
2146
package cn.sharesdk.wechat.utils; import android.os.Bundle; public class WXMediaMessage$a { public static Bundle a(WXMediaMessage paramWXMediaMessage) { Bundle localBundle = new Bundle(); localBundle.putInt("_wxobject_sdkVer", paramWXMediaMessage.sdkVer); localBundle.putString("_wxobject_title", paramWXMediaMessage.title); localBundle.putString("_wxobject_description", paramWXMediaMessage.description); localBundle.putByteArray("_wxobject_thumbdata", paramWXMediaMessage.thumbData); if (paramWXMediaMessage.mediaObject != null) { localBundle.putString("_wxobject_identifier_", "com.tencent.mm.sdk.openapi." + paramWXMediaMessage.mediaObject.getClass().getSimpleName()); paramWXMediaMessage.mediaObject.serialize(localBundle); } return localBundle; } public static WXMediaMessage a(Bundle paramBundle) { WXMediaMessage localWXMediaMessage = new WXMediaMessage(); localWXMediaMessage.sdkVer = paramBundle.getInt("_wxobject_sdkVer"); localWXMediaMessage.title = paramBundle.getString("_wxobject_title"); localWXMediaMessage.description = paramBundle.getString("_wxobject_description"); localWXMediaMessage.thumbData = paramBundle.getByteArray("_wxobject_thumbdata"); String str = paramBundle.getString("_wxobject_identifier_"); if ((str == null) || (str.length() <= 0)) return localWXMediaMessage; try { str = str.replace("com.tencent.mm.sdk.openapi", "cn.sharesdk.wechat.utils"); localWXMediaMessage.mediaObject = ((WXMediaMessage.IMediaObject)Class.forName(str).newInstance()); localWXMediaMessage.mediaObject.unserialize(paramBundle); return localWXMediaMessage; } catch (Exception localException) { cn.sharesdk.framework.utils.d.a().w(localException); cn.sharesdk.framework.utils.d.a().w("get media object from bundle failed: unknown ident " + str, new Object[0]); } return localWXMediaMessage; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: cn.sharesdk.wechat.utils.WXMediaMessage.a * JD-Core Version: 0.6.0 */
unlicense
Yismen/dicenew
libraries/phpExcel/Documentation/Examples/Reader/exampleReader06.php
1406
<?php error_reporting(E_ALL); set_time_limit(0); date_default_timezone_set('Europe/London'); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>PHPExcel Reader Example #06</title> </head> <body> <h1>PHPExcel Reader Example #06</h1> <h2>Simple File Reader Loading All WorkSheets</h2> <?php /** Include path **/ set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/'); /** PHPExcel_IOFactory */ include '../../../../../phpExcel/Documentation/Examples/Reader/PHPExcel/IOFactory.php'; $inputFileType = 'Excel5'; // $inputFileType = 'Excel2007'; // $inputFileType = 'Excel2003XML'; // $inputFileType = 'OOCalc'; // $inputFileType = 'Gnumeric'; $inputFileName = './sampleData/example1.xls'; echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />'; $objReader = PHPExcel_IOFactory::createReader($inputFileType); echo 'Loading all WorkSheets<br />'; $objReader->setLoadAllSheets(); $objPHPExcel = $objReader->load($inputFileName); echo '<hr />'; echo $objPHPExcel->getSheetCount(),' worksheet',(($objPHPExcel->getSheetCount() == 1) ? '' : 's'),' loaded<br /><br />'; $loadedSheetNames = $objPHPExcel->getSheetNames(); foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) { echo $sheetIndex,' -> ',$loadedSheetName,'<br />'; } ?> <body> </html>
unlicense
JFixby/PSDUnpacker
jfixby-tool-psd-unpacker-test/jfixby-tool-psd-unpacker-test/com/jfixby/psd/unpacker/run/UnpackExamplePSD.java
2433
package com.jfixby.psd.unpacker.run; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import com.jfixby.psd.unpacker.api.PSDFileContent; import com.jfixby.psd.unpacker.api.PSDLayer; import com.jfixby.psd.unpacker.api.PSDRaster; import com.jfixby.psd.unpacker.api.PSDRootLayer; import com.jfixby.psd.unpacker.api.PSDUnpacker; import com.jfixby.psd.unpacker.api.PSDUnpackingParameters; import com.jfixby.scarabei.api.file.File; import com.jfixby.scarabei.api.file.FileOutputStream; import com.jfixby.scarabei.api.file.LocalFileSystem; import com.jfixby.scarabei.api.log.L; import com.jfixby.scarabei.red.desktop.ScarabeiDesktop; public class UnpackExamplePSD { public static void main(String[] args) throws IOException { ScarabeiDesktop.deploy(); File home = LocalFileSystem.ApplicationHome(); File examples_folder = home.child("unpacker-input"); File example_psd_file = examples_folder.child("example1.psd"); PSDUnpackingParameters specs = PSDUnpacker.newUnpackingSpecs(); specs.setPSDFile(example_psd_file); File output_folder = home.child("unpacker-output"); // specs.setOutputFolderPath(output_path); output_folder.makeFolder(); // output_folder.clearFolder(); PSDFileContent result = PSDUnpacker.unpack(specs); result.print(); PSDRootLayer root = result.getRootlayer(); for (int i = 0; i < root.numberOfChildren(); i++) { PSDLayer child = root.getChild(i); process_child(child, output_folder); } } static int k = 0; private static void process_folder(PSDLayer root, File output_path) throws IOException { for (int i = 0; i < root.numberOfChildren(); i++) { PSDLayer child = root.getChild(i); process_child(child, output_path); } } private static void process_child(PSDLayer child, File output_path) throws IOException { if (child.isVisible()) { if (child.isFolder()) { process_folder(child, output_path); } else { PSDRaster raster = child.getRaster(); BufferedImage java_image = raster.getBufferedImage(); String raster_name = child.getName(); File output_file = output_path.child(raster_name + ".png"); k++; L.d("writing", output_file); FileOutputStream os = output_file.newOutputStream(); OutputStream java_stream = os.toJavaOutputStream(); ImageIO.write(java_image, "png", java_stream); java_stream.close(); } } } }
unlicense
WSDOT-GIS/ArcGisTileTest
SpatialReference.cs
268
using System.Runtime.Serialization; namespace ArcGisTileTest { [DataContract] public class SpatialReference { [DataMember] public int? wkid { get; set; } [DataMember] public string wkt { get; set; } } }
unlicense
ECain/ArcGISOnlineInteraction
AGORestCallTestFS/DataContractObjects/AdminLayerInfo.cs
512
using System.Runtime.Serialization; namespace AGORestCallTestFS { [DataContract] class AdminLayerInfo { [DataMember] public string TableName { get; set; } [DataMember] public GeometryField geometryField { get; set; } [DataMember] public Extent TableExtent { get; set; } } //Used for AddDefinition on Feature Services [DataContract] class AdminLayerInfoAttribute { [DataMember] public GeometryField geometryField { get; set; } } }
unlicense
cjschneider2/novluno
client/src/sdl/render/map/objects.rs
5481
use crate::core_compat::entity::rmd_type::RmdType; use crate::core_compat::entity::sprite_type::SpriteType; use crate::game::Game; use crate::geometry::point::Point; use crate::geometry::rectangle::Rectangle; use crate::resource_manager::list_manager::ListType; use crate::sdl2::rect::Rect; use crate::sdl::Sdl; use crate::sdl::render::map::next_tile; use sdl::render; struct DrawObject { texture: *mut sdl2::sys::SDL_Texture, src: Rect, dst: Rect, z: i32, highlight: bool, } pub fn objects(sdl: &mut Sdl, game: &mut Game) { let obj_list = game.list_manager.get_list(ListType::Object).unwrap(); let map = game.map_manager.get_map(game.state.map).unwrap(); let tile_stride = map.size_x() as i32; let tile_height = 24i32; let tile_width = 48i32; let mut tile_x = 0i32; let mut tile_y = 0i32; let _view_bounds = Rectangle::new_from_points( (-100 - game.state.map_off.0, -100 - game.state.map_off.1), (100 + game.window.0, 100 + game.window.1), ); let mut draw_list = Vec::<DrawObject>::new(); for map_tile in map.tiles().iter() { let (map_x, map_y) = game.state.map_off; let tile_offset = Point::new( tile_x * tile_width, tile_y * tile_height, ); let mouse_offset = Point::new( game.input.mouse_x - map_x, game.input.mouse_y - map_y, ); // skip tiles which are out out of view let tile_rect = Rectangle::new_from_points((tile_offset.x, tile_offset.y), (tile_width, tile_height)); // debug: active rectangle let is_active = tile_rect.contains_point(&mouse_offset); // draw tile objects let obj_entry = map_tile.obj_rmd_entry; if obj_entry.file() != 0 { let file = obj_entry.file() as usize; let index = obj_entry.index() as usize; if let Ok(rmd) = game.data_manager.get_data(RmdType::Object, file) { if let Some(entry) = rmd.get_entry(index) { for img in entry.images() { for id in img.image_id.iter() { // get the sprite let _id: usize = *id as usize; let item = obj_list.get_item(_id).unwrap(); let sprite = game.sprite_manager.get_sprite_entry(&item.entry, SpriteType::Object, sdl).unwrap(); // calculate the sprite's image offsets let img_rect = Rect::new(0, 0, sprite.sprite.x_dim as u32, sprite.sprite.y_dim as u32); let img_x_1_off = img.source_x1 - sprite.sprite.x_off; let img_y_1_off = img.source_y1 - sprite.sprite.y_off; let _src_pts = [(img_x_1_off, img_y_1_off).into(), (img.source_x2 - sprite.sprite.x_off, img.source_y2 - sprite.sprite.y_off).into()]; let mut _x_diff = 0; let mut _y_diff = 0; let mut src_rect = Rect::from_enclose_points(&_src_pts, None).unwrap(); if let Some(rect) = src_rect.intersection(img_rect) { if img_x_1_off < 0 { _x_diff = -img_x_1_off; } if img_y_1_off < 0 { _y_diff = -img_y_1_off; } src_rect = rect; } // actually move the destination rectangle into position let mut dst_rect = Rect::new(_x_diff, _y_diff, src_rect.width(), src_rect.height()); dst_rect.offset(game.state.map_off.0, game.state.map_off.1); dst_rect.offset(tile_offset.x, tile_offset.y); dst_rect.offset(img.dest_x, img.dest_y); draw_list.push(DrawObject { texture: sprite.texture.raw(), src: src_rect, dst: dst_rect, z: tile_x + tile_y + img.render_z, highlight: is_active, }); } } } } } // end if obj_entry != 0 // update tile positions next_tile(&mut tile_x, &mut tile_y, tile_stride); } // sort by z-index draw_list.sort_unstable_by(|obj1, obj2| { obj1.z.partial_cmp(&obj2.z).unwrap() }); // render struct DebugList { dst: Rect, z: i32, } let mut debug_list = Vec::<DebugList>::new(); //println!("{:?}", draw_list.len()); draw_list.iter().for_each(|obj| { let texture = unsafe { sdl.texture_creator.raw_create_texture(obj.texture) }; let _ = sdl.canvas.copy(&texture, obj.src, obj.dst); if obj.highlight { debug_list.push(DebugList { dst: obj.dst, z: obj.z }) } }); // debug renders debug_list.iter().for_each(|obj| { // let (x, y) = game.state.map_off; sdl.canvas.set_draw_color(sdl2::pixels::Color::RGB(10, 10, 255)); let _ = sdl.canvas.draw_rect(obj.dst); let z_idx = format!("z:{}", obj.z); render::text::line(sdl, &z_idx, obj.dst.left(), obj.dst.top()); }); }
unlicense
JackSW/hasoffers-php-client
src/Api/Brand/AdManager.php
4707
<?php namespace DraperStudio\HasOffers\Api\Brand; use DraperStudio\HasOffers\Base; class AdManager extends Base { /** * API Endpoint Type. * * @var string */ protected $endpointType = 'Brand'; /** * API Endpoint Name. * * @var string */ protected $endpointName = 'AdManager'; /** * Add Ad Campaign Creative with data properties by Ad Campaign ID. * * @param array $parameters * * @return object */ public function addCreative($parameters = []) { return $this->get('addCreative', $parameters); } /** * Create Ad Campaign with data properties. * * @param array $parameters * * @return object */ public function createCampaign($parameters = []) { return $this->get('createCampaign', $parameters); } /** * Find all Ad Campaign objects by filters. * * @param array $parameters * * @return object */ public function findAllCampaigns($parameters = []) { return $this->get('findAllCampaigns', $parameters); } /** * Find all Ad Campaign Creatives by filters. * * @param array $parameters * * @return object */ public function findAllCreatives($parameters = []) { return $this->get('findAllCreatives', $parameters); } /** * Find Ad Campaign object by Ad Campaign ID. * * @param array $parameters * * @return object */ public function findCampaignById($parameters = []) { return $this->get('findCampaignById', $parameters); } /** * Find Ad Campaign Creative by Ad Campaign Creative ID. * * @param array $parameters * * @return object */ public function findCreativeById($parameters = []) { return $this->get('findCreativeById', $parameters); } /** * Get total active Ad Campaigns being currently ran by affiliate_access level. * * @param array $parameters * * @return object */ public function getActiveNetworkCampaignCount($parameters = []) { return $this->get('getActiveNetworkCampaignCount', $parameters); } /** * Get Ad Campaign code. * * @param array $parameters * * @return object */ public function getCampaignCode($parameters = []) { return $this->get('getCampaignCode', $parameters); } /** * Get Ad Campaign Creatives by Ad Campaign ID and other filters. * * @param array $parameters * * @return object */ public function getCampaignCreatives($parameters = []) { return $this->get('getCampaignCreatives', $parameters); } /** * Get total media usage for start to end date for Ad Campaigns. * * @param array $parameters * * @return object */ public function getUsage($parameters = []) { return $this->get('getUsage', $parameters); } /** * Set Ad Campaign Creative weights with data. * * @param array $parameters * * @return object */ public function setCreativeCustomWeights($parameters = []) { return $this->get('setCreativeCustomWeights', $parameters); } /** * Set Ad Campaign Creative weights with data properties. * * @param array $parameters * * @return object */ public function setCreativeWeights($parameters = []) { return $this->get('setCreativeWeights', $parameters); } /** * Update Ad Campaign with data properties by Ad Campaign ID. * * @param array $parameters * * @return object */ public function updateCampaign($parameters = []) { return $this->get('updateCampaign', $parameters); } /** * Update Ad Campaign field with value by Ad Campaign ID. * * @param array $parameters * * @return object */ public function updateCampaignField($parameters = []) { return $this->get('updateCampaignField', $parameters); } /** * Update Ad Campaign Creative by Ad Campaign Creative ID. * * @param array $parameters * * @return object */ public function updateCreative($parameters = []) { return $this->get('updateCreative', $parameters); } /** * Update a given field for an ad campaign creative by its ID. * * @param array $parameters * * @return object */ public function updateCreativeField($parameters = []) { return $this->get('updateCreativeField', $parameters); } }
unlicense
ghzmdr/71pictures
src/js/lib/Region.js
1663
import { isFunction } from 'underscore'; export default class Region { constructor(selector) { this.el = document.querySelector(selector); } show(NextView, options) { options = options || {}; if (!options.forceRefresh && this._currentView && this._currentView.constructor === NextView) { if (isFunction(this._currentView.updateData)) { this._currentView.updateData(options); } return this._currentView; } var nextView = new NextView(options); var prevView = this._currentView; this._currentView = nextView; var isAttached = false; const attach = () => { if (isAttached) return; isAttached = true; this.el.appendChild(nextView.el); nextView.trigger('attached'); } const immediateTransitionIn = () => { if (isFunction(nextView.immediateTransitionIn)) { attach(); nextView.immediateTransitionIn(); } } const transitionIn = () => { attach(); if (isFunction(nextView.transitionIn)) nextView.transitionIn(); } const disposePrevView = () => { prevView.remove(); transitionIn(); } immediateTransitionIn(); if (prevView) { if (isFunction(prevView.transitionOut)) { prevView.transitionOut(disposePrevView); } else { disposePrevView(); } } else { transitionIn(); } return this._currentView; } }
unlicense
Jesse-V/Buddhabrot
src/postprocessing/main.hpp
216
#ifndef MAIN #define MAIN #include <algorithm> #include <vector> #include <string> typedef std::vector<std::vector<unsigned long>> Matrix2D; void writeMatrixToPPM(Matrix2D& matrix, std::string filename); #endif
unlicense
yangboz/north-american-adventure
RushuPHP/example/configure.php
5509
<?php /** * @author Ligboy * @name 微信调用接口类 * @example 里面是Wechat类内所有需要的接口,都是需要按自己情况实现的方法 */ class WechatTools{ var $memcache; var $db_link = null; function __construct(){ //这里使用memcache存储cookies和token,没有该环境的用户可以自己去实现使用文件或其他方式存取 $this->memcache = new Memcache(); $this->memcache->connect("127.0.0.1", 11211); } /** * @name 获取Cookies * @see WechatSessionToolInter::getCookies() */ public function getCookies($session="default") { return $this->memcache->get("wechat_cookies".$session); //使用memcache高速缓存存取cookies } /** * @name 获取token * @see WechatSessionToolInter::getToken() */ public function getToken() { return $this->memcache->get("wechat_token"); //使用memcache高速缓存存取Token } /** * @name 设置保存Cookies * @param string $Cookies * @param string $session * @see WechatSessionToolInter::setCookies() */ public function setCookies($Cookies, $session='default') { $this->memcache->set("wechat_cookies".$session, $Cookies); //使用memcache高速缓存存取cookies } /** * @name 设置保存token * @param string $token * @see WechatSessionToolInter::setToken() */ public function setToken($token) { $this->memcache->set("wechat_token", $token); //使用memcache高速缓存存取Token } /** * @name 判断指定Openid是否关联 * @param string $Openid 指定Openid * @return boolean 返回逻辑判断结果 * @see WechatAscToolInter::getAscStatusByOpenid() */ function getAscStatusByOpenid($Openid) { $sql = "SELECT * FROM weixin_followusers WHERE weixin_followusers.openid='$Openid'"; $db_link = mysql_connect("127.0.0.1", "root", "password"); if (!$db_link) { die("Connect Db Error!"); } mysql_select_db("db_name", $db_link); mysql_query("set names 'utf8'", $db_link); // $query = "Select * from 'weixin_fakelist'"; $result = mysql_query($sql, $db_link); $row = mysql_fetch_assoc($result); if ($row[2]!="") { return $row; } else { return false; } } /** * @name 判断指定fakeid是否关联 * @param string $fakeid 指定fakeid * @return boolean 返回逻辑判断结果 * @see WechatAscToolInter::getAscStatusByFakeid() */ function getAscStatusByFakeid($fakeid) { $sql = "SELECT * FROM weixin_followusers WHERE weixin_followusers.fakeid='$fakeid'"; $db_link = mysql_connect("127.0.0.1", "root", "password"); if (!$db_link) { die("Connect Db Error!"); } mysql_select_db("db_name", $db_link); mysql_query("set names 'utf8'", $db_link); $result = mysql_query($sql, $db_link); $row = mysql_fetch_assoc($result); if ($row) { return $row; } else { return false; } } /** * @name 设置fakeid与Openid的关联 * @param string $openid Openid * @param string $fakeid fakeid * @param string $detailInfo 用户详细信息(可选) * @return resource * @see WechatAscToolInter::setAssociation() */ function setAssociation($openid, $fakeid, $detailInfo) { $sql = "SELECT * FROM weixin_followusers WHERE weixin_followusers.openid='$openid'"; $insertsql = "UPDATE weixin_followusers SET fakeid='$fakeid',name='$detailInfo[NickName]',gender='$detailInfo[Sex]' WHERE weixin_followusers.openid='$openid'"; $db_link = mysql_connect("127.0.0.1", "root", "password"); if (!$db_link) { die("Connect Db Error!"); } mysql_select_db("db_name", $db_link); mysql_query("set names 'utf8'", $db_link); $result = mysql_query($insertsql, $db_link); return $result; } /** * @name 用户关注执行动作 * @param string $openid Openid * @return bool|resource * @see WechatFollowToolInter::followAddAction() */ function followAddAction($openid) { $sql = "SELECT id,fakeid,subscribed FROM weixin_followusers WHERE weixin_followusers.openid='$openid'"; $updatesql = "UPDATE weixin_followusers SET weixin_followusers.subscribed=1 WHERE weixin_followusers.openid='$openid'"; $insertsql = "INSERT INTO weixin_followusers(openid,subscribed) VALUE ('$openid',1)"; $db_link = mysql_connect("127.0.0.1", "root", "password"); if (!$db_link) { die("Connect Db Error!"); } mysql_select_db("db_name", $db_link); mysql_query("set names 'utf8'", $db_link); $result = mysql_query($sql, $db_link); $row = mysql_fetch_assoc($result); var_dump($row); if ($row[2]==="0") { return mysql_query($updatesql, $db_link); } elseif($row[2]==="1") { return true; } else { return mysql_query($insertsql, $db_link); } } /** * @name 取消关注执行动作 * @param string $openid Openid * @see WechatFollowToolInter::followCancelAction() */ function followCancelAction($openid) { $updatesql = "UPDATE weixin_followusers SET weixin_followusers.subscribed=0 WHERE weixin_followusers.openid='$openid'"; $db_link = mysql_connect("127.0.0.1", "root", "password"); if (!$db_link) { die("Connect Db Error!"); } mysql_select_db("db_name", $db_link); mysql_query("set names 'utf8'", $db_link); $result = mysql_query($updatesql, $db_link); } } //上面类的实例化 $wechatToolObj = new WechatTools(); //下面是设置文件 return array( 'token'=>'mytoken', 'account'=>'ligboy@gmail.com', 'password'=>'password', "wechattool"=>$wechatToolObj /*这里是上面的接口类实例对象,也可以通过setWechatToolFun()设置*/ );
unlicense
clilystudio/NetBook
allsrc/com/ushaqi/zhuishushenqi/widget/m(1).java
737
package com.ushaqi.zhuishushenqi.widget; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.ushaqi.zhuishushenqi.model.PostComment; import com.ushaqi.zhuishushenqi.ui.post.AbsPostActivity; final class m implements DialogInterface.OnClickListener { m(CommentItemView paramCommentItemView, PostComment paramPostComment) { } public final void onClick(DialogInterface paramDialogInterface, int paramInt) { CommentItemView.a(this.b).a(this.a.toRepliedInfo(), CommentItemView.d(this.b)); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ushaqi.zhuishushenqi.widget.m * JD-Core Version: 0.6.0 */
unlicense
fisherro/streams
examples/examples.cpp
8852
#include <ctime> #include <regex> #include <string> #include <fmt/time.h> #include <streams/ostream.hpp> #include <streams/istream.hpp> struct Student { std::string name; int id; float gpa; }; void write_student_binary(streams::ostream& out, const Student& student) { out.put(student.name.size()); out.write(gsl::as_bytes(gsl::span<const char>( student.name.data(), student.name.size()))); out.put(student.id); out.put(student.gpa); } streams::optional<Student> read_student_binary(streams::istream& in) { Student student; auto size = in.get<std::string::size_type>(); if (!size) return streams::nullopt; if (*size <= 0) return streams::nullopt; student.name.resize(*size); auto result = in.read(gsl::as_writeable_bytes(gsl::span<char>( &student.name[0], student.name.size()))); if (result.size() <= 0) return streams::nullopt; if (!in.get(student.id)) return streams::nullopt; if (!in.get(student.gpa)) return streams::nullopt; return student; } void write_student_text(streams::ostream& out, const Student& student) { streams::print(out, "\"{}\",{},{}\n", student.name, student.id, student.gpa); } streams::optional<Student> read_student_text(streams::istream& in) { //What to do about "formatted input"? // //In my experience, formatted input was never as easy as the standard //iostreams pretended. It is about matching patterns and splitting up //the input into small chunks that might then be used with an ad hoc //istringstream and operator>>. //(Or, more nicely, via boost::lexical_cast.) // //More thought needed. auto line = streams::get_line(in); if (!line) return streams::nullopt; std::regex rx(R"|("([^"]+)",([0-9]+),([0-9.]+))|"); std::smatch match; if (!std::regex_match(*line, match, rx)) { throw std::string("Format mismatch!"); } Student student; student.name = match[1]; student.id = std::stoi(match[2]); student.gpa = std::stof(match[3]); return student; } void print_student_header() { streams::print(streams::stdouts, "{:<10} {:^4} {:>5}\n", "NAME", "ID", "GPA"); } void print_student(const Student& student) { streams::print(streams::stdouts, "{:<10} {:^4} {:>5.2f}\n", student.name, student.id, student.gpa); } int main() { std::vector<Student> class_roll{ { "Alice", 12, 3.9 }, { "Bob", 23, 3.0 }, { "Chris", 34, 3.2 } }; //Unformatted I/O: { streams::vector_ostream out; std::for_each(class_roll.begin(), class_roll.end(), [&out](const auto& student) { write_student_binary(out, student); }); streams::span_istream in(out.vector()); std::vector<Student> roll2; while (true) { auto student = read_student_binary(in); if (!student) break; roll2.push_back(*student); } print_student_header(); std::for_each(roll2.begin(), roll2.end(), print_student); } //Formatted I/O: { streams::vector_ostream out; std::for_each(class_roll.begin(), class_roll.end(), [&out](const auto& student) { write_student_text(out, student); }); streams::span_istream in(out.vector()); std::vector<Student> roll2; while (true) { auto student = read_student_text(in); if (!student) break; roll2.push_back(*student); } print_student_header(); std::for_each(roll2.begin(), roll2.end(), print_student); } //Character-based filter ostream: { struct Shout_ostream: public streams::ostream { streams::ostream& _sink; Shout_ostream(ostream& s): _sink(s) {} std::ptrdiff_t _write(gsl::span<const gsl::byte> before) override { std::vector<gsl::byte> after; after.reserve(before.size()); std::transform(before.begin(), before.end(), std::back_inserter(after), [](gsl::byte b) { return static_cast<gsl::byte>( ::toupper(static_cast<int>(b))); }); return _sink.write(after); } void _flush() override { _sink.flush(); } }; Shout_ostream out(streams::stdouts); streams::put_line(out, "This is a test. This is only a test."); } //Line-based filter ostream: { struct Line_number_ostream: public streams::ostream { int _line = 0; streams::ostream& _sink; explicit Line_number_ostream(streams::ostream& out): _sink(out) {} std::ptrdiff_t _write(gsl::span<const gsl::byte> data) override { std::ptrdiff_t written = 0; if (0 == _line) { //If this is the first time we're called, //write the header for the first line. streams::vector_ostream vos; streams::print(vos, "{}: ", ++_line); written += _sink.write(vos.vector()); } do { auto nl = std::find(data.begin(), data.end(), gsl::byte('\n')); if (data.end() == nl) { //If there is now newline, //write the data and we're done. written += _sink.write(data); break; } //Otherwise, write up to and including the newline... auto count = std::distance(data.begin(), nl + 1); written += _sink.write(data.first(count)); //...write the line header... streams::vector_ostream vos; streams::print(vos, "{}: ", ++_line); written += _sink.write(vos.vector()); //...and most to past the newline. data = data.subspan(count); } while (data.size() > 0); return written; } void _flush() override { _sink.flush(); } }; Line_number_ostream lnos(streams::stdouts); streams::put_string(lnos, "Roses are red,\n" "Violets are blue,\n" "This poem has bugs,\n" "And...NO CARRIER"); streams::put_char(streams::stdouts, '\n'); } //Line-based filter otream, take 2: { struct Reverse_line_ostream: public streams::ostream { streams::ostream& _sink; std::vector<gsl::byte> _buffer; Reverse_line_ostream(ostream& s): _sink(s) {} std::ptrdiff_t _write(gsl::span<const gsl::byte> data) override { auto written = data.size(); while (data.size() > 0) { auto nl = std::find(data.begin(), data.end(), gsl::byte('\n')); if (data.end() != nl) { auto count = std::distance(data.begin(), nl); std::copy_n(data.begin(), count, std::back_inserter(_buffer)); std::reverse(_buffer.begin(), _buffer.end()); _buffer.push_back(gsl::byte('\n')); _sink.write(_buffer); _sink.flush(); _buffer.clear(); data = data.subspan(count + 1); } else { std::copy(data.begin(), data.end(), std::back_inserter(_buffer)); break; } } return written; } ~Reverse_line_ostream() { try { if (!_buffer.empty()) { std::reverse(_buffer.begin(), _buffer.end()); _sink.write(_buffer); _sink.flush(); } } catch (...) { //Don't let exceptions escape dtors! } } }; { Reverse_line_ostream rlos(streams::stdouts); streams::put_string(rlos, "Roses are red,\n" "Violets are blue,\n" "This poem has bugs,\n" "And...NO CARRIER"); } streams::put_char(streams::stdouts, '\n'); } }
unlicense
agamemnus/history-easy.js
test-more.js
2243
// (1) Define a persistent variable holding your URL GET variables. // (2) define a function for the history control to call when a page should change. The function should have two parameters: // (2a) the initial object/state. // (2b) an internal callback function call that should run once the function finishes processing. // (3) set an initial page value. (doesn't have to be a number; can be a string) // (4) Set what the persistent URL variable in (1) is. // (5) You can then do e.g. "history_control.load_page ({page_variable: page_value})" to add a history state. test_function () function test_function () { var test_main = this test_main.app_url_vars = {} var history_control = this.history_control = new history_control_object ({ 'onstatechange' : // (1): function called when the history changes. function (init, callback) { // (2a, 2b): init, internal callback. var page = init.page set_current_page (page) callback () // This is needed for any inline/custom callbacks to run. }, 'var_name' : 'page', 'initial_page' : 0, // (3): initial page value. 'base_filename' : '', 'app_url_vars' : test_main.app_url_vars // (4) a persistent variable holding your URL GET variables. }) // Load the first page. // If the initial page variable named "var_name" is not defined on the next line, use the initial_page value defined in new history_control_object. // (ie: "{'page': test_main.app_url_vars.page}"). history_control.load_page (undefined, {callback: page_zero_was_loaded}) // history_control.load_page ({page:'5', callback: page_zero_was_loaded}) // Load the second page, and set another title. function page_zero_was_loaded (init) { console.log ("Stand by. Loading next page in 3 seconds...") setTimeout (function () { test_main.app_url_vars.page = parseInt(test_main.app_url_vars.page) + 1 history_control.title = "Page " + test_main.app_url_vars.page history_control.load_page ({page: test_main.app_url_vars.page}, {callback: function () { console.log ("The second page was loaded.") }}) }, 3000) } function set_current_page (new_page) { document.body.innerHTML = 'We are on page: ' + new_page + '. Check the console log for further details...' } }
unlicense
khajehosseini/society
protected/views/cost/index.php
440
<?php $this->breadcrumbs=array( Yii::t('cost','Costs'), ); $this->menu=array( array('label'=>Yii::t('general','Create').' '.Yii::t('cost','Cost'),'url'=>array('create')), array('label'=>Yii::t('general','Manage') . ' ' . Yii::t('cost','Cost'),'url'=>array('admin')), ); ?> <h1><?php echo Yii::t('cost','Costs');?></h1> <?php $this->widget('bootstrap.widgets.TbListView',array( 'dataProvider'=>$dataProvider, 'itemView'=>'_view', )); ?>
unlicense
Arquisoft/voters_2a
src/client/js/controller.js
1109
var app = angular.module("votersModule",[]); app.config(function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }); app.controller("votersController", function($scope, $http) { $scope.ok = false; $scope.ko = false; $scope.datosFormulario = {}; $scope.autenticar = function(){ $http.post("http://localhost:8080/GetVoterInfo", $scope.datosFormulario) .success(function(data) { $scope.ok = true; $scope.ko = false; $scope.respuesta = data; }) .error(function(data) { $scope.ok = false; $scope.ko = true; console.log('Error:' + data); }); }; $scope.cambiarClave = function(){ $http.post("http://localhost:8080/UpdatePassword", $scope.datosFormulario) .success(function(data) { $scope.ok = true; $scope.ko = false; $scope.respuesta = data; console.log(data); }) .error(function(data) { $scope.ok = false; $scope.ko = true; console.log('Error:' + data); }); }; });
unlicense
meecoder/web
websites/KianDustin/login/page/pageAmanda.php
265
<html> <head><?php include($_SERVER["DOCUMENT_ROOT"] . "/header.php"); ?> <title> Kian and Dustin, Logged in as Amanda </title> </head> <body bgcolor="ABC992"> <h1>Kian and Dustin</h1> <p> <b>Welcome to Kian and Dustin!</b><br> Hello, Amanda. </p> </body> </html>
unlicense
CaddyDz/Ruby
p2/ch8/times_and_dates/s1/time.rb
137
puts require 'Time' puts Time.new puts Time.at(100000000) puts Time.mktime(2007,10,3,14,3,6) puts Time.parse("March 22, 1985, 10:35 PM")
unlicense
Ackincolor/GLAS
Main/Controler/ListenerButtonLeft.java
318
package Main.Controler; import Main.View.*; import java.awt.event.*; public class ListenerButtonLeft implements ActionListener { FenetreMain fen; public ListenerButtonLeft(FenetreMain fen) { this.fen = fen; } public void actionPerformed(ActionEvent e) { //ajout ou suppression de fichier a modifier } }
unlicense
mateusfreira/material-icaro.io
lib/angular-material/modules/closure/checkbox/checkbox.js
4176
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.7.0-rc2-master-f71eb32 */ goog.provide('ng.material.components.checkbox'); goog.require('ng.material.core'); (function() { 'use strict'; /** * @ngdoc module * @name material.components.checkbox * @description Checkbox module! */ angular.module('material.components.checkbox', [ 'material.core' ]) .directive('mdCheckbox', MdCheckboxDirective); /** * @ngdoc directive * @name mdCheckbox * @module material.components.checkbox * @restrict E * * @description * The checkbox directive is used like the normal [angular checkbox](https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D). * * @param {string} ng-model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {expression=} ng-true-value The value to which the expression should be set when selected. * @param {expression=} ng-false-value The value to which the expression should be set when not selected. * @param {string=} ng-change Angular expression to be executed when input changes due to user interaction with the input element. * @param {boolean=} md-no-ink Use of attribute indicates use of ripple ink effects * @param {string=} aria-label Adds label to checkbox for accessibility. * Defaults to checkbox's text. If no default text is found, a warning will be logged. * * @usage * <hljs lang="html"> * <md-checkbox ng-model="isChecked" aria-label="Finished?"> * Finished ? * </md-checkbox> * * <md-checkbox md-no-ink ng-model="hasInk" aria-label="No Ink Effects"> * No Ink Effects * </md-checkbox> * * <md-checkbox ng-disabled="true" ng-model="isDisabled" aria-label="Disabled"> * Disabled * </md-checkbox> * * </hljs> * */ function MdCheckboxDirective(inputDirective, $mdInkRipple, $mdAria, $mdConstant, $mdTheming, $mdUtil) { inputDirective = inputDirective[0]; var CHECKED_CSS = 'md-checked'; return { restrict: 'E', transclude: true, require: '?ngModel', template: '<div class="md-container" md-ink-ripple md-ink-ripple-checkbox>' + '<div class="md-icon"></div>' + '</div>' + '<div ng-transclude class="md-label"></div>', compile: compile }; // ********************************************************** // Private Methods // ********************************************************** function compile (tElement, tAttrs) { tAttrs.type = 'checkbox'; tAttrs.tabIndex = 0; tElement.attr('role', tAttrs.type); return function postLink(scope, element, attr, ngModelCtrl) { ngModelCtrl = ngModelCtrl || $mdUtil.fakeNgModel(); var checked = false; $mdTheming(element); $mdAria.expectWithText(tElement, 'aria-label'); // Reuse the original input[type=checkbox] directive from Angular core. // This is a bit hacky as we need our own event listener and own render // function. inputDirective.link.pre(scope, { on: angular.noop, 0: {} }, attr, [ngModelCtrl]); // Used by switch. in Switch, we don't want click listeners; we have more granular // touchup/touchdown listening. if (!attr.mdNoClick) { element.on('click', listener); } element.on('keypress', keypressHandler); ngModelCtrl.$render = render; function keypressHandler(ev) { if(ev.which === $mdConstant.KEY_CODE.SPACE) { ev.preventDefault(); listener(ev); } } function listener(ev) { if (element[0].hasAttribute('disabled')) return; scope.$apply(function() { checked = !checked; ngModelCtrl.$setViewValue(checked, ev && ev.type); ngModelCtrl.$render(); }); } function render() { checked = ngModelCtrl.$viewValue; if(checked) { element.addClass(CHECKED_CSS); } else { element.removeClass(CHECKED_CSS); } } }; } } MdCheckboxDirective.$inject = ["inputDirective", "$mdInkRipple", "$mdAria", "$mdConstant", "$mdTheming", "$mdUtil"]; })();
unlicense
ktye/editor
cmd/go/goinstall.go
676
package main import ( "bytes" "os/exec" ) func (p *program) install() error { if err := p.Forward("Write", nil); err != nil { return err } if err, errtxt := goInstall(); err != nil { return err } else if errtxt != "" { p.Name += "+Errors" p.Default = "" p.Text = errtxt p.Clean = false return nil } if err := p.Forward("read", nil); err != nil { return err } return nil } func goInstall() (error, string) { var stderr bytes.Buffer cmd := exec.Command("go", "install") cmd.Stderr = &stderr if err := cmd.Start(); err != nil { return err, "" } if err := cmd.Wait(); err != nil { return nil, string(stderr.Bytes()) } return nil, "" }
unlicense
kyorohiro/HetimaUtil
src_util/net/hetimatan/tool/WGet.java
1312
package net.hetimatan.tool; import java.io.IOException; import net.hetimatan.net.http.HttpGet; import net.hetimatan.net.http.HttpGetListener; import net.hetimatan.util.event.CloseRunnerTask; import net.hetimatan.util.event.net.KyoroSocketEventRunner; public class WGet { public static void main(String[] args) { if(args.length != 1) { System.out.println("java"+WGet.class.getSimpleName()+" http://www.example.com"); return; } System.out.println("start args[0]=" + args[0]); try { HttpGet getter = new HttpGet( new HttpGetListener() { @Override public boolean onReceiveHeader(HttpGet httpGet) throws IOException {return false;} @Override public boolean onReceiveBody(HttpGet httpGet) throws IOException { System.out.println("\n-------@1-------\n:"+new String(httpGet.getHeader())+"\n-------@/1-------\n:"); System.out.println("\n-------@2-------\n:"+new String(httpGet.getBody())+"\n-------@/1-------\n:"); return false; } }).update(args[0]); KyoroSocketEventRunner runner = getter.startTask(null, new CloseRunnerTask(null)); runner.waitByClose(30000); runner.close(); } catch (IOException e) { e.printStackTrace(); } catch(InterruptedException e) { e.printStackTrace(); } finally { System.out.println("end"); } } }
unlicense
juanpale/ObligatorioWhile
while_ut1Obligatorio/src/examples/while_ut1/ast/BExp.java
1151
package examples.while_ut1.ast; import java.util.*; /** Categoría sintáctica de las expresiones booleanas de While, las construcciones del lenguaje que evalúan a un valor de verdad (booleano). */ public abstract class BExp extends Exp{ abstract public String unparse(); @Override public abstract String toString(); @Override public abstract int hashCode(); @Override public abstract boolean equals(Object obj); public static BExp generate(Random random, int min, int max) { final int TERMINAL_COUNT = 1; final int NONTERMINAL_COUNT = 4; int i = min > 0 ? random.nextInt(NONTERMINAL_COUNT) + TERMINAL_COUNT : random.nextInt(max > 0 ? NONTERMINAL_COUNT + TERMINAL_COUNT: TERMINAL_COUNT); switch (i) { //Terminals case 0: return TruthValue.generate(random, min-1, max-1); //Non terminals case 1: return CompareEqual.generate(random, min-1, max-1); case 2: return CompareLessOrEqual.generate(random, min-1, max-1); case 3: return Negation.generate(random, min-1, max-1); case 4: return Conjunction.generate(random, min-1, max-1); default: throw new Error("Unexpected error at BExp.generate()!"); } } }
unlicense
cc14514/hq6
hq-pdk/src/main/java/org/hyperic/hq/product/util/PluginMain.java
10975
/* * NOTE: This copyright does *not* cover user programs that use HQ * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * This file is part of HQ. * * HQ is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.hq.product.util; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.net.URLClassLoader; import java.net.URL; import java.net.URLDecoder; import java.util.Iterator; import java.util.Properties; import org.apache.log4j.PropertyConfigurator; import org.hyperic.hq.product.ProductPlugin; import org.hyperic.hq.product.ProductPluginManager; import org.hyperic.util.PluginLoader; /** * Run the main method for a plugin class. * Example: * java -jar pdk/lib/hq-pdk.jar apache ApacheServerDetector */ //cut-n-pasted-n-chopped from sigar.cmd.Runner class public class PluginMain { private static final String DEFAULT_PACKAGE = "org.hyperic.hq.plugin"; private static URL jarURL(String jar) throws Exception { return new URL("jar", null, "file:" + jar + "!/"); } private static URL[] getLibJars(String dir) throws Exception { File[] jars = new File(dir).listFiles(new FileFilter() { public boolean accept(File file) { return file.getName().endsWith(".jar"); } }); if (jars == null) { return new URL[0]; } URL[] urls = new URL[jars.length]; for (int i=0; i<jars.length; i++) { urls[i] = jarURL(jars[i].getAbsolutePath()); } return urls; } private static void addVersionFile(String pdkDir) throws Exception { //Add URL for agent lib dir containing hq-version.properties for -v option File versionProperties = new File(pdkDir, "../lib"); URL versionProps = versionProperties.toURI().toURL(); addURLs(new URL[] {versionProps}); } private static URLClassLoader getLoader() { return (URLClassLoader)Thread.currentThread().getContextClassLoader(); } private static String getPdkDir() { URL[] urls = getLoader().getURLs(); for (int i=0; i<urls.length; i++) { String url = urls[i].getFile(); if (!url.contains(PluginDumper.PRODUCT_JAR)) { continue; } url = URLDecoder.decode(url); //"%20" -> " " //strip lib/hq-pdk.jar return new File(url).getParentFile().getParent(); } return "pdk"; } private static void addURLs(URL[] jars) throws Exception { URLClassLoader loader = getLoader(); //bypass protected access. Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); addURL.setAccessible(true); //pound sand. for (int i=0; i<jars.length; i++) { addURL.invoke(loader, new Object[] { jars[i] }); } } private static void addJarDir(String dir) throws Exception { URL[] jars = getLibJars(dir); addURLs(jars); } private static Class getPluginClass(PluginDumper pd, String plugin, String className) throws Exception { pd.init(); ProductPlugin productPlugin = pd.ppm.getProductPlugin(plugin); String packageName = productPlugin.getPluginProperty("package"); if (packageName == null) { packageName = DEFAULT_PACKAGE + "." + plugin; } String mainClass = packageName + "." + className; PluginLoader.setClassLoader(productPlugin); try { return Class.forName(mainClass, true, productPlugin.getClass().getClassLoader()); } catch (ClassNotFoundException e) { System.out.println("Invalid ClassName: " + mainClass); return null; } finally { PluginLoader.resetClassLoader(productPlugin); } } private static void runMain(PluginDumper pd, String[] args) throws Exception { int offset; ProductPlugin productPlugin = null; String plugin, className=null, mainClass=null; final String usage = "Usage: PluginMain plugin ClassName"; if (args.length < 1) { throw new IllegalArgumentException(usage); } plugin = args[0]; if (plugin.indexOf(".") != -1) { //example: //java -jar pdk/lib/hq-pdk.jar \ //org.hyperic.hq.product.URLMetric https://localhost/ mainClass = plugin; plugin = null; offset = 1; } else { if (args.length < 2) { throw new IllegalArgumentException(usage); } //example: //java -jar pdk/lib/hq-pdk.jar \ //apache ApacheServerDetector className = args[1]; offset = 2; } String[] pargs = new String[args.length - offset]; System.arraycopy(args, offset, pargs, 0, args.length-offset); Class cmd = null; if (plugin != null) { cmd = getPluginClass(pd, plugin, className); if (cmd == null) { return; } productPlugin = pd.ppm.getProductPlugin(plugin); } else { try { cmd = Class.forName(mainClass); } catch (ClassNotFoundException e) { System.out.println("Invalid ClassName: " + mainClass); return; } } Method main = cmd.getMethod("main", new Class[] { String[].class }); if (productPlugin != null) { PluginLoader.setClassLoader(productPlugin); } try { main.invoke(null, new Object[] { pargs }); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof NoClassDefFoundError) { System.out.println("Class Not Found: " + t.getMessage()); } else { t.printStackTrace(); } } finally { if (productPlugin != null) { PluginLoader.resetClassLoader(productPlugin); } } } private static final String[][] LOG_PROPS = { { "log4j.appender.R", "org.apache.log4j.ConsoleAppender" }, { "log4j.appender.R.layout.ConversionPattern", "%-5p [%t] [%c{1}] %m%n" }, { "log4j.appender.R.layout", "org.apache.log4j.PatternLayout" } }; private static void configureLogging(String pdkDir, String level) { if (new File(level).exists()) { PropertyConfigurator.configure(level); return; } Properties props = new Properties(); Properties agentProps = new Properties(); //pickup categories from from agent.properties File agentProperties = new File(pdkDir, "../../../conf/agent.properties"); if (agentProperties.exists()) { InputStream is = null; try { is = new FileInputStream(agentProperties); agentProps.load(is); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (Exception e) {} } } } for (Iterator it = agentProps.keySet().iterator(); it.hasNext();) { String key = (String)it.next(); if (key.startsWith("log4j.logger.") || key.startsWith("log4j.category.")) { props.setProperty(key, agentProps.getProperty(key)); } } props.setProperty("log4j.rootLogger", level.toUpperCase() + ", R"); for (int i=0; i<LOG_PROPS.length; i++) { props.setProperty(LOG_PROPS[i][0], LOG_PROPS[i][1]); } props.putAll(System.getProperties()); PropertyConfigurator.configure(props); } public static void main(String[] args) throws Exception { String pdkDir = System.getProperty(ProductPluginManager.PROP_PDK_DIR, getPdkDir()); File tmpDir = new File(new File(pdkDir).getParentFile(), "tmp"); //point the the agent tmp dir which gets cleaned out everytime //the agent is started. a must for windows where the files will //not get deleted because they are still open. if (tmpDir.exists() && tmpDir.canWrite()) { System.setProperty("java.io.tmpdir", tmpDir.toString()); } String pdkLib = pdkDir + File.separator + "lib"; String logLevel = System.getProperty("log", "error"); //bleh, make sure we get log level right. for (int i=0; i<args.length; i++) { if (args[i].startsWith("-Dlog=")) { logLevel = args[i].substring(6); } } addJarDir(pdkLib); addVersionFile(pdkDir); System.setProperty("org.hyperic.sigar.path", pdkLib); ProductPluginManager.setPdkDir(pdkDir); configureLogging(pdkDir, logLevel); PluginDumper pd = new PluginDumper(args); //XXX this is hackish, but dwim is more important if (!pd.config.hasSwitches) { runMain(pd, pd.config.args); } else { pd.init(); pd.invoke(); pd.shutdown(); } System.exit(0); } }
unlicense
jadnohra/connect
proto_5/connect/util/print_tree.py
1304
def print_tree(root, children_func=list, name_func=str): """Pretty print a tree, in the style of gnu tree""" # prefix components: space = ' ' branch = '│ ' # pointers: tee = '├── ' last = '└── ' # Inspired by https://stackoverflow.com/questions/9727673 def tree(node, children_func, name_func, prefix: str = ''): """A recursive generator, given a tree will yield a visual tree structure line by line with each line prefixed by the same characters """ contents = children_func(node) # contents each get pointers that are ├── with a final └── : pointers = [tee] * (len(contents) - 1) + [last] for pointer, path in zip(pointers, contents): yield prefix + str(pointer) + name_func(path) if len(children_func(path)): # extend the prefix and recurse: extension = branch if pointer == tee else space # i.e. space because last, └── , above so no more | yield from tree(path, children_func, name_func, prefix=prefix + extension) # Print the resulting tree print(name_func(root)) for line in tree(root, children_func, name_func): print(line)
unlicense
epicagency/bubo
src/helpers/utils.js
4364
/** * Check if an element is required * * @param {Object} el DOM element * @returns {boolean} true/false */ function isRequired(el) { return el.hasAttribute('required'); } /** * Check if an element has "rules" parameters * * @param {Object} el DOM element * @returns {Array|false} valid informations */ function hasRules(el) { const elType = el.getAttribute('type'); const rules = []; // Based on type attribute const types = [ // 'color', 'date', // 'datetime-local', 'email', 'number', 'tel', // 'time', 'url', ]; types.forEach((type) => { if (type === elType) { rules.push(addRule(type)); } }); // Based on other attributes const attributes = [ 'min', 'minlength', 'max', 'maxlength', 'pattern', // 'step', ]; attributes.forEach((attr) => { if (el.hasAttribute(attr)) { let val = el.getAttribute(attr); if (attr.includes('min') || attr.includes('max')) { if (elType === 'number') { val = parseFloat(val); } if (elType === 'date') { val = new Date(val); } } if (attr.includes('pattern')) { try { new RegExp(val); // eslint-disable-line no-new } catch (e) { throw new Error(`🦉 ${val} seems to be an invalid pattern!`); } } rules.push(addRule(attr, val)); } }); // If min/max -> special rule if (el.hasAttribute('min') && el.hasAttribute('max')) { rules.push(addRule('minmax')); } // If min/maxLength -> special rule if (el.hasAttribute('minlength') && el.hasAttribute('maxlength')) { rules.push(addRule('minmaxlength')); } if (rules.length > 0) { return rules; } return false; } /** * Create a new "rule" object * * @param {string} name name of the rule * @param {any} [value=null] value for validation * @returns {Object} rule */ function addRule(name, value = null) { const rule = { name }; if (value) { rule.value = value; } return rule; } /** * Check if item has rule * * @export * @param {Object} item Budo item * @param {string} name rule name * @returns {boolean} true/false */ export function hasRule(item, name) { const matches = item.rules.filter((rule) => rule.name === name); return matches.length === 1; } /** * Get item rule by rule name * * @export * @param {Object} item Budo item * @param {string} name rule name * @returns {Object} rule */ export function getRuleByName(item, name) { return item.rules.filter((rule) => rule.name === name)[0]; } /** * Check if an element should be validated * * @export * @param {Object} el DOM element * @returns {Object} item */ export function shouldValidate(el) { const item = {}; // Check / get required parameter const required = isRequired(el); if (required) { item.required = required; } // Check / get valid parameters (aka rules) const rules = hasRules(el); if (rules) { item.rules = rules; } // If something to validate // set others parameters // and return Bubo item if (item.required || item.rules) { item.el = el; item.name = el.dataset.formName || el.getAttribute('name'); item.label = el.dataset.formLabel || null; item.type = el.hasAttribute('type') ? el.getAttribute('type') : el.nodeName.toLowerCase(); return item; } return false; } /** * Source: https://gist.github.com/smeijer/6580740a0ff468960a5257108af1384e */ /** * Replace template expression * * @param {string} exp expression to replace * @param {Object} obj key/value for replacement * @param {string} [fb=`$\{${path}}`] fallback * @returns {string} replaced expression */ function get(exp, obj, fb = `$\{${exp}}`) { return exp.split('.').reduce((res, key) => res[key] || fb, obj); } /** * ES6 template string parser * * @export * @param {string} template template string * @param {Object} map key/value for replacement * @param {any} fallback fallback * @returns {string} parsed template */ export function parseTpl(template, map, fallback) { return template.replace(/\$\{.+?}/g, (match) => { // Extract ${<expression(s)>} from template // eslint-disable-next-line no-magic-numbers const exp = match.substr(2, match.length - 3).trim(); return get(exp, map, fallback); }); }
unlicense
matto483/wwjd
src/main/java/com/example/repository/UserDaoImpl.java
1275
package com.example.repository; import com.example.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * Created by MattyG on 6/8/17. */ @Repository public class UserDaoImpl implements UserDao{ @Autowired JdbcTemplate jdbcTemplate; @Override public void add(User user) { jdbcTemplate.update("INSERT INTO users(username, password, enabled) VALUES (?,?,?)", user.getUsername(), user.getPassword(), user.isEnabled()); } @Override public boolean isFound(String username){ String sql = "select username from users where username = ?"; try { jdbcTemplate.queryForObject( sql, String.class, username); return true; } catch (EmptyResultDataAccessException e) { return false; } } @Override public void add(String username) { jdbcTemplate.update("INSERT INTO users(username, password, enabled) VALUES (?,?,?)", username, null, true); } }
unlicense
NxtChg/pieces
js/int64/int64.js
6785
const POW2_32 = Math.pow(2, 32); const POW2_64 = Math.pow(2, 64); /* Constructors: - Int64(123) - Int64(Int64) - Int64(hi,lo) */ function Int64(v, low) { this.hi = this.lo = 0; if(v !== undefined) this.from(v, low); }//____________________________________________________________________________ Int64.prototype.is_eq = function(v){ return (this.hi == v.hi && this.lo == v.lo); }; Int64.prototype.is_nul = function(v){ return (this.hi == 0 && this.lo == 0); }; Int64.prototype.is_neg = function(v){ return (this.hi | 0) < 0; }; Int64.prototype.cmp = function(v, unsign) // compare: +1, 0, -1 { var a = (unsign ? this.hi >>> 0 : this.hi | 0); var b = (unsign ? v.hi >>> 0 : v.hi | 0); if(a < b) return -1; if(a > b) return +1; if(this.lo < v.lo) return -1; if(this.lo > v.lo) return +1; return 0; };//___________________________________________________________________________ Int64.prototype.neg = function() { if(this.hi == 2147483648 && this.lo == 0){ this.hi--; this.lo = POW2_32-1; return; } // special case for 0x80000000|00000000 var a = this.lo >>> 0; this.lo = (-a) >>> 0; var r = (a | (~a & this.lo)) >>> 31; this.hi = (-(this.hi >>> 0) - r) >>> 0; };//___________________________________________________________________________ Int64.prototype.abs = function(){ if(this.is_neg()) this.neg(); }; Int64.prototype.not = function(v) { if(!(v instanceof Int64)) v = new Int64(v); this.hi = (~this.hi) >>> 0; this.lo = (~this.lo) >>> 0; }; Int64.prototype.and = function(v) { if(!(v instanceof Int64)) v = new Int64(v); this.hi = (this.hi & v.hi) >>> 0; this.lo = (this.lo & v.lo) >>> 0; }; Int64.prototype.or = function(v) { if(!(v instanceof Int64)) v = new Int64(v); this.hi = (this.hi | v.hi) >>> 0; this.lo = (this.lo | v.lo) >>> 0; }; Int64.prototype.xor = function(v) { if(!(v instanceof Int64)) v = new Int64(v); this.hi = (this.hi ^ v.hi) >>> 0; this.lo = (this.lo ^ v.lo) >>> 0; }; //_____________________________________________________________________________ Int64.prototype.from = function(v, low) { if(low !== undefined){ this.hi = v; this.lo = low; return this; } if(v instanceof Int64){ this.hi = v.hi; this.lo = v.lo; return this; } var vi = Math.floor(Math.abs(v)) % POW2_64; this.hi = (vi / POW2_32) >>> 0; this.lo = (vi % POW2_32) >>> 0; if(v < 0) this.neg(); return this; };//___________________________________________________________________________ Int64.prototype.add = function(v) { if(!(v instanceof Int64)) v = new Int64(v); var t = (this.lo + v.lo) >>> 0; var c = ((this.lo & v.lo) | (this.lo | v.lo) & ~t) >>> 31; this.lo = t; this.hi = (this.hi + v.hi + c) >>> 0; return this; };//___________________________________________________________________________ Int64.prototype.sub = function(v) { if(!(v instanceof Int64)) v = new Int64(v); var t = ( this.lo - v.lo) >>> 0; var r = ((~this.lo & v.lo) | (~(this.lo ^ v.lo) & t)) >>> 31; this.lo = t; this.hi = (this.hi - v.hi - r) >>> 0; return this; };//___________________________________________________________________________ Int64.prototype.shl_1 = function() // shift left by one bit { this.hi = ((this.hi << 1) | this.lo >>> 31) >>> 0; this.lo = (this.lo << 1) >>> 0; }; Int64.prototype.shr_1 = function(unsign) // shift right by one bit { this.lo = ((this.lo >>> 1) | (this.hi << 31)) >>> 0; this.hi = (unsign ? this.hi >>> 1 : (this.hi >> 1) >>> 0 ); }; Int64.prototype.shl = function(n) // shift left by n bits { n %= 64; if(n < 1) return; this.hi = ((this.hi << n) | (this.lo >>> (32 - n))) >>> 0; this.lo = (this.lo << n) >>> 0; return this; }; Int64.prototype.shr = function(n, unsign) // shift right by n bits { n %= 64; if(n < 1) return; this.lo = ((this.lo >>> n) | (this.hi << (32 - n))) >>> 0; this.hi = (unsign ? this.hi >>> n : (this.hi >> n) >>> 0); return this; };//___________________________________________________________________________ Int64.prototype.mul = function(v) { var a = new Int64(this); var b = new Int64(v); this.hi = this.lo = 0; if(a.is_nul() || b.is_nul()) return this; var an = a.is_neg(); if(an) a.neg(); var bn = b.is_neg(); if(bn) b.neg(); if(a.cmp(b, true) < 0){ var tmp = a; a = b; b = tmp; } while(!b.is_nul()) { if(b.lo & 1) this.add(a); a.shl_1(); b.shr_1(); } if(an != bn) this.neg(); return this; };//___________________________________________________________________________ if(!Math.clz32){ Math.clz32 = function(x){ return (x === 0 ? 32 : 31 - Math.floor(Math.log(x >>> 0) * Math.LOG2E)); }; } Int64.prototype.clz = function(){ return this.hi ? Math.clz32(this.hi) : Math.clz32(this.lo) + 32; }; Int64.prototype._do_div = function(a, b, mod) { var q = new Int64(); switch(a.cmp(b, true)) { case -1:/*a = a; q = new Int64( );*/ break; case 0: a = q; q = new Int64(1); break; case +1: { var shift = b.clz() - a.clz(); b.shl(shift); while(shift-- >= 0) { q.shl_1(); if(!a.is_nul() && a.cmp(b, true) >= 0){ a.sub(b); q.lo |= 1; } b.shr_1(); } } } this.from(mod ? a : q); }; Int64.prototype.div = function(v, mod) { var a = new Int64(this); var b = new Int64(v); if(b.is_nul()) throw 'division by zero'; //if(b.is_one()) return; var an = a.is_neg(); if(an) a.neg(); var bn = b.is_neg(); if(bn) b.neg(); this._do_div(a, b, mod); if((mod && an) | (!mod && an != bn)) this.neg(); return this; }; Int64.prototype.mod = function(v){ this.div(v, true); return this; }; //_____________________________________________________________________________ Int64.prototype.toNumber = function() { if(this.is_neg()){ var t = new Int64(this); t.neg(); return -(t.hi * POW2_32 + t.lo); } return (this.hi * POW2_32 + this.lo); };//___________________________________________________________________________ Int64.prototype.toString = function(base) { var sign = '', t = new Int64(this); base = base || 10; if(t.is_neg()){ t.neg(); sign = '-'; } var s = '', n, v0 = t.lo, v1 = t.hi; if(base == 2) { for(n = 0; n < 32; n++) s = ((v0 >> n) & 1).toString(base) + s; for(n = 0; n < 32; n++) s = ((v1 >> n) & 1).toString(base) + s; return sign + s.replace(/^0+/, '') || '0'; } if(base == 16) { for(n = 0; n < 32; n += 4) s = ((v0 >> n) & 0xF).toString(base) + s; for(n = 0; n < 32; n += 4) s = ((v1 >> n) & 0xF).toString(base) + s; return sign + s.replace(/^0+/, '') || '0'; } return this.toNumber().toString(base); };//___________________________________________________________________________ Int64.prototype.print = function() { var a = ('00000000' + this.hi.toString(16)).slice(-8); var b = ('00000000' + this.lo.toString(16)).slice(-8); console.log('['+a+'|'+b+']', this.toNumber()); }
unlicense
ArturVasilov/PracticeITcs
Course 2 practice/WpfFinalWork/WpfFinalWork/App.xaml.cs
328
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace WpfFinalWork { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
unlicense
yangjun2/android
changhong/changhong_sdk/src/com/lidroid/xutils/http/client/util/URIBuilder.java
9282
/* * Copyright (c) 2013. wyouflf (wyouflf@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lidroid.xutils.http.client.util; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.conn.util.InetAddressUtils; import org.apache.http.message.BasicNameValuePair; import android.text.TextUtils; import com.lidroid.xutils.util.LogUtils; public class URIBuilder { private String scheme; private String encodedAuthority; private String userInfo; private String encodedUserInfo; private String host; private int port; private String path; private List<NameValuePair> queryParams; private String fragment; public URIBuilder() { this.port = -1; } public URIBuilder(final String uri) { try { _digestURI(new URI(uri.replace(" ", "%20"))); } catch (URISyntaxException e) { LogUtils.e(e.getMessage(), e); } } public URIBuilder(final URI uri) { digestURI(uri); } private void _digestURI(final URI uri) { this.scheme = uri.getScheme(); this.encodedAuthority = uri.getRawAuthority(); this.host = uri.getHost(); this.port = uri.getPort(); this.encodedUserInfo = uri.getRawUserInfo(); this.userInfo = uri.getUserInfo(); this.path = uri.getPath(); if (path != null) path = path.replace("%20", " "); String query = uri.getRawQuery(); if (query != null) query = query.replace("%20", " "); this.queryParams = parseQuery(query); this.fragment = uri.getFragment(); } private void digestURI(final URI uri) { this.scheme = uri.getScheme(); this.encodedAuthority = uri.getRawAuthority(); this.host = uri.getHost(); this.port = uri.getPort(); this.encodedUserInfo = uri.getRawUserInfo(); this.userInfo = uri.getUserInfo(); this.path = uri.getPath(); this.queryParams = parseQuery(uri.getRawQuery()); this.fragment = uri.getFragment(); } private List<NameValuePair> parseQuery(final String query) { if (!TextUtils.isEmpty(query)) { return URLEncodedUtils.parse(query); } return null; } /** * Builds a {@link java.net.URI} instance. * * @param charset */ public URI build(Charset charset) throws URISyntaxException { return new URI(buildString(charset)); } private String buildString(Charset charset) { StringBuilder sb = new StringBuilder(); if (this.scheme != null) { sb.append(this.scheme).append(':'); } if (this.encodedAuthority != null) { sb.append("//").append(this.encodedAuthority); } else if (this.host != null) { sb.append("//"); if (this.encodedUserInfo != null) { sb.append(this.encodedUserInfo).append("@"); } else if (this.userInfo != null) { sb.append(encodeUserInfo(this.userInfo, charset)).append("@"); } if (InetAddressUtils.isIPv6Address(this.host)) { sb.append("[").append(this.host).append("]"); } else { sb.append(this.host); } if (this.port >= 0) { sb.append(":").append(this.port); } } if (this.path != null) { sb.append(encodePath(normalizePath(this.path), charset)); } if (this.queryParams != null) { sb.append("?").append(encodeQuery(this.queryParams, charset)); } if (this.fragment != null) { sb.append("#").append(encodeFragment(this.fragment, charset)); } return sb.toString(); } private String encodeUserInfo(final String userInfo, Charset charset) { return URLEncodedUtils.encUserInfo(userInfo, charset); } private String encodePath(final String path, Charset charset) { return URLEncodedUtils.encPath(path, charset).replace("+", "20%"); } private String encodeQuery(final List<NameValuePair> params, Charset charset) { return URLEncodedUtils.format(params, charset); } private String encodeFragment(final String fragment, Charset charset) { return URLEncodedUtils.encFragment(fragment, charset); } /** * Sets URI scheme. */ public URIBuilder setScheme(final String scheme) { this.scheme = scheme; return this; } /** * Sets URI user info. The value is expected to be unescaped and may contain non ASCII * characters. */ public URIBuilder setUserInfo(final String userInfo) { this.userInfo = userInfo; this.encodedAuthority = null; this.encodedUserInfo = null; return this; } /** * Sets URI user info as a combination of username and password. These values are expected to * be unescaped and may contain non ASCII characters. */ public URIBuilder setUserInfo(final String username, final String password) { return setUserInfo(username + ':' + password); } /** * Sets URI host. */ public URIBuilder setHost(final String host) { this.host = host; this.encodedAuthority = null; return this; } /** * Sets URI port. */ public URIBuilder setPort(final int port) { this.port = port < 0 ? -1 : port; this.encodedAuthority = null; return this; } /** * Sets URI path. The value is expected to be unescaped and may contain non ASCII characters. */ public URIBuilder setPath(final String path) { this.path = path; return this; } /** * Removes URI query. */ public URIBuilder removeQuery() { this.queryParams = null; return this; } /** * Sets URI query. * <p/> * The value is expected to be encoded form data. */ public URIBuilder setQuery(final String query) { this.queryParams = parseQuery(query); return this; } /** * Adds parameter to URI query. The parameter name and value are expected to be unescaped * and may contain non ASCII characters. */ public URIBuilder addParameter(final String param, final String value) { if (this.queryParams == null) { this.queryParams = new ArrayList<NameValuePair>(); } this.queryParams.add(new BasicNameValuePair(param, value)); return this; } /** * Sets parameter of URI query overriding existing value if set. The parameter name and value * are expected to be unescaped and may contain non ASCII characters. */ public URIBuilder setParameter(final String param, final String value) { if (this.queryParams == null) { this.queryParams = new ArrayList<NameValuePair>(); } if (!this.queryParams.isEmpty()) { for (Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) { NameValuePair nvp = it.next(); if (nvp.getName().equals(param)) { it.remove(); } } } this.queryParams.add(new BasicNameValuePair(param, value)); return this; } /** * Sets URI fragment. The value is expected to be unescaped and may contain non ASCII * characters. */ public URIBuilder setFragment(final String fragment) { this.fragment = fragment; return this; } public String getScheme() { return this.scheme; } public String getUserInfo() { return this.userInfo; } public String getHost() { return this.host; } public int getPort() { return this.port; } public String getPath() { return this.path; } public List<NameValuePair> getQueryParams() { if (this.queryParams != null) { return new ArrayList<NameValuePair>(this.queryParams); } else { return new ArrayList<NameValuePair>(); } } public String getFragment() { return this.fragment; } private static String normalizePath(String path) { if (path == null) { return null; } int n = 0; for (; n < path.length(); n++) { if (path.charAt(n) != '/') { break; } } if (n > 1) { path = path.substring(n - 1); } return path; } }
unlicense
Samourai-Wallet/sentinel-android
app/src/main/java/com/samourai/sentinel/util/TypefaceUtil.java
722
package com.samourai.sentinel.util; import android.content.Context; import android.graphics.Typeface; public class TypefaceUtil { public static int awesome_arrow_down = 0xf063; public static int awesome_arrow_up = 0xf062; private static Typeface awesome_font = null; private static TypefaceUtil instance = null; private TypefaceUtil() { ; } public static TypefaceUtil getInstance(Context ctx) { if(instance == null) { instance = new TypefaceUtil(); awesome_font = Typeface.createFromAsset(ctx.getAssets(), "fontawesome-webfont.ttf"); } return instance; } public Typeface getAwesomeTypeface() { return awesome_font; } }
unlicense
andreas-schluens-asdev/asdk
jms-core/src/main/java/net/as_development/asdk/jms/core/beans/JMSMessageUtils.java
4480
/** * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package net.as_development.asdk.jms.core.beans; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.Validate; //============================================================================= public class JMSMessageUtils { //------------------------------------------------------------------------- private JMSMessageUtils () {} //------------------------------------------------------------------------- public static String getMessageType (final javax.jms.Message aMessage) throws Exception { final String sType = aMessage.getStringProperty(JMSMessageBean.HEADER_MSGTYPE); return sType; } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") public static < T extends JMSMessageBean > T emptyBeanFitsToMessage (final javax.jms.Message aMessage) throws Exception { final String sType = getMessageType (aMessage); Validate.notEmpty(sType, "No 'type' header defined in message. Cant create suitable message ..."); return (T) JMSMessageUtils.newBeanForType (sType); } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") public static < T extends JMSMessageBean > T newBeanForType (final String sType) throws Exception { final Class< T > aType = (Class< T >) Class.forName(sType); final Object aBean = aType.newInstance(); return (T) aBean; } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") public static < T extends JMSMessageBean > T constructResponse4Request (final T aRequest) throws Exception { final String sType = aRequest.getType(); final T aResponse = (T) newBeanForType (sType); aResponse.setJMSCorrelationID(aRequest.getJMSID()); final Set< String > lCustomHeader = aRequest.listCustomHeader(); for (final String sHeader : lCustomHeader) { if ( ! JMSBeanMapper.isCustomHeader (sHeader)) continue; final Object aValue = aRequest.getCustomHeader(sHeader); aResponse.setCustomHeader(sHeader, aValue); } return aResponse; } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") public static <T extends JMSMessageBean> T mapMessageToBean (final javax.jms.Message aMessage) throws Exception { final JMSMessageBean aBean = emptyBeanFitsToMessage(aMessage); mapMessageToBean (aMessage, aBean); return (T) aBean; } //------------------------------------------------------------------------- public static <T extends JMSMessageBean> void mapMessageToBean (final javax.jms.Message aMessage, final T aBean ) throws Exception { final JMSBeanMapper aMapper = JMSBeanMapper.get(); aMapper.mapMessageToBean(aMessage, aBean); } //------------------------------------------------------------------------- public static <T extends JMSMessageBean> void mapBeanToMessage (final T aBean , final javax.jms.Message aMessage) throws Exception { final JMSBeanMapper aMapper = JMSBeanMapper.get(); aMapper.mapBeanToMessage(aBean, aMessage); } }
unlicense
Your-Name-Here/MyCms
model/plugin.class.php
2916
<?php class plugin { private $events = array(); private $return = array(); private $hooks = array(); private $plugins = array(); function __construct() { } public function page($id) { $this->page = $id; } public function get_event_count($eventName) { return count($this->events[$eventName]); } /** * Attach Hook - Allows a plugin author to create a function and attach that function to fire when that hook is called using trigger_hook(). * @return void * @author Cody */ public function attach_hook($eventName, $callback) { if (!isset($this->events[$eventName])) { $this->events[$eventName] = array();} $this->events[$eventName][] = $callback; //return $callback; } /** * Trigger Hook - Allows a plugin author to attach a function to fire at this point in the script using attach_hook(). * @return void * @author Cody */ public function trigger_hook($eventName, $data = null, $array = FALSE ) { $this->hooks[] = $eventName; //echo $eventName." ".count($this->events[$eventName])."\n"; if(isset($this->events[$eventName]) ) { $ret_data = FALSE; foreach ($this->events[$eventName] as $callback) { $func_data = call_user_func($callback, $data); if($array) { $ret_data[] .= $func_data; } else { $ret_data = $func_data; } //echo $callback.": ".print_r($ret_data)."</br>"; } return $ret_data; } else { if(!is_array($data)) { return $data; } else if(isset($data['value'])) { return $data['value']; } else { return $data; } } } function parse_content($type) { return "Type: ".$type; } function register($name) { $this->plugins[] .= $name; } public function set_setting($name, $key, $value) { $this->plugins[$name][$key]=$value; } public function get_setting($name, $key) { if(in_array($name, array_keys($this->plugins))) { return $this->plugins[$name][$key]; } else { return FALSE; } } /** * Create a new block type. * @param typeName - Name the block * @param config_HTML - the html codes that will be inserted into the block list when dropping a block of this type onto the page. * @return void * @author Cody */ public function get_event_list() { return $this->events; } public function get_hooks() { return $this->hooks; } /** * Check to see if the current user is an administrator of the website. * * @return Booleen * @author */ public function is_user_admin() { $db = new database; $db->select('is_admin')->from('users')->where("id", "=", $_SESSION['user_id'])->go(FALSE); if ($db->data['is_admin'] == TRUE) { return TRUE; } else { return FALSE; } } } ?>
unlicense
AnuVishu/Sparse_Matrix
main.cpp
2801
#include <bits/stdc++.h> #include <debug/debug.h> using namespace std; int main() { int row; int col; cout << "enter the row "; cin >> row; cout << endl << "enter the column "; cin >> col; cout << endl; int mat[row][col]; int cntr=0; int non_zero; cout << "enter the elements of the sparse matrix" << endl; for(int i=0 ; i<row ; ++i) for(int j=0; j<col ; ++j) cin >> mat[i][j]; for(int i=0 ; i<row ; ++i){ for(int j=0 ;j<col; ++j) cout << "| " << mat[i][j] << " "; cout << endl; } cout << "the total no of elements in the matrix is " << row*col << endl; for(int i=0 ; i<row ; ++i) for(int j=0 ; j<col ; ++j){ if(mat[i][j] == 0) { cntr++; } } cout << "the total no fo 0's in the matrix are " << cntr << endl; non_zero = ((row*col)-cntr); cout << "total no of non zeros in the matrix is " << non_zero << endl; if(non_zero < cntr){ cout << endl << "**suitable for sparse matrix**" << endl; cout << endl << "Do you want to proceed? (y/n) "; char usr_choice; cin >> usr_choice; int temp=0; if(usr_choice == 'y' || usr_choice == 'Y'){ cout << "loading....." << endl << endl; int sprse_mat[non_zero][3]; int row_count=0; int col_count=0; for(int i=0 ; i<row ; ++i){ for(int j=0 ; j<col ; ++j) { if(mat[i][j] != 0){ col_count++; break; } } for(int k=0 ; k<col ; ++k) { if(mat[k][i] != 0){ row_count++; break; } } } cout << "row-> "<< row_count << endl <<"column-> "<< col_count << endl; //INITIALIZING THE INITIAL KNOWN VALUES sprse_mat[0][0] = row_count; sprse_mat[0][1] = col_count; sprse_mat[0][2] = non_zero; int cnt=1; for(int i=0 ; i<row ; ++i){ for(int j=0 ; j<col ; ++j){ if(mat[i][j] != 0){ sprse_mat[cnt][0] = i; sprse_mat[cnt][1] = j; sprse_mat[cnt][2] = mat[i][j]; cnt++; } } } //OUTPUT..... cout << "Sparse matrix of the above matrix is "<<endl; for(int i=0 ; i<=non_zero ; ++i){ for(int j=0 ; j<3 ; ++j) { cout << sprse_mat[i][j] << " "; } cout << endl; } } else if(usr_choice == 'n' || usr_choice == 'N') exit(0); } else{ cout << endl << "**not suitable for the sparse matrix**" << endl; } }
unlicense
dzucconi/corrasable
app/controllers/application_controller.rb
257
class ApplicationController < ActionController::Base after_action :allow_iframe def home @output = HTML.render(File.open("#{Rails.root}/README.md").read) end private def allow_iframe response.headers.except! 'X-Frame-Options' end end
unlicense
yayashanzei/iDesignFrame
Static/Jformer/js/jFormer.js
113095
/* * jFormer JavaScript Library v1.4.4 * http://jFormer.com/ * * Copyright 2011, Kirk Ouimet, Seth Zander Jensen * Dual licensed under the MIT or GPL Version 2 licenses. * http://jFormer.com/download#license * * Date: Mon Jan 10 2011 */ /** OTHER LICENSES * jquery.simpletip 1.3.1. A simple tooltip plugin * Copyright (c) 2009 Craig Thompson * http://craigsworks.com * Licensed under GPLv3 * http://www.opensource.org/licenses/gpl-3.0.html * Version : 1.3.1 * Released: February 5, 2009 - 11:04am * ---- * jQuery.ScrollTo - Easy element scrolling using jQuery. * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under MIT and GPL. * Date: 3/9/2009 * @author Ariel Flesler * @version 1.4.1 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html * ---- * Masked Input plugin for jQuery * Copyright (c) 2007-2009 Josh Bush (digitalbush.com) * Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) * Version: 1.2.2 (03/09/2009 22:39:06) * ---- * Date Input 1.2.1 * Requires jQuery version: >= 1.2.6 * Copyright (c) 2007-2008 Jonathan Leighton & Torchbox Ltd */ (function(){var a=false,b=/xyz/.test(function(){})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(c){function d(){!a&&this.init&&this.init.apply(this,arguments)}var e=this.prototype;a=true;var f=new this;a=false;for(var g in c)f[g]=typeof c[g]=="function"&&typeof e[g]=="function"&&b.test(c[g])?function(h,j){return function(){var l=this._super;this._super=e[h];var k=j.apply(this,arguments);this._super=l;return k}}(g,c[g]):c[g];d.prototype=f;d.constructor=d;d.extend=arguments.callee; return d}})(); DateInput=function(a){function b(c,d){if(typeof opts!="object")d={};a.extend(this,b.DEFAULT_OPTS,d);var e=a('<span class="jFormComponentDateButton">Find Date</span>');this.input=a(c);this.input.after(e);this.button=a(c).parent().find("span.jFormComponentDateButton");this.bindMethodsToObj("show","hide","hideIfClickOutside","keydownHandler","selectDate");this.build();this.selectDate();this.hide()}b.DEFAULT_OPTS={jFormComponentDateSelectorMonthNames:["January","February","March","April","May","June", "July","August","September","October","November","December"],short_jFormComponentDateSelectorMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],short_day_names:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],start_of_week:0};b.prototype={build:function(){var c=a('<p class="jFormComponentDateSelectorMonthNavigator"><span class="jFormComponentDateSelectorButton jFormComponentDateSelectorPrevious" title="[Page-Up]">&#171;</span> <span class="jFormComponentDateSelectorMonthName"></span> <span class="jFormComponentDateSelectorButton jFormComponentDateSelectorNext" title="[Page-Down]">&#187;</span></p>'); this.monthNameSpan=a(".jFormComponentDateSelectorMonthName",c);a(".jFormComponentDateSelectorPrevious",c).click(this.bindToObj(function(){this.moveMonthBy(-1)}));a(".jFormComponentDateSelectorNext",c).click(this.bindToObj(function(){this.moveMonthBy(1)}));var d=a('<p class="jFormComponentDateSelectorYearNavigator"><span class="jFormComponentDateSelectorButton jFormComponentDateSelectorPrevious" title="[Ctrl+Page-Up]">&#171;</span> <span class="jFormComponentDateSelectorYearName"></span> <span class="jFormComponentDateSelectorButton jFormComponentDateSelectorNext" title="[Ctrl+Page-Down]">&#187;</span></p>'); this.yearNameSpan=a(".jFormComponentDateSelectorYearName",d);a(".jFormComponentDateSelectorPrevious",d).click(this.bindToObj(function(){this.moveMonthBy(-12)}));a(".jFormComponentDateSelectorNext",d).click(this.bindToObj(function(){this.moveMonthBy(12)}));c=a('<div class="jFormComponentDateSelectorNavigator"></div>').append(c,d);var e="<table><thead><tr>";a(this.adjustDays(this.short_day_names)).each(function(){e+="<th>"+this+"</th>"});e+="</tr></thead><tbody></tbody></table>";this.dateSelector=this.rootLayers= a('<div class="jFormComponentDateSelector"></div>').append(c,e).insertAfter(this.input);if(a.browser.msie&&a.browser.version<7){this.ieframe=a('<iframe class="jFormComponentDateSelectorIEFrame" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);this.rootLayers=this.rootLayers.add(this.ieframe);a(".jFormComponentDateSelectorButton",c).mouseover(function(){a(this).addClass("hover")});a(".jFormComponentDateSelectorButton",c).mouseout(function(){a(this).removeClass("hover")})}this.tbody= a("tbody",this.dateSelector);this.input.change(this.bindToObj(function(){this.selectDate()}));this.selectDate()},selectMonth:function(c){var d=new Date(c.getFullYear(),c.getMonth(),1);if(!this.currentMonth||!(this.currentMonth.getFullYear()==d.getFullYear()&&this.currentMonth.getMonth()==d.getMonth())){this.currentMonth=d;d=this.rangeStart(c);var e=this.rangeEnd(c);e=this.daysBetween(d,e);for(var f="",g=0;g<=e;g++){var h=new Date(d.getFullYear(),d.getMonth(),d.getDate()+g,12,0);if(this.isFirstDayOfWeek(h))f+= "<tr>";f+=h.getMonth()==c.getMonth()?'<td class="jFormComponentDateSelectorSelectedDay" date="'+this.dateToString(h)+'">'+h.getDate()+"</td>":'<td class="jFormComponentDateSelectorUnselectedMonth" date="'+this.dateToString(h)+'">'+h.getDate()+"</td>";if(this.isLastDayOfWeek(h))f+="</tr>"}this.tbody.empty().append(f);this.monthNameSpan.empty().append(this.monthName(c));this.yearNameSpan.empty().append(this.currentMonth.getFullYear());a(".jFormComponentDateSelectorSelectedDay",this.tbody).click(this.bindToObj(function(j){this.changeInput(a(j.target).attr("date"))})); a("td[date="+this.dateToString(new Date)+"]",this.tbody).addClass("jFormComponentDateSelectorToday");a("td.jFormComponentDateSelectorSelectedDay",this.tbody).mouseover(function(){a(this).addClass("hover")});a("td.jFormComponentDateSelectorSelectedDay",this.tbody).mouseout(function(){a(this).removeClass("hover")})}a(".jFormComponentDateSelectorSelected",this.tbody).removeClass("jFormComponentDateSelectorSelected");a("td[date="+this.selectedDateString+"]",this.tbody).addClass("jFormComponentDateSelectorSelected")}, selectDate:function(c){if(typeof c=="undefined")c=this.stringToDate(this.input.val());c||(c=new Date);this.selectedDate=c;this.selectedDateString=this.dateToString(this.selectedDate);this.selectMonth(this.selectedDate)},changeInput:function(c){this.input.val(c).change();this.hide()},show:function(){this.rootLayers.css("display","block");this.button.unbind("click",this.show);this.input.unbind("focus",this.show);a(document.body).keydown(this.keydownHandler);a([window,document.body]).click(this.hideIfClickOutside); this.setPosition()},hide:function(){this.rootLayers.css("display","none");a([window,document.body]).unbind("click",this.hideIfClickOutside);this.button.click(this.show);this.input.focus(this.show);a(document.body).unbind("keydown",this.keydownHandler)},hideIfClickOutside:function(c){c.target!=this.input[0]&&c.target!=this.button[0]&&!this.insideSelector(c)&&this.hide()},insideSelector:function(c){var d=this.dateSelector.offset();d.right=d.left+this.dateSelector.outerWidth();d.bottom=d.top+this.dateSelector.outerHeight(); return c.pageY<d.bottom&&c.pageY>d.top&&c.pageX<d.right&&c.pageX>d.left},keydownHandler:function(c){switch(c.keyCode){case 9:case 27:this.hide();return;case 13:this.changeInput(this.selectedDateString);break;case 33:this.moveDateMonthBy(c.ctrlKey?-12:-1);break;case 34:this.moveDateMonthBy(c.ctrlKey?12:1);break;case 38:this.moveDateBy(-7);break;case 40:this.moveDateBy(7);break;case 37:this.moveDateBy(-1);break;case 39:this.moveDateBy(1);break;default:return}c.preventDefault()},stringToDate:function(c){c= c.replace(/[^\d]/g,"/");return c.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4,4})$/)?new Date(c):null},dateToString:function(c){function d(e){e=""+e;if(e.length==1)e="0"+e;return e}return d(c.getMonth()+1)+"/"+d(c.getDate())+"/"+c.getFullYear()},setPosition:function(){var c=this.button.position();this.rootLayers.css({top:c.top,left:c.left+this.button.outerWidth()+4});this.ieframe&&this.ieframe.css({width:this.dateSelector.outerWidth(),height:this.dateSelector.outerHeight()});c=c.top+this.dateSelector.outerHeight()+ 12;var d="";d=jFormerUtility.isSet(window.scrollY)?window.scrollY:document.documentElement.scrollTop;d+a(window).height()>c||a.scrollTo(c-a(window).height()+"px",250,{axis:"y"})},moveDateBy:function(c){this.selectDate(new Date(this.selectedDate.getFullYear(),this.selectedDate.getMonth(),this.selectedDate.getDate()+c))},moveDateMonthBy:function(c){var d=new Date(this.selectedDate.getFullYear(),this.selectedDate.getMonth()+c,this.selectedDate.getDate());d.getMonth()==this.selectedDate.getMonth()+c+ 1&&d.setDate(0);this.selectDate(d)},moveMonthBy:function(c){this.selectMonth(new Date(this.currentMonth.getFullYear(),this.currentMonth.getMonth()+c,this.currentMonth.getDate()))},monthName:function(c){return this.jFormComponentDateSelectorMonthNames[c.getMonth()]},bindToObj:function(c){var d=this;return function(){return c.apply(d,arguments)}},bindMethodsToObj:function(){for(var c=0;c<arguments.length;c++)this[arguments[c]]=this.bindToObj(this[arguments[c]])},indexFor:function(c,d){for(var e=0;e< c.length;e++)if(d==c[e])return e},monthNum:function(c){return this.indexFor(this.jFormComponentDateSelectorMonthNames,c)},shortMonthNum:function(c){return this.indexFor(this.short_jFormComponentDateSelectorMonthNames,c)},shortDayNum:function(c){return this.indexFor(this.short_day_names,c)},daysBetween:function(c,d){c=Date.UTC(c.getFullYear(),c.getMonth(),c.getDate());d=Date.UTC(d.getFullYear(),d.getMonth(),d.getDate());return(d-c)/864E5},changeDayTo:function(c,d,e){c=e*(Math.abs(d.getDay()-c-e*7)% 7);return new Date(d.getFullYear(),d.getMonth(),d.getDate()+c)},rangeStart:function(c){return this.changeDayTo(this.start_of_week,new Date(c.getFullYear(),c.getMonth()),-1)},rangeEnd:function(c){return this.changeDayTo((this.start_of_week-1)%7,new Date(c.getFullYear(),c.getMonth()+1,0),1)},isFirstDayOfWeek:function(c){return c.getDay()==this.start_of_week},isLastDayOfWeek:function(c){return c.getDay()==(this.start_of_week-1)%7},adjustDays:function(c){for(var d=[],e=0;e<c.length;e++)d[e]=c[(e+this.start_of_week)% 7];return d}};a.fn.date_input=function(c){return this.each(function(){new b(this,c)})};a.date_input={initialize:function(c){a("input.date_input").date_input(c)}};return b}(jQuery); (function(a){var b=(a.browser.msie?"paste":"input")+".mask",c=window.orientation!=undefined;a.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"}};a.fn.extend({caret:function(d,e){if(this.length!=0)if(typeof d=="number"){e=typeof e=="number"?e:d;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(d,e)}else if(this.createTextRange){var g=this.createTextRange();g.collapse(true);g.moveEnd("character",e);g.moveStart("character",d);g.select()}})}else{if(this[0].setSelectionRange){d= this[0].selectionStart;e=this[0].selectionEnd}else if(document.selection&&document.selection.createRange){var f=document.selection.createRange();d=0-f.duplicate().moveStart("character",-1E5);e=d+f.text.length}return{begin:d,end:e}}},unmask:function(){return this.trigger("unmask")},mask:function(d,e){if(!d&&this.length>0){var f=a(this[0]),g=f.data("tests");return a.map(f.data("buffer"),function(n,o){return g[o]?n:null}).join("")}e=a.extend({placeholder:"_",completed:null},e);var h=a.mask.definitions; g=[];var j=d.length,l=null,k=d.length;a.each(d.split(""),function(n,o){if(o=="?"){k--;j=n}else if(h[o]){g.push(RegExp(h[o]));if(l==null)l=g.length-1}else g.push(null)});return this.each(function(){function n(m){for(;++m<=k&&!g[m];);return m}function o(m){var p=a(this).caret(),q=m.keyCode;z=q<16||q>16&&q<32||q>32&&q<41;if(!m.shiftKey){if(q==36){m.preventDefault();a(this).caret(n(0))}if(q==35){m.preventDefault();m=r.val().indexOf(" ");for(p=r.val().length;g[m]==null||r.val().charAt(m)!=" ";){m+=1;if(m== p)break}a(this).caret(m);return false}}if(p.begin-p.end!=0&&(!z||q==8||q==46))u(p.begin,p.end);if(q==8||q==46||c&&q==127){for(m=p.begin+(q==46?0:-1);!g[m]&&--m>=0;);for(p=m;p<k;p++)if(g[p]){s[p]=e.placeholder;q=n(p);if(q<k&&g[p].test(s[q]))s[p]=s[q];else break}y();r.caret(Math.max(l,m));return false}else if(q==27){r.val(t);r.caret(0,v());return false}}function x(m){if(z){z=false;return m.keyCode==8?false:null}m=m||window.event;var p=m.charCode||m.keyCode||m.which,q=a(this).caret();if(m.ctrlKey||m.altKey|| m.metaKey)return true;else if(p>=32&&p<=125||p>186){m=n(q.begin-1);if(m<k){p=String.fromCharCode(p);if(g[m].test(p)){q=m;for(var w=e.placeholder;q<k;q++)if(g[q]){var A=n(q),B=s[q];s[q]=w;if(A<k&&g[A].test(B))w=B;else break}s[m]=p;y();m=n(m);a(this).caret(m);e.completed&&m==k&&e.completed.call(r)}}}return false}function u(m,p){for(var q=m;q<p&&q<k;q++)if(g[q])s[q]=e.placeholder}function y(){return r.val(s.join("")).val()}function v(m){for(var p=r.val(),q=-1,w=0,A=0;w<k;w++)if(g[w]){for(s[w]=e.placeholder;A++< p.length;){var B=p.charAt(A-1);if(g[w].test(B)){s[w]=B;q=w;break}}if(A>p.length)break}else if(s[w]==p[A]&&w!=j){A++;q=w}if(!m&&q+1<j){r.val("");u(0,k)}else if(m||q+1>=j){y();m||r.val(r.val().substring(0,q+1))}return j?w:l}var r=a(this),s=a.map(d.split(""),function(m){if(m!="?")return h[m]?e.placeholder:m}),z=false,t=r.val();r.data("buffer",s).data("tests",g);r.attr("readonly")||r.one("unmask",function(){r.unbind(".mask").removeData("buffer").removeData("tests")}).bind("focus.mask",function(){t=r.val(); var m=v();y();setTimeout(function(){m==d.length?r.caret(0,m):r.caret(m)},0)}).bind("blur.mask",function(){v();r.val()!=t&&r.change()}).bind("keydown.mask",o).bind("keypress.mask",x).bind(b,function(){setTimeout(function(){r.caret(v(true))},0)});v()})}})})(jQuery); (function(a){function b(d){return typeof d=="object"?d:{top:d,left:d}}var c=a.scrollTo=function(d,e,f){a(window).scrollTo(d,e,f)};c.defaults={axis:"xy",duration:parseFloat(a.fn.jquery)>=1.3?0:1};c.window=function(){return a(window).scrollable()};a.fn.scrollable=function(){return this.map(function(){if(!(!this.nodeName||a.inArray(this.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1))return this;var d=(this.contentWindow||this).document||this.ownerDocument||this;return a.browser.safari|| d.compatMode=="BackCompat"?d.body:d.documentElement})};a.fn.scrollTo=function(d,e,f){if(typeof e=="object"){f=e;e=0}if(typeof f=="function")f={onAfter:f};if(d=="max")d=9E9;f=a.extend({},c.defaults,f);e=e||f.speed||f.duration;f.queue=f.queue&&f.axis.length>1;if(f.queue)e/=2;f.offset=b(f.offset);f.over=b(f.over);return this.scrollable().each(function(){function g(u){l.animate(o,e,f.easing,u&&function(){u.call(this,d,f)})}function h(u){var y="scroll"+u;if(!x)return j[y];u="client"+u;var v=j.ownerDocument.documentElement, r=j.ownerDocument.body;return Math.max(v[y],r[y])-Math.min(v[u],r[u])}var j=this,l=a(j),k=d,n,o={},x=l.is("html,body");switch(typeof k){case "number":case "string":if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(k)){k=b(k);break}k=a(k,this);case "object":if(k.is||k.style)n=(k=a(k)).offset()}a.each(f.axis.split(""),function(u,y){var v=y=="x"?"Left":"Top",r=v.toLowerCase(),s="scroll"+v,z=j[s],t=y=="x"?"Width":"Height";if(n){o[s]=n[r]+(x?0:z-l.offset()[r]);if(f.margin){o[s]-=parseInt(k.css("margin"+v))||0;o[s]-= parseInt(k.css("border"+v+"Width"))||0}o[s]+=f.offset[r]||0;if(f.over[r])o[s]+=k[t.toLowerCase()]()*f.over[r]}else o[s]=k[r];if(/^\d+$/.test(o[s]))o[s]=o[s]<=0?0:Math.min(o[s],h(t));if(!u&&f.queue){z!=o[s]&&g(f.onAfterFirst);delete o[s]}});g(f.onAfter)}).end()}})(jQuery); (function(a){function b(e,f,g){var h=f.hash.slice(1),j=document.getElementById(h)||document.getElementsByName(h)[0];if(j){e&&e.preventDefault();var l=a(g.target);if(!(g.lock&&l.is(":animated")||g.onBefore&&g.onBefore.call(g,e,j,l)===false)){g.stop&&l.stop(true);if(g.hash){e=j.id==h?"id":"name";var k=a("<a> </a>").attr(e,h).css({position:"absolute",top:a(window).scrollTop(),left:a(window).scrollLeft()});j[e]="";a("body").prepend(k);location=f.hash;k.remove();j[e]=h}l.scrollTo(j,g).trigger("notify.serialScroll", [j])}}}var c=location.href.replace(/#.*/,""),d=a.localScroll=function(e){a("body").localScroll(e)};d.defaults={duration:1E3,axis:"y",event:"click",stop:true,target:window,reset:true};d.hash=function(e){if(location.hash){e=a.extend({},d.defaults,e);e.hash=false;if(e.reset){var f=e.duration;delete e.duration;a(e.target).scrollTo(0,e);e.duration=f}b(0,location,e)}};a.fn.localScroll=function(e){function f(){return!!this.href&&!!this.hash&&this.href.replace(this.hash,"")==c&&(!e.filter||a(this).is(e.filter))} e=a.extend({},d.defaults,e);return e.lazy?this.bind(e.event,function(g){var h=a([g.target,g.target.parentNode]).filter(f)[0];h&&b(g,h,e)}):this.find("a,area").filter(f).bind(e.event,function(g){b(g,this,e)}).end().end()}})(jQuery); (function(a){var b=".serialScroll",c=a.serialScroll=function(d){a.scrollTo.window().serialScroll(d)};c.defaults={duration:1E3,axis:"x",event:"click",start:0,step:1,lock:1,cycle:1,constant:1};a.fn.serialScroll=function(d){d=a.extend({},c.defaults,d);var e=d.event,f=d.step,g=d.lazy;return this.each(function(){function h(t){t.data+=v;j(t,this)}function j(t,m){if(!isNaN(m)){t.data=m;m=u}var p=t.data,q=t.type,w=d.exclude?k().slice(0,-d.exclude):k(),A=w.length,B=w[p],C=d.duration;q&&t.preventDefault(); if(r){clearTimeout(z);z=setTimeout(l,d.interval)}if(!B){p=p<0?0:p=A-1;if(v!=p)p=p;else if(d.cycle)p=A-p-1;else return;B=w[p]}if(!(!B||q&&v==p||d.lock&&x.is(":animated")||q&&d.onBefore&&d.onBefore.call(m,t,B,x,k(),p)===false)){d.stop&&x.queue("fx",[]).stop();if(d.constant)C=Math.abs(C/f*(v-p));x.scrollTo(B,C,d).trigger("notify"+b,[p])}}function l(){x.trigger("next"+b)}function k(){return a(y,u)}function n(t){if(!isNaN(t))return t;for(var m=k(),p;(p=m.index(t))==-1&&t!=u;)t=t.parentNode;return p}var o= d.target?this:document,x=a(d.target||this,o),u=x[0],y=d.items,v=d.start,r=d.interval,s=d.navigation,z;g||(y=k());d.force&&j({},v);a(d.prev||[],o).bind(e,-f,h);a(d.next||[],o).bind(e,f,h);u.ssbound||x.bind("prev"+b,-f,h).bind("next"+b,f,h).bind("goto"+b,j);r&&x.bind("start"+b,function(){if(!r){clearTimeout(z);r=1;l()}}).bind("stop"+b,function(){clearTimeout(z);r=0});x.bind("notify"+b,function(t,m){var p=n(m);if(p>-1)v=p});u.ssbound=1;if(d.jump)(g?x:k()).bind(e,function(t){j(t,n(t.target))});if(s)s= a(s,o).bind(e,function(t){t.data=Math.round(k().length/s.length)*s.index(this);j(t,this)})})}})(jQuery); (function(){function a(b,c){var d=this;b=jQuery(b);var e=['<span class="tipArrow"></span><div class="tipContent">',c.content.html(),"</div>"].join(""),f=jQuery(c.content).addClass(c.baseClass).addClass(c.fixed?c.fixedClass:"").addClass(c.persistent?c.persistentClass:"").html(e);jQuery(window).resize(function(){f.is(":visible")&&d.updatePos()});c.hidden?f.hide():f.show();if(c.persistent){b.click(function(){b.get(0)});jQuery(window).mousedown(function(g){f.css("display")!=="none"&&c.focus&&jQuery(g.target).parents(".tooltip").andSelf().filter(function(){return this=== f.get(0)})})}else{b.hover(function(g){d.show(g)},function(){d.hide()});c.fixed||b.mousemove(function(g){f.css("display")!=="none"&&d.updatePos(g)})}jQuery.extend(d,{getVersion:function(){return[1,2,0]},getParent:function(){return b},getTooltip:function(){return f},getPos:function(){return f.position()},setPos:function(g,h){var j=b.position();if(typeof g=="string")g=parseInt(g)+j.left;if(typeof h=="string")h=parseInt(h)+j.top;f.css({left:g,top:h});return d},show:function(g){if(c.onBeforeShow()===false)return false; d.updatePos(c.fixed?null:g);switch(c.showEffect){case "fade":f.fadeIn(c.showTime);break;case "slide":f.slideDown(c.showTime,d.updatePos);break;case "custom":c.showCustom.call(f,c.showTime);break;default:case "none":f.show()}f.addClass(c.activeClass);c.onShow.call(d);jQuery(document).trigger("blurTip",[f,"show"]);return d},hide:function(){c.onBeforeHide.call(d);switch(c.hideEffect){case "fade":f.fadeOut(c.hideTime);break;case "slide":f.slideUp(c.hideTime);break;case "custom":c.hideCustom.call(f,c.hideTime); break;default:case "none":f.hide()}f.removeClass(c.activeClass);c.onHide.call(d);jQuery(document).trigger("blurTip",[f,"hide"]);return d},update:function(){return d},load:function(g,h){c.beforeContentLoad.call(d);f.load(g,h,function(){c.onContentLoad.call(d)});return d},boundryCheck:function(g,h){var j=g+f.outerWidth(),l=h+f.outerHeight(),k=jQuery(window).width()+jQuery(window).scrollLeft(),n=jQuery(window).height()+jQuery(window).scrollTop();return[j>=k,l>=n]},updatePos:function(g){var h=f.outerWidth(), j=f.outerHeight();if(!g&&c.fixed)if(c.position.constructor==Array){o=parseInt(c.position[0]);g=parseInt(c.position[1])}else if(jQuery(c.position).attr("nodeType")===1){g=jQuery(c.position).position();o=g.left;g=g.top}else{var l=b.position(),k=b.outerWidth(),n=b.outerHeight(),o="";g="";switch(c.position){case "top":o=l.left-h/2+k/2;g=l.top-j;break;case "bottom":o=l.left-h/2+k/2;g=l.top+n;break;case "left":o=l.left-h;g=l.top-j/2+n/2;break;case "right":o=l.left+k;g=l.top-j/2+n/2;break;case "topRight":o= l.left+k;g=l.top;break;default:case "default":o=k/2+l.left+20;g=l.top}}else{o=g.pageX;g=g.pageY}if(typeof c.position!="object"){o+=c.offset[0];g+=c.offset[1];if(c.boundryCheck){l=d.boundryCheck(o,g);if(l[0])o=o-h/2-2*c.offset[0];if(l[1])g=g-j/2-2*c.offset[1]}}else{if(typeof c.position[0]=="string")o=String(o);if(typeof c.position[1]=="string")g=String(g)}d.setPos(o,g);return d}})}jQuery.fn.simpletip=function(b){var c=jQuery(this).eq(typeof b=="number"?b:0).data("simpletip");if(c)return c;var d={content:"A simple tooltip", persistent:false,focus:false,hidden:true,position:"default",offset:[0,0],boundryCheck:false,fixed:true,showEffect:"fade",showTime:150,showCustom:null,hideEffect:"fade",hideTime:150,hideCustom:null,baseClass:"tooltip",activeClass:"active",fixedClass:"fixed",persistentClass:"persistent",focusClass:"focus",onBeforeShow:function(){return true},onShow:function(){},onBeforeHide:function(){},onHide:function(){},beforeContentLoad:function(){},onContentLoad:function(){}};jQuery.extend(d,b);this.each(function(){var e= new a(jQuery(this),d);jQuery(this).data("simpletip",e)});return this}})(); JFormer=Class.extend({init:function(a,b){this.initializing=true;this.options=$.extend(true,{animationOptions:{pageScroll:{duration:375,adjustHeightDuration:375},instance:{appearDuration:0,appearEffect:"fade",removeDuration:0,removeEffect:"fade",adjustHeightDuration:0},dependency:{appearDuration:250,appearEffect:"fade",hideDuration:100,hideEffect:"fade",adjustHeightDuration:100},alert:{appearDuration:250,appearEffect:"fade",hideDuration:100,hideEffect:"fade"},modal:{appearDuration:0,hideDuration:0}}, trackBind:false,disableAnalytics:false,setupPageScroller:true,validationTips:true,pageNavigator:false,saveState:false,splashPage:false,progressBar:false,alertsEnabled:true,clientSideValidation:true,debugMode:false,submitButtonText:"Submit",submitProcessingButtonText:"Processing...",onSubmitStart:function(){return true},onSubmitFinish:function(){return true}},b.options||{});if(this.options.trackBind)jQuery.fn.bind=function(d){return function(){console.count("jQuery Bind Count");console.log("jQuery Bind %o", arguments[0],this);return d.apply(this,arguments)}}(jQuery.fn.bind);this.id=a;this.form=$(["form#",this.id].join(""));this.formData={};this.jFormPageWrapper=this.form.find("div.jFormPageWrapper");this.jFormPageScroller=this.form.find("div.jFormPageScroller");this.jFormPageNavigator=null;this.jFormPages={};this.maxJFormPageIdArrayIndexReached=this.currentJFormPage=null;this.jFormPageIdArray=[];this.currentJFormPageIdArrayIndex=null;this.blurredTips=[];this.lastEnabledPage=false;this.initializationTime= (new Date).getTime()/1E3;this.jFormComponentCount=this.durationInSeconds=0;this.control=this.form.find("ul.jFormerControl");this.controlNextLi=this.form.find("ul.jFormerControl li.nextLi");this.controlNextButton=this.controlNextLi.find("button.nextButton");this.controlPreviousLi=this.form.find("ul.jFormerControl li.previousLi");this.controlPreviousButton=this.controlPreviousLi.find("button.previousButton");this.saveIntervalSetTimeoutId=null;this.initPages(b.jFormPages);if(this.options.splashPage!== false||this.options.saveState!==false){if(this.options.splashPage==false)this.options.splashPage={};this.addSplashPage()}else{this.maxJFormPageIdArrayIndexReached=this.currentJFormPageIdArrayIndex=0;this.currentJFormPage=this.jFormPages[this.jFormPageIdArray[0]];this.currentJFormPage.active=true;this.currentJFormPage.startTime=(new Date).getTime()/1E3;this.options.pageNavigator!==false&&this.addPageNavigator()}this.options.setupPageScroller&&this.setupPageScroller();this.hideInactivePages();this.setupControl(); this.addSubmitListener();this.addEnterKeyListener();this.addBlurTipListener();this.checkDependencies(true);this.initializing=false;var c=this;$(window).load(function(){c.adjustHeight()})},initPages:function(a){var b=this,c=$.each,d={};c(a,function(e,f){var g=new JFormPage(b,e,f.options);g.show();g.options.dependencyOptions!==null&&$.each(g.options.dependencyOptions.dependentOn,function(h,j){if(d[j]===undefined)d[j]={pages:[],sections:[],components:[]};d[j].pages.push({jFormPageId:e})});c(f.jFormSections, function(h,j){var l=new JFormSection(g,h,j.options);l.options.dependencyOptions!==null&&$.each(l.options.dependencyOptions.dependentOn,function(k,n){if(d[n]===undefined)d[n]={pages:[],sections:[],components:[]};d[n].sections.push({jFormPageId:e,jFormSectionId:h})});c(j.jFormComponents,function(k,n){b.jFormComponentCount+=1;var o=new window[n.type.split('\\').pop()](l,k,n.type,n.options);l.addComponent(o);o.options.dependencyOptions!==null&&$.each(o.options.dependencyOptions.dependentOn,function(x,u){if(d[u]===undefined)d[u]= {pages:[],sections:[],components:[]};d[u].components.push({jFormPageId:e,jFormSectionId:h,jFormComponentId:k})})});g.addSection(l)});b.addJFormPage(g)});$.each(d,function(e,f){$("#"+e+":text, textarea#"+e).bind("keyup",function(){$.each(f.pages,function(h,j){b.jFormPages[j.jFormPageId].checkDependencies()});$.each(f.sections,function(h,j){b.jFormPages[j.jFormPageId].jFormSections[j.jFormSectionId].checkDependencies()});$.each(f.components,function(h,j){b.jFormPages[j.jFormPageId].jFormSections[j.jFormSectionId].jFormComponents[j.jFormComponentId].checkDependencies()})}); $("#"+e+"-wrapper").bind("jFormComponent:changed",function(){$.each(f.pages,function(h,j){b.jFormPages[j.jFormPageId].checkDependencies()});$.each(f.sections,function(h,j){b.jFormPages[j.jFormPageId].jFormSections[j.jFormSectionId].checkDependencies()});$.each(f.components,function(h,j){b.jFormPages[j.jFormPageId].jFormSections[j.jFormSectionId].jFormComponents[j.jFormComponentId].checkDependencies()})});var g=b.select(e);if(g!==null&&g.options.instanceOptions!==null)g.options.dependencies=f})},select:function(a){var b= false,c=null;$.each(this.jFormPages,function(d,e){$.each(e.jFormSections,function(f,g){$.each(g.jFormComponents,function(h,j){if(j.id==a){c=j;b=true}return!b});return!b});return!b});return c},checkDependencies:function(){$.each(this.jFormPages,function(a,b){b.checkDependencies();$.each(b.jFormSections,function(c,d){d.checkDependencies();$.each(d.jFormComponents,function(e,f){f.checkDependencies()})})})},addSplashPage:function(){var a=this;this.options.splashPage.jFormPage=new JFormPage(this,this.form.find("div.jFormerSplashPage").attr("id")); this.options.splashPage.jFormPage.addSection(new JFormSection(this.options.splashPage.jFormPage,this.form.find("div.jFormerSplashPage").attr("id")+"-section"));this.options.splashPage.jFormPage.page.width(this.form.width());this.options.splashPage.jFormPage.active=true;this.options.splashPage.jFormPage.startTime=(new Date).getTime()/1E3;this.currentJFormPage=this.options.splashPage.jFormPage;this.jFormPageWrapper.height(this.options.splashPage.jFormPage.page.outerHeight());if(this.options.splashPage.customButtonId){this.options.splashPage.controlSplashLi= this.form.find("#"+this.options.splashPage.customButtonId);this.options.splashPage.controlSplashButton=this.form.find("#"+this.options.splashPage.customButtonId)}else{this.options.splashPage.controlSplashLi=this.form.find("li.splashLi");this.options.splashPage.controlSplashButton=this.form.find("button.splashButton")}this.setupControl();this.options.saveState!==false?a.addSaveStateToSplashPage():this.options.splashPage.controlSplashButton.bind("click",function(b){b.preventDefault();a.beginFormFromSplashPage(false)})}, beginFormFromSplashPage:function(a,b){var c=this;if(this.options.pageNavigator!==false&&this.jFormPageNavigator==null){this.addPageNavigator();this.jFormPageNavigator.show()}else this.options.pageNavigator!==false&&this.jFormPageNavigator.show();this.form.find(".jFormPage").css("width",this.form.find(".jFormWrapperContainer").width());c.options.splashPage.jFormPage.active=false;if(!b){c.currentJFormPageIdArrayIndex=0;c.jFormPages[c.jFormPageIdArray[0]].scrollTo({onAfter:function(){c.options.splashPage.jFormPage.hide(); c.renumberPageNavigator()}})}a&&c.initSaveState()},addSaveStateToSplashPage:function(){var a=this,b=a.options.splashPage.jFormPage.id+"-section";$.each(a.options.saveState.components,function(e,f){a.options.splashPage.jFormPage.jFormSections[b].addComponent(new window[f.type](a.options.splashPage.jFormPage.jFormSections[b],e,f.type,f.options))});var c="newForm",d=this.options.splashPage.jFormPage.jFormSections[b].jFormComponents;d.saveStateStatus.component.find("input:option").bind("click",{context:this}, function(e){a.form.find("li.jFormerFailureNotice").remove();c=$(e.target).val();if(c=="newForm"){d.saveStatePassword.component.find("label").html('Create password: <span class="jFormComponentLabelRequiredStar"> *</span>');a.options.splashPage.controlSplashButton.text("Begin")}else if(c=="resumeForm"){d.saveStatePassword.component.find("label").html('Form password: <span class="jFormComponentLabelRequiredStar"> *</span>');a.options.splashPage.controlSplashButton.text("Resume")}});a.options.splashPage.controlSplashButton.bind("click", {context:this},function(e){e.preventDefault();a.form.find("li.jFormerFailureNotice").remove();var f=d.saveStateIdentifier.validate(),g=d.saveStatePassword.validate();if(f&&g){if(c=="newForm"){a.options.splashPage.controlSplashButton.text("Creating form...");var h={};h.meta={};h.meta.totalTime=0;h.meta.currentPage=a.getActivePage().id;h.meta.maxPageIndex=a.maxJFormPageIdArrayIndexReached;h.form={}}else a.options.splashPage.controlSplashButton.text("Loading form...");$(e.target).attr("disabled","disabled"); $.ajax({url:a.form.attr("action"),type:"post",data:{jFormerTask:"initializeSaveState",identifier:d.saveStateIdentifier.getValue(),password:d.saveStatePassword.getValue(),formState:c,formData:jFormerUtility.jsonEncode(h)},dataType:"json",success:function(j){if(j.status=="success")if(c=="newForm")a.beginFormFromSplashPage(true,false);else{if(c=="resumeForm"){a.beginFormFromSplashPage(true,true);a.durationInSeconds=j.response.meta.totalTime;a.setData(j.response.form);a.maxJFormPageIdArrayIndexReached= j.response.meta.maxPageIndex;a.options.pageNavigator!=null&&a.updatePageNavigator();if(a.jFormPages[j.response.meta.currentPage]==undefined)j.response.meta.currentPage=a.jFormPages[a.jFormPageIdArray[0]].id;if(a.jFormPages[j.response.meta.currentPage].active===false){a.currentJFormPageIdArrayIndex=$.inArray(j.response.meta.currentPage,a.jFormPageIdArray);a.jFormPages[j.response.meta.currentPage].scrollTo({onAfter:function(){a.options.splashPage.jFormPage.hide()}})}}}else if(j.status=="exists"){c== "newForm"?a.options.splashPage.controlSplashButton.text("Begin"):a.options.splashPage.controlSplashButton.text("Resume");j.response.failureNoticeHtml&&a.control.append($('<li class="jFormerFailureNotice jFormComponentValidationFailed">'+j.response.failureNoticeHtml+"</li>"));$(e.target).removeAttr("disabled")}else if(j.status=="failure"){c=="newForm"?a.options.splashPage.controlSplashButton.text("Begin"):a.options.splashPage.controlSplashButton.text("Resume");j.response.failureNoticeHtml&&a.control.append($(['<li class="jFormerFailureNotice jFormComponentValidationFailed">', j.response.failureNoticeHtml,"</li>"].join("")));j.response.failureJs&&eval(j.response.failureJs);$(e.target).removeAttr("disabled")}},error:function(){a.showAlert("There was a problem initializing the form.");a.setupControl()}})}else a.options.splashPage.jFormPage.focusOnFirstFailedComponent()})},addPageNavigator:function(){var a=this;this.jFormPageNavigator=this.form.find(".jFormPageNavigator");this.jFormPageNavigator.find(".jFormPageNavigatorLink:first").click(function(){if(a.currentJFormPageIdArrayIndex!= 0){a.currentJFormPageIdArrayIndex=0;a.scrollToPage(a.jFormPageIdArray[0],{})}});this.options.pageNavigator.position=="right"&&this.form.find(".jFormWrapperContainer").width(this.form.width()-this.jFormPageNavigator.width()-30)},updatePageNavigator:function(){for(var a=this,b,c,d=1;d<=this.maxJFormPageIdArrayIndexReached+1;d++){b=d;var e=$("#navigatePage"+b);this.currentJFormPageIdArrayIndex!=b-1?e.removeClass("jFormPageNavigatorLinkActive"):e.addClass("jFormPageNavigatorLinkActive");if(e.hasClass("jFormPageNavigatorLinkLocked")){e.removeClass("jFormPageNavigatorLinkLocked").addClass("jFormPageNavigatorLinkUnlocked"); e.click(function(f){f=$(f.target);f.is("li")||(f=f.closest("li"));c=f.attr("id").match(/[0-9]+$/);c=parseInt(c)-1;a.getActivePage().validate(true);a.currentJFormPageIdArrayIndex!=c&&a.scrollToPage(a.jFormPageIdArray[c]);a.currentJFormPageIdArrayIndex=c})}}},renumberPageNavigator:function(){$(".jFormPageNavigatorLink:visible").each(function(a,b){$(b).find("span").length>0?$(b).find("span").html(a+1):$(b).html("Page "+(a+1))})},addJFormPage:function(a){this.jFormPageIdArray.push(a.id);this.jFormPages[a.id]= a},removeJFormPage:function(a){$("#"+a).remove();this.jFormPageIdArray=$.grep(this.jFormPageIdArray,function(b){return b!=a});delete this.jFormPages[a]},addEnterKeyListener:function(){var a=this;this.form.bind("keydown",{context:this},function(b){if(b.keyCode===13||b.charCode===13)$(b.target).is("textarea")||b.preventDefault()});this.form.bind("keyup",{context:this},function(b){a.getActivePage();if(b.keyCode===13||b.charCode===13){var c=$(b.target);if(!c.is("textarea"))if(c.is("button")){b.preventDefault(); c.trigger("click").blur()}else if(c.is(".jFormComponentEnterSubmits")){b.preventDefault();c.blur();a.controlNextButton.trigger("click")}else if(c.is("input:checkbox")){b.preventDefault();c.trigger("click")}else if(c.is("input:password")){b.preventDefault();c.blur();a.options.splashPage!==null&&a.currentJFormPage.id==a.options.splashPage.jFormPage.id?a.options.splashPage.controlSplashButton.trigger("click"):a.controlNextButton.trigger("click")}}})},addSubmitListener:function(){var a=this;this.form.bind("submit", {context:this},function(b){b.preventDefault();a.submitEvent(b)})},initSaveState:function(){var a=this;if(this.options.saveState!==null){this.saveIntervalSetTimeoutId=setInterval(function(){a.saveState(a.options.saveState.showSavingAlert)},this.options.saveState.interval*1E3);this.saveStateInitialized=true}},saveState:function(a){if(this.saveRunning==true)return true;this.saveRunning=true;var b=this,c=this.durationInSeconds+this.getTimeActive(),d={};d.meta={};d.meta.totalTime=c;d.meta.currentPage= this.getActivePage().id;d.meta.maxPageIndex=this.maxJFormPageIdArrayIndexReached;d.form=this.getData();$.ajax({url:b.form.attr("action"),type:"post",data:{jFormerTask:"saveState",formData:jFormerUtility.jsonEncode(d)},dataType:"json",success:function(){a===true&&b.showAlert("Saving...");b.saveRunning=false},error:function(e,f,g){if(f!="error")g=f?f:"unknown";b.showAlert("There was an error saving your form, we'll try again : "+g,"error");b.saveRunning=false}})},getData:function(){var a=this;this.formData= {};$.each(this.jFormPages,function(b,c){a.formData[b]=c.getData()});return this.formData},setData:function(a){var b=this;this.formData=a;$.each(a,function(c,d){b.jFormPages[c]!=undefined&&b.jFormPages[c].setData(d)});return this.formData},setupPageScroller:function(a){var b={adjustHeightDuration:0,jFormWrapperContainerWidth:this.form.find(".jFormWrapperContainer").width(),jFormPageWrapperWidth:this.jFormPageWrapper.width(),activePageOuterHeight:this.getActivePage().page.outerHeight()};a=$.extend(b, a);b=this.form.find(".jFormPage");b.css("width",a.jFormWrapperContainerWidth).show();this.jFormPageScroller.css("width",a.jFormPageWrapperWidth*(b.length+1));this.jFormPageWrapper.height(a.activePageOuterHeight);this.scrollToPage(this.currentJFormPage.id,a)},setupControl:function(){var a=this;this.controlNextButton.unbind().click(function(b){b.preventDefault();b.context=a;a.submitEvent(b)}).removeAttr("disabled");this.lastEnabledPage=false;for(i=this.jFormPageIdArray.length-1;i>this.currentJFormPageIdArrayIndex;i--){if(!this.jFormPages[this.jFormPageIdArray[i]].disabledByDependency){this.lastEnabledPage= false;break}this.lastEnabledPage=true}this.controlPreviousButton.unbind().click(function(b){b.preventDefault();if(a.options.splashPage!==false&&a.currentJFormPageIdArrayIndex===0){a.currentJFormPageIdArrayIndex=null;a.jFormPageNavigator&&a.jFormPageNavigator.hide();a.options.splashPage.jFormPage.scrollTo()}else{if(a.jFormPages[a.jFormPageIdArray[a.currentJFormPageIdArrayIndex-1]].disabledByDependency)for(b=1;b<=a.currentJFormPageIdArrayIndex;b++){var c=a.currentJFormPageIdArrayIndex-b;if(c==0&&a.options.splashPage!== false&&a.jFormPages[a.jFormPageIdArray[c]].disabledByDependency){a.jFormPageNavigator&&a.jFormPageNavigator.hide();a.options.splashPage.jFormPage.scrollTo();break}else if(!a.jFormPages[a.jFormPageIdArray[c]].disabledByDependency){a.currentJFormPageIdArrayIndex=c;break}}else a.currentJFormPageIdArrayIndex-=1;a.scrollToPage(a.jFormPageIdArray[a.currentJFormPageIdArrayIndex])}});if(this.currentJFormPageIdArrayIndex===0&&this.currentJFormPageIdArrayIndex!=this.jFormPageIdArray.length-1&&this.lastEnabledPage=== false){this.controlNextButton.html("Next");this.controlNextLi.show();this.controlPreviousLi.hide();this.controlPreviousButton.attr("disabled","disabled")}else if(a.currentJFormPageIdArrayIndex==this.jFormPageIdArray.length-1||this.lastEnabledPage===true){this.controlNextButton.html(this.options.submitButtonText);this.controlNextLi.show();if(a.currentJFormPageIdArrayIndex===0){this.controlPreviousLi.hide();this.controlPreviousButton.attr("disabled","")}else if(a.currentJFormPageIdArrayIndex>0){this.controlPreviousButton.removeAttr("disabled"); this.controlPreviousLi.show()}}else{this.controlNextButton.html("Next");this.controlNextLi.show();this.controlPreviousButton.removeAttr("disabled");this.controlPreviousLi.show()}if(this.options.splashPage!==false){if(this.options.splashPage.jFormPage.active){this.options.splashPage.controlSplashLi.show();this.controlNextLi.hide();this.controlPreviousLi.hide();this.controlPreviousButton.attr("disabled","disabled")}else this.options.splashPage.controlSplashLi.hide();if(this.currentJFormPageIdArrayIndex=== 0&&this.options.saveState==false){this.controlPreviousButton.removeAttr("disabled");this.controlPreviousLi.show()}}if(this.control.find(".startOver").length==1){this.controlNextLi.hide();this.controlPreviousLi.hide();this.control.find(".startOver").one("click",function(b){b.preventDefault();a.currentJFormPageIdArrayIndex=0;a.scrollToPage(a.jFormPageIdArray[0],{onAfter:function(){$(b.target).parent().remove();a.removeJFormPage(a.id+"jFormPageFailure")}})})}},scrollToPage:function(a,b){if(this.jFormPages[a]&& this.jFormPages[a].disabledByDependency)return false;var c=this;this.controlNextButton.attr("disabled",true);this.controlPreviousButton.attr("disabled",true);if(this.jFormPages[a]&&this.jFormPages[a].options.onScrollTo.onBefore!==null){if(this.jFormPages[a].options.onScrollTo.notificationHtml!==undefined)c.control.find(".jformerScrollToNotification").length!=0?c.control.find(".jformerScrollToNotification").html(this.jFormPages[a].options.onScrollTo.notificationHtml):c.control.append('<li class="jformerScrollToNotification">'+ this.jFormPages[a].options.onScrollTo.notificationHtml+"<li>");this.jFormPages[a].options.onScrollTo.onBefore()}var d=this.getActivePage();d.durationActiveInSeconds+=d.getTimeActive();$.each(this.jFormPages,function(f,g){g.show();g.active=false});if(c.options.splashPage!==false&&a==c.options.splashPage.jFormPage.id){c.currentJFormPage=c.options.splashPage.jFormPage;c.currentJFormPage.show()}else this.currentJFormPage=this.jFormPages[a];this.currentJFormPage.active=true;b&&b.adjustHeightDuration!== undefined?c.adjustHeight({adjustHeightDuration:b.adjustHeightDuration}):c.adjustHeight();this.jFormPageWrapper.dequeue();this.scrollToTop();var e=this.initializing;this.jFormPageWrapper.scrollTo(c.currentJFormPage.page,c.options.animationOptions.pageScroll.duration,{onAfter:function(){$(c.jFormPageWrapper).queue("fx").length<=1&&c.hideInactivePages(c.getActivePage());if(c.maxJFormPageIdArrayIndexReached<c.currentJFormPageIdArrayIndex)c.maxJFormPageIdArrayIndexReached=c.currentJFormPageIdArrayIndex; c.updatePageNavigator();c.currentJFormPage.startTime=(new Date).getTime()/1E3;b&&b.onAfter&&b.onAfter();c.setupControl();c.controlNextButton.removeAttr("disabled").blur();c.controlPreviousButton.removeAttr("disabled").blur();c.currentJFormPage.validationPassed===false&&!e&&c.currentJFormPage.focusOnFirstFailedComponent();if(c.jFormPages[a]&&c.jFormPages[a].options.onScrollTo.onAfter!==null){c.jFormPages[a].options.onScrollTo.onAfter();c.jFormPages[a].options.onScrollTo.notificationHtml!==null&&c.control.find("li.jFormerScrollToNotification").remove()}}}); return this},scrollToTop:function(){this.initializing||$(window).scrollTop()>this.form.offset().top&&$(document).scrollTo(this.form,this.options.animationOptions.pageScroll.duration,{offset:{top:-10}})},getActivePage:function(){return this.currentJFormPage},getTimeActive:function(){var a=0;$.each(this.jFormPages,function(b,c){a+=c.durationActiveInSeconds});a+=this.getActivePage().getTimeActive();return a},hideInactivePages:function(){$.each(this.jFormPages,function(a,b){b.hide()})},clearValidation:function(){$.each(this.jFormPages, function(a,b){b.clearValidation()})},submitEvent:function(a){a.stopPropagation();a.preventDefault();this.control.find(".jFormerFailureNotice").remove();this.form.find(".jFormerFailure").remove();typeof this.options.onSubmitStart!="function"?eval(this.options.onSubmitStart):this.options.onSubmitStart();var b=false;if(this.options.clientSideValidation)b=this.currentJFormPageIdArrayIndex<this.jFormPageIdArray.length-1&&!this.lastEnabledPage?this.getActivePage().validate():this.validateAll();else{this.clearValidation(); b=true}if(this.options.onSubmitFinish())if(b&&this.currentJFormPageIdArrayIndex==this.jFormPageIdArray.length-1||this.lastEnabledPage===true)this.submitForm(a);else if(b&&this.currentJFormPageIdArrayIndex<this.jFormPageIdArray.length-1){if(this.jFormPages[this.jFormPageIdArray[this.currentJFormPageIdArrayIndex+1]].disabledByDependency)for(a=this.currentJFormPageIdArrayIndex+1;a<=this.jFormPageIdArray.length-1;a++){if(!this.jFormPages[this.jFormPageIdArray[this.currentJFormPageIdArrayIndex+a]].disabledByDependency){this.currentJFormPageIdArrayIndex+= a;break}}else this.currentJFormPageIdArrayIndex+=1;this.scrollToPage(this.jFormPageIdArray[this.currentJFormPageIdArrayIndex])}},validateAll:function(){var a=this,b=true,c=0;$.each(this.jFormPages,function(d,e){if(e.validate()===false){a.currentJFormPageIdArrayIndex=c;a.currentJFormPage.id!=e.id&&e.scrollTo();return b=false}c++});return b},adjustHeight:function(a){var b=this.options.animationOptions.pageScroll.adjustHeightDuration;if(this.initializing)b=0;else if(a&&a.adjustHeightDuration!==undefined)b= a.adjustHeightDuration;this.jFormPageWrapper.animate({height:this.getActivePage().page.outerHeight()},b)},submitForm:function(){var a=this.form.clone(false);a.attr("id",a.attr("id")+"-clone");a.attr("style","display: none;");a.empty();a.appendTo($(this.form).parent());var b=$('<input type="hidden" name="jFormer" />').attr("value",encodeURI(jFormerUtility.jsonEncode(this.getData()))),c=$('<input type="hidden" name="jFormerId" value="'+this.id+'" />');a.append(b);a.append(c);this.form.find("input:file").each(function(d, e){if($(e).val()!=""){var f=$(e).closest(".jFormSection").attr("id"),g=$(e).closest(".jFormPage").attr("id");if($(e).attr("id").match(/-section[0-9]+/)){var h=null,j=$(e).closest(".jFormSection"),l=j.attr("id").replace(/-section[0-9]+/,"");f=f.replace(/-section[0-9]+/,"");j.closest(".jFormPage").find("div[id*="+l+"]").each(function(n,o){if(j.attr("id")==$(o).attr("id")){h=n+1;return false}return true});e.attr("name",e.attr("name").replace(/-section[0-9]+/,"-section"+h))}if($(e).attr("id").match(/-instance[0-9]+/)){l= $(e).attr("id").replace(/-instance[0-9]+/,"");var k=null;$(e).closest(".jFormSection").find("input[id*="+l+"]").each(function(n,o){if($(o).attr("id")==$(e).attr("id")){k=n+1;return false}return true});e.attr("name",$(e).attr("name").replace(/-instance[0-9]+/,"-instance"+k))}$(e).attr("name",$(e).attr("name")+":"+g+":"+f);$(e).appendTo(a)}});a.submit();a.remove();this.options.debugMode?this.form.find("iframe:hidden").show():this.controlNextButton.text(this.options.submitProcessingButtonText).attr("disabled", "disabled")},handleFormSubmissionResponse:function(a){var b=this;if(a.status=="failure"){a.response.validationFailed&&$.each(a.response.validationFailed,function(d,e){$.each(e,function(f,g){$.isArray(g)?$.each(g,function(h,j){var l;l=h!=0?"-section"+(h+1):"";$.each(j,function(k,n){b.jFormPages[d].jFormSections[f].instanceArray[h].jFormComponents[k+l].handleServerValidationResponse(n)})}):$.each(g,function(h,j){b.jFormPages[d].jFormSections[f].jFormComponents[h].handleServerValidationResponse(j)})})}); if(a.response.failureHtml){this.control.find(".jFormerFailure").remove();this.control.after('<div class="jFormerFailure">'+a.response.failureHtml+"</div>")}this.form.find("iframe").contents().find("body script").remove();this.form.find("iframe").contents().find("body").html()!==null&&this.form.find(".jFormerFailure").append("<p>Output:</p>"+this.form.find("iframe").contents().find("body").html().trim());this.controlNextButton.text(this.options.submitButtonText);this.controlNextButton.removeAttr("disabled"); this.getActivePage().focusOnFirstFailedComponent()}else if(a.status=="success"){if(a.response.successPageHtml){clearInterval(this.saveIntervalSetTimeoutId);var c=$('<div id="'+this.id+'jFormPageSuccess" class="jFormPage jFormPageSuccess">'+a.response.successPageHtml+"</div>");c.width(this.jFormPages[this.jFormPageIdArray[0]].page.width());this.jFormPageScroller.append(c);c=new JFormPage(this,this.id+"jFormPageSuccess");this.addJFormPage(c);this.control.hide();this.jFormPageNavigator&&this.jFormPageNavigator.hide(); c.scrollTo()}else if(a.response.failurePageHtml){c=$('<div id="'+this.id+'jFormPageFailure" class="jFormPage jFormPageFailure">'+a.response.failurePageHtml+"</div>");c.width(this.jFormPages[this.jFormPageIdArray[0]].page.width());this.jFormPageScroller.append(c);c=new JFormPage(this,this.id+"jFormPageFailure");this.addJFormPage(c);this.control.append($('<li class="startOver"><button class="startOverButton">Start Over</button></li>'));c.scrollTo()}if(a.response.failureNoticeHtml){this.control.find(".jFormerFailureNotice").remove(); this.control.append('<li class="jFormerFailureNotice">'+a.response.failureNoticeHtml+"</li>");this.controlNextButton.text(this.options.submitButtonText);this.controlNextButton.removeAttr("disabled")}if(a.response.failureHtml){this.control.find(".jFormerFailure").remove();this.control.after('<div class="jFormerFailure">'+a.response.failureHtml+"</div>");this.controlNextButton.text(this.options.submitButtonText);this.controlNextButton.removeAttr("disabled")}if(a.response.successJs)eval(a.response.successJs); else a.response.failureJs&&eval(a.response.failureJs);if(a.response.redirect){this.controlNextButton.html("Redirecting...");document.location=a.response.redirect}}},showAlert:function(a,b,c,d){function e(){if(f.hideEffect=="slide")g.slideUp(f.hideDuration,function(){});else f.hideEffect=="fade"&&g.fadeOut(f.hideDuration,function(){})}if(this.options.alertsEnabled){var f=$.extend(this.options.animationOptions.alert,d),g=this.form.find(".jFormerAlertWrapper");c=this.form.find(".jFormerAlert");c.addClass(b); c.text(a);if(f.appearEffect=="slide")g.slideDown(f.appearDuration,function(){setTimeout(e(),1E3)});else f.appearAffect=="fade"&&g.fadeIn(f.appearDuration,function(){setTimeout(e(),1E3)})}},showModal:function(a,b,c,d){var e=this.form.find(".jFormerModalWrapper"),f=$.extend(this.options.animationOptions.modal,d);if(e.length==0){d=$('<div class="jFormerModalTransparency"></div>');e=$('<div style="display: none;" class="jFormerModalWrapper"><div class="jFormerModal"><div class="jFormerModalHeader">'+ a+'</div><div class="jFormerModalContent">'+b+'</div><div class="jFormerModalFooter"><button>Okay</button></div></div></div>');this.form.find(".jFormerAlertWrapper").after(d);this.form.find(".jFormerAlertWrapper").after(e);c!=""&&e.addClass(c);e.find("button").click(function(){$(".jFormerModalWrapper").hide(f.hideDuration);$(".jFormerModalTransparency").hide(f.hideDuration);$(".jFormerModalWrapper").remove();$(".jFormerModalTransparency").remove();$("body").css("overflow","auto")})}var g=e.find(".jFormerModal"); g.css({position:"absolute"});var h=$(window);$("body").css("overflow","hidden");h.resize(function(){j=h.width()/2-g.width()/2;l=h.height()/2-g.height()/2+h.scrollTop();g.css({top:l,left:j});$(".jFormerModalTransparency").width(h.width()).height(h.height())});$(".jFormerModalTransparency").click(function(k){if($(k.target).is(".jFormerModalTransparency")){e.hide(f.hideDuration);e.remove();$(".jFormerModalTransparency").hide(f.hideDuration);$(".jFormerModalTransparency").remove();$("body").css("overflow", "auto")}});e.show(f.appearDuration);var j=h.width()/2-g.width()/2,l=h.height()/2-g.height()/2+h.scrollTop();$(".jFormerModalTransparency").width(h.width()).height(h.height()*1.1).css("top",h.scrollTop());g.css({top:l,left:j})},recordAnalytics:function(){var a=this;this.options.disableAnalytics||setTimeout(function(){var b=$('<img src="'+("https:"==document.location.protocol?"https://ssl.":"http://www.")+"jformer.com/analytics/analytics.gif?pageCount="+a.jFormPageIdArray.length+"&componentCount="+ a.jFormComponentCount+"&formId="+a.id+'" style="display: none;" />');a.form.append(b);b.remove()},3E3)},updateProgressBar:function(){var a=0,b=0;$.each(this.jFormPages,function(d,e){$.each(e.jFormSections,function(f,g){$.each(g.jFormComponents,function(h,j){if(j.isRequired===true&&j.disabledByDependency===false&&g.disabledByDependency===false)if(j.type!="JFormComponentLikert"){a+=1;if(j.requiredCompleted===true)b+=1}})})});var c=parseInt(b/a*100);this.form.find(".jFormerProgressBar").animate({width:c+ "%"},500).html("<p>"+c+"%</p>")},addBlurTipListener:function(){var a=this;$(document).bind("blurTip",function(b,c,d){if(d=="hide"){a.blurredTips=$.map(a.blurredTips,function(e){return $(e).attr("id")==c.attr("id")?null:e});a.blurredTips[a.blurredTips.length-1]!=undefined&&a.blurredTips[a.blurredTips.length-1].removeClass("jFormerTipBlurred")}else if(d=="show"){a.blurredTips.length>0&&$.each(a.blurredTips,function(e,f){$(f).addClass("jFormerTipBlurred")});a.blurredTips.push(c);c.removeClass("jFormerTipBlurred")}})}}); JFormerUtility=function(){}; $.extend(JFormerUtility.prototype,{isSet:function(){var a=arguments,b=a.length,c=0;if(b==0)throw Error("Empty isSet.");for(;c!=b;)if(typeof a[c]=="undefined"||a[c]===null)return false;else c++;return true},empty:function(a){var b;if(a===""||a===0||a==="0"||a===null||a===false||a===undefined)return true;if(typeof a=="object"){for(b in a)if(typeof a[b]!=="function")return false;return true}return false},getExtraWidth:function(a){a=$(a);var b=0;b+=parseInt(a.css("padding-left"),10)+parseInt(a.css("padding-right"), 10);b+=parseInt(a.css("margin-left"),10)+parseInt(a.css("margin-right"),10);b+=parseInt(a.css("borderLeftWidth"),10)+parseInt(a.css("borderRightWidth"),10);return b},jsonEncode:function(a){var b=window.JSON;if(typeof b==="object"&&typeof b.stringify==="function")return b.stringify(a);var c=function(e){var f=/[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,g={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r", '"':'\\"',"\\":"\\\\"};f.lastIndex=0;return f.test(e)?'"'+e.replace(f,function(h){var j=g[h];return typeof j==="string"?j:"\\u"+("0000"+h.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'},d=function(e,f){var g="",h=0,j=h="";j=0;var l=g,k=[],n=f[e];if(n&&typeof n==="object"&&typeof n.toJSON==="function")n=n.toJSON(e);switch(typeof n){case "string":return c(n);case "number":return isFinite(n)?String(n):"null";case "boolean":case "null":return String(n);case "object":if(!n)return"null";g+=" "; k=[];if(Object.prototype.toString.apply(n)==="[object Array]"){j=n.length;for(h=0;h<j;h+=1)k[h]=d(h,n)||"null";return j=k.length===0?"[]":g?"[\n"+g+k.join(",\n"+g)+"\n"+l+"]":"["+k.join(",")+"]"}for(h in n)if(Object.hasOwnProperty.call(n,h))if(j=d(h,n))k.push(c(h)+(g?": ":":")+j);return j=k.length===0?"{}":g?"{\n"+g+k.join(",\n"+g)+"\n"+l+"}":"{"+k.join(",")+"}"}};return d("",{"":a})}});jFormerUtility=new JFormerUtility; (function(){var a=false,b=/xyz/.test(function(){})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(c){function d(){!a&&this.init&&this.init.apply(this,arguments)}var e=this.prototype;a=true;var f=new this;a=false;for(var g in c)f[g]=typeof c[g]=="function"&&typeof e[g]=="function"&&b.test(c[g])?function(h,j){return function(){var l=this._super;this._super=e[h];var k=j.apply(this,arguments);this._super=l;return k}}(g,c[g]):c[g];d.prototype=f;d.constructor=d;d.extend=arguments.callee; return d}})(); JFormPage=Class.extend({init:function(a,b,c){this.options=$.extend({dependencyOptions:null,onScrollTo:{onBefore:null,onAfter:null,notificationHtml:null}},c||{});if(this.options.onScrollTo.onBefore!==null){var d=$.trim(this.options.onScrollTo.onBefore);this.options.onScrollTo.onBefore=function(){eval(d)}}if(this.options.onScrollTo.onAfter!==null){var e=$.trim(this.options.onScrollTo.onAfter);this.options.onScrollTo.onAfter=function(){eval(e)}}this.jFormer=a;this.id=b;this.page=$("#"+b);this.jFormSections= {};this.formData={};this.active=false;this.validationPassed=null;this.disabledByDependency=false;this.durationActiveInSeconds=0},addSection:function(a){this.jFormSections[a.id]=a;return this},getData:function(){var a=this;if(this.disabledByDependency)this.formData=null;else{this.formData={};$.each(this.jFormSections,function(b,c){a.formData[b]=c.getData()})}return this.formData},setData:function(a){var b=this;$.each(a,function(c,d){if(b.jFormSections[c]!=undefined)b.jFormSections[c].setData(d);else a[c]= undefined});return this.formData=a},getTimeActive:function(){return(new Date).getTime()/1E3-this.startTime},validate:function(a){if(this.disabledByDependency)return null;var b=this,c=$.each;b.validationPassed=true;c(this.jFormSections,function(d,e){c(e.instanceArray,function(f,g){c(g.jFormComponents,function(h,j){j.type!="JFormComponentLikert"&&c(j.instanceArray,function(l,k){k.validate();if(k.validationPassed==false)b.validationPassed=false})})})});if(b.validationPassed)$("#navigatePage"+(b.jFormer.currentJFormPageIdArrayIndex+ 1)).removeClass("jFormPageNavigatorLinkWarning");else a||this.id===this.jFormer.currentJFormPage.id&&this.focusOnFirstFailedComponent();return b.validationPassed},clearValidation:function(){$.each(this.jFormSections,function(a,b){b.clearValidation()})},focusOnFirstFailedComponent:function(){var a=$.each,b=true;a(this.jFormSections,function(c,d){a(d.instanceArray,function(e,f){a(f.jFormComponents,function(g,h){a(h.instanceArray,function(j,l){if(!l.validationPassed||l.errorMessageArray.length>0){var k= l.component.offset().top-30,n=$(window).scrollTop();n<k&&n+$(window).height()>l.component.position().top?l.component.find(":input:first").focus():$.scrollTo(k+"px",500,{onAfter:function(){l.component.find(":input:first").focus()}});b=false}return b});return b});return b});return b})},scrollTo:function(a){this.jFormer.scrollToPage(this.id,a);return this},show:function(){this.page.hasClass("jFormPageInactive")&&this.page.removeClass("jFormPageInactive")},hide:function(){this.active||this.page.addClass("jFormPageInactive")}, disableByDependency:function(a){if(this.disabledByDependency!==a){var b=$.inArray(this.id,this.jFormer.jFormPageIdArray);if(a===true){this.page.hide();if(this.jFormer.options.pageNavigator!==false)if(this.options.dependencyOptions.display=="hide"){$("#navigatePage"+(b+1)).hide();this.jFormer.renumberPageNavigator()}else $("#navigatePage"+(b+1)).addClass("jFormPageNavigatorLinkDependencyLocked").find("span").html("&nbsp;")}else{this.checkChildrenDependencies();this.page.show();if(this.jFormer.options.pageNavigator!== false){this.options.dependencyOptions.display=="hide"?$("#navigatePage"+(b+1)).show():$("#navigatePage"+(b+1)).removeClass("jFormPageNavigatorLinkDependencyLocked");this.jFormer.renumberPageNavigator()}}this.disabledByDependency=a;this.jFormer.setupControl()}},checkDependencies:function(){this.options.dependencyOptions!==null&&this.disableByDependency(!eval(this.options.dependencyOptions.jsFunction))},checkChildrenDependencies:function(){$.each(this.jFormSections,function(a,b){b.checkDependencies()})}}); JFormSection=Class.extend({init:function(a,b,c){this.options=$.extend({dependencyOptions:null,instanceOptions:null},c||{});this.parentJFormPage=a;this.id=b;this.section=$("#"+b);this.jFormComponents={};this.formData=null;this.disabledByDependency=false;if(this.options.isInstance)this.clone=this.instanceArray=null;else{if(this.options.instanceOptions!=null){this.clone=this.section.clone();this.iterations=1}else this.clone=null;this.instanceArray=[this];this.createInstanceButton()}},createInstanceButton:function(){var a= this;if(this.options.instanceOptions!=null){var b=this.id+"-addInstance",c='<button id="'+b+'" class="jFormSectionAddInstanceButton">'+this.options.instanceOptions.addButtonText+"</button>";this.options.dependencyOptions!==null&&this.options.dependencyOptions.display=="hide"&&c.hide();this.section.after(c);this.parentJFormPage.page.find("#"+b).bind("click",function(d){d.preventDefault();a.disabledByDependency||a.addSectionInstance()})}},addSectionInstance:function(){var a=this;if(this.instanceArray.length< this.options.instanceOptions.max||this.options.instanceOptions.max===0){this.iterations++;var b=this.clone.clone(),c=this.id+"-removeInstance",d='<button id="'+c+'" class="jFormSectionRemoveInstanceButton">'+this.options.instanceOptions.removeButtonText+"</button>",e={};if(this.options.instanceOptions.animationOptions!==undefined)$.extend(e,this.parentJFormPage.jFormer.options.animationOptions.instance,this.options.instanceOptions.animationOptions);else e=this.parentJFormPage.jFormer.options.animationOptions.instance; $(b).append(d);b.find("#"+c).bind("click",function(f){var g=$(f.target);f.preventDefault();a.instanceArray=$.map(a.instanceArray,function(h){if(h.section.attr("id")==g.parent().attr("id"))h=null;return h});if(e.removeEffect=="none"||e.removeDuration===0){g.parent().remove();g.remove()}else if(e.removeEffect=="slide"){g.parent().slideUp(e.removeDuration,function(){g.parent().remove();g.remove()});a.parentJFormPage.jFormer.adjustHeight(e)}else g.parent().fadeOut(e.removeDuration,function(){g.parent().remove(); g.remove();a.parentJFormPage.jFormer.adjustHeight(e)});if(a.instanceArray.length<a.options.instanceOptions.max||a.options.instanceOptions.max===0)a.parentJFormPage.page.find("#"+a.id+"-addInstance").show();a.relabelSectionInstances(a.instanceArray,e)});b.hide();this.parentJFormPage.page.find("#"+this.id+"-addInstance").before(b);if(e.appearEffect=="none"||e.appearDuration===0)b.show();else if(e.appearEffect=="slide")b.slideDown(e.appearDuration,function(){a.parentJFormPage.jFormer.adjustHeight(e)}); else{b.fadeIn(e.appearDuration,function(){});a.parentJFormPage.jFormer.adjustHeight(e)}this.nameSectionInstance(b);this.instanceArray.push(this.createSectionInstanceObject(b,this.options));this.relabelSectionInstances(this.instanceArray,e);this.instanceArray.length>=this.options.instanceOptions.max&&this.options.instanceOptions.max!==0&&this.parentJFormPage.page.find("#"+this.id+"-addInstance").hide()}return this},removeInstance:function(){return this},nameSectionInstance:function(a){function b(e, f){var g=$(e).attr(f),h="";if(g.match(/(\-[A-Za-z0-9]+)&?/))h=g.match(/(\-[A-Za-z0-9]+)&?/)[1];d=h;d==""?$(e).attr(f,$(e).attr(f)+"-section"+c.iterations+d):$(e).attr(f,$(e).attr(f).replace(d,"-section"+c.iterations+d))}var c=this,d="";$(a).attr("id",$(a).attr("id")+"-section"+this.iterations);$(a).find("*").each(function(e,f){$(f).attr("id")&&b(f,"id");$(f).attr("for")&&b(f,"for");$(f).attr("name")&&b(f,"name")});return a},createSectionInstanceObject:function(a,b){var c=$.extend(true,{},b);c.isInstance= true;var d=this,e=new JFormSection(this.parentJFormPage,this.id+"-section"+this.iterations,c);$.each(this.jFormComponents,function(f,g){var h=$.extend(true,{},g.options);h.isInstance=false;h=new window[g.type](e,g.id+"-section"+d.iterations,g.type,h);e.addComponent(h)});return e},relabelSectionInstances:function(a,b){$.each(a,function(c,d){if(c!==0){var e=c+1,f=d.section.find(".jFormSectionTitle").children(":first");if(f.length>0)f.text().match(/(\([0-9]+\))$/)?f.text(f.text().replace(/(\([0-9]+\))$/, "("+e+")")):f.text(f.text()+" ("+e+")")}});this.parentJFormPage.jFormer.adjustHeight(b)},addComponent:function(a){this.jFormComponents[a.id]=a;return this},clearValidation:function(){$.each(this.jFormComponents,function(a,b){b.clearValidation()})},getData:function(){var a=this;if(this.disabledByDependency)this.formData=null;else if(this.instanceArray.length>1){this.formData=[];$.each(this.instanceArray,function(b,c){var d={};$.each(c.jFormComponents,function(e,f){if(f.type!="JFormComponentLikertStatement"){e= e.replace(/-section[0-9]+/,"");d[e]=f.getData()}});a.formData.push(d)})}else{this.formData={};$.each(this.jFormComponents,function(b,c){if(c.type!="JFormComponentLikertStatement")a.formData[b]=c.getData()})}return this.formData},setData:function(a){var b=this;$.isArray(a)?$.each(a,function(c,d){c!==0&&b.instanceArray[c]==undefined&&b.addSectionInstance();$.each(d,function(e,f){if(c!==0)e=e+"-section"+(c+1);b.instanceArray[c].jFormComponents[e]!=undefined&&b.instanceArray[c].jFormComponents[e].setData(f)})}): $.each(a,function(c,d){b.jFormComponents[c]!=undefined&&b.jFormComponents[c].setData(d)})},disableByDependency:function(a){var b=this,c=b.parentJFormPage.jFormer.initializing?{adjustHeightDuration:0,appearDuration:0,appearEffect:"none",hideDuration:0,hideEffect:"none"}:this.options.dependencyOptions.animationOptions!==undefined?$.extend(c,this.parentJFormPage.jFormer.options.animationOptions.dependency,this.options.dependencyOptions.animationOptions):this.parentJFormPage.jFormer.options.animationOptions.dependency, d=this.section;$.each(this.instanceArray,function(f,g){if(f!==0)d=d.add(g.section)});if(this.options.instanceOptions!==null&&(this.instanceArray.length<this.options.instanceOptions.max||this.options.instanceOptions.max===0)){var e=$(this.parentJFormSection.section.find("#"+this.id+"-addInstance"));if(b.parentJFormPage.jFormer.initializing)if(!a&&e.is(":hidden")){e.show();b.parentJFormPage.jFormer.adjustHeight({adjustHeightDuration:0})}d=d.add(e)}if(this.disabledByDependency!==a){if(a)if(this.options.dependencyOptions.display== "hide")if(c.hideEffect=="none"||c.hideDuration===0){d.hide();b.parentJFormPage.jFormer.adjustHeight(c)}else if(c.appearEffect==="fade")d.fadeOut(c.hideDuration,function(){b.parentJFormPage.jFormer.adjustHeight(c)});else c.appearEffect==="slide"&&d.slideUp(c.hideDuration,function(){b.parentJFormPage.jFormer.adjustHeight(c)});else{d.addClass("jFormSectionDependencyDisabled").find(":not(.jFormComponentDisabled) > :input").attr("disabled","disabled");this.parentJFormPage.jFormer.adjustHeight({adjustHeightDuration:0})}else{if(this.options.dependencyOptions.display== "hide")if(c.appearEffect=="none"||c.appearDuration===0){d.show();b.parentJFormPage.jFormer.adjustHeight(c)}else if(c.hideEffect==="fade"){d.fadeIn(c.appearDuration);b.parentJFormPage.jFormer.adjustHeight(c)}else{if(c.hideEffect==="slide"){d.slideDown(c.appearDuration);b.parentJFormPage.jFormer.adjustHeight(c)}}else{d.removeClass("jFormSectionDependencyDisabled").find(":not(.jFormComponentDisabled) > :input").removeAttr("disabled");this.parentJFormPage.jFormer.adjustHeight({adjustHeightDuration:0})}this.checkChildrenDependencies()}this.disabledByDependency= a}},checkDependencies:function(){this.options.dependencyOptions!==null&&this.disableByDependency(!eval(this.options.dependencyOptions.jsFunction))},checkChildrenDependencies:function(){$.each(this.jFormComponents,function(a,b){b.checkDependencies()})}}); JFormComponent=Class.extend({init:function(a,b,c,d){this.options=$.extend({validationOptions:[],showErrorTipOnce:false,triggerFunction:null,componentChangedOptions:null,dependencyOptions:null,instanceOptions:null,tipTargetPosition:"rightMiddle",tipCornerPosition:"leftTop",isInstance:false},d||{});this.parentJFormSection=a;this.id=b;this.component=$("#"+b+"-wrapper");this.formData=null;this.type=c;this.errorMessageArray=[];this.tip=null;this.tipDiv=this.component.find("#"+this.id+"-tip");this.tipTarget= null;this.validationPassed=true;this.requiredCompleted=this.isRequired=this.disabledByDependency=false;this.validationFunctions={required:function(e){var f=["Required."];return e.value!=""?"success":f}};if(this.options.isInstance)this.clone=this.instanceArray=null;else{if(this.options.instanceOptions!=null){this.clone=this.component.clone();this.iterations=1}else this.clone=null;this.instanceArray=[this];this.createInstanceButton()}this.initialize();this.reformValidations();this.addHighlightListeners(); this.defineComponentChangedEventListener();this.catchComponentChangedEventListener();$.trim(this.tipDiv.html())!==""&&this.addTip();this.addTipListeners()},addHighlightListeners:function(){var a=this;this.component.find(":input:not(button):not(hidden)").each(function(b,c){$(c).bind("focus",function(){a.highlight()});$(c).bind("blur",function(){a.removeHighlight();if((a.type=="JFormComponentName"||a.type=="JFormComponentAddress"||a.type=="JFormComponentCreditCard")&&a.changed===true)a.validate()})}); if(this.component.find("input:checkbox, input:radio").length>0){this.component.mouseenter(function(){a.highlight()});this.component.mouseleave(function(){a.removeHighlight()})}return this},reformValidations:function(){var a={},b=this;$.each(this.options.validationOptions,function(c,d){if(d=="required")b.isRequired=true;if(c>=0)a[d]={component:b.component};else if(typeof d!="object"){a[c]={component:b.component};a[c][c]=d}else if(typeof d=="object"){if(d[0]!=undefined){a[c]={};a[c][c]=d}else a[c]= d;a[c].component=b.component}});this.options.validationOptions=a},defineComponentChangedEventListener:function(){var a=this;this.component.find("input:checkbox, input:radio").each(function(b,c){$(c).bind("click",function(){$(this).trigger("jFormComponent:changed",a)})});this.component.find(":input:not(button, :checkbox, :radio)").each(function(b,c){$(c).bind("change",function(){$(this).trigger("jFormComponent:changed",a)})})},catchComponentChangedEventListener:function(){var a=this;this.component.bind("jFormComponent:changed", function(){a.options.triggerFunction!==null&&eval(a.options.triggerFunction);if(a.type=="JFormComponentName"||a.type=="JFormComponentAddress"||a.type=="JFormComponentLikert"||a.type=="JFormComponentCreditCard")a.changed=true;a.parentJFormSection.parentJFormPage.jFormer.options.clientSideValidation&&a.validate();a.parentJFormSection.parentJFormPage.jFormer.options.progressBar!==false&&a.parentJFormSection.parentJFormPage.jFormer.updateProgressBar()})},highlight:function(){this.component.addClass("jFormComponentHighlight").trigger("jFormComponent:highlighted", this.component);this.component.trigger("jFormComponent:showTip",this.component)},removeHighlight:function(){var a=this;this.component.removeClass("jFormComponentHighlight").trigger("jFormComponent:highlightRemoved",this.component);setTimeout(function(){a.component.hasClass("jFormComponentHighlight")||a.component.trigger("jFormComponent:hideTip",a.component)},1)},getData:function(){var a=this;if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)this.formData=null;else if(this.instanceArray.length> 1){this.formData=[];$.each(this.instanceArray,function(b,c){var d=c.getValue();a.formData.push(d)})}else this.formData=this.getValue();return this.formData},setData:function(a){var b=this;$.isArray(a)?$.each(a,function(c,d){if(b.type=="JFormComponentMultipleChoice"&&($.isArray(d)||b.multipeChoiceType=="radio")||b.type!="JFormComponentMultipleChoice"){c!==0&&b.instanceArray[c]==undefined&&b.addInstance();b.instanceArray[c].setValue(d)}else{b.setValue(a);return false}}):this.setValue(a)},createInstanceButton:function(){var a= this;if(this.options.instanceOptions!=null){var b=$('<button id="'+this.id+'-addInstance" class="jFormComponentAddInstanceButton">'+this.options.instanceOptions.addButtonText+"</button>");this.options.dependencyOptions!==null&&b.hide();this.component.after(b);this.parentJFormSection.section.find("#"+this.id+"-addInstance").bind("click",function(c){c.preventDefault();a.disabledByDependency||a.addInstance()})}},addInstance:function(){this.options.componentChangedOptions!=null&&this.options.componentChangedOptions.instance!= undefined&&this.options.componentChangedOptions.instance==true&&this.component.trigger("jFormComponent:changed",this);var a=this;if(this.instanceArray.length<this.options.instanceOptions.max||this.options.instanceOptions.max===0){var b=this.clone.clone(),c=this.parentJFormSection.section.find("#"+this.id+"-addInstance"),d={};d=this.options.instanceOptions.animationOptions!==undefined?$.extend(d,this.parentJFormSection.parentJFormPage.jFormer.options.animationOptions.instance,this.options.instanceOptions.animationOptions): this.parentJFormSection.parentJFormPage.jFormer.options.animationOptions.instance;$(b).append('<button id="'+this.id+'-removeInstance" class="jFormComponentRemoveInstanceButton">'+this.options.instanceOptions.removeButtonText+"</button>");b.find("#"+this.id+"-removeInstance").bind("click",function(f){var g=$(f.target);f.preventDefault();a.instanceArray=$.map(a.instanceArray,function(h){if(h.component.attr("id")==g.parent().attr("id")){h.tip!=null&&h.tip.hide();h=null}return h});if(d.removeEffect== "none"||d.removeDuration===0){g.parent().remove();g.remove()}else d.removeEffect=="slide"?g.parent().slideUp(d.removeDuration,function(){g.parent().remove();g.remove();a.parentJFormSection.parentJFormPage.jFormer.adjustHeight(d)}):g.parent().fadeOut(d.removeDuration,function(){g.parent().remove();g.remove();a.parentJFormSection.parentJFormPage.jFormer.adjustHeight(d)});if(a.instanceArray.length<a.options.instanceOptions.max||a.options.instanceOptions.max===0)c.show();a.relabelInstances(a.instanceArray, d)});b.hide();c.before(b);if(d.appearEffect=="none"||d.appearDuration===0){if(!a.disabledByDependency||a.disabledByDependency&&a.options.dependencyOptions.display!="hide")b.show()}else a.disabledByDependency||(d.appearEffect=="slide"?b.slideDown(d.appearDuration,function(){a.parentJFormSection.parentJFormPage.jFormer.jFormPageWrapper.dequeue();a.parentJFormSection.parentJFormPage.jFormer.adjustHeight(d)}):b.fadeIn(d.appearDuration,function(){a.parentJFormSection.parentJFormPage.jFormer.jFormPageWrapper.dequeue(); a.parentJFormSection.parentJFormPage.jFormer.adjustHeight(d)}));this.nameInstance(b);b=this.createInstanceObject(b,this.options);this.instanceArray.push(b);this.relabelInstances(this.instanceArray,d);this.instanceArray.length==this.options.instanceOptions.max&&this.options.instanceOptions.max!==0&&c.hide();if(this.options.dependencies!=undefined){var e=a.parentJFormSection.parentJFormPage.jFormer;b.component.find(":text, textarea").bind("keyup",function(){$.each(a.options.dependencies.pages,function(f, g){e.jFormPages[g.jFormPageId].checkDependencies()});$.each(a.options.dependencies.sections,function(f,g){e.jFormPages[g.jFormPageId].jFormSections[g.jFormSectionId].checkDependencies()});$.each(a.options.dependencies.components,function(f,g){e.jFormPages[g.jFormPageId].jFormSections[g.jFormSectionId].jFormComponents[g.jFormComponentId].checkDependencies()})});b.component.bind("jFormComponent:changed",function(){$.each(a.options.dependencies.pages,function(f,g){e.jFormPages[g.jFormPageId].checkDependencies()}); $.each(a.options.dependencies.sections,function(f,g){e.jFormPages[g.jFormPageId].jFormSections[g.jFormSectionId].checkDependencies()});$.each(a.options.dependencies.components,function(f,g){e.jFormPages[g.jFormPageId].jFormSections[g.jFormSectionId].jFormComponents[g.jFormComponentId].checkDependencies()})})}this.disabledByDependency&&this.disableByDependency(true)}return this},nameInstance:function(a){function b(e,f){var g=$(e).attr(f),h="";if(g.match(/\-(div|label|tip|removeInstance)\b/))h=g.match(/\-(div|label|tip|removeInstance)\b/)[0]; d=h;d==""?$(e).attr(f,$(e).attr(f)+"-instance"+c.iterations+d):$(e).attr(f,$(e).attr(f).replace(d,"-instance"+c.iterations+d))}a=$(a);var c=this,d="";this.iterations++;a.attr("id",a.attr("id").replace("-wrapper","-instance"+this.iterations+"-wrapper"));a.find("*").each(function(e,f){$(f).attr("id")&&b(f,"id");$(f).attr("for")&&b(f,"for");$(f).attr("name")&&b(f,"name")});return a},createInstanceObject:function(a,b){var c=$.extend(true,{},b);c.isInstance=true;if(this.options.componentChangedOptions!= null&&this.options.componentChangedOptions.children!=undefined&&this.options.componentChangedOptions.children==false)c.componentChangedOptions=null;return new window[this.type](this.parentJFormSection,this.id+"-instance"+this.iterations,this.type,c)},relabelInstances:function(a,b){$.each(a,function(c,d){if(c!==0){var e=c+1,f=d.component.find("#"+d.component.attr("id").replace("-wrapper","-label"));if(f.length>0){var g=f.find("span.jFormComponentLabelRequiredStar");g.length>0&&g.remove();if(f.html().match(/:$/))f.html(f.html().replace(/(\([0-9]+\))?:/, " ("+e+"):"));else f.text().match(/(\([0-9]+\))$/)?f.text(f.text().replace(/(\([0-9]+\))$/,"("+e+")")):f.text(f.text()+" ("+e+")")}else{f=d.component.find("label");g=f.find("span.jFormComponentLabelRequiredStar");g.length>0&&g.remove();f.text().match(/(\([0-9]+\))$/)?f.text(f.text().replace(/(\([0-9]+\))$/,"("+e+")")):f.text(f.text()+" ("+e+")")}f.append(g)}});this.parentJFormSection.parentJFormPage.jFormer.adjustHeight(b)},addTip:function(){var a=this;if(typeof this.tip!=="function")this.tip=this.tipTarget.simpletip({persistent:true, focus:true,position:"topRight",content:a.tipDiv,baseClass:"jFormerTip",hideEffect:"none",onBeforeShow:function(){if(a.tipDiv.find(".tipContent").text()=="")return false},onShow:function(){var b=$(window).height(),c=this.getTooltip().offset().top+this.getTooltip().outerHeight()+12;$(window).scrollTop()+b<c&&$.scrollTo(c-b+"px",250,{axis:"y"})}}).simpletip()},addTipListeners:function(){var a=this;this.component.bind("jFormComponent:showTip",function(){a.tip&&typeof a.tip=="object"&&$.trim(a.tipDiv.html())!== ""&&a.tip.show()});this.component.bind("jFormComponent:hideTip",function(){a.tip&&typeof a.tip=="object"&&a.tip.hide();a.options.showErrorTipOnce&&a.clearValidation()});return this},clearValidation:function(){this.errorMessageArray=[];this.validationPassed=true;this.component.removeClass("jFormComponentValidationFailed");this.component.addClass("jFormComponentValidationPassed");this.component.find(".tipErrorUl").remove();if(this.tip&&typeof this.tip=="object"){this.tip.update(this.tipDiv.html()); $.trim(this.tipDiv.find(".tipContent").html())==""&&this.tipDiv.hide()}},initialize:function(){},getValue:function(){},setValue:function(){},clearData:function(){this.component.find(":input").val("")},validate:function(a){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;if(this.options.validationOptions.length<1)return true;if(a)var b=true;var c=this;this.clearValidation();var d=this.getValue();if(d===null)return true;$.each(this.options.validationOptions,function(e, f){f.value=d;var g=c.validationFunctions[e](f);if(g=="success"){if(e.match("required"))c.requiredCompleted=true;return true}else{if(e.match("required")){c.requiredCompleted=false;if(c.parentJFormSection.parentJFormPage.jFormer.options.pageNavigator!=false){var h=$.inArray(c.parentJFormSection.parentJFormPage.id,c.parentJFormSection.parentJFormPage.jFormer.jFormPageIdArray);$("#navigatePage"+(h+1)).addClass("jFormPageNavigatorLinkWarning")}}if(a)b=false;else $.merge(c.errorMessageArray,g)}});if(a)return b; else{if(this.errorMessageArray.length>0){this.handleErrors();this.validationPassed=false}return this.validationPassed}},handleServerValidationResponse:function(a){$.each(this.instanceArray,function(b,c){c.clearValidation()});if(a!=null&&a.length>0)if(this.instanceArray.length!=1)$.each(this.instanceArray,function(b,c){if(!jFormerUtility.empty(a[b])){$.each(a[b],function(d,e){e!=""&&c.errorMessageArray.push(e)});if(c.errorMessageArray.length>0){c.validationPassed=false;c.handleErrors()}}});else{this.errorMessageArray= a;this.validationPassed=false;this.handleErrors()}},handleErrors:function(){this.component.removeClass("jFormComponentValidationPassed");this.component.addClass("jFormComponentValidationFailed");this.tipDiv.length==0&&this.createTipDiv();if(this.parentJFormSection.parentJFormPage.jFormer.options.validationTips){var a=$('<ul id="'+this.id+'-tipErrorUl" class="tipErrorUl"></ul>');$.each(this.errorMessageArray,function(b,c){a.append("<li>"+c+"</li>")});this.tipDiv.find(".tipContent").append(a);this.tip.update(this.tipDiv.html()); this.component.hasClass("jFormComponentHighlight")&&this.tip.show()}},createTipDiv:function(){this.tipDiv=$('<div id="'+this.id+'-tip" style="display: none;"></div>');this.component.append(this.tipDiv);this.addTip()},disableByDependency:function(a){var b=this,c={};this.options.componentChangedOptions!=null&&this.options.componentChangedOptions.dependency!=undefined&&this.options.componentChangedOptions.dependency==true&&this.component.trigger("jFormComponent:changed",this);var d=this.component;$.each(this.instanceArray, function(f,g){if(f!==0)d=d.add(g.component)});if(this.options.instanceOptions!==null&&(this.instanceArray.length<this.options.instanceOptions.max||this.options.instanceOptions.max===0)){var e=$(this.parentJFormSection.section.find("#"+this.id+"-addInstance"));if(b.parentJFormSection.parentJFormPage.jFormer.initializing)if(!a&&e.is(":hidden")){e.show();b.parentJFormSection.parentJFormPage.jFormer.adjustHeight({adjustHeightDuration:0})}else if(this.options.dependencyOptions.display=="lock"){e.show(); b.parentJFormSection.parentJFormPage.jFormer.adjustHeight({adjustHeightDuration:0})}d=d.add(e)}c=b.parentJFormSection.parentJFormPage.jFormer.initializing?{adjustHeightDelay:0,appearDuration:0,appearEffect:"none",hideDuration:0,hideEffect:"none"}:this.options.dependencyOptions.animationOptions!==undefined?$.extend(c,this.parentJFormSection.parentJFormPage.jFormer.options.animationOptions.dependency,this.options.dependencyOptions.animationOptions):this.parentJFormSection.parentJFormPage.jFormer.options.animationOptions.dependency; if(this.disabledByDependency!==a){if(a){this.clearValidation();if(this.options.dependencyOptions.display=="hide")if(c.hideEffect=="none"||c.hideDuration===0){d.hide(c.hideDuration);b.parentJFormSection.parentJFormPage.jFormer.adjustHeight(c)}else if(c.hideEffect==="fade")d.fadeOut(c.hideDuration,function(){b.parentJFormSection.parentJFormPage.jFormer.adjustHeight(c)});else c.hideEffect==="fade"&&d.slideUp(c.hideDuration,function(){b.parentJFormSection.parentJFormPage.jFormer.adjustHeight(c)});else d.addClass("jFormComponentDependencyDisabled").find(":input").attr("disabled", "disabled")}else if(this.options.dependencyOptions.display=="hide")if(c.appearEffect=="none"||c.apearDuration===0){d.show();b.parentJFormSection.parentJFormPage.jFormer.adjustHeight(c)}else if(c.appearEffect==="fade"){d.fadeIn(c.appearDuration);b.parentJFormSection.parentJFormPage.jFormer.adjustHeight(c)}else{if(c.appearEffect==="slide"){d.slideDown(c.appearDuration);b.parentJFormSection.parentJFormPage.jFormer.adjustHeight(c)}}else d.removeClass("jFormComponentDependencyDisabled").find(":input").removeAttr("disabled"); this.disabledByDependency=a}},checkDependencies:function(){this.options.dependencyOptions!==null&&this.disableByDependency(!eval(this.options.dependencyOptions.jsFunction))}}); JFormComponentAddress=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.tipTarget=this.component;this.options.emptyValue&&this.addEmptyValues();this.validationFunctions={required:function(a){var b=[];a.value.addressLine1==""&&b.push(["Street Address is required."]);a.value.city==""&&b.push(["City is required."]);a.value.state==""&&b.push(["State is required."]);a.value.zip==""&&b.push(["Zip is required."]);a.value.country==""&&b.push(["Country is required."]); return b.length<1?"success":b}};this.changed=false},setValue:function(a){if(a===null||a==="")a={addressline1:"",city:"",state:"",zip:""};if(this.options.emptyValue){a.addressLine1!=this.options.emptyValue.addressLine1&&this.component.find(":input[id*=addressLine1]").removeClass("defaultValue").val(a.addressLine1).blur();a.addressLine2!=this.options.emptyValue.addressLine2&&this.component.find(":input[id*=addressLine2]").removeClass("defaultValue").val(a.addressLine2).blur();a.city!=this.options.emptyValue.city&& this.component.find(":input[id*=city]").removeClass("defaultValue").val(a.city).blur();if(a.state!=this.options.emptyValue.state||this.options.emptyValue.state==undefined)this.component.find(":input[id*=state]").removeClass("defaultValue").val(a.state).blur();a.zip!=this.options.emptyValue.zip&&this.component.find(":input[id*=zip]").removeClass("defaultValue").val(a.zip).blur()}else{this.component.find(":input[id*=addressLine1]").val(a.addressLine1);this.component.find(":input[id*=addressLine2]").val(a.addressLine2); this.component.find(":input[id*=city]").val(a.city);this.component.find(":input[id*=state]").val(a.state);this.component.find(":input[id*=zip]").val(a.zip)}this.component.find(":input[id*=country]").val(a.country);this.validate(true)},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;var a={},b=this;a.addressLine1=b.component.find(":input[id*=addressLine1]").val();a.addressLine2=b.component.find(":input[id*=addressLine2]").val();a.city=b.component.find(":input[id*=city]").val(); a.state=b.component.find(":input[id*=state]").val();a.zip=b.component.find(":input[id*=zip]").val();a.country=b.component.find(":input[id*=country]").val();this.component.find(":input").each(function(c,d){a[$(d).attr("id").replace(b.id+"-","")]=$(d).val()});if(this.options.emptyValue){if(a.addressLine1==this.options.emptyValue.addressLine1)a.addressLine1="";if(a.addressLine2==this.options.emptyValue.addressLine2)a.addressLine2="";if(a.city==this.options.emptyValue.city)a.city="";if(a.state==this.options.emptyValue.state)a.state= "";if(a.zip==this.options.emptyValue.zip)a.zip=""}return a},validate:function(){if(this.parentJFormSection.parentJFormPage.jFormer.options.clientSideValidation){var a=this;this.changed||this._super();setTimeout(function(){if(!a.component.hasClass("jFormComponentHighlight")){if(a.options.validationOptions.length<1)return true;a.clearValidation();$.each(a.options.validationOptions,function(b,c){c.value=a.getValue();var d=a.validationFunctions[b](c);if(d!="success"){$.merge(a.errorMessageArray,d);a.validationPassed= false}});a.errorMessageArray.length>0&&a.handleErrors();a.changed=false;return a.validationPassed}},1)}},addEmptyValues:function(){var a=this;$.each(this.options.emptyValue,function(b,c){var d=a.component.find("input[id*="+b+"]");d.addClass("defaultValue");d.focus(function(e){if($.trim($(e.target).val())==c){$(e.target).val("");$(e.target).removeClass("defaultValue")}});d.blur(function(e){if($.trim($(e.target).val())==""){$(e.target).addClass("defaultValue");$(e.target).val(c)}});d.trigger("blur")})}}); JFormComponentCreditCard=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.tipTarget=this.component;this.options.emptyValues&&this.addEmptyValues();this.validationFunctions={required:function(a){var b=[];a.value.cardType!=undefined&&a.value.cardType==""&&b.push(["Card type is required."]);a.value.cardNumber==""&&b.push(["Credit card number is required."]);a.value.cardNumber!=""&&a.value.cardNumber.match(/[^\d]/)&&b.push(["Card number may only contain numbers."]); if(a.value.cardNumber!=""&&(a.value.cardNumber.length<13||a.value.cardNumber.length>16))b.push(["Card number must contain 13 to 16 digits."]);a.value.expirationMonth==""&&b.push(["Expiration month is required."]);a.value.expirationYear==""&&b.push(["Expiration year is required."]);a.value.securityCode!=undefined&&a.value.securityCode==""&&b.push(["Security code is required."]);a.value.securityCode!=undefined&&a.value.securityCode!=""&&a.value.securityCode.match(/[^\d]/)&&b.push(["Security code may only contain numbers."]); a.value.securityCode!=undefined&&a.value.securityCode!=""&&a.value.securityCode.length<3&&b.push(["Security code must contain 3 or 4 digits."]);return b.length<1?"success":b}};this.changed=false},setValue:function(a){if(this.options.emptyValues){a.cardType!=undefined&&this.component.find(":input[id*=cardType]").removeClass("defaultValue").val(a.cardType).blur();a.cardNumber!=this.options.emptyValues.cardNumber&&this.component.find(":input[id*=cardNumber]").removeClass("defaultValue").val(a.cardNumber).blur(); this.component.find(":input[id*=expirationMonth]").removeClass("defaultValue").val(a.expirationMonth).blur();this.component.find(":input[id*=expirationYear]").removeClass("defaultValue").val(a.expirationYear).blur();a.securityCode!=undefined&&a.securityCode!=this.options.emptyValues.securityCode&&this.component.find(":input[id*=expirationMonth]").removeClass("defaultValue").val(a.expirationMonth).blur()}else{a.cardType!=undefined&&this.component.find(":input[id*=cardType]").val(a.cardType);this.component.find(":input[id*=cardNumber]").val(a.cardNumber); this.component.find(":input[id*=expirationMonth]").val(a.expirationMonth);this.component.find(":input[id*=expirationYear]").val(a.expirationYear);a.securityCode!=undefined&&this.component.find(":input[id*=securityCode]").val(a.securityCode)}this.validate(true)},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;var a={};if(this.component.find(":input[id*=cardType]").length!=0)a.cardType=this.component.find(":input[id*=cardType]").val();a.cardNumber= this.component.find(":input[id*=cardNumber]").val();a.expirationMonth=this.component.find(":input[id*=expirationMonth]").val();a.expirationYear=this.component.find(":input[id*=expirationYear]").val();if(this.component.find(":input[id*=securityCode]").length!=0)a.securityCode=this.component.find(":input[id*=securityCode]").val();if(this.options.emptyValues){if(a.cardNumber==this.options.emptyValues.cardNumber)a.cardNumber="";if(a.securityCode!=undefined&&a.securityCode==this.options.emptyValues.securityCode)a.securityCode= ""}return a},validate:function(){if(this.parentJFormSection.parentJFormPage.jFormer.options.clientSideValidation){var a=this;this.changed||this._super();setTimeout(function(){if(!a.component.hasClass("jFormComponentHighlight")){if(a.options.validationOptions.length<1)return true;a.clearValidation();$.each(a.options.validationOptions,function(b,c){c.value=a.getValue();var d=a.validationFunctions[b](c);if(d!="success"){$.merge(a.errorMessageArray,d);a.validationPassed=false}});a.errorMessageArray.length> 0&&a.handleErrors();a.changed=false;return a.validationPassed}},1)}},addEmptyValues:function(){var a=this;$.each(this.options.emptyValues,function(b,c){var d=a.component.find("input[id*="+b+"]");d.addClass("defaultValue");d.focus(function(e){if($.trim($(e.target).val())==c){$(e.target).val("");$(e.target).removeClass("defaultValue")}});d.blur(function(e){if($.trim($(e.target).val())==""){$(e.target).addClass("defaultValue");$(e.target).val(c)}});d.trigger("blur")})}}); JFormComponentDate=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){var a=this;this.monthArray=["January","February","March","April","May","June","July","August","September","October","November","December"];this.addCalendar();this.tipTarget=this.component.find(".jFormComponentDateSelector");if(this.tipTarget==undefined)this.tipTarget=this.component;this.options.validationOptions.length==0&&this.reformValidations();this.validationFunctions={required:function(b){var c= [];if(b.value.month==""||b.value.day==""||b.value.year==""||b.value==null){c.push("Required.");return c}var d=parseInt(b.value.month),e=parseInt(b.value.day);b=b.value.year;var f=false;b.match(/[\d]{4}/)||c.push("You must enter a valid year.");if(d<1||d>12)c.push("You must enter a valid month.");if(d==4||d==6||d==9||d==11){if(e>30)f=true}else if(d==2){b=parseInt(b);if(e>(b%4==0&&(b%100!=0||b%400==0)?29:28))f=true}if(e>31||e<1)f=true;f&&c.push("You must enter a valid day.");return c.length<1?"success": c},minDate:function(b){var c=[],d=a.getDateFromString(b.minDate);a.getDateFromObject(b.value)<d&&c.push("Date must be on or after "+a.monthArray[d.getMonth()]+" "+d.getDate()+", "+d.getFullYear()+".");return c.length<1?"success":c},maxDate:function(b){var c=[],d=a.getDateFromString(b.maxDate);a.getDateFromObject(b.value)>d&&c.push("Date must be on or before "+a.monthArray[d.getMonth()]+" "+d.getDate()+", "+d.getFullYear()+".");return c.length<1?"success":c},teenager:function(b){var c=new Date(b.value.year, b.value.month,b.value.day),d=new Date;c=new Date(d.getFullYear()-13,d.getMonth(),d.getDate())-c;return b.value==""||c>=0?"success":"You must be at least 13 years old to use this site."}}},highlight:function(){var a=this;this.component.addClass("jFormComponentHighlight").trigger("jFormComponent:highlighted",this.component);setTimeout(function(){a.component.trigger("jFormComponent:showTip",a.component)},1)},addCalendar:function(){var a=this.component.find("input:text");a.date_input();a.bind("keyup", function(b){b.keyCode==9||b.keyCode==27||b.keyCode==13||b.keyCode==33||b.keyCode==34||b.keyCode==38||b.keyCode==40||b.keyCode==37||b.keyCode==39||a.val().length==10&&a.trigger("change")})},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;var a={month:"",day:"",year:""},b=$("#"+this.id).val();if(b!=""){b=b.split(b.match(/[^\d]/));if(b[0]!=undefined)a.month=b[0];if(b[1]!=undefined)a.day=b[1];if(b[2]!=undefined)a.year=b[2]}return a},getDateFromString:function(a){a= a.split("-");return new Date(parseInt(a[0],10),parseInt(a[1],10)-1,parseInt(a[2],10))},getDateFromObject:function(a){return new Date(parseInt(a.year,10),parseInt(a.month,10)-1,parseInt(a.day,10))},setValue:function(a){function b(c){if(c==""||c=="undefined")return"";c=""+c;if(c.length==1)c="0"+c;return c}if(a==null||a.month=="undefined"||a.year=="undefined"||a.day=="undefined")$("#"+this.id).val("");else{$("#"+this.id).val(b(a.month)+"/"+b(a.day)+"/"+a.year);$("#"+this.id).val()=="//"&&$("#"+this.id).val(""); this.validate(true)}}});JFormComponentDropDown=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.tipTarget=this.component.find("select:last")},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;return $("#"+this.id).val()},setValue:function(a){$("#"+this.id).val(a).trigger("jFormComponent:changed");this.validate(true)}}); JFormComponentFile=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){var a=this.component.find("button").parent();if(a.length<1)a=this.component.find("input:file");this.tipTarget=a;this.options.customStyle&&this.setOnChange();this.validationFunctions={required:function(b){var c=["Required."];return b.value!=""?"success":c},extension:function(b){var c=["Must have the ."+b.extension+" extension."],d=RegExp("\\."+b.extension+"$","i");return b.value==""||b.value.match(d)? "success":c},extensionType:function(b){var c,d=["Incorrect file type."];if($.isArray(b.extensionType))c=RegExp("\\.("+b.extensionType.join("|")+")$","i");else{c={};c.image=/\.(bmp|gif|jpe?g|png|psd|psp|thm|tif)/i;c.document=/\.(doc|docx|log|msg|pages|rtf|txt|wpd|wps)/i;c.audio=/\.(aac|aif|iff|m3u|mid|midi|mp3|mpa|ra|wav|wma)/i;c.video=/\.(3g2|3gp|asf|asx|avi|flv|mov|mp4|mpg|rm|swf|vob|wmv)/i;c.web=/\.(asp|css|htm|html|js|jsp|php|rss|xhtml)/i;c=RegExp(c[b.extensionType]);d=["Must be an "+b.extensionType+ " file type."]}return b.value==""||b.value.match(c)?"success":d},size:function(){return true},imageDimensions:function(){return true},minImageDimensions:function(){return true}}},setOnChange:function(){var a=this;this.component.find("input:file").change(function(b){b=b.target.value.replace(/.+\\/,"");a.component.find("input:text").val(b)})},setValue:function(){return false},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;return this.component.find("input:file").val()}, validate:function(){this._super()}});JFormComponentHidden=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;return $("#"+this.id).val()},validate:function(){this._super()}}); JFormComponentLikert=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){var a=this;this.changed=false;this.tipTarget=this.component;this.statementComponentArray={};$.each(this.options.statementArray,function(b,c){if(!jFormerUtility.empty(a.options.validationOptions))c.validationOptions=a.options.validationOptions;var d=new JFormComponentLikertStatement(a.parentJFormSection,b,"JFormComponentLikertStatement",c);d.id=a.id+"-"+d.id;a.parentJFormSection.addComponent(d); a.statementComponentArray[b]=d})},clearValidation:function(){$.each(this.statementComponentArray,function(a,b){b.clearValidation()})},setValue:function(){},catchComponentChangedEventListener:function(){return null},addHighlightListeners:function(){return null},defineComponentChangedEventListener:function(){return null},addTipListeners:function(){return null},getValue:function(){var a={};$.each(this.statementComponentArray,function(b,c){a[b]=c.getValue()});return a},handleErrors:function(){return true}, handleServerValidationResponse:function(a){var b=this;a.length>0&&$.each(this.instanceArray,function(c,d){$.each(a,function(e,f){$.each(f,function(g,h){var j=b.parentJFormSection.jFormComponents[d.id+"-"+g];if(j!=undefined){j.errorMessageArray=[h];j.validationPassed=false;j.handleErrors()}})})})},validate:function(){return true}}); JFormComponentLikertStatement=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.changed=false;this.tipTarget=this.component=$("input[name="+this.id+"]:first").closest("tr");this.tipDiv=this.component.find("div.jFormComponentLikertStatementTip");this.validationFunctions={required:function(a){var b=["Required."];return a.value.length>0?"success":b}}},setValue:function(a){this.component.find("input").val([a]);this.validate(true)},validate:function(){this._super()}, getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;var a=this.component.find("input:checked");return a=a.length>0?a.val():""}}); JFormComponentMultipleChoice=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.tipTarget=this.component;this.addChoiceTips();this.validationFunctions={required:function(a){var b=["Required."];return a.value.length>0?"success":b},minOptions:function(a){var b=["You must select more than "+a.minOptions+" options"];return a.value.length==0||a.value.length>a.minOptions?"success":b},maxOptions:function(a){var b=["You may select up to "+a.maxOptions+" options. You have selected "+ a.value.length+"."];return a.value.length==0||a.value.length<=a.maxOptions?"success":b}}},addChoiceTips:function(){var a=this.component.find("div.jFormComponentMultipleChoiceTip");a.length>0&&a.each(function(b,c){var d=$(c).prev("label").find(".jFormComponentMultipleChoiceTipIcon");if(d.length==0)d=$(c).parent();d.simpletip({position:"topRight",content:$(c),baseClass:"jFormerTip jFormComponentMultipleChoiceTip",hideEffect:"none"})})},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null; var a;if(this.options.multipleChoiceType=="checkbox"){a=[];this.component.find("input:checked").each(function(b,c){a.push($(c).val())})}else a=this.component.find("input:checked").length>0?this.component.find("input:checked").val():"";return a},setValue:function(a){var b=this;if(this.options.multipleChoiceType=="checkbox")$.each(a,function(c,d){b.component.find("input[value='"+d+"']").attr("checked","checked").trigger("jFormComponent:changed")});else{this.component.find("input[value='"+a+"']").attr("checked", "checked").trigger("jFormComponent:changed");a==null&&this.component.find("input").attr("checked",false).trigger("jFormComponent:changed")}this.validate(true)}}); JFormComponentName=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.tipTarget=this.component.find("input:last");this.options.emptyValue&&this.addEmptyValues();this.changed=false;this.validationFunctions={required:function(a){var b=[];a.value.firstName==""&&b.push(["First name is required."]);a.value.lastName==""&&b.push(["Last name is required."]);return b.length<1?"success":b}}},setValue:function(a){if(this.options.emptyValue){a.firstName!=this.options.emptyValue.firstName&& this.component.find("input[id*=firstName]").removeClass("defaultValue").val(a.firstName).blur();this.component.find("input[id*=middleInitial]").removeClass("defaultValue").val(a.middleInitial).blur();a.lastName!=this.options.emptyValue.lastName&&this.component.find("input[id*=lastName]").removeClass("defaultValue").val(a.lastName).blur()}else{this.component.find("input[id*=firstName]").val(a.firstName);this.component.find("input[id*=middleInitial]").val(a.middleInitial);this.component.find("input[id*=lastName]").val(a.lastName)}this.validate(true)}, getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;var a={};a.firstName=this.component.find("input[id*=firstName]").val();a.middleInitial=this.component.find("input[id*=middleInitial]").val();a.lastName=this.component.find("input[id*=lastName]").val();if(this.options.emptyValue){if(a.firstName==this.options.emptyValue.firstName)a.firstName="";if(this.component.find("input[id$=middleInitial]").hasClass("defaultValue"))a.middleInitial="";if(a.lastName== this.options.emptyValue.lastName)a.lastName=""}return a},validate:function(){if(this.parentJFormSection.parentJFormPage.jFormer.options.clientSideValidation){var a=this;this.changed||this._super();setTimeout(function(){if(!a.component.hasClass("jFormComponentHighlight")){if(a.options.validationOptions.length<1)return true;a.clearValidation();$.each(a.options.validationOptions,function(b,c){c.value=a.getValue();var d=a.validationFunctions[b](c);if(d!="success"){$.merge(a.errorMessageArray,d);a.validationPassed= false}});a.errorMessageArray.length>0&&a.handleErrors();a.changed=false;return a.validationPassed}},1)}},addEmptyValues:function(){var a=this;$.each(this.options.emptyValue,function(b,c){var d=a.component.find("input[id*="+b+"]");d.addClass("defaultValue");d.focus(function(e){if($.trim($(e.target).val())==c){$(e.target).val("");$(e.target).removeClass("defaultValue")}});d.blur(function(e){if($.trim($(e.target).val())==""){$(e.target).addClass("defaultValue");$(e.target).val(c)}});d.trigger("blur")})}}); JFormComponentSingleLineText=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d)},initialize:function(){this.tipTarget=this.component.find("input:last");this.enterSubmits=false;this.options.mask&&this.addMask();this.options.emptyValue&&this.addEmptyValue();this.component.find("input:password").length==1&&this.options.showStrength&&this.addPasswordStrength();this.validationFunctions={alpha:function(a){var b=["Must only contain letters."];return a.value==""||a.value.match(/^[A-Za-z]+$/i)? "success":b},alphaDecimal:function(a){var b=["Must only contain letters, numbers, or periods."];return a.value==""||a.value.match(/^[A-Za-z0-9\.]+$/i)?"success":b},alphaNumeric:function(a){var b=["Must only contain letters or numbers."];return a.value==""||a.value.match(/^[A-Za-z0-9]+$/i)?"success":b},blank:function(a){var b=["Must be blank."];return $.trim(a.value).length==0?"success":b},canadianPostal:function(a){var b=["Must be a valid Canadian postal code."];return a.value==""||a.value.match(/^[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]$/)? "success":b},date:function(a){var b=["Must be a date in the mm/dd/yyyy format."];return a.value==""||a.value.match(/^(0?[1-9]|1[012])[\- \/.](0?[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2}$/)?"success":b},dateTime:function(a){var b=["Must be a date in the mm/dd/yyyy hh:mm:ss tt format. ss and tt are optional."];return a.value==""||a.value.match(/^(0?[1-9]|1[012])[\- \/.](0?[1-9]|[12][0-9]|3[01])[\- \/.](19|20)?[0-9]{2} [0-2]?\d:[0-5]\d(:[0-5]\d)?( ?(a|p)m)?$/i)?"success":b},decimal:function(a){var b= ["Must be a number without any commas. Decimal is optional."];return a.value==""||a.value.match(/^-?((\d+(\.\d+)?)|(\.\d+))$/)?"success":b},decimalNegative:function(a){var b=["Must be a negative number without any commas. Decimal is optional."],c=this.decimal(a);return a.value==""||c=="success"&&parseFloat(a.value)<0?"success":b},decimalPositive:function(a){var b=["Must be a positive number without any commas. Decimal is optional."],c=this.decimal(a);return a.value==""||c=="success"&&parseFloat(a.value)> 0?"success":b},decimalZeroNegative:function(a){var b=["Must be zero or a negative number without any commas. Decimal is optional."],c=self.validations.decimal({value:a.value});return a.value==""||c=="success"&&parseFloat(a.value)<=0?"success":b},decimalZeroPositive:function(a){var b=["Must be zero or a positive number without any commas. Decimal is optional."],c=this.decimal(a);return a.value==""||c=="success"&&parseFloat(a.value)>=0?"success":b},email:function(a){var b=["Must be a valid e-mail address."]; return a.value==""||a.value.match(/^[A-Z0-9._%-\+]+@(?:[A-Z0-9\-]+\.)+[A-Z]{2,4}$/i)?"success":b},integer:function(a){var b=["Must be a whole number."];return a.value==""||a.value.match(/^-?\d+$/)?"success":b},integerNegative:function(a){var b=["Must be a negative whole number."],c=this.integer(a);return a.value==""||c=="success"&&parseInt(a.value,10)<0?"success":b},integerPositive:function(a){var b=["Must be a positive whole number."],c=this.integer(a);return a.value==""||c=="success"&&parseInt(a.value, 10)>0?"success":b},integerZeroNegative:function(a){var b=["Must be zero or a negative whole number."],c=this.integer(a);return a.value==""||c=="success"&&parseInt(a.value,10)<=0?"success":b},integerZeroPositive:function(a){var b=["Must be zero or a positive whole number."],c=this.integer(a);return a.value==""||c=="success"&&parseInt(a.value,10)>=0?"success":b},isbn:function(a){var b=["Must be a valid ISBN and consist of either ten or thirteen characters."];if(a.value.match(/^(?=.{13}$)\d{1,5}([\- ])\d{1,7}\1\d{1,6}\1(\d|X)$/))b= "sucess";if(a.value.match(/^\d{9}(\d|X)$/))b="sucess";if(a.value.match(/^(?=.{17}$)\d{3}([\- ])\d{1,5}\1\d{1,7}\1\d{1,6}\1(\d|X)$/))b="sucess";if(a.value.match(/^\d{3}[\- ]\d{9}(\d|X)$/))b="sucess";if(a.value.match(/^\d{12}(\d|X)$/))b="sucess";return b},length:function(a){var b=["Must be exactly "+a.length+" characters long. Current value is "+a.value.length+" characters."];return a.value==""||a.value.length==a.length?"success":b},matches:function(a){var b=["Does not match."],c=a.matches;if(a.sectionInstances){var d= a.component.attr("id").match(/-section[\d]+/);if(d)c=a.matches+d}return a.value==$("#"+c).val()?"success":b},maxLength:function(a){var b=["Must be less than "+a.maxLength+" characters long. Current value is "+a.value.length+" characters."];return a.value==""||a.value.length<=a.maxLength?"success":b},maxFloat:function(a){var b="Must be numeric and cannot have more than "+a.maxFloat+" decimal place(s).",c=RegExp("^-?((\\d+(\\.\\d{0,"+a.maxFloat+"})?)|(\\.\\d{0,"+a+"}))$");return a.value==""||a.value.match(c)? "success":b},maxValue:function(a){var b=["Must be numeric with a maximum value of "+a.maxValue+"."];return a.value<=a.maxValue?"success":b},minLength:function(a){var b=["Must be at least "+a.minLength+" characters long. Current value is "+a.value.length+" characters."];return a.value==""||a.value.length>=a.minLength?"success":b},minValue:function(a){var b=["Must be numeric with a minimum value of "+a.minValue+"."];return a.value>=a.minValue?"success":b},money:function(a){var b=["Must be a valid dollar value."]; return a.value==""||a.value.match(/^\$?[1-9][0-9]{0,2}(,?[0-9]{3})*(\.[0-9]{2})?$/)?"success":b},moneyNegative:function(a){var b=["Must be a valid negative dollar value."];return a.value==""||a.value.match(/^((-?\$)|(\$-?)|(-))?((\d+(\.\d{2})?)|(\.\d{2}))$/)&&RegExp.$5<0?"success":b},moneyPositive:function(a){var b=["Must be a valid positive dollar value."];return a.value==""||a.value.match(/^((-?\$)|(\$-?)|(-))?((\d+(\.\d{2})?)|(\.\d{2}))$/)&&RegExp.$5>0?"success":b},moneyZeroNegative:function(a){var b= ["Must be zero or a valid negative dollar value."];return a.value==""||a.value.match(/^((-?\$)|(\$-?)|(-))?((\d+(\.\d{2})?)|(\.\d{2}))$/)&&RegExp.$5<=0?"success":b},moneyZeroPositive:function(a){var b=["Must be zero or a valid positive dollar value."];return a.value==""||a.value.match(/^((-?\$)|(\$-?)|(-))?((\d+(\.\d{2})?)|(\.\d{2}))$/)&&RegExp.$5>=0?"success":b},password:function(a){var b=["Must be between 4 and 32 characters."];return a.value==""||a.value.match(/^.{4,32}$/)?"success":b},phone:function(a){var b= ["Must be a 10 digit phone number."];return a.value==""||a.value.match(/^(1[\-. ]?)?\(?[0-9]{3}\)?[\-. ]?[0-9]{3}[\-. ]?[0-9]{4}$/)?"success":b},postalZip:function(a){var b=["Must be a valid United States zip code, Canadian postal code, or United Kingdom postal code."];return a.value==""||this.zip(a)=="success"||this.canadianPostal(a)=="success"||this.ukPostal()=="success"?"success":b},required:function(a){var b=["Required."];return a.value!=""?"success":b},serverSide:function(a){if(a.value=="")return"success"; var b=[];a.component.addClass("jFormComponentServerSideCheck");$.ajax({url:a.url,type:"post",data:{task:a.task,value:a.value},dataType:"json",cache:false,async:false,success:function(c){if(c.status!="success")b=c.response;a.component.removeClass("jFormComponentServerSideCheck")},error:function(c,d,e){if(d!="error")e=d?d:"Unknown error";b=["There was an error during server side validation: "+e];a.component.removeClass("jFormComponentServerSideCheck")}});return b.length<1?"success":b},ssn:function(a){var b= ["Must be a valid United States social security number."];return a.value==""||a.value.match(/^\d{3}-?\d{2}-?\d{4}$/i)?"success":b},teenager:function(a){var b=new Date(a.value),c=new Date;b=new Date(c.getFullYear()-13,c.getMonth(),c.getDate())-b;return a.value==""||b>=0?"success":"Must be at least 13 years old."},time:function(a){var b=["Must be a time in the hh:mm:ss tt format. ss and tt are optional."];return a.value==""||a.value.match(/^[0-2]?\d:[0-5]\d(:[0-5]\d)?( ?(a|p)m)?$/i)?"success":b},ukPostal:function(a){var b= ["Must be a valid United Kingdom postal code."];return a.value==""||a.value.match(/^[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}$/)?"success":b},url:function(a){var b=["Must be a valid Internet address."];return a.value==""||a.value.match(/^((ht|f)tp(s)?:\/\/|www\.)?([\-A-Z0-9.]+)(\.[a-zA-Z]{2,4})(\/[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?(\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?$/i)?"success":b},username:function(a){var b=["Must use 4 to 32 characters and start with a letter."];return a.value==""||a.value.match(/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/)? "success":b},zip:function(a){var b=["Must be a valid United States zip code."];return a.value==""||a.value.match(/^[0-9]{5}(?:-[0-9]{4})?$/)?"success":b}}},addMask:function(){this.component.find("input").mask("?"+this.options.mask,{placeholder:" "})},addPasswordStrength:function(){var a=this,b=this.component,c="<p id='"+this.id+"-strength' > Strength: <b> "+this.getPasswordStrength().strength+" </b> </p>";b.find("div.jFormComponentTip").append(c);b.find("input:password").bind("keyup",function(){b.find("#"+ a.id+"-strength b").text(a.getPasswordStrength().strength);a.tip.update(b.find("div.jFormComponentTip").html())})},getPasswordStrength:function(){var a=this.getValue(),b=0,c="None";if(a.length>=6)b+=1;if(a.length>=10)b+=1;if(a.match(/[a-z]/))b+=1;if(a.match(/[A-Z]/))b+=1;if(a.match(/\d+/))b+=1;if(a.match(/(\d.*\d)/))b+=1;if(a.match(/[!,@#$%\^&*?_~]/))b+=1;if(a.match(/([!,@#$%\^&*?_~].*[!,@#$%\^&*?_~])/))b+=1;if(a.match(/[a-z]/)&&a.match(/[A-Z]/))b+=1;if(a.match(/\d/)&&a.match(/\D/))b+=1;if(a.match(/[a-z]/)&& a.match(/[A-Z]/)&&a.match(/\d/)&&a.match(/[!,@#$%\^&*?_~]/))b+=1;if(b===0)c="None";else if(b<=1)c="Very Weak";else if(b<=3)c="Weak";else if(b<=5)c="Good";else if(b<=7)c="Strong";else if(b>7)c="Very Strong";return{score:b,strength:c}},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null;var a=$("#"+this.id).val();return this.options.emptyValue?a==this.options.emptyValue?"":a:a},setValue:function(a){$("#"+this.id).val(a).removeClass("defaultValue"); this.validate(true)},addEmptyValue:function(){var a=this.options.emptyValue,b=this.component.find("input");b.addClass("defaultValue");b.val(a);var c="";b.focus(function(d){c=$(d.target);if($.trim(c.val())==a){c.val("");c.removeClass("defaultValue")}});b.blur(function(d){c=$(d.target);if($.trim(c.val())==""){c.addClass("defaultValue");c.val(a)}})}}); JFormComponentTextArea=JFormComponent.extend({init:function(a,b,c,d){this._super(a,b,c,d);this.options.allowTabbing&&this.allowTabbing();this.options.emptyValue&&this.addEmptyValue();this.options.autoGrow&&this.addAutoGrow()},initialize:function(){this.tipTarget=this.component.find("textarea");this.options.emptyValue&&this.addEmptyValue()},allowTabbing:function(){this.component.find("textarea").bind("keydown",function(a){if(a!=null)if(a.keyCode==9){if(this.setSelectionRange){var b=this.selectionStart, c=this.selectionEnd;this.value=this.value.substring(0,b)+"\t"+this.value.substr(c);this.setSelectionRange(b+1,b+1);this.focus()}else if(this.createTextRange){document.selection.createRange().text="\t";a.returnValue=false}a.preventDefault&&a.preventDefault();return false}})},addEmptyValue:function(){var a=this.options.emptyValue,b=this.component.find("textarea");b.addClass("defaultValue");b.val(a);var c="";b.focus(function(d){c=$(d.target);if($.trim(c.val())==a){c.val("");c.removeClass("defaultValue")}}); b.blur(function(d){c=$(d.target);if($.trim(c.val())==""){c.addClass("defaultValue");c.val(a)}})},addAutoGrow:function(){var a=this,b=this.component.find("textarea"),c=b.height();b.css("lineHeight");var d=$("<div></div>").css({position:"absolute",top:-1E4,left:-1E4,width:b.width()-parseInt(b.css("paddingLeft"))-parseInt(b.css("paddingRight")),fontSize:b.css("fontSize"),fontFamily:b.css("fontFamily"),lineHeight:b.css("lineHeight"),resize:"none"}).appendTo(document.body),e=function(){var f=b.val().replace(/</g, "&lt;").replace(/>/g,"&gt;").replace(/&/g,"&amp;").replace(/\n$/,"<br/>&nbsp;").replace(/\n/g,"<br/>").replace(/ {2,}/g,function(g){for(var h=0,j="";h<g.length-1;h++)j+="&nbsp;";return j+" "});d.html(f);b.css("height",Math.max(d.height()+20,c));a.parentJFormSection.parentJFormPage.jFormer.currentJFormPage&&a.parentJFormSection.parentJFormPage.jFormer.adjustHeight({delay:0})};$(b).change(e).keyup(e).keydown(e);e.apply(b);return this},getValue:function(){if(this.disabledByDependency||this.parentJFormSection.disabledByDependency)return null; var a=$("#"+this.id).val();return this.options.emptyValue?a==this.options.emptyValue?"":a:a},setValue:function(a){$("#"+this.id).val(a);this.validate(true)}});
unlicense
inri13666/google-api-php-client-v2
libs/Google/Service/AdSense/CustomChannelTargetingInfo.php
858
<?php namespace Google\Service\AdSense; class CustomChannelTargetingInfo extends \Google\Model { public $adsAppearOn; public $description; public $location; public $siteLanguage; public function setAdsAppearOn($adsAppearOn) { $this->adsAppearOn = $adsAppearOn; } public function getAdsAppearOn() { return $this->adsAppearOn; } public function setDescription($description) { $this->description = $description; } public function getDescription() { return $this->description; } public function setLocation($location) { $this->location = $location; } public function getLocation() { return $this->location; } public function setSiteLanguage($siteLanguage) { $this->siteLanguage = $siteLanguage; } public function getSiteLanguage() { return $this->siteLanguage; } }
unlicense
the-ramones/jaxb
src/attribute/address/USAddress.java
1865
package attribute.address; import javax.xml.bind.annotation.XmlAttribute; public class USAddress { @XmlAttribute static final String country = "USA"; private String city; private String name; private String state; private String street; @XmlAttribute private int zip; /** * The zero arg constructor is used by JAXB Unmarshaller to create an * instance of this type. */ public USAddress() { } public USAddress( String name, String street, String city, String state, int zip) { this.name = name; this.street = street; this.city = city; this.state = state; this.zip = zip; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getZip() { return zip; } /** * * * public void setZip(int zip) { this.zip = zip; } ** */ public String getState() { return state; } @XmlAttribute public void setState(String state) { this.state = state; } public String toString() { StringBuilder s = new StringBuilder(); if (name != null) { s.append(name) .append('\n'); } s.append(street) .append('\n') .append(city) .append(", ") .append(state) .append(" ") .append(zip); return s.toString(); } }
unlicense
supersonic902/antivirus-beacon
database 1.c++
473
create bin scan this = ready ready scan scan this [input] database = all files line 1241 2 a 7 a 14 b 19 a 25 b 27 c 28 c 30 b 31 c 31 d <--virus1--> line 1244 1 c 2 d 9 b 12 e 15 b 16 a 18 d 21 b 24 f 25 c 26 d <--virus2--> md#2=03b880022d0300a31304b106d3e08ec0a3a47cbe007ebf0000b9000cfcf3a4ff2ea27cb80000cd13 <--virus--> md#3=be007ebf0000b9000cfcf3a4ff2ea27cb80000cd13b801028a169e7c8a2e9f7c8a36a17ccd13c3 <--virus--> md#1575(A)=d087ecbe3c01bf0000b91000fcf2a4e9
unlicense
DottyVinnie/PortMod
src/main/java/com/dottyvinnie/portmod/init/ModBlocks.java
1910
package com.dottyvinnie.portmod.init; import com.dottyvinnie.portmod.IConfig; import com.dottyvinnie.portmod.blocks.*; import com.dottyvinnie.portmod.lib.Reference; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import java.lang.reflect.Field; @GameRegistry.ObjectHolder(Reference.MOD_ID) public class ModBlocks { public static final Block coarse_dirt = new BlockCoarseDirt(); public static final Block magma = new BlockMagma(); public static final Block purpur_block = new BlockPurpurBlock(); public static final Block stone = new BlockNewStone(); public static final Block sea_lantern = new BlockSeaLantern(); public static final Block prismarine = new BlockPrismarine(); public static final Block bone_block = new BlockBone(); public static void init() { try { for (Field f : ModBlocks.class.getDeclaredFields()) { Object obj = f.get(null); if (obj instanceof Block) registerBlock((Block) obj); else if (obj instanceof Block[]) for (Block block : (Block[]) obj) if (block != null) registerBlock(block); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static void registerBlock(Block block) { if (!(block instanceof IConfig) || ((IConfig) block).isEnabled()) { String name = block.getUnlocalizedName(); String[] strings = name.split("\\."); if (block instanceof ISubBlocksPM) GameRegistry.registerBlock(block, ((ISubBlocksPM) block).getItemBlockClass(), strings[strings.length - 1]); else GameRegistry.registerBlock(block, strings[strings.length - 1]); if (block instanceof IBurnable) Blocks.fire.setFireInfo(block, 5, 20); } } public static interface ISubBlocksPM { Class<? extends ItemBlock> getItemBlockClass(); } public static interface IBurnable { } }
unlicense
arlm/StoryboardTables
AsyncDataDownloader.designer.cs
1529
// WARNING // // This file has been generated automatically by Xamarin Studio to store outlets and // actions made in the UI designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using MonoTouch.Foundation; using System.CodeDom.Compiler; namespace StoryboardTables { [Register ("AsyncDataDownloader")] partial class AsyncDataDownloader { [Outlet] MonoTouch.UIKit.UIImageView DownloadedImageView { get; set; } [Outlet] MonoTouch.UIKit.UIButton getAsync { get; set; } [Outlet] MonoTouch.UIKit.UIButton GetButton { get; set; } [Outlet] MonoTouch.UIKit.UIButton getXMLX { get; set; } [Outlet] MonoTouch.UIKit.UIButton kayitOldumu { get; set; } [Outlet] MonoTouch.UIKit.UILabel ResultLabel { get; set; } [Outlet] MonoTouch.UIKit.UITextView ResultTextView { get; set; } void ReleaseDesignerOutlets () { if (DownloadedImageView != null) { DownloadedImageView.Dispose (); DownloadedImageView = null; } if (getAsync != null) { getAsync.Dispose (); getAsync = null; } if (GetButton != null) { GetButton.Dispose (); GetButton = null; } if (getXMLX != null) { getXMLX.Dispose (); getXMLX = null; } if (kayitOldumu != null) { kayitOldumu.Dispose (); kayitOldumu = null; } if (ResultLabel != null) { ResultLabel.Dispose (); ResultLabel = null; } if (ResultTextView != null) { ResultTextView.Dispose (); ResultTextView = null; } } } }
unlicense
clilystudio/NetBook
allsrc/com/ximalaya/ting/android/opensdk/util/XiMaDataSupport$3.java
657
package com.ximalaya.ting.android.opensdk.util; import java.util.List; import org.litepal.b.d; class XiMaDataSupport$3 extends MyAsyncTask<Void, Void, List<T>> { protected List<T> doInBackground(Void[] paramArrayOfVoid) { return d.findAll(this.val$modelClass, this.val$isEager, this.val$ids); } protected void onPostExecute(List<T> paramList) { if (this.val$callback == null) return; this.val$callback.onResult(paramList); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ximalaya.ting.android.opensdk.util.XiMaDataSupport.3 * JD-Core Version: 0.6.0 */
unlicense
PhompAng/06016219-SOFTWARE-ENGINEERING
Singleton/src/com/company/Doubleton/Doubleton.java
951
package com.company.Doubleton; import java.util.ArrayList; import java.util.Random; /** * Created by phompang on 11/26/2016 AD. */ public class Doubleton { private static ArrayList<Doubleton> doubletonArrayList = new ArrayList<>(); private int num; private Doubleton() { this.setNum(new Random().nextInt()); } public static Doubleton getIntance(int index) throws Exception { if (index > 2) { throw new Exception("Fuck"); } if (doubletonArrayList.size() == 0) { doubletonArrayList.add(null); doubletonArrayList.add(null); } if (doubletonArrayList.get(index) == null) { Doubleton d = new Doubleton(); doubletonArrayList.set(index, d); } return doubletonArrayList.get(index); } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }
unlicense
pixeltasim/IRCBot-Pixeltasim
plugins/scp.py
1594
from whiffle import wikidotapi from util import hook import re import time,threading @hook.command def scp(inp): #this is for WL use, easily adaptable to SCP ".scp <Article #> -- Will return exact match of 'SCP-Article#'" api = wikidotapi.connection() #creates API connection api.Site = "scp-wiki" pages = api.refresh_pages() #refresh page list provided by the API, is only a list of strings line = re.sub("[ ,']",'-',inp) #removes spaces and apostrophes and replaces them with dashes, per wikidot's standards for page in pages: if "scp-"+line.lower() == page: #check for first match to input if api.page_exists(page.lower()): #only api call in .tale, verification of page existence try: #must do error handling as the key will be wrong for most of the items if "scp" in api.get_page_item(page,"tags"): #check for tag rating = api.get_page_item(page,"rating") if rating < 0: ratesign = "-" if rating >= 0: ratesign = "+" #adds + or minus sign in front of rating ratestring = "Rating["+ratesign+str(rating)+"]" author = api.get_page_item(page,"created_by") authorstring = "Written by "+author title = api.get_page_item(page,"title") sepstring = ", " return "nonick::"+title+" ("+ratestring+sepstring+authorstring+") - http://scp-wiki.net/"+page.lower() #returns the string, nonick:: means that the caller's nick isn't prefixed except KeyError: pass else: return "nonick::Match found but page does not exist, please consult pixeltasim for error." return "nonick::Page not found"
unlicense
Mugurell/Learning
C++/C++ Primer 5th ed/Ch 13 - Copy & Move Control/Simplification of a vector of strings/StrVec.cpp
14636
/****************************************************************************** ******************************************************************************* * * Author: Lingurar Petru-Mugurel * Written: 09 Jul 2015, 21:29:32:436 * Last updated: 17 Jul 2015, 16:15:34:357 * * Compilation: g++ -std=c++14 -Wall -Werror -Wextra -pedantic -Wshadow * (g++ 5.1) -Woverloaded-virtual -Winvalid-pch -Wcast-align * -Wformat=2 -Wformat-nonliteral -Wmissing-declarations * -Wmissing-format-attribute -Wmissing-include-dirs * -Wredundant-decls -Wswitch-default -Wswitch-enum * * Execution: ./... * * Description: * Implementation file for the StrVec class * * Exercise 13.43: Rewrite the free member to use for_each and a lambda * in place of the for loop to destroy the elements. Which * implementation do you prefer, and why? * * Bugs: * --- None --- * * TODO: * --- None --- * * Notes: * --- * ******************************************************************************* ******************************************************************************/ #include <utility> // for std::move #include <algorithm> // std::for_each() #include <iostream> #include <iterator> // for std::make_move_iterator #include <utility> // for std::move #include "StrVec.h" /*********************************************************************** * Constructors, destructor and copy/move control members ***********************************************************************/ // Constructor that takes an initializer list of strings, empty by default. StrVec::StrVec(const std::initializer_list<std::string> &stringList) { const std::pair<std::string*, std::string*> newData = allocAndCopy(stringList.begin(), stringList.end()); firstElement = newData.first; // because allocAndCopy allocates space for exactly as many elements as it // is given, offTheEnd also points just past the last constructed element. firstFree = offTheEnd = newData.second; } // Copy/move control members StrVec::StrVec(const StrVec &constructFromMe) { const std::pair<std::string*, std::string*> newData = allocAndCopy(constructFromMe.begin(), constructFromMe.end()); firstElement = newData.first; // because allocAndCopy allocates space for exactly as many elements as it // is given, offTheEnd also points just past the last constructed element. firstFree = offTheEnd = newData.second; } StrVec::StrVec(StrVec &&constructFromMe) noexcept : firstElement(constructFromMe.firstElement), firstFree(constructFromMe.firstFree), offTheEnd(constructFromMe.offTheEnd) { // leave constructFromMe in a safe state to run the destructor on constructFromMe.firstElement = constructFromMe.firstFree = constructFromMe.offTheEnd = nullptr; } StrVec& StrVec::operator=(const StrVec &copyFromMe) { // call allocAndCopy to allocate exactly as many elements as in copyFromMe std::pair<std::string*, std::string*> data = allocAndCopy(copyFromMe.begin(), copyFromMe.end()); free(); firstElement = data.first; firstFree = offTheEnd = data.second; return *this; } StrVec& StrVec::operator=(StrVec &&moveFromMe) noexcept { // make sure to avoid self-assignment if (this != &moveFromMe) { free(); firstElement = moveFromMe.firstElement; firstFree = moveFromMe.firstFree; offTheEnd = moveFromMe.offTheEnd; //leave the right hand operand in a state safe to run the destructor on moveFromMe.firstElement = moveFromMe.firstFree = moveFromMe.offTheEnd = nullptr; } return *this; } StrVec::~StrVec() { free(); } /********************************************************************** * Overloaded operations * Members. **********************************************************************/ StrVec& StrVec::operator=(std::initializer_list<std::string> il) { std::pair<std::string*, std::string*> data = allocAndCopy(il.begin(), il.end()); free(); firstElement = data.first; firstFree = offTheEnd = data.second; return *this; } std::string& StrVec::operator[](std::size_t n) { return firstElement[n]; } const std::string& StrVec::operator[](std::size_t n) const { return firstElement[n]; } /********************************************************************** * Overloaded operations * Non - members. Friends **********************************************************************/ // Comparison operations. // Two vectors of strings are equal when they have the same size // and exactly the same strings bool operator==(const StrVec &lhv, const StrVec &rhv) { bool equality = true; if (lhv.size() == rhv.size()) { for (std::string left : lhv) { for (std::string right : rhv) { if (left != right) { equality = false; break; } } } } else equality = false; return equality; } bool operator!=(const StrVec &lhv, const StrVec &rhv) { // delegate the operator== function to do the checking return !(lhv == rhv); } // Relational operations. // Using the same function the stl vector uses: std::lexicographical_compare. // Will compare each element from each vector on the same position. // If both sequences compare equal until one of them ends, the shorter // sequence is lexicographically less than the longer one. bool operator<(const StrVec &lhv, const StrVec &rhv) { return std::lexicographical_compare(lhv.begin(), lhv.end(), rhv.begin(), rhv.end()); } // For the other 3 functions we'll delegate operator< to do the cheking bool operator>(const StrVec &lhv, const StrVec &rhv) { return rhv < lhv; } bool operator<=(const StrVec &lhv, const StrVec &rhv) { return !(rhv < lhv); } bool operator>=(const StrVec &lhv, const StrVec &rhv) { return !(lhv < rhv); } /************************************************************************** * Utilities used by the copy constructor, assignment operator, destructor * Private members. **************************************************************************/ // Because the memory an allocator allocates is unconstructed, we'll use the // allocator's construct member to create objects in that space when we need // to add an element. Similarly, when we remove an element, we'll use the // destroy member to destroy the element. std::allocator<std::string> StrVec::alloc; // will set the StrVec's capacity ro exactly the required size void StrVec::resize(const size_t &newSize) { // if newSize is bigger than the current capacity // we'll just call reserve to increase it if (newSize > capacity()) reserve(newSize); // If newSize is smaller than the capacity reduce the capacity to newSize. // If newSize is smaller than the current size, we'll assume that the // user also wants to deallocate some memory so we'll move elements from // the current vector up to newSize to a newly constructed one. if (size() > newSize || capacity() > newSize) { // allocate newSize heap space for a new vector std::string *newMemory = alloc.allocate(newSize); // move data from the old heap memory to the new one std::string *dest = newMemory; std::string *curr = firstElement; for (size_t i = 0; i < newSize; ++i) alloc.construct(dest++, std::move(*curr++)); // free the old heap memory once we've moved the data from it //std::cout << "**Before free, size() - " << size() << "\n\n"; free(); //std::cout << "**After free, size() - " << size() << "\n\n"; // update our StrVec's members to newMemory ones firstElement = newMemory; firstFree = offTheEnd = firstElement + newSize; } } // A call to reserve changes the capacity of the vector only if the requested // space exceeds the current capacity. void StrVec::reserve(const size_t &newSize) { // First check if our 'vector' has any elements. // If the 'vector' is empty, allocate it the required space and finish. if (size() == 0 && newSize > capacity()) { // allocate the required heap space std::string *newMemory = alloc.allocate(newSize); // initialize this StrVec's elements firstElement = newMemory; firstFree = offTheEnd = firstElement + newSize; } // If it has elements they must be copied in the new heap space if (newSize > capacity()) { // allocate the required heap space std::string *newMemory = alloc.allocate(newSize); // move data from the old memory to the newly allocated one // pointer to the free position in the newly allocated memory std::string *dest = newMemory; // pointer to the current element we're working with from the old memory std::string *curr = firstElement; size_t oldSize = size(); for (size_t i = 0; i != oldSize; i++) { // because we're using the move constructor, the memory managed by // those strings will not be copied. Instead, each string we // construct will take ownership of the memory from the string to // which elem points. alloc.construct(dest++, std::move(*curr++)); } // free the old heap memory free(); // initialize this StrVec's members with newMemory pointers firstElement = newMemory; firstFree = dest; offTheEnd = firstElement + newSize; } } void StrVec::reallocate() { // we'll double the capacity of StrVec each time we reallocate // if StrVec is empty, we allocate room for one element auto newCapacity = size() ? 2 * size() : 1; // allocate new memory std::string *newData = alloc.allocate(newCapacity); ///////// Will use uninitialized_copy as an easier alternative to this /////// // // // move the data from the old memory to the new // std::string *dest = newData; // points to the next free position // // in the new array // auto elem = firstElement; // points to next element in the old array // size_t currentSize = size(); // for (size_t i = 0; i != currentSize; i++) { // // because we're using the move constructor,memory managed by those // // strings will not be copied. Instead, each string we construct will // // take ownership of the memory from the string to which elem points. // alloc.construct(dest++, std::move(*elem++)); // } ////////////////////////////////////////////////////////////////////////////// // "move" the elements using std::uninitialized_copy and move iterators // (which yield rvalue references) // uninitialized_copy will return an iterator to the last element in newData std::string *last = std::uninitialized_copy (std::make_move_iterator(begin()), // begin iterator std::make_move_iterator(end()), // end iterator newData); // output iterator to the initial position free(); // free the old space once we've moved the elements // update our data structure to point to the new elements firstElement = newData; firstFree = last; offTheEnd = firstElement + newCapacity; } // If there isn't room for another element, chk_n_alloc will call reallocate // to get more space. void StrVec::checkAndAllocate() { if (size() == capacity()) reallocate(); } // The allocAndCopy member will allocate enough storage to hold its given range // of elements, and will copy those elements into the newly allocated space. // This function returns a pair of pointers, pointing to the beginning of the // new space and just past the last element it copied: std::pair<std::string *, std::string *> StrVec::allocAndCopy(const std::string *begin, const std::string *end) { // allocate space to hold as many elements as there are in the range std::string* data = alloc.allocate(end - begin); // initialize and return a pair constructed from data and // the value returned by data and uninitializedCopy // uninitialized_copy copies elements from the input range into // unconstructed, raw memory denoted by the iterator data return {data, std::uninitialized_copy(begin, end, data)}; } // The free member has two responsibilities: It must destroy the elements and // then deallocate the space that this StrVec itself allocated. The for loop // calls the allocator member destroy in reverse order, starting with the last // constructed element and finishing with the first: void StrVec::free() { // may not pass deallocate on a null pointer, // if firstElement is null, there's no work to do if (firstElement) { // destroy the old elements in reverse order while (firstFree != firstElement) { alloc.destroy(--firstFree); } // Implementation as for Ex 13.43 // std::for_each(firstElement, firstFree, // [] (std::string &curr) { alloc.destroy(&curr);} ); alloc.deallocate(firstElement, offTheEnd - firstElement); } } /************************************************************************** * Analogous functions to the ones of a stl vector **************************************************************************/ // The push_back function calls checkAndAllocate to ensure that there is room // for an element. If necessary, checkAndAllocate will call reallocate. // When checkAndAllocate returns, push_back knows that there is room for the new // element. It asks its allocator member to construct a new last element. void StrVec::push_back(const std::string &string) { checkAndAllocate(); // ensure that there is room for another element // construct a copy of string in the element to which firstFree points alloc.construct(firstFree++, string); } void StrVec::push_back(std::string &&string) { checkAndAllocate(); // reallocate the StrVec if necessary alloc.construct(firstFree++, std::move(string)); } std::string *StrVec::end() const { return firstFree; } std::string *StrVec::begin() const { return firstElement; } size_t StrVec::capacity() const { return offTheEnd - firstElement; } size_t StrVec::size() const { return firstFree - firstElement; }
unlicense
dermoumi/m2n
src/graphics/shader.hpp
1960
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN CATION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> */ #pragma once #include "../config.hpp" // Represents a set of GLSL Vertex and Fragment shaders class Shader { public: virtual ~Shader() = default; virtual bool load(const char* vertexShader, const char* fragmentShader) = 0; virtual void setUniform(int location, uint8_t type, float* data, uint32_t count = 1) = 0; virtual void setSampler(int location, uint8_t unit) = 0; virtual int uniformLocation(const char* name) const = 0; virtual int samplerLocation(const char* name) const = 0; static const char* log(); static const char* defaultVSCode(); static const char* defaultFSCode(); static void bind(Shader* shader); };
unlicense
GoldenR1618/SoftUni-Exercises-and-Exams
06.C#_OOP_Basics/01.DEFINING_CLASSES/EXERCISE/11. Pokemon Trainer/Properties/AssemblyInfo.cs
1409
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("11. Pokemon Trainer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("11. Pokemon Trainer")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2f982def-cb17-4dfa-b317-8f6602a73e4e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
unlicense
fremag/Nats.Services
Nats.Services.KeyValueStoreDemo/StoreClient/StoreClientForm.cs
2758
using Nats.Services.Core; using Nats.Services.Core.DiscoveryService; using NATS.Client; using NLog; using StoreServices; using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace StoreClient { public partial class StoreClientForm : Form { ILogger logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.FullName); IConnection connection; NatsServiceFactory serviceFactory; IProductStoreService storeService; StoreClientModel<string, Product, ProductInfo> model = new StoreClientModel<string, Product, ProductInfo>(); public StoreClientForm() { InitializeComponent(); } private async void StoreClientForm_LoadAsync(object sender, EventArgs e) { var options = ConnectionFactory.GetDefaultOptions(); options.Url = Defaults.Url; connection = new ConnectionFactory().CreateConnection(options); logger.Info($"Looking for a server."); var uiSched = TaskScheduler.FromCurrentSynchronizationContext(); string serverName = await Task.Run(() => DiscoverServer(connection, logger)); logger.Info($"Server found: {serverName}."); Text += serverName; await InitServicesAsync(serverName); logger.Info($"Store initialized: {objectListView1.GetItemCount()}"); } private async Task InitServicesAsync(string serverName) { serviceFactory = new NatsServiceFactory(connection, serverName); storeService = serviceFactory.BuildServiceClient<IProductStoreService>(); await model.InitAsync(storeService, objectListView1); Text += $", {objectListView1.GetItemCount()} products"; } public static string DiscoverServer(IConnection connection, ILogger logger=null, int periodMs=1000) { var serviceFactory = new NatsServiceFactory(connection, "Unknown"); var discoveryService = serviceFactory.BuildServiceClient<IDiscoveryService>(); string agentName = null; bool serverFound = false; discoveryService.EchoEvent += name => { agentName = name; serverFound = true; }; while (!serverFound) { logger?.Info("Looking for a server..."); discoveryService.Sonar(); Thread.Sleep(periodMs); } return agentName; } private void StoreClientForm_FormClosing(object sender, FormClosingEventArgs e) { connection.Close(); } } }
unlicense
GordonCoffeeCan/Gravity_Lover_Game_Studio_II
Gravity Game/Assets/Scripts/HubTriggerManager.cs
3346
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HubTriggerManager : MonoBehaviour { private bool playerPREntered = false; private bool playerJPEntered = false; // Use this for initialization void Start () { GameManager.musicSource.Music1.TransitionTo(1f); } // Update is called once per frame void Update () { switch (this.name) { case "Door1Trigger": DoorAnim(0, true); break; case "Door2Trigger": DoorAnim(1, true); break; case "Door3Trigger": DoorAnim(2, true); break; case "Door4Trigger": DoorAnim(3, true); break; case "Door1CloseTrigger": DoorAnim(0, false); DoorAnim(1, true); DoorAnim(2, true); if (NewGameData.level02Done == false) { HubManager._level02Portal.SetActive(true); } if(NewGameData.level03Done == false) { HubManager._level03Portal.SetActive(true); } RotateHub(); break; case "Door2CloseTrigger": if (NewGameData.level02Done == true) { DoorAnim(1, false); } RotateHub(); break; case "Door3CloseTrigger": if (NewGameData.level03Done == true) { DoorAnim(2, false); } if (NewGameData.level04Done == false) { HubManager._level04Portal.SetActive(true); } RotateHub(); break; case "Door4CloseTrigger": //DoorAnim(3, false); break; } } private void OnTriggerEnter2D(Collider2D _col) { if(_col.tag == "Player1") { playerPREntered = true; } if (_col.tag == "Player2") { playerJPEntered = true; } } private void OnTriggerExit2D(Collider2D _col) { if (_col.tag == "Player1") { playerPREntered = false; } if (_col.tag == "Player2") { playerJPEntered = false; } } private void DoorAnim(int _index, bool _isOpen) { if (playerPREntered == true && playerJPEntered == true) { HubManager.doors[_index].SetBool("Open", _isOpen); } } private void RotateHub() { if (playerPREntered == true && playerJPEntered == true) { if (NewGameData.tutorialLevelDone == true && NewGameData.level02Done == false && NewGameData.level03Done == false) { HubManager.levelState = HubManager.LevelState.level01Finished; } if (NewGameData.tutorialLevelDone == true && NewGameData.level02Done == true && NewGameData.level03Done == true) { HubManager.levelState = HubManager.LevelState.level02And03Finished; DoorAnim(3, true); } if (NewGameData.level04Done == true) { } } } }
unlicense
DeveloperXY/ResumeGenerator
src/com/developerxy/resume/section/acc/Accounts.java
261
package com.developerxy.resume.section.acc; import java.lang.annotation.*; /** * Created by Mohammed Aouf ZOUAG on 18/04/2017. */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Accounts { Account[] value(); }
unlicense
bansarids30/cs50
pset7/public/index.php
641
<?php // configuration require("../includes/config.php"); $rows = query("SELECT symbol, shares FROM stocks WHERE id = ?", $_SESSION["id"]); $positions = []; foreach ($rows as $row) { $stock = lookup($row["symbol"]); if ($stock !== false) { $positions[] = [ "name" => $stock["name"], "price" => $stock["price"], "shares" => $row["shares"], "symbol" => $row["symbol"] ]; } } // render portfolio render("portfolio.php", ["positions" => $positions,"title" => "Portfolio"]); ?>
unlicense
mntamim/vending-machine-kata
vending-machine-kata/src/vending/machine/kata/Coin.java
1282
package vending.machine.kata; /** * * @author mntam */ public class Coin { private final int weightInMilligrams; /** * Constructor to create coins * @param weightInMilligrams weight of the coin being made */ public Coin(int weightInMilligrams) { this.weightInMilligrams = weightInMilligrams; } /** * @return the weight of the coin in milligrams */ public int getWeightInMilligrams() { return weightInMilligrams; } /** * Creates a new Penny * @return a Coin object with the properties of a Penny */ public static Coin newPenny() { return new Coin(2500); } /** * Creates a new Nickel * @return a Coin object with the properties of a Nickel */ public static Coin newNickel() { return new Coin(5000); } /** * Creates a new Dime * @return a Coin object with the properties of a Dime */ public static Coin newDime() { return new Coin(2268); } /** * Creates a new Quarter * @return a Coin object with the properties of a Dime */ public static Coin newQuarter() { return new Coin(5670); } }
unlicense
joaovfc/experimentjavaapp
src/projpackage/JanelaPrincipal.java
2341
package projpackage; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class JanelaPrincipal extends JFrame { private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); private JTextField txt = new JTextField("enter text"); public JanelaPrincipal(String title) { setLayout(new GridLayout()); setTitle(title); add(b1); add(b2); add(txt); txt.addActionListener(new TextListener()); b1.addActionListener(new BtListener()); b2.addActionListener(new Bt2Listener(b2)); } class TextListener implements ActionListener { public void actionPerformed(ActionEvent e) { final String phrase = txt.getText(); txt.setText(""); SwingUtilities.invokeLater(new Runnable() { public void run() { System.out.println("chaging title to " + phrase); getJanelaPrincipal().setTitle(phrase); } }); } } class BtListener implements ActionListener { public void actionPerformed(ActionEvent e) { final String phrase = txt.getText(); txt.setText(""); SwingUtilities.invokeLater(new Runnable() { public void run() { if (proggg.js == null) SwingConsole.runNoSize(proggg.js = new JanelaSec()); else proggg.js.setVisible(true); } }); } } class Bt2Listener implements ActionListener { private JButton j; public Bt2Listener(JButton but) { j = but; } public void actionPerformed(ActionEvent e) { final String phrase = txt.getText(); txt.setText(""); SwingUtilities.invokeLater(new Runnable() { public void run() { System.out.println("changing " + j.getText() + " to " + phrase); j.setText(phrase); } }); } } public JanelaPrincipal getJanelaPrincipal() { return JanelaPrincipal.this; } }
unlicense
losman333/lostkawzlifestyle_newsblog
lostkawzlifestyle1/settings.py
6697
""" Django settings for lostkawzlifestyle1 project. Generated by 'django-admin startproject' using Django 1.9.12. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ from decouple import config, Csv import dj_database_url import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'sekizai', 'djangocms_admin_style', 'filer', 'easy_thumbnails', 'mptt', 'reversion', 'cms', 'menus', 'treebeard', 'storages', 'django.contrib.sites', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'djangocms_youtube', 'absolute', 'aldryn_forms', 'aldryn_forms.contrib.email_notifications', 'captcha', 'emailit', 'aldryn_apphooks_config', 'aldryn_mailchimp', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_background_image', 'lostkawzlifestyle1', 'aldryn_people', 'aldryn_reversion', 'aldryn_translation_tools', 'aldryn_gallery', 'aldryn_boilerplates', 'parler', 'sortedm2m', 'taggit', 'social_widgets', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] THUMBNAIL_HIGH_RESOLUTION = True THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', 'easy_thumbnails.processors.scale_and_crop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters', 'easy_thumbnails.processors.background', ) ROOT_URLCONF = 'lostkawzlifestyle1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'cms.context_processors.cms_settings', 'sekizai.context_processors.sekizai', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'lostkawzlifestyle1.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] CMS_TEMPLATES = [ ('base.html', 'base'), ('content.html', 'content page template'), ('gallery.html', 'gallery '), ] DJANGOCMS_STYLE_TAGS = ['div', 'article', 'hr', 'br', 'section', 'header', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SOCIAL_AUTH_FACEBOOK_KEY = config('SOCIAL_AUTH_FACEBOOK_KEY') SOCIAL_AUTH_FACEBOOK_SECRET = config('SOCIAL_AUTH_FACEBOOK_SECRET') MAILCHIMP_API_KEY = config('MAILCHIMP_API_KEY') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ AWS_STORAGE_BUCKET_NAME = config('BUCKET_NAME') AWS_CLOUDFRONT_DOMAIN = config('CD_DOMAIN') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' STATIC_ROOT = '/static/' STATIC_URL = '/static/' STATICFILES_LOCATION = '/static/' #STATICFILES_STORAGE = 'custom_storages.StaticStorage' #STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"),] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env)
unlicense
Inviz/lsd
Source/Action/Display.js
1112
/* --- script: Display.js description: Shows or hides things license: Public domain (http://unlicense.org). authors: Yaroslaff Fedin requires: - LSD.Action provides: - LSD.Action.Display - LSD.Action.Show - LSD.Action.Hide ... */ LSD.Action.Display = LSD.Action.build({ enable: function(target) { var widget = LSD.Module.DOM.find(target, true); if (widget) { if (widget.animate) widget.animate(true); else widget.show(); } else if (target.nodeName) { target.removeAttribute('hidden'); } }, disable: function(target) { var widget = LSD.Module.DOM.find(target, true); if (widget) { if (widget.animate) widget.animate(false); else widget.hide(); } else if (target.nodeName) { target.setAttribute('hidden', 'hidden'); } }, getState: function(target) { var element = (target.element || target); return target.hidden || (target.getAttribute && (target.getAttribute('hidden') == 'hidden')) || (element.getStyle && (element.getStyle('display') == 'none')); }, enabler: 'show', disabler: 'hide' });
unlicense
SeanShubin/web-sync
domain/src/test/scala/com/seanshubin/web/sync/domain/ErrorHandlerTest.scala
795
package com.seanshubin.web.sync.domain import org.scalatest.FunSuite import org.scalatest.easymock.EasyMockSugar class ErrorHandlerTest extends FunSuite with EasyMockSugar { test("do nothing if no errors") { val errorHandler: ErrorHandler = new ErrorHandlerImpl val downloadResults: Seq[DownloadResult] = Seq(DownloadResultSamples.downloadResultSame) errorHandler.shutdown(downloadResults) } test("propagate exception if errors") { val errorHandler: ErrorHandler = new ErrorHandlerImpl val downloadResults: Seq[DownloadResult] = Seq(DownloadResultSamples.downloadResultMissingBoth) val thrown = intercept[RuntimeException] { errorHandler.shutdown(downloadResults) } assert(thrown.getMessage === "Forwarding exception due to web sync errors") } }
unlicense
D-Inc/EnderIO
src/main/java/crazypants/enderio/machine/obelisk/render/ObeliskRenderManager.java
5221
package crazypants.enderio.machine.obelisk.render; import crazypants.enderio.machine.AbstractMachineEntity; import crazypants.enderio.machine.obelisk.attractor.TileAttractor; import crazypants.enderio.machine.obelisk.aversion.AversionObeliskRenderer; import crazypants.enderio.machine.obelisk.aversion.TileAversionObelisk; import crazypants.enderio.machine.obelisk.inhibitor.TileInhibitorObelisk; import crazypants.enderio.machine.obelisk.relocator.RelocatorObeliskRenderer; import crazypants.enderio.machine.obelisk.relocator.TileRelocatorObelisk; import crazypants.enderio.machine.obelisk.weather.TileWeatherObelisk; import crazypants.enderio.machine.obelisk.weather.WeatherObeliskSpecialRenderer; import crazypants.enderio.machine.obelisk.xp.TileExperienceObelisk; import crazypants.enderio.material.Material; import crazypants.enderio.render.registry.TextureRegistry; import crazypants.enderio.render.registry.TextureRegistry.TextureSupplier; import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import static crazypants.enderio.ModObject.blockAttractor; import static crazypants.enderio.ModObject.blockExperienceObelisk; import static crazypants.enderio.ModObject.blockInhibitorObelisk; import static crazypants.enderio.ModObject.blockSpawnGuard; import static crazypants.enderio.ModObject.blockSpawnRelocator; import static crazypants.enderio.ModObject.blockWeatherObelisk; import static crazypants.enderio.ModObject.itemMaterial; import static crazypants.enderio.ModObject.itemXpTransfer; @SideOnly(Side.CLIENT) public class ObeliskRenderManager { public static final ObeliskRenderManager INSTANCE = new ObeliskRenderManager(); public static ModelResourceLocation MODEL_LOCATION = new ModelResourceLocation("enderio:obelisk"); private TextureSupplier[] textures = { TextureRegistry.registerTexture("blocks/obeliskBottom"), TextureRegistry.registerTexture("blocks/blockSoulMachineTop"), TextureRegistry.registerTexture("blocks/blockAttractorSide"), TextureRegistry.registerTexture("blocks/blockAttractorSide"), TextureRegistry.registerTexture("blocks/blockAttractorSide"), TextureRegistry.registerTexture("blocks/blockAttractorSide") }; private TextureSupplier[] activeTextures = { TextureRegistry.registerTexture("blocks/obeliskBottom"), TextureRegistry.registerTexture("blocks/blockSoulMachineTop"), TextureRegistry.registerTexture("blocks/blockAttractorSideOn"), TextureRegistry.registerTexture("blocks/blockAttractorSideOn"), TextureRegistry.registerTexture("blocks/blockAttractorSideOn"), TextureRegistry.registerTexture("blocks/blockAttractorSideOn") }; private ObeliskRenderManager() { } public void registerRenderers() { Block block; block = blockExperienceObelisk.getBlock(); if (block != null) { ObeliskSpecialRenderer<TileExperienceObelisk> eor = new ObeliskSpecialRenderer<TileExperienceObelisk>(new ItemStack(itemXpTransfer.getItem()), block); registerRenderer(block, TileExperienceObelisk.class, eor); } block = blockAttractor.getBlock(); if (block != null) { ObeliskSpecialRenderer<TileAttractor> eor = new ObeliskSpecialRenderer<TileAttractor>( new ItemStack(itemMaterial.getItem(), 1, Material.ATTRACTOR_CRYSTAL.ordinal()), block); registerRenderer(block, TileAttractor.class, eor); } block = blockSpawnGuard.getBlock(); if (block != null) { AversionObeliskRenderer eor = new AversionObeliskRenderer(); registerRenderer(block, TileAversionObelisk.class, eor); } block = blockSpawnRelocator.getBlock(); if (block != null) { RelocatorObeliskRenderer eor = new RelocatorObeliskRenderer(); registerRenderer(block, TileRelocatorObelisk.class, eor); } block = blockWeatherObelisk.getBlock(); if (block != null) { ObeliskSpecialRenderer<TileWeatherObelisk> eor = new WeatherObeliskSpecialRenderer(new ItemStack(Items.FIREWORKS)); registerRenderer(block, TileWeatherObelisk.class, eor); } block = blockInhibitorObelisk.getBlock(); if (block != null) { ObeliskSpecialRenderer<TileInhibitorObelisk> eor = new ObeliskSpecialRenderer<TileInhibitorObelisk>(new ItemStack(Items.ENDER_PEARL), block); registerRenderer(block, TileInhibitorObelisk.class, eor); } } private <T extends AbstractMachineEntity> void registerRenderer(Block block, Class<T> tileClass, TileEntitySpecialRenderer<? super T> specialRenderer) { ClientRegistry.bindTileEntitySpecialRenderer(tileClass, specialRenderer); ForgeHooksClient.registerTESRItemStack(Item.getItemFromBlock(block), 0, tileClass); } public TextureSupplier[] getTextures() { return textures; } public TextureSupplier[] getActiveTextures() { return activeTextures; } }
unlicense
onpointtech/stack-reference
src/main/webapp/scripts/app/entities/employer/employer.controller.js
1853
'use strict'; angular.module('aquilaApp') .controller('EmployerController', function ($scope, Employer, ParseLinks) { $scope.employers = []; $scope.page = 1; $scope.loadAll = function() { Employer.query({page: $scope.page, per_page: 20}, function(result, headers) { $scope.links = ParseLinks.parse(headers('link')); $scope.employers = result; }); }; $scope.loadPage = function(page) { $scope.page = page; $scope.loadAll(); }; $scope.loadAll(); $scope.create = function () { Employer.update($scope.employer, function () { $scope.loadAll(); $('#saveEmployerModal').modal('hide'); $scope.clear(); }); }; $scope.update = function (id) { Employer.get({id: id}, function(result) { $scope.employer = result; $('#saveEmployerModal').modal('show'); }); }; $scope.delete = function (id) { Employer.get({id: id}, function(result) { $scope.employer = result; $('#deleteEmployerConfirmation').modal('show'); }); }; $scope.confirmDelete = function (id) { Employer.delete({id: id}, function () { $scope.loadAll(); $('#deleteEmployerConfirmation').modal('hide'); $scope.clear(); }); }; $scope.clear = function () { $scope.employer = {name: null, address: null, contactName: null, contactPhone: null, id: null}; $scope.editForm.$setPristine(); $scope.editForm.$setUntouched(); }; });
apache-2.0
wwu-pi/md2-framework
de.wwu.md2.framework/src/de/wwu/md2/framework/generator/IPlatformGenerator.java
736
package de.wwu.md2.framework.generator; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.xtext.generator.IGenerator; /** * Platform generator interface. */ public interface IPlatformGenerator extends IGenerator { /** * Enable code generation for multiple input models (resources). * * @param input - A set of model resources for which to generate the code. * @param fsa - File system access to be used to generate files. */ public void doGenerate(ResourceSet input, IExtendedFileSystemAccess fsa); /** * This method provides a platform prefix to distinguish generators for different * target platforms. * * @return Platform prefix string. */ public String getPlatformPrefix(); }
apache-2.0
biobricks/dbos
schemas/timestamp/1.0.0.js
1259
/* Copyright 2017 The BioBricks Foundation 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. */ module.exports = { $schema: 'http://json-schema.org/draft-06/schema#', type: 'object', properties: { timestamp: { type: 'object', properties: { digest: {$ref: '#/definitions/digest'}, uri: { type: 'string', format: 'uri' }, time: { type: 'string', format: 'date-time' } }, required: ['time', 'digest', 'uri'], additionalProperties: false }, signature: {$ref: '#/definitions/signature'} }, required: ['timestamp', 'signature'], additionalProperties: false, definitions: { digest: require('../digest'), signature: require('../signature') } }
apache-2.0
wooga/airflow
airflow/utils/email.py
5000
# # 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. import collections import logging import os import smtplib from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate from typing import Iterable, List, Union from airflow.configuration import conf from airflow.exceptions import AirflowConfigException log = logging.getLogger(__name__) def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', mime_charset='utf-8', **kwargs): """ Send email using backend specified in EMAIL_BACKEND. """ backend = conf.getimport('email', 'EMAIL_BACKEND') to = get_email_address_list(to) to = ", ".join(to) return backend(to, subject, html_content, files=files, dryrun=dryrun, cc=cc, bcc=bcc, mime_subtype=mime_subtype, mime_charset=mime_charset, **kwargs) def send_email_smtp(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', mime_charset='utf-8', **kwargs): """ Send an email with html content >>> send_email('test@example.com', 'foo', '<b>Foo</b> bar', ['/dev/null'], dryrun=True) """ smtp_mail_from = conf.get('smtp', 'SMTP_MAIL_FROM') to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg['Subject'] = subject msg['From'] = smtp_mail_from msg['To'] = ", ".join(to) recipients = to if cc: cc = get_email_address_list(cc) msg['CC'] = ", ".join(cc) recipients = recipients + cc if bcc: # don't add bcc in header bcc = get_email_address_list(bcc) recipients = recipients + bcc msg['Date'] = formatdate(localtime=True) mime_text = MIMEText(html_content, 'html', mime_charset) msg.attach(mime_text) for fname in files or []: basename = os.path.basename(fname) with open(fname, "rb") as file: part = MIMEApplication( file.read(), Name=basename ) part['Content-Disposition'] = 'attachment; filename="%s"' % basename part['Content-ID'] = '<%s>' % basename msg.attach(part) send_mime_email(smtp_mail_from, recipients, msg, dryrun) def send_mime_email(e_from, e_to, mime_msg, dryrun=False): """ Send MIME email. """ smtp_host = conf.get('smtp', 'SMTP_HOST') smtp_port = conf.getint('smtp', 'SMTP_PORT') smtp_starttls = conf.getboolean('smtp', 'SMTP_STARTTLS') smtp_ssl = conf.getboolean('smtp', 'SMTP_SSL') smtp_user = None smtp_password = None try: smtp_user = conf.get('smtp', 'SMTP_USER') smtp_password = conf.get('smtp', 'SMTP_PASSWORD') except AirflowConfigException: log.debug("No user/password found for SMTP, so logging in with no authentication.") if not dryrun: conn = smtplib.SMTP_SSL(smtp_host, smtp_port) if smtp_ssl else smtplib.SMTP(smtp_host, smtp_port) if smtp_starttls: conn.starttls() if smtp_user and smtp_password: conn.login(smtp_user, smtp_password) log.info("Sent an alert email to %s", e_to) conn.sendmail(e_from, e_to, mime_msg.as_string()) conn.quit() def get_email_address_list(addresses: Union[str, Iterable[str]]) -> List[str]: """ Get list of email addresses. """ if isinstance(addresses, str): return _get_email_list_from_str(addresses) elif isinstance(addresses, collections.abc.Iterable): if not all(isinstance(item, str) for item in addresses): raise TypeError("The items in your iterable must be strings.") return list(addresses) received_type = type(addresses).__name__ raise TypeError("Unexpected argument type: Received '{}'.".format(received_type)) def _get_email_list_from_str(addresses: str) -> List[str]: delimiters = [",", ";"] for delimiter in delimiters: if delimiter in addresses: return [address.strip() for address in addresses.split(delimiter)] return [addresses]
apache-2.0
liqilun/iticket
src/main/java/com/iticket/util/VmBaseUtil.java
7402
package com.iticket.util; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; public class VmBaseUtil extends StringUtils { public final static String subLastText(String temp, String text) { if (StringUtils.isBlank(temp) || StringUtils.isBlank(text)) return ""; return StringUtils.substring(text, StringUtils.lastIndexOf(text, temp) + 1); } public final static String encodeStr(String str, String encoding) { try { if (StringUtils.isBlank(str)) { return str; } String result = URLEncoder.encode(str, encoding); return result; } catch (UnsupportedEncodingException e) {// ignore } return null; } /** * Checks if a List/array is empty. * * @param list * the List/array/map to check. * @return <code>true</code> if the List/array/map is null or empty. */ public final static boolean isEmptyList(Object list) { return BeanUtil.isEmptyContainer(list); } public final static boolean isEmpObj(Object obj) { if (obj == null) return true; if (obj.getClass().isArray()) { // Thanks to Eric Fixler for this refactor. return Array.getLength(obj) == 0; } if (obj instanceof Collection) { return ((Collection) obj).size() == 0; } if (obj instanceof Map) { return ((Map) obj).size() == 0; } return false; } public final static boolean isNotEmpObj(Object obj) { return !isEmpObj(obj); } public final static Integer size(Object list) { if (list == null) return 0; if (list.getClass().isArray()) { // Thanks to Eric Fixler for this refactor. return new Integer(Array.getLength(list)); } if (list instanceof Collection) { return ((Collection) list).size(); } if (list instanceof Map) { return ((Map) list).size(); } return 0; } public final static String printList(String[] list) { return StringUtils.join(list, ","); } public final static String printList(List<String> list) { return printList(list, ","); } public final static String printList(List<String> list, String separatorChars) { if (isEmptyList(list)) return null; String[] a = list.toArray(new String[list.size()]); return StringUtils.join(a, separatorChars); } public final static boolean isNull(Object obj) { if (obj == null) return true; if (obj instanceof String) { return StringUtils.isBlank((String) obj); } return false; } public final static boolean eq(Object obj1, Object obj2) { if (obj1 == null) return obj2 == null; if (obj2 == null) return false; if (obj1.equals(obj2)) return true; if (obj1.getClass().equals(obj2.getClass())) return false; return StringUtils.equals(obj1.toString(), obj2.toString()); } public final static boolean gt(Object obj1, Object obj2) { if (obj1 == null && obj2 == null) return true; if (obj2 == null) return true; if (obj1 == null) return false; if (obj1.getClass().equals(obj2.getClass())) { try { int i = ((Comparable) obj1).compareTo(obj2); return i > 0; } catch (Exception e) { return false; } } else { try { return Double.parseDouble("" + obj1) - Double.parseDouble("" + obj2) > 0; } catch (Exception e) { return ("" + obj1).compareTo(obj2.toString()) > 0; } } } public final static Object dft(Object original, Object value) { if (original == null) return value; if (original instanceof String && isBlank("" + original)) return value; return original; } public final static boolean contains(Object list, Object element) { if (list == null) return false; if (list.getClass().isArray()) { return arrayContains(list, element); } if (!(list instanceof Collection)) { return false; } return ((Collection) list).contains(element); } private final static boolean arrayContains(Object array, Object element) { int size = size(array).intValue(); try { for (int index = 0; index < size; ++index) { if (eq(element, Array.get(array, index))) { return true; } } } catch (IndexOutOfBoundsException e) { return false; } catch (Exception e) { } return false; } public final static boolean isAscii(String s) { if (s == null) return true; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) > 256) return false; } return true; } /** * * switch value in value1 and value2 * * @return */ public final static Object sw(Object value1, Object value2, Object current) { if (current == null || current.equals(value1)) return value2; else return value1; } public final static String dft(String src, String dft) { if (isBlank(src)) return dft; return src; } public final static String dft2(String src, String result, String dft) { if (isBlank(src)) return dft; return StringUtils.isBlank(result) ? src : result; } public final static int getByteLength(String input) { if (input == null) return 0; int length = input.length(); int byteLength = length; for (int i = 0; i < length; i++) if (input.charAt(i) > 128) byteLength++; return byteLength; } public final static boolean isBlank(Object obj) { if (obj == null) return true; return StringUtils.isBlank(obj + ""); } public final static String replaceName(String name, String replaceOldName, String repalceNewName) { if (StringUtils.isNotBlank(name) && name.indexOf(replaceOldName) != -1) { return name.replace(replaceOldName, repalceNewName); } else { return name; } } public final static String formatPercent(Integer num1, Integer num2) { return formatPercent(num1, num2, "0.00%"); } public final static String formatPercent(Integer num1, Integer num2, String format) { if (num1 == null || num2 == null || num2 == 0) return "?"; double div = (double) num1 / num2; DecimalFormat myformat = (DecimalFormat) NumberFormat .getPercentInstance(); myformat.applyPattern(format); return myformat.format(div); } public final static String formatPercent(Double num1, Double num2) { if (num1 == null || num2 == null || num2 == 0) return ""; String format = "0.00%"; if (num1.intValue() == num1.doubleValue() && num2.intValue() == num2.doubleValue()) { format = "0%"; } return formatPercent(num1, num2, format); } public final static String formatPercent(Double num1, Double num2, String format) { if (num1 == null || num2 == null || num2 == 0) return ""; double div = num1 / num2; DecimalFormat myformat = (DecimalFormat) NumberFormat .getPercentInstance(); myformat.applyPattern(format); return myformat.format(div); } public final static String getJsonValueByKey(String json, String key) { return JsonUtils.getJsonValueByKey(json, key); } public final static String getSmobile(String mobile) { if (!ValidateUtil.isMobile(mobile)) return ""; return mobile.substring(0, 3) + "****" + mobile.substring(7, 11); } }
apache-2.0
SUPERCILEX/FirebaseUI-Android
auth/src/main/java/com/firebase/ui/auth/util/data/ProviderAvailability.java
783
package com.firebase.ui.auth.util.data; import android.support.annotation.RestrictTo; @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class ProviderAvailability { public static final boolean IS_FACEBOOK_AVAILABLE = exists("com.facebook.login.LoginManager"); public static final boolean IS_TWITTER_AVAILABLE = exists("com.twitter.sdk.android.core.identity.TwitterAuthClient"); private ProviderAvailability() { throw new AssertionError("No instance for you!"); } private static boolean exists(String name) { boolean exists; try { Class.forName(name); exists = true; } catch (ClassNotFoundException e) { exists = false; } return exists; } }
apache-2.0
GennadiyL/AppKit
Core/Consoles.GennadiyLe.Core/Validation/ValidationConsole.cs
1219
using System; using System.Collections.Generic; using FluentValidation.Results; namespace Consoles.GennadiyLe.Core.Validation { public class ValidationConsole { public void Run() { TempData data1 = new TempData() { Name = "ssss", Id = Guid.NewGuid(), Age = 15 }; ITempDataValidator validator = new TempDataValidator(); //IValidator<TempData> validator = validator1; ValidationResult result1 = validator.Validate(data1); ValidationFailure failure = result1.Errors[0]; object attemptedValue = failure.AttemptedValue; object customState = failure.CustomState; string errorCode = failure.ErrorCode; object[] formattedMessageArguments = failure.FormattedMessageArguments; string propertyName = failure.PropertyName; Dictionary<string, object> formattedMessagePlaceholderValues = failure.FormattedMessagePlaceholderValues; #pragma warning disable CS0219 // Variable is assigned but its value is never used int n = 0; #pragma warning restore CS0219 // Variable is assigned but its value is never used } } }
apache-2.0