code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * This file is part of l2jserver2 <l2jserver2.com>. * * l2jserver2 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. * * l2jserver2 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 l2jserver2. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jserver.service.game.item; /** * @author <a href="http://www.rogiel.com">Rogiel</a> */ public class NonStackableItemsServiceException extends ItemServiceException { /** * Java Serialization API ID */ private static final long serialVersionUID = 1L; /** * Creates a new instance */ public NonStackableItemsServiceException() { } /** * @param message * the message * @param cause * the cause */ public NonStackableItemsServiceException(String message, Throwable cause) { super(message, cause); } /** * @param message * the message */ public NonStackableItemsServiceException(String message) { super(message); } /** * @param cause * the cause */ public NonStackableItemsServiceException(Throwable cause) { super(cause); } }
l2jserver2/l2jserver2
l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/service/game/item/NonStackableItemsServiceException.java
Java
gpl-3.0
1,539
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] int estimateDiam(IntegerVector initial, IntegerMatrix moves){ //This function should return an upper bound on the diameter! int diam=1000; return diam; }
windisch/rrSample
src/estimateDiam.cpp
C++
gpl-3.0
222
#include "stdafx.h" #include "S0MeterSerial.h" #include "../main/Logger.h" #include "../main/Helper.h" #include "../main/RFXtrx.h" #include "../main/mainworker.h" #include "P1MeterBase.h" #include "hardwaretypes.h" #include <string> #include <algorithm> #include <iostream> #include <boost/bind.hpp> #include <ctime> // //Class S0MeterSerial // S0MeterSerial::S0MeterSerial(const int ID, const std::string& devname, const unsigned int baud_rate, const int M1Type, const int M1PPH, const int M2Type, const int M2PPH) { m_HwdID=ID; m_szSerialPort=devname; m_iBaudRate=baud_rate; //Quick hack, meters 3 till 5 uses same parameter as 1 for now, till we can configure it m_meters[0].m_type=M1Type; m_meters[1].m_type=M2Type; m_meters[2].m_type=M1Type; m_meters[3].m_type=M1Type; m_meters[4].m_type=M1Type; m_meters[0].m_pulse_per_unit=1000.0; m_meters[1].m_pulse_per_unit=1000.0; m_meters[2].m_pulse_per_unit=1000.0; m_meters[3].m_pulse_per_unit=1000.0; m_meters[4].m_pulse_per_unit=1000.0; if (M1PPH!=0) m_meters[0].m_pulse_per_unit=float(M1PPH); if (M2PPH!=0) m_meters[1].m_pulse_per_unit=float(M1PPH); } S0MeterSerial::~S0MeterSerial() { clearReadCallback(); } bool S0MeterSerial::StartHardware() { //Try to open the Serial Port try { _log.Log(LOG_NORM,"S0 Meter Using serial port: %s", m_szSerialPort.c_str()); #ifndef WIN32 openOnlyBaud( m_szSerialPort, m_iBaudRate, boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::even), boost::asio::serial_port_base::character_size(7) ); #else open( m_szSerialPort, m_iBaudRate, boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::even), boost::asio::serial_port_base::character_size(7) ); #endif } catch (boost::exception & e) { _log.Log(LOG_ERROR,"Error opening serial port!"); #ifdef _DEBUG _log.Log(LOG_ERROR,"-----------------\n%s\n-----------------",boost::diagnostic_information(e).c_str()); #endif return false; } catch ( ... ) { _log.Log(LOG_ERROR,"Error opening serial port!!!"); return false; } m_bIsStarted=true; m_bufferpos=0; ReloadLastTotals(); setReadCallback(boost::bind(&S0MeterSerial::readCallback, this, _1, _2)); sOnConnected(this); return true; } bool S0MeterSerial::StopHardware() { m_bIsStarted=false; if (isOpen()) { try { clearReadCallback(); close(); doClose(); setErrorStatus(true); } catch(...) { //Don't throw from a Stop command } } return true; } void S0MeterSerial::readCallback(const char *data, size_t len) { boost::lock_guard<boost::mutex> l(readQueueMutex); if (!m_bIsStarted) return; if (!m_bEnableReceive) return; //receiving not enabled ParseData((const unsigned char*)data, (int)len); } void S0MeterSerial::WriteToHardware(const char *pdata, const unsigned char length) { }
ozarchie/domoticz
hardware/S0MeterSerial.cpp
C++
gpl-3.0
2,962
require (ENV['OPERATOR_HOME'] + '/vagrant/lib/common/module/paths.rb') include CommonPaths eval File.read( COMMON + '/pre/0_synced.rb' ) if File.file?("synced.rb") eval File.read("synced.rb") end eval File.read( COMMON + '/pre/1_init.rb' ) eval File.read( COMMON + '/pre/2_install.rb' ) eval File.read( COMMON + '/pre/3_setup.rb' ) eval File.read( COMMON + '/pre/4_system.rb' ) if File.file?("provision.rb") eval File.read("provision.rb") end eval File.read( COMMON + '/post/cleanup.rb' )
valterhenrique/operator
vagrant/lib/common/provision.rb
Ruby
gpl-3.0
498
vti_encoding:SR|utf8-nl vti_timelastmodified:TW|14 Aug 2014 12:39:17 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Office-PC\\Rafael vti_modifiedby:SR|Office-PC\\Rafael vti_timecreated:TR|01 Nov 2014 09:09:36 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Aug 2014 12:39:17 -0000 vti_cacheddtm:TX|03 Nov 2015 21:05:11 -0000 vti_filesize:IR|922 vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000 vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:05:11 -0000
Vitronic/kaufreund.de
admin/language/english/openbay/_vti_cnf/amazonus_stockupdates.php
PHP
gpl-3.0
753
################################################################### # $Id$ # # Copyright (c) 2009 Aaron Turner, <aturner at synfin dot net> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # * Neither the name of the Aaron Turner nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ################################################################### # - Find out if the system supports Linux's TX_RING socket API # we only try compiling the test since that looks for TX_RING INCLUDE(CheckCSourceRuns) CHECK_C_SOURCE_RUNS(" #include <sys/socket.h> #include <netpacket/packet.h> #include <net/ethernet.h> /* the L2 protocols */ #include <netinet/in.h> /* htons */ #include <linux/if_packet.h> int main(int argc, char *argv[]) { int test; test = TP_STATUS_WRONG_FORMAT exit(0); } " TX_RING_RUN_RESULT) SET(HAVE_TX_RING NO) IF(TX_RING_RUN_RESULT EQUAL 1) SET(HAVE_TX_RING YES) MESSAGE(STATUS "System has TX_RING support") ELSE(TX_RING_RUN_RESULT EQUAL 1) MESSAGE(STATUS "System does not have TX_RING support") ENDIF(TX_RING_RUN_RESULT EQUAL 1)
synfinatic/tcpreplay
cmake/CheckTxRing.cmake
CMake
gpl-3.0
2,455
/* This is a conversion from LIB-R-MATH to Typescript/Javascript Copyright (C) 2018 Jacob K.F. Bogers info@mail.jacob-bogers.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import { debug } from 'debug'; import { ML_ERR_return_NAN, R_Q_P01_boundaries } from '@common/logger'; import { lfastchoose } from '@lib/special/choose'; import { R_DT_qIv } from '@dist/exp/expm1'; import { DBL_EPSILON } from '@lib/r-func'; import type { QHyperFunctionMap, CalcQHyper } from './qhyper_wasm'; const printer_qhyper = debug('qhyper'); const _d = new Float64Array(7); const ixr = 0; const isum = 1; const ixb = 2; const iterm = 3; const iNR = 4; const iNB = 5; // init let backendTinyN: CalcQHyper = cpuBackendTinyN; let backendBigN: CalcQHyper = cpuBackendBigN; export function registerBackend(fns: QHyperFunctionMap): void { backendTinyN = fns.calcTinyN; backendBigN = fns.calcBigN; } export function unRegisterBackend(): boolean { const previous = !!backendTinyN && !!backendBigN; backendTinyN = cpuBackendTinyN; backendBigN = cpuBackendBigN; return previous; } function cpuBackendTinyN(sum: number, term: number, p: number, xr: number, end: number, xb: number, NB: number, NR: number): number { while (sum < p && xr < end) { //xr++ xr++; NB++; term *= (NR / xr) * (xb / NB); sum += term; xb--; NR--; } return xr; } function cpuBackendBigN(sum: number, term: number, p: number, xr: number, end: number, xb: number, NB: number, NR: number): number { while (sum < p && xr < end) { xr++; NB++; term += Math.log((NR / xr) * (xb / NB)); sum += Math.exp(term); xb--; NR--; } return xr; } export function qhyper( p: number, nr: number, nb: number, n: number, lowerTail = true, logP = false ): number { if (isNaN(p) || isNaN(nr) || isNaN(nb) || isNaN(n)) { return NaN; } if (!isFinite(p) || !isFinite(nr) || !isFinite(nb) || !isFinite(n)) { return ML_ERR_return_NAN(printer_qhyper); } _d[iNR] = Math.round(nr); _d[iNB] = Math.round(nb); const N = _d[iNR] + _d[iNB]; n = Math.round(n); if (_d[iNR] < 0 || _d[iNB] < 0 || n < 0 || n > N) return ML_ERR_return_NAN(printer_qhyper); /* Goal: Find xr (= #{red balls in sample}) such that * phyper(xr, NR,NB, n) >= p > phyper(xr - 1, NR,NB, n) */ const xstart = Math.max(0, n - _d[iNB]); const xend = Math.min(n, _d[iNR]); const rc = R_Q_P01_boundaries(lowerTail, logP, p, xstart, xend); if (rc !== undefined) { return rc; } _d[ixr] = xstart; _d[ixb] = n - _d[ixr]; /* always ( = #{black balls in sample} ) */ const small_N = N < 1000; /* won't have underflow in product below */ /* if N is small, term := product.ratio( bin.coef ); otherwise work with its logarithm to protect against underflow */ _d[iterm] = lfastchoose(_d[iNR], _d[ixr]) + lfastchoose(_d[iNB], _d[ixb]) - lfastchoose(N, n); if (small_N) _d[iterm] = Math.exp(_d[iterm]); _d[iNR] -= _d[ixr]; _d[iNB] -= _d[ixb]; if (!lowerTail || logP) { p = R_DT_qIv(lowerTail, logP, p); } p *= 1 - 1000 * DBL_EPSILON; /* was 64, but failed on FreeBSD sometimes */ _d[isum] = small_N ? _d[iterm] : Math.exp(_d[iterm]); // for speed, removed if (small_N) out of the while loop return (small_N) ? backendTinyN( _d[isum], _d[iterm], p, _d[ixr], xend, _d[ixb], _d[iNB], _d[iNR] ) : backendBigN( _d[isum], _d[iterm], p, _d[ixr], xend, _d[ixb], _d[iNB], _d[iNR] ); }
jacobbogers/libRmath.js
src/lib/distributions/hypergeometric/qhyper.ts
TypeScript
gpl-3.0
4,360
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Jun 18 18:05:19 BST 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> H-Index (FlexiGraph Reference) </TITLE> <META NAME="date" CONTENT="2010-06-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="H-Index (FlexiGraph Reference)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-7.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-9.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-8.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-8.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">R</A> <A HREF="index-17.html">S</A> <A HREF="index-18.html">T</A> <A HREF="index-19.html">U</A> <A HREF="index-20.html">V</A> <A HREF="index-21.html">W</A> <A HREF="index-22.html">X</A> <A HREF="index-23.html">Y</A> <A HREF="index-24.html">Z</A> <HR> <A NAME="_H_"><!-- --></A><H2> <B>H</B></H2> <DL> <DT><A HREF="../gr/forth/ics/graph/path/PathFilter.html#hamilton()"><B>hamilton()</B></A> - Static method in class gr.forth.ics.graph.path.<A HREF="../gr/forth/ics/graph/path/PathFilter.html" title="class in gr.forth.ics.graph.path">PathFilter</A> <DD><B>Deprecated.</B>&nbsp;&nbsp; <DT><A HREF="../gr/forth/ics/graph/Tuple.html#has(java.lang.Object)"><B>has(Object)</B></A> - Method in interface gr.forth.ics.graph.<A HREF="../gr/forth/ics/graph/Tuple.html" title="interface in gr.forth.ics.graph">Tuple</A> <DD>Returns true if an entry is found (in this tuple, or in its parent) with the specified key, either regular or weak. <DT><A HREF="../gr/forth/ics/graph/event/GraphEvent.html#hashCode()"><B>hashCode()</B></A> - Method in class gr.forth.ics.graph.event.<A HREF="../gr/forth/ics/graph/event/GraphEvent.html" title="class in gr.forth.ics.graph.event">GraphEvent</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/layout/GPoint.html#hashCode()"><B>hashCode()</B></A> - Method in class gr.forth.ics.graph.layout.<A HREF="../gr/forth/ics/graph/layout/GPoint.html" title="class in gr.forth.ics.graph.layout">GPoint</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/layout/GRect.html#hashCode()"><B>hashCode()</B></A> - Method in class gr.forth.ics.graph.layout.<A HREF="../gr/forth/ics/graph/layout/GRect.html" title="class in gr.forth.ics.graph.layout">GRect</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/path/AbstractPath.html#hashCode()"><B>hashCode()</B></A> - Method in class gr.forth.ics.graph.path.<A HREF="../gr/forth/ics/graph/path/AbstractPath.html" title="class in gr.forth.ics.graph.path">AbstractPath</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/algo/transitivity/SuccessorSetFactory.html#hashSetBased()"><B>hashSetBased()</B></A> - Static method in class gr.forth.ics.graph.algo.transitivity.<A HREF="../gr/forth/ics/graph/algo/transitivity/SuccessorSetFactory.html" title="class in gr.forth.ics.graph.algo.transitivity">SuccessorSetFactory</A> <DD>Returns a <code>SuccessorSetFactory</code> that creates successor sets represented as <code>HashSet</code>s. <DT><A HREF="../gr/forth/ics/graph/path/ExpansionFront.html#hasNext()"><B>hasNext()</B></A> - Method in class gr.forth.ics.graph.path.<A HREF="../gr/forth/ics/graph/path/ExpansionFront.html" title="class in gr.forth.ics.graph.path">ExpansionFront</A> <DD><B>Deprecated.</B>&nbsp;&nbsp; <DT><A HREF="../gr/forth/ics/util/AbstractCompoundIterator.html#hasNext()"><B>hasNext()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/AbstractCompoundIterator.html" title="class in gr.forth.ics.util">AbstractCompoundIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html#hasNext()"><B>hasNext()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html" title="class in gr.forth.ics.util">AbstractCompoundListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/FilteringIterator.html#hasNext()"><B>hasNext()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/FilteringIterator.html" title="class in gr.forth.ics.util">FilteringIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/FilteringListIterator.html#hasNext()"><B>hasNext()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/FilteringListIterator.html" title="class in gr.forth.ics.util">FilteringListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/PushBackIterator.html#hasNext()"><B>hasNext()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/PushBackIterator.html" title="class in gr.forth.ics.util">PushBackIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/AbstractCompoundIterator.html#hasNextIterator()"><B>hasNextIterator()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/AbstractCompoundIterator.html" title="class in gr.forth.ics.util">AbstractCompoundIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html#hasNextIterator()"><B>hasNextIterator()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html" title="class in gr.forth.ics.util">AbstractCompoundListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/CompoundIterator.html#hasNextIterator()"><B>hasNextIterator()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/CompoundIterator.html" title="class in gr.forth.ics.util">CompoundIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/CompoundListIterator.html#hasNextIterator()"><B>hasNextIterator()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/CompoundListIterator.html" title="class in gr.forth.ics.util">CompoundListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/algo/DegreeSorter.html#hasNodes(int)"><B>hasNodes(int)</B></A> - Method in class gr.forth.ics.graph.algo.<A HREF="../gr/forth/ics/graph/algo/DegreeSorter.html" title="class in gr.forth.ics.graph.algo">DegreeSorter</A> <DD>Returns whether there are any nodes in the graph with the specified degree. <DT><A HREF="../gr/forth/ics/util/Args.html#hasNoNull(java.lang.Iterable)"><B>hasNoNull(Iterable&lt;?&gt;)</B></A> - Static method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/Args.html" title="class in gr.forth.ics.util">Args</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/Args.html#hasNoNull(java.lang.String, java.lang.Iterable)"><B>hasNoNull(String, Iterable&lt;?&gt;)</B></A> - Static method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/Args.html" title="class in gr.forth.ics.util">Args</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html#hasPrevious()"><B>hasPrevious()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html" title="class in gr.forth.ics.util">AbstractCompoundListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/FilteringListIterator.html#hasPrevious()"><B>hasPrevious()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/FilteringListIterator.html" title="class in gr.forth.ics.util">FilteringListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html#hasPreviousIterator()"><B>hasPreviousIterator()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/AbstractCompoundListIterator.html" title="class in gr.forth.ics.util">AbstractCompoundListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/util/CompoundListIterator.html#hasPreviousIterator()"><B>hasPreviousIterator()</B></A> - Method in class gr.forth.ics.util.<A HREF="../gr/forth/ics/util/CompoundListIterator.html" title="class in gr.forth.ics.util">CompoundListIterator</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/path/Path.html#headEdge()"><B>headEdge()</B></A> - Method in interface gr.forth.ics.graph.path.<A HREF="../gr/forth/ics/graph/path/Path.html" title="interface in gr.forth.ics.graph.path">Path</A> <DD>Returns the first edge of this path. <DT><A HREF="../gr/forth/ics/graph/path/Path.html#headNode()"><B>headNode()</B></A> - Method in interface gr.forth.ics.graph.path.<A HREF="../gr/forth/ics/graph/path/Path.html" title="interface in gr.forth.ics.graph.path">Path</A> <DD>Returns the first node of this path. <DT><A HREF="../gr/forth/ics/graph/path/Path.html#headPath(int)"><B>headPath(int)</B></A> - Method in interface gr.forth.ics.graph.path.<A HREF="../gr/forth/ics/graph/path/Path.html" title="interface in gr.forth.ics.graph.path">Path</A> <DD>Returns a path that starts at the start of this path, and continues for the specified number of steps along this path. <DT><A HREF="../gr/forth/ics/graph/layout/GRect.html#height()"><B>height()</B></A> - Method in class gr.forth.ics.graph.layout.<A HREF="../gr/forth/ics/graph/layout/GRect.html" title="class in gr.forth.ics.graph.layout">GRect</A> <DD>&nbsp; <DT><A HREF="../gr/forth/ics/graph/Hint.html" title="enum in gr.forth.ics.graph"><B>Hint</B></A> - Enum in <A HREF="../gr/forth/ics/graph/package-summary.html">gr.forth.ics.graph</A><DD>Runtime performance hints that can be used by graph implementations.<DT><A HREF="../gr/forth/ics/graph/InspectableGraph.html#hint(gr.forth.ics.graph.Hint)"><B>hint(Hint)</B></A> - Method in interface gr.forth.ics.graph.<A HREF="../gr/forth/ics/graph/InspectableGraph.html" title="interface in gr.forth.ics.graph">InspectableGraph</A> <DD>Provides hints to the graph implementation about desired runtime performance. </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-7.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-9.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-8.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-8.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">R</A> <A HREF="index-17.html">S</A> <A HREF="index-18.html">T</A> <A HREF="index-19.html">U</A> <A HREF="index-20.html">V</A> <A HREF="index-21.html">W</A> <A HREF="index-22.html">X</A> <A HREF="index-23.html">Y</A> <A HREF="index-24.html">Z</A> <HR> </BODY> </HTML>
unidesigner/pyconto
scratch/flexigraph-0.1/dist/javadoc/index-files/index-8.html
HTML
gpl-3.0
15,555
/******************************************************************************* * LogDruid : Generate charts and reports using data gathered in log files * Copyright (C) 2016 Frederic Valente (frederic.valente@gmail.com) * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. *******************************************************************************/ package logdruid.ui.table; import javax.swing.JPanel; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import org.apache.log4j.Logger; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.text.ParseException; import org.apache.commons.lang3.time.FastDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import logdruid.data.Repository; import logdruid.data.record.EventRecording; import logdruid.data.record.MetadataRecording; import logdruid.data.record.Recording; import logdruid.data.record.RecordingItem; import logdruid.data.record.StatRecording; import logdruid.ui.NoProcessingRegexTableRenderer; import logdruid.util.DataMiner; import logdruid.util.PatternCache; public class StatRecordingEditorTable extends JPanel { private static Logger logger = Logger.getLogger(DataMiner.class.getName()); private boolean DEBUG = false; static Matcher m; static ArrayList records = null; private MyTableModel model; private String[] header = { "Name", "Before", "Inside type", "Inside regex", "After", "Active", "Show", "Value" }; private ArrayList<Object[]> data = new ArrayList<Object[]>(); JTable table = null; private String theLine = ""; private JTextPane examplePane; private Repository rep = null; private Recording recording; /** * @wbp.parser.constructor */ @SuppressWarnings("unchecked") public StatRecordingEditorTable(JTextPane textPane) { super(new GridLayout(1, 0)); model = new MyTableModel(data, header); table = new JTable(model); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setFont(new Font("SansSerif", Font.PLAIN, 11)); // table.setPreferredScrollableViewportSize(new Dimension(500, 200)); table.setPreferredScrollableViewportSize(table.getPreferredSize()); table.setFillsViewportHeight(true); this.theLine = textPane.getText(); this.examplePane = textPane; // Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); // Set up column sizes. initColumnSizes(table); // Fiddle with the Type column's cell editors/renderers. setUpTypeColumn(table, table.getColumnModel().getColumn(2)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(1)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(3)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(4)); // Add the scroll pane to this panel. add(scrollPane); //Add(); FixValues(); } public StatRecordingEditorTable(Repository repo, Recording re, JTextPane textPane) { super(new GridLayout(1, 0)); this.examplePane = textPane; model = new MyTableModel(data, header); table = new JTable(model); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); rep = repo; this.theLine = textPane.getText(); recording = re; // Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); // Set up column sizes. initColumnSizes(table); // Fiddle with the Type column's cell editors/renderers. setUpTypeColumn(table, table.getColumnModel().getColumn(2)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(3)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(1)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(4)); // Add the scroll pane to this panel. add(scrollPane); records = ((StatRecording) re).getRecordingItem(); // Collections.sort(records); if (records != null) { Iterator<RecordingItem> it = records.iterator(); while (it.hasNext()) { RecordingItem rI = it.next(); String inside=""; inside= DataMiner.getMainRegex( rI.getType(),rI.getInside(), repo.getDateFormat(re.getDateFormatID())) ; logger.debug("inside: " + inside); data.add(new Object[] { rI.getName(), rI.getBefore(), rI.getType(), inside,rI.getAfter(), rI.isSelected(),rI.isShow(), "" }); logger.debug("added: " + rI.getName()); } FixValues(); } } public void FixValues() { String patternString = ""; Matcher matcher; PatternCache patternCache=new PatternCache(); Iterator<Object[]> it = data.iterator(); Object[] obj; while (it.hasNext()) { obj = (Object[])it.next(); String stBefore = (String) obj[1]; String stType = (String) obj[2]; String stInside = (String) obj[3]; String stAfter = (String) obj[4]; logger.debug("stType: " + stType); if (stType.equals("date") && rep.getDateFormat(recording.getDateFormatID()).getPattern() != null) { patternString += stBefore + "(" + rep.getDateFormat(recording.getDateFormatID()).getPattern() + ")" + stAfter; logger.debug("getTypeString(stType) getPattern -: " + rep.getDateFormat(recording.getDateFormatID()).getPattern()); logger.debug("getTypeString(stType) getDateFormat -: " + rep.getDateFormat(recording.getDateFormatID()).getDateFormat()); } else { if (stType.equals("manual")){ patternString += stBefore + "(" + stInside + ")" + stAfter; logger.debug("getTypeString(stType) -: " + stInside); }else{ patternString += stBefore + "(" + DataMiner.getTypeString(stType) + ")" + stAfter; logger.debug("getTypeString(stType) -: " + DataMiner.getTypeString(stType)); } } } try { logger.debug("theLine: " + examplePane.getText()); logger.debug("patternString: " + patternString); Highlighter h = examplePane.getHighlighter(); h.removeAllHighlights(); int currIndex = 0; String[] lines = examplePane.getText().split(System.getProperty("line.separator")); if (lines.length>=1){ for (int i=0; i<lines.length ; i++){ matcher = patternCache.getPattern(patternString,recording.isCaseSensitive()).matcher(lines[i]); if (matcher.find()) { // int currIndex = 0; // doc.insertString(doc.getLength(),line+"\n", null); for (int i2 = 1; i2 <= matcher.groupCount(); i2++) { model.setValueAt(matcher.group(i2), i2 - 1, 7); h.addHighlight(currIndex+matcher.start(i2), +currIndex+matcher.end(i2), new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE)); } } logger.debug("currIndex: " + currIndex + "matcher.end(i2): " + lines[i].length()+",l: "+lines[i]); currIndex += lines[i].length()+1 ; } } } catch (Exception e1) { e1.printStackTrace(); // System.exit(1); } } private void initColumnSizes(JTable theTable) { TableColumn column = null; Component comp = null; int headerWidth = 0; int cellWidth = 0; TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer(); for (int i = 0; i < 8; i++) { column = theTable.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0); headerWidth = comp.getPreferredSize().width; cellWidth = comp.getPreferredSize().width; if (DEBUG) { logger.debug("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth); } column.setPreferredWidth(Math.max(headerWidth, cellWidth)); } } public void setUpInsideRegexColumn(JTable theTable, TableColumn typeColumn) { DefaultTableCellRenderer renderer = new NoProcessingRegexTableRenderer(); // renderer.setBackground(Color.GRAY); typeColumn.setCellRenderer(renderer); } public void setUpTypeColumn(JTable theTable, TableColumn typeColumn) { // Set up the editor for the Type cells. JComboBox<String> comboBox = new JComboBox<String>(); comboBox.addItem("date"); comboBox.addItem("double"); comboBox.addItem("long"); comboBox.addItem("manual"); comboBox.addItem("percent"); comboBox.addItem("string"); comboBox.addItem("stringminimum"); comboBox.addItem("word"); typeColumn.setCellEditor(new DefaultCellEditor(comboBox)); // Set up tool tips for the Type cells. DefaultTableCellRenderer renderer = new NoProcessingRegexTableRenderer(); renderer.setToolTipText("Click for combo box"); typeColumn.setCellRenderer(renderer); } class MyTableModel extends AbstractTableModel { private String[] header; private ArrayList<Object[]> data; public MyTableModel(ArrayList<Object[]> data, String[] header) { this.header = header; this.data = data; } @Override public int getColumnCount() { if (header == null) { return 0; } else return header.length; } @Override public String getColumnName(int column) { return header[column]; } @Override public int getRowCount() { return data.size(); } @Override public Object getValueAt(int row, int column) { return data.get(row)[column]; } @Override public void setValueAt(Object value, int row, int column) { data.get(row)[column] = value; fireTableCellUpdated(row, column); } public Class<? extends Object> getColumnClass(int c) { if (getValueAt(0, c)!=null){ return getValueAt(0, c).getClass(); } else return String.class; } public boolean isCellEditable(int row, int col) { // Note that the data/cell address is constant, // no matt&er where the cell appears onscreen. if (col > 6) { return false; } else {if (col==3 && !data.get(row)[2].equals("manual")){ return false; } else{ return true; } } } } public ArrayList<RecordingItem> getRecordingItems() { ArrayList<RecordingItem> toReturn = new ArrayList<RecordingItem>(); for (int i = 0; i < data.size(); i++) { // model.getRowCount() toReturn.add(new RecordingItem((String) model.getValueAt(i, 0), (String) model.getValueAt(i, 1), (String) model.getValueAt(i, 2), (String) model.getValueAt(i,3), (String) model.getValueAt(i, 4),(Boolean) model.getValueAt(i, 5), (Boolean) model.getValueAt(i, 6), (String) model.getValueAt(i, 7))); } return toReturn; } public void Add() { data.add(new Object[] { "default", ".*", "long",DataMiner.getTypeString("long"), "", Boolean.TRUE,Boolean.TRUE, "" }); table.repaint(); } public void Insert() { data.add(((table.getSelectedRow() != -1) ? table.convertRowIndexToModel(table.getSelectedRow()) : -1), new Object[] { "default", ".*", "long",DataMiner.getTypeString("long"), "", Boolean.TRUE,Boolean.TRUE, "" }); table.repaint(); } public void Remove() { data.remove(((table.getSelectedRow() != -1) ? table.convertRowIndexToModel(table.getSelectedRow()) : -1)); table.repaint(); } }
fvalente/LogDruid
src/logdruid/ui/table/StatRecordingEditorTable.java
Java
gpl-3.0
11,941
import React from 'react'; import { connect } from 'react-redux'; import { View } from 'react-native'; import sb from 'react-native-style-block'; import { TButton, TFormGroup } from '../components/TComponent'; import { showLoading, showAlert, hideAlert } from '@shared/redux/actions/ui'; import { register } from '@shared/redux/actions/user'; import { StackScreenProps } from '@react-navigation/stack'; import { RootStackParamList } from '@app/router'; interface Props extends StackScreenProps<RootStackParamList, 'Register'> { dispatch: any; } interface State { username: string; password: string; passwordRepeat: string; } class RegisterScreen extends React.Component<Props, State> { constructor(props) { super(props); this.state = { username: '', password: '', passwordRepeat: '', }; } checkInputErr() { const { username, password, passwordRepeat } = this.state; if (!username) { return '用户名不能为空'; } if (!/^[A-Za-z\d]{5,16}$/.test(username)) { return '用户名必须为5到16位英文或数字'; } if (!password) { return '密码不能为空'; } if (!/^[A-Za-z\d]{5,16}$/.test(password)) { return '密码必须为5到16位英文或数字'; } if (password !== passwordRepeat) { return '重复密码不一致'; } return ''; } handleRegister() { const err = this.checkInputErr(); if (err) { this.props.dispatch( showAlert({ title: '格式错误', content: err, }) ); } else { this.props.dispatch(showLoading()); const username = this.state.username; const password = this.state.password; this.props.dispatch( register(username, password, () => { this.props.dispatch( showAlert({ content: '注册成功', onConfirm: () => { this.props.dispatch(hideAlert()); this.props.navigation.goBack(); }, }) ); }) ); } } render() { return ( <View style={styles.container}> <TFormGroup label="用户名" value={this.state.username} onChangeText={(username) => this.setState({ username })} input={{ placeholder: '请输入用户名', }} /> <TFormGroup label="密码" value={this.state.password} onChangeText={(password) => this.setState({ password })} input={{ placeholder: '请输入密码', secureTextEntry: true, }} /> <TFormGroup label="重复密码" value={this.state.passwordRepeat} onChangeText={(passwordRepeat) => this.setState({ passwordRepeat })} input={{ placeholder: '请再次输入密码', secureTextEntry: true, }} /> <TButton onPress={() => this.handleRegister()}>成为祭品</TButton> </View> ); } } const styles = { container: [ // sb.alignCenter(), sb.flex(), sb.padding(20, 20, 0), ], }; export default connect()(RegisterScreen);
TRPGEngine/Client
src/app/src/screens/RegisterScreen.tsx
TypeScript
gpl-3.0
3,227
// // _ _ ______ _ _ _ _ _ _ _ // | \ | | | ____| | (_) | (_) | | | | // | \| | ___ | |__ __| |_| |_ _ _ __ __ _| | | | // | . ` |/ _ \ | __| / _` | | __| | '_ \ / _` | | | | // | |\ | (_) | | |___| (_| | | |_| | | | | (_| |_|_|_| // |_| \_|\___/ |______\__,_|_|\__|_|_| |_|\__, (_|_|_) // __/ | // |___/ // // This file is auto-generated. Do not edit manually // // Copyright 2013 Automatak LLC // // Automatak LLC (www.automatak.com) licenses this file // to you under the the Apache License Version 2.0 (the "License"): // // http://www.apache.org/licenses/LICENSE-2.0.html // #include "opendnp3/gen/LinkFunction.h" namespace opendnp3 { uint8_t LinkFunctionToType(LinkFunction arg) { return static_cast<uint8_t>(arg); } LinkFunction LinkFunctionFromType(uint8_t arg) { switch(arg) { case(0x40): return LinkFunction::PRI_RESET_LINK_STATES; case(0x42): return LinkFunction::PRI_TEST_LINK_STATES; case(0x43): return LinkFunction::PRI_CONFIRMED_USER_DATA; case(0x44): return LinkFunction::PRI_UNCONFIRMED_USER_DATA; case(0x49): return LinkFunction::PRI_REQUEST_LINK_STATUS; case(0x0): return LinkFunction::SEC_ACK; case(0x1): return LinkFunction::SEC_NACK; case(0xB): return LinkFunction::SEC_LINK_STATUS; case(0xF): return LinkFunction::SEC_NOT_SUPPORTED; default: return LinkFunction::INVALID; } } char const* LinkFunctionToString(LinkFunction arg) { switch(arg) { case(LinkFunction::PRI_RESET_LINK_STATES): return "PRI_RESET_LINK_STATES"; case(LinkFunction::PRI_TEST_LINK_STATES): return "PRI_TEST_LINK_STATES"; case(LinkFunction::PRI_CONFIRMED_USER_DATA): return "PRI_CONFIRMED_USER_DATA"; case(LinkFunction::PRI_UNCONFIRMED_USER_DATA): return "PRI_UNCONFIRMED_USER_DATA"; case(LinkFunction::PRI_REQUEST_LINK_STATUS): return "PRI_REQUEST_LINK_STATUS"; case(LinkFunction::SEC_ACK): return "SEC_ACK"; case(LinkFunction::SEC_NACK): return "SEC_NACK"; case(LinkFunction::SEC_LINK_STATUS): return "SEC_LINK_STATUS"; case(LinkFunction::SEC_NOT_SUPPORTED): return "SEC_NOT_SUPPORTED"; default: return "INVALID"; } } }
thiagoralves/OpenPLC_v2
dnp3/cpp/libs/src/opendnp3/gen/LinkFunction.cpp
C++
gpl-3.0
2,376
/* MAVLink logfile transfer functions */ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <AP_HAL/AP_HAL.h> #include <DataFlash/DataFlash.h> #include <GCS_MAVLink/GCS.h> // for LOG_ENTRY extern const AP_HAL::HAL& hal; // We avoid doing log messages when timing is critical: bool DataFlash_Class::should_handle_log_message() { if (!WritesEnabled()) { // this is currently used as a proxy for "in_mavlink_delay" return false; } if (vehicle_is_armed()) { return false; } return true; } /** handle all types of log download requests from the GCS */ void DataFlash_Class::handle_log_message(GCS_MAVLINK &link, mavlink_message_t *msg) { if (!should_handle_log_message()) { return; } switch (msg->msgid) { case MAVLINK_MSG_ID_LOG_REQUEST_LIST: handle_log_request_list(link, msg); break; case MAVLINK_MSG_ID_LOG_REQUEST_DATA: handle_log_request_data(link, msg); break; case MAVLINK_MSG_ID_LOG_ERASE: handle_log_request_erase(link, msg); break; case MAVLINK_MSG_ID_LOG_REQUEST_END: handle_log_request_end(link, msg); break; } } /** handle all types of log download requests from the GCS */ void DataFlash_Class::handle_log_request_list(GCS_MAVLINK &link, mavlink_message_t *msg) { if (_log_sending_link != nullptr) { link.send_text(MAV_SEVERITY_INFO, "Log download in progress"); return; } mavlink_log_request_list_t packet; mavlink_msg_log_request_list_decode(msg, &packet); _log_listing = false; _log_sending = false; _log_num_logs = get_num_logs(); if (_log_num_logs == 0) { _log_next_list_entry = 0; _log_last_list_entry = 0; } else { _log_next_list_entry = packet.start; _log_last_list_entry = packet.end; if (_log_last_list_entry > _log_num_logs) { _log_last_list_entry = _log_num_logs; } if (_log_next_list_entry < 1) { _log_next_list_entry = 1; } } _log_listing = true; _log_sending_link = &link; handle_log_send_listing(); } /** handle request for log data */ void DataFlash_Class::handle_log_request_data(GCS_MAVLINK &link, mavlink_message_t *msg) { if (_log_sending_link != nullptr) { // some GCS (e.g. MAVProxy) attempt to stream request_data // messages when they're filling gaps in the downloaded logs. // This channel check avoids complaining to them, at the cost // of silently dropping any repeated attempts to start logging if (_log_sending_link->get_chan() != link.get_chan()) { link.send_text(MAV_SEVERITY_INFO, "Log download in progress"); } return; } mavlink_log_request_data_t packet; mavlink_msg_log_request_data_decode(msg, &packet); _in_log_download = true; _log_listing = false; if (!_log_sending || _log_num_data != packet.id) { _log_sending = false; uint16_t num_logs = get_num_logs(); if (packet.id > num_logs || packet.id < 1) { return; } uint32_t time_utc, size; get_log_info(packet.id, size, time_utc); _log_num_data = packet.id; _log_data_size = size; uint16_t end; get_log_boundaries(packet.id, _log_data_page, end); } _log_data_offset = packet.ofs; if (_log_data_offset >= _log_data_size) { _log_data_remaining = 0; } else { _log_data_remaining = _log_data_size - _log_data_offset; } if (_log_data_remaining > packet.count) { _log_data_remaining = packet.count; } _log_sending = true; _log_sending_link = &link; handle_log_send(); } /** handle request to erase log data */ void DataFlash_Class::handle_log_request_erase(GCS_MAVLINK &link, mavlink_message_t *msg) { // mavlink_log_erase_t packet; // mavlink_msg_log_erase_decode(msg, &packet); EraseAll(); } /** handle request to stop transfer and resume normal logging */ void DataFlash_Class::handle_log_request_end(GCS_MAVLINK &link, mavlink_message_t *msg) { mavlink_log_request_end_t packet; mavlink_msg_log_request_end_decode(msg, &packet); _in_log_download = false; _log_sending = false; _log_sending_link = nullptr; } /** trigger sending of log messages if there are some pending */ void DataFlash_Class::handle_log_send() { if (_log_sending_link == nullptr) { return; } if (hal.util->get_soft_armed()) { // might be flying return; } if (_log_listing) { handle_log_send_listing(); } if (!_log_sending) { return; } #if CONFIG_HAL_BOARD == HAL_BOARD_SITL // assume USB speeds in SITL for the purposes of log download const uint8_t num_sends = 40; #else uint8_t num_sends = 1; if (_log_sending_link->is_high_bandwidth() && hal.gpio->usb_connected()) { // when on USB we can send a lot more data num_sends = 250; } else if (_log_sending_link->have_flow_control()) { #if CONFIG_HAL_BOARD == HAL_BOARD_LINUX num_sends = 80; #else num_sends = 10; #endif } #endif for (uint8_t i=0; i<num_sends; i++) { if (_log_sending) { if (!handle_log_send_data()) break; } } } /** trigger sending of log messages if there are some pending */ void DataFlash_Class::handle_log_send_listing() { if (!HAVE_PAYLOAD_SPACE(_log_sending_link->get_chan(), LOG_ENTRY)) { // no space return; } if (AP_HAL::millis() - _log_sending_link->get_last_heartbeat_time() > 3000) { // give a heartbeat a chance return; } uint32_t size, time_utc; if (_log_next_list_entry == 0) { size = 0; time_utc = 0; } else { get_log_info(_log_next_list_entry, size, time_utc); } mavlink_msg_log_entry_send(_log_sending_link->get_chan(), _log_next_list_entry, _log_num_logs, _log_last_list_entry, time_utc, size); if (_log_next_list_entry == _log_last_list_entry) { _log_listing = false; _log_sending_link = nullptr; } else { _log_next_list_entry++; } } /** trigger sending of log data if there are some pending */ bool DataFlash_Class::handle_log_send_data() { if (!HAVE_PAYLOAD_SPACE(_log_sending_link->get_chan(), LOG_DATA)) { // no space return false; } if (AP_HAL::millis() - _log_sending_link->get_last_heartbeat_time() > 3000) { // give a heartbeat a chance return false; } int16_t ret = 0; uint32_t len = _log_data_remaining; mavlink_log_data_t packet; if (len > MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN) { len = MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN; } ret = get_log_data(_log_num_data, _log_data_page, _log_data_offset, len, packet.data); if (ret < 0) { // report as EOF on error ret = 0; } if (ret < MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN) { memset(&packet.data[ret], 0, MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN-ret); } packet.ofs = _log_data_offset; packet.id = _log_num_data; packet.count = ret; _mav_finalize_message_chan_send(_log_sending_link->get_chan(), MAVLINK_MSG_ID_LOG_DATA, (const char *)&packet, MAVLINK_MSG_ID_LOG_DATA_MIN_LEN, MAVLINK_MSG_ID_LOG_DATA_LEN, MAVLINK_MSG_ID_LOG_DATA_CRC); _log_data_offset += len; _log_data_remaining -= len; if (ret < MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN || _log_data_remaining == 0) { _log_sending = false; _in_log_download = false; _log_sending_link = nullptr; } return true; }
dut09/ardupilot
libraries/DataFlash/DataFlash_MAVLinkLogTransfer.cpp
C++
gpl-3.0
8,640
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "datapoint/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
jacobtomlinson/datapoint-python
datapoint/_version.py
Python
gpl-3.0
18,444
<?php class Wsu_Networksecurities_Sso_YahoologinController extends Wsu_Networksecurities_Controller_Sso_Abstract { // url to login public function loginAction() { $customerHelper = Mage::helper('wsu_networksecurities/customer'); $yahoologin = Mage::getModel('wsu_networksecurities/sso_yahoologin'); $hasSession = $yahoologin->hasSession(); if($hasSession == FALSE) { $authUrl = $yahoologin->getAuthUrl(); $this->_redirectUrl($authUrl); }else{ $session = $yahoologin->getSession(); $userSession = $session->getSessionedUser(); $user_info = $userSession->loadProfile(); if(count($user_info)) { $this->handleCustomer($user_info); }else{ Mage::getSingleton('core/session')->addError($this->__('Login failed as you have not granted access.')); $customerHelper->setJsRedirect(Mage::getBaseUrl()); } } } public function makeCustomerData($user_info) { $data = array(); $emails = $user_info->emails; if(isset($emails)){ foreach($emails as $email) { if($email->primary == 1){ $data['email'] = $email->handle; } } } $data['username'] = $user_info->nickname; if(!isset($user['email'])){ $data['email']=$data['username'].'@yahoo.com'; } $data['firstname'] = $user_info->givenName; $data['lastname'] = $user_info->familyName; if(!isset($data['firstname'])){ $data['firstname']=$data['username']; } if(!isset($user['lastname'])){ $data['lastname']=''; } $gender = $user_info->gender; if(isset($gender)){ $data['gender'] = $gender=="M" ? '1' : '2'; } $birthYear = $user_info->birthYear; if(isset($birthYear)){ $data['dob'] = '1/1/'.$birthYear; } $data['provider']="yahoo"; $data['email']=$email; $data['firstname']=$frist_name; $data['lastname']=$last_name; return $data; } }
washingtonstateuniversity/WSUMAGE-networksecurities
app/code/local/Wsu/Networksecurities/controllers/Sso/YahoologinController.php
PHP
gpl-3.0
1,838
# -*- coding: utf-8 -*- """ Common structures and functions used by other scripts. """ from xml.etree import cElementTree as ET str_to_entailment = {'none': 0, 'entailment': 1, 'paraphrase': 2} entailment_to_str = {v: k for k, v in str_to_entailment.items()} class Pair(object): ''' Class representing a pair of texts from SICK or RTE. It is meant to be used as an abstract representation for both. ''' def __init__(self, t, h, id_, entailment, similarity): ''' :param t: string with the text :param h: string with the hypothesis :param id_: int indicating id in the original file :param entailment: int indicating entailment class :param similarity: float ''' self.t = t self.h = h self.id = id_ self.entailment = entailment self.similarity = similarity def read_xml(filename, need_labels): ''' Read an RTE XML file and return a list of Pair objects. :param filename: name of the file to read :param need_labels: boolean indicating if labels should be present ''' pairs = [] tree = ET.parse(filename) root = tree.getroot() for xml_pair in root.iter('pair'): t = xml_pair.find('t').text h = xml_pair.find('h').text attribs = dict(xml_pair.items()) id_ = int(attribs['id']) if 'entailment' in attribs: ent_string = attribs['entailment'].lower() try: ent_value = str_to_entailment[ent_string] except ValueError: msg = 'Unexpected value for attribute "entailment" at pair {}: {}' raise ValueError(msg.format(id_, ent_string)) else: ent_value = None if 'similarity' in attribs: similarity = float(attribs['similarity']) else: similarity = None if need_labels and similarity is None and ent_value is None: msg = 'Missing both entailment and similarity values for pair {}'.format(id_) raise ValueError(msg) pair = Pair(t, h, id_, ent_value, similarity) pairs.append(pair) return pairs
nathanshartmann/portuguese_word_embeddings
sentence_similarity/utils/commons.py
Python
gpl-3.0
2,224
#include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <map> #include <climits> using namespace std; #define all(t) begin(t), end(t) #define sp << " " << using ul = unsigned long; vector<bool> X; vector<int> sieve; template <typename I> void make_sieve(I MAX) { //create table of primes I M = MAX>>1; if (!(MAX & 1)) M--; X.resize(M+1,true); I k; for (I j=1,p=3,q=4;j<=M;j++, p+=2, q+=2*p-2) { if (X[j]==0) continue; else k=q; while (k <= M) { X[k] = 0; k += p; } } for (I i=5;i<(I)X.size();i++) if (X[i]) sieve.push_back(2*i+1); } template <typename R> R gcd(R a, R b) { while (true) { if (b==0) return a; a %= b; if (a==0) return b; b %= a; } } struct ratio { ul p, q; ratio(): p(0), q(1) {} ratio(ul a, ul b) : p(a), q(b) {} ratio simplify() { ul c = gcd(p, q); p /= c; q /= c; return *this; } ratio operator+(const ratio& b) { ratio a; a.p = p * b.q + q * b.p; a.q = q * b.q; a.simplify(); return a; } ratio operator-(const ratio& b) { ratio a; a.p = p * b.q - q * b.p; a.q = q * b.q; a.simplify(); return a; } void operator=(const ratio& b) { p = b.p; q = b.q; } bool operator<(const ratio& b) const { return p*b.q < q*b.p; } bool operator==(const ratio& b) const { return !(*this < b) && !(b < *this); } bool operator<=(const ratio& b) const { return (*this < b) || (*this == b); } bool operator!=(const ratio& b) const { return !(*this == b); } }; vector<pair<int, vector<ratio>>> Dom; ostream& operator<<(ostream& os, const ratio& r) { os << r.p << '/' << r.q; return os; } template <typename I> void print(const vector<I>& a) { for (auto e: a) cout << e << ' '; cout << endl; } void visit(vector<size_t>& x) { auto il = Dom.begin(); for (size_t i=0;i < Dom.size();i++, il++) if ((il->second)[x[i]] != ratio()) cout << il->first << ' '; cout << endl; } int main() { int N, D; cin >> D >> N; make_sieve(N); //B1 Initialize for (int i=2;i<=N;i++) { if (i<11) {Dom.push_back(make_pair(i,vector<ratio>{ratio(), ratio(1,i*i)})); continue;} if (i == 52) { Dom.push_back(make_pair(i,vector<ratio>{ratio(), ratio(1,169)+ratio(1,169*9)+ratio(1,169*16)})); continue; } if (i == 91) { Dom.push_back(make_pair(i,vector<ratio>{ratio(), ratio(1,169*4)+ratio(1,169*25)+ratio(1,169*49)})); continue; } if (i == 95) { Dom.push_back(make_pair(i,vector<ratio>{ratio(), ratio(1,361*4)+ratio(1,361*9)+ratio(1,361*25)})); continue; } if (i == 99) { Dom.push_back(make_pair(i,vector<ratio>{ratio(), ratio(1,121*4)+ratio(1,121*9)+ratio(1,121*81), ratio(1,121)+ratio(1,121*9)+ratio(1,121*16)+ratio(1,121*36)+ratio(1,121*81), ratio(1,121)+ratio(1,121*25)+ratio(1,121*49)+ratio(1,121*64)+ratio(1,121*81)})); continue; } bool use = true; for (size_t j=0;j < sieve.size() && sieve[j]<=i;j++) { if (i%sieve[j]==0) {use = false; break;} } if (use) { Dom.push_back(make_pair(i,vector<ratio> {ratio(), ratio(1,i*i)})); } } //for (auto e: Dom) {cout << e.first << ": "; print(e.second);cout << endl;} vector<ratio> S(Dom.size()+1); int n = Dom.size(); int l{0}; int i = n-1; ratio d(1, D); for (auto it = Dom.rbegin(); it != Dom.rend(); it++, i--) { S[i] = S[i+1] + it->second.back(); } vector<size_t> x(n,0); int cnt{0}; ratio sigma; B2: if (l == n) { visit(x); cnt++; l--; goto B5; } x[l] = 0; B3: sigma = sigma + Dom[l].second[x[l]]; if ((sigma < d && d == sigma + S[l+1])|| sigma == d) { l++; goto B2;}//found solution if (l<n-1 && sigma < d && d < sigma + S[l+1]) { l++; goto B2;} B4://set x[l] to the next larger element if (x[l] < Dom[l].second.size()-1) { x[l]++; goto B3;} B5: l--; if (l>=0) { /*downdata by undoing changes made in B3 and return to B4*/ sigma = sigma - Dom[l+1].second[x[l+1]]; goto B4; } cout << cnt << endl; }
frits-scholer/pr
pr152/p152_v2.cpp
C++
gpl-3.0
4,242
// Type definitions for Google Drive API v3 3.0 // Project: https://developers.google.com/drive/ // Definitions by: Bolisov Alexey <https://github.com/Bolisov> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/drive/v3/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Drive API v3 */ function load(name: "drive", version: "v3"): PromiseLike<void>; function load(name: "drive", version: "v3", callback: () => any): void; const about: drive.AboutResource; const changes: drive.ChangesResource; const channels: drive.ChannelsResource; const comments: drive.CommentsResource; const files: drive.FilesResource; const permissions: drive.PermissionsResource; const replies: drive.RepliesResource; const revisions: drive.RevisionsResource; const teamdrives: drive.TeamdrivesResource; namespace drive { interface About { /** Whether the user has installed the requesting app. */ appInstalled?: boolean; /** A map of source MIME type to possible targets for all supported exports. */ exportFormats?: Record<string, string[]>; /** The currently supported folder colors as RGB hex strings. */ folderColorPalette?: string[]; /** A map of source MIME type to possible targets for all supported imports. */ importFormats?: Record<string, string[]>; /** Identifies what kind of resource this is. Value: the fixed string "drive#about". */ kind?: string; /** A map of maximum import sizes by MIME type, in bytes. */ maxImportSizes?: Record<string, string>; /** The maximum upload size in bytes. */ maxUploadSize?: string; /** The user's storage quota limits and usage. All fields are measured in bytes. */ storageQuota?: { /** The usage limit, if applicable. This will not be present if the user has unlimited storage. */ limit?: string; /** The total usage across all services. */ usage?: string; /** The usage by all files in Google Drive. */ usageInDrive?: string; /** The usage by trashed files in Google Drive. */ usageInDriveTrash?: string; }; /** A list of themes that are supported for Team Drives. */ teamDriveThemes?: Array<{ /** A link to this Team Drive theme's background image. */ backgroundImageLink?: string; /** The color of this Team Drive theme as an RGB hex string. */ colorRgb?: string; /** The ID of the theme. */ id?: string; }>; /** The authenticated user. */ user?: User; } interface Change { /** The updated state of the file. Present if the type is file and the file has not been removed from this list of changes. */ file?: File; /** The ID of the file which has changed. */ fileId?: string; /** Identifies what kind of resource this is. Value: the fixed string "drive#change". */ kind?: string; /** Whether the file or Team Drive has been removed from this list of changes, for example by deletion or loss of access. */ removed?: boolean; /** * The updated state of the Team Drive. Present if the type is teamDrive, the user is still a member of the Team Drive, and the Team Drive has not been * removed. */ teamDrive?: TeamDrive; /** The ID of the Team Drive associated with this change. */ teamDriveId?: string; /** The time of this change (RFC 3339 date-time). */ time?: string; /** The type of the change. Possible values are file and teamDrive. */ type?: string; } interface ChangeList { /** The list of changes. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ changes?: Change[]; /** Identifies what kind of resource this is. Value: the fixed string "drive#changeList". */ kind?: string; /** The starting page token for future changes. This will be present only if the end of the current changes list has been reached. */ newStartPageToken?: string; /** * The page token for the next page of changes. This will be absent if the end of the changes list has been reached. If the token is rejected for any * reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; } interface Channel { /** The address where notifications are delivered for this channel. */ address?: string; /** Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. */ expiration?: string; /** A UUID or similar unique string that identifies this channel. */ id?: string; /** Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". */ kind?: string; /** Additional parameters controlling delivery channel behavior. Optional. */ params?: Record<string, string>; /** A Boolean value to indicate whether payload is wanted. Optional. */ payload?: boolean; /** An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. */ resourceId?: string; /** A version-specific identifier for the watched resource. */ resourceUri?: string; /** An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. */ token?: string; /** The type of delivery mechanism used for this channel. */ type?: string; } interface Comment { /** A region of the document represented as a JSON string. See anchor documentation for details on how to define and interpret anchor properties. */ anchor?: string; /** The user who created the comment. */ author?: User; /** The plain text content of the comment. This field is used for setting the content, while htmlContent should be displayed. */ content?: string; /** The time at which the comment was created (RFC 3339 date-time). */ createdTime?: string; /** Whether the comment has been deleted. A deleted comment has no content. */ deleted?: boolean; /** The content of the comment with HTML formatting. */ htmlContent?: string; /** The ID of the comment. */ id?: string; /** Identifies what kind of resource this is. Value: the fixed string "drive#comment". */ kind?: string; /** The last time the comment or any of its replies was modified (RFC 3339 date-time). */ modifiedTime?: string; /** * The file content to which the comment refers, typically within the anchor region. For a text file, for example, this would be the text at the location * of the comment. */ quotedFileContent?: { /** The MIME type of the quoted content. */ mimeType?: string; /** The quoted content itself. This is interpreted as plain text if set through the API. */ value?: string; }; /** The full list of replies to the comment in chronological order. */ replies?: Reply[]; /** Whether the comment has been resolved by one of its replies. */ resolved?: boolean; } interface CommentList { /** The list of comments. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ comments?: Comment[]; /** Identifies what kind of resource this is. Value: the fixed string "drive#commentList". */ kind?: string; /** * The page token for the next page of comments. This will be absent if the end of the comments list has been reached. If the token is rejected for any * reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; } interface File { /** * A collection of arbitrary key-value pairs which are private to the requesting app. * Entries with null values are cleared in update and copy requests. */ appProperties?: Record<string, string>; /** Capabilities the current user has on this file. Each capability corresponds to a fine-grained action that a user may take. */ capabilities?: { /** Whether the current user can add children to this folder. This is always false when the item is not a folder. */ canAddChildren?: boolean; /** Whether the current user can change whether viewers can copy the contents of this file. */ canChangeViewersCanCopyContent?: boolean; /** Whether the current user can comment on this file. */ canComment?: boolean; /** * Whether the current user can copy this file. For a Team Drive item, whether the current user can copy non-folder descendants of this item, or this item * itself if it is not a folder. */ canCopy?: boolean; /** Whether the current user can delete this file. */ canDelete?: boolean; /** Whether the current user can download this file. */ canDownload?: boolean; /** Whether the current user can edit this file. */ canEdit?: boolean; /** Whether the current user can list the children of this folder. This is always false when the item is not a folder. */ canListChildren?: boolean; /** Whether the current user can move this item into a Team Drive. If the item is in a Team Drive, this field is equivalent to canMoveTeamDriveItem. */ canMoveItemIntoTeamDrive?: boolean; /** * Whether the current user can move this Team Drive item by changing its parent. Note that a request to change the parent for this item may still fail * depending on the new parent that is being added. Only populated for Team Drive files. */ canMoveTeamDriveItem?: boolean; /** * Whether the current user can read the revisions resource of this file. For a Team Drive item, whether revisions of non-folder descendants of this item, * or this item itself if it is not a folder, can be read. */ canReadRevisions?: boolean; /** Whether the current user can read the Team Drive to which this file belongs. Only populated for Team Drive files. */ canReadTeamDrive?: boolean; /** Whether the current user can remove children from this folder. This is always false when the item is not a folder. */ canRemoveChildren?: boolean; /** Whether the current user can rename this file. */ canRename?: boolean; /** Whether the current user can modify the sharing settings for this file. */ canShare?: boolean; /** Whether the current user can move this file to trash. */ canTrash?: boolean; /** Whether the current user can restore this file from trash. */ canUntrash?: boolean; }; /** Additional information about the content of the file. These fields are never populated in responses. */ contentHints?: { /** Text to be indexed for the file to improve fullText queries. This is limited to 128KB in length and may contain HTML elements. */ indexableText?: string; /** A thumbnail for the file. This will only be used if Drive cannot generate a standard thumbnail. */ thumbnail?: { /** The thumbnail data encoded with URL-safe Base64 (RFC 4648 section 5). */ image?: string; /** The MIME type of the thumbnail. */ mimeType?: string; }; }; /** The time at which the file was created (RFC 3339 date-time). */ createdTime?: string; /** A short description of the file. */ description?: string; /** Whether the file has been explicitly trashed, as opposed to recursively trashed from a parent folder. */ explicitlyTrashed?: boolean; /** The final component of fullFileExtension. This is only available for files with binary content in Drive. */ fileExtension?: string; /** * The color for a folder as an RGB hex string. The supported colors are published in the folderColorPalette field of the About resource. * If an unsupported color is specified, the closest color in the palette will be used instead. */ folderColorRgb?: string; /** * The full file extension extracted from the name field. May contain multiple concatenated extensions, such as "tar.gz". This is only available for files * with binary content in Drive. * This is automatically updated when the name field changes, however it is not cleared if the new name does not contain a valid extension. */ fullFileExtension?: string; /** Whether any users are granted file access directly on this file. This field is only populated for Team Drive files. */ hasAugmentedPermissions?: boolean; /** * Whether this file has a thumbnail. This does not indicate whether the requesting app has access to the thumbnail. To check access, look for the * presence of the thumbnailLink field. */ hasThumbnail?: boolean; /** The ID of the file's head revision. This is currently only available for files with binary content in Drive. */ headRevisionId?: string; /** A static, unauthenticated link to the file's icon. */ iconLink?: string; /** The ID of the file. */ id?: string; /** Additional metadata about image media, if available. */ imageMediaMetadata?: { /** The aperture used to create the photo (f-number). */ aperture?: number; /** The make of the camera used to create the photo. */ cameraMake?: string; /** The model of the camera used to create the photo. */ cameraModel?: string; /** The color space of the photo. */ colorSpace?: string; /** The exposure bias of the photo (APEX value). */ exposureBias?: number; /** The exposure mode used to create the photo. */ exposureMode?: string; /** The length of the exposure, in seconds. */ exposureTime?: number; /** Whether a flash was used to create the photo. */ flashUsed?: boolean; /** The focal length used to create the photo, in millimeters. */ focalLength?: number; /** The height of the image in pixels. */ height?: number; /** The ISO speed used to create the photo. */ isoSpeed?: number; /** The lens used to create the photo. */ lens?: string; /** Geographic location information stored in the image. */ location?: { /** The altitude stored in the image. */ altitude?: number; /** The latitude stored in the image. */ latitude?: number; /** The longitude stored in the image. */ longitude?: number; }; /** The smallest f-number of the lens at the focal length used to create the photo (APEX value). */ maxApertureValue?: number; /** The metering mode used to create the photo. */ meteringMode?: string; /** The rotation in clockwise degrees from the image's original orientation. */ rotation?: number; /** The type of sensor used to create the photo. */ sensor?: string; /** The distance to the subject of the photo, in meters. */ subjectDistance?: number; /** The date and time the photo was taken (EXIF DateTime). */ time?: string; /** The white balance mode used to create the photo. */ whiteBalance?: string; /** The width of the image in pixels. */ width?: number; }; /** Whether the file was created or opened by the requesting app. */ isAppAuthorized?: boolean; /** Identifies what kind of resource this is. Value: the fixed string "drive#file". */ kind?: string; /** The last user to modify the file. */ lastModifyingUser?: User; /** The MD5 checksum for the content of the file. This is only applicable to files with binary content in Drive. */ md5Checksum?: string; /** * The MIME type of the file. * Drive will attempt to automatically detect an appropriate value from uploaded content if no value is provided. The value cannot be changed unless a new * revision is uploaded. * If a file is created with a Google Doc MIME type, the uploaded content will be imported if possible. The supported import formats are published in the * About resource. */ mimeType?: string; /** Whether the file has been modified by this user. */ modifiedByMe?: boolean; /** The last time the file was modified by the user (RFC 3339 date-time). */ modifiedByMeTime?: string; /** * The last time the file was modified by anyone (RFC 3339 date-time). * Note that setting modifiedTime will also update modifiedByMeTime for the user. */ modifiedTime?: string; /** * The name of the file. This is not necessarily unique within a folder. Note that for immutable items such as the top level folders of Team Drives, My * Drive root folder, and Application Data folder the name is constant. */ name?: string; /** * The original filename of the uploaded content if available, or else the original value of the name field. This is only available for files with binary * content in Drive. */ originalFilename?: string; /** Whether the user owns the file. Not populated for Team Drive files. */ ownedByMe?: boolean; /** The owners of the file. Currently, only certain legacy files may have more than one owner. Not populated for Team Drive files. */ owners?: User[]; /** * The IDs of the parent folders which contain the file. * If not specified as part of a create request, the file will be placed directly in the My Drive folder. Update requests must use the addParents and * removeParents parameters to modify the values. */ parents?: string[]; /** List of permission IDs for users with access to this file. */ permissionIds?: string[]; /** The full list of permissions for the file. This is only available if the requesting user can share the file. Not populated for Team Drive files. */ permissions?: Permission[]; /** * A collection of arbitrary key-value pairs which are visible to all apps. * Entries with null values are cleared in update and copy requests. */ properties?: Record<string, string>; /** The number of storage quota bytes used by the file. This includes the head revision as well as previous revisions with keepForever enabled. */ quotaBytesUsed?: string; /** Whether the file has been shared. Not populated for Team Drive files. */ shared?: boolean; /** The time at which the file was shared with the user, if applicable (RFC 3339 date-time). */ sharedWithMeTime?: string; /** The user who shared the file with the requesting user, if applicable. */ sharingUser?: User; /** The size of the file's content in bytes. This is only applicable to files with binary content in Drive. */ size?: string; /** The list of spaces which contain the file. The currently supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string[]; /** Whether the user has starred the file. */ starred?: boolean; /** ID of the Team Drive the file resides in. */ teamDriveId?: string; /** * A short-lived link to the file's thumbnail, if available. Typically lasts on the order of hours. Only populated when the requesting app can access the * file's content. */ thumbnailLink?: string; /** The thumbnail version for use in thumbnail cache invalidation. */ thumbnailVersion?: string; /** * Whether the file has been trashed, either explicitly or from a trashed parent folder. Only the owner may trash a file, and other users cannot see files * in the owner's trash. */ trashed?: boolean; /** The time that the item was trashed (RFC 3339 date-time). Only populated for Team Drive files. */ trashedTime?: string; /** If the file has been explicitly trashed, the user who trashed it. Only populated for Team Drive files. */ trashingUser?: User; /** A monotonically increasing version number for the file. This reflects every change made to the file on the server, even those not visible to the user. */ version?: string; /** Additional metadata about video media. This may not be available immediately upon upload. */ videoMediaMetadata?: { /** The duration of the video in milliseconds. */ durationMillis?: string; /** The height of the video in pixels. */ height?: number; /** The width of the video in pixels. */ width?: number; }; /** Whether the file has been viewed by this user. */ viewedByMe?: boolean; /** The last time the file was viewed by the user (RFC 3339 date-time). */ viewedByMeTime?: string; /** Whether users with only reader or commenter permission can copy the file's content. This affects copy, download, and print operations. */ viewersCanCopyContent?: boolean; /** A link for downloading the content of the file in a browser. This is only available for files with binary content in Drive. */ webContentLink?: string; /** A link for opening the file in a relevant Google editor or viewer in a browser. */ webViewLink?: string; /** Whether users with only writer permission can modify the file's permissions. Not populated for Team Drive files. */ writersCanShare?: boolean; } interface FileList { /** The list of files. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ files?: File[]; /** * Whether the search process was incomplete. If true, then some search results may be missing, since all documents were not searched. This may occur when * searching multiple Team Drives with the "user,allTeamDrives" corpora, but all corpora could not be searched. When this happens, it is suggested that * clients narrow their query by choosing a different corpus such as "user" or "teamDrive". */ incompleteSearch?: boolean; /** Identifies what kind of resource this is. Value: the fixed string "drive#fileList". */ kind?: string; /** * The page token for the next page of files. This will be absent if the end of the files list has been reached. If the token is rejected for any reason, * it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; } interface GeneratedIds { /** The IDs generated for the requesting user in the specified space. */ ids?: string[]; /** Identifies what kind of resource this is. Value: the fixed string "drive#generatedIds". */ kind?: string; /** The type of file that can be created with these IDs. */ space?: string; } interface Permission { /** Whether the permission allows the file to be discovered through search. This is only applicable for permissions of type domain or anyone. */ allowFileDiscovery?: boolean; /** Whether the account associated with this permission has been deleted. This field only pertains to user and group permissions. */ deleted?: boolean; /** A displayable name for users, groups or domains. */ displayName?: string; /** The domain to which this permission refers. */ domain?: string; /** The email address of the user or group to which this permission refers. */ emailAddress?: string; /** * The time at which this permission will expire (RFC 3339 date-time). Expiration times have the following restrictions: * - They can only be set on user and group permissions * - The time must be in the future * - The time cannot be more than a year in the future */ expirationTime?: string; /** The ID of this permission. This is a unique identifier for the grantee, and is published in User resources as permissionId. */ id?: string; /** Identifies what kind of resource this is. Value: the fixed string "drive#permission". */ kind?: string; /** A link to the user's profile photo, if available. */ photoLink?: string; /** * The role granted by this permission. While new values may be supported in the future, the following are currently allowed: * - organizer * - owner * - writer * - commenter * - reader */ role?: string; /** * Details of whether the permissions on this Team Drive item are inherited or directly on this item. This is an output-only field which is present only * for Team Drive items. */ teamDrivePermissionDetails?: Array<{ /** Whether this permission is inherited. This field is always populated. This is an output-only field. */ inherited?: boolean; /** The ID of the item from which this permission is inherited. This is an output-only field and is only populated for members of the Team Drive. */ inheritedFrom?: string; /** * The primary role for this user. While new values may be added in the future, the following are currently possible: * - organizer * - writer * - commenter * - reader */ role?: string; /** * The Team Drive permission type for this user. While new values may be added in future, the following are currently possible: * - file * - member */ teamDrivePermissionType?: string; }>; /** * The type of the grantee. Valid values are: * - user * - group * - domain * - anyone */ type?: string; } interface PermissionList { /** Identifies what kind of resource this is. Value: the fixed string "drive#permissionList". */ kind?: string; /** * The page token for the next page of permissions. This field will be absent if the end of the permissions list has been reached. If the token is * rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; /** The list of permissions. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ permissions?: Permission[]; } interface Reply { /** * The action the reply performed to the parent comment. Valid values are: * - resolve * - reopen */ action?: string; /** The user who created the reply. */ author?: User; /** * The plain text content of the reply. This field is used for setting the content, while htmlContent should be displayed. This is required on creates if * no action is specified. */ content?: string; /** The time at which the reply was created (RFC 3339 date-time). */ createdTime?: string; /** Whether the reply has been deleted. A deleted reply has no content. */ deleted?: boolean; /** The content of the reply with HTML formatting. */ htmlContent?: string; /** The ID of the reply. */ id?: string; /** Identifies what kind of resource this is. Value: the fixed string "drive#reply". */ kind?: string; /** The last time the reply was modified (RFC 3339 date-time). */ modifiedTime?: string; } interface ReplyList { /** Identifies what kind of resource this is. Value: the fixed string "drive#replyList". */ kind?: string; /** * The page token for the next page of replies. This will be absent if the end of the replies list has been reached. If the token is rejected for any * reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; /** The list of replies. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ replies?: Reply[]; } interface Revision { /** The ID of the revision. */ id?: string; /** * Whether to keep this revision forever, even if it is no longer the head revision. If not set, the revision will be automatically purged 30 days after * newer content is uploaded. This can be set on a maximum of 200 revisions for a file. * This field is only applicable to files with binary content in Drive. */ keepForever?: boolean; /** Identifies what kind of resource this is. Value: the fixed string "drive#revision". */ kind?: string; /** The last user to modify this revision. */ lastModifyingUser?: User; /** The MD5 checksum of the revision's content. This is only applicable to files with binary content in Drive. */ md5Checksum?: string; /** The MIME type of the revision. */ mimeType?: string; /** The last time the revision was modified (RFC 3339 date-time). */ modifiedTime?: string; /** The original filename used to create this revision. This is only applicable to files with binary content in Drive. */ originalFilename?: string; /** Whether subsequent revisions will be automatically republished. This is only applicable to Google Docs. */ publishAuto?: boolean; /** Whether this revision is published. This is only applicable to Google Docs. */ published?: boolean; /** Whether this revision is published outside the domain. This is only applicable to Google Docs. */ publishedOutsideDomain?: boolean; /** The size of the revision's content in bytes. This is only applicable to files with binary content in Drive. */ size?: string; } interface RevisionList { /** Identifies what kind of resource this is. Value: the fixed string "drive#revisionList". */ kind?: string; /** * The page token for the next page of revisions. This will be absent if the end of the revisions list has been reached. If the token is rejected for any * reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; /** The list of revisions. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ revisions?: Revision[]; } interface StartPageToken { /** Identifies what kind of resource this is. Value: the fixed string "drive#startPageToken". */ kind?: string; /** The starting page token for listing changes. */ startPageToken?: string; } interface TeamDrive { /** * An image file and cropping parameters from which a background image for this Team Drive is set. This is a write only field; it can only be set on * drive.teamdrives.update requests that don't set themeId. When specified, all fields of the backgroundImageFile must be set. */ backgroundImageFile?: { /** The ID of an image file in Drive to use for the background image. */ id?: string; /** * The width of the cropped image in the closed range of 0 to 1. This value represents the width of the cropped image divided by the width of the entire * image. The height is computed by applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280 pixels wide and 144 * pixels high. */ width?: number; /** * The X coordinate of the upper left corner of the cropping area in the background image. This is a value in the closed range of 0 to 1. This value * represents the horizontal distance from the left side of the entire image to the left side of the cropping area divided by the width of the entire * image. */ xCoordinate?: number; /** * The Y coordinate of the upper left corner of the cropping area in the background image. This is a value in the closed range of 0 to 1. This value * represents the vertical distance from the top side of the entire image to the top side of the cropping area divided by the height of the entire image. */ yCoordinate?: number; }; /** A short-lived link to this Team Drive's background image. */ backgroundImageLink?: string; /** Capabilities the current user has on this Team Drive. */ capabilities?: { /** Whether the current user can add children to folders in this Team Drive. */ canAddChildren?: boolean; /** Whether the current user can change the background of this Team Drive. */ canChangeTeamDriveBackground?: boolean; /** Whether the current user can comment on files in this Team Drive. */ canComment?: boolean; /** Whether the current user can copy files in this Team Drive. */ canCopy?: boolean; /** * Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may still fail if there are untrashed items inside the Team * Drive. */ canDeleteTeamDrive?: boolean; /** Whether the current user can download files in this Team Drive. */ canDownload?: boolean; /** Whether the current user can edit files in this Team Drive */ canEdit?: boolean; /** Whether the current user can list the children of folders in this Team Drive. */ canListChildren?: boolean; /** Whether the current user can add members to this Team Drive or remove them or change their role. */ canManageMembers?: boolean; /** Whether the current user can read the revisions resource of files in this Team Drive. */ canReadRevisions?: boolean; /** Whether the current user can remove children from folders in this Team Drive. */ canRemoveChildren?: boolean; /** Whether the current user can rename files or folders in this Team Drive. */ canRename?: boolean; /** Whether the current user can rename this Team Drive. */ canRenameTeamDrive?: boolean; /** Whether the current user can share files or folders in this Team Drive. */ canShare?: boolean; }; /** The color of this Team Drive as an RGB hex string. It can only be set on a drive.teamdrives.update request that does not set themeId. */ colorRgb?: string; /** The ID of this Team Drive which is also the ID of the top level folder for this Team Drive. */ id?: string; /** Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive". */ kind?: string; /** The name of this Team Drive. */ name?: string; /** * The ID of the theme from which the background image and color will be set. The set of possible teamDriveThemes can be retrieved from a drive.about.get * response. When not specified on a drive.teamdrives.create request, a random theme is chosen from which the background image and color are set. This is * a write-only field; it can only be set on requests that don't set colorRgb or backgroundImageFile. */ themeId?: string; } interface TeamDriveList { /** Identifies what kind of resource this is. Value: the fixed string "drive#teamDriveList". */ kind?: string; /** * The page token for the next page of Team Drives. This will be absent if the end of the Team Drives list has been reached. If the token is rejected for * any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string; /** The list of Team Drives. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ teamDrives?: TeamDrive[]; } interface User { /** A plain text displayable name for this user. */ displayName?: string; /** The email address of the user. This may not be present in certain contexts if the user has not made their email address visible to the requester. */ emailAddress?: string; /** Identifies what kind of resource this is. Value: the fixed string "drive#user". */ kind?: string; /** Whether this user is the requesting user. */ me?: boolean; /** The user's ID as visible in Permission resources. */ permissionId?: string; /** A link to the user's profile photo, if available. */ photoLink?: string; } interface AboutResource { /** Gets information about the user, the user's Drive, and system capabilities. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<About>; } interface ChangesResource { /** Gets the starting pageToken for listing future changes. */ getStartPageToken(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** The ID of the Team Drive for which the starting pageToken for listing future changes from that Team Drive will be returned. */ teamDriveId?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<StartPageToken>; /** Lists the changes for a user or Team Drive. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed * from the list of changes and there will be no further change entries for this file. */ includeCorpusRemovals?: boolean; /** Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. */ includeRemoved?: boolean; /** Whether Team Drive files or changes should be included in results. */ includeTeamDriveItems?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The maximum number of changes to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to * the response from the getStartPageToken method. */ pageToken: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or * shared files which have not been added to My Drive. */ restrictToMyDrive?: boolean; /** A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** * The Team Drive from which changes will be returned. If specified the change IDs will be reflective of the Team Drive; use the combined Team Drive ID * and change ID as an identifier. */ teamDriveId?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<ChangeList>; /** Subscribes to changes for a user. */ watch(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed * from the list of changes and there will be no further change entries for this file. */ includeCorpusRemovals?: boolean; /** Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. */ includeRemoved?: boolean; /** Whether Team Drive files or changes should be included in results. */ includeTeamDriveItems?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The maximum number of changes to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to * the response from the getStartPageToken method. */ pageToken: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or * shared files which have not been added to My Drive. */ restrictToMyDrive?: boolean; /** A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** * The Team Drive from which changes will be returned. If specified the change IDs will be reflective of the Team Drive; use the combined Team Drive ID * and change ID as an identifier. */ teamDriveId?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Channel>; } interface ChannelsResource { /** Stop watching resources through this channel */ stop(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; } interface CommentsResource { /** Creates a new comment on a file. */ create(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; /** Deletes a comment. */ delete(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets a comment by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** Whether to return deleted comments. Deleted comments will not include their original content. */ includeDeleted?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; /** Lists a file's comments. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** Whether to include deleted comments. Deleted comments will not include their original content. */ includeDeleted?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The maximum number of comments to return per page. */ pageSize?: number; /** The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The minimum value of 'modifiedTime' for the result comments (RFC 3339 date-time). */ startModifiedTime?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CommentList>; /** Updates a comment with patch semantics. */ update(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; } interface FilesResource { /** Creates a copy of a file and applies any requested updates with patch semantics. */ copy(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** * Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to * the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders. */ ignoreDefaultVisibility?: boolean; /** Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Drive. */ keepRevisionForever?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** A language hint for OCR processing during image import (ISO 639-1 code). */ ocrLanguage?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<File>; /** Creates a new file. */ create(request: { resource: { /** * The name of the file. This is not necessarily unique within a folder. * Note that for immutable items such as the top level folders of Team Drives, My Drive root folder, and Application Data folder the name is constant. */ name: string; /** * The MIME type of the file. * Drive will attempt to automatically detect an appropriate value from uploaded content if no value is provided. The value cannot be changed unless a new revision is uploaded. * * If a file is created with a Google Doc MIME type, the uploaded content will be imported if possible. The supported import formats are published in the About resource. */ mimeType: string; /** * The IDs of the parent folders which contain the file. * If not specified as part of a create request, the file will be placed directly in the My Drive folder. Update requests must use the addParents and removeParents parameters to modify the values. */ parents: string[]; }; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to * the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders. */ ignoreDefaultVisibility?: boolean; /** Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Drive. */ keepRevisionForever?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** A language hint for OCR processing during image import (ISO 639-1 code). */ ocrLanguage?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** Whether to use the uploaded content as indexable text. */ useContentAsIndexableText?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<File>; /** * Permanently deletes a file owned by the user without moving it to the trash. If the file belongs to a Team Drive the user must be an organizer on the * parent. If the target is a folder, all descendants owned by the user are also deleted. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Permanently deletes all of the user's trashed files. */ emptyTrash(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB. */ export(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The MIME type of the format requested for this export. */ mimeType: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Generates a set of file IDs which can be provided in create requests. */ generateIds(request: { /** Data format for the response. */ alt?: string; /** The number of IDs to return. */ count?: number; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The space in which the IDs can be used to create new files. Supported values are 'drive' and 'appDataFolder'. */ space?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<GeneratedIds>; /** Gets a file's metadata or content by ID. */ get(request: { /** Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. */ acknowledgeAbuse?: boolean; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<File>; /** Lists or searches files. */ list(request: { /** Data format for the response. */ alt?: string; /** * Comma-separated list of bodies of items (files/documents) to which the query applies. Supported bodies are 'user', 'domain', 'teamDrive' and * 'allTeamDrives'. 'allTeamDrives' must be combined with 'user'; all other values must be used in isolation. Prefer 'user' or 'teamDrive' to * 'allTeamDrives' for efficiency. */ corpora?: string; /** The source of files to list. Deprecated: use 'corpora' instead. */ corpus?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Whether Team Drive items should be included in results. */ includeTeamDriveItems?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * A comma-separated list of sort keys. Valid keys are 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name', 'name_natural', * 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred', and 'viewedByMeTime'. Each key sorts ascending by default, but may be reversed with the * 'desc' modifier. Example usage: ?orderBy=folder,modifiedTime desc,name. Please note that there is a current limitation for users with approximately one * million files in which the requested sort order is ignored. */ orderBy?: string; /** The maximum number of files to return per page. Partial or empty result pages are possible even before the end of the files list has been reached. */ pageSize?: number; /** The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** A query for filtering the file results. See the "Search for Files" guide for supported syntax. */ q?: string; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** A comma-separated list of spaces to query within the corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** ID of Team Drive to search. */ teamDriveId?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<FileList>; /** Updates a file's metadata and/or content with patch semantics. */ update(request: { /** A comma-separated list of parent IDs to add. */ addParents?: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Drive. */ keepRevisionForever?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** A language hint for OCR processing during image import (ISO 639-1 code). */ ocrLanguage?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** A comma-separated list of parent IDs to remove. */ removeParents?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** Whether to use the uploaded content as indexable text. */ useContentAsIndexableText?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<File>; /** Subscribes to changes to a file */ watch(request: { /** Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. */ acknowledgeAbuse?: boolean; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Channel>; } interface PermissionsResource { /** Creates a permission for a file or Team Drive. */ create(request: { /** Data format for the response. */ alt?: string; /** A custom message to include in the notification email. */ emailMessage?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file or Team Drive. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Whether to send a notification email when sharing to users or groups. This defaults to true for users and groups, and is not allowed for other * requests. It must not be disabled for ownership transfers. */ sendNotificationEmail?: boolean; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** * Whether to transfer ownership to the specified user and downgrade the current owner to a writer. This parameter is required as an acknowledgement of * the side effect. */ transferOwnership?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Permission>; /** Deletes a permission. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file or Team Drive. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the permission. */ permissionId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets a permission by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the permission. */ permissionId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Permission>; /** Lists a file's or Team Drive's permissions. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file or Team Drive. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The maximum number of permissions to return per page. When not set for files in a Team Drive, at most 100 results will be returned. When not set for * files that are not in a Team Drive, the entire list will be returned. */ pageSize?: number; /** The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PermissionList>; /** Updates a permission with patch semantics. */ update(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file or Team Drive. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the permission. */ permissionId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to remove the expiration date. */ removeExpiration?: boolean; /** Whether the requesting application supports Team Drives. */ supportsTeamDrives?: boolean; /** * Whether to transfer ownership to the specified user and downgrade the current owner to a writer. This parameter is required as an acknowledgement of * the side effect. */ transferOwnership?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Permission>; } interface RepliesResource { /** Creates a new reply to a comment. */ create(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Reply>; /** Deletes a reply. */ delete(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the reply. */ replyId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets a reply by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** Whether to return deleted replies. Deleted replies will not include their original content. */ includeDeleted?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the reply. */ replyId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Reply>; /** Lists a comment's replies. */ list(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** Whether to include deleted replies. Deleted replies will not include their original content. */ includeDeleted?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The maximum number of replies to return per page. */ pageSize?: number; /** The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<ReplyList>; /** Updates a reply with patch semantics. */ update(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the reply. */ replyId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Reply>; } interface RevisionsResource { /** Permanently deletes a revision. This method is only applicable to files with binary content in Drive. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the revision. */ revisionId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets a revision's metadata or content by ID. */ get(request: { /** Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. */ acknowledgeAbuse?: boolean; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the revision. */ revisionId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Revision>; /** Lists a file's revisions. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The maximum number of revisions to return per page. */ pageSize?: number; /** The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<RevisionList>; /** Updates a revision with patch semantics. */ update(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The ID of the file. */ fileId: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the revision. */ revisionId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Revision>; } interface TeamdrivesResource { /** Creates a new Team Drive. */ create(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * An ID, such as a random UUID, which uniquely identifies this user's request for idempotent creation of a Team Drive. A repeated request by the same * user and with the same request ID will avoid creating duplicates by attempting to create the same Team Drive. If the Team Drive already exists a 409 * error will be returned. */ requestId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<TeamDrive>; /** Permanently deletes a Team Drive for which the user is an organizer. The Team Drive cannot contain any untrashed items. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the Team Drive */ teamDriveId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets a Team Drive's metadata by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the Team Drive */ teamDriveId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<TeamDrive>; /** Lists the user's Team Drives. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Maximum number of Team Drives to return. */ pageSize?: number; /** Page token for Team Drives. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<TeamDriveList>; /** Updates a Team Drive's metadata */ update(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the Team Drive */ teamDriveId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<TeamDrive>; } } }
Bludwarf/cuetube
src/@types/gapi.client.drive/index.d.ts
TypeScript
gpl-3.0
110,329
/* * ltr501.c - Support for Lite-On LTR501 ambient light and proximity sensor * * Copyright 2014 Peter Meerwald <pmeerw@pmeerw.net> * * This file is subject to the terms and conditions of version 2 of * the GNU General Public License. See the file COPYING in the main * directory of this archive for more details. * * 7-bit I2C slave address 0x23 * * TODO: IR LED characteristics */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/regmap.h> #include <linux/acpi.h> #include <linux/iio/iio.h> #include <linux/iio/events.h> #include <linux/iio/sysfs.h> #include <linux/iio/trigger_consumer.h> #include <linux/iio/buffer.h> #include <linux/iio/triggered_buffer.h> #define LTR501_DRV_NAME "ltr501" #define LTR501_ALS_CONTR 0x80 /* ALS operation mode, SW reset */ #define LTR501_PS_CONTR 0x81 /* PS operation mode */ #define LTR501_PS_MEAS_RATE 0x84 /* measurement rate*/ #define LTR501_ALS_MEAS_RATE 0x85 /* ALS integ time, measurement rate*/ #define LTR501_PART_ID 0x86 #define LTR501_MANUFAC_ID 0x87 #define LTR501_ALS_DATA1 0x88 /* 16-bit, little endian */ #define LTR501_ALS_DATA0 0x8a /* 16-bit, little endian */ #define LTR501_ALS_PS_STATUS 0x8c #define LTR501_PS_DATA 0x8d /* 16-bit, little endian */ #define LTR501_INTR 0x8f /* output mode, polarity, mode */ #define LTR501_PS_THRESH_UP 0x90 /* 11 bit, ps upper threshold */ #define LTR501_PS_THRESH_LOW 0x92 /* 11 bit, ps lower threshold */ #define LTR501_ALS_THRESH_UP 0x97 /* 16 bit, ALS upper threshold */ #define LTR501_ALS_THRESH_LOW 0x99 /* 16 bit, ALS lower threshold */ #define LTR501_INTR_PRST 0x9e /* ps thresh, als thresh */ #define LTR501_MAX_REG 0x9f #define LTR501_ALS_CONTR_SW_RESET BIT(2) #define LTR501_CONTR_PS_GAIN_MASK (BIT(3) | BIT(2)) #define LTR501_CONTR_PS_GAIN_SHIFT 2 #define LTR501_CONTR_ALS_GAIN_MASK BIT(3) #define LTR501_CONTR_ACTIVE BIT(1) #define LTR501_STATUS_ALS_INTR BIT(3) #define LTR501_STATUS_ALS_RDY BIT(2) #define LTR501_STATUS_PS_INTR BIT(1) #define LTR501_STATUS_PS_RDY BIT(0) #define LTR501_PS_DATA_MASK 0x7ff #define LTR501_PS_THRESH_MASK 0x7ff #define LTR501_ALS_THRESH_MASK 0xffff #define LTR501_ALS_DEF_PERIOD 500000 #define LTR501_PS_DEF_PERIOD 100000 #define LTR501_REGMAP_NAME "ltr501_regmap" #define LTR501_LUX_CONV(vis_coeff, vis_data, ir_coeff, ir_data) \ ((vis_coeff * vis_data) - (ir_coeff * ir_data)) static const int int_time_mapping[] = {100000, 50000, 200000, 400000}; static const struct reg_field reg_field_it = REG_FIELD(LTR501_ALS_MEAS_RATE, 3, 4); static const struct reg_field reg_field_als_intr = REG_FIELD(LTR501_INTR, 0, 0); static const struct reg_field reg_field_ps_intr = REG_FIELD(LTR501_INTR, 1, 1); static const struct reg_field reg_field_als_rate = REG_FIELD(LTR501_ALS_MEAS_RATE, 0, 2); static const struct reg_field reg_field_ps_rate = REG_FIELD(LTR501_PS_MEAS_RATE, 0, 3); static const struct reg_field reg_field_als_prst = REG_FIELD(LTR501_INTR_PRST, 0, 3); static const struct reg_field reg_field_ps_prst = REG_FIELD(LTR501_INTR_PRST, 4, 7); struct ltr501_samp_table { int freq_val; /* repetition frequency in micro HZ*/ int time_val; /* repetition rate in micro seconds */ }; #define LTR501_RESERVED_GAIN -1 enum { ltr501 = 0, ltr559, ltr301, }; struct ltr501_gain { int scale; int uscale; }; static struct ltr501_gain ltr501_als_gain_tbl[] = { {1, 0}, {0, 5000}, }; static struct ltr501_gain ltr559_als_gain_tbl[] = { {1, 0}, {0, 500000}, {0, 250000}, {0, 125000}, {LTR501_RESERVED_GAIN, LTR501_RESERVED_GAIN}, {LTR501_RESERVED_GAIN, LTR501_RESERVED_GAIN}, {0, 20000}, {0, 10000}, }; static struct ltr501_gain ltr501_ps_gain_tbl[] = { {1, 0}, {0, 250000}, {0, 125000}, {0, 62500}, }; static struct ltr501_gain ltr559_ps_gain_tbl[] = { {0, 62500}, /* x16 gain */ {0, 31250}, /* x32 gain */ {0, 15625}, /* bits X1 are for x64 gain */ {0, 15624}, }; struct ltr501_chip_info { u8 partid; struct ltr501_gain *als_gain; int als_gain_tbl_size; struct ltr501_gain *ps_gain; int ps_gain_tbl_size; u8 als_mode_active; u8 als_gain_mask; u8 als_gain_shift; struct iio_chan_spec const *channels; const int no_channels; const struct iio_info *info; const struct iio_info *info_no_irq; }; struct ltr501_data { struct i2c_client *client; struct mutex lock_als, lock_ps; struct ltr501_chip_info *chip_info; u8 als_contr, ps_contr; int als_period, ps_period; /* period in micro seconds */ struct regmap *regmap; struct regmap_field *reg_it; struct regmap_field *reg_als_intr; struct regmap_field *reg_ps_intr; struct regmap_field *reg_als_rate; struct regmap_field *reg_ps_rate; struct regmap_field *reg_als_prst; struct regmap_field *reg_ps_prst; }; static const struct ltr501_samp_table ltr501_als_samp_table[] = { {20000000, 50000}, {10000000, 100000}, {5000000, 200000}, {2000000, 500000}, {1000000, 1000000}, {500000, 2000000}, {500000, 2000000}, {500000, 2000000} }; static const struct ltr501_samp_table ltr501_ps_samp_table[] = { {20000000, 50000}, {14285714, 70000}, {10000000, 100000}, {5000000, 200000}, {2000000, 500000}, {1000000, 1000000}, {500000, 2000000}, {500000, 2000000}, {500000, 2000000} }; static int ltr501_match_samp_freq(const struct ltr501_samp_table *tab, int len, int val, int val2) { int i, freq; freq = val * 1000000 + val2; for (i = 0; i < len; i++) { if (tab[i].freq_val == freq) { return i; } } return -EINVAL; } static int ltr501_als_read_samp_freq(struct ltr501_data *data, int *val, int *val2) { int ret, i; ret = regmap_field_read(data->reg_als_rate, &i); if (ret < 0) { return ret; } if (i < 0 || i >= ARRAY_SIZE(ltr501_als_samp_table)) { return -EINVAL; } *val = ltr501_als_samp_table[i].freq_val / 1000000; *val2 = ltr501_als_samp_table[i].freq_val % 1000000; return IIO_VAL_INT_PLUS_MICRO; } static int ltr501_ps_read_samp_freq(struct ltr501_data *data, int *val, int *val2) { int ret, i; ret = regmap_field_read(data->reg_ps_rate, &i); if (ret < 0) { return ret; } if (i < 0 || i >= ARRAY_SIZE(ltr501_ps_samp_table)) { return -EINVAL; } *val = ltr501_ps_samp_table[i].freq_val / 1000000; *val2 = ltr501_ps_samp_table[i].freq_val % 1000000; return IIO_VAL_INT_PLUS_MICRO; } static int ltr501_als_write_samp_freq(struct ltr501_data *data, int val, int val2) { int i, ret; i = ltr501_match_samp_freq(ltr501_als_samp_table, ARRAY_SIZE(ltr501_als_samp_table), val, val2); if (i < 0) { return i; } mutex_lock(&data->lock_als); ret = regmap_field_write(data->reg_als_rate, i); mutex_unlock(&data->lock_als); return ret; } static int ltr501_ps_write_samp_freq(struct ltr501_data *data, int val, int val2) { int i, ret; i = ltr501_match_samp_freq(ltr501_ps_samp_table, ARRAY_SIZE(ltr501_ps_samp_table), val, val2); if (i < 0) { return i; } mutex_lock(&data->lock_ps); ret = regmap_field_write(data->reg_ps_rate, i); mutex_unlock(&data->lock_ps); return ret; } static int ltr501_als_read_samp_period(struct ltr501_data *data, int *val) { int ret, i; ret = regmap_field_read(data->reg_als_rate, &i); if (ret < 0) { return ret; } if (i < 0 || i >= ARRAY_SIZE(ltr501_als_samp_table)) { return -EINVAL; } *val = ltr501_als_samp_table[i].time_val; return IIO_VAL_INT; } static int ltr501_ps_read_samp_period(struct ltr501_data *data, int *val) { int ret, i; ret = regmap_field_read(data->reg_ps_rate, &i); if (ret < 0) { return ret; } if (i < 0 || i >= ARRAY_SIZE(ltr501_ps_samp_table)) { return -EINVAL; } *val = ltr501_ps_samp_table[i].time_val; return IIO_VAL_INT; } /* IR and visible spectrum coeff's are given in data sheet */ static unsigned long ltr501_calculate_lux(u16 vis_data, u16 ir_data) { unsigned long ratio, lux; if (vis_data == 0) { return 0; } /* multiply numerator by 100 to avoid handling ratio < 1 */ ratio = DIV_ROUND_UP(ir_data * 100, ir_data + vis_data); if (ratio < 45) { lux = LTR501_LUX_CONV(1774, vis_data, -1105, ir_data); } else if (ratio >= 45 && ratio < 64) { lux = LTR501_LUX_CONV(3772, vis_data, 1336, ir_data); } else if (ratio >= 64 && ratio < 85) { lux = LTR501_LUX_CONV(1690, vis_data, 169, ir_data); } else { lux = 0; } return lux / 1000; } static int ltr501_drdy(struct ltr501_data *data, u8 drdy_mask) { int tries = 100; int ret, status; while (tries--) { ret = regmap_read(data->regmap, LTR501_ALS_PS_STATUS, &status); if (ret < 0) { return ret; } if ((status & drdy_mask) == drdy_mask) { return 0; } msleep(25); } dev_err(&data->client->dev, "ltr501_drdy() failed, data not ready\n"); return -EIO; } static int ltr501_set_it_time(struct ltr501_data *data, int it) { int ret, i, index = -1, status; for (i = 0; i < ARRAY_SIZE(int_time_mapping); i++) { if (int_time_mapping[i] == it) { index = i; break; } } /* Make sure integ time index is valid */ if (index < 0) { return -EINVAL; } ret = regmap_read(data->regmap, LTR501_ALS_CONTR, &status); if (ret < 0) { return ret; } if (status & LTR501_CONTR_ALS_GAIN_MASK) { /* * 200 ms and 400 ms integ time can only be * used in dynamic range 1 */ if (index > 1) { return -EINVAL; } } else /* 50 ms integ time can only be used in dynamic range 2 */ if (index == 1) { return -EINVAL; } return regmap_field_write(data->reg_it, index); } /* read int time in micro seconds */ static int ltr501_read_it_time(struct ltr501_data *data, int *val, int *val2) { int ret, index; ret = regmap_field_read(data->reg_it, &index); if (ret < 0) { return ret; } /* Make sure integ time index is valid */ if (index < 0 || index >= ARRAY_SIZE(int_time_mapping)) { return -EINVAL; } *val2 = int_time_mapping[index]; *val = 0; return IIO_VAL_INT_PLUS_MICRO; } static int ltr501_read_als(struct ltr501_data *data, __le16 buf[2]) { int ret; ret = ltr501_drdy(data, LTR501_STATUS_ALS_RDY); if (ret < 0) { return ret; } /* always read both ALS channels in given order */ return regmap_bulk_read(data->regmap, LTR501_ALS_DATA1, buf, 2 * sizeof(__le16)); } static int ltr501_read_ps(struct ltr501_data *data) { int ret, status; ret = ltr501_drdy(data, LTR501_STATUS_PS_RDY); if (ret < 0) { return ret; } ret = regmap_bulk_read(data->regmap, LTR501_PS_DATA, &status, 2); if (ret < 0) { return ret; } return status; } static int ltr501_read_intr_prst(struct ltr501_data *data, enum iio_chan_type type, int *val2) { int ret, samp_period, prst; switch (type) { case IIO_INTENSITY: ret = regmap_field_read(data->reg_als_prst, &prst); if (ret < 0) { return ret; } ret = ltr501_als_read_samp_period(data, &samp_period); if (ret < 0) { return ret; } *val2 = samp_period * prst; return IIO_VAL_INT_PLUS_MICRO; case IIO_PROXIMITY: ret = regmap_field_read(data->reg_ps_prst, &prst); if (ret < 0) { return ret; } ret = ltr501_ps_read_samp_period(data, &samp_period); if (ret < 0) { return ret; } *val2 = samp_period * prst; return IIO_VAL_INT_PLUS_MICRO; default: return -EINVAL; } return -EINVAL; } static int ltr501_write_intr_prst(struct ltr501_data *data, enum iio_chan_type type, int val, int val2) { int ret, samp_period, new_val; unsigned long period; if (val < 0 || val2 < 0) { return -EINVAL; } /* period in microseconds */ period = ((val * 1000000) + val2); switch (type) { case IIO_INTENSITY: ret = ltr501_als_read_samp_period(data, &samp_period); if (ret < 0) { return ret; } /* period should be atleast equal to sampling period */ if (period < samp_period) { return -EINVAL; } new_val = DIV_ROUND_UP(period, samp_period); if (new_val < 0 || new_val > 0x0f) { return -EINVAL; } mutex_lock(&data->lock_als); ret = regmap_field_write(data->reg_als_prst, new_val); mutex_unlock(&data->lock_als); if (ret >= 0) { data->als_period = period; } return ret; case IIO_PROXIMITY: ret = ltr501_ps_read_samp_period(data, &samp_period); if (ret < 0) { return ret; } /* period should be atleast equal to rate */ if (period < samp_period) { return -EINVAL; } new_val = DIV_ROUND_UP(period, samp_period); if (new_val < 0 || new_val > 0x0f) { return -EINVAL; } mutex_lock(&data->lock_ps); ret = regmap_field_write(data->reg_ps_prst, new_val); mutex_unlock(&data->lock_ps); if (ret >= 0) { data->ps_period = period; } return ret; default: return -EINVAL; } return -EINVAL; } static const struct iio_event_spec ltr501_als_event_spec[] = { { .type = IIO_EV_TYPE_THRESH, .dir = IIO_EV_DIR_RISING, .mask_separate = BIT(IIO_EV_INFO_VALUE), }, { .type = IIO_EV_TYPE_THRESH, .dir = IIO_EV_DIR_FALLING, .mask_separate = BIT(IIO_EV_INFO_VALUE), }, { .type = IIO_EV_TYPE_THRESH, .dir = IIO_EV_DIR_EITHER, .mask_separate = BIT(IIO_EV_INFO_ENABLE) | BIT(IIO_EV_INFO_PERIOD), }, }; static const struct iio_event_spec ltr501_pxs_event_spec[] = { { .type = IIO_EV_TYPE_THRESH, .dir = IIO_EV_DIR_RISING, .mask_separate = BIT(IIO_EV_INFO_VALUE), }, { .type = IIO_EV_TYPE_THRESH, .dir = IIO_EV_DIR_FALLING, .mask_separate = BIT(IIO_EV_INFO_VALUE), }, { .type = IIO_EV_TYPE_THRESH, .dir = IIO_EV_DIR_EITHER, .mask_separate = BIT(IIO_EV_INFO_ENABLE) | BIT(IIO_EV_INFO_PERIOD), }, }; #define LTR501_INTENSITY_CHANNEL(_idx, _addr, _mod, _shared, \ _evspec, _evsize) { \ .type = IIO_INTENSITY, \ .modified = 1, \ .address = (_addr), \ .channel2 = (_mod), \ .info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \ .info_mask_shared_by_type = (_shared), \ .scan_index = (_idx), \ .scan_type = { \ .sign = 'u', \ .realbits = 16, \ .storagebits = 16, \ .endianness = IIO_CPU, \ }, \ .event_spec = _evspec,\ .num_event_specs = _evsize,\ } #define LTR501_LIGHT_CHANNEL() { \ .type = IIO_LIGHT, \ .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), \ .scan_index = -1, \ } static const struct iio_chan_spec ltr501_channels[] = { LTR501_LIGHT_CHANNEL(), LTR501_INTENSITY_CHANNEL(0, LTR501_ALS_DATA0, IIO_MOD_LIGHT_BOTH, 0, ltr501_als_event_spec, ARRAY_SIZE(ltr501_als_event_spec)), LTR501_INTENSITY_CHANNEL(1, LTR501_ALS_DATA1, IIO_MOD_LIGHT_IR, BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_INT_TIME) | BIT(IIO_CHAN_INFO_SAMP_FREQ), NULL, 0), { .type = IIO_PROXIMITY, .address = LTR501_PS_DATA, .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE), .scan_index = 2, .scan_type = { .sign = 'u', .realbits = 11, .storagebits = 16, .endianness = IIO_CPU, }, .event_spec = ltr501_pxs_event_spec, .num_event_specs = ARRAY_SIZE(ltr501_pxs_event_spec), }, IIO_CHAN_SOFT_TIMESTAMP(3), }; static const struct iio_chan_spec ltr301_channels[] = { LTR501_LIGHT_CHANNEL(), LTR501_INTENSITY_CHANNEL(0, LTR501_ALS_DATA0, IIO_MOD_LIGHT_BOTH, 0, ltr501_als_event_spec, ARRAY_SIZE(ltr501_als_event_spec)), LTR501_INTENSITY_CHANNEL(1, LTR501_ALS_DATA1, IIO_MOD_LIGHT_IR, BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_INT_TIME) | BIT(IIO_CHAN_INFO_SAMP_FREQ), NULL, 0), IIO_CHAN_SOFT_TIMESTAMP(2), }; static int ltr501_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask) { struct ltr501_data *data = iio_priv(indio_dev); __le16 buf[2]; int ret, i; switch (mask) { case IIO_CHAN_INFO_PROCESSED: if (iio_buffer_enabled(indio_dev)) { return -EBUSY; } switch (chan->type) { case IIO_LIGHT: mutex_lock(&data->lock_als); ret = ltr501_read_als(data, buf); mutex_unlock(&data->lock_als); if (ret < 0) { return ret; } *val = ltr501_calculate_lux(le16_to_cpu(buf[1]), le16_to_cpu(buf[0])); return IIO_VAL_INT; default: return -EINVAL; } case IIO_CHAN_INFO_RAW: if (iio_buffer_enabled(indio_dev)) { return -EBUSY; } switch (chan->type) { case IIO_INTENSITY: mutex_lock(&data->lock_als); ret = ltr501_read_als(data, buf); mutex_unlock(&data->lock_als); if (ret < 0) { return ret; } *val = le16_to_cpu(chan->address == LTR501_ALS_DATA1 ? buf[0] : buf[1]); return IIO_VAL_INT; case IIO_PROXIMITY: mutex_lock(&data->lock_ps); ret = ltr501_read_ps(data); mutex_unlock(&data->lock_ps); if (ret < 0) { return ret; } *val = ret & LTR501_PS_DATA_MASK; return IIO_VAL_INT; default: return -EINVAL; } case IIO_CHAN_INFO_SCALE: switch (chan->type) { case IIO_INTENSITY: i = (data->als_contr & data->chip_info->als_gain_mask) >> data->chip_info->als_gain_shift; *val = data->chip_info->als_gain[i].scale; *val2 = data->chip_info->als_gain[i].uscale; return IIO_VAL_INT_PLUS_MICRO; case IIO_PROXIMITY: i = (data->ps_contr & LTR501_CONTR_PS_GAIN_MASK) >> LTR501_CONTR_PS_GAIN_SHIFT; *val = data->chip_info->ps_gain[i].scale; *val2 = data->chip_info->ps_gain[i].uscale; return IIO_VAL_INT_PLUS_MICRO; default: return -EINVAL; } case IIO_CHAN_INFO_INT_TIME: switch (chan->type) { case IIO_INTENSITY: return ltr501_read_it_time(data, val, val2); default: return -EINVAL; } case IIO_CHAN_INFO_SAMP_FREQ: switch (chan->type) { case IIO_INTENSITY: return ltr501_als_read_samp_freq(data, val, val2); case IIO_PROXIMITY: return ltr501_ps_read_samp_freq(data, val, val2); default: return -EINVAL; } } return -EINVAL; } static int ltr501_get_gain_index(struct ltr501_gain *gain, int size, int val, int val2) { int i; for (i = 0; i < size; i++) if (val == gain[i].scale && val2 == gain[i].uscale) { return i; } return -1; } static int ltr501_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int val, int val2, long mask) { struct ltr501_data *data = iio_priv(indio_dev); int i, ret, freq_val, freq_val2; struct ltr501_chip_info *info = data->chip_info; if (iio_buffer_enabled(indio_dev)) { return -EBUSY; } switch (mask) { case IIO_CHAN_INFO_SCALE: switch (chan->type) { case IIO_INTENSITY: i = ltr501_get_gain_index(info->als_gain, info->als_gain_tbl_size, val, val2); if (i < 0) { return -EINVAL; } data->als_contr &= ~info->als_gain_mask; data->als_contr |= i << info->als_gain_shift; return regmap_write(data->regmap, LTR501_ALS_CONTR, data->als_contr); case IIO_PROXIMITY: i = ltr501_get_gain_index(info->ps_gain, info->ps_gain_tbl_size, val, val2); if (i < 0) { return -EINVAL; } data->ps_contr &= ~LTR501_CONTR_PS_GAIN_MASK; data->ps_contr |= i << LTR501_CONTR_PS_GAIN_SHIFT; return regmap_write(data->regmap, LTR501_PS_CONTR, data->ps_contr); default: return -EINVAL; } case IIO_CHAN_INFO_INT_TIME: switch (chan->type) { case IIO_INTENSITY: if (val != 0) { return -EINVAL; } mutex_lock(&data->lock_als); i = ltr501_set_it_time(data, val2); mutex_unlock(&data->lock_als); return i; default: return -EINVAL; } case IIO_CHAN_INFO_SAMP_FREQ: switch (chan->type) { case IIO_INTENSITY: ret = ltr501_als_read_samp_freq(data, &freq_val, &freq_val2); if (ret < 0) { return ret; } ret = ltr501_als_write_samp_freq(data, val, val2); if (ret < 0) { return ret; } /* update persistence count when changing frequency */ ret = ltr501_write_intr_prst(data, chan->type, 0, data->als_period); if (ret < 0) return ltr501_als_write_samp_freq(data, freq_val, freq_val2); return ret; case IIO_PROXIMITY: ret = ltr501_ps_read_samp_freq(data, &freq_val, &freq_val2); if (ret < 0) { return ret; } ret = ltr501_ps_write_samp_freq(data, val, val2); if (ret < 0) { return ret; } /* update persistence count when changing frequency */ ret = ltr501_write_intr_prst(data, chan->type, 0, data->ps_period); if (ret < 0) return ltr501_ps_write_samp_freq(data, freq_val, freq_val2); return ret; default: return -EINVAL; } } return -EINVAL; } static int ltr501_read_thresh(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int *val, int *val2) { struct ltr501_data *data = iio_priv(indio_dev); int ret, thresh_data; switch (chan->type) { case IIO_INTENSITY: switch (dir) { case IIO_EV_DIR_RISING: ret = regmap_bulk_read(data->regmap, LTR501_ALS_THRESH_UP, &thresh_data, 2); if (ret < 0) { return ret; } *val = thresh_data & LTR501_ALS_THRESH_MASK; return IIO_VAL_INT; case IIO_EV_DIR_FALLING: ret = regmap_bulk_read(data->regmap, LTR501_ALS_THRESH_LOW, &thresh_data, 2); if (ret < 0) { return ret; } *val = thresh_data & LTR501_ALS_THRESH_MASK; return IIO_VAL_INT; default: return -EINVAL; } case IIO_PROXIMITY: switch (dir) { case IIO_EV_DIR_RISING: ret = regmap_bulk_read(data->regmap, LTR501_PS_THRESH_UP, &thresh_data, 2); if (ret < 0) { return ret; } *val = thresh_data & LTR501_PS_THRESH_MASK; return IIO_VAL_INT; case IIO_EV_DIR_FALLING: ret = regmap_bulk_read(data->regmap, LTR501_PS_THRESH_LOW, &thresh_data, 2); if (ret < 0) { return ret; } *val = thresh_data & LTR501_PS_THRESH_MASK; return IIO_VAL_INT; default: return -EINVAL; } default: return -EINVAL; } return -EINVAL; } static int ltr501_write_thresh(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int val, int val2) { struct ltr501_data *data = iio_priv(indio_dev); int ret; if (val < 0) { return -EINVAL; } switch (chan->type) { case IIO_INTENSITY: if (val > LTR501_ALS_THRESH_MASK) { return -EINVAL; } switch (dir) { case IIO_EV_DIR_RISING: mutex_lock(&data->lock_als); ret = regmap_bulk_write(data->regmap, LTR501_ALS_THRESH_UP, &val, 2); mutex_unlock(&data->lock_als); return ret; case IIO_EV_DIR_FALLING: mutex_lock(&data->lock_als); ret = regmap_bulk_write(data->regmap, LTR501_ALS_THRESH_LOW, &val, 2); mutex_unlock(&data->lock_als); return ret; default: return -EINVAL; } case IIO_PROXIMITY: if (val > LTR501_PS_THRESH_MASK) { return -EINVAL; } switch (dir) { case IIO_EV_DIR_RISING: mutex_lock(&data->lock_ps); ret = regmap_bulk_write(data->regmap, LTR501_PS_THRESH_UP, &val, 2); mutex_unlock(&data->lock_ps); return ret; case IIO_EV_DIR_FALLING: mutex_lock(&data->lock_ps); ret = regmap_bulk_write(data->regmap, LTR501_PS_THRESH_LOW, &val, 2); mutex_unlock(&data->lock_ps); return ret; default: return -EINVAL; } default: return -EINVAL; } return -EINVAL; } static int ltr501_read_event(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int *val, int *val2) { int ret; switch (info) { case IIO_EV_INFO_VALUE: return ltr501_read_thresh(indio_dev, chan, type, dir, info, val, val2); case IIO_EV_INFO_PERIOD: ret = ltr501_read_intr_prst(iio_priv(indio_dev), chan->type, val2); *val = *val2 / 1000000; *val2 = *val2 % 1000000; return ret; default: return -EINVAL; } return -EINVAL; } static int ltr501_write_event(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int val, int val2) { switch (info) { case IIO_EV_INFO_VALUE: if (val2 != 0) { return -EINVAL; } return ltr501_write_thresh(indio_dev, chan, type, dir, info, val, val2); case IIO_EV_INFO_PERIOD: return ltr501_write_intr_prst(iio_priv(indio_dev), chan->type, val, val2); default: return -EINVAL; } return -EINVAL; } static int ltr501_read_event_config(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir) { struct ltr501_data *data = iio_priv(indio_dev); int ret, status; switch (chan->type) { case IIO_INTENSITY: ret = regmap_field_read(data->reg_als_intr, &status); if (ret < 0) { return ret; } return status; case IIO_PROXIMITY: ret = regmap_field_read(data->reg_ps_intr, &status); if (ret < 0) { return ret; } return status; default: return -EINVAL; } return -EINVAL; } static int ltr501_write_event_config(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, int state) { struct ltr501_data *data = iio_priv(indio_dev); int ret; /* only 1 and 0 are valid inputs */ if (state != 1 && state != 0) { return -EINVAL; } switch (chan->type) { case IIO_INTENSITY: mutex_lock(&data->lock_als); ret = regmap_field_write(data->reg_als_intr, state); mutex_unlock(&data->lock_als); return ret; case IIO_PROXIMITY: mutex_lock(&data->lock_ps); ret = regmap_field_write(data->reg_ps_intr, state); mutex_unlock(&data->lock_ps); return ret; default: return -EINVAL; } return -EINVAL; } static ssize_t ltr501_show_proximity_scale_avail(struct device *dev, struct device_attribute *attr, char *buf) { struct ltr501_data *data = iio_priv(dev_to_iio_dev(dev)); struct ltr501_chip_info *info = data->chip_info; ssize_t len = 0; int i; for (i = 0; i < info->ps_gain_tbl_size; i++) { if (info->ps_gain[i].scale == LTR501_RESERVED_GAIN) { continue; } len += scnprintf(buf + len, PAGE_SIZE - len, "%d.%06d ", info->ps_gain[i].scale, info->ps_gain[i].uscale); } buf[len - 1] = '\n'; return len; } static ssize_t ltr501_show_intensity_scale_avail(struct device *dev, struct device_attribute *attr, char *buf) { struct ltr501_data *data = iio_priv(dev_to_iio_dev(dev)); struct ltr501_chip_info *info = data->chip_info; ssize_t len = 0; int i; for (i = 0; i < info->als_gain_tbl_size; i++) { if (info->als_gain[i].scale == LTR501_RESERVED_GAIN) { continue; } len += scnprintf(buf + len, PAGE_SIZE - len, "%d.%06d ", info->als_gain[i].scale, info->als_gain[i].uscale); } buf[len - 1] = '\n'; return len; } static IIO_CONST_ATTR_INT_TIME_AVAIL("0.05 0.1 0.2 0.4"); static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("20 10 5 2 1 0.5"); static IIO_DEVICE_ATTR(in_proximity_scale_available, S_IRUGO, ltr501_show_proximity_scale_avail, NULL, 0); static IIO_DEVICE_ATTR(in_intensity_scale_available, S_IRUGO, ltr501_show_intensity_scale_avail, NULL, 0); static struct attribute *ltr501_attributes[] = { &iio_dev_attr_in_proximity_scale_available.dev_attr.attr, &iio_dev_attr_in_intensity_scale_available.dev_attr.attr, &iio_const_attr_integration_time_available.dev_attr.attr, &iio_const_attr_sampling_frequency_available.dev_attr.attr, NULL }; static struct attribute *ltr301_attributes[] = { &iio_dev_attr_in_intensity_scale_available.dev_attr.attr, &iio_const_attr_integration_time_available.dev_attr.attr, &iio_const_attr_sampling_frequency_available.dev_attr.attr, NULL }; static const struct attribute_group ltr501_attribute_group = { .attrs = ltr501_attributes, }; static const struct attribute_group ltr301_attribute_group = { .attrs = ltr301_attributes, }; static const struct iio_info ltr501_info_no_irq = { .read_raw = ltr501_read_raw, .write_raw = ltr501_write_raw, .attrs = &ltr501_attribute_group, .driver_module = THIS_MODULE, }; static const struct iio_info ltr501_info = { .read_raw = ltr501_read_raw, .write_raw = ltr501_write_raw, .attrs = &ltr501_attribute_group, .read_event_value = &ltr501_read_event, .write_event_value = &ltr501_write_event, .read_event_config = &ltr501_read_event_config, .write_event_config = &ltr501_write_event_config, .driver_module = THIS_MODULE, }; static const struct iio_info ltr301_info_no_irq = { .read_raw = ltr501_read_raw, .write_raw = ltr501_write_raw, .attrs = &ltr301_attribute_group, .driver_module = THIS_MODULE, }; static const struct iio_info ltr301_info = { .read_raw = ltr501_read_raw, .write_raw = ltr501_write_raw, .attrs = &ltr301_attribute_group, .read_event_value = &ltr501_read_event, .write_event_value = &ltr501_write_event, .read_event_config = &ltr501_read_event_config, .write_event_config = &ltr501_write_event_config, .driver_module = THIS_MODULE, }; static struct ltr501_chip_info ltr501_chip_info_tbl[] = { [ltr501] = { .partid = 0x08, .als_gain = ltr501_als_gain_tbl, .als_gain_tbl_size = ARRAY_SIZE(ltr501_als_gain_tbl), .ps_gain = ltr501_ps_gain_tbl, .ps_gain_tbl_size = ARRAY_SIZE(ltr501_ps_gain_tbl), .als_mode_active = BIT(0) | BIT(1), .als_gain_mask = BIT(3), .als_gain_shift = 3, .info = &ltr501_info, .info_no_irq = &ltr501_info_no_irq, .channels = ltr501_channels, .no_channels = ARRAY_SIZE(ltr501_channels), }, [ltr559] = { .partid = 0x09, .als_gain = ltr559_als_gain_tbl, .als_gain_tbl_size = ARRAY_SIZE(ltr559_als_gain_tbl), .ps_gain = ltr559_ps_gain_tbl, .ps_gain_tbl_size = ARRAY_SIZE(ltr559_ps_gain_tbl), .als_mode_active = BIT(1), .als_gain_mask = BIT(2) | BIT(3) | BIT(4), .als_gain_shift = 2, .info = &ltr501_info, .info_no_irq = &ltr501_info_no_irq, .channels = ltr501_channels, .no_channels = ARRAY_SIZE(ltr501_channels), }, [ltr301] = { .partid = 0x08, .als_gain = ltr501_als_gain_tbl, .als_gain_tbl_size = ARRAY_SIZE(ltr501_als_gain_tbl), .als_mode_active = BIT(0) | BIT(1), .als_gain_mask = BIT(3), .als_gain_shift = 3, .info = &ltr301_info, .info_no_irq = &ltr301_info_no_irq, .channels = ltr301_channels, .no_channels = ARRAY_SIZE(ltr301_channels), }, }; static int ltr501_write_contr(struct ltr501_data *data, u8 als_val, u8 ps_val) { int ret; ret = regmap_write(data->regmap, LTR501_ALS_CONTR, als_val); if (ret < 0) { return ret; } return regmap_write(data->regmap, LTR501_PS_CONTR, ps_val); } static irqreturn_t ltr501_trigger_handler(int irq, void *p) { struct iio_poll_func *pf = p; struct iio_dev *indio_dev = pf->indio_dev; struct ltr501_data *data = iio_priv(indio_dev); u16 buf[8]; __le16 als_buf[2]; u8 mask = 0; int j = 0; int ret, psdata; memset(buf, 0, sizeof(buf)); /* figure out which data needs to be ready */ if (test_bit(0, indio_dev->active_scan_mask) || test_bit(1, indio_dev->active_scan_mask)) { mask |= LTR501_STATUS_ALS_RDY; } if (test_bit(2, indio_dev->active_scan_mask)) { mask |= LTR501_STATUS_PS_RDY; } ret = ltr501_drdy(data, mask); if (ret < 0) { goto done; } if (mask & LTR501_STATUS_ALS_RDY) { ret = regmap_bulk_read(data->regmap, LTR501_ALS_DATA1, (u8 *)als_buf, sizeof(als_buf)); if (ret < 0) { return ret; } if (test_bit(0, indio_dev->active_scan_mask)) { buf[j++] = le16_to_cpu(als_buf[1]); } if (test_bit(1, indio_dev->active_scan_mask)) { buf[j++] = le16_to_cpu(als_buf[0]); } } if (mask & LTR501_STATUS_PS_RDY) { ret = regmap_bulk_read(data->regmap, LTR501_PS_DATA, &psdata, 2); if (ret < 0) { goto done; } buf[j++] = psdata & LTR501_PS_DATA_MASK; } iio_push_to_buffers_with_timestamp(indio_dev, buf, iio_get_time_ns(indio_dev)); done: iio_trigger_notify_done(indio_dev->trig); return IRQ_HANDLED; } static irqreturn_t ltr501_interrupt_handler(int irq, void *private) { struct iio_dev *indio_dev = private; struct ltr501_data *data = iio_priv(indio_dev); int ret, status; ret = regmap_read(data->regmap, LTR501_ALS_PS_STATUS, &status); if (ret < 0) { dev_err(&data->client->dev, "irq read int reg failed\n"); return IRQ_HANDLED; } if (status & LTR501_STATUS_ALS_INTR) iio_push_event(indio_dev, IIO_UNMOD_EVENT_CODE(IIO_INTENSITY, 0, IIO_EV_TYPE_THRESH, IIO_EV_DIR_EITHER), iio_get_time_ns(indio_dev)); if (status & LTR501_STATUS_PS_INTR) iio_push_event(indio_dev, IIO_UNMOD_EVENT_CODE(IIO_PROXIMITY, 0, IIO_EV_TYPE_THRESH, IIO_EV_DIR_EITHER), iio_get_time_ns(indio_dev)); return IRQ_HANDLED; } static int ltr501_init(struct ltr501_data *data) { int ret, status; ret = regmap_read(data->regmap, LTR501_ALS_CONTR, &status); if (ret < 0) { return ret; } data->als_contr = status | data->chip_info->als_mode_active; ret = regmap_read(data->regmap, LTR501_PS_CONTR, &status); if (ret < 0) { return ret; } data->ps_contr = status | LTR501_CONTR_ACTIVE; ret = ltr501_read_intr_prst(data, IIO_INTENSITY, &data->als_period); if (ret < 0) { return ret; } ret = ltr501_read_intr_prst(data, IIO_PROXIMITY, &data->ps_period); if (ret < 0) { return ret; } return ltr501_write_contr(data, data->als_contr, data->ps_contr); } static bool ltr501_is_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { case LTR501_ALS_DATA1: case LTR501_ALS_DATA0: case LTR501_ALS_PS_STATUS: case LTR501_PS_DATA: return true; default: return false; } } static struct regmap_config ltr501_regmap_config = { .name = LTR501_REGMAP_NAME, .reg_bits = 8, .val_bits = 8, .max_register = LTR501_MAX_REG, .cache_type = REGCACHE_RBTREE, .volatile_reg = ltr501_is_volatile_reg, }; static int ltr501_powerdown(struct ltr501_data *data) { return ltr501_write_contr(data, data->als_contr & ~data->chip_info->als_mode_active, data->ps_contr & ~LTR501_CONTR_ACTIVE); } static const char *ltr501_match_acpi_device(struct device *dev, int *chip_idx) { const struct acpi_device_id *id; id = acpi_match_device(dev->driver->acpi_match_table, dev); if (!id) { return NULL; } *chip_idx = id->driver_data; return dev_name(dev); } static int ltr501_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct ltr501_data *data; struct iio_dev *indio_dev; struct regmap *regmap; int ret, partid, chip_idx = 0; const char *name = NULL; indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data)); if (!indio_dev) { return -ENOMEM; } regmap = devm_regmap_init_i2c(client, &ltr501_regmap_config); if (IS_ERR(regmap)) { dev_err(&client->dev, "Regmap initialization failed.\n"); return PTR_ERR(regmap); } data = iio_priv(indio_dev); i2c_set_clientdata(client, indio_dev); data->client = client; data->regmap = regmap; mutex_init(&data->lock_als); mutex_init(&data->lock_ps); data->reg_it = devm_regmap_field_alloc(&client->dev, regmap, reg_field_it); if (IS_ERR(data->reg_it)) { dev_err(&client->dev, "Integ time reg field init failed.\n"); return PTR_ERR(data->reg_it); } data->reg_als_intr = devm_regmap_field_alloc(&client->dev, regmap, reg_field_als_intr); if (IS_ERR(data->reg_als_intr)) { dev_err(&client->dev, "ALS intr mode reg field init failed\n"); return PTR_ERR(data->reg_als_intr); } data->reg_ps_intr = devm_regmap_field_alloc(&client->dev, regmap, reg_field_ps_intr); if (IS_ERR(data->reg_ps_intr)) { dev_err(&client->dev, "PS intr mode reg field init failed.\n"); return PTR_ERR(data->reg_ps_intr); } data->reg_als_rate = devm_regmap_field_alloc(&client->dev, regmap, reg_field_als_rate); if (IS_ERR(data->reg_als_rate)) { dev_err(&client->dev, "ALS samp rate field init failed.\n"); return PTR_ERR(data->reg_als_rate); } data->reg_ps_rate = devm_regmap_field_alloc(&client->dev, regmap, reg_field_ps_rate); if (IS_ERR(data->reg_ps_rate)) { dev_err(&client->dev, "PS samp rate field init failed.\n"); return PTR_ERR(data->reg_ps_rate); } data->reg_als_prst = devm_regmap_field_alloc(&client->dev, regmap, reg_field_als_prst); if (IS_ERR(data->reg_als_prst)) { dev_err(&client->dev, "ALS prst reg field init failed\n"); return PTR_ERR(data->reg_als_prst); } data->reg_ps_prst = devm_regmap_field_alloc(&client->dev, regmap, reg_field_ps_prst); if (IS_ERR(data->reg_ps_prst)) { dev_err(&client->dev, "PS prst reg field init failed.\n"); return PTR_ERR(data->reg_ps_prst); } ret = regmap_read(data->regmap, LTR501_PART_ID, &partid); if (ret < 0) { return ret; } if (id) { name = id->name; chip_idx = id->driver_data; } else if (ACPI_HANDLE(&client->dev)) { name = ltr501_match_acpi_device(&client->dev, &chip_idx); } else { return -ENODEV; } data->chip_info = &ltr501_chip_info_tbl[chip_idx]; if ((partid >> 4) != data->chip_info->partid) { return -ENODEV; } indio_dev->dev.parent = &client->dev; indio_dev->info = data->chip_info->info; indio_dev->channels = data->chip_info->channels; indio_dev->num_channels = data->chip_info->no_channels; indio_dev->name = name; indio_dev->modes = INDIO_DIRECT_MODE; ret = ltr501_init(data); if (ret < 0) { return ret; } if (client->irq > 0) { ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, ltr501_interrupt_handler, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, "ltr501_thresh_event", indio_dev); if (ret) { dev_err(&client->dev, "request irq (%d) failed\n", client->irq); return ret; } } else { indio_dev->info = data->chip_info->info_no_irq; } ret = iio_triggered_buffer_setup(indio_dev, NULL, ltr501_trigger_handler, NULL); if (ret) { goto powerdown_on_error; } ret = iio_device_register(indio_dev); if (ret) { goto error_unreg_buffer; } return 0; error_unreg_buffer: iio_triggered_buffer_cleanup(indio_dev); powerdown_on_error: ltr501_powerdown(data); return ret; } static int ltr501_remove(struct i2c_client *client) { struct iio_dev *indio_dev = i2c_get_clientdata(client); iio_device_unregister(indio_dev); iio_triggered_buffer_cleanup(indio_dev); ltr501_powerdown(iio_priv(indio_dev)); return 0; } #ifdef CONFIG_PM_SLEEP static int ltr501_suspend(struct device *dev) { struct ltr501_data *data = iio_priv(i2c_get_clientdata( to_i2c_client(dev))); return ltr501_powerdown(data); } static int ltr501_resume(struct device *dev) { struct ltr501_data *data = iio_priv(i2c_get_clientdata( to_i2c_client(dev))); return ltr501_write_contr(data, data->als_contr, data->ps_contr); } #endif static SIMPLE_DEV_PM_OPS(ltr501_pm_ops, ltr501_suspend, ltr501_resume); static const struct acpi_device_id ltr_acpi_match[] = { {"LTER0501", ltr501}, {"LTER0559", ltr559}, {"LTER0301", ltr301}, { }, }; MODULE_DEVICE_TABLE(acpi, ltr_acpi_match); static const struct i2c_device_id ltr501_id[] = { { "ltr501", ltr501}, { "ltr559", ltr559}, { "ltr301", ltr301}, { } }; MODULE_DEVICE_TABLE(i2c, ltr501_id); static struct i2c_driver ltr501_driver = { .driver = { .name = LTR501_DRV_NAME, .pm = &ltr501_pm_ops, .acpi_match_table = ACPI_PTR(ltr_acpi_match), }, .probe = ltr501_probe, .remove = ltr501_remove, .id_table = ltr501_id, }; module_i2c_driver(ltr501_driver); MODULE_AUTHOR("Peter Meerwald <pmeerw@pmeerw.net>"); MODULE_DESCRIPTION("Lite-On LTR501 ambient light and proximity sensor driver"); MODULE_LICENSE("GPL");
williamfdevine/PrettyLinux
drivers/iio/light/ltr501.c
C
gpl-3.0
40,731
package jene.samples.surface3d; import java.util.ArrayList; import java.util.List; import javax.vecmath.Point3d; import jene.AbstractOrganism; import jene.Mutation; import jene.Mutator; import jene.Node; import jene.Organism; import jene.Pixel; import jene.Utils; /** * * @author James Stout * */ public class S3DOrganism extends AbstractOrganism<UV, Point3d> { static double VALUE = .7; static double COLOR_DRIFT = .1; private List<Node<Pixel,Double>> _roots; private double[] _color; S3DOrganism(List<Node<Pixel, Double>> roots, double[] color) { _roots = new ArrayList<Node<Pixel,Double>>(roots); _color = color; } public float[] color() { int[] color = RgbHsv.HSVtoRGB((float) _color[0],(float) _color[1], (float) _color[2]); return new float[] {color[0]/256.0f, color[1]/256.0f, color[2]/256.0f}; } public Point3d evaluate(UV input) { return new Point3d(_roots.get(0).evaluate(new Pixel(input.u, input.v)), _roots.get(1).evaluate(new Pixel(input.u, input.v)), _roots.get(2).evaluate(new Pixel(input.u, input.v))); } public List<? extends Node<?, ?>> nodes() { return _roots; } public S3DOrganism mutateAsexually(Mutator mutator) { List<Mutation> mutations = new ArrayList<Mutation>(); List<Node<Pixel,Double>> newRoots = new ArrayList<Node<Pixel,Double>>(); for (Node<Pixel, Double> root : _roots) { newRoots.add(mutator.mutateNodeTree(root, mutations)); } // drift color double[] newColor = new double[] {_color[0], _color[1], _color[2]}; newColor[0] = newColor[0] + COLOR_DRIFT * Utils.RANDOM.nextGaussian() + 1.; newColor[0] = newColor[0] - Math.floor(newColor[0]); //newColor [0] = Math.min(1.0, Math.max(0.0,newColor[0] + COLOR_DRIFT * Utils.RANDOM.nextGaussian())); newColor[1] = Math.min(1.0, Math.max(0.5, newColor[1] + COLOR_DRIFT * Utils.RANDOM.nextGaussian())); return new S3DOrganism(newRoots, newColor); } public S3DOrganism mutateSexually( Organism<UV, Point3d> mate, Mutator mutator) { S3DOrganism myMate = (S3DOrganism) mate; List<Node<Pixel, Double>> mateNodes = myMate._roots; List<Node<Pixel, Double>> newNodes = new ArrayList<Node<Pixel,Double>>(); int i=0; for (Node<Pixel, Double> mateNode : mateNodes) { newNodes.add(mutator.mateNodeTrees(_roots.get(i++), mateNode)); } int[] color1 = RgbHsv.HSVtoRGB((float) _color[0],(float) _color[1], (float) _color[2]); int[] color2 = RgbHsv.HSVtoRGB((float) myMate._color[0],(float) myMate._color[1], (float) myMate._color[2]); int[] newColor = new int[] {(color1[0]+color2[0])/2, (color1[1]+color2[1])/2, (color1[2]+color2[2])/2}; float[] newHsvf = RgbHsv.RGBtoHSV(newColor[0], newColor[1], newColor[2], null); double[] newHsv = new double[] {newHsvf[0], newHsvf[1], VALUE}; return new S3DOrganism(newNodes, newHsv); } }
wolfmanstout/jene
src/jene/samples/surface3d/S3DOrganism.java
Java
gpl-3.0
2,816
FROM geerlingguy/docker-centos6-ansible:latest RUN yum install -y python-pip RUN pip install --upgrade --ignore-installed --no-cache-dir pip RUN pip install setuptools==33.1.1 --ignore-installed --no-cache-dir RUN pip install python-logstash --ignore-installed --no-cache-dir RUN yum install -y sudo curl tar wget
pgporada/ansible-gutenberg
containers/centos6/Dockerfile
Dockerfile
gpl-3.0
314
from edges import EdgeExtractor from extractor import Extractor from parambfs import ParamExtractor
daajoe/trellis
trellis/extractor/__init__.py
Python
gpl-3.0
99
package com.example.androidwebsocket; import org.json.JSONArray; import org.json.JSONObject; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import de.tavendo.autobahn.WebSocket; import de.tavendo.autobahn.WebSocketConnection; import de.tavendo.autobahn.WebSocketException; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import org.apache.http.Header; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private WebSocketConnection mWebConnection = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { connetWebSocket(); } catch (WebSocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.findViewById(R.id.button1).setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub if (mWebConnection != null) { mWebConnection.sendTextMessage("Test"); } } }); final JsonHttpResponseHandler handler = new JsonHttpResponseHandler() { public void onSuccess(JSONArray arg0) { // 成功后返回一个JSONArray数据 Log.i("hck", arg0.length() + ""); try { } catch (Exception e) { Log.e("hck", e.toString()); } }; public void onFailure(Throwable arg0) { Log.e("hck", " onFailure" + arg0.toString()); }; public void onFinish() { Log.i("hck", "onFinish"); }; @Override public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) { Log.i("hck", "onSuccess "); Log.d("hck", responseBody.toString()); }; }; this.findViewById(R.id.button2).setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub AsyncHttpClient client =new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("intValue", 1); params.put("stringValue", "test"); client.post("http://10.100.13.64:8080/data2", params, handler); } }); } private void connetWebSocket() throws WebSocketException { mWebConnection = new WebSocketConnection(); mWebConnection.connect("ws://10.100.13.151:8080/websocket", new WebSocket.ConnectionHandler(){ @Override public void onOpen() { // TODO Auto-generated method stub Log.d(TAG, "WebSocketConnection & onOpen()"); mWebConnection.sendTextMessage("Hello Android Web Socket"); } @Override public void onClose(int code, String reason) { // TODO Auto-generated method stub Log.d(TAG, "WebSocketConnection & onClose()"); } @Override public void onTextMessage(String payload) { // TODO Auto-generated method stub Log.d(TAG, "Receive:"+payload); } @Override public void onRawTextMessage(byte[] payload) { // TODO Auto-generated method stub Log.d(TAG, "Receive:"+payload.toString()); } @Override public void onBinaryMessage(byte[] payload) { // TODO Auto-generated method stub } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
xzzhuo/GitStudy
AndroidWebSocket/src/com/example/androidwebsocket/MainActivity.java
Java
gpl-3.0
4,172
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (1.8.0_101) on Fri Nov 25 11:47:49 CET 2016 --> <title>Uses of Class fr.cdiEnterprise.view.MainFrame</title> <meta name="date" content="2016-11-25"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class fr.cdiEnterprise.view.MainFrame"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../fr/cdiEnterprise/view/MainFrame.html" title="class in fr.cdiEnterprise.view">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?fr/cdiEnterprise/view/class-use/MainFrame.html" target="_top">Frames</a></li> <li><a href="MainFrame.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class fr.cdiEnterprise.view.MainFrame" class="title">Uses of Class<br>fr.cdiEnterprise.view.MainFrame</h2> </div> <div class="classUseContainer">No usage of fr.cdiEnterprise.view.MainFrame</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../fr/cdiEnterprise/view/MainFrame.html" title="class in fr.cdiEnterprise.view">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?fr/cdiEnterprise/view/class-use/MainFrame.html" target="_top">Frames</a></li> <li><a href="MainFrame.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
CDI-Enterprise/ecf-16035-b
doc-ecf-2/fr/cdiEnterprise/view/class-use/MainFrame.html
HTML
gpl-3.0
4,398
/*** *sys/timeb.h - definition/declarations for _ftime() * * Copyright (c) Microsoft Corporation. All rights reserved. * *Purpose: * This file define the _ftime() function and the types it uses. * [System V] * * [Public] * ****/ #if _MSC_VER > 1000 #pragma once #endif #ifndef _INC_TIMEB #define _INC_TIMEB #include <crtdefs.h> #if !defined(_WIN32) #error ERROR: Only Win32 target supported! #endif #ifdef _MSC_VER #pragma pack(push,_CRT_PACKING) #endif /* _MSC_VER */ #ifdef __cplusplus extern "C" { #endif /* Define _CRTIMP */ #ifndef _CRTIMP #ifdef _DLL #define _CRTIMP __declspec(dllimport) #else /* ndef _DLL */ #define _CRTIMP #endif /* _DLL */ #endif /* _CRTIMP */ /* Define __cdecl for non-Microsoft compilers */ #if ( !defined(_MSC_VER) && !defined(__cdecl) ) #define __cdecl #endif #if !defined(_W64) #if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 #define _W64 __w64 #else #define _W64 #endif #endif #ifdef _USE_32BIT_TIME_T #ifdef _WIN64 #include <crtwrn.h> #pragma _CRT_WARNING( _NO_32BIT_TIME_T ) #undef _USE_32BIT_TIME_T #endif #else #if _INTEGRAL_MAX_BITS < 64 #define _USE_32BIT_TIME_T #endif #endif #ifndef _TIME32_T_DEFINED typedef _W64 long __time32_t; /* 32-bit time value */ #define _TIME32_T_DEFINED #endif #ifndef _TIME64_T_DEFINED #if _INTEGRAL_MAX_BITS >= 64 typedef __int64 __time64_t; /* 64-bit time value */ #endif #define _TIME64_T_DEFINED #endif #ifndef _TIME_T_DEFINED #ifdef _USE_32BIT_TIME_T typedef __time32_t time_t; /* time value */ #else typedef __time64_t time_t; /* time value */ #endif #define _TIME_T_DEFINED /* avoid multiple def's of time_t */ #endif /* Structure returned by _ftime system call */ #ifndef _TIMEB_DEFINED struct __timeb32 { __time32_t time; unsigned short millitm; short timezone; short dstflag; }; #if !__STDC__ /* Non-ANSI name for compatibility */ struct timeb { time_t time; unsigned short millitm; short timezone; short dstflag; }; #endif #if _INTEGRAL_MAX_BITS >= 64 struct __timeb64 { __time64_t time; unsigned short millitm; short timezone; short dstflag; }; #endif #ifdef _USE_32BIT_TIME_T #define _timeb __timeb32 #define _ftime _ftime32 #define _ftime_s _ftime32_s #else #define _timeb __timeb64 #define _ftime _ftime64 #define _ftime_s _ftime64_s #endif #define _TIMEB_DEFINED #endif #include <crtdefs.h> /* Function prototypes */ _CRT_INSECURE_DEPRECATE(_ftime32_s) _CRTIMP void __cdecl _ftime32(__out struct __timeb32 * _Time); _CRTIMP errno_t __cdecl _ftime32_s(__out struct __timeb32 * _Time); #if _INTEGRAL_MAX_BITS >= 64 _CRT_INSECURE_DEPRECATE(_ftime64_s) _CRTIMP void __cdecl _ftime64(__out struct __timeb64 * _Time); _CRTIMP errno_t __cdecl _ftime64_s(__out struct __timeb64 * _Time); #endif #if !defined(RC_INVOKED) && !defined(__midl) #include <sys/timeb.inl> #endif #ifdef __cplusplus } #endif #ifdef _MSC_VER #pragma pack(pop) #endif /* _MSC_VER */ #endif /* _INC_TIMEB */
willjoseph/cpparch
cpparch/cppparse/msvc-8.0/include/sys/timeb.h
C
gpl-3.0
3,340
/** vi:ft=cpp ts=8 et sw=4 sts=4 tw=80 * emacs: -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 8; c-file-style: "linux" -*- * * scan_python: * Use external python scripts to post-process flow files * * 2020-09-27 - slg - removed from build because this is only Python 2.7 */ #include "config.h" #include "dfxml/src/hash_t.h" #include "tcpflow.h" #include <iostream> #include <sys/types.h> #if HAVE_PYTHON2_7_PYTHON_H # include <python2.7/Python.h> // Get header: install package "python-devel" #endif struct ScanPython { ScanPython() : py_path() , py_module() , py_function() , init_script() #if HAVE_PYTHON2_7_PYTHON_H , pythonFunction (NULL) #endif { } ScanPython(const ScanPython& o) : py_path(o.py_path) , py_module(o.py_module) , py_function(o.py_function) , init_script(o.init_script) #if HAVE_PYTHON2_7_PYTHON_H , pythonFunction (NULL) #endif { } ScanPython& operator=(const ScanPython& o) { py_path = o.py_path; py_module = o.py_module; py_function = o.py_function; init_script = o.init_script; #if HAVE_PYTHON2_7_PYTHON_H pythonFunction = NULL; #endif return *this; } void startup(const scanner_params& sp); void init(const scanner_params& sp); void before(); void scan(const scanner_params& sp); void shutdown(); std::string py_path; std::string py_module; std::string py_function; std::string init_script; #if HAVE_PYTHON2_7_PYTHON_H PyObject* pythonFunction; #endif }; void ScanPython::startup(const scanner_params& sp) { if (sp.sp_version != scanner_params::CURRENT_SP_VERSION) { std::cerr << "scan_python requires sp version " << scanner_params::CURRENT_SP_VERSION << "; " << "got version " << sp.sp_version << "\n"; exit(1); } sp.info->name = "python"; sp.info->flags = scanner_info::SCANNER_DISABLED; sp.info->get_config("py_path", &py_path, " Directory to find python module (optional)"); sp.info->get_config("py_module", &py_module, " Name of python module (script name without extension)"); sp.info->get_config("py_function", &py_function, "Function name within the python module"); } static std::string get_working_dir(const std::string& path) { if (path.empty()) { return "os.getcwd()"; } if (path[0] == '/'){ return "'" + path + "'"; } else { return "os.getcwd() + '/" + path + "'"; } } void ScanPython::init(const scanner_params& /*sp*/) { if (py_module.empty() || py_function.empty()) { DEBUG(1)("[scan_python] Cannot call python becase no provided module/function." "\n" "\t\t\t\t" "Please use arguments -S py_module=module -S py_function=foo" ); // "\n" "\t\t\t\t" "The scanner 'python' is disabled to avoid warning messages."); // sp.info->flags = scanner_info::SCANNER_DISABLED; // TODO(simsong): Should we disable the scanner to avoid warnings? return; } // Write the initialization script to set directory to the local system path init_script = "import sys, os" "\n" "workingDir = " + get_working_dir(py_path) + "\n" "sys.path.append(workingDir)" "\n"; #if HAVE_PYTHON2_7_PYTHON_H // Spawn python interpreter Py_Initialize(); DEBUG(10) ("[scan_python] Initialize Python using script:" "\n" "%s", init_script.c_str()); PyRun_SimpleString(init_script.c_str()); // Create PyObject from script filename PyObject* pName = PyString_FromString(py_module.c_str()); if (pName == NULL) { DEBUG(2) ("[scan_python] Cannot create PyObject from path='%s' and module='%s'" "\n" "\t\t\t" "Try using three arguments: -S py_path=path -S py_module=module -S py_function=foo", py_path.c_str(), py_module.c_str()); return; } // Import script file in python interpreter PyObject* pModule = PyImport_Import(pName); if (pModule == NULL) { DEBUG(2) ("[scan_python] Cannot import module='%s' from path='%s' in Python interpreter" "\n" "\t\t\t" "Try using three arguments: -S py_path=path -S py_module=module -S py_function=foo", py_module.c_str(), py_path.c_str()); return; } // Identify function to be used pythonFunction = PyObject_GetAttrString(pModule, py_function.c_str()); if (pythonFunction == NULL) { DEBUG(2) ("[scan_python] Cannot identify function='%s' in module='%s' from path='%s'" "\n" "\t\t\t" "Try using three arguments: -S py_path=path -S py_module=module -S py_function=foo", py_function.c_str(), py_module.c_str(), py_path.c_str()); return; } #endif } // TODO(simsong): Why is PHASE_THREAD_BEFORE_SCAN never processed? void ScanPython::before() { } void ScanPython::scan(const scanner_params& sp) { #if HAVE_PYTHON2_7_PYTHON_H if (pythonFunction == NULL) { init(sp); if (pythonFunction == NULL) { // DEBUG(1)("[scan_python] Cannot initialize => Disabled the scanner to avoid warning messages."); // sp.info->flags = scanner_info::SCANNER_DISABLED; // TODO(simsong): Should we disable the scanner to avoid warnings? return; } } // Cast packet buffer contents into a string and create pyObject std::string data(reinterpret_cast<char const*>(sp.sbuf.buf)); PyObject* pData = PyString_FromString(data.c_str()); // Compose python argument in the form of a tuple and pass the argument to // the chosen function; if the function does not return anything or // encounters an error, return to exit and/or display the error PyObject* pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, pData); PyObject* pResult = PyObject_CallObject(pythonFunction, pArgs); if (pResult) { // If XML-reporting enabled => Insert the string returned by the python function if (sp.sxml) { const char* returned_string = PyString_AsString(pResult); (*sp.sxml) << "<tcpflow:result scan=\"python\" " "path=\""<< py_path <<"\" " "module=\""<< py_module <<"\" " "function=\""<< py_function; if (returned_string) (*sp.sxml) <<"\">"<< returned_string <<"</tcpflow:result>"; else (*sp.sxml) << "\"/>"; } } #else DEBUG(2) ("[scan_python] tcpflow cannot call python scripts required by the scanner 'python'" "\n" "\t\t" "because the header <python2.7/Python.h> was not present during the tcpflow build." "\n" "\t\t" "Try to install package 'python-devel' and build again tcpflow (./configure)"); #endif } void ScanPython::shutdown() { #if HAVE_PYTHON2_7_PYTHON_H // Terminate the python interpreter and exit Py_Finalize(); pythonFunction = NULL; #endif } extern "C" void scan_python(const scanner_params& sp, const recursion_control_block& /*rcb*/) { static ScanPython singleton; switch (sp.phase) { case scanner_params::PHASE_NONE: break; // Called in main thread to parse configuration // (also used to build the --help text) case scanner_params::PHASE_STARTUP: singleton.startup(sp); break; // Should be called in main thread after all scanners loaded (but never called) case scanner_params::PHASE_INIT: singleton.init(sp); break; // Called in worker thread before first scan case scanner_params::PHASE_THREAD_BEFORE_SCAN: singleton.before(); break; // Called in worker thread for each sbuf case scanner_params::PHASE_SCAN: singleton.scan(sp); break; // Called in main thread when scanner is shutdown case scanner_params::PHASE_SHUTDOWN: singleton.shutdown(); break; } }
simsong/tcpflow
src/scan_python.cpp
C++
gpl-3.0
8,167
<?php /** * Export the configurations by MAC address and file type */ $access_role = "reader"; require_once("access.php"); require_once("lib/validate.php"); Header("Content-Type: text/plain; charset=UTF-8"); if ($_GET["type"] == "sig") { echo "voipconf\n"; exit(0); } if (($mac = valid_mac($_GET["mac"])) === false) exit(1); require_once("lib/ini.php"); $chan = new Ini(); $chan->load($g_chan_sync); foreach ($chan->sections() as $user) { if ($chan->get($user, "mac") == $mac) { $username = $user; break; } } if (!isset($username)) exit(1); switch ($_GET["type"]) { case "sbo": ?> [<?php echo $username; ?>] type=friend host=<?php echo $g_serv_ip; ?> secret=<?php echo $chan->get($username, "secret"); ?> context=<?php echo $username; ?> sbo_tunnel=yes <?php break; case "chan_sync": ?> [<?php echo $username; ?>] authname=<?php echo $username; ?> secret=<?php echo $chan->get($username, "secret"); ?> host=<?php echo $g_serv_ip; ?> port=<?php echo $g_serv_port; ?> context=<?php echo $username; ?> disallow=all allow=g729,g723 <?php break; case "ael": require_once("lib/ext.php"); $contents = file_get_contents($g_ext_usr); while (strlen($contents) > 0) { $len = ExtParser::extractBlock($contents); if ($len === false) break; $block = substr($contents, 0, $len); $segs = preg_split("/\s+/", $block); if ($segs[1] == $username) { echo $block; break; } $contents = ltrim(substr($contents, $len)); } break; case "sbo-general-register": echo "$username:" . $chan->get($username, "secret") . "@$g_serv_ip:$g_serv_port\n"; break; default: exit(1); } ?>
xiaosuo/voipconf
export.php
PHP
gpl-3.0
1,613
#ifndef MANTID_CURVEFITTING_SIMPLECHEBFUNTEST_H_ #define MANTID_CURVEFITTING_SIMPLECHEBFUNTEST_H_ #include <cxxtest/TestSuite.h> #include "MantidCurveFitting/Functions/SimpleChebfun.h" #include <cmath> using namespace Mantid; using namespace Mantid::API; using namespace Mantid::CurveFitting; using namespace Mantid::CurveFitting::Functions; namespace { double Sin(double x) { return sin(x); } double Cos(double x) { return cos(x); } double Exp(double x) { return exp(-x * x / 2); } } class SimpleChebfunTest : public CxxTest::TestSuite { public: // This pair of boilerplate methods prevent the suite being created statically // This means the constructor isn't called when running other tests static SimpleChebfunTest *createSuite() { return new SimpleChebfunTest(); } static void destroySuite(SimpleChebfunTest *suite) { delete suite; } void test_constructor_low_accuracy() { SimpleChebfun cheb(5, Sin, -M_PI, M_PI); do_test_values(cheb, Sin, 0.02); TS_ASSERT(cheb.isGood()); } void test_constructor_high_accuracy() { SimpleChebfun cheb(21, Sin, -M_PI, M_PI); do_test_values(cheb, Sin, 1e-15); TS_ASSERT(cheb.isGood()); } void test_constructor_best_fit() { SimpleChebfun cheb(Sin, -M_PI, M_PI); do_test_values(cheb, Sin, 2e-15); TS_ASSERT_EQUALS(cheb.size(), 20); TS_ASSERT(cheb.isGood()); } void test_constructor_bad_fit() { SimpleChebfun cheb(Sin, -1000, 1000); do_test_values(cheb, Sin, 2e-15); TS_ASSERT_EQUALS(cheb.size(), 10); TS_ASSERT(!cheb.isGood()); } void test_constructor_smooth() { double xa[] = { -10, -9.7979797979798, -9.5959595959596, -9.39393939393939, -9.19191919191919, -8.98989898989899, -8.78787878787879, -8.58585858585859, -8.38383838383838, -8.18181818181818, -7.97979797979798, -7.77777777777778, -7.57575757575758, -7.37373737373737, -7.17171717171717, -6.96969696969697, -6.76767676767677, -6.56565656565657, -6.36363636363636, -6.16161616161616, -5.95959595959596, -5.75757575757576, -5.55555555555556, -5.35353535353535, -5.15151515151515, -4.94949494949495, -4.74747474747475, -4.54545454545455, -4.34343434343434, -4.14141414141414, -3.93939393939394, -3.73737373737374, -3.53535353535354, -3.33333333333333, -3.13131313131313, -2.92929292929293, -2.72727272727273, -2.52525252525253, -2.32323232323232, -2.12121212121212, -1.91919191919192, -1.71717171717172, -1.51515151515152, -1.31313131313131, -1.11111111111111, -0.90909090909091, -0.707070707070708, -0.505050505050505, -0.303030303030303, -0.1010101010101, 0.1010101010101, 0.303030303030303, 0.505050505050505, 0.707070707070708, 0.909090909090908, 1.11111111111111, 1.31313131313131, 1.51515151515152, 1.71717171717172, 1.91919191919192, 2.12121212121212, 2.32323232323232, 2.52525252525252, 2.72727272727273, 2.92929292929293, 3.13131313131313, 3.33333333333333, 3.53535353535353, 3.73737373737374, 3.93939393939394, 4.14141414141414, 4.34343434343434, 4.54545454545454, 4.74747474747475, 4.94949494949495, 5.15151515151515, 5.35353535353535, 5.55555555555556, 5.75757575757576, 5.95959595959596, 6.16161616161616, 6.36363636363636, 6.56565656565656, 6.76767676767677, 6.96969696969697, 7.17171717171717, 7.37373737373737, 7.57575757575757, 7.77777777777778, 7.97979797979798, 8.18181818181818, 8.38383838383838, 8.58585858585858, 8.78787878787879, 8.98989898989899, 9.19191919191919, 9.39393939393939, 9.5959595959596, 9.7979797979798, 10}; double ya[] = { 0.00639183934751033, -0.0188335740757259, -0.00899934560411868, 0.00283632596574657, -0.00598441814465674, 0.00696204020099447, -0.00287351005669914, -0.0225096725729169, 0.0111069805441983, -0.00577115078672668, -0.0109182725418975, 0.000532199156305037, 0.00696599114054958, 0.00365932816743702, -0.0200435513032935, 0.00900735793474218, -0.0111338670746253, 0.023255697971321, -0.00832455823569091, -0.0029048509120321, -0.0153785693305323, -0.00180000537108807, 0.00596251427052631, 0.0172553307333174, 0.00361568201271514, 0.00928919020849222, -0.0211978053309214, -0.00222464964883951, 0.00360438675108187, 0.00530721642552667, 0.00784709918377635, 0.00416006087543879, 0.00960094613670988, 0.00996615094193702, 0.00137548954996262, 0.0207270701280542, 0.0216393663905915, 0.0377090829328035, 0.0579050519986335, 0.0801382017977186, 0.157688228936361, 0.22703382274324, 0.309878514091159, 0.430306496879367, 0.544703938468763, 0.666604084021673, 0.773206598668196, 0.871405974058432, 0.975632619000061, 0.995752614565419, 1.00464752735264, 0.941959943590075, 0.869798994190271, 0.781879765315447, 0.652587049158077, 0.523235702848816, 0.41967192318005, 0.325189965870962, 0.228996533585127, 0.161368813413821, 0.107691324301568, 0.0699110846617227, 0.0638760790932532, 0.0302559377573298, 0.00460798768888443, 0.014804492257474, -1.54042567271596e-05, 0.00465828504155101, 0.0127947548498089, -0.00200744725099752, 0.00340488681152168, 0.00438153206037417, 0.012532700578783, -0.00479858530403384, 0.00996622957226827, -0.00129829848432229, -0.0236134931852313, -0.0167198070830326, -0.0178570689154704, 0.0190929355772175, 0.0197262324322656, 0.0053771716671835, 0.020458130293195, 0.00968251677260515, -0.00308402567609968, -0.01009201343035, -0.0106552592606136, -0.00480150616204374, 0.00257980679328633, 0.0106976614827359, 0.00214320379664739, -0.00465281998719138, 0.00166258796607687, 0.00762058850311789, -0.0175536414593233, 0.027652419889149, -0.00829997647938784, -0.0158371138209429, -0.0216384527223296, -0.007513269418583}; size_t n = sizeof(xa) / sizeof(double); std::vector<double> x(xa, xa + n); std::vector<double> y(ya, ya + n); SimpleChebfun cheb(x, y); TS_ASSERT_EQUALS(cheb.size(), n); TS_ASSERT(cheb.isGood()); do_test_values(cheb, Exp, 0.021, 0.021); } void test_derivative() { SimpleChebfun cheb_sin(Sin, -M_PI, M_PI); auto cheb_cos = cheb_sin.derivative(); do_test_values(cheb_cos, Cos, 1e-13, 1e-13); } void test_roughRoots() { SimpleChebfun cheb(Sin, -2 * M_PI - 0.1, 2 * M_PI + 0.1); auto roots = cheb.roughRoots(); TS_ASSERT_EQUALS(roots.size(), 5); if (roots.size() == 5) { TS_ASSERT_DELTA(roots[0], -2 * M_PI, 1e-4); TS_ASSERT_DELTA(roots[1], -M_PI, 1e-2); TS_ASSERT_DELTA(roots[2], 0, 1e-9); TS_ASSERT_DELTA(roots[3], M_PI, 1e-2); TS_ASSERT_DELTA(roots[4], 2 * M_PI, 1e-4); } } private: void do_test_values(const SimpleChebfun &cheb, std::function<double(double)> fun, double accur1 = 1e-14, double accur2 = 1e-14) { TS_ASSERT(cheb.size() > 0); TS_ASSERT(cheb.width() > 0.0); if (cheb.isGood()) { size_t n = static_cast<size_t>(1.3 * static_cast<double>(cheb.size())); auto x = cheb.linspace(n); for (size_t i = 0; i < n; ++i) { // std::cerr << x[i] << ' ' << cheb(x[i]) - fun(x[i]) << '\n'; TS_ASSERT_DELTA(cheb(x[i]), fun(x[i]), accur1); } } auto &xp = cheb.xPoints(); for (double i : xp) { // std::cerr << xp[i] << ' ' << cheb(xp[i]) - fun(xp[i]) << '\n'; TS_ASSERT_DELTA(cheb(i), fun(i), accur2); } } }; #endif /* MANTID_CURVEFITTING_SIMPLECHEBFUNTEST_H_ */
ScreamingUdder/mantid
Framework/CurveFitting/test/Functions/SimpleChebfunTest.h
C
gpl-3.0
7,815
/** * Copyright (C) 2016 Fernando Berti - Daniel Campodonico - Emiliano Gioria - Lucas Moretti - Esteban Rebechi - Andres Leonel Rico * This file is part of Olimpo. * * Olimpo 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. * * Olimpo 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 Olimpo. If not, see <http://www.gnu.org/licenses/>. */ package app.comun; import java.util.regex.Pattern; import org.springframework.stereotype.Service; /** * Clase encargada de la conversion de strings */ @Service public class FormateadorString { /** * Retorna el string con la primera letra en mayúscula * * @param entrada * string a convertir * @return string de entrada con la primera letra en mayúscula */ public String primeraMayuscula(String entrada) { if(entrada == null){ return null; } switch(entrada.length()) { // Los strings vacíos se retornan como están. case 0: entrada = ""; break; // Los strings de un solo caracter se devuelven en mayúscula. case 1: entrada = entrada.toUpperCase(); break; // Sino, mayúscula la primera letra, minúscula el resto. default: entrada = entrada.substring(0, 1).toUpperCase() + entrada.substring(1).toLowerCase(); } return entrada; } /** * Retorna el string con la primera letra de cada palabra en mayúscula a menos que sean "a|de|del|el|en|la|las|lo|los|of|y" * * @param entrada * string a convertir * @return string de entrada con la primera letra de cada palabra en mayúscula */ public String nombrePropio(String entrada) { if(entrada == null){ return null; } //Si la entrada consiste solo de espacios en blanco, se devuelve una cadena vacía entrada.trim(); if(entrada.equals("")){ return ""; } //Se convierte toda la cadena a minúsculas entrada.toLowerCase(); //Se separan las palabras String[] partes = entrada.split(" "); StringBuffer salida = new StringBuffer(); //Si la palabra es alguna de las siguientes, no se debe convertir a mayúscula su primer letra Pattern patron = Pattern.compile("a|de|del|el|en|la|las|lo|los|of|y"); for(String parte: partes){ if(patron.matcher(parte).matches()){ salida.append(parte + " "); } else{ if(!parte.equals("")){ salida.append(parte.substring(0, 1).toUpperCase() + parte.substring(1) + " "); } } } //Se convierte la primera letra a mayúscula en caso de no haberlo hecho antes y se recortan los espacios al final return (salida.substring(0, 1).toUpperCase() + salida.substring(1)).trim(); } }
bertilxi/Olimpo
src/app/comun/FormateadorString.java
Java
gpl-3.0
3,019
if (typeof com == "undefined") { var com = {}; } com.sppad = com.sppad || {}; com.sppad.booky = com.sppad.booky || {}; com.sppad.booky.Groups = new function() { var self = this; this.bookmarkInfoMap = new com.sppad.collections.Map(); this.groupIdMap = new com.sppad.collections.Map(); this.primaryIdCounts = new com.sppad.collections.Map(); this.bookmarkIdToPrimaryId = new com.sppad.collections.Map(); /** * Gets the launcher ID for a given tab. Currently this is based off the * hostname only. * * @param aTab * A browser tab * @return The id for the launcher for aTab */ this.getPrimaryIdFromTab = function(aTab) { try { let currentUri = gBrowser.getBrowserForTab(aTab).currentURI; return this.getPrimaryIdFromUri(currentUri); } catch (err) { return aTab.label; } }; /** * Gets the launcher ID for a given URI. Currently this is based off the * hostname only. * * @param uriString * A string representing a URI * @return The id for the launcher for uriString */ this.getPrimaryIdFromUriString = function(uriString) { try { return Services.io.newURI(uriString, null, null).host || uriString; } catch (err) { return uriString; } }; this.getPrimaryIdFromUri = function(aUri) { try { return aUri.host || aUri.asciiSpec; } catch (err) { return aUri.asciiSpec; } }; return { getHostFromUriString : function(aUriString) { return self.getPrimaryIdFromUriString(aUriString); }, getHostFromUri : function(aUri) { return self.getPrimaryIdFromUri(aUri); }, getIdFromTab : function(aTab) { let primaryId = self.getPrimaryIdFromTab(aTab); return self.groupIdMap.get(primaryId); }, getIdFromUriString : function(aUriString) { let primaryId = self.getPrimaryIdFromUriString(aUriString); return self.groupIdMap.get(primaryId); }, handleEvent : function(aEvent) { switch (aEvent.type) { case com.sppad.booky.Bookmarks.EVENT_ADD_FOLDER: case com.sppad.booky.Bookmarks.EVENT_LOAD_FOLDER: return this.onFolderAdded(aEvent); case com.sppad.booky.Bookmarks.EVENT_MOV_FOLDER: return this.onFolderMoved(aEvent); case com.sppad.booky.Bookmarks.EVENT_DEL_FOLDER: return this.onFolderRemoved(aEvent); case com.sppad.booky.Bookmarks.EVENT_ADD_BOOKMARK: case com.sppad.booky.Bookmarks.EVENT_LOAD_BOOKMARK: return this.onBookmarkAdded(aEvent); case com.sppad.booky.Bookmarks.EVENT_MOV_BOOKMARK: return this.onBookmarkMoved(aEvent); case com.sppad.booky.Bookmarks.EVENT_DEL_BOOKMARK: return this.onBookmarkRemoved(aEvent); case com.sppad.booky.Bookmarks.EVENT_UPDATE_TITLE: return this.onTitleUpdated(aEvent); default: return null; } }, /** * Moves a bookmark item to the correct launcher folder for that item. * If none exists, a new folder is created and the bookmark is moved * there. * * @param aItemId * A bookmark itemId * @param aUri * A string representing the URI of the bookmark */ moveToCorrectFolder: function(aItemId, aUriString) { let primaryId = self.getPrimaryIdFromUriString(aUriString); let folderId = self.groupIdMap.get(primaryId) || com.sppad.booky.Bookmarks.createFolder(""); com.sppad.booky.Bookmarks.moveAfter(null, aItemId, folderId); }, /** * Handles a bookmark being added. * <p> * For tracked bookmarks, the parentId will correspond to a sub-folder * of the quick launch bookmarks folder. This also acts as the group's * id. */ onBookmarkAdded: function(aEvent) { let itemId = aEvent.itemId; let parentId = com.sppad.booky.Bookmarks.getFolder(itemId); let grandparentId = com.sppad.booky.Bookmarks.getFolder(parentId); // Check if bookmark is directly under the quick launch folder and // move it to the appropriate sub-folder if so. The bookmark move // event will end up calling us again once the bookmark is in the // right location. if(com.sppad.booky.Bookmarks.isQuickLaunchFolder(parentId)) { this.moveToCorrectFolder(itemId, aEvent.uri); return; } // Not in a launcher folder, so nothing to do if(!com.sppad.booky.Bookmarks.isQuickLaunchFolder(grandparentId)) return; let primaryId = self.getPrimaryIdFromUriString(aEvent.uri); let prevFolderId = self.groupIdMap.get(primaryId); // Used to track the parent folder. Needed for when a bookmark is // deleted so we know which launcher it came from. let bookmarkInfo = { 'parentId' : parentId, 'primaryId' : primaryId, }; self.groupIdMap.put(primaryId, parentId); self.bookmarkInfoMap.put(itemId, bookmarkInfo); let launcher = com.sppad.booky.Launcher.getLauncher(parentId); launcher.setBookmarks(com.sppad.booky.Bookmarks.getBookmarks(parentId)); // Get all tabs in the same host let tabs = gBrowser.tabs; let sameHostTabs = new Array(); for(let i=0; i<tabs.length; i++) if(primaryId == self.getPrimaryIdFromTab(tabs[i])) sameHostTabs.push(tabs[i]); // Handle moving betweem two launchers. Moves all bookmarks with the // same host from the old launcher to the new one. let movingLaunchers = (prevFolderId != undefined) && (parentId != prevFolderId); if(movingLaunchers) { // Grab all the bookmarks with the same host and move them let otherbookmarks = com.sppad.booky.Bookmarks.getBookmarks(prevFolderId); otherbookmarks.forEach(function(bookmark) { if(primaryId == self.getPrimaryIdFromUriString(bookmark.uri)) { self.bookmarkInfoMap.put(bookmark.itemId, bookmarkInfo); com.sppad.booky.Bookmarks.moveAfter(null, bookmark.itemId, parentId); } }); let previousLauncher = com.sppad.booky.Launcher.getLauncher(prevFolderId); previousLauncher.removeTabArray(sameHostTabs); previousLauncher.setBookmarks(com.sppad.booky.Bookmarks.getBookmarks(prevFolderId)); } else { /* * Update how many bookmark URIs we are tracking that correspond * to this site. Needed so that we can know when to remove the * mapping between URI and group id. */ let count = self.primaryIdCounts.get(primaryId, 0) + 1; self.primaryIdCounts.put(primaryId, count); } // Tabs not in the launcher yet, so add them if(!prevFolderId || movingLaunchers) launcher.addTabArray(sameHostTabs); com.sppad.booky.Resizer.onResize(); }, /** * Handles a bookmark being removed. This is called after the bookmark * has already been removed, so we need to lookup which launcher the * bookmark belonged to. */ onBookmarkRemoved: function(aEvent) { let itemId = aEvent.itemId; let info = self.bookmarkInfoMap.get(itemId); // Not a tracked bookmark, nothing to do if(!info) return; let parentId = info.parentId; let primaryId = info.primaryId; // Update how many bookmarks map to the launcher let count = self.primaryIdCounts.get(primaryId, 0) - 1; if(count > 0) { self.primaryIdCounts.put(primaryId, count); } else { self.primaryIdCounts.remove(primaryId); self.groupIdMap.remove(primaryId); } self.bookmarkInfoMap.remove(itemId); // Update the launcher, if it still exists let launcher = com.sppad.booky.Launcher.getLauncher(parentId); if(launcher) { launcher.setBookmarks(com.sppad.booky.Bookmarks.getBookmarks(parentId)); launcher.updateAttributes(); } com.sppad.booky.Resizer.onResize(); }, /** * Handles a bookmark move event. Note that a move can be within the * quick launch folder or from another bookmark folder entirely. */ onBookmarkMoved: function(aEvent) { let itemId = aEvent.itemId; let parentId = com.sppad.booky.Bookmarks.getFolder(itemId); let grandparentId = com.sppad.booky.Bookmarks.getFolder(parentId); let info = self.bookmarkInfoMap.get(itemId); // Moving within a launcher. update bookmarks for ordering if(info && parentId == info.parentId) { let launcher = com.sppad.booky.Launcher.getLauncher(parentId); launcher.setBookmarks(com.sppad.booky.Bookmarks.getBookmarks(parentId)); // bookmark leaving entirely } else if(info && !com.sppad.booky.Bookmarks.isQuickLaunchFolder(parentId) && !com.sppad.booky.Bookmarks.isQuickLaunchFolder(grandparentId)) { this.onBookmarkRemoved(aEvent); // onBookmarkAdded handles bookmarks that are new and those that // moving between groups } else { this.onBookmarkAdded(aEvent); } }, /** * Handles a folder being added. Folders correspond to launchers if they * are direct sub folders of the quick launch folder. */ onFolderAdded: function(aEvent) { let itemId = aEvent.itemId; let nextItemId = aEvent.nextItemId; let parentId = com.sppad.booky.Bookmarks.getFolder(itemId); // Not a direct subfolder, so nothing to do if(!com.sppad.booky.Bookmarks.isQuickLaunchFolder(parentId)) return; let bookmarkInfo = { 'parentId' : parentId, }; self.bookmarkInfoMap.put(itemId, bookmarkInfo); let launcher = com.sppad.booky.Launcher.createLauncher(itemId); com.sppad.booky.Bookmarks.loadFolder(itemId); launcher.setTitle(aEvent.title); launcher.createBefore(nextItemId); com.sppad.booky.Booky.updateLauncherCount(1); com.sppad.booky.Resizer.onResize(); }, /** * Handles folders being removed. Only care about launcher folders. */ onFolderRemoved: function(aEvent) { let itemId = aEvent.itemId; let info = self.bookmarkInfoMap.get(itemId); // Not a direct subfolder, so nothing to do if(!info) return; self.bookmarkInfoMap.remove(itemId); let launcher = com.sppad.booky.Launcher.getLauncher(itemId); launcher.removeLauncher(); com.sppad.booky.Booky.updateLauncherCount(-1); com.sppad.booky.Resizer.onResize(); }, /** * Handles folders being moved. Only care about launcher folders. */ onFolderMoved: function(aEvent) { let itemId = aEvent.itemId; let nextItemId = aEvent.nextItemId; let parentId = com.sppad.booky.Bookmarks.getFolder(itemId); let info = self.bookmarkInfoMap.get(itemId); // Launcher folder is being reordered with siblings if(info && parentId == info.parentId) { let launcher = com.sppad.booky.Launcher.getLauncher(itemId); launcher.createBefore(nextItemId); com.sppad.booky.Resizer.onResize(); // Folder is moving in/out or has nothing to do with the quick // launch folder } else { this.onFolderRemoved(aEvent); this.onFolderAdded(aEvent); } }, onTitleUpdated: function(aEvent) { let itemId = aEvent.itemId; let parentId = com.sppad.booky.Bookmarks.getFolder(itemId); // Not a launcher, so nothing to do if(!com.sppad.booky.Bookmarks.isQuickLaunchFolder(parentId)) return; let launcher = com.sppad.booky.Launcher.getLauncher(itemId); launcher.setTitle(aEvent.title); }, setup : function() { com.sppad.booky.Bookmarks.addListener(this); com.sppad.booky.Booky.updateLauncherCount(0); com.sppad.booky.Bookmarks.loadBookmarks(); }, cleanup : function() { com.sppad.booky.Bookmarks.removeListener(this); }, } };
sparhami/booky
chrome/content/groups.js
JavaScript
gpl-3.0
14,131
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Events</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="EventDetail"> <h3>Death</h3> <table class="infolist eventlist"> <tbody> <tr> <td class="ColumnAttribute">Gramps ID</td> <td class="ColumnGRAMPSID">E16625</td> </tr> <tr> <td class="ColumnAttribute">Date</td> <td class="ColumnColumnDate"> 1940-09-24 </td> </tr> <tr> <td class="ColumnAttribute">Place</td> <td class="ColumnColumnPlace"> <a href="../../../plc/e/1/d15f6076beb11430de13b7adb1e.html" title=""> </a> </td> </tr> </tbody> </table> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/a/3/d15f60709ad59753e77bb0f9e3a.html" title="Letter from Judy Roake 07/03/2007" name ="sref1"> Letter from Judy Roake 07/03/2007 <span class="grampsid"> [S0365]</span> </a> <ol> <li id="sref1a"> <ul> <li> Confidence: Low </li> </ul> </li> </ol> </li> </ol> </div> <div class="subsection" id="references"> <h4>References</h4> <ol class="Col1" role="Volume-n-Page"type = 1> <li> <a href="../../../ppl/d/e/d15f607752c5a0204817b9520ed.html"> GAMMON, Richard <span class="grampsid"> [I16699]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:15<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/evt/8/4/d15f60775485d2d2b19fcd67048.html
HTML
gpl-3.0
3,379
package net.refination.refinecraft.commands; import net.refination.refinecraft.CommandSource; import net.refination.refinecraft.utils.DateUtil; import net.refination.refinecraft.utils.NumberUtil; import org.bukkit.*; import java.lang.management.ManagementFactory; import java.util.List; import java.util.logging.Level; import static net.refination.refinecraft.I18n.tl; public class Commandgc extends RefineCraftCommand { public Commandgc() { super("gc"); } @Override protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { double tps = RC.getTimer().getAverageTPS(); ChatColor color; if (tps >= 18.0) { color = ChatColor.GREEN; } else if (tps >= 15.0) { color = ChatColor.YELLOW; } else { color = ChatColor.RED; } sender.sendMessage(tl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()))); sender.sendMessage(tl("tps", "" + color + NumberUtil.formatDouble(tps))); sender.sendMessage(tl("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); sender.sendMessage(tl("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); sender.sendMessage(tl("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024))); List<World> worlds = server.getWorlds(); for (World w : worlds) { String worldType = "World"; switch (w.getEnvironment()) { case NETHER: worldType = "Nether"; break; case THE_END: worldType = "The End"; break; } int tileEntities = 0; try { for (Chunk chunk : w.getLoadedChunks()) { tileEntities += chunk.getTileEntities().length; } } catch (java.lang.ClassCastException ex) { Bukkit.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); } sender.sendMessage(tl("gcWorld", worldType, w.getName(), w.getLoadedChunks().length, w.getEntities().size(), tileEntities)); } } }
HkB115/RefineCraft
RefineCraft/src/net/refination/refinecraft/commands/Commandgc.java
Java
gpl-3.0
2,286
/***************************************************************************** * * Copyright (C) 2016 Atmel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holders nor the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #ifndef _AVR_IO_H_ # error "Include <avr/io.h> instead of this file." #endif #ifndef _AVR_IOXXX_H_ # define _AVR_IOXXX_H_ "iox256c3.h" #else # error "Attempt to include more than one <avr/ioXXX.h> file." #endif #ifndef _AVR_ATXMEGA256C3_H_INCLUDED #define _AVR_ATXMEGA256C3_H_INCLUDED /* Ungrouped common registers */ #define GPIOR0 _SFR_MEM8(0x0000) /* General Purpose IO Register 0 */ #define GPIOR1 _SFR_MEM8(0x0001) /* General Purpose IO Register 1 */ #define GPIOR2 _SFR_MEM8(0x0002) /* General Purpose IO Register 2 */ #define GPIOR3 _SFR_MEM8(0x0003) /* General Purpose IO Register 3 */ /* Deprecated */ #define GPIO0 _SFR_MEM8(0x0000) /* General Purpose IO Register 0 */ #define GPIO1 _SFR_MEM8(0x0001) /* General Purpose IO Register 1 */ #define GPIO2 _SFR_MEM8(0x0002) /* General Purpose IO Register 2 */ #define GPIO3 _SFR_MEM8(0x0003) /* General Purpose IO Register 3 */ #define CCP _SFR_MEM8(0x0034) /* Configuration Change Protection */ #define RAMPD _SFR_MEM8(0x0038) /* Ramp D */ #define RAMPX _SFR_MEM8(0x0039) /* Ramp X */ #define RAMPY _SFR_MEM8(0x003A) /* Ramp Y */ #define RAMPZ _SFR_MEM8(0x003B) /* Ramp Z */ #define EIND _SFR_MEM8(0x003C) /* Extended Indirect Jump */ #define SPL _SFR_MEM8(0x003D) /* Stack Pointer Low */ #define SPH _SFR_MEM8(0x003E) /* Stack Pointer High */ #define SREG _SFR_MEM8(0x003F) /* Status Register */ /* C Language Only */ #if !defined (__ASSEMBLER__) #include <stdint.h> typedef volatile uint8_t register8_t; typedef volatile uint16_t register16_t; typedef volatile uint32_t register32_t; #ifdef _WORDREGISTER #undef _WORDREGISTER #endif #define _WORDREGISTER(regname) \ __extension__ union \ { \ register16_t regname; \ struct \ { \ register8_t regname ## L; \ register8_t regname ## H; \ }; \ } #ifdef _DWORDREGISTER #undef _DWORDREGISTER #endif #define _DWORDREGISTER(regname) \ __extension__ union \ { \ register32_t regname; \ struct \ { \ register8_t regname ## 0; \ register8_t regname ## 1; \ register8_t regname ## 2; \ register8_t regname ## 3; \ }; \ } /* ========================================================================== IO Module Structures ========================================================================== */ /* -------------------------------------------------------------------------- VPORT - Virtual Ports -------------------------------------------------------------------------- */ /* Virtual Port */ typedef struct VPORT_struct { register8_t DIR; /* I/O Port Data Direction */ register8_t OUT; /* I/O Port Output */ register8_t IN; /* I/O Port Input */ register8_t INTFLAGS; /* Interrupt Flag Register */ } VPORT_t; /* -------------------------------------------------------------------------- XOCD - On-Chip Debug System -------------------------------------------------------------------------- */ /* On-Chip Debug System */ typedef struct OCD_struct { register8_t OCDR0; /* OCD Register 0 */ register8_t OCDR1; /* OCD Register 1 */ } OCD_t; /* -------------------------------------------------------------------------- CPU - CPU -------------------------------------------------------------------------- */ /* CCP signatures */ typedef enum CCP_enum { CCP_SPM_gc = (0x9D<<0), /* SPM Instruction Protection */ CCP_IOREG_gc = (0xD8<<0), /* IO Register Protection */ } CCP_t; /* -------------------------------------------------------------------------- CLK - Clock System -------------------------------------------------------------------------- */ /* Clock System */ typedef struct CLK_struct { register8_t CTRL; /* Control Register */ register8_t PSCTRL; /* Prescaler Control Register */ register8_t LOCK; /* Lock register */ register8_t RTCCTRL; /* RTC Control Register */ register8_t USBCTRL; /* USB Control Register */ } CLK_t; /* Power Reduction */ typedef struct PR_struct { register8_t PRGEN; /* General Power Reduction */ register8_t PRPA; /* Power Reduction Port A */ register8_t reserved_0x02; register8_t PRPC; /* Power Reduction Port C */ register8_t PRPD; /* Power Reduction Port D */ register8_t PRPE; /* Power Reduction Port E */ register8_t PRPF; /* Power Reduction Port F */ } PR_t; /* System Clock Selection */ typedef enum CLK_SCLKSEL_enum { CLK_SCLKSEL_RC2M_gc = (0x00<<0), /* Internal 2 MHz RC Oscillator */ CLK_SCLKSEL_RC32M_gc = (0x01<<0), /* Internal 32 MHz RC Oscillator */ CLK_SCLKSEL_RC32K_gc = (0x02<<0), /* Internal 32.768 kHz RC Oscillator */ CLK_SCLKSEL_XOSC_gc = (0x03<<0), /* External Crystal Oscillator or Clock */ CLK_SCLKSEL_PLL_gc = (0x04<<0), /* Phase Locked Loop */ } CLK_SCLKSEL_t; /* Prescaler A Division Factor */ typedef enum CLK_PSADIV_enum { CLK_PSADIV_1_gc = (0x00<<2), /* Divide by 1 */ CLK_PSADIV_2_gc = (0x01<<2), /* Divide by 2 */ CLK_PSADIV_4_gc = (0x03<<2), /* Divide by 4 */ CLK_PSADIV_8_gc = (0x05<<2), /* Divide by 8 */ CLK_PSADIV_16_gc = (0x07<<2), /* Divide by 16 */ CLK_PSADIV_32_gc = (0x09<<2), /* Divide by 32 */ CLK_PSADIV_64_gc = (0x0B<<2), /* Divide by 64 */ CLK_PSADIV_128_gc = (0x0D<<2), /* Divide by 128 */ CLK_PSADIV_256_gc = (0x0F<<2), /* Divide by 256 */ CLK_PSADIV_512_gc = (0x11<<2), /* Divide by 512 */ } CLK_PSADIV_t; /* Prescaler B and C Division Factor */ typedef enum CLK_PSBCDIV_enum { CLK_PSBCDIV_1_1_gc = (0x00<<0), /* Divide B by 1 and C by 1 */ CLK_PSBCDIV_1_2_gc = (0x01<<0), /* Divide B by 1 and C by 2 */ CLK_PSBCDIV_4_1_gc = (0x02<<0), /* Divide B by 4 and C by 1 */ CLK_PSBCDIV_2_2_gc = (0x03<<0), /* Divide B by 2 and C by 2 */ } CLK_PSBCDIV_t; /* RTC Clock Source */ typedef enum CLK_RTCSRC_enum { CLK_RTCSRC_ULP_gc = (0x00<<1), /* 1.024 kHz from internal 32kHz ULP */ CLK_RTCSRC_TOSC_gc = (0x01<<1), /* 1.024 kHz from 32.768 kHz crystal oscillator on TOSC */ CLK_RTCSRC_RCOSC_gc = (0x02<<1), /* 1.024 kHz from internal 32.768 kHz RC oscillator */ CLK_RTCSRC_TOSC32_gc = (0x05<<1), /* 32.768 kHz from 32.768 kHz crystal oscillator on TOSC */ CLK_RTCSRC_RCOSC32_gc = (0x06<<1), /* 32.768 kHz from internal 32.768 kHz RC oscillator */ CLK_RTCSRC_EXTCLK_gc = (0x07<<1), /* External Clock from TOSC1 */ } CLK_RTCSRC_t; /* USB Prescaler Division Factor */ typedef enum CLK_USBPSDIV_enum { CLK_USBPSDIV_1_gc = (0x00<<3), /* Divide by 1 */ CLK_USBPSDIV_2_gc = (0x01<<3), /* Divide by 2 */ CLK_USBPSDIV_4_gc = (0x02<<3), /* Divide by 4 */ CLK_USBPSDIV_8_gc = (0x03<<3), /* Divide by 8 */ CLK_USBPSDIV_16_gc = (0x04<<3), /* Divide by 16 */ CLK_USBPSDIV_32_gc = (0x05<<3), /* Divide by 32 */ } CLK_USBPSDIV_t; /* USB Clock Source */ typedef enum CLK_USBSRC_enum { CLK_USBSRC_PLL_gc = (0x00<<1), /* PLL */ CLK_USBSRC_RC32M_gc = (0x01<<1), /* Internal 32 MHz RC Oscillator */ } CLK_USBSRC_t; /* -------------------------------------------------------------------------- SLEEP - Sleep Controller -------------------------------------------------------------------------- */ /* Sleep Controller */ typedef struct SLEEP_struct { register8_t CTRL; /* Control Register */ } SLEEP_t; /* Sleep Mode */ typedef enum SLEEP_SMODE_enum { SLEEP_SMODE_IDLE_gc = (0x00<<1), /* Idle mode */ SLEEP_SMODE_PDOWN_gc = (0x02<<1), /* Power-down Mode */ SLEEP_SMODE_PSAVE_gc = (0x03<<1), /* Power-save Mode */ SLEEP_SMODE_STDBY_gc = (0x06<<1), /* Standby Mode */ SLEEP_SMODE_ESTDBY_gc = (0x07<<1), /* Extended Standby Mode */ } SLEEP_SMODE_t; #define SLEEP_MODE_IDLE (0x00<<1) #define SLEEP_MODE_PWR_DOWN (0x02<<1) #define SLEEP_MODE_PWR_SAVE (0x03<<1) #define SLEEP_MODE_STANDBY (0x06<<1) #define SLEEP_MODE_EXT_STANDBY (0x07<<1) /* -------------------------------------------------------------------------- OSC - Oscillator -------------------------------------------------------------------------- */ /* Oscillator */ typedef struct OSC_struct { register8_t CTRL; /* Control Register */ register8_t STATUS; /* Status Register */ register8_t XOSCCTRL; /* External Oscillator Control Register */ register8_t XOSCFAIL; /* Oscillator Failure Detection Register */ register8_t RC32KCAL; /* 32.768 kHz Internal Oscillator Calibration Register */ register8_t PLLCTRL; /* PLL Control Register */ register8_t DFLLCTRL; /* DFLL Control Register */ } OSC_t; /* Oscillator Frequency Range */ typedef enum OSC_FRQRANGE_enum { OSC_FRQRANGE_04TO2_gc = (0x00<<6), /* 0.4 - 2 MHz */ OSC_FRQRANGE_2TO9_gc = (0x01<<6), /* 2 - 9 MHz */ OSC_FRQRANGE_9TO12_gc = (0x02<<6), /* 9 - 12 MHz */ OSC_FRQRANGE_12TO16_gc = (0x03<<6), /* 12 - 16 MHz */ } OSC_FRQRANGE_t; /* External Oscillator Selection and Startup Time */ typedef enum OSC_XOSCSEL_enum { OSC_XOSCSEL_EXTCLK_gc = (0x00<<0), /* External Clock - 6 CLK */ OSC_XOSCSEL_32KHz_gc = (0x02<<0), /* 32.768 kHz TOSC - 32K CLK */ OSC_XOSCSEL_XTAL_256CLK_gc = (0x03<<0), /* 0.4-16 MHz XTAL - 256 CLK */ OSC_XOSCSEL_XTAL_1KCLK_gc = (0x07<<0), /* 0.4-16 MHz XTAL - 1K CLK */ OSC_XOSCSEL_XTAL_16KCLK_gc = (0x0B<<0), /* 0.4-16 MHz XTAL - 16K CLK */ } OSC_XOSCSEL_t; /* PLL Clock Source */ typedef enum OSC_PLLSRC_enum { OSC_PLLSRC_RC2M_gc = (0x00<<6), /* Internal 2 MHz RC Oscillator */ OSC_PLLSRC_RC32M_gc = (0x02<<6), /* Internal 32 MHz RC Oscillator */ OSC_PLLSRC_XOSC_gc = (0x03<<6), /* External Oscillator */ } OSC_PLLSRC_t; /* 2 MHz DFLL Calibration Reference */ typedef enum OSC_RC2MCREF_enum { OSC_RC2MCREF_RC32K_gc = (0x00<<0), /* Internal 32.768 kHz RC Oscillator */ OSC_RC2MCREF_XOSC32K_gc = (0x01<<0), /* External 32.768 kHz Crystal Oscillator */ } OSC_RC2MCREF_t; /* 32 MHz DFLL Calibration Reference */ typedef enum OSC_RC32MCREF_enum { OSC_RC32MCREF_RC32K_gc = (0x00<<1), /* Internal 32.768 kHz RC Oscillator */ OSC_RC32MCREF_XOSC32K_gc = (0x01<<1), /* External 32.768 kHz Crystal Oscillator */ OSC_RC32MCREF_USBSOF_gc = (0x02<<1), /* USB Start of Frame */ } OSC_RC32MCREF_t; /* -------------------------------------------------------------------------- DFLL - DFLL -------------------------------------------------------------------------- */ /* DFLL */ typedef struct DFLL_struct { register8_t CTRL; /* Control Register */ register8_t reserved_0x01; register8_t CALA; /* Calibration Register A */ register8_t CALB; /* Calibration Register B */ register8_t COMP0; /* Oscillator Compare Register 0 */ register8_t COMP1; /* Oscillator Compare Register 1 */ register8_t COMP2; /* Oscillator Compare Register 2 */ register8_t reserved_0x07; } DFLL_t; /* -------------------------------------------------------------------------- RST - Reset -------------------------------------------------------------------------- */ /* Reset */ typedef struct RST_struct { register8_t STATUS; /* Status Register */ register8_t CTRL; /* Control Register */ } RST_t; /* -------------------------------------------------------------------------- WDT - Watch-Dog Timer -------------------------------------------------------------------------- */ /* Watch-Dog Timer */ typedef struct WDT_struct { register8_t CTRL; /* Control */ register8_t WINCTRL; /* Windowed Mode Control */ register8_t STATUS; /* Status */ } WDT_t; /* Period setting */ typedef enum WDT_PER_enum { WDT_PER_8CLK_gc = (0x00<<2), /* 8 cycles (8ms @ 3.3V) */ WDT_PER_16CLK_gc = (0x01<<2), /* 16 cycles (16ms @ 3.3V) */ WDT_PER_32CLK_gc = (0x02<<2), /* 32 cycles (32ms @ 3.3V) */ WDT_PER_64CLK_gc = (0x03<<2), /* 64 cycles (64ms @ 3.3V) */ WDT_PER_128CLK_gc = (0x04<<2), /* 128 cycles (0.128s @ 3.3V) */ WDT_PER_256CLK_gc = (0x05<<2), /* 256 cycles (0.256s @ 3.3V) */ WDT_PER_512CLK_gc = (0x06<<2), /* 512 cycles (0.512s @ 3.3V) */ WDT_PER_1KCLK_gc = (0x07<<2), /* 1K cycles (1s @ 3.3V) */ WDT_PER_2KCLK_gc = (0x08<<2), /* 2K cycles (2s @ 3.3V) */ WDT_PER_4KCLK_gc = (0x09<<2), /* 4K cycles (4s @ 3.3V) */ WDT_PER_8KCLK_gc = (0x0A<<2), /* 8K cycles (8s @ 3.3V) */ } WDT_PER_t; /* Closed window period */ typedef enum WDT_WPER_enum { WDT_WPER_8CLK_gc = (0x00<<2), /* 8 cycles (8ms @ 3.3V) */ WDT_WPER_16CLK_gc = (0x01<<2), /* 16 cycles (16ms @ 3.3V) */ WDT_WPER_32CLK_gc = (0x02<<2), /* 32 cycles (32ms @ 3.3V) */ WDT_WPER_64CLK_gc = (0x03<<2), /* 64 cycles (64ms @ 3.3V) */ WDT_WPER_128CLK_gc = (0x04<<2), /* 128 cycles (0.128s @ 3.3V) */ WDT_WPER_256CLK_gc = (0x05<<2), /* 256 cycles (0.256s @ 3.3V) */ WDT_WPER_512CLK_gc = (0x06<<2), /* 512 cycles (0.512s @ 3.3V) */ WDT_WPER_1KCLK_gc = (0x07<<2), /* 1K cycles (1s @ 3.3V) */ WDT_WPER_2KCLK_gc = (0x08<<2), /* 2K cycles (2s @ 3.3V) */ WDT_WPER_4KCLK_gc = (0x09<<2), /* 4K cycles (4s @ 3.3V) */ WDT_WPER_8KCLK_gc = (0x0A<<2), /* 8K cycles (8s @ 3.3V) */ } WDT_WPER_t; /* -------------------------------------------------------------------------- MCU - MCU Control -------------------------------------------------------------------------- */ /* MCU Control */ typedef struct MCU_struct { register8_t DEVID0; /* Device ID byte 0 */ register8_t DEVID1; /* Device ID byte 1 */ register8_t DEVID2; /* Device ID byte 2 */ register8_t REVID; /* Revision ID */ register8_t reserved_0x04; register8_t reserved_0x05; register8_t reserved_0x06; register8_t ANAINIT; /* Analog Startup Delay */ register8_t EVSYSLOCK; /* Event System Lock */ register8_t AWEXLOCK; /* AWEX Lock */ register8_t reserved_0x0A; register8_t reserved_0x0B; } MCU_t; /* -------------------------------------------------------------------------- PMIC - Programmable Multi-level Interrupt Controller -------------------------------------------------------------------------- */ /* Programmable Multi-level Interrupt Controller */ typedef struct PMIC_struct { register8_t STATUS; /* Status Register */ register8_t INTPRI; /* Interrupt Priority */ register8_t CTRL; /* Control Register */ register8_t reserved_0x03; register8_t reserved_0x04; register8_t reserved_0x05; register8_t reserved_0x06; register8_t reserved_0x07; register8_t reserved_0x08; register8_t reserved_0x09; register8_t reserved_0x0A; register8_t reserved_0x0B; register8_t reserved_0x0C; register8_t reserved_0x0D; register8_t reserved_0x0E; register8_t reserved_0x0F; } PMIC_t; /* -------------------------------------------------------------------------- PORTCFG - Port Configuration -------------------------------------------------------------------------- */ /* I/O port Configuration */ typedef struct PORTCFG_struct { register8_t MPCMASK; /* Multi-pin Configuration Mask */ register8_t reserved_0x01; register8_t VPCTRLA; /* Virtual Port Control Register A */ register8_t VPCTRLB; /* Virtual Port Control Register B */ register8_t CLKEVOUT; /* Clock and Event Out Register */ register8_t reserved_0x05; register8_t EVOUTSEL; /* Event Output Select */ } PORTCFG_t; /* Virtual Port Mapping */ typedef enum PORTCFG_VP02MAP_enum { PORTCFG_VP02MAP_PORTA_gc = (0x00<<0), /* Mapped To PORTA */ PORTCFG_VP02MAP_PORTB_gc = (0x01<<0), /* Mapped To PORTB */ PORTCFG_VP02MAP_PORTC_gc = (0x02<<0), /* Mapped To PORTC */ PORTCFG_VP02MAP_PORTD_gc = (0x03<<0), /* Mapped To PORTD */ PORTCFG_VP02MAP_PORTE_gc = (0x04<<0), /* Mapped To PORTE */ PORTCFG_VP02MAP_PORTF_gc = (0x05<<0), /* Mapped To PORTF */ PORTCFG_VP02MAP_PORTG_gc = (0x06<<0), /* Mapped To PORTG */ PORTCFG_VP02MAP_PORTH_gc = (0x07<<0), /* Mapped To PORTH */ PORTCFG_VP02MAP_PORTJ_gc = (0x08<<0), /* Mapped To PORTJ */ PORTCFG_VP02MAP_PORTK_gc = (0x09<<0), /* Mapped To PORTK */ PORTCFG_VP02MAP_PORTL_gc = (0x0A<<0), /* Mapped To PORTL */ PORTCFG_VP02MAP_PORTM_gc = (0x0B<<0), /* Mapped To PORTM */ PORTCFG_VP02MAP_PORTN_gc = (0x0C<<0), /* Mapped To PORTN */ PORTCFG_VP02MAP_PORTP_gc = (0x0D<<0), /* Mapped To PORTP */ PORTCFG_VP02MAP_PORTQ_gc = (0x0E<<0), /* Mapped To PORTQ */ PORTCFG_VP02MAP_PORTR_gc = (0x0F<<0), /* Mapped To PORTR */ } PORTCFG_VP02MAP_t; /* Virtual Port Mapping */ typedef enum PORTCFG_VP13MAP_enum { PORTCFG_VP13MAP_PORTA_gc = (0x00<<4), /* Mapped To PORTA */ PORTCFG_VP13MAP_PORTB_gc = (0x01<<4), /* Mapped To PORTB */ PORTCFG_VP13MAP_PORTC_gc = (0x02<<4), /* Mapped To PORTC */ PORTCFG_VP13MAP_PORTD_gc = (0x03<<4), /* Mapped To PORTD */ PORTCFG_VP13MAP_PORTE_gc = (0x04<<4), /* Mapped To PORTE */ PORTCFG_VP13MAP_PORTF_gc = (0x05<<4), /* Mapped To PORTF */ PORTCFG_VP13MAP_PORTG_gc = (0x06<<4), /* Mapped To PORTG */ PORTCFG_VP13MAP_PORTH_gc = (0x07<<4), /* Mapped To PORTH */ PORTCFG_VP13MAP_PORTJ_gc = (0x08<<4), /* Mapped To PORTJ */ PORTCFG_VP13MAP_PORTK_gc = (0x09<<4), /* Mapped To PORTK */ PORTCFG_VP13MAP_PORTL_gc = (0x0A<<4), /* Mapped To PORTL */ PORTCFG_VP13MAP_PORTM_gc = (0x0B<<4), /* Mapped To PORTM */ PORTCFG_VP13MAP_PORTN_gc = (0x0C<<4), /* Mapped To PORTN */ PORTCFG_VP13MAP_PORTP_gc = (0x0D<<4), /* Mapped To PORTP */ PORTCFG_VP13MAP_PORTQ_gc = (0x0E<<4), /* Mapped To PORTQ */ PORTCFG_VP13MAP_PORTR_gc = (0x0F<<4), /* Mapped To PORTR */ } PORTCFG_VP13MAP_t; /* System Clock Output Port */ typedef enum PORTCFG_CLKOUT_enum { PORTCFG_CLKOUT_OFF_gc = (0x00<<0), /* System Clock Output Disabled */ PORTCFG_CLKOUT_PC7_gc = (0x01<<0), /* System Clock Output on Port C pin 7 */ PORTCFG_CLKOUT_PD7_gc = (0x02<<0), /* System Clock Output on Port D pin 7 */ PORTCFG_CLKOUT_PE7_gc = (0x03<<0), /* System Clock Output on Port E pin 7 */ } PORTCFG_CLKOUT_t; /* Peripheral Clock Output Select */ typedef enum PORTCFG_CLKOUTSEL_enum { PORTCFG_CLKOUTSEL_CLK1X_gc = (0x00<<2), /* 1x Peripheral Clock Output to pin */ PORTCFG_CLKOUTSEL_CLK2X_gc = (0x01<<2), /* 2x Peripheral Clock Output to pin */ PORTCFG_CLKOUTSEL_CLK4X_gc = (0x02<<2), /* 4x Peripheral Clock Output to pin */ } PORTCFG_CLKOUTSEL_t; /* Event Output Port */ typedef enum PORTCFG_EVOUT_enum { PORTCFG_EVOUT_OFF_gc = (0x00<<4), /* Event Output Disabled */ PORTCFG_EVOUT_PC7_gc = (0x01<<4), /* Event Channel 7 Output on Port C pin 7 */ PORTCFG_EVOUT_PD7_gc = (0x02<<4), /* Event Channel 7 Output on Port D pin 7 */ PORTCFG_EVOUT_PE7_gc = (0x03<<4), /* Event Channel 7 Output on Port E pin 7 */ } PORTCFG_EVOUT_t; /* Event Output Select */ typedef enum PORTCFG_EVOUTSEL_enum { PORTCFG_EVOUTSEL_0_gc = (0x00<<0), /* Event Channel 0 output to pin */ PORTCFG_EVOUTSEL_1_gc = (0x01<<0), /* Event Channel 1 output to pin */ PORTCFG_EVOUTSEL_2_gc = (0x02<<0), /* Event Channel 2 output to pin */ PORTCFG_EVOUTSEL_3_gc = (0x03<<0), /* Event Channel 3 output to pin */ } PORTCFG_EVOUTSEL_t; /* -------------------------------------------------------------------------- CRC - Cyclic Redundancy Checker -------------------------------------------------------------------------- */ /* Cyclic Redundancy Checker */ typedef struct CRC_struct { register8_t CTRL; /* Control Register */ register8_t STATUS; /* Status Register */ register8_t reserved_0x02; register8_t DATAIN; /* Data Input */ register8_t CHECKSUM0; /* Checksum byte 0 */ register8_t CHECKSUM1; /* Checksum byte 1 */ register8_t CHECKSUM2; /* Checksum byte 2 */ register8_t CHECKSUM3; /* Checksum byte 3 */ } CRC_t; /* Reset */ typedef enum CRC_RESET_enum { CRC_RESET_NO_gc = (0x00<<6), /* No Reset */ CRC_RESET_RESET0_gc = (0x02<<6), /* Reset CRC with CHECKSUM to all zeros */ CRC_RESET_RESET1_gc = (0x03<<6), /* Reset CRC with CHECKSUM to all ones */ } CRC_RESET_t; /* Input Source */ typedef enum CRC_SOURCE_enum { CRC_SOURCE_DISABLE_gc = (0x00<<0), /* Disabled */ CRC_SOURCE_IO_gc = (0x01<<0), /* I/O Interface */ CRC_SOURCE_FLASH_gc = (0x02<<0), /* Flash */ } CRC_SOURCE_t; /* -------------------------------------------------------------------------- EVSYS - Event System -------------------------------------------------------------------------- */ /* Event System */ typedef struct EVSYS_struct { register8_t CH0MUX; /* Event Channel 0 Multiplexer */ register8_t CH1MUX; /* Event Channel 1 Multiplexer */ register8_t CH2MUX; /* Event Channel 2 Multiplexer */ register8_t CH3MUX; /* Event Channel 3 Multiplexer */ register8_t reserved_0x04; register8_t reserved_0x05; register8_t reserved_0x06; register8_t reserved_0x07; register8_t CH0CTRL; /* Channel 0 Control Register */ register8_t CH1CTRL; /* Channel 1 Control Register */ register8_t CH2CTRL; /* Channel 2 Control Register */ register8_t CH3CTRL; /* Channel 3 Control Register */ register8_t reserved_0x0C; register8_t reserved_0x0D; register8_t reserved_0x0E; register8_t reserved_0x0F; register8_t STROBE; /* Event Strobe */ register8_t DATA; /* Event Data */ } EVSYS_t; /* Quadrature Decoder Index Recognition Mode */ typedef enum EVSYS_QDIRM_enum { EVSYS_QDIRM_00_gc = (0x00<<5), /* QDPH0 = 0, QDPH90 = 0 */ EVSYS_QDIRM_01_gc = (0x01<<5), /* QDPH0 = 0, QDPH90 = 1 */ EVSYS_QDIRM_10_gc = (0x02<<5), /* QDPH0 = 1, QDPH90 = 0 */ EVSYS_QDIRM_11_gc = (0x03<<5), /* QDPH0 = 1, QDPH90 = 1 */ } EVSYS_QDIRM_t; /* Digital filter coefficient */ typedef enum EVSYS_DIGFILT_enum { EVSYS_DIGFILT_1SAMPLE_gc = (0x00<<0), /* 1 SAMPLE */ EVSYS_DIGFILT_2SAMPLES_gc = (0x01<<0), /* 2 SAMPLES */ EVSYS_DIGFILT_3SAMPLES_gc = (0x02<<0), /* 3 SAMPLES */ EVSYS_DIGFILT_4SAMPLES_gc = (0x03<<0), /* 4 SAMPLES */ EVSYS_DIGFILT_5SAMPLES_gc = (0x04<<0), /* 5 SAMPLES */ EVSYS_DIGFILT_6SAMPLES_gc = (0x05<<0), /* 6 SAMPLES */ EVSYS_DIGFILT_7SAMPLES_gc = (0x06<<0), /* 7 SAMPLES */ EVSYS_DIGFILT_8SAMPLES_gc = (0x07<<0), /* 8 SAMPLES */ } EVSYS_DIGFILT_t; /* Event Channel multiplexer input selection */ typedef enum EVSYS_CHMUX_enum { EVSYS_CHMUX_OFF_gc = (0x00<<0), /* Off */ EVSYS_CHMUX_RTC_OVF_gc = (0x08<<0), /* RTC Overflow */ EVSYS_CHMUX_RTC_CMP_gc = (0x09<<0), /* RTC Compare Match */ EVSYS_CHMUX_USB_gc = (0x0A<<0), /* USB Setup, SOF, CRC error and UNF/OVF */ EVSYS_CHMUX_ACA_CH0_gc = (0x10<<0), /* Analog Comparator A Channel 0 */ EVSYS_CHMUX_ACA_CH1_gc = (0x11<<0), /* Analog Comparator A Channel 1 */ EVSYS_CHMUX_ACA_WIN_gc = (0x12<<0), /* Analog Comparator A Window */ EVSYS_CHMUX_ADCA_CH0_gc = (0x20<<0), /* ADC A Channel */ EVSYS_CHMUX_PORTA_PIN0_gc = (0x50<<0), /* Port A, Pin0 */ EVSYS_CHMUX_PORTA_PIN1_gc = (0x51<<0), /* Port A, Pin1 */ EVSYS_CHMUX_PORTA_PIN2_gc = (0x52<<0), /* Port A, Pin2 */ EVSYS_CHMUX_PORTA_PIN3_gc = (0x53<<0), /* Port A, Pin3 */ EVSYS_CHMUX_PORTA_PIN4_gc = (0x54<<0), /* Port A, Pin4 */ EVSYS_CHMUX_PORTA_PIN5_gc = (0x55<<0), /* Port A, Pin5 */ EVSYS_CHMUX_PORTA_PIN6_gc = (0x56<<0), /* Port A, Pin6 */ EVSYS_CHMUX_PORTA_PIN7_gc = (0x57<<0), /* Port A, Pin7 */ EVSYS_CHMUX_PORTB_PIN0_gc = (0x58<<0), /* Port B, Pin0 */ EVSYS_CHMUX_PORTB_PIN1_gc = (0x59<<0), /* Port B, Pin1 */ EVSYS_CHMUX_PORTB_PIN2_gc = (0x5A<<0), /* Port B, Pin2 */ EVSYS_CHMUX_PORTB_PIN3_gc = (0x5B<<0), /* Port B, Pin3 */ EVSYS_CHMUX_PORTB_PIN4_gc = (0x5C<<0), /* Port B, Pin4 */ EVSYS_CHMUX_PORTB_PIN5_gc = (0x5D<<0), /* Port B, Pin5 */ EVSYS_CHMUX_PORTB_PIN6_gc = (0x5E<<0), /* Port B, Pin6 */ EVSYS_CHMUX_PORTB_PIN7_gc = (0x5F<<0), /* Port B, Pin7 */ EVSYS_CHMUX_PORTC_PIN0_gc = (0x60<<0), /* Port C, Pin0 */ EVSYS_CHMUX_PORTC_PIN1_gc = (0x61<<0), /* Port C, Pin1 */ EVSYS_CHMUX_PORTC_PIN2_gc = (0x62<<0), /* Port C, Pin2 */ EVSYS_CHMUX_PORTC_PIN3_gc = (0x63<<0), /* Port C, Pin3 */ EVSYS_CHMUX_PORTC_PIN4_gc = (0x64<<0), /* Port C, Pin4 */ EVSYS_CHMUX_PORTC_PIN5_gc = (0x65<<0), /* Port C, Pin5 */ EVSYS_CHMUX_PORTC_PIN6_gc = (0x66<<0), /* Port C, Pin6 */ EVSYS_CHMUX_PORTC_PIN7_gc = (0x67<<0), /* Port C, Pin7 */ EVSYS_CHMUX_PORTD_PIN0_gc = (0x68<<0), /* Port D, Pin0 */ EVSYS_CHMUX_PORTD_PIN1_gc = (0x69<<0), /* Port D, Pin1 */ EVSYS_CHMUX_PORTD_PIN2_gc = (0x6A<<0), /* Port D, Pin2 */ EVSYS_CHMUX_PORTD_PIN3_gc = (0x6B<<0), /* Port D, Pin3 */ EVSYS_CHMUX_PORTD_PIN4_gc = (0x6C<<0), /* Port D, Pin4 */ EVSYS_CHMUX_PORTD_PIN5_gc = (0x6D<<0), /* Port D, Pin5 */ EVSYS_CHMUX_PORTD_PIN6_gc = (0x6E<<0), /* Port D, Pin6 */ EVSYS_CHMUX_PORTD_PIN7_gc = (0x6F<<0), /* Port D, Pin7 */ EVSYS_CHMUX_PORTE_PIN0_gc = (0x70<<0), /* Port E, Pin0 */ EVSYS_CHMUX_PORTE_PIN1_gc = (0x71<<0), /* Port E, Pin1 */ EVSYS_CHMUX_PORTE_PIN2_gc = (0x72<<0), /* Port E, Pin2 */ EVSYS_CHMUX_PORTE_PIN3_gc = (0x73<<0), /* Port E, Pin3 */ EVSYS_CHMUX_PORTE_PIN4_gc = (0x74<<0), /* Port E, Pin4 */ EVSYS_CHMUX_PORTE_PIN5_gc = (0x75<<0), /* Port E, Pin5 */ EVSYS_CHMUX_PORTE_PIN6_gc = (0x76<<0), /* Port E, Pin6 */ EVSYS_CHMUX_PORTE_PIN7_gc = (0x77<<0), /* Port E, Pin7 */ EVSYS_CHMUX_PORTF_PIN0_gc = (0x78<<0), /* Port F, Pin0 */ EVSYS_CHMUX_PORTF_PIN1_gc = (0x79<<0), /* Port F, Pin1 */ EVSYS_CHMUX_PORTF_PIN2_gc = (0x7A<<0), /* Port F, Pin2 */ EVSYS_CHMUX_PORTF_PIN3_gc = (0x7B<<0), /* Port F, Pin3 */ EVSYS_CHMUX_PORTF_PIN4_gc = (0x7C<<0), /* Port F, Pin4 */ EVSYS_CHMUX_PORTF_PIN5_gc = (0x7D<<0), /* Port F, Pin5 */ EVSYS_CHMUX_PORTF_PIN6_gc = (0x7E<<0), /* Port F, Pin6 */ EVSYS_CHMUX_PORTF_PIN7_gc = (0x7F<<0), /* Port F, Pin7 */ EVSYS_CHMUX_PRESCALER_1_gc = (0x80<<0), /* Prescaler, divide by 1 */ EVSYS_CHMUX_PRESCALER_2_gc = (0x81<<0), /* Prescaler, divide by 2 */ EVSYS_CHMUX_PRESCALER_4_gc = (0x82<<0), /* Prescaler, divide by 4 */ EVSYS_CHMUX_PRESCALER_8_gc = (0x83<<0), /* Prescaler, divide by 8 */ EVSYS_CHMUX_PRESCALER_16_gc = (0x84<<0), /* Prescaler, divide by 16 */ EVSYS_CHMUX_PRESCALER_32_gc = (0x85<<0), /* Prescaler, divide by 32 */ EVSYS_CHMUX_PRESCALER_64_gc = (0x86<<0), /* Prescaler, divide by 64 */ EVSYS_CHMUX_PRESCALER_128_gc = (0x87<<0), /* Prescaler, divide by 128 */ EVSYS_CHMUX_PRESCALER_256_gc = (0x88<<0), /* Prescaler, divide by 256 */ EVSYS_CHMUX_PRESCALER_512_gc = (0x89<<0), /* Prescaler, divide by 512 */ EVSYS_CHMUX_PRESCALER_1024_gc = (0x8A<<0), /* Prescaler, divide by 1024 */ EVSYS_CHMUX_PRESCALER_2048_gc = (0x8B<<0), /* Prescaler, divide by 2048 */ EVSYS_CHMUX_PRESCALER_4096_gc = (0x8C<<0), /* Prescaler, divide by 4096 */ EVSYS_CHMUX_PRESCALER_8192_gc = (0x8D<<0), /* Prescaler, divide by 8192 */ EVSYS_CHMUX_PRESCALER_16384_gc = (0x8E<<0), /* Prescaler, divide by 16384 */ EVSYS_CHMUX_PRESCALER_32768_gc = (0x8F<<0), /* Prescaler, divide by 32768 */ EVSYS_CHMUX_TCC0_OVF_gc = (0xC0<<0), /* Timer/Counter C0 Overflow */ EVSYS_CHMUX_TCC0_ERR_gc = (0xC1<<0), /* Timer/Counter C0 Error */ EVSYS_CHMUX_TCC0_CCA_gc = (0xC4<<0), /* Timer/Counter C0 Compare or Capture A */ EVSYS_CHMUX_TCC0_CCB_gc = (0xC5<<0), /* Timer/Counter C0 Compare or Capture B */ EVSYS_CHMUX_TCC0_CCC_gc = (0xC6<<0), /* Timer/Counter C0 Compare or Capture C */ EVSYS_CHMUX_TCC0_CCD_gc = (0xC7<<0), /* Timer/Counter C0 Compare or Capture D */ EVSYS_CHMUX_TCC1_OVF_gc = (0xC8<<0), /* Timer/Counter C1 Overflow */ EVSYS_CHMUX_TCC1_ERR_gc = (0xC9<<0), /* Timer/Counter C1 Error */ EVSYS_CHMUX_TCC1_CCA_gc = (0xCC<<0), /* Timer/Counter C1 Compare or Capture A */ EVSYS_CHMUX_TCC1_CCB_gc = (0xCD<<0), /* Timer/Counter C1 Compare or Capture B */ EVSYS_CHMUX_TCD0_OVF_gc = (0xD0<<0), /* Timer/Counter D0 Overflow */ EVSYS_CHMUX_TCD0_ERR_gc = (0xD1<<0), /* Timer/Counter D0 Error */ EVSYS_CHMUX_TCD0_CCA_gc = (0xD4<<0), /* Timer/Counter D0 Compare or Capture A */ EVSYS_CHMUX_TCD0_CCB_gc = (0xD5<<0), /* Timer/Counter D0 Compare or Capture B */ EVSYS_CHMUX_TCD0_CCC_gc = (0xD6<<0), /* Timer/Counter D0 Compare or Capture C */ EVSYS_CHMUX_TCD0_CCD_gc = (0xD7<<0), /* Timer/Counter D0 Compare or Capture D */ EVSYS_CHMUX_TCE0_OVF_gc = (0xE0<<0), /* Timer/Counter E0 Overflow */ EVSYS_CHMUX_TCE0_ERR_gc = (0xE1<<0), /* Timer/Counter E0 Error */ EVSYS_CHMUX_TCE0_CCA_gc = (0xE4<<0), /* Timer/Counter E0 Compare or Capture A */ EVSYS_CHMUX_TCE0_CCB_gc = (0xE5<<0), /* Timer/Counter E0 Compare or Capture B */ EVSYS_CHMUX_TCE0_CCC_gc = (0xE6<<0), /* Timer/Counter E0 Compare or Capture C */ EVSYS_CHMUX_TCE0_CCD_gc = (0xE7<<0), /* Timer/Counter E0 Compare or Capture D */ EVSYS_CHMUX_TCF0_OVF_gc = (0xF0<<0), /* Timer/Counter F0 Overflow */ EVSYS_CHMUX_TCF0_ERR_gc = (0xF1<<0), /* Timer/Counter F0 Error */ EVSYS_CHMUX_TCF0_CCA_gc = (0xF4<<0), /* Timer/Counter F0 Compare or Capture A */ EVSYS_CHMUX_TCF0_CCB_gc = (0xF5<<0), /* Timer/Counter F0 Compare or Capture B */ EVSYS_CHMUX_TCF0_CCC_gc = (0xF6<<0), /* Timer/Counter F0 Compare or Capture C */ EVSYS_CHMUX_TCF0_CCD_gc = (0xF7<<0), /* Timer/Counter F0 Compare or Capture D */ } EVSYS_CHMUX_t; /* -------------------------------------------------------------------------- NVM - Non Volatile Memory Controller -------------------------------------------------------------------------- */ /* Non-volatile Memory Controller */ typedef struct NVM_struct { register8_t ADDR0; /* Address Register 0 */ register8_t ADDR1; /* Address Register 1 */ register8_t ADDR2; /* Address Register 2 */ register8_t reserved_0x03; register8_t DATA0; /* Data Register 0 */ register8_t DATA1; /* Data Register 1 */ register8_t DATA2; /* Data Register 2 */ register8_t reserved_0x07; register8_t reserved_0x08; register8_t reserved_0x09; register8_t CMD; /* Command */ register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t INTCTRL; /* Interrupt Control */ register8_t reserved_0x0E; register8_t STATUS; /* Status */ register8_t LOCK_BITS; /* Lock Bits (Changed from LOCKBITS to avoid avr-libc collision) */ } NVM_t; /* NVM Command */ typedef enum NVM_CMD_enum { NVM_CMD_NO_OPERATION_gc = (0x00<<0), /* Noop/Ordinary LPM */ NVM_CMD_READ_USER_SIG_ROW_gc = (0x01<<0), /* Read user signature row */ NVM_CMD_READ_CALIB_ROW_gc = (0x02<<0), /* Read calibration row */ NVM_CMD_READ_EEPROM_gc = (0x06<<0), /* Read EEPROM */ NVM_CMD_READ_FUSES_gc = (0x07<<0), /* Read fuse byte */ NVM_CMD_WRITE_LOCK_BITS_gc = (0x08<<0), /* Write lock bits */ NVM_CMD_ERASE_USER_SIG_ROW_gc = (0x18<<0), /* Erase user signature row */ NVM_CMD_WRITE_USER_SIG_ROW_gc = (0x1A<<0), /* Write user signature row */ NVM_CMD_ERASE_APP_gc = (0x20<<0), /* Erase Application Section */ NVM_CMD_ERASE_APP_PAGE_gc = (0x22<<0), /* Erase Application Section page */ NVM_CMD_LOAD_FLASH_BUFFER_gc = (0x23<<0), /* Load Flash page buffer */ NVM_CMD_WRITE_APP_PAGE_gc = (0x24<<0), /* Write Application Section page */ NVM_CMD_ERASE_WRITE_APP_PAGE_gc = (0x25<<0), /* Erase-and-write Application Section page */ NVM_CMD_ERASE_FLASH_BUFFER_gc = (0x26<<0), /* Erase/flush Flash page buffer */ NVM_CMD_ERASE_BOOT_PAGE_gc = (0x2A<<0), /* Erase Boot Section page */ NVM_CMD_ERASE_FLASH_PAGE_gc = (0x2B<<0), /* Erase Flash Page */ NVM_CMD_WRITE_BOOT_PAGE_gc = (0x2C<<0), /* Write Boot Section page */ NVM_CMD_ERASE_WRITE_BOOT_PAGE_gc = (0x2D<<0), /* Erase-and-write Boot Section page */ NVM_CMD_WRITE_FLASH_PAGE_gc = (0x2E<<0), /* Write Flash Page */ NVM_CMD_ERASE_WRITE_FLASH_PAGE_gc = (0x2F<<0), /* Erase-and-write Flash Page */ NVM_CMD_ERASE_EEPROM_gc = (0x30<<0), /* Erase EEPROM */ NVM_CMD_ERASE_EEPROM_PAGE_gc = (0x32<<0), /* Erase EEPROM page */ NVM_CMD_LOAD_EEPROM_BUFFER_gc = (0x33<<0), /* Load EEPROM page buffer */ NVM_CMD_WRITE_EEPROM_PAGE_gc = (0x34<<0), /* Write EEPROM page */ NVM_CMD_ERASE_WRITE_EEPROM_PAGE_gc = (0x35<<0), /* Erase-and-write EEPROM page */ NVM_CMD_ERASE_EEPROM_BUFFER_gc = (0x36<<0), /* Erase/flush EEPROM page buffer */ NVM_CMD_APP_CRC_gc = (0x38<<0), /* Application section CRC */ NVM_CMD_BOOT_CRC_gc = (0x39<<0), /* Boot Section CRC */ NVM_CMD_FLASH_RANGE_CRC_gc = (0x3A<<0), /* Flash Range CRC */ NVM_CMD_CHIP_ERASE_gc = (0x40<<0), /* Erase Chip */ NVM_CMD_READ_NVM_gc = (0x43<<0), /* Read NVM */ NVM_CMD_WRITE_FUSE_gc = (0x4C<<0), /* Write Fuse byte */ NVM_CMD_ERASE_BOOT_gc = (0x68<<0), /* Erase Boot Section */ NVM_CMD_FLASH_CRC_gc = (0x78<<0), /* Flash CRC */ } NVM_CMD_t; /* SPM ready interrupt level */ typedef enum NVM_SPMLVL_enum { NVM_SPMLVL_OFF_gc = (0x00<<2), /* Interrupt disabled */ NVM_SPMLVL_LO_gc = (0x01<<2), /* Low level */ NVM_SPMLVL_MED_gc = (0x02<<2), /* Medium level */ NVM_SPMLVL_HI_gc = (0x03<<2), /* High level */ } NVM_SPMLVL_t; /* EEPROM ready interrupt level */ typedef enum NVM_EELVL_enum { NVM_EELVL_OFF_gc = (0x00<<0), /* Interrupt disabled */ NVM_EELVL_LO_gc = (0x01<<0), /* Low level */ NVM_EELVL_MED_gc = (0x02<<0), /* Medium level */ NVM_EELVL_HI_gc = (0x03<<0), /* High level */ } NVM_EELVL_t; /* Boot lock bits - boot setcion */ typedef enum NVM_BLBB_enum { NVM_BLBB_RWLOCK_gc = (0x00<<6), /* Read and write not allowed */ NVM_BLBB_RLOCK_gc = (0x01<<6), /* Read not allowed */ NVM_BLBB_WLOCK_gc = (0x02<<6), /* Write not allowed */ NVM_BLBB_NOLOCK_gc = (0x03<<6), /* No locks */ } NVM_BLBB_t; /* Boot lock bits - application section */ typedef enum NVM_BLBA_enum { NVM_BLBA_RWLOCK_gc = (0x00<<4), /* Read and write not allowed */ NVM_BLBA_RLOCK_gc = (0x01<<4), /* Read not allowed */ NVM_BLBA_WLOCK_gc = (0x02<<4), /* Write not allowed */ NVM_BLBA_NOLOCK_gc = (0x03<<4), /* No locks */ } NVM_BLBA_t; /* Boot lock bits - application table section */ typedef enum NVM_BLBAT_enum { NVM_BLBAT_RWLOCK_gc = (0x00<<2), /* Read and write not allowed */ NVM_BLBAT_RLOCK_gc = (0x01<<2), /* Read not allowed */ NVM_BLBAT_WLOCK_gc = (0x02<<2), /* Write not allowed */ NVM_BLBAT_NOLOCK_gc = (0x03<<2), /* No locks */ } NVM_BLBAT_t; /* Lock bits */ typedef enum NVM_LB_enum { NVM_LB_RWLOCK_gc = (0x00<<0), /* Read and write not allowed */ NVM_LB_WLOCK_gc = (0x02<<0), /* Write not allowed */ NVM_LB_NOLOCK_gc = (0x03<<0), /* No locks */ } NVM_LB_t; /* -------------------------------------------------------------------------- ADC - Analog/Digital Converter -------------------------------------------------------------------------- */ /* ADC Channel */ typedef struct ADC_CH_struct { register8_t CTRL; /* Control Register */ register8_t MUXCTRL; /* MUX Control */ register8_t INTCTRL; /* Channel Interrupt Control Register */ register8_t INTFLAGS; /* Interrupt Flags */ _WORDREGISTER(RES); /* Channel Result */ register8_t SCAN; /* Input Channel Scan */ register8_t reserved_0x07; } ADC_CH_t; /* Analog-to-Digital Converter */ typedef struct ADC_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t REFCTRL; /* Reference Control */ register8_t EVCTRL; /* Event Control */ register8_t PRESCALER; /* Clock Prescaler */ register8_t reserved_0x05; register8_t INTFLAGS; /* Interrupt Flags */ register8_t TEMP; /* Temporary Register */ register8_t reserved_0x08; register8_t reserved_0x09; register8_t reserved_0x0A; register8_t reserved_0x0B; _WORDREGISTER(CAL); /* Calibration Value */ register8_t reserved_0x0E; register8_t reserved_0x0F; _WORDREGISTER(CH0RES); /* Channel 0 Result */ register8_t reserved_0x12; register8_t reserved_0x13; register8_t reserved_0x14; register8_t reserved_0x15; register8_t reserved_0x16; register8_t reserved_0x17; _WORDREGISTER(CMP); /* Compare Value */ register8_t reserved_0x1A; register8_t reserved_0x1B; register8_t reserved_0x1C; register8_t reserved_0x1D; register8_t reserved_0x1E; register8_t reserved_0x1F; ADC_CH_t CH0; /* ADC Channel 0 */ } ADC_t; /* Current Limitation */ typedef enum ADC_CURRLIMIT_enum { ADC_CURRLIMIT_NO_gc = (0x00<<5), /* No current limit, 300ksps max sampling rate */ ADC_CURRLIMIT_LOW_gc = (0x01<<5), /* Low current limit, 250ksps max sampling rate */ ADC_CURRLIMIT_MED_gc = (0x02<<5), /* Medium current limit, 150ksps max sampling rate */ ADC_CURRLIMIT_HIGH_gc = (0x03<<5), /* High current limit, 50ksps max sampling rate */ } ADC_CURRLIMIT_t; /* Positive input multiplexer selection */ typedef enum ADC_CH_MUXPOS_enum { ADC_CH_MUXPOS_PIN0_gc = (0x00<<3), /* Input pin 0 */ ADC_CH_MUXPOS_PIN1_gc = (0x01<<3), /* Input pin 1 */ ADC_CH_MUXPOS_PIN2_gc = (0x02<<3), /* Input pin 2 */ ADC_CH_MUXPOS_PIN3_gc = (0x03<<3), /* Input pin 3 */ ADC_CH_MUXPOS_PIN4_gc = (0x04<<3), /* Input pin 4 */ ADC_CH_MUXPOS_PIN5_gc = (0x05<<3), /* Input pin 5 */ ADC_CH_MUXPOS_PIN6_gc = (0x06<<3), /* Input pin 6 */ ADC_CH_MUXPOS_PIN7_gc = (0x07<<3), /* Input pin 7 */ ADC_CH_MUXPOS_PIN8_gc = (0x08<<3), /* Input pin 8 */ ADC_CH_MUXPOS_PIN9_gc = (0x09<<3), /* Input pin 9 */ ADC_CH_MUXPOS_PIN10_gc = (0x0A<<3), /* Input pin 10 */ ADC_CH_MUXPOS_PIN11_gc = (0x0B<<3), /* Input pin 11 */ ADC_CH_MUXPOS_PIN12_gc = (0x0C<<3), /* Input pin 12 */ ADC_CH_MUXPOS_PIN13_gc = (0x0D<<3), /* Input pin 13 */ ADC_CH_MUXPOS_PIN14_gc = (0x0E<<3), /* Input pin 14 */ ADC_CH_MUXPOS_PIN15_gc = (0x0F<<3), /* Input pin 15 */ } ADC_CH_MUXPOS_t; /* Internal input multiplexer selections */ typedef enum ADC_CH_MUXINT_enum { ADC_CH_MUXINT_TEMP_gc = (0x00<<3), /* Temperature Reference */ ADC_CH_MUXINT_BANDGAP_gc = (0x01<<3), /* Bandgap Reference */ ADC_CH_MUXINT_SCALEDVCC_gc = (0x02<<3), /* 1/10 scaled VCC */ } ADC_CH_MUXINT_t; /* Negative input multiplexer selection */ typedef enum ADC_CH_MUXNEG_enum { ADC_CH_MUXNEG_PIN0_gc = (0x00<<0), /* Input pin 0 */ ADC_CH_MUXNEG_PIN1_gc = (0x01<<0), /* Input pin 1 */ ADC_CH_MUXNEG_PIN2_gc = (0x02<<0), /* Input pin 2 */ ADC_CH_MUXNEG_PIN3_gc = (0x03<<0), /* Input pin 3 */ ADC_CH_MUXNEG_PIN4_gc = (0x00<<0), /* Input pin 4 */ ADC_CH_MUXNEG_PIN5_gc = (0x01<<0), /* Input pin 5 */ ADC_CH_MUXNEG_PIN6_gc = (0x02<<0), /* Input pin 6 */ ADC_CH_MUXNEG_PIN7_gc = (0x03<<0), /* Input pin 7 */ } ADC_CH_MUXNEG_t; /* Input mode */ typedef enum ADC_CH_INPUTMODE_enum { ADC_CH_INPUTMODE_INTERNAL_gc = (0x00<<0), /* Internal inputs, no gain */ ADC_CH_INPUTMODE_SINGLEENDED_gc = (0x01<<0), /* Single-ended input, no gain */ ADC_CH_INPUTMODE_DIFF_gc = (0x02<<0), /* Differential input, no gain */ ADC_CH_INPUTMODE_DIFFWGAIN_gc = (0x03<<0), /* Differential input, with gain */ } ADC_CH_INPUTMODE_t; /* Gain factor */ typedef enum ADC_CH_GAIN_enum { ADC_CH_GAIN_1X_gc = (0x00<<2), /* 1x gain */ ADC_CH_GAIN_2X_gc = (0x01<<2), /* 2x gain */ ADC_CH_GAIN_4X_gc = (0x02<<2), /* 4x gain */ ADC_CH_GAIN_8X_gc = (0x03<<2), /* 8x gain */ ADC_CH_GAIN_16X_gc = (0x04<<2), /* 16x gain */ ADC_CH_GAIN_32X_gc = (0x05<<2), /* 32x gain */ ADC_CH_GAIN_64X_gc = (0x06<<2), /* 64x gain */ ADC_CH_GAIN_DIV2_gc = (0x07<<2), /* x/2 gain */ } ADC_CH_GAIN_t; /* Conversion result resolution */ typedef enum ADC_RESOLUTION_enum { ADC_RESOLUTION_12BIT_gc = (0x00<<1), /* 12-bit right-adjusted result */ ADC_RESOLUTION_8BIT_gc = (0x02<<1), /* 8-bit right-adjusted result */ ADC_RESOLUTION_LEFT12BIT_gc = (0x03<<1), /* 12-bit left-adjusted result */ } ADC_RESOLUTION_t; /* Voltage reference selection */ typedef enum ADC_REFSEL_enum { ADC_REFSEL_INT1V_gc = (0x00<<4), /* Internal 1V */ ADC_REFSEL_INTVCC_gc = (0x01<<4), /* Internal VCC / 1.6 */ ADC_REFSEL_AREFA_gc = (0x02<<4), /* External reference on PORT A */ ADC_REFSEL_AREFB_gc = (0x03<<4), /* External reference on PORT B */ ADC_REFSEL_INTVCC2_gc = (0x04<<4), /* Internal VCC / 2 */ } ADC_REFSEL_t; /* Event channel input selection */ typedef enum ADC_EVSEL_enum { ADC_EVSEL_0_gc = (0x00<<3), /* Event Channel 0 */ ADC_EVSEL_1_gc = (0x01<<3), /* Event Channel 1 */ ADC_EVSEL_2_gc = (0x02<<3), /* Event Channel 2 */ ADC_EVSEL_3_gc = (0x03<<3), /* Event Channel 3 */ } ADC_EVSEL_t; /* Event action selection */ typedef enum ADC_EVACT_enum { ADC_EVACT_NONE_gc = (0x00<<0), /* No event action */ ADC_EVACT_CH0_gc = (0x01<<0), /* First event triggers channel 0 */ ADC_EVACT_SYNCSWEEP_gc = (0x06<<0), /* The ADC is flushed and restarted for accurate timing */ } ADC_EVACT_t; /* Interupt mode */ typedef enum ADC_CH_INTMODE_enum { ADC_CH_INTMODE_COMPLETE_gc = (0x00<<2), /* Interrupt on conversion complete */ ADC_CH_INTMODE_BELOW_gc = (0x01<<2), /* Interrupt on result below compare value */ ADC_CH_INTMODE_ABOVE_gc = (0x03<<2), /* Interrupt on result above compare value */ } ADC_CH_INTMODE_t; /* Interrupt level */ typedef enum ADC_CH_INTLVL_enum { ADC_CH_INTLVL_OFF_gc = (0x00<<0), /* Interrupt disabled */ ADC_CH_INTLVL_LO_gc = (0x01<<0), /* Low level */ ADC_CH_INTLVL_MED_gc = (0x02<<0), /* Medium level */ ADC_CH_INTLVL_HI_gc = (0x03<<0), /* High level */ } ADC_CH_INTLVL_t; /* Clock prescaler */ typedef enum ADC_PRESCALER_enum { ADC_PRESCALER_DIV4_gc = (0x00<<0), /* Divide clock by 4 */ ADC_PRESCALER_DIV8_gc = (0x01<<0), /* Divide clock by 8 */ ADC_PRESCALER_DIV16_gc = (0x02<<0), /* Divide clock by 16 */ ADC_PRESCALER_DIV32_gc = (0x03<<0), /* Divide clock by 32 */ ADC_PRESCALER_DIV64_gc = (0x04<<0), /* Divide clock by 64 */ ADC_PRESCALER_DIV128_gc = (0x05<<0), /* Divide clock by 128 */ ADC_PRESCALER_DIV256_gc = (0x06<<0), /* Divide clock by 256 */ ADC_PRESCALER_DIV512_gc = (0x07<<0), /* Divide clock by 512 */ } ADC_PRESCALER_t; /* -------------------------------------------------------------------------- AC - Analog Comparator -------------------------------------------------------------------------- */ /* Analog Comparator */ typedef struct AC_struct { register8_t AC0CTRL; /* Analog Comparator 0 Control */ register8_t AC1CTRL; /* Analog Comparator 1 Control */ register8_t AC0MUXCTRL; /* Analog Comparator 0 MUX Control */ register8_t AC1MUXCTRL; /* Analog Comparator 1 MUX Control */ register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t WINCTRL; /* Window Mode Control */ register8_t STATUS; /* Status */ } AC_t; /* Interrupt mode */ typedef enum AC_INTMODE_enum { AC_INTMODE_BOTHEDGES_gc = (0x00<<6), /* Interrupt on both edges */ AC_INTMODE_FALLING_gc = (0x02<<6), /* Interrupt on falling edge */ AC_INTMODE_RISING_gc = (0x03<<6), /* Interrupt on rising edge */ } AC_INTMODE_t; /* Interrupt level */ typedef enum AC_INTLVL_enum { AC_INTLVL_OFF_gc = (0x00<<4), /* Interrupt disabled */ AC_INTLVL_LO_gc = (0x01<<4), /* Low level */ AC_INTLVL_MED_gc = (0x02<<4), /* Medium level */ AC_INTLVL_HI_gc = (0x03<<4), /* High level */ } AC_INTLVL_t; /* Hysteresis mode selection */ typedef enum AC_HYSMODE_enum { AC_HYSMODE_NO_gc = (0x00<<1), /* No hysteresis */ AC_HYSMODE_SMALL_gc = (0x01<<1), /* Small hysteresis */ AC_HYSMODE_LARGE_gc = (0x02<<1), /* Large hysteresis */ } AC_HYSMODE_t; /* Positive input multiplexer selection */ typedef enum AC_MUXPOS_enum { AC_MUXPOS_PIN0_gc = (0x00<<3), /* Pin 0 */ AC_MUXPOS_PIN1_gc = (0x01<<3), /* Pin 1 */ AC_MUXPOS_PIN2_gc = (0x02<<3), /* Pin 2 */ AC_MUXPOS_PIN3_gc = (0x03<<3), /* Pin 3 */ AC_MUXPOS_PIN4_gc = (0x04<<3), /* Pin 4 */ AC_MUXPOS_PIN5_gc = (0x05<<3), /* Pin 5 */ AC_MUXPOS_PIN6_gc = (0x06<<3), /* Pin 6 */ } AC_MUXPOS_t; /* Negative input multiplexer selection */ typedef enum AC_MUXNEG_enum { AC_MUXNEG_PIN0_gc = (0x00<<0), /* Pin 0 */ AC_MUXNEG_PIN1_gc = (0x01<<0), /* Pin 1 */ AC_MUXNEG_PIN3_gc = (0x02<<0), /* Pin 3 */ AC_MUXNEG_PIN5_gc = (0x03<<0), /* Pin 5 */ AC_MUXNEG_PIN7_gc = (0x04<<0), /* Pin 7 */ AC_MUXNEG_BANDGAP_gc = (0x06<<0), /* Bandgap Reference */ AC_MUXNEG_SCALER_gc = (0x07<<0), /* Internal voltage scaler */ } AC_MUXNEG_t; /* Windows interrupt mode */ typedef enum AC_WINTMODE_enum { AC_WINTMODE_ABOVE_gc = (0x00<<2), /* Interrupt on above window */ AC_WINTMODE_INSIDE_gc = (0x01<<2), /* Interrupt on inside window */ AC_WINTMODE_BELOW_gc = (0x02<<2), /* Interrupt on below window */ AC_WINTMODE_OUTSIDE_gc = (0x03<<2), /* Interrupt on outside window */ } AC_WINTMODE_t; /* Window interrupt level */ typedef enum AC_WINTLVL_enum { AC_WINTLVL_OFF_gc = (0x00<<0), /* Interrupt disabled */ AC_WINTLVL_LO_gc = (0x01<<0), /* Low priority */ AC_WINTLVL_MED_gc = (0x02<<0), /* Medium priority */ AC_WINTLVL_HI_gc = (0x03<<0), /* High priority */ } AC_WINTLVL_t; /* Window mode state */ typedef enum AC_WSTATE_enum { AC_WSTATE_ABOVE_gc = (0x00<<6), /* Signal above window */ AC_WSTATE_INSIDE_gc = (0x01<<6), /* Signal inside window */ AC_WSTATE_BELOW_gc = (0x02<<6), /* Signal below window */ } AC_WSTATE_t; /* -------------------------------------------------------------------------- RTC - Real-Time Counter -------------------------------------------------------------------------- */ /* Real-Time Counter */ typedef struct RTC_struct { register8_t CTRL; /* Control Register */ register8_t STATUS; /* Status Register */ register8_t INTCTRL; /* Interrupt Control Register */ register8_t INTFLAGS; /* Interrupt Flags */ register8_t TEMP; /* Temporary register */ register8_t reserved_0x05; register8_t reserved_0x06; register8_t reserved_0x07; _WORDREGISTER(CNT); /* Count Register */ _WORDREGISTER(PER); /* Period Register */ _WORDREGISTER(COMP); /* Compare Register */ } RTC_t; /* Prescaler Factor */ typedef enum RTC_PRESCALER_enum { RTC_PRESCALER_OFF_gc = (0x00<<0), /* RTC Off */ RTC_PRESCALER_DIV1_gc = (0x01<<0), /* RTC Clock */ RTC_PRESCALER_DIV2_gc = (0x02<<0), /* RTC Clock / 2 */ RTC_PRESCALER_DIV8_gc = (0x03<<0), /* RTC Clock / 8 */ RTC_PRESCALER_DIV16_gc = (0x04<<0), /* RTC Clock / 16 */ RTC_PRESCALER_DIV64_gc = (0x05<<0), /* RTC Clock / 64 */ RTC_PRESCALER_DIV256_gc = (0x06<<0), /* RTC Clock / 256 */ RTC_PRESCALER_DIV1024_gc = (0x07<<0), /* RTC Clock / 1024 */ } RTC_PRESCALER_t; /* Compare Interrupt level */ typedef enum RTC_COMPINTLVL_enum { RTC_COMPINTLVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ RTC_COMPINTLVL_LO_gc = (0x01<<2), /* Low Level */ RTC_COMPINTLVL_MED_gc = (0x02<<2), /* Medium Level */ RTC_COMPINTLVL_HI_gc = (0x03<<2), /* High Level */ } RTC_COMPINTLVL_t; /* Overflow Interrupt level */ typedef enum RTC_OVFINTLVL_enum { RTC_OVFINTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ RTC_OVFINTLVL_LO_gc = (0x01<<0), /* Low Level */ RTC_OVFINTLVL_MED_gc = (0x02<<0), /* Medium Level */ RTC_OVFINTLVL_HI_gc = (0x03<<0), /* High Level */ } RTC_OVFINTLVL_t; /* -------------------------------------------------------------------------- TWI - Two-Wire Interface -------------------------------------------------------------------------- */ /* */ typedef struct TWI_MASTER_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t CTRLC; /* Control Register C */ register8_t STATUS; /* Status Register */ register8_t BAUD; /* Baurd Rate Control Register */ register8_t ADDR; /* Address Register */ register8_t DATA; /* Data Register */ } TWI_MASTER_t; /* */ typedef struct TWI_SLAVE_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t STATUS; /* Status Register */ register8_t ADDR; /* Address Register */ register8_t DATA; /* Data Register */ register8_t ADDRMASK; /* Address Mask Register */ } TWI_SLAVE_t; /* Two-Wire Interface */ typedef struct TWI_struct { register8_t CTRL; /* TWI Common Control Register */ TWI_MASTER_t MASTER; /* TWI master module */ TWI_SLAVE_t SLAVE; /* TWI slave module */ } TWI_t; /* SDA Hold Time */ typedef enum TWI_SDAHOLD_enum { TWI_SDAHOLD_OFF_gc = (0x00<<1), /* SDA Hold Time off */ TWI_SDAHOLD_50NS_gc = (0x01<<1), /* SDA Hold Time 50 ns */ TWI_SDAHOLD_300NS_gc = (0x02<<1), /* SDA Hold Time 300 ns */ TWI_SDAHOLD_400NS_gc = (0x03<<1), /* SDA Hold Time 400 ns */ } TWI_SDAHOLD_t; /* Master Interrupt Level */ typedef enum TWI_MASTER_INTLVL_enum { TWI_MASTER_INTLVL_OFF_gc = (0x00<<6), /* Interrupt Disabled */ TWI_MASTER_INTLVL_LO_gc = (0x01<<6), /* Low Level */ TWI_MASTER_INTLVL_MED_gc = (0x02<<6), /* Medium Level */ TWI_MASTER_INTLVL_HI_gc = (0x03<<6), /* High Level */ } TWI_MASTER_INTLVL_t; /* Inactive Timeout */ typedef enum TWI_MASTER_TIMEOUT_enum { TWI_MASTER_TIMEOUT_DISABLED_gc = (0x00<<2), /* Bus Timeout Disabled */ TWI_MASTER_TIMEOUT_50US_gc = (0x01<<2), /* 50 Microseconds */ TWI_MASTER_TIMEOUT_100US_gc = (0x02<<2), /* 100 Microseconds */ TWI_MASTER_TIMEOUT_200US_gc = (0x03<<2), /* 200 Microseconds */ } TWI_MASTER_TIMEOUT_t; /* Master Command */ typedef enum TWI_MASTER_CMD_enum { TWI_MASTER_CMD_NOACT_gc = (0x00<<0), /* No Action */ TWI_MASTER_CMD_REPSTART_gc = (0x01<<0), /* Issue Repeated Start Condition */ TWI_MASTER_CMD_RECVTRANS_gc = (0x02<<0), /* Receive or Transmit Data */ TWI_MASTER_CMD_STOP_gc = (0x03<<0), /* Issue Stop Condition */ } TWI_MASTER_CMD_t; /* Master Bus State */ typedef enum TWI_MASTER_BUSSTATE_enum { TWI_MASTER_BUSSTATE_UNKNOWN_gc = (0x00<<0), /* Unknown Bus State */ TWI_MASTER_BUSSTATE_IDLE_gc = (0x01<<0), /* Bus is Idle */ TWI_MASTER_BUSSTATE_OWNER_gc = (0x02<<0), /* This Module Controls The Bus */ TWI_MASTER_BUSSTATE_BUSY_gc = (0x03<<0), /* The Bus is Busy */ } TWI_MASTER_BUSSTATE_t; /* Slave Interrupt Level */ typedef enum TWI_SLAVE_INTLVL_enum { TWI_SLAVE_INTLVL_OFF_gc = (0x00<<6), /* Interrupt Disabled */ TWI_SLAVE_INTLVL_LO_gc = (0x01<<6), /* Low Level */ TWI_SLAVE_INTLVL_MED_gc = (0x02<<6), /* Medium Level */ TWI_SLAVE_INTLVL_HI_gc = (0x03<<6), /* High Level */ } TWI_SLAVE_INTLVL_t; /* Slave Command */ typedef enum TWI_SLAVE_CMD_enum { TWI_SLAVE_CMD_NOACT_gc = (0x00<<0), /* No Action */ TWI_SLAVE_CMD_COMPTRANS_gc = (0x02<<0), /* Used To Complete a Transaction */ TWI_SLAVE_CMD_RESPONSE_gc = (0x03<<0), /* Used in Response to Address/Data Interrupt */ } TWI_SLAVE_CMD_t; /* -------------------------------------------------------------------------- USB - USB -------------------------------------------------------------------------- */ /* USB Endpoint */ typedef struct USB_EP_struct { register8_t STATUS; /* Endpoint Status */ register8_t CTRL; /* Endpoint Control */ _WORDREGISTER(CNT); /* USB Endpoint Counter */ _WORDREGISTER(DATAPTR); /* Data Pointer */ _WORDREGISTER(AUXDATA); /* Auxiliary Data */ } USB_EP_t; /* Universal Serial Bus */ typedef struct USB_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t STATUS; /* Status Register */ register8_t ADDR; /* Address Register */ register8_t FIFOWP; /* FIFO Write Pointer Register */ register8_t FIFORP; /* FIFO Read Pointer Register */ _WORDREGISTER(EPPTR); /* Endpoint Configuration Table Pointer */ register8_t INTCTRLA; /* Interrupt Control Register A */ register8_t INTCTRLB; /* Interrupt Control Register B */ register8_t INTFLAGSACLR; /* Clear Interrupt Flag Register A */ register8_t INTFLAGSASET; /* Set Interrupt Flag Register A */ register8_t INTFLAGSBCLR; /* Clear Interrupt Flag Register B */ register8_t INTFLAGSBSET; /* Set Interrupt Flag Register B */ register8_t reserved_0x0E; register8_t reserved_0x0F; register8_t reserved_0x10; register8_t reserved_0x11; register8_t reserved_0x12; register8_t reserved_0x13; register8_t reserved_0x14; register8_t reserved_0x15; register8_t reserved_0x16; register8_t reserved_0x17; register8_t reserved_0x18; register8_t reserved_0x19; register8_t reserved_0x1A; register8_t reserved_0x1B; register8_t reserved_0x1C; register8_t reserved_0x1D; register8_t reserved_0x1E; register8_t reserved_0x1F; register8_t reserved_0x20; register8_t reserved_0x21; register8_t reserved_0x22; register8_t reserved_0x23; register8_t reserved_0x24; register8_t reserved_0x25; register8_t reserved_0x26; register8_t reserved_0x27; register8_t reserved_0x28; register8_t reserved_0x29; register8_t reserved_0x2A; register8_t reserved_0x2B; register8_t reserved_0x2C; register8_t reserved_0x2D; register8_t reserved_0x2E; register8_t reserved_0x2F; register8_t reserved_0x30; register8_t reserved_0x31; register8_t reserved_0x32; register8_t reserved_0x33; register8_t reserved_0x34; register8_t reserved_0x35; register8_t reserved_0x36; register8_t reserved_0x37; register8_t reserved_0x38; register8_t reserved_0x39; register8_t CAL0; /* Calibration Byte 0 */ register8_t CAL1; /* Calibration Byte 1 */ } USB_t; /* USB Endpoint Table */ typedef struct USB_EP_TABLE_struct { USB_EP_t EP0OUT; /* Endpoint 0 */ USB_EP_t EP0IN; /* Endpoint 0 */ USB_EP_t EP1OUT; /* Endpoint 1 */ USB_EP_t EP1IN; /* Endpoint 1 */ USB_EP_t EP2OUT; /* Endpoint 2 */ USB_EP_t EP2IN; /* Endpoint 2 */ USB_EP_t EP3OUT; /* Endpoint 3 */ USB_EP_t EP3IN; /* Endpoint 3 */ USB_EP_t EP4OUT; /* Endpoint 4 */ USB_EP_t EP4IN; /* Endpoint 4 */ USB_EP_t EP5OUT; /* Endpoint 5 */ USB_EP_t EP5IN; /* Endpoint 5 */ USB_EP_t EP6OUT; /* Endpoint 6 */ USB_EP_t EP6IN; /* Endpoint 6 */ USB_EP_t EP7OUT; /* Endpoint 7 */ USB_EP_t EP7IN; /* Endpoint 7 */ USB_EP_t EP8OUT; /* Endpoint 8 */ USB_EP_t EP8IN; /* Endpoint 8 */ USB_EP_t EP9OUT; /* Endpoint 9 */ USB_EP_t EP9IN; /* Endpoint 9 */ USB_EP_t EP10OUT; /* Endpoint 10 */ USB_EP_t EP10IN; /* Endpoint 10 */ USB_EP_t EP11OUT; /* Endpoint 11 */ USB_EP_t EP11IN; /* Endpoint 11 */ USB_EP_t EP12OUT; /* Endpoint 12 */ USB_EP_t EP12IN; /* Endpoint 12 */ USB_EP_t EP13OUT; /* Endpoint 13 */ USB_EP_t EP13IN; /* Endpoint 13 */ USB_EP_t EP14OUT; /* Endpoint 14 */ USB_EP_t EP14IN; /* Endpoint 14 */ USB_EP_t EP15OUT; /* Endpoint 15 */ USB_EP_t EP15IN; /* Endpoint 15 */ register8_t reserved_0x100; register8_t reserved_0x101; register8_t reserved_0x102; register8_t reserved_0x103; register8_t reserved_0x104; register8_t reserved_0x105; register8_t reserved_0x106; register8_t reserved_0x107; register8_t reserved_0x108; register8_t reserved_0x109; register8_t reserved_0x10A; register8_t reserved_0x10B; register8_t reserved_0x10C; register8_t reserved_0x10D; register8_t reserved_0x10E; register8_t reserved_0x10F; register8_t FRAMENUML; /* Frame Number Low Byte */ register8_t FRAMENUMH; /* Frame Number High Byte */ } USB_EP_TABLE_t; /* Interrupt level */ typedef enum USB_INTLVL_enum { USB_INTLVL_OFF_gc = (0x00<<0), /* Interrupt disabled */ USB_INTLVL_LO_gc = (0x01<<0), /* Low level */ USB_INTLVL_MED_gc = (0x02<<0), /* Medium level */ USB_INTLVL_HI_gc = (0x03<<0), /* High level */ } USB_INTLVL_t; /* USB Endpoint Type */ typedef enum USB_EP_TYPE_enum { USB_EP_TYPE_DISABLE_gc = (0x00<<6), /* Endpoint Disabled */ USB_EP_TYPE_CONTROL_gc = (0x01<<6), /* Control */ USB_EP_TYPE_BULK_gc = (0x02<<6), /* Bulk/Interrupt */ USB_EP_TYPE_ISOCHRONOUS_gc = (0x03<<6), /* Isochronous */ } USB_EP_TYPE_t; /* USB Endpoint Buffersize */ typedef enum USB_EP_BUFSIZE_enum { USB_EP_BUFSIZE_8_gc = (0x00<<0), /* 8 bytes buffer size */ USB_EP_BUFSIZE_16_gc = (0x01<<0), /* 16 bytes buffer size */ USB_EP_BUFSIZE_32_gc = (0x02<<0), /* 32 bytes buffer size */ USB_EP_BUFSIZE_64_gc = (0x03<<0), /* 64 bytes buffer size */ USB_EP_BUFSIZE_128_gc = (0x04<<0), /* 128 bytes buffer size */ USB_EP_BUFSIZE_256_gc = (0x05<<0), /* 256 bytes buffer size */ USB_EP_BUFSIZE_512_gc = (0x06<<0), /* 512 bytes buffer size */ USB_EP_BUFSIZE_1023_gc = (0x07<<0), /* 1023 bytes buffer size */ } USB_EP_BUFSIZE_t; /* -------------------------------------------------------------------------- PORT - I/O Port Configuration -------------------------------------------------------------------------- */ /* I/O Ports */ typedef struct PORT_struct { register8_t DIR; /* I/O Port Data Direction */ register8_t DIRSET; /* I/O Port Data Direction Set */ register8_t DIRCLR; /* I/O Port Data Direction Clear */ register8_t DIRTGL; /* I/O Port Data Direction Toggle */ register8_t OUT; /* I/O Port Output */ register8_t OUTSET; /* I/O Port Output Set */ register8_t OUTCLR; /* I/O Port Output Clear */ register8_t OUTTGL; /* I/O Port Output Toggle */ register8_t IN; /* I/O port Input */ register8_t INTCTRL; /* Interrupt Control Register */ register8_t INT0MASK; /* Port Interrupt 0 Mask */ register8_t INT1MASK; /* Port Interrupt 1 Mask */ register8_t INTFLAGS; /* Interrupt Flag Register */ register8_t reserved_0x0D; register8_t REMAP; /* I/O Port Pin Remap Register */ register8_t reserved_0x0F; register8_t PIN0CTRL; /* Pin 0 Control Register */ register8_t PIN1CTRL; /* Pin 1 Control Register */ register8_t PIN2CTRL; /* Pin 2 Control Register */ register8_t PIN3CTRL; /* Pin 3 Control Register */ register8_t PIN4CTRL; /* Pin 4 Control Register */ register8_t PIN5CTRL; /* Pin 5 Control Register */ register8_t PIN6CTRL; /* Pin 6 Control Register */ register8_t PIN7CTRL; /* Pin 7 Control Register */ } PORT_t; /* Port Interrupt 0 Level */ typedef enum PORT_INT0LVL_enum { PORT_INT0LVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ PORT_INT0LVL_LO_gc = (0x01<<0), /* Low Level */ PORT_INT0LVL_MED_gc = (0x02<<0), /* Medium Level */ PORT_INT0LVL_HI_gc = (0x03<<0), /* High Level */ } PORT_INT0LVL_t; /* Port Interrupt 1 Level */ typedef enum PORT_INT1LVL_enum { PORT_INT1LVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ PORT_INT1LVL_LO_gc = (0x01<<2), /* Low Level */ PORT_INT1LVL_MED_gc = (0x02<<2), /* Medium Level */ PORT_INT1LVL_HI_gc = (0x03<<2), /* High Level */ } PORT_INT1LVL_t; /* Output/Pull Configuration */ typedef enum PORT_OPC_enum { PORT_OPC_TOTEM_gc = (0x00<<3), /* Totempole */ PORT_OPC_BUSKEEPER_gc = (0x01<<3), /* Totempole w/ Bus keeper on Input and Output */ PORT_OPC_PULLDOWN_gc = (0x02<<3), /* Totempole w/ Pull-down on Input */ PORT_OPC_PULLUP_gc = (0x03<<3), /* Totempole w/ Pull-up on Input */ PORT_OPC_WIREDOR_gc = (0x04<<3), /* Wired OR */ PORT_OPC_WIREDAND_gc = (0x05<<3), /* Wired AND */ PORT_OPC_WIREDORPULL_gc = (0x06<<3), /* Wired OR w/ Pull-down */ PORT_OPC_WIREDANDPULL_gc = (0x07<<3), /* Wired AND w/ Pull-up */ } PORT_OPC_t; /* Input/Sense Configuration */ typedef enum PORT_ISC_enum { PORT_ISC_BOTHEDGES_gc = (0x00<<0), /* Sense Both Edges */ PORT_ISC_RISING_gc = (0x01<<0), /* Sense Rising Edge */ PORT_ISC_FALLING_gc = (0x02<<0), /* Sense Falling Edge */ PORT_ISC_LEVEL_gc = (0x03<<0), /* Sense Level (Transparent For Events) */ PORT_ISC_INPUT_DISABLE_gc = (0x07<<0), /* Disable Digital Input Buffer */ } PORT_ISC_t; /* -------------------------------------------------------------------------- TC - 16-bit Timer/Counter With PWM -------------------------------------------------------------------------- */ /* 16-bit Timer/Counter 0 */ typedef struct TC0_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t CTRLC; /* Control register C */ register8_t CTRLD; /* Control Register D */ register8_t CTRLE; /* Control Register E */ register8_t reserved_0x05; register8_t INTCTRLA; /* Interrupt Control Register A */ register8_t INTCTRLB; /* Interrupt Control Register B */ register8_t CTRLFCLR; /* Control Register F Clear */ register8_t CTRLFSET; /* Control Register F Set */ register8_t CTRLGCLR; /* Control Register G Clear */ register8_t CTRLGSET; /* Control Register G Set */ register8_t INTFLAGS; /* Interrupt Flag Register */ register8_t reserved_0x0D; register8_t reserved_0x0E; register8_t TEMP; /* Temporary Register For 16-bit Access */ register8_t reserved_0x10; register8_t reserved_0x11; register8_t reserved_0x12; register8_t reserved_0x13; register8_t reserved_0x14; register8_t reserved_0x15; register8_t reserved_0x16; register8_t reserved_0x17; register8_t reserved_0x18; register8_t reserved_0x19; register8_t reserved_0x1A; register8_t reserved_0x1B; register8_t reserved_0x1C; register8_t reserved_0x1D; register8_t reserved_0x1E; register8_t reserved_0x1F; _WORDREGISTER(CNT); /* Count */ register8_t reserved_0x22; register8_t reserved_0x23; register8_t reserved_0x24; register8_t reserved_0x25; _WORDREGISTER(PER); /* Period */ _WORDREGISTER(CCA); /* Compare or Capture A */ _WORDREGISTER(CCB); /* Compare or Capture B */ _WORDREGISTER(CCC); /* Compare or Capture C */ _WORDREGISTER(CCD); /* Compare or Capture D */ register8_t reserved_0x30; register8_t reserved_0x31; register8_t reserved_0x32; register8_t reserved_0x33; register8_t reserved_0x34; register8_t reserved_0x35; _WORDREGISTER(PERBUF); /* Period Buffer */ _WORDREGISTER(CCABUF); /* Compare Or Capture A Buffer */ _WORDREGISTER(CCBBUF); /* Compare Or Capture B Buffer */ _WORDREGISTER(CCCBUF); /* Compare Or Capture C Buffer */ _WORDREGISTER(CCDBUF); /* Compare Or Capture D Buffer */ } TC0_t; /* 16-bit Timer/Counter 1 */ typedef struct TC1_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t CTRLC; /* Control register C */ register8_t CTRLD; /* Control Register D */ register8_t CTRLE; /* Control Register E */ register8_t reserved_0x05; register8_t INTCTRLA; /* Interrupt Control Register A */ register8_t INTCTRLB; /* Interrupt Control Register B */ register8_t CTRLFCLR; /* Control Register F Clear */ register8_t CTRLFSET; /* Control Register F Set */ register8_t CTRLGCLR; /* Control Register G Clear */ register8_t CTRLGSET; /* Control Register G Set */ register8_t INTFLAGS; /* Interrupt Flag Register */ register8_t reserved_0x0D; register8_t reserved_0x0E; register8_t TEMP; /* Temporary Register For 16-bit Access */ register8_t reserved_0x10; register8_t reserved_0x11; register8_t reserved_0x12; register8_t reserved_0x13; register8_t reserved_0x14; register8_t reserved_0x15; register8_t reserved_0x16; register8_t reserved_0x17; register8_t reserved_0x18; register8_t reserved_0x19; register8_t reserved_0x1A; register8_t reserved_0x1B; register8_t reserved_0x1C; register8_t reserved_0x1D; register8_t reserved_0x1E; register8_t reserved_0x1F; _WORDREGISTER(CNT); /* Count */ register8_t reserved_0x22; register8_t reserved_0x23; register8_t reserved_0x24; register8_t reserved_0x25; _WORDREGISTER(PER); /* Period */ _WORDREGISTER(CCA); /* Compare or Capture A */ _WORDREGISTER(CCB); /* Compare or Capture B */ register8_t reserved_0x2C; register8_t reserved_0x2D; register8_t reserved_0x2E; register8_t reserved_0x2F; register8_t reserved_0x30; register8_t reserved_0x31; register8_t reserved_0x32; register8_t reserved_0x33; register8_t reserved_0x34; register8_t reserved_0x35; _WORDREGISTER(PERBUF); /* Period Buffer */ _WORDREGISTER(CCABUF); /* Compare Or Capture A Buffer */ _WORDREGISTER(CCBBUF); /* Compare Or Capture B Buffer */ } TC1_t; /* Clock Selection */ typedef enum TC_CLKSEL_enum { TC_CLKSEL_OFF_gc = (0x00<<0), /* Timer Off */ TC_CLKSEL_DIV1_gc = (0x01<<0), /* System Clock */ TC_CLKSEL_DIV2_gc = (0x02<<0), /* System Clock / 2 */ TC_CLKSEL_DIV4_gc = (0x03<<0), /* System Clock / 4 */ TC_CLKSEL_DIV8_gc = (0x04<<0), /* System Clock / 8 */ TC_CLKSEL_DIV64_gc = (0x05<<0), /* System Clock / 64 */ TC_CLKSEL_DIV256_gc = (0x06<<0), /* System Clock / 256 */ TC_CLKSEL_DIV1024_gc = (0x07<<0), /* System Clock / 1024 */ TC_CLKSEL_EVCH0_gc = (0x08<<0), /* Event Channel 0 */ TC_CLKSEL_EVCH1_gc = (0x09<<0), /* Event Channel 1 */ TC_CLKSEL_EVCH2_gc = (0x0A<<0), /* Event Channel 2 */ TC_CLKSEL_EVCH3_gc = (0x0B<<0), /* Event Channel 3 */ } TC_CLKSEL_t; /* Waveform Generation Mode */ typedef enum TC_WGMODE_enum { TC_WGMODE_NORMAL_gc = (0x00<<0), /* Normal Mode */ TC_WGMODE_FRQ_gc = (0x01<<0), /* Frequency Generation Mode */ TC_WGMODE_SINGLESLOPE_gc = (0x03<<0), /* Single Slope */ TC_WGMODE_SS_gc = (0x03<<0), /* Single Slope */ TC_WGMODE_DSTOP_gc = (0x05<<0), /* Dual Slope, Update on TOP */ TC_WGMODE_DS_T_gc = (0x05<<0), /* Dual Slope, Update on TOP */ TC_WGMODE_DSBOTH_gc = (0x06<<0), /* Dual Slope, Update on both TOP and BOTTOM */ TC_WGMODE_DS_TB_gc = (0x06<<0), /* Dual Slope, Update on both TOP and BOTTOM */ TC_WGMODE_DSBOTTOM_gc = (0x07<<0), /* Dual Slope, Update on BOTTOM */ TC_WGMODE_DS_B_gc = (0x07<<0), /* Dual Slope, Update on BOTTOM */ } TC_WGMODE_t; /* Byte Mode */ typedef enum TC_BYTEM_enum { TC_BYTEM_NORMAL_gc = (0x00<<0), /* 16-bit mode */ TC_BYTEM_BYTEMODE_gc = (0x01<<0), /* Timer/Counter operating in byte mode only */ TC_BYTEM_SPLITMODE_gc = (0x02<<0), /* Timer/Counter split into two 8-bit Counters (TC2) */ } TC_BYTEM_t; /* Event Action */ typedef enum TC_EVACT_enum { TC_EVACT_OFF_gc = (0x00<<5), /* No Event Action */ TC_EVACT_CAPT_gc = (0x01<<5), /* Input Capture */ TC_EVACT_UPDOWN_gc = (0x02<<5), /* Externally Controlled Up/Down Count */ TC_EVACT_QDEC_gc = (0x03<<5), /* Quadrature Decode */ TC_EVACT_RESTART_gc = (0x04<<5), /* Restart */ TC_EVACT_FRQ_gc = (0x05<<5), /* Frequency Capture */ TC_EVACT_PW_gc = (0x06<<5), /* Pulse-width Capture */ } TC_EVACT_t; /* Event Selection */ typedef enum TC_EVSEL_enum { TC_EVSEL_OFF_gc = (0x00<<0), /* No Event Source */ TC_EVSEL_CH0_gc = (0x08<<0), /* Event Channel 0 */ TC_EVSEL_CH1_gc = (0x09<<0), /* Event Channel 1 */ TC_EVSEL_CH2_gc = (0x0A<<0), /* Event Channel 2 */ TC_EVSEL_CH3_gc = (0x0B<<0), /* Event Channel 3 */ } TC_EVSEL_t; /* Error Interrupt Level */ typedef enum TC_ERRINTLVL_enum { TC_ERRINTLVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ TC_ERRINTLVL_LO_gc = (0x01<<2), /* Low Level */ TC_ERRINTLVL_MED_gc = (0x02<<2), /* Medium Level */ TC_ERRINTLVL_HI_gc = (0x03<<2), /* High Level */ } TC_ERRINTLVL_t; /* Overflow Interrupt Level */ typedef enum TC_OVFINTLVL_enum { TC_OVFINTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ TC_OVFINTLVL_LO_gc = (0x01<<0), /* Low Level */ TC_OVFINTLVL_MED_gc = (0x02<<0), /* Medium Level */ TC_OVFINTLVL_HI_gc = (0x03<<0), /* High Level */ } TC_OVFINTLVL_t; /* Compare or Capture D Interrupt Level */ typedef enum TC_CCDINTLVL_enum { TC_CCDINTLVL_OFF_gc = (0x00<<6), /* Interrupt Disabled */ TC_CCDINTLVL_LO_gc = (0x01<<6), /* Low Level */ TC_CCDINTLVL_MED_gc = (0x02<<6), /* Medium Level */ TC_CCDINTLVL_HI_gc = (0x03<<6), /* High Level */ } TC_CCDINTLVL_t; /* Compare or Capture C Interrupt Level */ typedef enum TC_CCCINTLVL_enum { TC_CCCINTLVL_OFF_gc = (0x00<<4), /* Interrupt Disabled */ TC_CCCINTLVL_LO_gc = (0x01<<4), /* Low Level */ TC_CCCINTLVL_MED_gc = (0x02<<4), /* Medium Level */ TC_CCCINTLVL_HI_gc = (0x03<<4), /* High Level */ } TC_CCCINTLVL_t; /* Compare or Capture B Interrupt Level */ typedef enum TC_CCBINTLVL_enum { TC_CCBINTLVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ TC_CCBINTLVL_LO_gc = (0x01<<2), /* Low Level */ TC_CCBINTLVL_MED_gc = (0x02<<2), /* Medium Level */ TC_CCBINTLVL_HI_gc = (0x03<<2), /* High Level */ } TC_CCBINTLVL_t; /* Compare or Capture A Interrupt Level */ typedef enum TC_CCAINTLVL_enum { TC_CCAINTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ TC_CCAINTLVL_LO_gc = (0x01<<0), /* Low Level */ TC_CCAINTLVL_MED_gc = (0x02<<0), /* Medium Level */ TC_CCAINTLVL_HI_gc = (0x03<<0), /* High Level */ } TC_CCAINTLVL_t; /* Timer/Counter Command */ typedef enum TC_CMD_enum { TC_CMD_NONE_gc = (0x00<<2), /* No Command */ TC_CMD_UPDATE_gc = (0x01<<2), /* Force Update */ TC_CMD_RESTART_gc = (0x02<<2), /* Force Restart */ TC_CMD_RESET_gc = (0x03<<2), /* Force Hard Reset */ } TC_CMD_t; /* -------------------------------------------------------------------------- TC2 - 16-bit Timer/Counter type 2 -------------------------------------------------------------------------- */ /* 16-bit Timer/Counter type 2 */ typedef struct TC2_struct { register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t CTRLC; /* Control register C */ register8_t reserved_0x03; register8_t CTRLE; /* Control Register E */ register8_t reserved_0x05; register8_t INTCTRLA; /* Interrupt Control Register A */ register8_t INTCTRLB; /* Interrupt Control Register B */ register8_t reserved_0x08; register8_t CTRLF; /* Control Register F */ register8_t reserved_0x0A; register8_t reserved_0x0B; register8_t INTFLAGS; /* Interrupt Flag Register */ register8_t reserved_0x0D; register8_t reserved_0x0E; register8_t reserved_0x0F; register8_t reserved_0x10; register8_t reserved_0x11; register8_t reserved_0x12; register8_t reserved_0x13; register8_t reserved_0x14; register8_t reserved_0x15; register8_t reserved_0x16; register8_t reserved_0x17; register8_t reserved_0x18; register8_t reserved_0x19; register8_t reserved_0x1A; register8_t reserved_0x1B; register8_t reserved_0x1C; register8_t reserved_0x1D; register8_t reserved_0x1E; register8_t reserved_0x1F; register8_t LCNT; /* Low Byte Count */ register8_t HCNT; /* High Byte Count */ register8_t reserved_0x22; register8_t reserved_0x23; register8_t reserved_0x24; register8_t reserved_0x25; register8_t LPER; /* Low Byte Period */ register8_t HPER; /* High Byte Period */ register8_t LCMPA; /* Low Byte Compare A */ register8_t HCMPA; /* High Byte Compare A */ register8_t LCMPB; /* Low Byte Compare B */ register8_t HCMPB; /* High Byte Compare B */ register8_t LCMPC; /* Low Byte Compare C */ register8_t HCMPC; /* High Byte Compare C */ register8_t LCMPD; /* Low Byte Compare D */ register8_t HCMPD; /* High Byte Compare D */ } TC2_t; /* Clock Selection */ typedef enum TC2_CLKSEL_enum { TC2_CLKSEL_OFF_gc = (0x00<<0), /* Timer Off */ TC2_CLKSEL_DIV1_gc = (0x01<<0), /* System Clock */ TC2_CLKSEL_DIV2_gc = (0x02<<0), /* System Clock / 2 */ TC2_CLKSEL_DIV4_gc = (0x03<<0), /* System Clock / 4 */ TC2_CLKSEL_DIV8_gc = (0x04<<0), /* System Clock / 8 */ TC2_CLKSEL_DIV64_gc = (0x05<<0), /* System Clock / 64 */ TC2_CLKSEL_DIV256_gc = (0x06<<0), /* System Clock / 256 */ TC2_CLKSEL_DIV1024_gc = (0x07<<0), /* System Clock / 1024 */ TC2_CLKSEL_EVCH0_gc = (0x08<<0), /* Event Channel 0 */ TC2_CLKSEL_EVCH1_gc = (0x09<<0), /* Event Channel 1 */ TC2_CLKSEL_EVCH2_gc = (0x0A<<0), /* Event Channel 2 */ TC2_CLKSEL_EVCH3_gc = (0x0B<<0), /* Event Channel 3 */ } TC2_CLKSEL_t; /* Byte Mode */ typedef enum TC2_BYTEM_enum { TC2_BYTEM_NORMAL_gc = (0x00<<0), /* 16-bit mode */ TC2_BYTEM_BYTEMODE_gc = (0x01<<0), /* Timer/Counter operating in byte mode only (TC2) */ TC2_BYTEM_SPLITMODE_gc = (0x02<<0), /* Timer/Counter split into two 8-bit Counters */ } TC2_BYTEM_t; /* High Byte Underflow Interrupt Level */ typedef enum TC2_HUNFINTLVL_enum { TC2_HUNFINTLVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ TC2_HUNFINTLVL_LO_gc = (0x01<<2), /* Low Level */ TC2_HUNFINTLVL_MED_gc = (0x02<<2), /* Medium Level */ TC2_HUNFINTLVL_HI_gc = (0x03<<2), /* High Level */ } TC2_HUNFINTLVL_t; /* Low Byte Underflow Interrupt Level */ typedef enum TC2_LUNFINTLVL_enum { TC2_LUNFINTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ TC2_LUNFINTLVL_LO_gc = (0x01<<0), /* Low Level */ TC2_LUNFINTLVL_MED_gc = (0x02<<0), /* Medium Level */ TC2_LUNFINTLVL_HI_gc = (0x03<<0), /* High Level */ } TC2_LUNFINTLVL_t; /* Low Byte Compare D Interrupt Level */ typedef enum TC2_LCMPDINTLVL_enum { TC2_LCMPDINTLVL_OFF_gc = (0x00<<6), /* Interrupt Disabled */ TC2_LCMPDINTLVL_LO_gc = (0x01<<6), /* Low Level */ TC2_LCMPDINTLVL_MED_gc = (0x02<<6), /* Medium Level */ TC2_LCMPDINTLVL_HI_gc = (0x03<<6), /* High Level */ } TC2_LCMPDINTLVL_t; /* Low Byte Compare C Interrupt Level */ typedef enum TC2_LCMPCINTLVL_enum { TC2_LCMPCINTLVL_OFF_gc = (0x00<<4), /* Interrupt Disabled */ TC2_LCMPCINTLVL_LO_gc = (0x01<<4), /* Low Level */ TC2_LCMPCINTLVL_MED_gc = (0x02<<4), /* Medium Level */ TC2_LCMPCINTLVL_HI_gc = (0x03<<4), /* High Level */ } TC2_LCMPCINTLVL_t; /* Low Byte Compare B Interrupt Level */ typedef enum TC2_LCMPBINTLVL_enum { TC2_LCMPBINTLVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ TC2_LCMPBINTLVL_LO_gc = (0x01<<2), /* Low Level */ TC2_LCMPBINTLVL_MED_gc = (0x02<<2), /* Medium Level */ TC2_LCMPBINTLVL_HI_gc = (0x03<<2), /* High Level */ } TC2_LCMPBINTLVL_t; /* Low Byte Compare A Interrupt Level */ typedef enum TC2_LCMPAINTLVL_enum { TC2_LCMPAINTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ TC2_LCMPAINTLVL_LO_gc = (0x01<<0), /* Low Level */ TC2_LCMPAINTLVL_MED_gc = (0x02<<0), /* Medium Level */ TC2_LCMPAINTLVL_HI_gc = (0x03<<0), /* High Level */ } TC2_LCMPAINTLVL_t; /* Timer/Counter Command */ typedef enum TC2_CMD_enum { TC2_CMD_NONE_gc = (0x00<<2), /* No Command */ TC2_CMD_RESTART_gc = (0x02<<2), /* Force Restart */ TC2_CMD_RESET_gc = (0x03<<2), /* Force Hard Reset */ } TC2_CMD_t; /* Timer/Counter Command */ typedef enum TC2_CMDEN_enum { TC2_CMDEN_LOW_gc = (0x01<<0), /* Low Byte Timer/Counter */ TC2_CMDEN_HIGH_gc = (0x02<<0), /* High Byte Timer/Counter */ TC2_CMDEN_BOTH_gc = (0x03<<0), /* Both Low Byte and High Byte Timer/Counters */ } TC2_CMDEN_t; /* -------------------------------------------------------------------------- AWEX - Timer/Counter Advanced Waveform Extension -------------------------------------------------------------------------- */ /* Advanced Waveform Extension */ typedef struct AWEX_struct { register8_t CTRL; /* Control Register */ register8_t reserved_0x01; register8_t FDEMASK; /* Fault Detection Event Mask */ register8_t FDCTRL; /* Fault Detection Control Register */ register8_t STATUS; /* Status Register */ register8_t STATUSSET; /* Status Set Register */ register8_t DTBOTH; /* Dead Time Both Sides */ register8_t DTBOTHBUF; /* Dead Time Both Sides Buffer */ register8_t DTLS; /* Dead Time Low Side */ register8_t DTHS; /* Dead Time High Side */ register8_t DTLSBUF; /* Dead Time Low Side Buffer */ register8_t DTHSBUF; /* Dead Time High Side Buffer */ register8_t OUTOVEN; /* Output Override Enable */ } AWEX_t; /* Fault Detect Action */ typedef enum AWEX_FDACT_enum { AWEX_FDACT_NONE_gc = (0x00<<0), /* No Fault Protection */ AWEX_FDACT_CLEAROE_gc = (0x01<<0), /* Clear Output Enable Bits */ AWEX_FDACT_CLEARDIR_gc = (0x03<<0), /* Clear I/O Port Direction Bits */ } AWEX_FDACT_t; /* -------------------------------------------------------------------------- HIRES - Timer/Counter High-Resolution Extension -------------------------------------------------------------------------- */ /* High-Resolution Extension */ typedef struct HIRES_struct { register8_t CTRLA; /* Control Register */ } HIRES_t; /* High Resolution Enable */ typedef enum HIRES_HREN_enum { HIRES_HREN_NONE_gc = (0x00<<0), /* No Fault Protection */ HIRES_HREN_TC0_gc = (0x01<<0), /* Enable High Resolution on Timer/Counter 0 */ HIRES_HREN_TC1_gc = (0x02<<0), /* Enable High Resolution on Timer/Counter 1 */ HIRES_HREN_BOTH_gc = (0x03<<0), /* Enable High Resolution both Timer/Counters */ } HIRES_HREN_t; /* -------------------------------------------------------------------------- USART - Universal Asynchronous Receiver-Transmitter -------------------------------------------------------------------------- */ /* Universal Synchronous/Asynchronous Receiver/Transmitter */ typedef struct USART_struct { register8_t DATA; /* Data Register */ register8_t STATUS; /* Status Register */ register8_t reserved_0x02; register8_t CTRLA; /* Control Register A */ register8_t CTRLB; /* Control Register B */ register8_t CTRLC; /* Control Register C */ register8_t BAUDCTRLA; /* Baud Rate Control Register A */ register8_t BAUDCTRLB; /* Baud Rate Control Register B */ } USART_t; /* Receive Complete Interrupt level */ typedef enum USART_RXCINTLVL_enum { USART_RXCINTLVL_OFF_gc = (0x00<<4), /* Interrupt Disabled */ USART_RXCINTLVL_LO_gc = (0x01<<4), /* Low Level */ USART_RXCINTLVL_MED_gc = (0x02<<4), /* Medium Level */ USART_RXCINTLVL_HI_gc = (0x03<<4), /* High Level */ } USART_RXCINTLVL_t; /* Transmit Complete Interrupt level */ typedef enum USART_TXCINTLVL_enum { USART_TXCINTLVL_OFF_gc = (0x00<<2), /* Interrupt Disabled */ USART_TXCINTLVL_LO_gc = (0x01<<2), /* Low Level */ USART_TXCINTLVL_MED_gc = (0x02<<2), /* Medium Level */ USART_TXCINTLVL_HI_gc = (0x03<<2), /* High Level */ } USART_TXCINTLVL_t; /* Data Register Empty Interrupt level */ typedef enum USART_DREINTLVL_enum { USART_DREINTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ USART_DREINTLVL_LO_gc = (0x01<<0), /* Low Level */ USART_DREINTLVL_MED_gc = (0x02<<0), /* Medium Level */ USART_DREINTLVL_HI_gc = (0x03<<0), /* High Level */ } USART_DREINTLVL_t; /* Character Size */ typedef enum USART_CHSIZE_enum { USART_CHSIZE_5BIT_gc = (0x00<<0), /* Character size: 5 bit */ USART_CHSIZE_6BIT_gc = (0x01<<0), /* Character size: 6 bit */ USART_CHSIZE_7BIT_gc = (0x02<<0), /* Character size: 7 bit */ USART_CHSIZE_8BIT_gc = (0x03<<0), /* Character size: 8 bit */ USART_CHSIZE_9BIT_gc = (0x07<<0), /* Character size: 9 bit */ } USART_CHSIZE_t; /* Communication Mode */ typedef enum USART_CMODE_enum { USART_CMODE_ASYNCHRONOUS_gc = (0x00<<6), /* Asynchronous Mode */ USART_CMODE_SYNCHRONOUS_gc = (0x01<<6), /* Synchronous Mode */ USART_CMODE_IRDA_gc = (0x02<<6), /* IrDA Mode */ USART_CMODE_MSPI_gc = (0x03<<6), /* Master SPI Mode */ } USART_CMODE_t; /* Parity Mode */ typedef enum USART_PMODE_enum { USART_PMODE_DISABLED_gc = (0x00<<4), /* No Parity */ USART_PMODE_EVEN_gc = (0x02<<4), /* Even Parity */ USART_PMODE_ODD_gc = (0x03<<4), /* Odd Parity */ } USART_PMODE_t; /* -------------------------------------------------------------------------- SPI - Serial Peripheral Interface -------------------------------------------------------------------------- */ /* Serial Peripheral Interface */ typedef struct SPI_struct { register8_t CTRL; /* Control Register */ register8_t INTCTRL; /* Interrupt Control Register */ register8_t STATUS; /* Status Register */ register8_t DATA; /* Data Register */ } SPI_t; /* SPI Mode */ typedef enum SPI_MODE_enum { SPI_MODE_0_gc = (0x00<<2), /* SPI Mode 0 */ SPI_MODE_1_gc = (0x01<<2), /* SPI Mode 1 */ SPI_MODE_2_gc = (0x02<<2), /* SPI Mode 2 */ SPI_MODE_3_gc = (0x03<<2), /* SPI Mode 3 */ } SPI_MODE_t; /* Prescaler setting */ typedef enum SPI_PRESCALER_enum { SPI_PRESCALER_DIV4_gc = (0x00<<0), /* System Clock / 4 */ SPI_PRESCALER_DIV16_gc = (0x01<<0), /* System Clock / 16 */ SPI_PRESCALER_DIV64_gc = (0x02<<0), /* System Clock / 64 */ SPI_PRESCALER_DIV128_gc = (0x03<<0), /* System Clock / 128 */ } SPI_PRESCALER_t; /* Interrupt level */ typedef enum SPI_INTLVL_enum { SPI_INTLVL_OFF_gc = (0x00<<0), /* Interrupt Disabled */ SPI_INTLVL_LO_gc = (0x01<<0), /* Low Level */ SPI_INTLVL_MED_gc = (0x02<<0), /* Medium Level */ SPI_INTLVL_HI_gc = (0x03<<0), /* High Level */ } SPI_INTLVL_t; /* -------------------------------------------------------------------------- IRCOM - IR Communication Module -------------------------------------------------------------------------- */ /* IR Communication Module */ typedef struct IRCOM_struct { register8_t CTRL; /* Control Register */ register8_t TXPLCTRL; /* IrDA Transmitter Pulse Length Control Register */ register8_t RXPLCTRL; /* IrDA Receiver Pulse Length Control Register */ } IRCOM_t; /* Event channel selection */ typedef enum IRDA_EVSEL_enum { IRDA_EVSEL_OFF_gc = (0x00<<0), /* No Event Source */ IRDA_EVSEL_0_gc = (0x08<<0), /* Event Channel 0 */ IRDA_EVSEL_1_gc = (0x09<<0), /* Event Channel 1 */ IRDA_EVSEL_2_gc = (0x0A<<0), /* Event Channel 2 */ IRDA_EVSEL_3_gc = (0x0B<<0), /* Event Channel 3 */ } IRDA_EVSEL_t; /* -------------------------------------------------------------------------- FUSE - Fuses and Lockbits -------------------------------------------------------------------------- */ /* Fuses */ typedef struct NVM_FUSES_struct { register8_t reserved_0x00; register8_t FUSEBYTE1; /* Watchdog Configuration */ register8_t FUSEBYTE2; /* Reset Configuration */ register8_t reserved_0x03; register8_t FUSEBYTE4; /* Start-up Configuration */ register8_t FUSEBYTE5; /* EESAVE and BOD Level */ } NVM_FUSES_t; /* Boot Loader Section Reset Vector */ typedef enum BOOTRST_enum { BOOTRST_BOOTLDR_gc = (0x00<<6), /* Boot Loader Reset */ BOOTRST_APPLICATION_gc = (0x01<<6), /* Application Reset */ } BOOTRST_t; /* Timer Oscillator pin location */ typedef enum TOSCSEL_enum { TOSCSEL_ALTERNATE_gc = (0x00<<5), /* TOSC1 / TOSC2 on separate pins */ TOSCSEL_XTAL_gc = (0x01<<5), /* TOSC1 / TOSC2 shared with XTAL1 / XTAL2 */ } TOSCSEL_t; /* BOD operation */ typedef enum BOD_enum { BOD_SAMPLED_gc = (0x01<<0), /* BOD enabled in sampled mode */ BOD_CONTINUOUS_gc = (0x02<<0), /* BOD enabled continuously */ BOD_DISABLED_gc = (0x03<<0), /* BOD Disabled */ } BOD_t; /* BOD operation */ typedef enum BODACT_enum { BODACT_SAMPLED_gc = (0x01<<4), /* BOD enabled in sampled mode */ BODACT_CONTINUOUS_gc = (0x02<<4), /* BOD enabled continuously */ BODACT_DISABLED_gc = (0x03<<4), /* BOD Disabled */ } BODACT_t; /* Watchdog (Window) Timeout Period */ typedef enum WD_enum { WD_8CLK_gc = (0x00<<4), /* 8 cycles (8ms @ 3.3V) */ WD_16CLK_gc = (0x01<<4), /* 16 cycles (16ms @ 3.3V) */ WD_32CLK_gc = (0x02<<4), /* 32 cycles (32ms @ 3.3V) */ WD_64CLK_gc = (0x03<<4), /* 64 cycles (64ms @ 3.3V) */ WD_128CLK_gc = (0x04<<4), /* 128 cycles (0.125s @ 3.3V) */ WD_256CLK_gc = (0x05<<4), /* 256 cycles (0.25s @ 3.3V) */ WD_512CLK_gc = (0x06<<4), /* 512 cycles (0.5s @ 3.3V) */ WD_1KCLK_gc = (0x07<<4), /* 1K cycles (1s @ 3.3V) */ WD_2KCLK_gc = (0x08<<4), /* 2K cycles (2s @ 3.3V) */ WD_4KCLK_gc = (0x09<<4), /* 4K cycles (4s @ 3.3V) */ WD_8KCLK_gc = (0x0A<<4), /* 8K cycles (8s @ 3.3V) */ } WD_t; /* Watchdog (Window) Timeout Period */ typedef enum WDP_enum { WDP_8CLK_gc = (0x00<<0), /* 8 cycles (8ms @ 3.3V) */ WDP_16CLK_gc = (0x01<<0), /* 16 cycles (16ms @ 3.3V) */ WDP_32CLK_gc = (0x02<<0), /* 32 cycles (32ms @ 3.3V) */ WDP_64CLK_gc = (0x03<<0), /* 64 cycles (64ms @ 3.3V) */ WDP_128CLK_gc = (0x04<<0), /* 128 cycles (0.125s @ 3.3V) */ WDP_256CLK_gc = (0x05<<0), /* 256 cycles (0.25s @ 3.3V) */ WDP_512CLK_gc = (0x06<<0), /* 512 cycles (0.5s @ 3.3V) */ WDP_1KCLK_gc = (0x07<<0), /* 1K cycles (1s @ 3.3V) */ WDP_2KCLK_gc = (0x08<<0), /* 2K cycles (2s @ 3.3V) */ WDP_4KCLK_gc = (0x09<<0), /* 4K cycles (4s @ 3.3V) */ WDP_8KCLK_gc = (0x0A<<0), /* 8K cycles (8s @ 3.3V) */ } WDP_t; /* Start-up Time */ typedef enum SUT_enum { SUT_0MS_gc = (0x03<<2), /* 0 ms */ SUT_4MS_gc = (0x01<<2), /* 4 ms */ SUT_64MS_gc = (0x00<<2), /* 64 ms */ } SUT_t; /* Brownout Detection Voltage Level */ typedef enum BODLVL_enum { BODLVL_1V6_gc = (0x07<<0), /* 1.6 V */ BODLVL_1V8_gc = (0x06<<0), /* 1.8 V */ BODLVL_2V0_gc = (0x05<<0), /* 2.0 V */ BODLVL_2V2_gc = (0x04<<0), /* 2.2 V */ BODLVL_2V4_gc = (0x03<<0), /* 2.4 V */ BODLVL_2V6_gc = (0x02<<0), /* 2.6 V */ BODLVL_2V8_gc = (0x01<<0), /* 2.8 V */ BODLVL_3V0_gc = (0x00<<0), /* 3.0 V */ } BODLVL_t; /* -------------------------------------------------------------------------- LOCKBIT - Fuses and Lockbits -------------------------------------------------------------------------- */ /* Lock Bits */ typedef struct NVM_LOCKBITS_struct { register8_t LOCK_BITS; /* Lock Bits (Changed from LOCKBITS to avoid avr-libc collision) */ } NVM_LOCKBITS_t; /* Boot lock bits - boot setcion */ typedef enum FUSE_BLBB_enum { FUSE_BLBB_RWLOCK_gc = (0x00<<6), /* Read and write not allowed */ FUSE_BLBB_RLOCK_gc = (0x01<<6), /* Read not allowed */ FUSE_BLBB_WLOCK_gc = (0x02<<6), /* Write not allowed */ FUSE_BLBB_NOLOCK_gc = (0x03<<6), /* No locks */ } FUSE_BLBB_t; /* Boot lock bits - application section */ typedef enum FUSE_BLBA_enum { FUSE_BLBA_RWLOCK_gc = (0x00<<4), /* Read and write not allowed */ FUSE_BLBA_RLOCK_gc = (0x01<<4), /* Read not allowed */ FUSE_BLBA_WLOCK_gc = (0x02<<4), /* Write not allowed */ FUSE_BLBA_NOLOCK_gc = (0x03<<4), /* No locks */ } FUSE_BLBA_t; /* Boot lock bits - application table section */ typedef enum FUSE_BLBAT_enum { FUSE_BLBAT_RWLOCK_gc = (0x00<<2), /* Read and write not allowed */ FUSE_BLBAT_RLOCK_gc = (0x01<<2), /* Read not allowed */ FUSE_BLBAT_WLOCK_gc = (0x02<<2), /* Write not allowed */ FUSE_BLBAT_NOLOCK_gc = (0x03<<2), /* No locks */ } FUSE_BLBAT_t; /* Lock bits */ typedef enum FUSE_LB_enum { FUSE_LB_RWLOCK_gc = (0x00<<0), /* Read and write not allowed */ FUSE_LB_WLOCK_gc = (0x02<<0), /* Write not allowed */ FUSE_LB_NOLOCK_gc = (0x03<<0), /* No locks */ } FUSE_LB_t; /* -------------------------------------------------------------------------- SIGROW - Signature Row -------------------------------------------------------------------------- */ /* Production Signatures */ typedef struct NVM_PROD_SIGNATURES_struct { register8_t RCOSC2M; /* RCOSC 2 MHz Calibration Value B */ register8_t RCOSC2MA; /* RCOSC 2 MHz Calibration Value A */ register8_t RCOSC32K; /* RCOSC 32.768 kHz Calibration Value */ register8_t RCOSC32M; /* RCOSC 32 MHz Calibration Value B */ register8_t RCOSC32MA; /* RCOSC 32 MHz Calibration Value A */ register8_t reserved_0x05; register8_t reserved_0x06; register8_t reserved_0x07; register8_t LOTNUM0; /* Lot Number Byte 0, ASCII */ register8_t LOTNUM1; /* Lot Number Byte 1, ASCII */ register8_t LOTNUM2; /* Lot Number Byte 2, ASCII */ register8_t LOTNUM3; /* Lot Number Byte 3, ASCII */ register8_t LOTNUM4; /* Lot Number Byte 4, ASCII */ register8_t LOTNUM5; /* Lot Number Byte 5, ASCII */ register8_t reserved_0x0E; register8_t reserved_0x0F; register8_t WAFNUM; /* Wafer Number */ register8_t reserved_0x11; register8_t COORDX0; /* Wafer Coordinate X Byte 0 */ register8_t COORDX1; /* Wafer Coordinate X Byte 1 */ register8_t COORDY0; /* Wafer Coordinate Y Byte 0 */ register8_t COORDY1; /* Wafer Coordinate Y Byte 1 */ register8_t reserved_0x16; register8_t reserved_0x17; register8_t reserved_0x18; register8_t reserved_0x19; register8_t USBCAL0; /* USB Calibration Byte 0 */ register8_t USBCAL1; /* USB Calibration Byte 1 */ register8_t USBRCOSC; /* USB RCOSC Calibration Value B */ register8_t USBRCOSCA; /* USB RCOSC Calibration Value A */ register8_t reserved_0x1E; register8_t reserved_0x1F; register8_t ADCACAL0; /* ADCA Calibration Byte 0 */ register8_t ADCACAL1; /* ADCA Calibration Byte 1 */ register8_t reserved_0x22; register8_t reserved_0x23; register8_t reserved_0x24; register8_t reserved_0x25; register8_t reserved_0x26; register8_t reserved_0x27; register8_t reserved_0x28; register8_t reserved_0x29; register8_t reserved_0x2A; register8_t reserved_0x2B; register8_t reserved_0x2C; register8_t reserved_0x2D; register8_t TEMPSENSE0; /* Temperature Sensor Calibration Byte 0 */ register8_t TEMPSENSE1; /* Temperature Sensor Calibration Byte 1 */ register8_t reserved_0x30; register8_t reserved_0x31; register8_t reserved_0x32; register8_t reserved_0x33; register8_t reserved_0x34; register8_t reserved_0x35; register8_t reserved_0x36; register8_t reserved_0x37; register8_t reserved_0x38; register8_t reserved_0x39; register8_t reserved_0x3A; register8_t reserved_0x3B; register8_t reserved_0x3C; register8_t reserved_0x3D; register8_t reserved_0x3E; register8_t reserved_0x3F; } NVM_PROD_SIGNATURES_t; /* ========================================================================== IO Module Instances. Mapped to memory. ========================================================================== */ #define VPORT0 (*(VPORT_t *) 0x0010) /* Virtual Port */ #define VPORT1 (*(VPORT_t *) 0x0014) /* Virtual Port */ #define VPORT2 (*(VPORT_t *) 0x0018) /* Virtual Port */ #define VPORT3 (*(VPORT_t *) 0x001C) /* Virtual Port */ #define OCD (*(OCD_t *) 0x002E) /* On-Chip Debug System */ #define CLK (*(CLK_t *) 0x0040) /* Clock System */ #define SLEEP (*(SLEEP_t *) 0x0048) /* Sleep Controller */ #define OSC (*(OSC_t *) 0x0050) /* Oscillator */ #define DFLLRC32M (*(DFLL_t *) 0x0060) /* DFLL */ #define DFLLRC2M (*(DFLL_t *) 0x0068) /* DFLL */ #define PR (*(PR_t *) 0x0070) /* Power Reduction */ #define RST (*(RST_t *) 0x0078) /* Reset */ #define WDT (*(WDT_t *) 0x0080) /* Watch-Dog Timer */ #define MCU (*(MCU_t *) 0x0090) /* MCU Control */ #define PMIC (*(PMIC_t *) 0x00A0) /* Programmable Multi-level Interrupt Controller */ #define PORTCFG (*(PORTCFG_t *) 0x00B0) /* I/O port Configuration */ #define CRC (*(CRC_t *) 0x00D0) /* Cyclic Redundancy Checker */ #define EVSYS (*(EVSYS_t *) 0x0180) /* Event System */ #define NVM (*(NVM_t *) 0x01C0) /* Non-volatile Memory Controller */ #define ADCA (*(ADC_t *) 0x0200) /* Analog-to-Digital Converter */ #define ACA (*(AC_t *) 0x0380) /* Analog Comparator */ #define RTC (*(RTC_t *) 0x0400) /* Real-Time Counter */ #define TWIC (*(TWI_t *) 0x0480) /* Two-Wire Interface */ #define TWIE (*(TWI_t *) 0x04A0) /* Two-Wire Interface */ #define USB (*(USB_t *) 0x04C0) /* Universal Serial Bus */ #define PORTA (*(PORT_t *) 0x0600) /* I/O Ports */ #define PORTB (*(PORT_t *) 0x0620) /* I/O Ports */ #define PORTC (*(PORT_t *) 0x0640) /* I/O Ports */ #define PORTD (*(PORT_t *) 0x0660) /* I/O Ports */ #define PORTE (*(PORT_t *) 0x0680) /* I/O Ports */ #define PORTF (*(PORT_t *) 0x06A0) /* I/O Ports */ #define PORTR (*(PORT_t *) 0x07E0) /* I/O Ports */ #define TCC0 (*(TC0_t *) 0x0800) /* 16-bit Timer/Counter 0 */ #define TCC2 (*(TC2_t *) 0x0800) /* 16-bit Timer/Counter type 2 */ #define TCC1 (*(TC1_t *) 0x0840) /* 16-bit Timer/Counter 1 */ #define AWEXC (*(AWEX_t *) 0x0880) /* Advanced Waveform Extension */ #define HIRESC (*(HIRES_t *) 0x0890) /* High-Resolution Extension */ #define USARTC0 (*(USART_t *) 0x08A0) /* Universal Synchronous/Asynchronous Receiver/Transmitter */ #define SPIC (*(SPI_t *) 0x08C0) /* Serial Peripheral Interface */ #define IRCOM (*(IRCOM_t *) 0x08F8) /* IR Communication Module */ #define TCD0 (*(TC0_t *) 0x0900) /* 16-bit Timer/Counter 0 */ #define TCD2 (*(TC2_t *) 0x0900) /* 16-bit Timer/Counter type 2 */ #define USARTD0 (*(USART_t *) 0x09A0) /* Universal Synchronous/Asynchronous Receiver/Transmitter */ #define SPID (*(SPI_t *) 0x09C0) /* Serial Peripheral Interface */ #define TCE0 (*(TC0_t *) 0x0A00) /* 16-bit Timer/Counter 0 */ #define TCE2 (*(TC2_t *) 0x0A00) /* 16-bit Timer/Counter type 2 */ #define USARTE0 (*(USART_t *) 0x0AA0) /* Universal Synchronous/Asynchronous Receiver/Transmitter */ #define TCF0 (*(TC0_t *) 0x0B00) /* 16-bit Timer/Counter 0 */ #define TCF2 (*(TC2_t *) 0x0B00) /* 16-bit Timer/Counter type 2 */ #endif /* !defined (__ASSEMBLER__) */ /* ========== Flattened fully qualified IO register names ========== */ /* GPIO - General Purpose IO Registers */ #define GPIO_GPIOR0 _SFR_MEM8(0x0000) #define GPIO_GPIOR1 _SFR_MEM8(0x0001) #define GPIO_GPIOR2 _SFR_MEM8(0x0002) #define GPIO_GPIOR3 _SFR_MEM8(0x0003) /* Deprecated */ #define GPIO_GPIO0 _SFR_MEM8(0x0000) #define GPIO_GPIO1 _SFR_MEM8(0x0001) #define GPIO_GPIO2 _SFR_MEM8(0x0002) #define GPIO_GPIO3 _SFR_MEM8(0x0003) /* NVM_FUSES - Fuses */ #define FUSE_FUSEBYTE1 _SFR_MEM8(0x0001) #define FUSE_FUSEBYTE2 _SFR_MEM8(0x0002) #define FUSE_FUSEBYTE4 _SFR_MEM8(0x0004) #define FUSE_FUSEBYTE5 _SFR_MEM8(0x0005) /* NVM_LOCKBITS - Lock Bits */ #define LOCKBIT_LOCKBITS _SFR_MEM8(0x0000) /* NVM_PROD_SIGNATURES - Production Signatures */ #define PRODSIGNATURES_RCOSC2M _SFR_MEM8(0x0000) #define PRODSIGNATURES_RCOSC2MA _SFR_MEM8(0x0001) #define PRODSIGNATURES_RCOSC32K _SFR_MEM8(0x0002) #define PRODSIGNATURES_RCOSC32M _SFR_MEM8(0x0003) #define PRODSIGNATURES_RCOSC32MA _SFR_MEM8(0x0004) #define PRODSIGNATURES_LOTNUM0 _SFR_MEM8(0x0008) #define PRODSIGNATURES_LOTNUM1 _SFR_MEM8(0x0009) #define PRODSIGNATURES_LOTNUM2 _SFR_MEM8(0x000A) #define PRODSIGNATURES_LOTNUM3 _SFR_MEM8(0x000B) #define PRODSIGNATURES_LOTNUM4 _SFR_MEM8(0x000C) #define PRODSIGNATURES_LOTNUM5 _SFR_MEM8(0x000D) #define PRODSIGNATURES_WAFNUM _SFR_MEM8(0x0010) #define PRODSIGNATURES_COORDX0 _SFR_MEM8(0x0012) #define PRODSIGNATURES_COORDX1 _SFR_MEM8(0x0013) #define PRODSIGNATURES_COORDY0 _SFR_MEM8(0x0014) #define PRODSIGNATURES_COORDY1 _SFR_MEM8(0x0015) #define PRODSIGNATURES_USBCAL0 _SFR_MEM8(0x001A) #define PRODSIGNATURES_USBCAL1 _SFR_MEM8(0x001B) #define PRODSIGNATURES_USBRCOSC _SFR_MEM8(0x001C) #define PRODSIGNATURES_USBRCOSCA _SFR_MEM8(0x001D) #define PRODSIGNATURES_ADCACAL0 _SFR_MEM8(0x0020) #define PRODSIGNATURES_ADCACAL1 _SFR_MEM8(0x0021) #define PRODSIGNATURES_TEMPSENSE0 _SFR_MEM8(0x002E) #define PRODSIGNATURES_TEMPSENSE1 _SFR_MEM8(0x002F) /* VPORT - Virtual Port */ #define VPORT0_DIR _SFR_MEM8(0x0010) #define VPORT0_OUT _SFR_MEM8(0x0011) #define VPORT0_IN _SFR_MEM8(0x0012) #define VPORT0_INTFLAGS _SFR_MEM8(0x0013) /* VPORT - Virtual Port */ #define VPORT1_DIR _SFR_MEM8(0x0014) #define VPORT1_OUT _SFR_MEM8(0x0015) #define VPORT1_IN _SFR_MEM8(0x0016) #define VPORT1_INTFLAGS _SFR_MEM8(0x0017) /* VPORT - Virtual Port */ #define VPORT2_DIR _SFR_MEM8(0x0018) #define VPORT2_OUT _SFR_MEM8(0x0019) #define VPORT2_IN _SFR_MEM8(0x001A) #define VPORT2_INTFLAGS _SFR_MEM8(0x001B) /* VPORT - Virtual Port */ #define VPORT3_DIR _SFR_MEM8(0x001C) #define VPORT3_OUT _SFR_MEM8(0x001D) #define VPORT3_IN _SFR_MEM8(0x001E) #define VPORT3_INTFLAGS _SFR_MEM8(0x001F) /* OCD - On-Chip Debug System */ #define OCD_OCDR0 _SFR_MEM8(0x002E) #define OCD_OCDR1 _SFR_MEM8(0x002F) /* CPU - CPU registers */ #define CPU_CCP _SFR_MEM8(0x0034) #define CPU_RAMPD _SFR_MEM8(0x0038) #define CPU_RAMPX _SFR_MEM8(0x0039) #define CPU_RAMPY _SFR_MEM8(0x003A) #define CPU_RAMPZ _SFR_MEM8(0x003B) #define CPU_EIND _SFR_MEM8(0x003C) #define CPU_SPL _SFR_MEM8(0x003D) #define CPU_SPH _SFR_MEM8(0x003E) #define CPU_SREG _SFR_MEM8(0x003F) /* CLK - Clock System */ #define CLK_CTRL _SFR_MEM8(0x0040) #define CLK_PSCTRL _SFR_MEM8(0x0041) #define CLK_LOCK _SFR_MEM8(0x0042) #define CLK_RTCCTRL _SFR_MEM8(0x0043) #define CLK_USBCTRL _SFR_MEM8(0x0044) /* SLEEP - Sleep Controller */ #define SLEEP_CTRL _SFR_MEM8(0x0048) /* OSC - Oscillator */ #define OSC_CTRL _SFR_MEM8(0x0050) #define OSC_STATUS _SFR_MEM8(0x0051) #define OSC_XOSCCTRL _SFR_MEM8(0x0052) #define OSC_XOSCFAIL _SFR_MEM8(0x0053) #define OSC_RC32KCAL _SFR_MEM8(0x0054) #define OSC_PLLCTRL _SFR_MEM8(0x0055) #define OSC_DFLLCTRL _SFR_MEM8(0x0056) /* DFLL - DFLL */ #define DFLLRC32M_CTRL _SFR_MEM8(0x0060) #define DFLLRC32M_CALA _SFR_MEM8(0x0062) #define DFLLRC32M_CALB _SFR_MEM8(0x0063) #define DFLLRC32M_COMP0 _SFR_MEM8(0x0064) #define DFLLRC32M_COMP1 _SFR_MEM8(0x0065) #define DFLLRC32M_COMP2 _SFR_MEM8(0x0066) /* DFLL - DFLL */ #define DFLLRC2M_CTRL _SFR_MEM8(0x0068) #define DFLLRC2M_CALA _SFR_MEM8(0x006A) #define DFLLRC2M_CALB _SFR_MEM8(0x006B) #define DFLLRC2M_COMP0 _SFR_MEM8(0x006C) #define DFLLRC2M_COMP1 _SFR_MEM8(0x006D) #define DFLLRC2M_COMP2 _SFR_MEM8(0x006E) /* PR - Power Reduction */ #define PR_PRGEN _SFR_MEM8(0x0070) #define PR_PRPA _SFR_MEM8(0x0071) #define PR_PRPC _SFR_MEM8(0x0073) #define PR_PRPD _SFR_MEM8(0x0074) #define PR_PRPE _SFR_MEM8(0x0075) #define PR_PRPF _SFR_MEM8(0x0076) /* RST - Reset */ #define RST_STATUS _SFR_MEM8(0x0078) #define RST_CTRL _SFR_MEM8(0x0079) /* WDT - Watch-Dog Timer */ #define WDT_CTRL _SFR_MEM8(0x0080) #define WDT_WINCTRL _SFR_MEM8(0x0081) #define WDT_STATUS _SFR_MEM8(0x0082) /* MCU - MCU Control */ #define MCU_DEVID0 _SFR_MEM8(0x0090) #define MCU_DEVID1 _SFR_MEM8(0x0091) #define MCU_DEVID2 _SFR_MEM8(0x0092) #define MCU_REVID _SFR_MEM8(0x0093) #define MCU_ANAINIT _SFR_MEM8(0x0097) #define MCU_EVSYSLOCK _SFR_MEM8(0x0098) #define MCU_AWEXLOCK _SFR_MEM8(0x0099) /* PMIC - Programmable Multi-level Interrupt Controller */ #define PMIC_STATUS _SFR_MEM8(0x00A0) #define PMIC_INTPRI _SFR_MEM8(0x00A1) #define PMIC_CTRL _SFR_MEM8(0x00A2) /* PORTCFG - I/O port Configuration */ #define PORTCFG_MPCMASK _SFR_MEM8(0x00B0) #define PORTCFG_VPCTRLA _SFR_MEM8(0x00B2) #define PORTCFG_VPCTRLB _SFR_MEM8(0x00B3) #define PORTCFG_CLKEVOUT _SFR_MEM8(0x00B4) #define PORTCFG_EVOUTSEL _SFR_MEM8(0x00B6) /* CRC - Cyclic Redundancy Checker */ #define CRC_CTRL _SFR_MEM8(0x00D0) #define CRC_STATUS _SFR_MEM8(0x00D1) #define CRC_DATAIN _SFR_MEM8(0x00D3) #define CRC_CHECKSUM0 _SFR_MEM8(0x00D4) #define CRC_CHECKSUM1 _SFR_MEM8(0x00D5) #define CRC_CHECKSUM2 _SFR_MEM8(0x00D6) #define CRC_CHECKSUM3 _SFR_MEM8(0x00D7) /* EVSYS - Event System */ #define EVSYS_CH0MUX _SFR_MEM8(0x0180) #define EVSYS_CH1MUX _SFR_MEM8(0x0181) #define EVSYS_CH2MUX _SFR_MEM8(0x0182) #define EVSYS_CH3MUX _SFR_MEM8(0x0183) #define EVSYS_CH0CTRL _SFR_MEM8(0x0188) #define EVSYS_CH1CTRL _SFR_MEM8(0x0189) #define EVSYS_CH2CTRL _SFR_MEM8(0x018A) #define EVSYS_CH3CTRL _SFR_MEM8(0x018B) #define EVSYS_STROBE _SFR_MEM8(0x0190) #define EVSYS_DATA _SFR_MEM8(0x0191) /* NVM - Non-volatile Memory Controller */ #define NVM_ADDR0 _SFR_MEM8(0x01C0) #define NVM_ADDR1 _SFR_MEM8(0x01C1) #define NVM_ADDR2 _SFR_MEM8(0x01C2) #define NVM_DATA0 _SFR_MEM8(0x01C4) #define NVM_DATA1 _SFR_MEM8(0x01C5) #define NVM_DATA2 _SFR_MEM8(0x01C6) #define NVM_CMD _SFR_MEM8(0x01CA) #define NVM_CTRLA _SFR_MEM8(0x01CB) #define NVM_CTRLB _SFR_MEM8(0x01CC) #define NVM_INTCTRL _SFR_MEM8(0x01CD) #define NVM_STATUS _SFR_MEM8(0x01CF) #define NVM_LOCKBITS _SFR_MEM8(0x01D0) /* ADC - Analog-to-Digital Converter */ #define ADCA_CTRLA _SFR_MEM8(0x0200) #define ADCA_CTRLB _SFR_MEM8(0x0201) #define ADCA_REFCTRL _SFR_MEM8(0x0202) #define ADCA_EVCTRL _SFR_MEM8(0x0203) #define ADCA_PRESCALER _SFR_MEM8(0x0204) #define ADCA_INTFLAGS _SFR_MEM8(0x0206) #define ADCA_TEMP _SFR_MEM8(0x0207) #define ADCA_CAL _SFR_MEM16(0x020C) #define ADCA_CH0RES _SFR_MEM16(0x0210) #define ADCA_CMP _SFR_MEM16(0x0218) #define ADCA_CH0_CTRL _SFR_MEM8(0x0220) #define ADCA_CH0_MUXCTRL _SFR_MEM8(0x0221) #define ADCA_CH0_INTCTRL _SFR_MEM8(0x0222) #define ADCA_CH0_INTFLAGS _SFR_MEM8(0x0223) #define ADCA_CH0_RES _SFR_MEM16(0x0224) #define ADCA_CH0_SCAN _SFR_MEM8(0x0226) /* AC - Analog Comparator */ #define ACA_AC0CTRL _SFR_MEM8(0x0380) #define ACA_AC1CTRL _SFR_MEM8(0x0381) #define ACA_AC0MUXCTRL _SFR_MEM8(0x0382) #define ACA_AC1MUXCTRL _SFR_MEM8(0x0383) #define ACA_CTRLA _SFR_MEM8(0x0384) #define ACA_CTRLB _SFR_MEM8(0x0385) #define ACA_WINCTRL _SFR_MEM8(0x0386) #define ACA_STATUS _SFR_MEM8(0x0387) /* RTC - Real-Time Counter */ #define RTC_CTRL _SFR_MEM8(0x0400) #define RTC_STATUS _SFR_MEM8(0x0401) #define RTC_INTCTRL _SFR_MEM8(0x0402) #define RTC_INTFLAGS _SFR_MEM8(0x0403) #define RTC_TEMP _SFR_MEM8(0x0404) #define RTC_CNT _SFR_MEM16(0x0408) #define RTC_PER _SFR_MEM16(0x040A) #define RTC_COMP _SFR_MEM16(0x040C) /* TWI - Two-Wire Interface */ #define TWIC_CTRL _SFR_MEM8(0x0480) #define TWIC_MASTER_CTRLA _SFR_MEM8(0x0481) #define TWIC_MASTER_CTRLB _SFR_MEM8(0x0482) #define TWIC_MASTER_CTRLC _SFR_MEM8(0x0483) #define TWIC_MASTER_STATUS _SFR_MEM8(0x0484) #define TWIC_MASTER_BAUD _SFR_MEM8(0x0485) #define TWIC_MASTER_ADDR _SFR_MEM8(0x0486) #define TWIC_MASTER_DATA _SFR_MEM8(0x0487) #define TWIC_SLAVE_CTRLA _SFR_MEM8(0x0488) #define TWIC_SLAVE_CTRLB _SFR_MEM8(0x0489) #define TWIC_SLAVE_STATUS _SFR_MEM8(0x048A) #define TWIC_SLAVE_ADDR _SFR_MEM8(0x048B) #define TWIC_SLAVE_DATA _SFR_MEM8(0x048C) #define TWIC_SLAVE_ADDRMASK _SFR_MEM8(0x048D) /* TWI - Two-Wire Interface */ #define TWIE_CTRL _SFR_MEM8(0x04A0) #define TWIE_MASTER_CTRLA _SFR_MEM8(0x04A1) #define TWIE_MASTER_CTRLB _SFR_MEM8(0x04A2) #define TWIE_MASTER_CTRLC _SFR_MEM8(0x04A3) #define TWIE_MASTER_STATUS _SFR_MEM8(0x04A4) #define TWIE_MASTER_BAUD _SFR_MEM8(0x04A5) #define TWIE_MASTER_ADDR _SFR_MEM8(0x04A6) #define TWIE_MASTER_DATA _SFR_MEM8(0x04A7) #define TWIE_SLAVE_CTRLA _SFR_MEM8(0x04A8) #define TWIE_SLAVE_CTRLB _SFR_MEM8(0x04A9) #define TWIE_SLAVE_STATUS _SFR_MEM8(0x04AA) #define TWIE_SLAVE_ADDR _SFR_MEM8(0x04AB) #define TWIE_SLAVE_DATA _SFR_MEM8(0x04AC) #define TWIE_SLAVE_ADDRMASK _SFR_MEM8(0x04AD) /* USB - Universal Serial Bus */ #define USB_CTRLA _SFR_MEM8(0x04C0) #define USB_CTRLB _SFR_MEM8(0x04C1) #define USB_STATUS _SFR_MEM8(0x04C2) #define USB_ADDR _SFR_MEM8(0x04C3) #define USB_FIFOWP _SFR_MEM8(0x04C4) #define USB_FIFORP _SFR_MEM8(0x04C5) #define USB_EPPTR _SFR_MEM16(0x04C6) #define USB_INTCTRLA _SFR_MEM8(0x04C8) #define USB_INTCTRLB _SFR_MEM8(0x04C9) #define USB_INTFLAGSACLR _SFR_MEM8(0x04CA) #define USB_INTFLAGSASET _SFR_MEM8(0x04CB) #define USB_INTFLAGSBCLR _SFR_MEM8(0x04CC) #define USB_INTFLAGSBSET _SFR_MEM8(0x04CD) #define USB_CAL0 _SFR_MEM8(0x04FA) #define USB_CAL1 _SFR_MEM8(0x04FB) /* PORT - I/O Ports */ #define PORTA_DIR _SFR_MEM8(0x0600) #define PORTA_DIRSET _SFR_MEM8(0x0601) #define PORTA_DIRCLR _SFR_MEM8(0x0602) #define PORTA_DIRTGL _SFR_MEM8(0x0603) #define PORTA_OUT _SFR_MEM8(0x0604) #define PORTA_OUTSET _SFR_MEM8(0x0605) #define PORTA_OUTCLR _SFR_MEM8(0x0606) #define PORTA_OUTTGL _SFR_MEM8(0x0607) #define PORTA_IN _SFR_MEM8(0x0608) #define PORTA_INTCTRL _SFR_MEM8(0x0609) #define PORTA_INT0MASK _SFR_MEM8(0x060A) #define PORTA_INT1MASK _SFR_MEM8(0x060B) #define PORTA_INTFLAGS _SFR_MEM8(0x060C) #define PORTA_REMAP _SFR_MEM8(0x060E) #define PORTA_PIN0CTRL _SFR_MEM8(0x0610) #define PORTA_PIN1CTRL _SFR_MEM8(0x0611) #define PORTA_PIN2CTRL _SFR_MEM8(0x0612) #define PORTA_PIN3CTRL _SFR_MEM8(0x0613) #define PORTA_PIN4CTRL _SFR_MEM8(0x0614) #define PORTA_PIN5CTRL _SFR_MEM8(0x0615) #define PORTA_PIN6CTRL _SFR_MEM8(0x0616) #define PORTA_PIN7CTRL _SFR_MEM8(0x0617) /* PORT - I/O Ports */ #define PORTB_DIR _SFR_MEM8(0x0620) #define PORTB_DIRSET _SFR_MEM8(0x0621) #define PORTB_DIRCLR _SFR_MEM8(0x0622) #define PORTB_DIRTGL _SFR_MEM8(0x0623) #define PORTB_OUT _SFR_MEM8(0x0624) #define PORTB_OUTSET _SFR_MEM8(0x0625) #define PORTB_OUTCLR _SFR_MEM8(0x0626) #define PORTB_OUTTGL _SFR_MEM8(0x0627) #define PORTB_IN _SFR_MEM8(0x0628) #define PORTB_INTCTRL _SFR_MEM8(0x0629) #define PORTB_INT0MASK _SFR_MEM8(0x062A) #define PORTB_INT1MASK _SFR_MEM8(0x062B) #define PORTB_INTFLAGS _SFR_MEM8(0x062C) #define PORTB_REMAP _SFR_MEM8(0x062E) #define PORTB_PIN0CTRL _SFR_MEM8(0x0630) #define PORTB_PIN1CTRL _SFR_MEM8(0x0631) #define PORTB_PIN2CTRL _SFR_MEM8(0x0632) #define PORTB_PIN3CTRL _SFR_MEM8(0x0633) #define PORTB_PIN4CTRL _SFR_MEM8(0x0634) #define PORTB_PIN5CTRL _SFR_MEM8(0x0635) #define PORTB_PIN6CTRL _SFR_MEM8(0x0636) #define PORTB_PIN7CTRL _SFR_MEM8(0x0637) /* PORT - I/O Ports */ #define PORTC_DIR _SFR_MEM8(0x0640) #define PORTC_DIRSET _SFR_MEM8(0x0641) #define PORTC_DIRCLR _SFR_MEM8(0x0642) #define PORTC_DIRTGL _SFR_MEM8(0x0643) #define PORTC_OUT _SFR_MEM8(0x0644) #define PORTC_OUTSET _SFR_MEM8(0x0645) #define PORTC_OUTCLR _SFR_MEM8(0x0646) #define PORTC_OUTTGL _SFR_MEM8(0x0647) #define PORTC_IN _SFR_MEM8(0x0648) #define PORTC_INTCTRL _SFR_MEM8(0x0649) #define PORTC_INT0MASK _SFR_MEM8(0x064A) #define PORTC_INT1MASK _SFR_MEM8(0x064B) #define PORTC_INTFLAGS _SFR_MEM8(0x064C) #define PORTC_REMAP _SFR_MEM8(0x064E) #define PORTC_PIN0CTRL _SFR_MEM8(0x0650) #define PORTC_PIN1CTRL _SFR_MEM8(0x0651) #define PORTC_PIN2CTRL _SFR_MEM8(0x0652) #define PORTC_PIN3CTRL _SFR_MEM8(0x0653) #define PORTC_PIN4CTRL _SFR_MEM8(0x0654) #define PORTC_PIN5CTRL _SFR_MEM8(0x0655) #define PORTC_PIN6CTRL _SFR_MEM8(0x0656) #define PORTC_PIN7CTRL _SFR_MEM8(0x0657) /* PORT - I/O Ports */ #define PORTD_DIR _SFR_MEM8(0x0660) #define PORTD_DIRSET _SFR_MEM8(0x0661) #define PORTD_DIRCLR _SFR_MEM8(0x0662) #define PORTD_DIRTGL _SFR_MEM8(0x0663) #define PORTD_OUT _SFR_MEM8(0x0664) #define PORTD_OUTSET _SFR_MEM8(0x0665) #define PORTD_OUTCLR _SFR_MEM8(0x0666) #define PORTD_OUTTGL _SFR_MEM8(0x0667) #define PORTD_IN _SFR_MEM8(0x0668) #define PORTD_INTCTRL _SFR_MEM8(0x0669) #define PORTD_INT0MASK _SFR_MEM8(0x066A) #define PORTD_INT1MASK _SFR_MEM8(0x066B) #define PORTD_INTFLAGS _SFR_MEM8(0x066C) #define PORTD_REMAP _SFR_MEM8(0x066E) #define PORTD_PIN0CTRL _SFR_MEM8(0x0670) #define PORTD_PIN1CTRL _SFR_MEM8(0x0671) #define PORTD_PIN2CTRL _SFR_MEM8(0x0672) #define PORTD_PIN3CTRL _SFR_MEM8(0x0673) #define PORTD_PIN4CTRL _SFR_MEM8(0x0674) #define PORTD_PIN5CTRL _SFR_MEM8(0x0675) #define PORTD_PIN6CTRL _SFR_MEM8(0x0676) #define PORTD_PIN7CTRL _SFR_MEM8(0x0677) /* PORT - I/O Ports */ #define PORTE_DIR _SFR_MEM8(0x0680) #define PORTE_DIRSET _SFR_MEM8(0x0681) #define PORTE_DIRCLR _SFR_MEM8(0x0682) #define PORTE_DIRTGL _SFR_MEM8(0x0683) #define PORTE_OUT _SFR_MEM8(0x0684) #define PORTE_OUTSET _SFR_MEM8(0x0685) #define PORTE_OUTCLR _SFR_MEM8(0x0686) #define PORTE_OUTTGL _SFR_MEM8(0x0687) #define PORTE_IN _SFR_MEM8(0x0688) #define PORTE_INTCTRL _SFR_MEM8(0x0689) #define PORTE_INT0MASK _SFR_MEM8(0x068A) #define PORTE_INT1MASK _SFR_MEM8(0x068B) #define PORTE_INTFLAGS _SFR_MEM8(0x068C) #define PORTE_REMAP _SFR_MEM8(0x068E) #define PORTE_PIN0CTRL _SFR_MEM8(0x0690) #define PORTE_PIN1CTRL _SFR_MEM8(0x0691) #define PORTE_PIN2CTRL _SFR_MEM8(0x0692) #define PORTE_PIN3CTRL _SFR_MEM8(0x0693) #define PORTE_PIN4CTRL _SFR_MEM8(0x0694) #define PORTE_PIN5CTRL _SFR_MEM8(0x0695) #define PORTE_PIN6CTRL _SFR_MEM8(0x0696) #define PORTE_PIN7CTRL _SFR_MEM8(0x0697) /* PORT - I/O Ports */ #define PORTF_DIR _SFR_MEM8(0x06A0) #define PORTF_DIRSET _SFR_MEM8(0x06A1) #define PORTF_DIRCLR _SFR_MEM8(0x06A2) #define PORTF_DIRTGL _SFR_MEM8(0x06A3) #define PORTF_OUT _SFR_MEM8(0x06A4) #define PORTF_OUTSET _SFR_MEM8(0x06A5) #define PORTF_OUTCLR _SFR_MEM8(0x06A6) #define PORTF_OUTTGL _SFR_MEM8(0x06A7) #define PORTF_IN _SFR_MEM8(0x06A8) #define PORTF_INTCTRL _SFR_MEM8(0x06A9) #define PORTF_INT0MASK _SFR_MEM8(0x06AA) #define PORTF_INT1MASK _SFR_MEM8(0x06AB) #define PORTF_INTFLAGS _SFR_MEM8(0x06AC) #define PORTF_REMAP _SFR_MEM8(0x06AE) #define PORTF_PIN0CTRL _SFR_MEM8(0x06B0) #define PORTF_PIN1CTRL _SFR_MEM8(0x06B1) #define PORTF_PIN2CTRL _SFR_MEM8(0x06B2) #define PORTF_PIN3CTRL _SFR_MEM8(0x06B3) #define PORTF_PIN4CTRL _SFR_MEM8(0x06B4) #define PORTF_PIN5CTRL _SFR_MEM8(0x06B5) #define PORTF_PIN6CTRL _SFR_MEM8(0x06B6) #define PORTF_PIN7CTRL _SFR_MEM8(0x06B7) /* PORT - I/O Ports */ #define PORTR_DIR _SFR_MEM8(0x07E0) #define PORTR_DIRSET _SFR_MEM8(0x07E1) #define PORTR_DIRCLR _SFR_MEM8(0x07E2) #define PORTR_DIRTGL _SFR_MEM8(0x07E3) #define PORTR_OUT _SFR_MEM8(0x07E4) #define PORTR_OUTSET _SFR_MEM8(0x07E5) #define PORTR_OUTCLR _SFR_MEM8(0x07E6) #define PORTR_OUTTGL _SFR_MEM8(0x07E7) #define PORTR_IN _SFR_MEM8(0x07E8) #define PORTR_INTCTRL _SFR_MEM8(0x07E9) #define PORTR_INT0MASK _SFR_MEM8(0x07EA) #define PORTR_INT1MASK _SFR_MEM8(0x07EB) #define PORTR_INTFLAGS _SFR_MEM8(0x07EC) #define PORTR_REMAP _SFR_MEM8(0x07EE) #define PORTR_PIN0CTRL _SFR_MEM8(0x07F0) #define PORTR_PIN1CTRL _SFR_MEM8(0x07F1) #define PORTR_PIN2CTRL _SFR_MEM8(0x07F2) #define PORTR_PIN3CTRL _SFR_MEM8(0x07F3) #define PORTR_PIN4CTRL _SFR_MEM8(0x07F4) #define PORTR_PIN5CTRL _SFR_MEM8(0x07F5) #define PORTR_PIN6CTRL _SFR_MEM8(0x07F6) #define PORTR_PIN7CTRL _SFR_MEM8(0x07F7) /* TC0 - 16-bit Timer/Counter 0 */ #define TCC0_CTRLA _SFR_MEM8(0x0800) #define TCC0_CTRLB _SFR_MEM8(0x0801) #define TCC0_CTRLC _SFR_MEM8(0x0802) #define TCC0_CTRLD _SFR_MEM8(0x0803) #define TCC0_CTRLE _SFR_MEM8(0x0804) #define TCC0_INTCTRLA _SFR_MEM8(0x0806) #define TCC0_INTCTRLB _SFR_MEM8(0x0807) #define TCC0_CTRLFCLR _SFR_MEM8(0x0808) #define TCC0_CTRLFSET _SFR_MEM8(0x0809) #define TCC0_CTRLGCLR _SFR_MEM8(0x080A) #define TCC0_CTRLGSET _SFR_MEM8(0x080B) #define TCC0_INTFLAGS _SFR_MEM8(0x080C) #define TCC0_TEMP _SFR_MEM8(0x080F) #define TCC0_CNT _SFR_MEM16(0x0820) #define TCC0_PER _SFR_MEM16(0x0826) #define TCC0_CCA _SFR_MEM16(0x0828) #define TCC0_CCB _SFR_MEM16(0x082A) #define TCC0_CCC _SFR_MEM16(0x082C) #define TCC0_CCD _SFR_MEM16(0x082E) #define TCC0_PERBUF _SFR_MEM16(0x0836) #define TCC0_CCABUF _SFR_MEM16(0x0838) #define TCC0_CCBBUF _SFR_MEM16(0x083A) #define TCC0_CCCBUF _SFR_MEM16(0x083C) #define TCC0_CCDBUF _SFR_MEM16(0x083E) /* TC2 - 16-bit Timer/Counter type 2 */ #define TCC2_CTRLA _SFR_MEM8(0x0800) #define TCC2_CTRLB _SFR_MEM8(0x0801) #define TCC2_CTRLC _SFR_MEM8(0x0802) #define TCC2_CTRLE _SFR_MEM8(0x0804) #define TCC2_INTCTRLA _SFR_MEM8(0x0806) #define TCC2_INTCTRLB _SFR_MEM8(0x0807) #define TCC2_CTRLF _SFR_MEM8(0x0809) #define TCC2_INTFLAGS _SFR_MEM8(0x080C) #define TCC2_LCNT _SFR_MEM8(0x0820) #define TCC2_HCNT _SFR_MEM8(0x0821) #define TCC2_LPER _SFR_MEM8(0x0826) #define TCC2_HPER _SFR_MEM8(0x0827) #define TCC2_LCMPA _SFR_MEM8(0x0828) #define TCC2_HCMPA _SFR_MEM8(0x0829) #define TCC2_LCMPB _SFR_MEM8(0x082A) #define TCC2_HCMPB _SFR_MEM8(0x082B) #define TCC2_LCMPC _SFR_MEM8(0x082C) #define TCC2_HCMPC _SFR_MEM8(0x082D) #define TCC2_LCMPD _SFR_MEM8(0x082E) #define TCC2_HCMPD _SFR_MEM8(0x082F) /* TC1 - 16-bit Timer/Counter 1 */ #define TCC1_CTRLA _SFR_MEM8(0x0840) #define TCC1_CTRLB _SFR_MEM8(0x0841) #define TCC1_CTRLC _SFR_MEM8(0x0842) #define TCC1_CTRLD _SFR_MEM8(0x0843) #define TCC1_CTRLE _SFR_MEM8(0x0844) #define TCC1_INTCTRLA _SFR_MEM8(0x0846) #define TCC1_INTCTRLB _SFR_MEM8(0x0847) #define TCC1_CTRLFCLR _SFR_MEM8(0x0848) #define TCC1_CTRLFSET _SFR_MEM8(0x0849) #define TCC1_CTRLGCLR _SFR_MEM8(0x084A) #define TCC1_CTRLGSET _SFR_MEM8(0x084B) #define TCC1_INTFLAGS _SFR_MEM8(0x084C) #define TCC1_TEMP _SFR_MEM8(0x084F) #define TCC1_CNT _SFR_MEM16(0x0860) #define TCC1_PER _SFR_MEM16(0x0866) #define TCC1_CCA _SFR_MEM16(0x0868) #define TCC1_CCB _SFR_MEM16(0x086A) #define TCC1_PERBUF _SFR_MEM16(0x0876) #define TCC1_CCABUF _SFR_MEM16(0x0878) #define TCC1_CCBBUF _SFR_MEM16(0x087A) /* AWEX - Advanced Waveform Extension */ #define AWEXC_CTRL _SFR_MEM8(0x0880) #define AWEXC_FDEMASK _SFR_MEM8(0x0882) #define AWEXC_FDCTRL _SFR_MEM8(0x0883) #define AWEXC_STATUS _SFR_MEM8(0x0884) #define AWEXC_STATUSSET _SFR_MEM8(0x0885) #define AWEXC_DTBOTH _SFR_MEM8(0x0886) #define AWEXC_DTBOTHBUF _SFR_MEM8(0x0887) #define AWEXC_DTLS _SFR_MEM8(0x0888) #define AWEXC_DTHS _SFR_MEM8(0x0889) #define AWEXC_DTLSBUF _SFR_MEM8(0x088A) #define AWEXC_DTHSBUF _SFR_MEM8(0x088B) #define AWEXC_OUTOVEN _SFR_MEM8(0x088C) /* HIRES - High-Resolution Extension */ #define HIRESC_CTRLA _SFR_MEM8(0x0890) /* USART - Universal Synchronous/Asynchronous Receiver/Transmitter */ #define USARTC0_DATA _SFR_MEM8(0x08A0) #define USARTC0_STATUS _SFR_MEM8(0x08A1) #define USARTC0_CTRLA _SFR_MEM8(0x08A3) #define USARTC0_CTRLB _SFR_MEM8(0x08A4) #define USARTC0_CTRLC _SFR_MEM8(0x08A5) #define USARTC0_BAUDCTRLA _SFR_MEM8(0x08A6) #define USARTC0_BAUDCTRLB _SFR_MEM8(0x08A7) /* SPI - Serial Peripheral Interface */ #define SPIC_CTRL _SFR_MEM8(0x08C0) #define SPIC_INTCTRL _SFR_MEM8(0x08C1) #define SPIC_STATUS _SFR_MEM8(0x08C2) #define SPIC_DATA _SFR_MEM8(0x08C3) /* IRCOM - IR Communication Module */ #define IRCOM_CTRL _SFR_MEM8(0x08F8) #define IRCOM_TXPLCTRL _SFR_MEM8(0x08F9) #define IRCOM_RXPLCTRL _SFR_MEM8(0x08FA) /* TC0 - 16-bit Timer/Counter 0 */ #define TCD0_CTRLA _SFR_MEM8(0x0900) #define TCD0_CTRLB _SFR_MEM8(0x0901) #define TCD0_CTRLC _SFR_MEM8(0x0902) #define TCD0_CTRLD _SFR_MEM8(0x0903) #define TCD0_CTRLE _SFR_MEM8(0x0904) #define TCD0_INTCTRLA _SFR_MEM8(0x0906) #define TCD0_INTCTRLB _SFR_MEM8(0x0907) #define TCD0_CTRLFCLR _SFR_MEM8(0x0908) #define TCD0_CTRLFSET _SFR_MEM8(0x0909) #define TCD0_CTRLGCLR _SFR_MEM8(0x090A) #define TCD0_CTRLGSET _SFR_MEM8(0x090B) #define TCD0_INTFLAGS _SFR_MEM8(0x090C) #define TCD0_TEMP _SFR_MEM8(0x090F) #define TCD0_CNT _SFR_MEM16(0x0920) #define TCD0_PER _SFR_MEM16(0x0926) #define TCD0_CCA _SFR_MEM16(0x0928) #define TCD0_CCB _SFR_MEM16(0x092A) #define TCD0_CCC _SFR_MEM16(0x092C) #define TCD0_CCD _SFR_MEM16(0x092E) #define TCD0_PERBUF _SFR_MEM16(0x0936) #define TCD0_CCABUF _SFR_MEM16(0x0938) #define TCD0_CCBBUF _SFR_MEM16(0x093A) #define TCD0_CCCBUF _SFR_MEM16(0x093C) #define TCD0_CCDBUF _SFR_MEM16(0x093E) /* TC2 - 16-bit Timer/Counter type 2 */ #define TCD2_CTRLA _SFR_MEM8(0x0900) #define TCD2_CTRLB _SFR_MEM8(0x0901) #define TCD2_CTRLC _SFR_MEM8(0x0902) #define TCD2_CTRLE _SFR_MEM8(0x0904) #define TCD2_INTCTRLA _SFR_MEM8(0x0906) #define TCD2_INTCTRLB _SFR_MEM8(0x0907) #define TCD2_CTRLF _SFR_MEM8(0x0909) #define TCD2_INTFLAGS _SFR_MEM8(0x090C) #define TCD2_LCNT _SFR_MEM8(0x0920) #define TCD2_HCNT _SFR_MEM8(0x0921) #define TCD2_LPER _SFR_MEM8(0x0926) #define TCD2_HPER _SFR_MEM8(0x0927) #define TCD2_LCMPA _SFR_MEM8(0x0928) #define TCD2_HCMPA _SFR_MEM8(0x0929) #define TCD2_LCMPB _SFR_MEM8(0x092A) #define TCD2_HCMPB _SFR_MEM8(0x092B) #define TCD2_LCMPC _SFR_MEM8(0x092C) #define TCD2_HCMPC _SFR_MEM8(0x092D) #define TCD2_LCMPD _SFR_MEM8(0x092E) #define TCD2_HCMPD _SFR_MEM8(0x092F) /* USART - Universal Synchronous/Asynchronous Receiver/Transmitter */ #define USARTD0_DATA _SFR_MEM8(0x09A0) #define USARTD0_STATUS _SFR_MEM8(0x09A1) #define USARTD0_CTRLA _SFR_MEM8(0x09A3) #define USARTD0_CTRLB _SFR_MEM8(0x09A4) #define USARTD0_CTRLC _SFR_MEM8(0x09A5) #define USARTD0_BAUDCTRLA _SFR_MEM8(0x09A6) #define USARTD0_BAUDCTRLB _SFR_MEM8(0x09A7) /* SPI - Serial Peripheral Interface */ #define SPID_CTRL _SFR_MEM8(0x09C0) #define SPID_INTCTRL _SFR_MEM8(0x09C1) #define SPID_STATUS _SFR_MEM8(0x09C2) #define SPID_DATA _SFR_MEM8(0x09C3) /* TC0 - 16-bit Timer/Counter 0 */ #define TCE0_CTRLA _SFR_MEM8(0x0A00) #define TCE0_CTRLB _SFR_MEM8(0x0A01) #define TCE0_CTRLC _SFR_MEM8(0x0A02) #define TCE0_CTRLD _SFR_MEM8(0x0A03) #define TCE0_CTRLE _SFR_MEM8(0x0A04) #define TCE0_INTCTRLA _SFR_MEM8(0x0A06) #define TCE0_INTCTRLB _SFR_MEM8(0x0A07) #define TCE0_CTRLFCLR _SFR_MEM8(0x0A08) #define TCE0_CTRLFSET _SFR_MEM8(0x0A09) #define TCE0_CTRLGCLR _SFR_MEM8(0x0A0A) #define TCE0_CTRLGSET _SFR_MEM8(0x0A0B) #define TCE0_INTFLAGS _SFR_MEM8(0x0A0C) #define TCE0_TEMP _SFR_MEM8(0x0A0F) #define TCE0_CNT _SFR_MEM16(0x0A20) #define TCE0_PER _SFR_MEM16(0x0A26) #define TCE0_CCA _SFR_MEM16(0x0A28) #define TCE0_CCB _SFR_MEM16(0x0A2A) #define TCE0_CCC _SFR_MEM16(0x0A2C) #define TCE0_CCD _SFR_MEM16(0x0A2E) #define TCE0_PERBUF _SFR_MEM16(0x0A36) #define TCE0_CCABUF _SFR_MEM16(0x0A38) #define TCE0_CCBBUF _SFR_MEM16(0x0A3A) #define TCE0_CCCBUF _SFR_MEM16(0x0A3C) #define TCE0_CCDBUF _SFR_MEM16(0x0A3E) /* TC2 - 16-bit Timer/Counter type 2 */ #define TCE2_CTRLA _SFR_MEM8(0x0A00) #define TCE2_CTRLB _SFR_MEM8(0x0A01) #define TCE2_CTRLC _SFR_MEM8(0x0A02) #define TCE2_CTRLE _SFR_MEM8(0x0A04) #define TCE2_INTCTRLA _SFR_MEM8(0x0A06) #define TCE2_INTCTRLB _SFR_MEM8(0x0A07) #define TCE2_CTRLF _SFR_MEM8(0x0A09) #define TCE2_INTFLAGS _SFR_MEM8(0x0A0C) #define TCE2_LCNT _SFR_MEM8(0x0A20) #define TCE2_HCNT _SFR_MEM8(0x0A21) #define TCE2_LPER _SFR_MEM8(0x0A26) #define TCE2_HPER _SFR_MEM8(0x0A27) #define TCE2_LCMPA _SFR_MEM8(0x0A28) #define TCE2_HCMPA _SFR_MEM8(0x0A29) #define TCE2_LCMPB _SFR_MEM8(0x0A2A) #define TCE2_HCMPB _SFR_MEM8(0x0A2B) #define TCE2_LCMPC _SFR_MEM8(0x0A2C) #define TCE2_HCMPC _SFR_MEM8(0x0A2D) #define TCE2_LCMPD _SFR_MEM8(0x0A2E) #define TCE2_HCMPD _SFR_MEM8(0x0A2F) /* USART - Universal Synchronous/Asynchronous Receiver/Transmitter */ #define USARTE0_DATA _SFR_MEM8(0x0AA0) #define USARTE0_STATUS _SFR_MEM8(0x0AA1) #define USARTE0_CTRLA _SFR_MEM8(0x0AA3) #define USARTE0_CTRLB _SFR_MEM8(0x0AA4) #define USARTE0_CTRLC _SFR_MEM8(0x0AA5) #define USARTE0_BAUDCTRLA _SFR_MEM8(0x0AA6) #define USARTE0_BAUDCTRLB _SFR_MEM8(0x0AA7) /* TC0 - 16-bit Timer/Counter 0 */ #define TCF0_CTRLA _SFR_MEM8(0x0B00) #define TCF0_CTRLB _SFR_MEM8(0x0B01) #define TCF0_CTRLC _SFR_MEM8(0x0B02) #define TCF0_CTRLD _SFR_MEM8(0x0B03) #define TCF0_CTRLE _SFR_MEM8(0x0B04) #define TCF0_INTCTRLA _SFR_MEM8(0x0B06) #define TCF0_INTCTRLB _SFR_MEM8(0x0B07) #define TCF0_CTRLFCLR _SFR_MEM8(0x0B08) #define TCF0_CTRLFSET _SFR_MEM8(0x0B09) #define TCF0_CTRLGCLR _SFR_MEM8(0x0B0A) #define TCF0_CTRLGSET _SFR_MEM8(0x0B0B) #define TCF0_INTFLAGS _SFR_MEM8(0x0B0C) #define TCF0_TEMP _SFR_MEM8(0x0B0F) #define TCF0_CNT _SFR_MEM16(0x0B20) #define TCF0_PER _SFR_MEM16(0x0B26) #define TCF0_CCA _SFR_MEM16(0x0B28) #define TCF0_CCB _SFR_MEM16(0x0B2A) #define TCF0_CCC _SFR_MEM16(0x0B2C) #define TCF0_CCD _SFR_MEM16(0x0B2E) #define TCF0_PERBUF _SFR_MEM16(0x0B36) #define TCF0_CCABUF _SFR_MEM16(0x0B38) #define TCF0_CCBBUF _SFR_MEM16(0x0B3A) #define TCF0_CCCBUF _SFR_MEM16(0x0B3C) #define TCF0_CCDBUF _SFR_MEM16(0x0B3E) /* TC2 - 16-bit Timer/Counter type 2 */ #define TCF2_CTRLA _SFR_MEM8(0x0B00) #define TCF2_CTRLB _SFR_MEM8(0x0B01) #define TCF2_CTRLC _SFR_MEM8(0x0B02) #define TCF2_CTRLE _SFR_MEM8(0x0B04) #define TCF2_INTCTRLA _SFR_MEM8(0x0B06) #define TCF2_INTCTRLB _SFR_MEM8(0x0B07) #define TCF2_CTRLF _SFR_MEM8(0x0B09) #define TCF2_INTFLAGS _SFR_MEM8(0x0B0C) #define TCF2_LCNT _SFR_MEM8(0x0B20) #define TCF2_HCNT _SFR_MEM8(0x0B21) #define TCF2_LPER _SFR_MEM8(0x0B26) #define TCF2_HPER _SFR_MEM8(0x0B27) #define TCF2_LCMPA _SFR_MEM8(0x0B28) #define TCF2_HCMPA _SFR_MEM8(0x0B29) #define TCF2_LCMPB _SFR_MEM8(0x0B2A) #define TCF2_HCMPB _SFR_MEM8(0x0B2B) #define TCF2_LCMPC _SFR_MEM8(0x0B2C) #define TCF2_HCMPC _SFR_MEM8(0x0B2D) #define TCF2_LCMPD _SFR_MEM8(0x0B2E) #define TCF2_HCMPD _SFR_MEM8(0x0B2F) /*================== Bitfield Definitions ================== */ /* VPORT - Virtual Ports */ /* VPORT.INTFLAGS bit masks and bit positions */ #define VPORT_INT1IF_bm 0x02 /* Port Interrupt 1 Flag bit mask. */ #define VPORT_INT1IF_bp 1 /* Port Interrupt 1 Flag bit position. */ #define VPORT_INT0IF_bm 0x01 /* Port Interrupt 0 Flag bit mask. */ #define VPORT_INT0IF_bp 0 /* Port Interrupt 0 Flag bit position. */ /* XOCD - On-Chip Debug System */ /* OCD.OCDR0 bit masks and bit positions */ #define OCD_OCDRD_gm 0xFF /* OCDR Dirty group mask. */ #define OCD_OCDRD_gp 0 /* OCDR Dirty group position. */ #define OCD_OCDRD0_bm (1<<0) /* OCDR Dirty bit 0 mask. */ #define OCD_OCDRD0_bp 0 /* OCDR Dirty bit 0 position. */ #define OCD_OCDRD1_bm (1<<1) /* OCDR Dirty bit 1 mask. */ #define OCD_OCDRD1_bp 1 /* OCDR Dirty bit 1 position. */ #define OCD_OCDRD2_bm (1<<2) /* OCDR Dirty bit 2 mask. */ #define OCD_OCDRD2_bp 2 /* OCDR Dirty bit 2 position. */ #define OCD_OCDRD3_bm (1<<3) /* OCDR Dirty bit 3 mask. */ #define OCD_OCDRD3_bp 3 /* OCDR Dirty bit 3 position. */ #define OCD_OCDRD4_bm (1<<4) /* OCDR Dirty bit 4 mask. */ #define OCD_OCDRD4_bp 4 /* OCDR Dirty bit 4 position. */ #define OCD_OCDRD5_bm (1<<5) /* OCDR Dirty bit 5 mask. */ #define OCD_OCDRD5_bp 5 /* OCDR Dirty bit 5 position. */ #define OCD_OCDRD6_bm (1<<6) /* OCDR Dirty bit 6 mask. */ #define OCD_OCDRD6_bp 6 /* OCDR Dirty bit 6 position. */ #define OCD_OCDRD7_bm (1<<7) /* OCDR Dirty bit 7 mask. */ #define OCD_OCDRD7_bp 7 /* OCDR Dirty bit 7 position. */ /* OCD.OCDR1 bit masks and bit positions */ /* OCD_OCDRD Predefined. */ /* OCD_OCDRD Predefined. */ /* CPU - CPU */ /* CPU.CCP bit masks and bit positions */ #define CPU_CCP_gm 0xFF /* CCP signature group mask. */ #define CPU_CCP_gp 0 /* CCP signature group position. */ #define CPU_CCP0_bm (1<<0) /* CCP signature bit 0 mask. */ #define CPU_CCP0_bp 0 /* CCP signature bit 0 position. */ #define CPU_CCP1_bm (1<<1) /* CCP signature bit 1 mask. */ #define CPU_CCP1_bp 1 /* CCP signature bit 1 position. */ #define CPU_CCP2_bm (1<<2) /* CCP signature bit 2 mask. */ #define CPU_CCP2_bp 2 /* CCP signature bit 2 position. */ #define CPU_CCP3_bm (1<<3) /* CCP signature bit 3 mask. */ #define CPU_CCP3_bp 3 /* CCP signature bit 3 position. */ #define CPU_CCP4_bm (1<<4) /* CCP signature bit 4 mask. */ #define CPU_CCP4_bp 4 /* CCP signature bit 4 position. */ #define CPU_CCP5_bm (1<<5) /* CCP signature bit 5 mask. */ #define CPU_CCP5_bp 5 /* CCP signature bit 5 position. */ #define CPU_CCP6_bm (1<<6) /* CCP signature bit 6 mask. */ #define CPU_CCP6_bp 6 /* CCP signature bit 6 position. */ #define CPU_CCP7_bm (1<<7) /* CCP signature bit 7 mask. */ #define CPU_CCP7_bp 7 /* CCP signature bit 7 position. */ /* CPU.SREG bit masks and bit positions */ #define CPU_I_bm 0x80 /* Global Interrupt Enable Flag bit mask. */ #define CPU_I_bp 7 /* Global Interrupt Enable Flag bit position. */ #define CPU_T_bm 0x40 /* Transfer Bit bit mask. */ #define CPU_T_bp 6 /* Transfer Bit bit position. */ #define CPU_H_bm 0x20 /* Half Carry Flag bit mask. */ #define CPU_H_bp 5 /* Half Carry Flag bit position. */ #define CPU_S_bm 0x10 /* N Exclusive Or V Flag bit mask. */ #define CPU_S_bp 4 /* N Exclusive Or V Flag bit position. */ #define CPU_V_bm 0x08 /* Two's Complement Overflow Flag bit mask. */ #define CPU_V_bp 3 /* Two's Complement Overflow Flag bit position. */ #define CPU_N_bm 0x04 /* Negative Flag bit mask. */ #define CPU_N_bp 2 /* Negative Flag bit position. */ #define CPU_Z_bm 0x02 /* Zero Flag bit mask. */ #define CPU_Z_bp 1 /* Zero Flag bit position. */ #define CPU_C_bm 0x01 /* Carry Flag bit mask. */ #define CPU_C_bp 0 /* Carry Flag bit position. */ /* CLK - Clock System */ /* CLK.CTRL bit masks and bit positions */ #define CLK_SCLKSEL_gm 0x07 /* System Clock Selection group mask. */ #define CLK_SCLKSEL_gp 0 /* System Clock Selection group position. */ #define CLK_SCLKSEL0_bm (1<<0) /* System Clock Selection bit 0 mask. */ #define CLK_SCLKSEL0_bp 0 /* System Clock Selection bit 0 position. */ #define CLK_SCLKSEL1_bm (1<<1) /* System Clock Selection bit 1 mask. */ #define CLK_SCLKSEL1_bp 1 /* System Clock Selection bit 1 position. */ #define CLK_SCLKSEL2_bm (1<<2) /* System Clock Selection bit 2 mask. */ #define CLK_SCLKSEL2_bp 2 /* System Clock Selection bit 2 position. */ /* CLK.PSCTRL bit masks and bit positions */ #define CLK_PSADIV_gm 0x7C /* Prescaler A Division Factor group mask. */ #define CLK_PSADIV_gp 2 /* Prescaler A Division Factor group position. */ #define CLK_PSADIV0_bm (1<<2) /* Prescaler A Division Factor bit 0 mask. */ #define CLK_PSADIV0_bp 2 /* Prescaler A Division Factor bit 0 position. */ #define CLK_PSADIV1_bm (1<<3) /* Prescaler A Division Factor bit 1 mask. */ #define CLK_PSADIV1_bp 3 /* Prescaler A Division Factor bit 1 position. */ #define CLK_PSADIV2_bm (1<<4) /* Prescaler A Division Factor bit 2 mask. */ #define CLK_PSADIV2_bp 4 /* Prescaler A Division Factor bit 2 position. */ #define CLK_PSADIV3_bm (1<<5) /* Prescaler A Division Factor bit 3 mask. */ #define CLK_PSADIV3_bp 5 /* Prescaler A Division Factor bit 3 position. */ #define CLK_PSADIV4_bm (1<<6) /* Prescaler A Division Factor bit 4 mask. */ #define CLK_PSADIV4_bp 6 /* Prescaler A Division Factor bit 4 position. */ #define CLK_PSBCDIV_gm 0x03 /* Prescaler B and C Division factor group mask. */ #define CLK_PSBCDIV_gp 0 /* Prescaler B and C Division factor group position. */ #define CLK_PSBCDIV0_bm (1<<0) /* Prescaler B and C Division factor bit 0 mask. */ #define CLK_PSBCDIV0_bp 0 /* Prescaler B and C Division factor bit 0 position. */ #define CLK_PSBCDIV1_bm (1<<1) /* Prescaler B and C Division factor bit 1 mask. */ #define CLK_PSBCDIV1_bp 1 /* Prescaler B and C Division factor bit 1 position. */ /* CLK.LOCK bit masks and bit positions */ #define CLK_LOCK_bm 0x01 /* Clock System Lock bit mask. */ #define CLK_LOCK_bp 0 /* Clock System Lock bit position. */ /* CLK.RTCCTRL bit masks and bit positions */ #define CLK_RTCSRC_gm 0x0E /* Clock Source group mask. */ #define CLK_RTCSRC_gp 1 /* Clock Source group position. */ #define CLK_RTCSRC0_bm (1<<1) /* Clock Source bit 0 mask. */ #define CLK_RTCSRC0_bp 1 /* Clock Source bit 0 position. */ #define CLK_RTCSRC1_bm (1<<2) /* Clock Source bit 1 mask. */ #define CLK_RTCSRC1_bp 2 /* Clock Source bit 1 position. */ #define CLK_RTCSRC2_bm (1<<3) /* Clock Source bit 2 mask. */ #define CLK_RTCSRC2_bp 3 /* Clock Source bit 2 position. */ #define CLK_RTCEN_bm 0x01 /* Clock Source Enable bit mask. */ #define CLK_RTCEN_bp 0 /* Clock Source Enable bit position. */ /* CLK.USBCTRL bit masks and bit positions */ #define CLK_USBPSDIV_gm 0x38 /* Prescaler Division Factor group mask. */ #define CLK_USBPSDIV_gp 3 /* Prescaler Division Factor group position. */ #define CLK_USBPSDIV0_bm (1<<3) /* Prescaler Division Factor bit 0 mask. */ #define CLK_USBPSDIV0_bp 3 /* Prescaler Division Factor bit 0 position. */ #define CLK_USBPSDIV1_bm (1<<4) /* Prescaler Division Factor bit 1 mask. */ #define CLK_USBPSDIV1_bp 4 /* Prescaler Division Factor bit 1 position. */ #define CLK_USBPSDIV2_bm (1<<5) /* Prescaler Division Factor bit 2 mask. */ #define CLK_USBPSDIV2_bp 5 /* Prescaler Division Factor bit 2 position. */ #define CLK_USBSRC_gm 0x06 /* Clock Source group mask. */ #define CLK_USBSRC_gp 1 /* Clock Source group position. */ #define CLK_USBSRC0_bm (1<<1) /* Clock Source bit 0 mask. */ #define CLK_USBSRC0_bp 1 /* Clock Source bit 0 position. */ #define CLK_USBSRC1_bm (1<<2) /* Clock Source bit 1 mask. */ #define CLK_USBSRC1_bp 2 /* Clock Source bit 1 position. */ #define CLK_USBSEN_bm 0x01 /* Clock Source Enable bit mask. */ #define CLK_USBSEN_bp 0 /* Clock Source Enable bit position. */ /* PR.PRGEN bit masks and bit positions */ #define PR_USB_bm 0x40 /* USB bit mask. */ #define PR_USB_bp 6 /* USB bit position. */ #define PR_AES_bm 0x10 /* AES bit mask. */ #define PR_AES_bp 4 /* AES bit position. */ #define PR_RTC_bm 0x04 /* Real-time Counter bit mask. */ #define PR_RTC_bp 2 /* Real-time Counter bit position. */ #define PR_EVSYS_bm 0x02 /* Event System bit mask. */ #define PR_EVSYS_bp 1 /* Event System bit position. */ #define PR_DMA_bm 0x01 /* DMA-Controller bit mask. */ #define PR_DMA_bp 0 /* DMA-Controller bit position. */ /* PR.PRPA bit masks and bit positions */ #define PR_ADC_bm 0x02 /* Port A ADC bit mask. */ #define PR_ADC_bp 1 /* Port A ADC bit position. */ #define PR_AC_bm 0x01 /* Port A Analog Comparator bit mask. */ #define PR_AC_bp 0 /* Port A Analog Comparator bit position. */ /* PR.PRPC bit masks and bit positions */ #define PR_TWI_bm 0x40 /* Port C Two-wire Interface bit mask. */ #define PR_TWI_bp 6 /* Port C Two-wire Interface bit position. */ #define PR_USART1_bm 0x20 /* Port C USART1 bit mask. */ #define PR_USART1_bp 5 /* Port C USART1 bit position. */ #define PR_USART0_bm 0x10 /* Port C USART0 bit mask. */ #define PR_USART0_bp 4 /* Port C USART0 bit position. */ #define PR_SPI_bm 0x08 /* Port C SPI bit mask. */ #define PR_SPI_bp 3 /* Port C SPI bit position. */ #define PR_HIRES_bm 0x04 /* Port C AWEX bit mask. */ #define PR_HIRES_bp 2 /* Port C AWEX bit position. */ #define PR_TC1_bm 0x02 /* Port C Timer/Counter1 bit mask. */ #define PR_TC1_bp 1 /* Port C Timer/Counter1 bit position. */ #define PR_TC0_bm 0x01 /* Port C Timer/Counter0 bit mask. */ #define PR_TC0_bp 0 /* Port C Timer/Counter0 bit position. */ /* PR.PRPD bit masks and bit positions */ /* PR_USART0 Predefined. */ /* PR_USART0 Predefined. */ /* PR_SPI Predefined. */ /* PR_SPI Predefined. */ /* PR_TC0 Predefined. */ /* PR_TC0 Predefined. */ /* PR.PRPE bit masks and bit positions */ /* PR_TWI Predefined. */ /* PR_TWI Predefined. */ /* PR_USART0 Predefined. */ /* PR_USART0 Predefined. */ /* PR_TC0 Predefined. */ /* PR_TC0 Predefined. */ /* PR.PRPF bit masks and bit positions */ /* PR_USART0 Predefined. */ /* PR_USART0 Predefined. */ /* PR_TC0 Predefined. */ /* PR_TC0 Predefined. */ /* SLEEP - Sleep Controller */ /* SLEEP.CTRL bit masks and bit positions */ #define SLEEP_SMODE_gm 0x0E /* Sleep Mode group mask. */ #define SLEEP_SMODE_gp 1 /* Sleep Mode group position. */ #define SLEEP_SMODE0_bm (1<<1) /* Sleep Mode bit 0 mask. */ #define SLEEP_SMODE0_bp 1 /* Sleep Mode bit 0 position. */ #define SLEEP_SMODE1_bm (1<<2) /* Sleep Mode bit 1 mask. */ #define SLEEP_SMODE1_bp 2 /* Sleep Mode bit 1 position. */ #define SLEEP_SMODE2_bm (1<<3) /* Sleep Mode bit 2 mask. */ #define SLEEP_SMODE2_bp 3 /* Sleep Mode bit 2 position. */ #define SLEEP_SEN_bm 0x01 /* Sleep Enable bit mask. */ #define SLEEP_SEN_bp 0 /* Sleep Enable bit position. */ /* OSC - Oscillator */ /* OSC.CTRL bit masks and bit positions */ #define OSC_PLLEN_bm 0x10 /* PLL Enable bit mask. */ #define OSC_PLLEN_bp 4 /* PLL Enable bit position. */ #define OSC_XOSCEN_bm 0x08 /* External Oscillator Enable bit mask. */ #define OSC_XOSCEN_bp 3 /* External Oscillator Enable bit position. */ #define OSC_RC32KEN_bm 0x04 /* Internal 32.768 kHz RC Oscillator Enable bit mask. */ #define OSC_RC32KEN_bp 2 /* Internal 32.768 kHz RC Oscillator Enable bit position. */ #define OSC_RC32MEN_bm 0x02 /* Internal 32 MHz RC Oscillator Enable bit mask. */ #define OSC_RC32MEN_bp 1 /* Internal 32 MHz RC Oscillator Enable bit position. */ #define OSC_RC2MEN_bm 0x01 /* Internal 2 MHz RC Oscillator Enable bit mask. */ #define OSC_RC2MEN_bp 0 /* Internal 2 MHz RC Oscillator Enable bit position. */ /* OSC.STATUS bit masks and bit positions */ #define OSC_PLLRDY_bm 0x10 /* PLL Ready bit mask. */ #define OSC_PLLRDY_bp 4 /* PLL Ready bit position. */ #define OSC_XOSCRDY_bm 0x08 /* External Oscillator Ready bit mask. */ #define OSC_XOSCRDY_bp 3 /* External Oscillator Ready bit position. */ #define OSC_RC32KRDY_bm 0x04 /* Internal 32.768 kHz RC Oscillator Ready bit mask. */ #define OSC_RC32KRDY_bp 2 /* Internal 32.768 kHz RC Oscillator Ready bit position. */ #define OSC_RC32MRDY_bm 0x02 /* Internal 32 MHz RC Oscillator Ready bit mask. */ #define OSC_RC32MRDY_bp 1 /* Internal 32 MHz RC Oscillator Ready bit position. */ #define OSC_RC2MRDY_bm 0x01 /* Internal 2 MHz RC Oscillator Ready bit mask. */ #define OSC_RC2MRDY_bp 0 /* Internal 2 MHz RC Oscillator Ready bit position. */ /* OSC.XOSCCTRL bit masks and bit positions */ #define OSC_FRQRANGE_gm 0xC0 /* Frequency Range group mask. */ #define OSC_FRQRANGE_gp 6 /* Frequency Range group position. */ #define OSC_FRQRANGE0_bm (1<<6) /* Frequency Range bit 0 mask. */ #define OSC_FRQRANGE0_bp 6 /* Frequency Range bit 0 position. */ #define OSC_FRQRANGE1_bm (1<<7) /* Frequency Range bit 1 mask. */ #define OSC_FRQRANGE1_bp 7 /* Frequency Range bit 1 position. */ #define OSC_X32KLPM_bm 0x20 /* 32.768 kHz XTAL OSC Low-power Mode bit mask. */ #define OSC_X32KLPM_bp 5 /* 32.768 kHz XTAL OSC Low-power Mode bit position. */ #define OSC_XOSCPWR_bm 0x10 /* 16 MHz Crystal Oscillator High Power mode bit mask. */ #define OSC_XOSCPWR_bp 4 /* 16 MHz Crystal Oscillator High Power mode bit position. */ #define OSC_XOSCSEL_gm 0x0F /* External Oscillator Selection and Startup Time group mask. */ #define OSC_XOSCSEL_gp 0 /* External Oscillator Selection and Startup Time group position. */ #define OSC_XOSCSEL0_bm (1<<0) /* External Oscillator Selection and Startup Time bit 0 mask. */ #define OSC_XOSCSEL0_bp 0 /* External Oscillator Selection and Startup Time bit 0 position. */ #define OSC_XOSCSEL1_bm (1<<1) /* External Oscillator Selection and Startup Time bit 1 mask. */ #define OSC_XOSCSEL1_bp 1 /* External Oscillator Selection and Startup Time bit 1 position. */ #define OSC_XOSCSEL2_bm (1<<2) /* External Oscillator Selection and Startup Time bit 2 mask. */ #define OSC_XOSCSEL2_bp 2 /* External Oscillator Selection and Startup Time bit 2 position. */ #define OSC_XOSCSEL3_bm (1<<3) /* External Oscillator Selection and Startup Time bit 3 mask. */ #define OSC_XOSCSEL3_bp 3 /* External Oscillator Selection and Startup Time bit 3 position. */ /* OSC.XOSCFAIL bit masks and bit positions */ #define OSC_PLLFDIF_bm 0x08 /* PLL Failure Detection Interrupt Flag bit mask. */ #define OSC_PLLFDIF_bp 3 /* PLL Failure Detection Interrupt Flag bit position. */ #define OSC_PLLFDEN_bm 0x04 /* PLL Failure Detection Enable bit mask. */ #define OSC_PLLFDEN_bp 2 /* PLL Failure Detection Enable bit position. */ #define OSC_XOSCFDIF_bm 0x02 /* XOSC Failure Detection Interrupt Flag bit mask. */ #define OSC_XOSCFDIF_bp 1 /* XOSC Failure Detection Interrupt Flag bit position. */ #define OSC_XOSCFDEN_bm 0x01 /* XOSC Failure Detection Enable bit mask. */ #define OSC_XOSCFDEN_bp 0 /* XOSC Failure Detection Enable bit position. */ /* OSC.PLLCTRL bit masks and bit positions */ #define OSC_PLLSRC_gm 0xC0 /* Clock Source group mask. */ #define OSC_PLLSRC_gp 6 /* Clock Source group position. */ #define OSC_PLLSRC0_bm (1<<6) /* Clock Source bit 0 mask. */ #define OSC_PLLSRC0_bp 6 /* Clock Source bit 0 position. */ #define OSC_PLLSRC1_bm (1<<7) /* Clock Source bit 1 mask. */ #define OSC_PLLSRC1_bp 7 /* Clock Source bit 1 position. */ #define OSC_PLLDIV_bm 0x20 /* Divide by 2 bit mask. */ #define OSC_PLLDIV_bp 5 /* Divide by 2 bit position. */ #define OSC_PLLFAC_gm 0x1F /* Multiplication Factor group mask. */ #define OSC_PLLFAC_gp 0 /* Multiplication Factor group position. */ #define OSC_PLLFAC0_bm (1<<0) /* Multiplication Factor bit 0 mask. */ #define OSC_PLLFAC0_bp 0 /* Multiplication Factor bit 0 position. */ #define OSC_PLLFAC1_bm (1<<1) /* Multiplication Factor bit 1 mask. */ #define OSC_PLLFAC1_bp 1 /* Multiplication Factor bit 1 position. */ #define OSC_PLLFAC2_bm (1<<2) /* Multiplication Factor bit 2 mask. */ #define OSC_PLLFAC2_bp 2 /* Multiplication Factor bit 2 position. */ #define OSC_PLLFAC3_bm (1<<3) /* Multiplication Factor bit 3 mask. */ #define OSC_PLLFAC3_bp 3 /* Multiplication Factor bit 3 position. */ #define OSC_PLLFAC4_bm (1<<4) /* Multiplication Factor bit 4 mask. */ #define OSC_PLLFAC4_bp 4 /* Multiplication Factor bit 4 position. */ /* OSC.DFLLCTRL bit masks and bit positions */ #define OSC_RC32MCREF_gm 0x06 /* 32 MHz DFLL Calibration Reference group mask. */ #define OSC_RC32MCREF_gp 1 /* 32 MHz DFLL Calibration Reference group position. */ #define OSC_RC32MCREF0_bm (1<<1) /* 32 MHz DFLL Calibration Reference bit 0 mask. */ #define OSC_RC32MCREF0_bp 1 /* 32 MHz DFLL Calibration Reference bit 0 position. */ #define OSC_RC32MCREF1_bm (1<<2) /* 32 MHz DFLL Calibration Reference bit 1 mask. */ #define OSC_RC32MCREF1_bp 2 /* 32 MHz DFLL Calibration Reference bit 1 position. */ #define OSC_RC2MCREF_bm 0x01 /* 2 MHz DFLL Calibration Reference bit mask. */ #define OSC_RC2MCREF_bp 0 /* 2 MHz DFLL Calibration Reference bit position. */ /* DFLL - DFLL */ /* DFLL.CTRL bit masks and bit positions */ #define DFLL_ENABLE_bm 0x01 /* DFLL Enable bit mask. */ #define DFLL_ENABLE_bp 0 /* DFLL Enable bit position. */ /* DFLL.CALA bit masks and bit positions */ #define DFLL_CALL_gm 0x7F /* DFLL Calibration Value A group mask. */ #define DFLL_CALL_gp 0 /* DFLL Calibration Value A group position. */ #define DFLL_CALL0_bm (1<<0) /* DFLL Calibration Value A bit 0 mask. */ #define DFLL_CALL0_bp 0 /* DFLL Calibration Value A bit 0 position. */ #define DFLL_CALL1_bm (1<<1) /* DFLL Calibration Value A bit 1 mask. */ #define DFLL_CALL1_bp 1 /* DFLL Calibration Value A bit 1 position. */ #define DFLL_CALL2_bm (1<<2) /* DFLL Calibration Value A bit 2 mask. */ #define DFLL_CALL2_bp 2 /* DFLL Calibration Value A bit 2 position. */ #define DFLL_CALL3_bm (1<<3) /* DFLL Calibration Value A bit 3 mask. */ #define DFLL_CALL3_bp 3 /* DFLL Calibration Value A bit 3 position. */ #define DFLL_CALL4_bm (1<<4) /* DFLL Calibration Value A bit 4 mask. */ #define DFLL_CALL4_bp 4 /* DFLL Calibration Value A bit 4 position. */ #define DFLL_CALL5_bm (1<<5) /* DFLL Calibration Value A bit 5 mask. */ #define DFLL_CALL5_bp 5 /* DFLL Calibration Value A bit 5 position. */ #define DFLL_CALL6_bm (1<<6) /* DFLL Calibration Value A bit 6 mask. */ #define DFLL_CALL6_bp 6 /* DFLL Calibration Value A bit 6 position. */ /* DFLL.CALB bit masks and bit positions */ #define DFLL_CALH_gm 0x3F /* DFLL Calibration Value B group mask. */ #define DFLL_CALH_gp 0 /* DFLL Calibration Value B group position. */ #define DFLL_CALH0_bm (1<<0) /* DFLL Calibration Value B bit 0 mask. */ #define DFLL_CALH0_bp 0 /* DFLL Calibration Value B bit 0 position. */ #define DFLL_CALH1_bm (1<<1) /* DFLL Calibration Value B bit 1 mask. */ #define DFLL_CALH1_bp 1 /* DFLL Calibration Value B bit 1 position. */ #define DFLL_CALH2_bm (1<<2) /* DFLL Calibration Value B bit 2 mask. */ #define DFLL_CALH2_bp 2 /* DFLL Calibration Value B bit 2 position. */ #define DFLL_CALH3_bm (1<<3) /* DFLL Calibration Value B bit 3 mask. */ #define DFLL_CALH3_bp 3 /* DFLL Calibration Value B bit 3 position. */ #define DFLL_CALH4_bm (1<<4) /* DFLL Calibration Value B bit 4 mask. */ #define DFLL_CALH4_bp 4 /* DFLL Calibration Value B bit 4 position. */ #define DFLL_CALH5_bm (1<<5) /* DFLL Calibration Value B bit 5 mask. */ #define DFLL_CALH5_bp 5 /* DFLL Calibration Value B bit 5 position. */ /* RST - Reset */ /* RST.STATUS bit masks and bit positions */ #define RST_SDRF_bm 0x40 /* Spike Detection Reset Flag bit mask. */ #define RST_SDRF_bp 6 /* Spike Detection Reset Flag bit position. */ #define RST_SRF_bm 0x20 /* Software Reset Flag bit mask. */ #define RST_SRF_bp 5 /* Software Reset Flag bit position. */ #define RST_PDIRF_bm 0x10 /* Programming and Debug Interface Interface Reset Flag bit mask. */ #define RST_PDIRF_bp 4 /* Programming and Debug Interface Interface Reset Flag bit position. */ #define RST_WDRF_bm 0x08 /* Watchdog Reset Flag bit mask. */ #define RST_WDRF_bp 3 /* Watchdog Reset Flag bit position. */ #define RST_BORF_bm 0x04 /* Brown-out Reset Flag bit mask. */ #define RST_BORF_bp 2 /* Brown-out Reset Flag bit position. */ #define RST_EXTRF_bm 0x02 /* External Reset Flag bit mask. */ #define RST_EXTRF_bp 1 /* External Reset Flag bit position. */ #define RST_PORF_bm 0x01 /* Power-on Reset Flag bit mask. */ #define RST_PORF_bp 0 /* Power-on Reset Flag bit position. */ /* RST.CTRL bit masks and bit positions */ #define RST_SWRST_bm 0x01 /* Software Reset bit mask. */ #define RST_SWRST_bp 0 /* Software Reset bit position. */ /* WDT - Watch-Dog Timer */ /* WDT.CTRL bit masks and bit positions */ #define WDT_PER_gm 0x3C /* Period group mask. */ #define WDT_PER_gp 2 /* Period group position. */ #define WDT_PER0_bm (1<<2) /* Period bit 0 mask. */ #define WDT_PER0_bp 2 /* Period bit 0 position. */ #define WDT_PER1_bm (1<<3) /* Period bit 1 mask. */ #define WDT_PER1_bp 3 /* Period bit 1 position. */ #define WDT_PER2_bm (1<<4) /* Period bit 2 mask. */ #define WDT_PER2_bp 4 /* Period bit 2 position. */ #define WDT_PER3_bm (1<<5) /* Period bit 3 mask. */ #define WDT_PER3_bp 5 /* Period bit 3 position. */ #define WDT_ENABLE_bm 0x02 /* Enable bit mask. */ #define WDT_ENABLE_bp 1 /* Enable bit position. */ #define WDT_CEN_bm 0x01 /* Change Enable bit mask. */ #define WDT_CEN_bp 0 /* Change Enable bit position. */ /* WDT.WINCTRL bit masks and bit positions */ #define WDT_WPER_gm 0x3C /* Windowed Mode Period group mask. */ #define WDT_WPER_gp 2 /* Windowed Mode Period group position. */ #define WDT_WPER0_bm (1<<2) /* Windowed Mode Period bit 0 mask. */ #define WDT_WPER0_bp 2 /* Windowed Mode Period bit 0 position. */ #define WDT_WPER1_bm (1<<3) /* Windowed Mode Period bit 1 mask. */ #define WDT_WPER1_bp 3 /* Windowed Mode Period bit 1 position. */ #define WDT_WPER2_bm (1<<4) /* Windowed Mode Period bit 2 mask. */ #define WDT_WPER2_bp 4 /* Windowed Mode Period bit 2 position. */ #define WDT_WPER3_bm (1<<5) /* Windowed Mode Period bit 3 mask. */ #define WDT_WPER3_bp 5 /* Windowed Mode Period bit 3 position. */ #define WDT_WEN_bm 0x02 /* Windowed Mode Enable bit mask. */ #define WDT_WEN_bp 1 /* Windowed Mode Enable bit position. */ #define WDT_WCEN_bm 0x01 /* Windowed Mode Change Enable bit mask. */ #define WDT_WCEN_bp 0 /* Windowed Mode Change Enable bit position. */ /* WDT.STATUS bit masks and bit positions */ #define WDT_SYNCBUSY_bm 0x01 /* Syncronization busy bit mask. */ #define WDT_SYNCBUSY_bp 0 /* Syncronization busy bit position. */ /* MCU - MCU Control */ /* MCU.ANAINIT bit masks and bit positions */ #define MCU_STARTUPDLYA_gm 0x03 /* Analog startup delay Port A group mask. */ #define MCU_STARTUPDLYA_gp 0 /* Analog startup delay Port A group position. */ #define MCU_STARTUPDLYA0_bm (1<<0) /* Analog startup delay Port A bit 0 mask. */ #define MCU_STARTUPDLYA0_bp 0 /* Analog startup delay Port A bit 0 position. */ #define MCU_STARTUPDLYA1_bm (1<<1) /* Analog startup delay Port A bit 1 mask. */ #define MCU_STARTUPDLYA1_bp 1 /* Analog startup delay Port A bit 1 position. */ /* MCU.EVSYSLOCK bit masks and bit positions */ #define MCU_EVSYS0LOCK_bm 0x01 /* Event Channel 0-3 Lock bit mask. */ #define MCU_EVSYS0LOCK_bp 0 /* Event Channel 0-3 Lock bit position. */ /* MCU.AWEXLOCK bit masks and bit positions */ #define MCU_AWEXCLOCK_bm 0x01 /* AWeX on T/C C0 Lock bit mask. */ #define MCU_AWEXCLOCK_bp 0 /* AWeX on T/C C0 Lock bit position. */ /* PMIC - Programmable Multi-level Interrupt Controller */ /* PMIC.STATUS bit masks and bit positions */ #define PMIC_NMIEX_bm 0x80 /* Non-maskable Interrupt Executing bit mask. */ #define PMIC_NMIEX_bp 7 /* Non-maskable Interrupt Executing bit position. */ #define PMIC_HILVLEX_bm 0x04 /* High Level Interrupt Executing bit mask. */ #define PMIC_HILVLEX_bp 2 /* High Level Interrupt Executing bit position. */ #define PMIC_MEDLVLEX_bm 0x02 /* Medium Level Interrupt Executing bit mask. */ #define PMIC_MEDLVLEX_bp 1 /* Medium Level Interrupt Executing bit position. */ #define PMIC_LOLVLEX_bm 0x01 /* Low Level Interrupt Executing bit mask. */ #define PMIC_LOLVLEX_bp 0 /* Low Level Interrupt Executing bit position. */ /* PMIC.INTPRI bit masks and bit positions */ #define PMIC_INTPRI_gm 0xFF /* Interrupt Priority group mask. */ #define PMIC_INTPRI_gp 0 /* Interrupt Priority group position. */ #define PMIC_INTPRI0_bm (1<<0) /* Interrupt Priority bit 0 mask. */ #define PMIC_INTPRI0_bp 0 /* Interrupt Priority bit 0 position. */ #define PMIC_INTPRI1_bm (1<<1) /* Interrupt Priority bit 1 mask. */ #define PMIC_INTPRI1_bp 1 /* Interrupt Priority bit 1 position. */ #define PMIC_INTPRI2_bm (1<<2) /* Interrupt Priority bit 2 mask. */ #define PMIC_INTPRI2_bp 2 /* Interrupt Priority bit 2 position. */ #define PMIC_INTPRI3_bm (1<<3) /* Interrupt Priority bit 3 mask. */ #define PMIC_INTPRI3_bp 3 /* Interrupt Priority bit 3 position. */ #define PMIC_INTPRI4_bm (1<<4) /* Interrupt Priority bit 4 mask. */ #define PMIC_INTPRI4_bp 4 /* Interrupt Priority bit 4 position. */ #define PMIC_INTPRI5_bm (1<<5) /* Interrupt Priority bit 5 mask. */ #define PMIC_INTPRI5_bp 5 /* Interrupt Priority bit 5 position. */ #define PMIC_INTPRI6_bm (1<<6) /* Interrupt Priority bit 6 mask. */ #define PMIC_INTPRI6_bp 6 /* Interrupt Priority bit 6 position. */ #define PMIC_INTPRI7_bm (1<<7) /* Interrupt Priority bit 7 mask. */ #define PMIC_INTPRI7_bp 7 /* Interrupt Priority bit 7 position. */ /* PMIC.CTRL bit masks and bit positions */ #define PMIC_RREN_bm 0x80 /* Round-Robin Priority Enable bit mask. */ #define PMIC_RREN_bp 7 /* Round-Robin Priority Enable bit position. */ #define PMIC_IVSEL_bm 0x40 /* Interrupt Vector Select bit mask. */ #define PMIC_IVSEL_bp 6 /* Interrupt Vector Select bit position. */ #define PMIC_HILVLEN_bm 0x04 /* High Level Enable bit mask. */ #define PMIC_HILVLEN_bp 2 /* High Level Enable bit position. */ #define PMIC_MEDLVLEN_bm 0x02 /* Medium Level Enable bit mask. */ #define PMIC_MEDLVLEN_bp 1 /* Medium Level Enable bit position. */ #define PMIC_LOLVLEN_bm 0x01 /* Low Level Enable bit mask. */ #define PMIC_LOLVLEN_bp 0 /* Low Level Enable bit position. */ /* PORTCFG - Port Configuration */ /* PORTCFG.VPCTRLA bit masks and bit positions */ #define PORTCFG_VP1MAP_gm 0xF0 /* Virtual Port 1 Mapping group mask. */ #define PORTCFG_VP1MAP_gp 4 /* Virtual Port 1 Mapping group position. */ #define PORTCFG_VP1MAP0_bm (1<<4) /* Virtual Port 1 Mapping bit 0 mask. */ #define PORTCFG_VP1MAP0_bp 4 /* Virtual Port 1 Mapping bit 0 position. */ #define PORTCFG_VP1MAP1_bm (1<<5) /* Virtual Port 1 Mapping bit 1 mask. */ #define PORTCFG_VP1MAP1_bp 5 /* Virtual Port 1 Mapping bit 1 position. */ #define PORTCFG_VP1MAP2_bm (1<<6) /* Virtual Port 1 Mapping bit 2 mask. */ #define PORTCFG_VP1MAP2_bp 6 /* Virtual Port 1 Mapping bit 2 position. */ #define PORTCFG_VP1MAP3_bm (1<<7) /* Virtual Port 1 Mapping bit 3 mask. */ #define PORTCFG_VP1MAP3_bp 7 /* Virtual Port 1 Mapping bit 3 position. */ #define PORTCFG_VP0MAP_gm 0x0F /* Virtual Port 0 Mapping group mask. */ #define PORTCFG_VP0MAP_gp 0 /* Virtual Port 0 Mapping group position. */ #define PORTCFG_VP0MAP0_bm (1<<0) /* Virtual Port 0 Mapping bit 0 mask. */ #define PORTCFG_VP0MAP0_bp 0 /* Virtual Port 0 Mapping bit 0 position. */ #define PORTCFG_VP0MAP1_bm (1<<1) /* Virtual Port 0 Mapping bit 1 mask. */ #define PORTCFG_VP0MAP1_bp 1 /* Virtual Port 0 Mapping bit 1 position. */ #define PORTCFG_VP0MAP2_bm (1<<2) /* Virtual Port 0 Mapping bit 2 mask. */ #define PORTCFG_VP0MAP2_bp 2 /* Virtual Port 0 Mapping bit 2 position. */ #define PORTCFG_VP0MAP3_bm (1<<3) /* Virtual Port 0 Mapping bit 3 mask. */ #define PORTCFG_VP0MAP3_bp 3 /* Virtual Port 0 Mapping bit 3 position. */ /* PORTCFG.VPCTRLB bit masks and bit positions */ #define PORTCFG_VP3MAP_gm 0xF0 /* Virtual Port 3 Mapping group mask. */ #define PORTCFG_VP3MAP_gp 4 /* Virtual Port 3 Mapping group position. */ #define PORTCFG_VP3MAP0_bm (1<<4) /* Virtual Port 3 Mapping bit 0 mask. */ #define PORTCFG_VP3MAP0_bp 4 /* Virtual Port 3 Mapping bit 0 position. */ #define PORTCFG_VP3MAP1_bm (1<<5) /* Virtual Port 3 Mapping bit 1 mask. */ #define PORTCFG_VP3MAP1_bp 5 /* Virtual Port 3 Mapping bit 1 position. */ #define PORTCFG_VP3MAP2_bm (1<<6) /* Virtual Port 3 Mapping bit 2 mask. */ #define PORTCFG_VP3MAP2_bp 6 /* Virtual Port 3 Mapping bit 2 position. */ #define PORTCFG_VP3MAP3_bm (1<<7) /* Virtual Port 3 Mapping bit 3 mask. */ #define PORTCFG_VP3MAP3_bp 7 /* Virtual Port 3 Mapping bit 3 position. */ #define PORTCFG_VP2MAP_gm 0x0F /* Virtual Port 2 Mapping group mask. */ #define PORTCFG_VP2MAP_gp 0 /* Virtual Port 2 Mapping group position. */ #define PORTCFG_VP2MAP0_bm (1<<0) /* Virtual Port 2 Mapping bit 0 mask. */ #define PORTCFG_VP2MAP0_bp 0 /* Virtual Port 2 Mapping bit 0 position. */ #define PORTCFG_VP2MAP1_bm (1<<1) /* Virtual Port 2 Mapping bit 1 mask. */ #define PORTCFG_VP2MAP1_bp 1 /* Virtual Port 2 Mapping bit 1 position. */ #define PORTCFG_VP2MAP2_bm (1<<2) /* Virtual Port 2 Mapping bit 2 mask. */ #define PORTCFG_VP2MAP2_bp 2 /* Virtual Port 2 Mapping bit 2 position. */ #define PORTCFG_VP2MAP3_bm (1<<3) /* Virtual Port 2 Mapping bit 3 mask. */ #define PORTCFG_VP2MAP3_bp 3 /* Virtual Port 2 Mapping bit 3 position. */ /* PORTCFG.CLKEVOUT bit masks and bit positions */ #define PORTCFG_CLKOUT_gm 0x03 /* Peripheral Clock Output Port group mask. */ #define PORTCFG_CLKOUT_gp 0 /* Peripheral Clock Output Port group position. */ #define PORTCFG_CLKOUT0_bm (1<<0) /* Peripheral Clock Output Port bit 0 mask. */ #define PORTCFG_CLKOUT0_bp 0 /* Peripheral Clock Output Port bit 0 position. */ #define PORTCFG_CLKOUT1_bm (1<<1) /* Peripheral Clock Output Port bit 1 mask. */ #define PORTCFG_CLKOUT1_bp 1 /* Peripheral Clock Output Port bit 1 position. */ #define PORTCFG_CLKOUTSEL_gm 0x0C /* Peripheral Clock Output Select group mask. */ #define PORTCFG_CLKOUTSEL_gp 2 /* Peripheral Clock Output Select group position. */ #define PORTCFG_CLKOUTSEL0_bm (1<<2) /* Peripheral Clock Output Select bit 0 mask. */ #define PORTCFG_CLKOUTSEL0_bp 2 /* Peripheral Clock Output Select bit 0 position. */ #define PORTCFG_CLKOUTSEL1_bm (1<<3) /* Peripheral Clock Output Select bit 1 mask. */ #define PORTCFG_CLKOUTSEL1_bp 3 /* Peripheral Clock Output Select bit 1 position. */ #define PORTCFG_EVOUT_gm 0x30 /* Event Output Port group mask. */ #define PORTCFG_EVOUT_gp 4 /* Event Output Port group position. */ #define PORTCFG_EVOUT0_bm (1<<4) /* Event Output Port bit 0 mask. */ #define PORTCFG_EVOUT0_bp 4 /* Event Output Port bit 0 position. */ #define PORTCFG_EVOUT1_bm (1<<5) /* Event Output Port bit 1 mask. */ #define PORTCFG_EVOUT1_bp 5 /* Event Output Port bit 1 position. */ #define PORTCFG_RTCOUT_bm 0x40 /* RTC Clock Output bit mask. */ #define PORTCFG_RTCOUT_bp 6 /* RTC Clock Output bit position. */ #define PORTCFG_CLKEVPIN_bm 0x80 /* Peripheral Clock and Event Output pin Select bit mask. */ #define PORTCFG_CLKEVPIN_bp 7 /* Peripheral Clock and Event Output pin Select bit position. */ /* PORTCFG.EVOUTSEL bit masks and bit positions */ #define PORTCFG_EVOUTSEL_gm 0x07 /* Event Output Select group mask. */ #define PORTCFG_EVOUTSEL_gp 0 /* Event Output Select group position. */ #define PORTCFG_EVOUTSEL0_bm (1<<0) /* Event Output Select bit 0 mask. */ #define PORTCFG_EVOUTSEL0_bp 0 /* Event Output Select bit 0 position. */ #define PORTCFG_EVOUTSEL1_bm (1<<1) /* Event Output Select bit 1 mask. */ #define PORTCFG_EVOUTSEL1_bp 1 /* Event Output Select bit 1 position. */ #define PORTCFG_EVOUTSEL2_bm (1<<2) /* Event Output Select bit 2 mask. */ #define PORTCFG_EVOUTSEL2_bp 2 /* Event Output Select bit 2 position. */ /* CRC - Cyclic Redundancy Checker */ /* CRC.CTRL bit masks and bit positions */ #define CRC_RESET_gm 0xC0 /* Reset group mask. */ #define CRC_RESET_gp 6 /* Reset group position. */ #define CRC_RESET0_bm (1<<6) /* Reset bit 0 mask. */ #define CRC_RESET0_bp 6 /* Reset bit 0 position. */ #define CRC_RESET1_bm (1<<7) /* Reset bit 1 mask. */ #define CRC_RESET1_bp 7 /* Reset bit 1 position. */ #define CRC_CRC32_bm 0x20 /* CRC Mode bit mask. */ #define CRC_CRC32_bp 5 /* CRC Mode bit position. */ #define CRC_SOURCE_gm 0x0F /* Input Source group mask. */ #define CRC_SOURCE_gp 0 /* Input Source group position. */ #define CRC_SOURCE0_bm (1<<0) /* Input Source bit 0 mask. */ #define CRC_SOURCE0_bp 0 /* Input Source bit 0 position. */ #define CRC_SOURCE1_bm (1<<1) /* Input Source bit 1 mask. */ #define CRC_SOURCE1_bp 1 /* Input Source bit 1 position. */ #define CRC_SOURCE2_bm (1<<2) /* Input Source bit 2 mask. */ #define CRC_SOURCE2_bp 2 /* Input Source bit 2 position. */ #define CRC_SOURCE3_bm (1<<3) /* Input Source bit 3 mask. */ #define CRC_SOURCE3_bp 3 /* Input Source bit 3 position. */ /* CRC.STATUS bit masks and bit positions */ #define CRC_ZERO_bm 0x02 /* Zero detection bit mask. */ #define CRC_ZERO_bp 1 /* Zero detection bit position. */ #define CRC_BUSY_bm 0x01 /* Busy bit mask. */ #define CRC_BUSY_bp 0 /* Busy bit position. */ /* EVSYS - Event System */ /* EVSYS.CH0MUX bit masks and bit positions */ #define EVSYS_CHMUX_gm 0xFF /* Event Channel 0 Multiplexer group mask. */ #define EVSYS_CHMUX_gp 0 /* Event Channel 0 Multiplexer group position. */ #define EVSYS_CHMUX0_bm (1<<0) /* Event Channel 0 Multiplexer bit 0 mask. */ #define EVSYS_CHMUX0_bp 0 /* Event Channel 0 Multiplexer bit 0 position. */ #define EVSYS_CHMUX1_bm (1<<1) /* Event Channel 0 Multiplexer bit 1 mask. */ #define EVSYS_CHMUX1_bp 1 /* Event Channel 0 Multiplexer bit 1 position. */ #define EVSYS_CHMUX2_bm (1<<2) /* Event Channel 0 Multiplexer bit 2 mask. */ #define EVSYS_CHMUX2_bp 2 /* Event Channel 0 Multiplexer bit 2 position. */ #define EVSYS_CHMUX3_bm (1<<3) /* Event Channel 0 Multiplexer bit 3 mask. */ #define EVSYS_CHMUX3_bp 3 /* Event Channel 0 Multiplexer bit 3 position. */ #define EVSYS_CHMUX4_bm (1<<4) /* Event Channel 0 Multiplexer bit 4 mask. */ #define EVSYS_CHMUX4_bp 4 /* Event Channel 0 Multiplexer bit 4 position. */ #define EVSYS_CHMUX5_bm (1<<5) /* Event Channel 0 Multiplexer bit 5 mask. */ #define EVSYS_CHMUX5_bp 5 /* Event Channel 0 Multiplexer bit 5 position. */ #define EVSYS_CHMUX6_bm (1<<6) /* Event Channel 0 Multiplexer bit 6 mask. */ #define EVSYS_CHMUX6_bp 6 /* Event Channel 0 Multiplexer bit 6 position. */ #define EVSYS_CHMUX7_bm (1<<7) /* Event Channel 0 Multiplexer bit 7 mask. */ #define EVSYS_CHMUX7_bp 7 /* Event Channel 0 Multiplexer bit 7 position. */ /* EVSYS.CH1MUX bit masks and bit positions */ /* EVSYS_CHMUX Predefined. */ /* EVSYS_CHMUX Predefined. */ /* EVSYS.CH2MUX bit masks and bit positions */ /* EVSYS_CHMUX Predefined. */ /* EVSYS_CHMUX Predefined. */ /* EVSYS.CH3MUX bit masks and bit positions */ /* EVSYS_CHMUX Predefined. */ /* EVSYS_CHMUX Predefined. */ /* EVSYS.CH0CTRL bit masks and bit positions */ #define EVSYS_QDIRM_gm 0x60 /* Quadrature Decoder Index Recognition Mode group mask. */ #define EVSYS_QDIRM_gp 5 /* Quadrature Decoder Index Recognition Mode group position. */ #define EVSYS_QDIRM0_bm (1<<5) /* Quadrature Decoder Index Recognition Mode bit 0 mask. */ #define EVSYS_QDIRM0_bp 5 /* Quadrature Decoder Index Recognition Mode bit 0 position. */ #define EVSYS_QDIRM1_bm (1<<6) /* Quadrature Decoder Index Recognition Mode bit 1 mask. */ #define EVSYS_QDIRM1_bp 6 /* Quadrature Decoder Index Recognition Mode bit 1 position. */ #define EVSYS_QDIEN_bm 0x10 /* Quadrature Decoder Index Enable bit mask. */ #define EVSYS_QDIEN_bp 4 /* Quadrature Decoder Index Enable bit position. */ #define EVSYS_QDEN_bm 0x08 /* Quadrature Decoder Enable bit mask. */ #define EVSYS_QDEN_bp 3 /* Quadrature Decoder Enable bit position. */ #define EVSYS_DIGFILT_gm 0x07 /* Digital Filter group mask. */ #define EVSYS_DIGFILT_gp 0 /* Digital Filter group position. */ #define EVSYS_DIGFILT0_bm (1<<0) /* Digital Filter bit 0 mask. */ #define EVSYS_DIGFILT0_bp 0 /* Digital Filter bit 0 position. */ #define EVSYS_DIGFILT1_bm (1<<1) /* Digital Filter bit 1 mask. */ #define EVSYS_DIGFILT1_bp 1 /* Digital Filter bit 1 position. */ #define EVSYS_DIGFILT2_bm (1<<2) /* Digital Filter bit 2 mask. */ #define EVSYS_DIGFILT2_bp 2 /* Digital Filter bit 2 position. */ /* EVSYS.CH1CTRL bit masks and bit positions */ /* EVSYS_DIGFILT Predefined. */ /* EVSYS_DIGFILT Predefined. */ /* EVSYS.CH2CTRL bit masks and bit positions */ /* EVSYS_DIGFILT Predefined. */ /* EVSYS_DIGFILT Predefined. */ /* EVSYS.CH3CTRL bit masks and bit positions */ /* EVSYS_DIGFILT Predefined. */ /* EVSYS_DIGFILT Predefined. */ /* NVM - Non Volatile Memory Controller */ /* NVM.CMD bit masks and bit positions */ #define NVM_CMD_gm 0x7F /* Command group mask. */ #define NVM_CMD_gp 0 /* Command group position. */ #define NVM_CMD0_bm (1<<0) /* Command bit 0 mask. */ #define NVM_CMD0_bp 0 /* Command bit 0 position. */ #define NVM_CMD1_bm (1<<1) /* Command bit 1 mask. */ #define NVM_CMD1_bp 1 /* Command bit 1 position. */ #define NVM_CMD2_bm (1<<2) /* Command bit 2 mask. */ #define NVM_CMD2_bp 2 /* Command bit 2 position. */ #define NVM_CMD3_bm (1<<3) /* Command bit 3 mask. */ #define NVM_CMD3_bp 3 /* Command bit 3 position. */ #define NVM_CMD4_bm (1<<4) /* Command bit 4 mask. */ #define NVM_CMD4_bp 4 /* Command bit 4 position. */ #define NVM_CMD5_bm (1<<5) /* Command bit 5 mask. */ #define NVM_CMD5_bp 5 /* Command bit 5 position. */ #define NVM_CMD6_bm (1<<6) /* Command bit 6 mask. */ #define NVM_CMD6_bp 6 /* Command bit 6 position. */ /* NVM.CTRLA bit masks and bit positions */ #define NVM_CMDEX_bm 0x01 /* Command Execute bit mask. */ #define NVM_CMDEX_bp 0 /* Command Execute bit position. */ /* NVM.CTRLB bit masks and bit positions */ #define NVM_EEMAPEN_bm 0x08 /* EEPROM Mapping Enable bit mask. */ #define NVM_EEMAPEN_bp 3 /* EEPROM Mapping Enable bit position. */ #define NVM_FPRM_bm 0x04 /* Flash Power Reduction Enable bit mask. */ #define NVM_FPRM_bp 2 /* Flash Power Reduction Enable bit position. */ #define NVM_EPRM_bm 0x02 /* EEPROM Power Reduction Enable bit mask. */ #define NVM_EPRM_bp 1 /* EEPROM Power Reduction Enable bit position. */ #define NVM_SPMLOCK_bm 0x01 /* SPM Lock bit mask. */ #define NVM_SPMLOCK_bp 0 /* SPM Lock bit position. */ /* NVM.INTCTRL bit masks and bit positions */ #define NVM_SPMLVL_gm 0x0C /* SPM Interrupt Level group mask. */ #define NVM_SPMLVL_gp 2 /* SPM Interrupt Level group position. */ #define NVM_SPMLVL0_bm (1<<2) /* SPM Interrupt Level bit 0 mask. */ #define NVM_SPMLVL0_bp 2 /* SPM Interrupt Level bit 0 position. */ #define NVM_SPMLVL1_bm (1<<3) /* SPM Interrupt Level bit 1 mask. */ #define NVM_SPMLVL1_bp 3 /* SPM Interrupt Level bit 1 position. */ #define NVM_EELVL_gm 0x03 /* EEPROM Interrupt Level group mask. */ #define NVM_EELVL_gp 0 /* EEPROM Interrupt Level group position. */ #define NVM_EELVL0_bm (1<<0) /* EEPROM Interrupt Level bit 0 mask. */ #define NVM_EELVL0_bp 0 /* EEPROM Interrupt Level bit 0 position. */ #define NVM_EELVL1_bm (1<<1) /* EEPROM Interrupt Level bit 1 mask. */ #define NVM_EELVL1_bp 1 /* EEPROM Interrupt Level bit 1 position. */ /* NVM.STATUS bit masks and bit positions */ #define NVM_NVMBUSY_bm 0x80 /* Non-volatile Memory Busy bit mask. */ #define NVM_NVMBUSY_bp 7 /* Non-volatile Memory Busy bit position. */ #define NVM_FBUSY_bm 0x40 /* Flash Memory Busy bit mask. */ #define NVM_FBUSY_bp 6 /* Flash Memory Busy bit position. */ #define NVM_EELOAD_bm 0x02 /* EEPROM Page Buffer Active Loading bit mask. */ #define NVM_EELOAD_bp 1 /* EEPROM Page Buffer Active Loading bit position. */ #define NVM_FLOAD_bm 0x01 /* Flash Page Buffer Active Loading bit mask. */ #define NVM_FLOAD_bp 0 /* Flash Page Buffer Active Loading bit position. */ /* NVM.LOCKBITS bit masks and bit positions */ #define NVM_BLBB_gm 0xC0 /* Boot Lock Bits - Boot Section group mask. */ #define NVM_BLBB_gp 6 /* Boot Lock Bits - Boot Section group position. */ #define NVM_BLBB0_bm (1<<6) /* Boot Lock Bits - Boot Section bit 0 mask. */ #define NVM_BLBB0_bp 6 /* Boot Lock Bits - Boot Section bit 0 position. */ #define NVM_BLBB1_bm (1<<7) /* Boot Lock Bits - Boot Section bit 1 mask. */ #define NVM_BLBB1_bp 7 /* Boot Lock Bits - Boot Section bit 1 position. */ #define NVM_BLBA_gm 0x30 /* Boot Lock Bits - Application Section group mask. */ #define NVM_BLBA_gp 4 /* Boot Lock Bits - Application Section group position. */ #define NVM_BLBA0_bm (1<<4) /* Boot Lock Bits - Application Section bit 0 mask. */ #define NVM_BLBA0_bp 4 /* Boot Lock Bits - Application Section bit 0 position. */ #define NVM_BLBA1_bm (1<<5) /* Boot Lock Bits - Application Section bit 1 mask. */ #define NVM_BLBA1_bp 5 /* Boot Lock Bits - Application Section bit 1 position. */ #define NVM_BLBAT_gm 0x0C /* Boot Lock Bits - Application Table group mask. */ #define NVM_BLBAT_gp 2 /* Boot Lock Bits - Application Table group position. */ #define NVM_BLBAT0_bm (1<<2) /* Boot Lock Bits - Application Table bit 0 mask. */ #define NVM_BLBAT0_bp 2 /* Boot Lock Bits - Application Table bit 0 position. */ #define NVM_BLBAT1_bm (1<<3) /* Boot Lock Bits - Application Table bit 1 mask. */ #define NVM_BLBAT1_bp 3 /* Boot Lock Bits - Application Table bit 1 position. */ #define NVM_LB_gm 0x03 /* Lock Bits group mask. */ #define NVM_LB_gp 0 /* Lock Bits group position. */ #define NVM_LB0_bm (1<<0) /* Lock Bits bit 0 mask. */ #define NVM_LB0_bp 0 /* Lock Bits bit 0 position. */ #define NVM_LB1_bm (1<<1) /* Lock Bits bit 1 mask. */ #define NVM_LB1_bp 1 /* Lock Bits bit 1 position. */ /* ADC - Analog/Digital Converter */ /* ADC_CH.CTRL bit masks and bit positions */ #define ADC_CH_START_bm 0x80 /* Channel Start Conversion bit mask. */ #define ADC_CH_START_bp 7 /* Channel Start Conversion bit position. */ #define ADC_CH_GAIN_gm 0x1C /* Gain Factor group mask. */ #define ADC_CH_GAIN_gp 2 /* Gain Factor group position. */ #define ADC_CH_GAIN0_bm (1<<2) /* Gain Factor bit 0 mask. */ #define ADC_CH_GAIN0_bp 2 /* Gain Factor bit 0 position. */ #define ADC_CH_GAIN1_bm (1<<3) /* Gain Factor bit 1 mask. */ #define ADC_CH_GAIN1_bp 3 /* Gain Factor bit 1 position. */ #define ADC_CH_GAIN2_bm (1<<4) /* Gain Factor bit 2 mask. */ #define ADC_CH_GAIN2_bp 4 /* Gain Factor bit 2 position. */ #define ADC_CH_INPUTMODE_gm 0x03 /* Input Mode Select group mask. */ #define ADC_CH_INPUTMODE_gp 0 /* Input Mode Select group position. */ #define ADC_CH_INPUTMODE0_bm (1<<0) /* Input Mode Select bit 0 mask. */ #define ADC_CH_INPUTMODE0_bp 0 /* Input Mode Select bit 0 position. */ #define ADC_CH_INPUTMODE1_bm (1<<1) /* Input Mode Select bit 1 mask. */ #define ADC_CH_INPUTMODE1_bp 1 /* Input Mode Select bit 1 position. */ /* ADC_CH.MUXCTRL bit masks and bit positions */ #define ADC_CH_MUXPOS_gm 0x78 /* MUX selection on Positive ADC input group mask. */ #define ADC_CH_MUXPOS_gp 3 /* MUX selection on Positive ADC input group position. */ #define ADC_CH_MUXPOS0_bm (1<<3) /* MUX selection on Positive ADC input bit 0 mask. */ #define ADC_CH_MUXPOS0_bp 3 /* MUX selection on Positive ADC input bit 0 position. */ #define ADC_CH_MUXPOS1_bm (1<<4) /* MUX selection on Positive ADC input bit 1 mask. */ #define ADC_CH_MUXPOS1_bp 4 /* MUX selection on Positive ADC input bit 1 position. */ #define ADC_CH_MUXPOS2_bm (1<<5) /* MUX selection on Positive ADC input bit 2 mask. */ #define ADC_CH_MUXPOS2_bp 5 /* MUX selection on Positive ADC input bit 2 position. */ #define ADC_CH_MUXPOS3_bm (1<<6) /* MUX selection on Positive ADC input bit 3 mask. */ #define ADC_CH_MUXPOS3_bp 6 /* MUX selection on Positive ADC input bit 3 position. */ #define ADC_CH_MUXINT_gm 0x78 /* MUX selection on Internal ADC input group mask. */ #define ADC_CH_MUXINT_gp 3 /* MUX selection on Internal ADC input group position. */ #define ADC_CH_MUXINT0_bm (1<<3) /* MUX selection on Internal ADC input bit 0 mask. */ #define ADC_CH_MUXINT0_bp 3 /* MUX selection on Internal ADC input bit 0 position. */ #define ADC_CH_MUXINT1_bm (1<<4) /* MUX selection on Internal ADC input bit 1 mask. */ #define ADC_CH_MUXINT1_bp 4 /* MUX selection on Internal ADC input bit 1 position. */ #define ADC_CH_MUXINT2_bm (1<<5) /* MUX selection on Internal ADC input bit 2 mask. */ #define ADC_CH_MUXINT2_bp 5 /* MUX selection on Internal ADC input bit 2 position. */ #define ADC_CH_MUXINT3_bm (1<<6) /* MUX selection on Internal ADC input bit 3 mask. */ #define ADC_CH_MUXINT3_bp 6 /* MUX selection on Internal ADC input bit 3 position. */ #define ADC_CH_MUXNEG_gm 0x03 /* MUX selection on Negative ADC input group mask. */ #define ADC_CH_MUXNEG_gp 0 /* MUX selection on Negative ADC input group position. */ #define ADC_CH_MUXNEG0_bm (1<<0) /* MUX selection on Negative ADC input bit 0 mask. */ #define ADC_CH_MUXNEG0_bp 0 /* MUX selection on Negative ADC input bit 0 position. */ #define ADC_CH_MUXNEG1_bm (1<<1) /* MUX selection on Negative ADC input bit 1 mask. */ #define ADC_CH_MUXNEG1_bp 1 /* MUX selection on Negative ADC input bit 1 position. */ /* ADC_CH.INTCTRL bit masks and bit positions */ #define ADC_CH_INTMODE_gm 0x0C /* Interrupt Mode group mask. */ #define ADC_CH_INTMODE_gp 2 /* Interrupt Mode group position. */ #define ADC_CH_INTMODE0_bm (1<<2) /* Interrupt Mode bit 0 mask. */ #define ADC_CH_INTMODE0_bp 2 /* Interrupt Mode bit 0 position. */ #define ADC_CH_INTMODE1_bm (1<<3) /* Interrupt Mode bit 1 mask. */ #define ADC_CH_INTMODE1_bp 3 /* Interrupt Mode bit 1 position. */ #define ADC_CH_INTLVL_gm 0x03 /* Interrupt Level group mask. */ #define ADC_CH_INTLVL_gp 0 /* Interrupt Level group position. */ #define ADC_CH_INTLVL0_bm (1<<0) /* Interrupt Level bit 0 mask. */ #define ADC_CH_INTLVL0_bp 0 /* Interrupt Level bit 0 position. */ #define ADC_CH_INTLVL1_bm (1<<1) /* Interrupt Level bit 1 mask. */ #define ADC_CH_INTLVL1_bp 1 /* Interrupt Level bit 1 position. */ /* ADC_CH.INTFLAGS bit masks and bit positions */ #define ADC_CH_CHIF_bm 0x01 /* Channel Interrupt Flag bit mask. */ #define ADC_CH_CHIF_bp 0 /* Channel Interrupt Flag bit position. */ /* ADC_CH.SCAN bit masks and bit positions */ #define ADC_CH_OFFSET_gm 0xF0 /* Positive MUX setting offset group mask. */ #define ADC_CH_OFFSET_gp 4 /* Positive MUX setting offset group position. */ #define ADC_CH_OFFSET0_bm (1<<4) /* Positive MUX setting offset bit 0 mask. */ #define ADC_CH_OFFSET0_bp 4 /* Positive MUX setting offset bit 0 position. */ #define ADC_CH_OFFSET1_bm (1<<5) /* Positive MUX setting offset bit 1 mask. */ #define ADC_CH_OFFSET1_bp 5 /* Positive MUX setting offset bit 1 position. */ #define ADC_CH_OFFSET2_bm (1<<6) /* Positive MUX setting offset bit 2 mask. */ #define ADC_CH_OFFSET2_bp 6 /* Positive MUX setting offset bit 2 position. */ #define ADC_CH_OFFSET3_bm (1<<7) /* Positive MUX setting offset bit 3 mask. */ #define ADC_CH_OFFSET3_bp 7 /* Positive MUX setting offset bit 3 position. */ #define ADC_CH_SCANNUM_gm 0x0F /* Number of Channels included in scan group mask. */ #define ADC_CH_SCANNUM_gp 0 /* Number of Channels included in scan group position. */ #define ADC_CH_SCANNUM0_bm (1<<0) /* Number of Channels included in scan bit 0 mask. */ #define ADC_CH_SCANNUM0_bp 0 /* Number of Channels included in scan bit 0 position. */ #define ADC_CH_SCANNUM1_bm (1<<1) /* Number of Channels included in scan bit 1 mask. */ #define ADC_CH_SCANNUM1_bp 1 /* Number of Channels included in scan bit 1 position. */ #define ADC_CH_SCANNUM2_bm (1<<2) /* Number of Channels included in scan bit 2 mask. */ #define ADC_CH_SCANNUM2_bp 2 /* Number of Channels included in scan bit 2 position. */ #define ADC_CH_SCANNUM3_bm (1<<3) /* Number of Channels included in scan bit 3 mask. */ #define ADC_CH_SCANNUM3_bp 3 /* Number of Channels included in scan bit 3 position. */ /* ADC.CTRLA bit masks and bit positions */ #define ADC_CH0START_bm 0x04 /* Channel 0 Start Conversion bit mask. */ #define ADC_CH0START_bp 2 /* Channel 0 Start Conversion bit position. */ #define ADC_FLUSH_bm 0x02 /* ADC Flush bit mask. */ #define ADC_FLUSH_bp 1 /* ADC Flush bit position. */ #define ADC_ENABLE_bm 0x01 /* Enable ADC bit mask. */ #define ADC_ENABLE_bp 0 /* Enable ADC bit position. */ /* ADC.CTRLB bit masks and bit positions */ #define ADC_CURRLIMIT_gm 0x60 /* Current Limitation group mask. */ #define ADC_CURRLIMIT_gp 5 /* Current Limitation group position. */ #define ADC_CURRLIMIT0_bm (1<<5) /* Current Limitation bit 0 mask. */ #define ADC_CURRLIMIT0_bp 5 /* Current Limitation bit 0 position. */ #define ADC_CURRLIMIT1_bm (1<<6) /* Current Limitation bit 1 mask. */ #define ADC_CURRLIMIT1_bp 6 /* Current Limitation bit 1 position. */ #define ADC_CONMODE_bm 0x10 /* Conversion Mode bit mask. */ #define ADC_CONMODE_bp 4 /* Conversion Mode bit position. */ #define ADC_FREERUN_bm 0x08 /* Free Running Mode Enable bit mask. */ #define ADC_FREERUN_bp 3 /* Free Running Mode Enable bit position. */ #define ADC_RESOLUTION_gm 0x06 /* Result Resolution group mask. */ #define ADC_RESOLUTION_gp 1 /* Result Resolution group position. */ #define ADC_RESOLUTION0_bm (1<<1) /* Result Resolution bit 0 mask. */ #define ADC_RESOLUTION0_bp 1 /* Result Resolution bit 0 position. */ #define ADC_RESOLUTION1_bm (1<<2) /* Result Resolution bit 1 mask. */ #define ADC_RESOLUTION1_bp 2 /* Result Resolution bit 1 position. */ /* ADC.REFCTRL bit masks and bit positions */ #define ADC_REFSEL_gm 0x70 /* Reference Selection group mask. */ #define ADC_REFSEL_gp 4 /* Reference Selection group position. */ #define ADC_REFSEL0_bm (1<<4) /* Reference Selection bit 0 mask. */ #define ADC_REFSEL0_bp 4 /* Reference Selection bit 0 position. */ #define ADC_REFSEL1_bm (1<<5) /* Reference Selection bit 1 mask. */ #define ADC_REFSEL1_bp 5 /* Reference Selection bit 1 position. */ #define ADC_REFSEL2_bm (1<<6) /* Reference Selection bit 2 mask. */ #define ADC_REFSEL2_bp 6 /* Reference Selection bit 2 position. */ #define ADC_BANDGAP_bm 0x02 /* Bandgap enable bit mask. */ #define ADC_BANDGAP_bp 1 /* Bandgap enable bit position. */ #define ADC_TEMPREF_bm 0x01 /* Temperature Reference Enable bit mask. */ #define ADC_TEMPREF_bp 0 /* Temperature Reference Enable bit position. */ /* ADC.EVCTRL bit masks and bit positions */ #define ADC_EVSEL_gm 0x18 /* Event Input Select group mask. */ #define ADC_EVSEL_gp 3 /* Event Input Select group position. */ #define ADC_EVSEL0_bm (1<<3) /* Event Input Select bit 0 mask. */ #define ADC_EVSEL0_bp 3 /* Event Input Select bit 0 position. */ #define ADC_EVSEL1_bm (1<<4) /* Event Input Select bit 1 mask. */ #define ADC_EVSEL1_bp 4 /* Event Input Select bit 1 position. */ #define ADC_EVACT_gm 0x07 /* Event Action Select group mask. */ #define ADC_EVACT_gp 0 /* Event Action Select group position. */ #define ADC_EVACT0_bm (1<<0) /* Event Action Select bit 0 mask. */ #define ADC_EVACT0_bp 0 /* Event Action Select bit 0 position. */ #define ADC_EVACT1_bm (1<<1) /* Event Action Select bit 1 mask. */ #define ADC_EVACT1_bp 1 /* Event Action Select bit 1 position. */ #define ADC_EVACT2_bm (1<<2) /* Event Action Select bit 2 mask. */ #define ADC_EVACT2_bp 2 /* Event Action Select bit 2 position. */ /* ADC.PRESCALER bit masks and bit positions */ #define ADC_PRESCALER_gm 0x07 /* Clock Prescaler Selection group mask. */ #define ADC_PRESCALER_gp 0 /* Clock Prescaler Selection group position. */ #define ADC_PRESCALER0_bm (1<<0) /* Clock Prescaler Selection bit 0 mask. */ #define ADC_PRESCALER0_bp 0 /* Clock Prescaler Selection bit 0 position. */ #define ADC_PRESCALER1_bm (1<<1) /* Clock Prescaler Selection bit 1 mask. */ #define ADC_PRESCALER1_bp 1 /* Clock Prescaler Selection bit 1 position. */ #define ADC_PRESCALER2_bm (1<<2) /* Clock Prescaler Selection bit 2 mask. */ #define ADC_PRESCALER2_bp 2 /* Clock Prescaler Selection bit 2 position. */ /* ADC.INTFLAGS bit masks and bit positions */ #define ADC_CH0IF_bm 0x01 /* Channel 0 Interrupt Flag bit mask. */ #define ADC_CH0IF_bp 0 /* Channel 0 Interrupt Flag bit position. */ /* AC - Analog Comparator */ /* AC.AC0CTRL bit masks and bit positions */ #define AC_INTMODE_gm 0xC0 /* Interrupt Mode group mask. */ #define AC_INTMODE_gp 6 /* Interrupt Mode group position. */ #define AC_INTMODE0_bm (1<<6) /* Interrupt Mode bit 0 mask. */ #define AC_INTMODE0_bp 6 /* Interrupt Mode bit 0 position. */ #define AC_INTMODE1_bm (1<<7) /* Interrupt Mode bit 1 mask. */ #define AC_INTMODE1_bp 7 /* Interrupt Mode bit 1 position. */ #define AC_INTLVL_gm 0x30 /* Interrupt Level group mask. */ #define AC_INTLVL_gp 4 /* Interrupt Level group position. */ #define AC_INTLVL0_bm (1<<4) /* Interrupt Level bit 0 mask. */ #define AC_INTLVL0_bp 4 /* Interrupt Level bit 0 position. */ #define AC_INTLVL1_bm (1<<5) /* Interrupt Level bit 1 mask. */ #define AC_INTLVL1_bp 5 /* Interrupt Level bit 1 position. */ #define AC_HYSMODE_gm 0x06 /* Hysteresis Mode group mask. */ #define AC_HYSMODE_gp 1 /* Hysteresis Mode group position. */ #define AC_HYSMODE0_bm (1<<1) /* Hysteresis Mode bit 0 mask. */ #define AC_HYSMODE0_bp 1 /* Hysteresis Mode bit 0 position. */ #define AC_HYSMODE1_bm (1<<2) /* Hysteresis Mode bit 1 mask. */ #define AC_HYSMODE1_bp 2 /* Hysteresis Mode bit 1 position. */ #define AC_ENABLE_bm 0x01 /* Enable bit mask. */ #define AC_ENABLE_bp 0 /* Enable bit position. */ /* AC.AC1CTRL bit masks and bit positions */ /* AC_INTMODE Predefined. */ /* AC_INTMODE Predefined. */ /* AC_INTLVL Predefined. */ /* AC_INTLVL Predefined. */ /* AC_HYSMODE Predefined. */ /* AC_HYSMODE Predefined. */ /* AC_ENABLE Predefined. */ /* AC_ENABLE Predefined. */ /* AC.AC0MUXCTRL bit masks and bit positions */ #define AC_MUXPOS_gm 0x38 /* MUX Positive Input group mask. */ #define AC_MUXPOS_gp 3 /* MUX Positive Input group position. */ #define AC_MUXPOS0_bm (1<<3) /* MUX Positive Input bit 0 mask. */ #define AC_MUXPOS0_bp 3 /* MUX Positive Input bit 0 position. */ #define AC_MUXPOS1_bm (1<<4) /* MUX Positive Input bit 1 mask. */ #define AC_MUXPOS1_bp 4 /* MUX Positive Input bit 1 position. */ #define AC_MUXPOS2_bm (1<<5) /* MUX Positive Input bit 2 mask. */ #define AC_MUXPOS2_bp 5 /* MUX Positive Input bit 2 position. */ #define AC_MUXNEG_gm 0x07 /* MUX Negative Input group mask. */ #define AC_MUXNEG_gp 0 /* MUX Negative Input group position. */ #define AC_MUXNEG0_bm (1<<0) /* MUX Negative Input bit 0 mask. */ #define AC_MUXNEG0_bp 0 /* MUX Negative Input bit 0 position. */ #define AC_MUXNEG1_bm (1<<1) /* MUX Negative Input bit 1 mask. */ #define AC_MUXNEG1_bp 1 /* MUX Negative Input bit 1 position. */ #define AC_MUXNEG2_bm (1<<2) /* MUX Negative Input bit 2 mask. */ #define AC_MUXNEG2_bp 2 /* MUX Negative Input bit 2 position. */ /* AC.AC1MUXCTRL bit masks and bit positions */ /* AC_MUXPOS Predefined. */ /* AC_MUXPOS Predefined. */ /* AC_MUXNEG Predefined. */ /* AC_MUXNEG Predefined. */ /* AC.CTRLA bit masks and bit positions */ #define AC_AC1OUT_bm 0x02 /* Analog Comparator 1 Output Enable bit mask. */ #define AC_AC1OUT_bp 1 /* Analog Comparator 1 Output Enable bit position. */ #define AC_AC0OUT_bm 0x01 /* Analog Comparator 0 Output Enable bit mask. */ #define AC_AC0OUT_bp 0 /* Analog Comparator 0 Output Enable bit position. */ /* AC.CTRLB bit masks and bit positions */ #define AC_SCALEFAC_gm 0x3F /* VCC Voltage Scaler Factor group mask. */ #define AC_SCALEFAC_gp 0 /* VCC Voltage Scaler Factor group position. */ #define AC_SCALEFAC0_bm (1<<0) /* VCC Voltage Scaler Factor bit 0 mask. */ #define AC_SCALEFAC0_bp 0 /* VCC Voltage Scaler Factor bit 0 position. */ #define AC_SCALEFAC1_bm (1<<1) /* VCC Voltage Scaler Factor bit 1 mask. */ #define AC_SCALEFAC1_bp 1 /* VCC Voltage Scaler Factor bit 1 position. */ #define AC_SCALEFAC2_bm (1<<2) /* VCC Voltage Scaler Factor bit 2 mask. */ #define AC_SCALEFAC2_bp 2 /* VCC Voltage Scaler Factor bit 2 position. */ #define AC_SCALEFAC3_bm (1<<3) /* VCC Voltage Scaler Factor bit 3 mask. */ #define AC_SCALEFAC3_bp 3 /* VCC Voltage Scaler Factor bit 3 position. */ #define AC_SCALEFAC4_bm (1<<4) /* VCC Voltage Scaler Factor bit 4 mask. */ #define AC_SCALEFAC4_bp 4 /* VCC Voltage Scaler Factor bit 4 position. */ #define AC_SCALEFAC5_bm (1<<5) /* VCC Voltage Scaler Factor bit 5 mask. */ #define AC_SCALEFAC5_bp 5 /* VCC Voltage Scaler Factor bit 5 position. */ /* AC.WINCTRL bit masks and bit positions */ #define AC_WEN_bm 0x10 /* Window Mode Enable bit mask. */ #define AC_WEN_bp 4 /* Window Mode Enable bit position. */ #define AC_WINTMODE_gm 0x0C /* Window Interrupt Mode group mask. */ #define AC_WINTMODE_gp 2 /* Window Interrupt Mode group position. */ #define AC_WINTMODE0_bm (1<<2) /* Window Interrupt Mode bit 0 mask. */ #define AC_WINTMODE0_bp 2 /* Window Interrupt Mode bit 0 position. */ #define AC_WINTMODE1_bm (1<<3) /* Window Interrupt Mode bit 1 mask. */ #define AC_WINTMODE1_bp 3 /* Window Interrupt Mode bit 1 position. */ #define AC_WINTLVL_gm 0x03 /* Window Interrupt Level group mask. */ #define AC_WINTLVL_gp 0 /* Window Interrupt Level group position. */ #define AC_WINTLVL0_bm (1<<0) /* Window Interrupt Level bit 0 mask. */ #define AC_WINTLVL0_bp 0 /* Window Interrupt Level bit 0 position. */ #define AC_WINTLVL1_bm (1<<1) /* Window Interrupt Level bit 1 mask. */ #define AC_WINTLVL1_bp 1 /* Window Interrupt Level bit 1 position. */ /* AC.STATUS bit masks and bit positions */ #define AC_WSTATE_gm 0xC0 /* Window Mode State group mask. */ #define AC_WSTATE_gp 6 /* Window Mode State group position. */ #define AC_WSTATE0_bm (1<<6) /* Window Mode State bit 0 mask. */ #define AC_WSTATE0_bp 6 /* Window Mode State bit 0 position. */ #define AC_WSTATE1_bm (1<<7) /* Window Mode State bit 1 mask. */ #define AC_WSTATE1_bp 7 /* Window Mode State bit 1 position. */ #define AC_AC1STATE_bm 0x20 /* Analog Comparator 1 State bit mask. */ #define AC_AC1STATE_bp 5 /* Analog Comparator 1 State bit position. */ #define AC_AC0STATE_bm 0x10 /* Analog Comparator 0 State bit mask. */ #define AC_AC0STATE_bp 4 /* Analog Comparator 0 State bit position. */ #define AC_WIF_bm 0x04 /* Window Mode Interrupt Flag bit mask. */ #define AC_WIF_bp 2 /* Window Mode Interrupt Flag bit position. */ #define AC_AC1IF_bm 0x02 /* Analog Comparator 1 Interrupt Flag bit mask. */ #define AC_AC1IF_bp 1 /* Analog Comparator 1 Interrupt Flag bit position. */ #define AC_AC0IF_bm 0x01 /* Analog Comparator 0 Interrupt Flag bit mask. */ #define AC_AC0IF_bp 0 /* Analog Comparator 0 Interrupt Flag bit position. */ /* RTC - Real-Time Counter */ /* RTC.CTRL bit masks and bit positions */ #define RTC_PRESCALER_gm 0x07 /* Prescaling Factor group mask. */ #define RTC_PRESCALER_gp 0 /* Prescaling Factor group position. */ #define RTC_PRESCALER0_bm (1<<0) /* Prescaling Factor bit 0 mask. */ #define RTC_PRESCALER0_bp 0 /* Prescaling Factor bit 0 position. */ #define RTC_PRESCALER1_bm (1<<1) /* Prescaling Factor bit 1 mask. */ #define RTC_PRESCALER1_bp 1 /* Prescaling Factor bit 1 position. */ #define RTC_PRESCALER2_bm (1<<2) /* Prescaling Factor bit 2 mask. */ #define RTC_PRESCALER2_bp 2 /* Prescaling Factor bit 2 position. */ /* RTC.STATUS bit masks and bit positions */ #define RTC_SYNCBUSY_bm 0x01 /* Synchronization Busy Flag bit mask. */ #define RTC_SYNCBUSY_bp 0 /* Synchronization Busy Flag bit position. */ /* RTC.INTCTRL bit masks and bit positions */ #define RTC_COMPINTLVL_gm 0x0C /* Compare Match Interrupt Level group mask. */ #define RTC_COMPINTLVL_gp 2 /* Compare Match Interrupt Level group position. */ #define RTC_COMPINTLVL0_bm (1<<2) /* Compare Match Interrupt Level bit 0 mask. */ #define RTC_COMPINTLVL0_bp 2 /* Compare Match Interrupt Level bit 0 position. */ #define RTC_COMPINTLVL1_bm (1<<3) /* Compare Match Interrupt Level bit 1 mask. */ #define RTC_COMPINTLVL1_bp 3 /* Compare Match Interrupt Level bit 1 position. */ #define RTC_OVFINTLVL_gm 0x03 /* Overflow Interrupt Level group mask. */ #define RTC_OVFINTLVL_gp 0 /* Overflow Interrupt Level group position. */ #define RTC_OVFINTLVL0_bm (1<<0) /* Overflow Interrupt Level bit 0 mask. */ #define RTC_OVFINTLVL0_bp 0 /* Overflow Interrupt Level bit 0 position. */ #define RTC_OVFINTLVL1_bm (1<<1) /* Overflow Interrupt Level bit 1 mask. */ #define RTC_OVFINTLVL1_bp 1 /* Overflow Interrupt Level bit 1 position. */ /* RTC.INTFLAGS bit masks and bit positions */ #define RTC_COMPIF_bm 0x02 /* Compare Match Interrupt Flag bit mask. */ #define RTC_COMPIF_bp 1 /* Compare Match Interrupt Flag bit position. */ #define RTC_OVFIF_bm 0x01 /* Overflow Interrupt Flag bit mask. */ #define RTC_OVFIF_bp 0 /* Overflow Interrupt Flag bit position. */ /* TWI - Two-Wire Interface */ /* TWI_MASTER.CTRLA bit masks and bit positions */ #define TWI_MASTER_INTLVL_gm 0xC0 /* Interrupt Level group mask. */ #define TWI_MASTER_INTLVL_gp 6 /* Interrupt Level group position. */ #define TWI_MASTER_INTLVL0_bm (1<<6) /* Interrupt Level bit 0 mask. */ #define TWI_MASTER_INTLVL0_bp 6 /* Interrupt Level bit 0 position. */ #define TWI_MASTER_INTLVL1_bm (1<<7) /* Interrupt Level bit 1 mask. */ #define TWI_MASTER_INTLVL1_bp 7 /* Interrupt Level bit 1 position. */ #define TWI_MASTER_RIEN_bm 0x20 /* Read Interrupt Enable bit mask. */ #define TWI_MASTER_RIEN_bp 5 /* Read Interrupt Enable bit position. */ #define TWI_MASTER_WIEN_bm 0x10 /* Write Interrupt Enable bit mask. */ #define TWI_MASTER_WIEN_bp 4 /* Write Interrupt Enable bit position. */ #define TWI_MASTER_ENABLE_bm 0x08 /* Enable TWI Master bit mask. */ #define TWI_MASTER_ENABLE_bp 3 /* Enable TWI Master bit position. */ /* TWI_MASTER.CTRLB bit masks and bit positions */ #define TWI_MASTER_TIMEOUT_gm 0x0C /* Inactive Bus Timeout group mask. */ #define TWI_MASTER_TIMEOUT_gp 2 /* Inactive Bus Timeout group position. */ #define TWI_MASTER_TIMEOUT0_bm (1<<2) /* Inactive Bus Timeout bit 0 mask. */ #define TWI_MASTER_TIMEOUT0_bp 2 /* Inactive Bus Timeout bit 0 position. */ #define TWI_MASTER_TIMEOUT1_bm (1<<3) /* Inactive Bus Timeout bit 1 mask. */ #define TWI_MASTER_TIMEOUT1_bp 3 /* Inactive Bus Timeout bit 1 position. */ #define TWI_MASTER_QCEN_bm 0x02 /* Quick Command Enable bit mask. */ #define TWI_MASTER_QCEN_bp 1 /* Quick Command Enable bit position. */ #define TWI_MASTER_SMEN_bm 0x01 /* Smart Mode Enable bit mask. */ #define TWI_MASTER_SMEN_bp 0 /* Smart Mode Enable bit position. */ /* TWI_MASTER.CTRLC bit masks and bit positions */ #define TWI_MASTER_ACKACT_bm 0x04 /* Acknowledge Action bit mask. */ #define TWI_MASTER_ACKACT_bp 2 /* Acknowledge Action bit position. */ #define TWI_MASTER_CMD_gm 0x03 /* Command group mask. */ #define TWI_MASTER_CMD_gp 0 /* Command group position. */ #define TWI_MASTER_CMD0_bm (1<<0) /* Command bit 0 mask. */ #define TWI_MASTER_CMD0_bp 0 /* Command bit 0 position. */ #define TWI_MASTER_CMD1_bm (1<<1) /* Command bit 1 mask. */ #define TWI_MASTER_CMD1_bp 1 /* Command bit 1 position. */ /* TWI_MASTER.STATUS bit masks and bit positions */ #define TWI_MASTER_RIF_bm 0x80 /* Read Interrupt Flag bit mask. */ #define TWI_MASTER_RIF_bp 7 /* Read Interrupt Flag bit position. */ #define TWI_MASTER_WIF_bm 0x40 /* Write Interrupt Flag bit mask. */ #define TWI_MASTER_WIF_bp 6 /* Write Interrupt Flag bit position. */ #define TWI_MASTER_CLKHOLD_bm 0x20 /* Clock Hold bit mask. */ #define TWI_MASTER_CLKHOLD_bp 5 /* Clock Hold bit position. */ #define TWI_MASTER_RXACK_bm 0x10 /* Received Acknowledge bit mask. */ #define TWI_MASTER_RXACK_bp 4 /* Received Acknowledge bit position. */ #define TWI_MASTER_ARBLOST_bm 0x08 /* Arbitration Lost bit mask. */ #define TWI_MASTER_ARBLOST_bp 3 /* Arbitration Lost bit position. */ #define TWI_MASTER_BUSERR_bm 0x04 /* Bus Error bit mask. */ #define TWI_MASTER_BUSERR_bp 2 /* Bus Error bit position. */ #define TWI_MASTER_BUSSTATE_gm 0x03 /* Bus State group mask. */ #define TWI_MASTER_BUSSTATE_gp 0 /* Bus State group position. */ #define TWI_MASTER_BUSSTATE0_bm (1<<0) /* Bus State bit 0 mask. */ #define TWI_MASTER_BUSSTATE0_bp 0 /* Bus State bit 0 position. */ #define TWI_MASTER_BUSSTATE1_bm (1<<1) /* Bus State bit 1 mask. */ #define TWI_MASTER_BUSSTATE1_bp 1 /* Bus State bit 1 position. */ /* TWI_SLAVE.CTRLA bit masks and bit positions */ #define TWI_SLAVE_INTLVL_gm 0xC0 /* Interrupt Level group mask. */ #define TWI_SLAVE_INTLVL_gp 6 /* Interrupt Level group position. */ #define TWI_SLAVE_INTLVL0_bm (1<<6) /* Interrupt Level bit 0 mask. */ #define TWI_SLAVE_INTLVL0_bp 6 /* Interrupt Level bit 0 position. */ #define TWI_SLAVE_INTLVL1_bm (1<<7) /* Interrupt Level bit 1 mask. */ #define TWI_SLAVE_INTLVL1_bp 7 /* Interrupt Level bit 1 position. */ #define TWI_SLAVE_DIEN_bm 0x20 /* Data Interrupt Enable bit mask. */ #define TWI_SLAVE_DIEN_bp 5 /* Data Interrupt Enable bit position. */ #define TWI_SLAVE_APIEN_bm 0x10 /* Address/Stop Interrupt Enable bit mask. */ #define TWI_SLAVE_APIEN_bp 4 /* Address/Stop Interrupt Enable bit position. */ #define TWI_SLAVE_ENABLE_bm 0x08 /* Enable TWI Slave bit mask. */ #define TWI_SLAVE_ENABLE_bp 3 /* Enable TWI Slave bit position. */ #define TWI_SLAVE_PIEN_bm 0x04 /* Stop Interrupt Enable bit mask. */ #define TWI_SLAVE_PIEN_bp 2 /* Stop Interrupt Enable bit position. */ #define TWI_SLAVE_PMEN_bm 0x02 /* Promiscuous Mode Enable bit mask. */ #define TWI_SLAVE_PMEN_bp 1 /* Promiscuous Mode Enable bit position. */ #define TWI_SLAVE_SMEN_bm 0x01 /* Smart Mode Enable bit mask. */ #define TWI_SLAVE_SMEN_bp 0 /* Smart Mode Enable bit position. */ /* TWI_SLAVE.CTRLB bit masks and bit positions */ #define TWI_SLAVE_ACKACT_bm 0x04 /* Acknowledge Action bit mask. */ #define TWI_SLAVE_ACKACT_bp 2 /* Acknowledge Action bit position. */ #define TWI_SLAVE_CMD_gm 0x03 /* Command group mask. */ #define TWI_SLAVE_CMD_gp 0 /* Command group position. */ #define TWI_SLAVE_CMD0_bm (1<<0) /* Command bit 0 mask. */ #define TWI_SLAVE_CMD0_bp 0 /* Command bit 0 position. */ #define TWI_SLAVE_CMD1_bm (1<<1) /* Command bit 1 mask. */ #define TWI_SLAVE_CMD1_bp 1 /* Command bit 1 position. */ /* TWI_SLAVE.STATUS bit masks and bit positions */ #define TWI_SLAVE_DIF_bm 0x80 /* Data Interrupt Flag bit mask. */ #define TWI_SLAVE_DIF_bp 7 /* Data Interrupt Flag bit position. */ #define TWI_SLAVE_APIF_bm 0x40 /* Address/Stop Interrupt Flag bit mask. */ #define TWI_SLAVE_APIF_bp 6 /* Address/Stop Interrupt Flag bit position. */ #define TWI_SLAVE_CLKHOLD_bm 0x20 /* Clock Hold bit mask. */ #define TWI_SLAVE_CLKHOLD_bp 5 /* Clock Hold bit position. */ #define TWI_SLAVE_RXACK_bm 0x10 /* Received Acknowledge bit mask. */ #define TWI_SLAVE_RXACK_bp 4 /* Received Acknowledge bit position. */ #define TWI_SLAVE_COLL_bm 0x08 /* Collision bit mask. */ #define TWI_SLAVE_COLL_bp 3 /* Collision bit position. */ #define TWI_SLAVE_BUSERR_bm 0x04 /* Bus Error bit mask. */ #define TWI_SLAVE_BUSERR_bp 2 /* Bus Error bit position. */ #define TWI_SLAVE_DIR_bm 0x02 /* Read/Write Direction bit mask. */ #define TWI_SLAVE_DIR_bp 1 /* Read/Write Direction bit position. */ #define TWI_SLAVE_AP_bm 0x01 /* Slave Address or Stop bit mask. */ #define TWI_SLAVE_AP_bp 0 /* Slave Address or Stop bit position. */ /* TWI_SLAVE.ADDRMASK bit masks and bit positions */ #define TWI_SLAVE_ADDRMASK_gm 0xFE /* Address Mask group mask. */ #define TWI_SLAVE_ADDRMASK_gp 1 /* Address Mask group position. */ #define TWI_SLAVE_ADDRMASK0_bm (1<<1) /* Address Mask bit 0 mask. */ #define TWI_SLAVE_ADDRMASK0_bp 1 /* Address Mask bit 0 position. */ #define TWI_SLAVE_ADDRMASK1_bm (1<<2) /* Address Mask bit 1 mask. */ #define TWI_SLAVE_ADDRMASK1_bp 2 /* Address Mask bit 1 position. */ #define TWI_SLAVE_ADDRMASK2_bm (1<<3) /* Address Mask bit 2 mask. */ #define TWI_SLAVE_ADDRMASK2_bp 3 /* Address Mask bit 2 position. */ #define TWI_SLAVE_ADDRMASK3_bm (1<<4) /* Address Mask bit 3 mask. */ #define TWI_SLAVE_ADDRMASK3_bp 4 /* Address Mask bit 3 position. */ #define TWI_SLAVE_ADDRMASK4_bm (1<<5) /* Address Mask bit 4 mask. */ #define TWI_SLAVE_ADDRMASK4_bp 5 /* Address Mask bit 4 position. */ #define TWI_SLAVE_ADDRMASK5_bm (1<<6) /* Address Mask bit 5 mask. */ #define TWI_SLAVE_ADDRMASK5_bp 6 /* Address Mask bit 5 position. */ #define TWI_SLAVE_ADDRMASK6_bm (1<<7) /* Address Mask bit 6 mask. */ #define TWI_SLAVE_ADDRMASK6_bp 7 /* Address Mask bit 6 position. */ #define TWI_SLAVE_ADDREN_bm 0x01 /* Address Enable bit mask. */ #define TWI_SLAVE_ADDREN_bp 0 /* Address Enable bit position. */ /* TWI.CTRL bit masks and bit positions */ #define TWI_SDAHOLD_gm 0x06 /* SDA Hold Time Enable group mask. */ #define TWI_SDAHOLD_gp 1 /* SDA Hold Time Enable group position. */ #define TWI_SDAHOLD0_bm (1<<1) /* SDA Hold Time Enable bit 0 mask. */ #define TWI_SDAHOLD0_bp 1 /* SDA Hold Time Enable bit 0 position. */ #define TWI_SDAHOLD1_bm (1<<2) /* SDA Hold Time Enable bit 1 mask. */ #define TWI_SDAHOLD1_bp 2 /* SDA Hold Time Enable bit 1 position. */ #define TWI_EDIEN_bm 0x01 /* External Driver Interface Enable bit mask. */ #define TWI_EDIEN_bp 0 /* External Driver Interface Enable bit position. */ /* USB - USB */ /* USB_EP.STATUS bit masks and bit positions */ #define USB_EP_STALLF_bm 0x80 /* Endpoint Stall Flag bit mask. */ #define USB_EP_STALLF_bp 7 /* Endpoint Stall Flag bit position. */ #define USB_EP_CRC_bm 0x80 /* CRC Error Flag bit mask. */ #define USB_EP_CRC_bp 7 /* CRC Error Flag bit position. */ #define USB_EP_UNF_bm 0x40 /* Underflow Enpoint FLag bit mask. */ #define USB_EP_UNF_bp 6 /* Underflow Enpoint FLag bit position. */ #define USB_EP_OVF_bm 0x40 /* Overflow Enpoint Flag for Output Endpoints bit mask. */ #define USB_EP_OVF_bp 6 /* Overflow Enpoint Flag for Output Endpoints bit position. */ #define USB_EP_TRNCOMPL0_bm 0x20 /* Transaction Complete 0 Flag bit mask. */ #define USB_EP_TRNCOMPL0_bp 5 /* Transaction Complete 0 Flag bit position. */ #define USB_EP_TRNCOMPL1_bm 0x10 /* Transaction Complete 1 Flag bit mask. */ #define USB_EP_TRNCOMPL1_bp 4 /* Transaction Complete 1 Flag bit position. */ #define USB_EP_SETUP_bm 0x10 /* SETUP Transaction Complete Flag bit mask. */ #define USB_EP_SETUP_bp 4 /* SETUP Transaction Complete Flag bit position. */ #define USB_EP_BANK_bm 0x08 /* Bank Select bit mask. */ #define USB_EP_BANK_bp 3 /* Bank Select bit position. */ #define USB_EP_BUSNACK1_bm 0x04 /* Data Buffer 1 Not Acknowledge bit mask. */ #define USB_EP_BUSNACK1_bp 2 /* Data Buffer 1 Not Acknowledge bit position. */ #define USB_EP_BUSNACK0_bm 0x02 /* Data Buffer 0 Not Acknowledge bit mask. */ #define USB_EP_BUSNACK0_bp 1 /* Data Buffer 0 Not Acknowledge bit position. */ #define USB_EP_TOGGLE_bm 0x01 /* Data Toggle bit mask. */ #define USB_EP_TOGGLE_bp 0 /* Data Toggle bit position. */ /* USB_EP.CTRL bit masks and bit positions */ #define USB_EP_TYPE_gm 0xC0 /* Endpoint Type group mask. */ #define USB_EP_TYPE_gp 6 /* Endpoint Type group position. */ #define USB_EP_TYPE0_bm (1<<6) /* Endpoint Type bit 0 mask. */ #define USB_EP_TYPE0_bp 6 /* Endpoint Type bit 0 position. */ #define USB_EP_TYPE1_bm (1<<7) /* Endpoint Type bit 1 mask. */ #define USB_EP_TYPE1_bp 7 /* Endpoint Type bit 1 position. */ #define USB_EP_MULTIPKT_bm 0x20 /* Multi Packet Transfer Enable bit mask. */ #define USB_EP_MULTIPKT_bp 5 /* Multi Packet Transfer Enable bit position. */ #define USB_EP_PINGPONG_bm 0x10 /* Ping-Pong Enable bit mask. */ #define USB_EP_PINGPONG_bp 4 /* Ping-Pong Enable bit position. */ #define USB_EP_INTDSBL_bm 0x08 /* Interrupt Disable bit mask. */ #define USB_EP_INTDSBL_bp 3 /* Interrupt Disable bit position. */ #define USB_EP_STALL_bm 0x04 /* Data Stall bit mask. */ #define USB_EP_STALL_bp 2 /* Data Stall bit position. */ #define USB_EP_BUFSIZE_gm 0x07 /* Data Buffer Size group mask. */ #define USB_EP_BUFSIZE_gp 0 /* Data Buffer Size group position. */ #define USB_EP_BUFSIZE0_bm (1<<0) /* Data Buffer Size bit 0 mask. */ #define USB_EP_BUFSIZE0_bp 0 /* Data Buffer Size bit 0 position. */ #define USB_EP_BUFSIZE1_bm (1<<1) /* Data Buffer Size bit 1 mask. */ #define USB_EP_BUFSIZE1_bp 1 /* Data Buffer Size bit 1 position. */ #define USB_EP_BUFSIZE2_bm (1<<2) /* Data Buffer Size bit 2 mask. */ #define USB_EP_BUFSIZE2_bp 2 /* Data Buffer Size bit 2 position. */ /* USB_EP.CNT bit masks and bit positions */ #define USB_EP_ZLP_bm 0x8000 /* Zero Length Packet bit mask. */ #define USB_EP_ZLP_bp 15 /* Zero Length Packet bit position. */ /* USB.CTRLA bit masks and bit positions */ #define USB_ENABLE_bm 0x80 /* USB Enable bit mask. */ #define USB_ENABLE_bp 7 /* USB Enable bit position. */ #define USB_SPEED_bm 0x40 /* Speed Select bit mask. */ #define USB_SPEED_bp 6 /* Speed Select bit position. */ #define USB_FIFOEN_bm 0x20 /* USB FIFO Enable bit mask. */ #define USB_FIFOEN_bp 5 /* USB FIFO Enable bit position. */ #define USB_STFRNUM_bm 0x10 /* Store Frame Number Enable bit mask. */ #define USB_STFRNUM_bp 4 /* Store Frame Number Enable bit position. */ #define USB_MAXEP_gm 0x0F /* Maximum Endpoint Addresses group mask. */ #define USB_MAXEP_gp 0 /* Maximum Endpoint Addresses group position. */ #define USB_MAXEP0_bm (1<<0) /* Maximum Endpoint Addresses bit 0 mask. */ #define USB_MAXEP0_bp 0 /* Maximum Endpoint Addresses bit 0 position. */ #define USB_MAXEP1_bm (1<<1) /* Maximum Endpoint Addresses bit 1 mask. */ #define USB_MAXEP1_bp 1 /* Maximum Endpoint Addresses bit 1 position. */ #define USB_MAXEP2_bm (1<<2) /* Maximum Endpoint Addresses bit 2 mask. */ #define USB_MAXEP2_bp 2 /* Maximum Endpoint Addresses bit 2 position. */ #define USB_MAXEP3_bm (1<<3) /* Maximum Endpoint Addresses bit 3 mask. */ #define USB_MAXEP3_bp 3 /* Maximum Endpoint Addresses bit 3 position. */ /* USB.CTRLB bit masks and bit positions */ #define USB_PULLRST_bm 0x10 /* Pull during Reset bit mask. */ #define USB_PULLRST_bp 4 /* Pull during Reset bit position. */ #define USB_RWAKEUP_bm 0x04 /* Remote Wake-up bit mask. */ #define USB_RWAKEUP_bp 2 /* Remote Wake-up bit position. */ #define USB_GNACK_bm 0x02 /* Global NACK bit mask. */ #define USB_GNACK_bp 1 /* Global NACK bit position. */ #define USB_ATTACH_bm 0x01 /* Attach bit mask. */ #define USB_ATTACH_bp 0 /* Attach bit position. */ /* USB.STATUS bit masks and bit positions */ #define USB_URESUME_bm 0x08 /* Upstream Resume bit mask. */ #define USB_URESUME_bp 3 /* Upstream Resume bit position. */ #define USB_RESUME_bm 0x04 /* Resume bit mask. */ #define USB_RESUME_bp 2 /* Resume bit position. */ #define USB_SUSPEND_bm 0x02 /* Bus Suspended bit mask. */ #define USB_SUSPEND_bp 1 /* Bus Suspended bit position. */ #define USB_BUSRST_bm 0x01 /* Bus Reset bit mask. */ #define USB_BUSRST_bp 0 /* Bus Reset bit position. */ /* USB.ADDR bit masks and bit positions */ #define USB_ADDR_gm 0x7F /* Device Address group mask. */ #define USB_ADDR_gp 0 /* Device Address group position. */ #define USB_ADDR0_bm (1<<0) /* Device Address bit 0 mask. */ #define USB_ADDR0_bp 0 /* Device Address bit 0 position. */ #define USB_ADDR1_bm (1<<1) /* Device Address bit 1 mask. */ #define USB_ADDR1_bp 1 /* Device Address bit 1 position. */ #define USB_ADDR2_bm (1<<2) /* Device Address bit 2 mask. */ #define USB_ADDR2_bp 2 /* Device Address bit 2 position. */ #define USB_ADDR3_bm (1<<3) /* Device Address bit 3 mask. */ #define USB_ADDR3_bp 3 /* Device Address bit 3 position. */ #define USB_ADDR4_bm (1<<4) /* Device Address bit 4 mask. */ #define USB_ADDR4_bp 4 /* Device Address bit 4 position. */ #define USB_ADDR5_bm (1<<5) /* Device Address bit 5 mask. */ #define USB_ADDR5_bp 5 /* Device Address bit 5 position. */ #define USB_ADDR6_bm (1<<6) /* Device Address bit 6 mask. */ #define USB_ADDR6_bp 6 /* Device Address bit 6 position. */ /* USB.FIFOWP bit masks and bit positions */ #define USB_FIFOWP_gm 0x1F /* FIFO Write Pointer group mask. */ #define USB_FIFOWP_gp 0 /* FIFO Write Pointer group position. */ #define USB_FIFOWP0_bm (1<<0) /* FIFO Write Pointer bit 0 mask. */ #define USB_FIFOWP0_bp 0 /* FIFO Write Pointer bit 0 position. */ #define USB_FIFOWP1_bm (1<<1) /* FIFO Write Pointer bit 1 mask. */ #define USB_FIFOWP1_bp 1 /* FIFO Write Pointer bit 1 position. */ #define USB_FIFOWP2_bm (1<<2) /* FIFO Write Pointer bit 2 mask. */ #define USB_FIFOWP2_bp 2 /* FIFO Write Pointer bit 2 position. */ #define USB_FIFOWP3_bm (1<<3) /* FIFO Write Pointer bit 3 mask. */ #define USB_FIFOWP3_bp 3 /* FIFO Write Pointer bit 3 position. */ #define USB_FIFOWP4_bm (1<<4) /* FIFO Write Pointer bit 4 mask. */ #define USB_FIFOWP4_bp 4 /* FIFO Write Pointer bit 4 position. */ /* USB.FIFORP bit masks and bit positions */ #define USB_FIFORP_gm 0x1F /* FIFO Read Pointer group mask. */ #define USB_FIFORP_gp 0 /* FIFO Read Pointer group position. */ #define USB_FIFORP0_bm (1<<0) /* FIFO Read Pointer bit 0 mask. */ #define USB_FIFORP0_bp 0 /* FIFO Read Pointer bit 0 position. */ #define USB_FIFORP1_bm (1<<1) /* FIFO Read Pointer bit 1 mask. */ #define USB_FIFORP1_bp 1 /* FIFO Read Pointer bit 1 position. */ #define USB_FIFORP2_bm (1<<2) /* FIFO Read Pointer bit 2 mask. */ #define USB_FIFORP2_bp 2 /* FIFO Read Pointer bit 2 position. */ #define USB_FIFORP3_bm (1<<3) /* FIFO Read Pointer bit 3 mask. */ #define USB_FIFORP3_bp 3 /* FIFO Read Pointer bit 3 position. */ #define USB_FIFORP4_bm (1<<4) /* FIFO Read Pointer bit 4 mask. */ #define USB_FIFORP4_bp 4 /* FIFO Read Pointer bit 4 position. */ /* USB.INTCTRLA bit masks and bit positions */ #define USB_SOFIE_bm 0x80 /* Start Of Frame Interrupt Enable bit mask. */ #define USB_SOFIE_bp 7 /* Start Of Frame Interrupt Enable bit position. */ #define USB_BUSEVIE_bm 0x40 /* Bus Event Interrupt Enable bit mask. */ #define USB_BUSEVIE_bp 6 /* Bus Event Interrupt Enable bit position. */ #define USB_BUSERRIE_bm 0x20 /* Bus Error Interrupt Enable bit mask. */ #define USB_BUSERRIE_bp 5 /* Bus Error Interrupt Enable bit position. */ #define USB_STALLIE_bm 0x10 /* STALL Interrupt Enable bit mask. */ #define USB_STALLIE_bp 4 /* STALL Interrupt Enable bit position. */ #define USB_INTLVL_gm 0x03 /* Interrupt Level group mask. */ #define USB_INTLVL_gp 0 /* Interrupt Level group position. */ #define USB_INTLVL0_bm (1<<0) /* Interrupt Level bit 0 mask. */ #define USB_INTLVL0_bp 0 /* Interrupt Level bit 0 position. */ #define USB_INTLVL1_bm (1<<1) /* Interrupt Level bit 1 mask. */ #define USB_INTLVL1_bp 1 /* Interrupt Level bit 1 position. */ /* USB.INTCTRLB bit masks and bit positions */ #define USB_TRNIE_bm 0x02 /* Transaction Complete Interrupt Enable bit mask. */ #define USB_TRNIE_bp 1 /* Transaction Complete Interrupt Enable bit position. */ #define USB_SETUPIE_bm 0x01 /* SETUP Transaction Complete Interrupt Enable bit mask. */ #define USB_SETUPIE_bp 0 /* SETUP Transaction Complete Interrupt Enable bit position. */ /* USB.INTFLAGSACLR bit masks and bit positions */ #define USB_SOFIF_bm 0x80 /* Start Of Frame Interrupt Flag bit mask. */ #define USB_SOFIF_bp 7 /* Start Of Frame Interrupt Flag bit position. */ #define USB_SUSPENDIF_bm 0x40 /* Suspend Interrupt Flag bit mask. */ #define USB_SUSPENDIF_bp 6 /* Suspend Interrupt Flag bit position. */ #define USB_RESUMEIF_bm 0x20 /* Resume Interrupt Flag bit mask. */ #define USB_RESUMEIF_bp 5 /* Resume Interrupt Flag bit position. */ #define USB_RSTIF_bm 0x10 /* Reset Interrupt Flag bit mask. */ #define USB_RSTIF_bp 4 /* Reset Interrupt Flag bit position. */ #define USB_CRCIF_bm 0x08 /* Isochronous CRC Error Interrupt Flag bit mask. */ #define USB_CRCIF_bp 3 /* Isochronous CRC Error Interrupt Flag bit position. */ #define USB_UNFIF_bm 0x04 /* Underflow Interrupt Flag bit mask. */ #define USB_UNFIF_bp 2 /* Underflow Interrupt Flag bit position. */ #define USB_OVFIF_bm 0x02 /* Overflow Interrupt Flag bit mask. */ #define USB_OVFIF_bp 1 /* Overflow Interrupt Flag bit position. */ #define USB_STALLIF_bm 0x01 /* STALL Interrupt Flag bit mask. */ #define USB_STALLIF_bp 0 /* STALL Interrupt Flag bit position. */ /* USB.INTFLAGSASET bit masks and bit positions */ /* USB_SOFIF Predefined. */ /* USB_SOFIF Predefined. */ /* USB_SUSPENDIF Predefined. */ /* USB_SUSPENDIF Predefined. */ /* USB_RESUMEIF Predefined. */ /* USB_RESUMEIF Predefined. */ /* USB_RSTIF Predefined. */ /* USB_RSTIF Predefined. */ /* USB_CRCIF Predefined. */ /* USB_CRCIF Predefined. */ /* USB_UNFIF Predefined. */ /* USB_UNFIF Predefined. */ /* USB_OVFIF Predefined. */ /* USB_OVFIF Predefined. */ /* USB_STALLIF Predefined. */ /* USB_STALLIF Predefined. */ /* USB.INTFLAGSBCLR bit masks and bit positions */ #define USB_TRNIF_bm 0x02 /* Transaction Complete Interrupt Flag bit mask. */ #define USB_TRNIF_bp 1 /* Transaction Complete Interrupt Flag bit position. */ #define USB_SETUPIF_bm 0x01 /* SETUP Transaction Complete Interrupt Flag bit mask. */ #define USB_SETUPIF_bp 0 /* SETUP Transaction Complete Interrupt Flag bit position. */ /* USB.INTFLAGSBSET bit masks and bit positions */ /* USB_TRNIF Predefined. */ /* USB_TRNIF Predefined. */ /* USB_SETUPIF Predefined. */ /* USB_SETUPIF Predefined. */ /* PORT - I/O Port Configuration */ /* PORT.INTCTRL bit masks and bit positions */ #define PORT_INT1LVL_gm 0x0C /* Port Interrupt 1 Level group mask. */ #define PORT_INT1LVL_gp 2 /* Port Interrupt 1 Level group position. */ #define PORT_INT1LVL0_bm (1<<2) /* Port Interrupt 1 Level bit 0 mask. */ #define PORT_INT1LVL0_bp 2 /* Port Interrupt 1 Level bit 0 position. */ #define PORT_INT1LVL1_bm (1<<3) /* Port Interrupt 1 Level bit 1 mask. */ #define PORT_INT1LVL1_bp 3 /* Port Interrupt 1 Level bit 1 position. */ #define PORT_INT0LVL_gm 0x03 /* Port Interrupt 0 Level group mask. */ #define PORT_INT0LVL_gp 0 /* Port Interrupt 0 Level group position. */ #define PORT_INT0LVL0_bm (1<<0) /* Port Interrupt 0 Level bit 0 mask. */ #define PORT_INT0LVL0_bp 0 /* Port Interrupt 0 Level bit 0 position. */ #define PORT_INT0LVL1_bm (1<<1) /* Port Interrupt 0 Level bit 1 mask. */ #define PORT_INT0LVL1_bp 1 /* Port Interrupt 0 Level bit 1 position. */ /* PORT.INTFLAGS bit masks and bit positions */ #define PORT_INT1IF_bm 0x02 /* Port Interrupt 1 Flag bit mask. */ #define PORT_INT1IF_bp 1 /* Port Interrupt 1 Flag bit position. */ #define PORT_INT0IF_bm 0x01 /* Port Interrupt 0 Flag bit mask. */ #define PORT_INT0IF_bp 0 /* Port Interrupt 0 Flag bit position. */ /* PORT.REMAP bit masks and bit positions */ #define PORT_SPI_bm 0x20 /* SPI bit mask. */ #define PORT_SPI_bp 5 /* SPI bit position. */ #define PORT_USART0_bm 0x10 /* USART0 bit mask. */ #define PORT_USART0_bp 4 /* USART0 bit position. */ #define PORT_TC0D_bm 0x08 /* Timer/Counter 0 Output Compare D bit mask. */ #define PORT_TC0D_bp 3 /* Timer/Counter 0 Output Compare D bit position. */ #define PORT_TC0C_bm 0x04 /* Timer/Counter 0 Output Compare C bit mask. */ #define PORT_TC0C_bp 2 /* Timer/Counter 0 Output Compare C bit position. */ #define PORT_TC0B_bm 0x02 /* Timer/Counter 0 Output Compare B bit mask. */ #define PORT_TC0B_bp 1 /* Timer/Counter 0 Output Compare B bit position. */ #define PORT_TC0A_bm 0x01 /* Timer/Counter 0 Output Compare A bit mask. */ #define PORT_TC0A_bp 0 /* Timer/Counter 0 Output Compare A bit position. */ /* PORT.PIN0CTRL bit masks and bit positions */ #define PORT_SRLEN_bm 0x80 /* Slew Rate Enable bit mask. */ #define PORT_SRLEN_bp 7 /* Slew Rate Enable bit position. */ #define PORT_INVEN_bm 0x40 /* Inverted I/O Enable bit mask. */ #define PORT_INVEN_bp 6 /* Inverted I/O Enable bit position. */ #define PORT_OPC_gm 0x38 /* Output/Pull Configuration group mask. */ #define PORT_OPC_gp 3 /* Output/Pull Configuration group position. */ #define PORT_OPC0_bm (1<<3) /* Output/Pull Configuration bit 0 mask. */ #define PORT_OPC0_bp 3 /* Output/Pull Configuration bit 0 position. */ #define PORT_OPC1_bm (1<<4) /* Output/Pull Configuration bit 1 mask. */ #define PORT_OPC1_bp 4 /* Output/Pull Configuration bit 1 position. */ #define PORT_OPC2_bm (1<<5) /* Output/Pull Configuration bit 2 mask. */ #define PORT_OPC2_bp 5 /* Output/Pull Configuration bit 2 position. */ #define PORT_ISC_gm 0x07 /* Input/Sense Configuration group mask. */ #define PORT_ISC_gp 0 /* Input/Sense Configuration group position. */ #define PORT_ISC0_bm (1<<0) /* Input/Sense Configuration bit 0 mask. */ #define PORT_ISC0_bp 0 /* Input/Sense Configuration bit 0 position. */ #define PORT_ISC1_bm (1<<1) /* Input/Sense Configuration bit 1 mask. */ #define PORT_ISC1_bp 1 /* Input/Sense Configuration bit 1 position. */ #define PORT_ISC2_bm (1<<2) /* Input/Sense Configuration bit 2 mask. */ #define PORT_ISC2_bp 2 /* Input/Sense Configuration bit 2 position. */ /* PORT.PIN1CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* PORT.PIN2CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* PORT.PIN3CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* PORT.PIN4CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* PORT.PIN5CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* PORT.PIN6CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* PORT.PIN7CTRL bit masks and bit positions */ /* PORT_SRLEN Predefined. */ /* PORT_SRLEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_INVEN Predefined. */ /* PORT_OPC Predefined. */ /* PORT_OPC Predefined. */ /* PORT_ISC Predefined. */ /* PORT_ISC Predefined. */ /* TC - 16-bit Timer/Counter With PWM */ /* TC0.CTRLA bit masks and bit positions */ #define TC0_CLKSEL_gm 0x0F /* Clock Selection group mask. */ #define TC0_CLKSEL_gp 0 /* Clock Selection group position. */ #define TC0_CLKSEL0_bm (1<<0) /* Clock Selection bit 0 mask. */ #define TC0_CLKSEL0_bp 0 /* Clock Selection bit 0 position. */ #define TC0_CLKSEL1_bm (1<<1) /* Clock Selection bit 1 mask. */ #define TC0_CLKSEL1_bp 1 /* Clock Selection bit 1 position. */ #define TC0_CLKSEL2_bm (1<<2) /* Clock Selection bit 2 mask. */ #define TC0_CLKSEL2_bp 2 /* Clock Selection bit 2 position. */ #define TC0_CLKSEL3_bm (1<<3) /* Clock Selection bit 3 mask. */ #define TC0_CLKSEL3_bp 3 /* Clock Selection bit 3 position. */ /* TC0.CTRLB bit masks and bit positions */ #define TC0_CCDEN_bm 0x80 /* Compare or Capture D Enable bit mask. */ #define TC0_CCDEN_bp 7 /* Compare or Capture D Enable bit position. */ #define TC0_CCCEN_bm 0x40 /* Compare or Capture C Enable bit mask. */ #define TC0_CCCEN_bp 6 /* Compare or Capture C Enable bit position. */ #define TC0_CCBEN_bm 0x20 /* Compare or Capture B Enable bit mask. */ #define TC0_CCBEN_bp 5 /* Compare or Capture B Enable bit position. */ #define TC0_CCAEN_bm 0x10 /* Compare or Capture A Enable bit mask. */ #define TC0_CCAEN_bp 4 /* Compare or Capture A Enable bit position. */ #define TC0_WGMODE_gm 0x07 /* Waveform generation mode group mask. */ #define TC0_WGMODE_gp 0 /* Waveform generation mode group position. */ #define TC0_WGMODE0_bm (1<<0) /* Waveform generation mode bit 0 mask. */ #define TC0_WGMODE0_bp 0 /* Waveform generation mode bit 0 position. */ #define TC0_WGMODE1_bm (1<<1) /* Waveform generation mode bit 1 mask. */ #define TC0_WGMODE1_bp 1 /* Waveform generation mode bit 1 position. */ #define TC0_WGMODE2_bm (1<<2) /* Waveform generation mode bit 2 mask. */ #define TC0_WGMODE2_bp 2 /* Waveform generation mode bit 2 position. */ /* TC0.CTRLC bit masks and bit positions */ #define TC0_CMPD_bm 0x08 /* Compare D Output Value bit mask. */ #define TC0_CMPD_bp 3 /* Compare D Output Value bit position. */ #define TC0_CMPC_bm 0x04 /* Compare C Output Value bit mask. */ #define TC0_CMPC_bp 2 /* Compare C Output Value bit position. */ #define TC0_CMPB_bm 0x02 /* Compare B Output Value bit mask. */ #define TC0_CMPB_bp 1 /* Compare B Output Value bit position. */ #define TC0_CMPA_bm 0x01 /* Compare A Output Value bit mask. */ #define TC0_CMPA_bp 0 /* Compare A Output Value bit position. */ /* TC0.CTRLD bit masks and bit positions */ #define TC0_EVACT_gm 0xE0 /* Event Action group mask. */ #define TC0_EVACT_gp 5 /* Event Action group position. */ #define TC0_EVACT0_bm (1<<5) /* Event Action bit 0 mask. */ #define TC0_EVACT0_bp 5 /* Event Action bit 0 position. */ #define TC0_EVACT1_bm (1<<6) /* Event Action bit 1 mask. */ #define TC0_EVACT1_bp 6 /* Event Action bit 1 position. */ #define TC0_EVACT2_bm (1<<7) /* Event Action bit 2 mask. */ #define TC0_EVACT2_bp 7 /* Event Action bit 2 position. */ #define TC0_EVDLY_bm 0x10 /* Event Delay bit mask. */ #define TC0_EVDLY_bp 4 /* Event Delay bit position. */ #define TC0_EVSEL_gm 0x0F /* Event Source Select group mask. */ #define TC0_EVSEL_gp 0 /* Event Source Select group position. */ #define TC0_EVSEL0_bm (1<<0) /* Event Source Select bit 0 mask. */ #define TC0_EVSEL0_bp 0 /* Event Source Select bit 0 position. */ #define TC0_EVSEL1_bm (1<<1) /* Event Source Select bit 1 mask. */ #define TC0_EVSEL1_bp 1 /* Event Source Select bit 1 position. */ #define TC0_EVSEL2_bm (1<<2) /* Event Source Select bit 2 mask. */ #define TC0_EVSEL2_bp 2 /* Event Source Select bit 2 position. */ #define TC0_EVSEL3_bm (1<<3) /* Event Source Select bit 3 mask. */ #define TC0_EVSEL3_bp 3 /* Event Source Select bit 3 position. */ /* TC0.CTRLE bit masks and bit positions */ #define TC0_BYTEM_gm 0x03 /* Byte Mode group mask. */ #define TC0_BYTEM_gp 0 /* Byte Mode group position. */ #define TC0_BYTEM0_bm (1<<0) /* Byte Mode bit 0 mask. */ #define TC0_BYTEM0_bp 0 /* Byte Mode bit 0 position. */ #define TC0_BYTEM1_bm (1<<1) /* Byte Mode bit 1 mask. */ #define TC0_BYTEM1_bp 1 /* Byte Mode bit 1 position. */ /* TC0.INTCTRLA bit masks and bit positions */ #define TC0_ERRINTLVL_gm 0x0C /* Error Interrupt Level group mask. */ #define TC0_ERRINTLVL_gp 2 /* Error Interrupt Level group position. */ #define TC0_ERRINTLVL0_bm (1<<2) /* Error Interrupt Level bit 0 mask. */ #define TC0_ERRINTLVL0_bp 2 /* Error Interrupt Level bit 0 position. */ #define TC0_ERRINTLVL1_bm (1<<3) /* Error Interrupt Level bit 1 mask. */ #define TC0_ERRINTLVL1_bp 3 /* Error Interrupt Level bit 1 position. */ #define TC0_OVFINTLVL_gm 0x03 /* Overflow interrupt level group mask. */ #define TC0_OVFINTLVL_gp 0 /* Overflow interrupt level group position. */ #define TC0_OVFINTLVL0_bm (1<<0) /* Overflow interrupt level bit 0 mask. */ #define TC0_OVFINTLVL0_bp 0 /* Overflow interrupt level bit 0 position. */ #define TC0_OVFINTLVL1_bm (1<<1) /* Overflow interrupt level bit 1 mask. */ #define TC0_OVFINTLVL1_bp 1 /* Overflow interrupt level bit 1 position. */ /* TC0.INTCTRLB bit masks and bit positions */ #define TC0_CCDINTLVL_gm 0xC0 /* Compare or Capture D Interrupt Level group mask. */ #define TC0_CCDINTLVL_gp 6 /* Compare or Capture D Interrupt Level group position. */ #define TC0_CCDINTLVL0_bm (1<<6) /* Compare or Capture D Interrupt Level bit 0 mask. */ #define TC0_CCDINTLVL0_bp 6 /* Compare or Capture D Interrupt Level bit 0 position. */ #define TC0_CCDINTLVL1_bm (1<<7) /* Compare or Capture D Interrupt Level bit 1 mask. */ #define TC0_CCDINTLVL1_bp 7 /* Compare or Capture D Interrupt Level bit 1 position. */ #define TC0_CCCINTLVL_gm 0x30 /* Compare or Capture C Interrupt Level group mask. */ #define TC0_CCCINTLVL_gp 4 /* Compare or Capture C Interrupt Level group position. */ #define TC0_CCCINTLVL0_bm (1<<4) /* Compare or Capture C Interrupt Level bit 0 mask. */ #define TC0_CCCINTLVL0_bp 4 /* Compare or Capture C Interrupt Level bit 0 position. */ #define TC0_CCCINTLVL1_bm (1<<5) /* Compare or Capture C Interrupt Level bit 1 mask. */ #define TC0_CCCINTLVL1_bp 5 /* Compare or Capture C Interrupt Level bit 1 position. */ #define TC0_CCBINTLVL_gm 0x0C /* Compare or Capture B Interrupt Level group mask. */ #define TC0_CCBINTLVL_gp 2 /* Compare or Capture B Interrupt Level group position. */ #define TC0_CCBINTLVL0_bm (1<<2) /* Compare or Capture B Interrupt Level bit 0 mask. */ #define TC0_CCBINTLVL0_bp 2 /* Compare or Capture B Interrupt Level bit 0 position. */ #define TC0_CCBINTLVL1_bm (1<<3) /* Compare or Capture B Interrupt Level bit 1 mask. */ #define TC0_CCBINTLVL1_bp 3 /* Compare or Capture B Interrupt Level bit 1 position. */ #define TC0_CCAINTLVL_gm 0x03 /* Compare or Capture A Interrupt Level group mask. */ #define TC0_CCAINTLVL_gp 0 /* Compare or Capture A Interrupt Level group position. */ #define TC0_CCAINTLVL0_bm (1<<0) /* Compare or Capture A Interrupt Level bit 0 mask. */ #define TC0_CCAINTLVL0_bp 0 /* Compare or Capture A Interrupt Level bit 0 position. */ #define TC0_CCAINTLVL1_bm (1<<1) /* Compare or Capture A Interrupt Level bit 1 mask. */ #define TC0_CCAINTLVL1_bp 1 /* Compare or Capture A Interrupt Level bit 1 position. */ /* TC0.CTRLFCLR bit masks and bit positions */ #define TC0_CMD_gm 0x0C /* Command group mask. */ #define TC0_CMD_gp 2 /* Command group position. */ #define TC0_CMD0_bm (1<<2) /* Command bit 0 mask. */ #define TC0_CMD0_bp 2 /* Command bit 0 position. */ #define TC0_CMD1_bm (1<<3) /* Command bit 1 mask. */ #define TC0_CMD1_bp 3 /* Command bit 1 position. */ #define TC0_LUPD_bm 0x02 /* Lock Update bit mask. */ #define TC0_LUPD_bp 1 /* Lock Update bit position. */ #define TC0_DIR_bm 0x01 /* Direction bit mask. */ #define TC0_DIR_bp 0 /* Direction bit position. */ /* TC0.CTRLFSET bit masks and bit positions */ /* TC0_CMD Predefined. */ /* TC0_CMD Predefined. */ /* TC0_LUPD Predefined. */ /* TC0_LUPD Predefined. */ /* TC0_DIR Predefined. */ /* TC0_DIR Predefined. */ /* TC0.CTRLGCLR bit masks and bit positions */ #define TC0_CCDBV_bm 0x10 /* Compare or Capture D Buffer Valid bit mask. */ #define TC0_CCDBV_bp 4 /* Compare or Capture D Buffer Valid bit position. */ #define TC0_CCCBV_bm 0x08 /* Compare or Capture C Buffer Valid bit mask. */ #define TC0_CCCBV_bp 3 /* Compare or Capture C Buffer Valid bit position. */ #define TC0_CCBBV_bm 0x04 /* Compare or Capture B Buffer Valid bit mask. */ #define TC0_CCBBV_bp 2 /* Compare or Capture B Buffer Valid bit position. */ #define TC0_CCABV_bm 0x02 /* Compare or Capture A Buffer Valid bit mask. */ #define TC0_CCABV_bp 1 /* Compare or Capture A Buffer Valid bit position. */ #define TC0_PERBV_bm 0x01 /* Period Buffer Valid bit mask. */ #define TC0_PERBV_bp 0 /* Period Buffer Valid bit position. */ /* TC0.CTRLGSET bit masks and bit positions */ /* TC0_CCDBV Predefined. */ /* TC0_CCDBV Predefined. */ /* TC0_CCCBV Predefined. */ /* TC0_CCCBV Predefined. */ /* TC0_CCBBV Predefined. */ /* TC0_CCBBV Predefined. */ /* TC0_CCABV Predefined. */ /* TC0_CCABV Predefined. */ /* TC0_PERBV Predefined. */ /* TC0_PERBV Predefined. */ /* TC0.INTFLAGS bit masks and bit positions */ #define TC0_CCDIF_bm 0x80 /* Compare or Capture D Interrupt Flag bit mask. */ #define TC0_CCDIF_bp 7 /* Compare or Capture D Interrupt Flag bit position. */ #define TC0_CCCIF_bm 0x40 /* Compare or Capture C Interrupt Flag bit mask. */ #define TC0_CCCIF_bp 6 /* Compare or Capture C Interrupt Flag bit position. */ #define TC0_CCBIF_bm 0x20 /* Compare or Capture B Interrupt Flag bit mask. */ #define TC0_CCBIF_bp 5 /* Compare or Capture B Interrupt Flag bit position. */ #define TC0_CCAIF_bm 0x10 /* Compare or Capture A Interrupt Flag bit mask. */ #define TC0_CCAIF_bp 4 /* Compare or Capture A Interrupt Flag bit position. */ #define TC0_ERRIF_bm 0x02 /* Error Interrupt Flag bit mask. */ #define TC0_ERRIF_bp 1 /* Error Interrupt Flag bit position. */ #define TC0_OVFIF_bm 0x01 /* Overflow Interrupt Flag bit mask. */ #define TC0_OVFIF_bp 0 /* Overflow Interrupt Flag bit position. */ /* TC1.CTRLA bit masks and bit positions */ #define TC1_CLKSEL_gm 0x0F /* Clock Selection group mask. */ #define TC1_CLKSEL_gp 0 /* Clock Selection group position. */ #define TC1_CLKSEL0_bm (1<<0) /* Clock Selection bit 0 mask. */ #define TC1_CLKSEL0_bp 0 /* Clock Selection bit 0 position. */ #define TC1_CLKSEL1_bm (1<<1) /* Clock Selection bit 1 mask. */ #define TC1_CLKSEL1_bp 1 /* Clock Selection bit 1 position. */ #define TC1_CLKSEL2_bm (1<<2) /* Clock Selection bit 2 mask. */ #define TC1_CLKSEL2_bp 2 /* Clock Selection bit 2 position. */ #define TC1_CLKSEL3_bm (1<<3) /* Clock Selection bit 3 mask. */ #define TC1_CLKSEL3_bp 3 /* Clock Selection bit 3 position. */ /* TC1.CTRLB bit masks and bit positions */ #define TC1_CCBEN_bm 0x20 /* Compare or Capture B Enable bit mask. */ #define TC1_CCBEN_bp 5 /* Compare or Capture B Enable bit position. */ #define TC1_CCAEN_bm 0x10 /* Compare or Capture A Enable bit mask. */ #define TC1_CCAEN_bp 4 /* Compare or Capture A Enable bit position. */ #define TC1_WGMODE_gm 0x07 /* Waveform generation mode group mask. */ #define TC1_WGMODE_gp 0 /* Waveform generation mode group position. */ #define TC1_WGMODE0_bm (1<<0) /* Waveform generation mode bit 0 mask. */ #define TC1_WGMODE0_bp 0 /* Waveform generation mode bit 0 position. */ #define TC1_WGMODE1_bm (1<<1) /* Waveform generation mode bit 1 mask. */ #define TC1_WGMODE1_bp 1 /* Waveform generation mode bit 1 position. */ #define TC1_WGMODE2_bm (1<<2) /* Waveform generation mode bit 2 mask. */ #define TC1_WGMODE2_bp 2 /* Waveform generation mode bit 2 position. */ /* TC1.CTRLC bit masks and bit positions */ #define TC1_CMPB_bm 0x02 /* Compare B Output Value bit mask. */ #define TC1_CMPB_bp 1 /* Compare B Output Value bit position. */ #define TC1_CMPA_bm 0x01 /* Compare A Output Value bit mask. */ #define TC1_CMPA_bp 0 /* Compare A Output Value bit position. */ /* TC1.CTRLD bit masks and bit positions */ #define TC1_EVACT_gm 0xE0 /* Event Action group mask. */ #define TC1_EVACT_gp 5 /* Event Action group position. */ #define TC1_EVACT0_bm (1<<5) /* Event Action bit 0 mask. */ #define TC1_EVACT0_bp 5 /* Event Action bit 0 position. */ #define TC1_EVACT1_bm (1<<6) /* Event Action bit 1 mask. */ #define TC1_EVACT1_bp 6 /* Event Action bit 1 position. */ #define TC1_EVACT2_bm (1<<7) /* Event Action bit 2 mask. */ #define TC1_EVACT2_bp 7 /* Event Action bit 2 position. */ #define TC1_EVDLY_bm 0x10 /* Event Delay bit mask. */ #define TC1_EVDLY_bp 4 /* Event Delay bit position. */ #define TC1_EVSEL_gm 0x0F /* Event Source Select group mask. */ #define TC1_EVSEL_gp 0 /* Event Source Select group position. */ #define TC1_EVSEL0_bm (1<<0) /* Event Source Select bit 0 mask. */ #define TC1_EVSEL0_bp 0 /* Event Source Select bit 0 position. */ #define TC1_EVSEL1_bm (1<<1) /* Event Source Select bit 1 mask. */ #define TC1_EVSEL1_bp 1 /* Event Source Select bit 1 position. */ #define TC1_EVSEL2_bm (1<<2) /* Event Source Select bit 2 mask. */ #define TC1_EVSEL2_bp 2 /* Event Source Select bit 2 position. */ #define TC1_EVSEL3_bm (1<<3) /* Event Source Select bit 3 mask. */ #define TC1_EVSEL3_bp 3 /* Event Source Select bit 3 position. */ /* TC1.CTRLE bit masks and bit positions */ #define TC1_BYTEM_bm 0x01 /* Byte Mode bit mask. */ #define TC1_BYTEM_bp 0 /* Byte Mode bit position. */ /* TC1.INTCTRLA bit masks and bit positions */ #define TC1_ERRINTLVL_gm 0x0C /* Error Interrupt Level group mask. */ #define TC1_ERRINTLVL_gp 2 /* Error Interrupt Level group position. */ #define TC1_ERRINTLVL0_bm (1<<2) /* Error Interrupt Level bit 0 mask. */ #define TC1_ERRINTLVL0_bp 2 /* Error Interrupt Level bit 0 position. */ #define TC1_ERRINTLVL1_bm (1<<3) /* Error Interrupt Level bit 1 mask. */ #define TC1_ERRINTLVL1_bp 3 /* Error Interrupt Level bit 1 position. */ #define TC1_OVFINTLVL_gm 0x03 /* Overflow interrupt level group mask. */ #define TC1_OVFINTLVL_gp 0 /* Overflow interrupt level group position. */ #define TC1_OVFINTLVL0_bm (1<<0) /* Overflow interrupt level bit 0 mask. */ #define TC1_OVFINTLVL0_bp 0 /* Overflow interrupt level bit 0 position. */ #define TC1_OVFINTLVL1_bm (1<<1) /* Overflow interrupt level bit 1 mask. */ #define TC1_OVFINTLVL1_bp 1 /* Overflow interrupt level bit 1 position. */ /* TC1.INTCTRLB bit masks and bit positions */ #define TC1_CCBINTLVL_gm 0x0C /* Compare or Capture B Interrupt Level group mask. */ #define TC1_CCBINTLVL_gp 2 /* Compare or Capture B Interrupt Level group position. */ #define TC1_CCBINTLVL0_bm (1<<2) /* Compare or Capture B Interrupt Level bit 0 mask. */ #define TC1_CCBINTLVL0_bp 2 /* Compare or Capture B Interrupt Level bit 0 position. */ #define TC1_CCBINTLVL1_bm (1<<3) /* Compare or Capture B Interrupt Level bit 1 mask. */ #define TC1_CCBINTLVL1_bp 3 /* Compare or Capture B Interrupt Level bit 1 position. */ #define TC1_CCAINTLVL_gm 0x03 /* Compare or Capture A Interrupt Level group mask. */ #define TC1_CCAINTLVL_gp 0 /* Compare or Capture A Interrupt Level group position. */ #define TC1_CCAINTLVL0_bm (1<<0) /* Compare or Capture A Interrupt Level bit 0 mask. */ #define TC1_CCAINTLVL0_bp 0 /* Compare or Capture A Interrupt Level bit 0 position. */ #define TC1_CCAINTLVL1_bm (1<<1) /* Compare or Capture A Interrupt Level bit 1 mask. */ #define TC1_CCAINTLVL1_bp 1 /* Compare or Capture A Interrupt Level bit 1 position. */ /* TC1.CTRLFCLR bit masks and bit positions */ #define TC1_CMD_gm 0x0C /* Command group mask. */ #define TC1_CMD_gp 2 /* Command group position. */ #define TC1_CMD0_bm (1<<2) /* Command bit 0 mask. */ #define TC1_CMD0_bp 2 /* Command bit 0 position. */ #define TC1_CMD1_bm (1<<3) /* Command bit 1 mask. */ #define TC1_CMD1_bp 3 /* Command bit 1 position. */ #define TC1_LUPD_bm 0x02 /* Lock Update bit mask. */ #define TC1_LUPD_bp 1 /* Lock Update bit position. */ #define TC1_DIR_bm 0x01 /* Direction bit mask. */ #define TC1_DIR_bp 0 /* Direction bit position. */ /* TC1.CTRLFSET bit masks and bit positions */ /* TC1_CMD Predefined. */ /* TC1_CMD Predefined. */ /* TC1_LUPD Predefined. */ /* TC1_LUPD Predefined. */ /* TC1_DIR Predefined. */ /* TC1_DIR Predefined. */ /* TC1.CTRLGCLR bit masks and bit positions */ #define TC1_CCBBV_bm 0x04 /* Compare or Capture B Buffer Valid bit mask. */ #define TC1_CCBBV_bp 2 /* Compare or Capture B Buffer Valid bit position. */ #define TC1_CCABV_bm 0x02 /* Compare or Capture A Buffer Valid bit mask. */ #define TC1_CCABV_bp 1 /* Compare or Capture A Buffer Valid bit position. */ #define TC1_PERBV_bm 0x01 /* Period Buffer Valid bit mask. */ #define TC1_PERBV_bp 0 /* Period Buffer Valid bit position. */ /* TC1.CTRLGSET bit masks and bit positions */ /* TC1_CCBBV Predefined. */ /* TC1_CCBBV Predefined. */ /* TC1_CCABV Predefined. */ /* TC1_CCABV Predefined. */ /* TC1_PERBV Predefined. */ /* TC1_PERBV Predefined. */ /* TC1.INTFLAGS bit masks and bit positions */ #define TC1_CCBIF_bm 0x20 /* Compare or Capture B Interrupt Flag bit mask. */ #define TC1_CCBIF_bp 5 /* Compare or Capture B Interrupt Flag bit position. */ #define TC1_CCAIF_bm 0x10 /* Compare or Capture A Interrupt Flag bit mask. */ #define TC1_CCAIF_bp 4 /* Compare or Capture A Interrupt Flag bit position. */ #define TC1_ERRIF_bm 0x02 /* Error Interrupt Flag bit mask. */ #define TC1_ERRIF_bp 1 /* Error Interrupt Flag bit position. */ #define TC1_OVFIF_bm 0x01 /* Overflow Interrupt Flag bit mask. */ #define TC1_OVFIF_bp 0 /* Overflow Interrupt Flag bit position. */ /* TC2 - 16-bit Timer/Counter type 2 */ /* TC2.CTRLA bit masks and bit positions */ #define TC2_CLKSEL_gm 0x0F /* Clock Selection group mask. */ #define TC2_CLKSEL_gp 0 /* Clock Selection group position. */ #define TC2_CLKSEL0_bm (1<<0) /* Clock Selection bit 0 mask. */ #define TC2_CLKSEL0_bp 0 /* Clock Selection bit 0 position. */ #define TC2_CLKSEL1_bm (1<<1) /* Clock Selection bit 1 mask. */ #define TC2_CLKSEL1_bp 1 /* Clock Selection bit 1 position. */ #define TC2_CLKSEL2_bm (1<<2) /* Clock Selection bit 2 mask. */ #define TC2_CLKSEL2_bp 2 /* Clock Selection bit 2 position. */ #define TC2_CLKSEL3_bm (1<<3) /* Clock Selection bit 3 mask. */ #define TC2_CLKSEL3_bp 3 /* Clock Selection bit 3 position. */ /* TC2.CTRLB bit masks and bit positions */ #define TC2_HCMPDEN_bm 0x80 /* High Byte Compare D Enable bit mask. */ #define TC2_HCMPDEN_bp 7 /* High Byte Compare D Enable bit position. */ #define TC2_HCMPCEN_bm 0x40 /* High Byte Compare C Enable bit mask. */ #define TC2_HCMPCEN_bp 6 /* High Byte Compare C Enable bit position. */ #define TC2_HCMPBEN_bm 0x20 /* High Byte Compare B Enable bit mask. */ #define TC2_HCMPBEN_bp 5 /* High Byte Compare B Enable bit position. */ #define TC2_HCMPAEN_bm 0x10 /* High Byte Compare A Enable bit mask. */ #define TC2_HCMPAEN_bp 4 /* High Byte Compare A Enable bit position. */ #define TC2_LCMPDEN_bm 0x08 /* Low Byte Compare D Enable bit mask. */ #define TC2_LCMPDEN_bp 3 /* Low Byte Compare D Enable bit position. */ #define TC2_LCMPCEN_bm 0x04 /* Low Byte Compare C Enable bit mask. */ #define TC2_LCMPCEN_bp 2 /* Low Byte Compare C Enable bit position. */ #define TC2_LCMPBEN_bm 0x02 /* Low Byte Compare B Enable bit mask. */ #define TC2_LCMPBEN_bp 1 /* Low Byte Compare B Enable bit position. */ #define TC2_LCMPAEN_bm 0x01 /* Low Byte Compare A Enable bit mask. */ #define TC2_LCMPAEN_bp 0 /* Low Byte Compare A Enable bit position. */ /* TC2.CTRLC bit masks and bit positions */ #define TC2_HCMPD_bm 0x80 /* High Byte Compare D Output Value bit mask. */ #define TC2_HCMPD_bp 7 /* High Byte Compare D Output Value bit position. */ #define TC2_HCMPC_bm 0x40 /* High Byte Compare C Output Value bit mask. */ #define TC2_HCMPC_bp 6 /* High Byte Compare C Output Value bit position. */ #define TC2_HCMPB_bm 0x20 /* High Byte Compare B Output Value bit mask. */ #define TC2_HCMPB_bp 5 /* High Byte Compare B Output Value bit position. */ #define TC2_HCMPA_bm 0x10 /* High Byte Compare A Output Value bit mask. */ #define TC2_HCMPA_bp 4 /* High Byte Compare A Output Value bit position. */ #define TC2_LCMPD_bm 0x08 /* Low Byte Compare D Output Value bit mask. */ #define TC2_LCMPD_bp 3 /* Low Byte Compare D Output Value bit position. */ #define TC2_LCMPC_bm 0x04 /* Low Byte Compare C Output Value bit mask. */ #define TC2_LCMPC_bp 2 /* Low Byte Compare C Output Value bit position. */ #define TC2_LCMPB_bm 0x02 /* Low Byte Compare B Output Value bit mask. */ #define TC2_LCMPB_bp 1 /* Low Byte Compare B Output Value bit position. */ #define TC2_LCMPA_bm 0x01 /* Low Byte Compare A Output Value bit mask. */ #define TC2_LCMPA_bp 0 /* Low Byte Compare A Output Value bit position. */ /* TC2.CTRLE bit masks and bit positions */ #define TC2_BYTEM_gm 0x03 /* Byte Mode group mask. */ #define TC2_BYTEM_gp 0 /* Byte Mode group position. */ #define TC2_BYTEM0_bm (1<<0) /* Byte Mode bit 0 mask. */ #define TC2_BYTEM0_bp 0 /* Byte Mode bit 0 position. */ #define TC2_BYTEM1_bm (1<<1) /* Byte Mode bit 1 mask. */ #define TC2_BYTEM1_bp 1 /* Byte Mode bit 1 position. */ /* TC2.INTCTRLA bit masks and bit positions */ #define TC2_HUNFINTLVL_gm 0x0C /* High Byte Underflow Interrupt Level group mask. */ #define TC2_HUNFINTLVL_gp 2 /* High Byte Underflow Interrupt Level group position. */ #define TC2_HUNFINTLVL0_bm (1<<2) /* High Byte Underflow Interrupt Level bit 0 mask. */ #define TC2_HUNFINTLVL0_bp 2 /* High Byte Underflow Interrupt Level bit 0 position. */ #define TC2_HUNFINTLVL1_bm (1<<3) /* High Byte Underflow Interrupt Level bit 1 mask. */ #define TC2_HUNFINTLVL1_bp 3 /* High Byte Underflow Interrupt Level bit 1 position. */ #define TC2_LUNFINTLVL_gm 0x03 /* Low Byte Underflow interrupt level group mask. */ #define TC2_LUNFINTLVL_gp 0 /* Low Byte Underflow interrupt level group position. */ #define TC2_LUNFINTLVL0_bm (1<<0) /* Low Byte Underflow interrupt level bit 0 mask. */ #define TC2_LUNFINTLVL0_bp 0 /* Low Byte Underflow interrupt level bit 0 position. */ #define TC2_LUNFINTLVL1_bm (1<<1) /* Low Byte Underflow interrupt level bit 1 mask. */ #define TC2_LUNFINTLVL1_bp 1 /* Low Byte Underflow interrupt level bit 1 position. */ /* TC2.INTCTRLB bit masks and bit positions */ #define TC2_LCMPDINTLVL_gm 0xC0 /* Low Byte Compare D Interrupt Level group mask. */ #define TC2_LCMPDINTLVL_gp 6 /* Low Byte Compare D Interrupt Level group position. */ #define TC2_LCMPDINTLVL0_bm (1<<6) /* Low Byte Compare D Interrupt Level bit 0 mask. */ #define TC2_LCMPDINTLVL0_bp 6 /* Low Byte Compare D Interrupt Level bit 0 position. */ #define TC2_LCMPDINTLVL1_bm (1<<7) /* Low Byte Compare D Interrupt Level bit 1 mask. */ #define TC2_LCMPDINTLVL1_bp 7 /* Low Byte Compare D Interrupt Level bit 1 position. */ #define TC2_LCMPCINTLVL_gm 0x30 /* Low Byte Compare C Interrupt Level group mask. */ #define TC2_LCMPCINTLVL_gp 4 /* Low Byte Compare C Interrupt Level group position. */ #define TC2_LCMPCINTLVL0_bm (1<<4) /* Low Byte Compare C Interrupt Level bit 0 mask. */ #define TC2_LCMPCINTLVL0_bp 4 /* Low Byte Compare C Interrupt Level bit 0 position. */ #define TC2_LCMPCINTLVL1_bm (1<<5) /* Low Byte Compare C Interrupt Level bit 1 mask. */ #define TC2_LCMPCINTLVL1_bp 5 /* Low Byte Compare C Interrupt Level bit 1 position. */ #define TC2_LCMPBINTLVL_gm 0x0C /* Low Byte Compare B Interrupt Level group mask. */ #define TC2_LCMPBINTLVL_gp 2 /* Low Byte Compare B Interrupt Level group position. */ #define TC2_LCMPBINTLVL0_bm (1<<2) /* Low Byte Compare B Interrupt Level bit 0 mask. */ #define TC2_LCMPBINTLVL0_bp 2 /* Low Byte Compare B Interrupt Level bit 0 position. */ #define TC2_LCMPBINTLVL1_bm (1<<3) /* Low Byte Compare B Interrupt Level bit 1 mask. */ #define TC2_LCMPBINTLVL1_bp 3 /* Low Byte Compare B Interrupt Level bit 1 position. */ #define TC2_LCMPAINTLVL_gm 0x03 /* Low Byte Compare A Interrupt Level group mask. */ #define TC2_LCMPAINTLVL_gp 0 /* Low Byte Compare A Interrupt Level group position. */ #define TC2_LCMPAINTLVL0_bm (1<<0) /* Low Byte Compare A Interrupt Level bit 0 mask. */ #define TC2_LCMPAINTLVL0_bp 0 /* Low Byte Compare A Interrupt Level bit 0 position. */ #define TC2_LCMPAINTLVL1_bm (1<<1) /* Low Byte Compare A Interrupt Level bit 1 mask. */ #define TC2_LCMPAINTLVL1_bp 1 /* Low Byte Compare A Interrupt Level bit 1 position. */ /* TC2.CTRLF bit masks and bit positions */ #define TC2_CMD_gm 0x0C /* Command group mask. */ #define TC2_CMD_gp 2 /* Command group position. */ #define TC2_CMD0_bm (1<<2) /* Command bit 0 mask. */ #define TC2_CMD0_bp 2 /* Command bit 0 position. */ #define TC2_CMD1_bm (1<<3) /* Command bit 1 mask. */ #define TC2_CMD1_bp 3 /* Command bit 1 position. */ #define TC2_CMDEN_gm 0x03 /* Command Enable group mask. */ #define TC2_CMDEN_gp 0 /* Command Enable group position. */ #define TC2_CMDEN0_bm (1<<0) /* Command Enable bit 0 mask. */ #define TC2_CMDEN0_bp 0 /* Command Enable bit 0 position. */ #define TC2_CMDEN1_bm (1<<1) /* Command Enable bit 1 mask. */ #define TC2_CMDEN1_bp 1 /* Command Enable bit 1 position. */ /* TC2.INTFLAGS bit masks and bit positions */ #define TC2_LCMPDIF_bm 0x80 /* Low Byte Compare D Interrupt Flag bit mask. */ #define TC2_LCMPDIF_bp 7 /* Low Byte Compare D Interrupt Flag bit position. */ #define TC2_LCMPCIF_bm 0x40 /* Low Byte Compare C Interrupt Flag bit mask. */ #define TC2_LCMPCIF_bp 6 /* Low Byte Compare C Interrupt Flag bit position. */ #define TC2_LCMPBIF_bm 0x20 /* Low Byte Compare B Interrupt Flag bit mask. */ #define TC2_LCMPBIF_bp 5 /* Low Byte Compare B Interrupt Flag bit position. */ #define TC2_LCMPAIF_bm 0x10 /* Low Byte Compare A Interrupt Flag bit mask. */ #define TC2_LCMPAIF_bp 4 /* Low Byte Compare A Interrupt Flag bit position. */ #define TC2_HUNFIF_bm 0x02 /* High Byte Underflow Interrupt Flag bit mask. */ #define TC2_HUNFIF_bp 1 /* High Byte Underflow Interrupt Flag bit position. */ #define TC2_LUNFIF_bm 0x01 /* Low Byte Underflow Interrupt Flag bit mask. */ #define TC2_LUNFIF_bp 0 /* Low Byte Underflow Interrupt Flag bit position. */ /* AWEX - Timer/Counter Advanced Waveform Extension */ /* AWEX.CTRL bit masks and bit positions */ #define AWEX_PGM_bm 0x20 /* Pattern Generation Mode bit mask. */ #define AWEX_PGM_bp 5 /* Pattern Generation Mode bit position. */ #define AWEX_CWCM_bm 0x10 /* Common Waveform Channel Mode bit mask. */ #define AWEX_CWCM_bp 4 /* Common Waveform Channel Mode bit position. */ #define AWEX_DTICCDEN_bm 0x08 /* Dead Time Insertion Compare Channel D Enable bit mask. */ #define AWEX_DTICCDEN_bp 3 /* Dead Time Insertion Compare Channel D Enable bit position. */ #define AWEX_DTICCCEN_bm 0x04 /* Dead Time Insertion Compare Channel C Enable bit mask. */ #define AWEX_DTICCCEN_bp 2 /* Dead Time Insertion Compare Channel C Enable bit position. */ #define AWEX_DTICCBEN_bm 0x02 /* Dead Time Insertion Compare Channel B Enable bit mask. */ #define AWEX_DTICCBEN_bp 1 /* Dead Time Insertion Compare Channel B Enable bit position. */ #define AWEX_DTICCAEN_bm 0x01 /* Dead Time Insertion Compare Channel A Enable bit mask. */ #define AWEX_DTICCAEN_bp 0 /* Dead Time Insertion Compare Channel A Enable bit position. */ /* AWEX.FDCTRL bit masks and bit positions */ #define AWEX_FDDBD_bm 0x10 /* Fault Detect on Disable Break Disable bit mask. */ #define AWEX_FDDBD_bp 4 /* Fault Detect on Disable Break Disable bit position. */ #define AWEX_FDMODE_bm 0x04 /* Fault Detect Mode bit mask. */ #define AWEX_FDMODE_bp 2 /* Fault Detect Mode bit position. */ #define AWEX_FDACT_gm 0x03 /* Fault Detect Action group mask. */ #define AWEX_FDACT_gp 0 /* Fault Detect Action group position. */ #define AWEX_FDACT0_bm (1<<0) /* Fault Detect Action bit 0 mask. */ #define AWEX_FDACT0_bp 0 /* Fault Detect Action bit 0 position. */ #define AWEX_FDACT1_bm (1<<1) /* Fault Detect Action bit 1 mask. */ #define AWEX_FDACT1_bp 1 /* Fault Detect Action bit 1 position. */ /* AWEX.STATUS bit masks and bit positions */ #define AWEX_FDF_bm 0x04 /* Fault Detect Flag bit mask. */ #define AWEX_FDF_bp 2 /* Fault Detect Flag bit position. */ #define AWEX_DTHSBUFV_bm 0x02 /* Dead Time High Side Buffer Valid bit mask. */ #define AWEX_DTHSBUFV_bp 1 /* Dead Time High Side Buffer Valid bit position. */ #define AWEX_DTLSBUFV_bm 0x01 /* Dead Time Low Side Buffer Valid bit mask. */ #define AWEX_DTLSBUFV_bp 0 /* Dead Time Low Side Buffer Valid bit position. */ /* AWEX.STATUSSET bit masks and bit positions */ /* AWEX_FDF Predefined. */ /* AWEX_FDF Predefined. */ /* AWEX_DTHSBUFV Predefined. */ /* AWEX_DTHSBUFV Predefined. */ /* AWEX_DTLSBUFV Predefined. */ /* AWEX_DTLSBUFV Predefined. */ /* HIRES - Timer/Counter High-Resolution Extension */ /* HIRES.CTRLA bit masks and bit positions */ #define HIRES_HREN_gm 0x03 /* High Resolution Enable group mask. */ #define HIRES_HREN_gp 0 /* High Resolution Enable group position. */ #define HIRES_HREN0_bm (1<<0) /* High Resolution Enable bit 0 mask. */ #define HIRES_HREN0_bp 0 /* High Resolution Enable bit 0 position. */ #define HIRES_HREN1_bm (1<<1) /* High Resolution Enable bit 1 mask. */ #define HIRES_HREN1_bp 1 /* High Resolution Enable bit 1 position. */ /* USART - Universal Asynchronous Receiver-Transmitter */ /* USART.STATUS bit masks and bit positions */ #define USART_RXCIF_bm 0x80 /* Receive Interrupt Flag bit mask. */ #define USART_RXCIF_bp 7 /* Receive Interrupt Flag bit position. */ #define USART_TXCIF_bm 0x40 /* Transmit Interrupt Flag bit mask. */ #define USART_TXCIF_bp 6 /* Transmit Interrupt Flag bit position. */ #define USART_DREIF_bm 0x20 /* Data Register Empty Flag bit mask. */ #define USART_DREIF_bp 5 /* Data Register Empty Flag bit position. */ #define USART_FERR_bm 0x10 /* Frame Error bit mask. */ #define USART_FERR_bp 4 /* Frame Error bit position. */ #define USART_BUFOVF_bm 0x08 /* Buffer Overflow bit mask. */ #define USART_BUFOVF_bp 3 /* Buffer Overflow bit position. */ #define USART_PERR_bm 0x04 /* Parity Error bit mask. */ #define USART_PERR_bp 2 /* Parity Error bit position. */ #define USART_RXB8_bm 0x01 /* Receive Bit 8 bit mask. */ #define USART_RXB8_bp 0 /* Receive Bit 8 bit position. */ /* USART.CTRLA bit masks and bit positions */ #define USART_RXCINTLVL_gm 0x30 /* Receive Interrupt Level group mask. */ #define USART_RXCINTLVL_gp 4 /* Receive Interrupt Level group position. */ #define USART_RXCINTLVL0_bm (1<<4) /* Receive Interrupt Level bit 0 mask. */ #define USART_RXCINTLVL0_bp 4 /* Receive Interrupt Level bit 0 position. */ #define USART_RXCINTLVL1_bm (1<<5) /* Receive Interrupt Level bit 1 mask. */ #define USART_RXCINTLVL1_bp 5 /* Receive Interrupt Level bit 1 position. */ #define USART_TXCINTLVL_gm 0x0C /* Transmit Interrupt Level group mask. */ #define USART_TXCINTLVL_gp 2 /* Transmit Interrupt Level group position. */ #define USART_TXCINTLVL0_bm (1<<2) /* Transmit Interrupt Level bit 0 mask. */ #define USART_TXCINTLVL0_bp 2 /* Transmit Interrupt Level bit 0 position. */ #define USART_TXCINTLVL1_bm (1<<3) /* Transmit Interrupt Level bit 1 mask. */ #define USART_TXCINTLVL1_bp 3 /* Transmit Interrupt Level bit 1 position. */ #define USART_DREINTLVL_gm 0x03 /* Data Register Empty Interrupt Level group mask. */ #define USART_DREINTLVL_gp 0 /* Data Register Empty Interrupt Level group position. */ #define USART_DREINTLVL0_bm (1<<0) /* Data Register Empty Interrupt Level bit 0 mask. */ #define USART_DREINTLVL0_bp 0 /* Data Register Empty Interrupt Level bit 0 position. */ #define USART_DREINTLVL1_bm (1<<1) /* Data Register Empty Interrupt Level bit 1 mask. */ #define USART_DREINTLVL1_bp 1 /* Data Register Empty Interrupt Level bit 1 position. */ /* USART.CTRLB bit masks and bit positions */ #define USART_RXEN_bm 0x10 /* Receiver Enable bit mask. */ #define USART_RXEN_bp 4 /* Receiver Enable bit position. */ #define USART_TXEN_bm 0x08 /* Transmitter Enable bit mask. */ #define USART_TXEN_bp 3 /* Transmitter Enable bit position. */ #define USART_CLK2X_bm 0x04 /* Double transmission speed bit mask. */ #define USART_CLK2X_bp 2 /* Double transmission speed bit position. */ #define USART_MPCM_bm 0x02 /* Multi-processor Communication Mode bit mask. */ #define USART_MPCM_bp 1 /* Multi-processor Communication Mode bit position. */ #define USART_TXB8_bm 0x01 /* Transmit bit 8 bit mask. */ #define USART_TXB8_bp 0 /* Transmit bit 8 bit position. */ /* USART.CTRLC bit masks and bit positions */ #define USART_CMODE_gm 0xC0 /* Communication Mode group mask. */ #define USART_CMODE_gp 6 /* Communication Mode group position. */ #define USART_CMODE0_bm (1<<6) /* Communication Mode bit 0 mask. */ #define USART_CMODE0_bp 6 /* Communication Mode bit 0 position. */ #define USART_CMODE1_bm (1<<7) /* Communication Mode bit 1 mask. */ #define USART_CMODE1_bp 7 /* Communication Mode bit 1 position. */ #define USART_PMODE_gm 0x30 /* Parity Mode group mask. */ #define USART_PMODE_gp 4 /* Parity Mode group position. */ #define USART_PMODE0_bm (1<<4) /* Parity Mode bit 0 mask. */ #define USART_PMODE0_bp 4 /* Parity Mode bit 0 position. */ #define USART_PMODE1_bm (1<<5) /* Parity Mode bit 1 mask. */ #define USART_PMODE1_bp 5 /* Parity Mode bit 1 position. */ #define USART_SBMODE_bm 0x08 /* Stop Bit Mode bit mask. */ #define USART_SBMODE_bp 3 /* Stop Bit Mode bit position. */ #define USART_CHSIZE_gm 0x07 /* Character Size group mask. */ #define USART_CHSIZE_gp 0 /* Character Size group position. */ #define USART_CHSIZE0_bm (1<<0) /* Character Size bit 0 mask. */ #define USART_CHSIZE0_bp 0 /* Character Size bit 0 position. */ #define USART_CHSIZE1_bm (1<<1) /* Character Size bit 1 mask. */ #define USART_CHSIZE1_bp 1 /* Character Size bit 1 position. */ #define USART_CHSIZE2_bm (1<<2) /* Character Size bit 2 mask. */ #define USART_CHSIZE2_bp 2 /* Character Size bit 2 position. */ /* USART.BAUDCTRLA bit masks and bit positions */ #define USART_BSEL_gm 0xFF /* Baud Rate Selection Bits [7:0] group mask. */ #define USART_BSEL_gp 0 /* Baud Rate Selection Bits [7:0] group position. */ #define USART_BSEL0_bm (1<<0) /* Baud Rate Selection Bits [7:0] bit 0 mask. */ #define USART_BSEL0_bp 0 /* Baud Rate Selection Bits [7:0] bit 0 position. */ #define USART_BSEL1_bm (1<<1) /* Baud Rate Selection Bits [7:0] bit 1 mask. */ #define USART_BSEL1_bp 1 /* Baud Rate Selection Bits [7:0] bit 1 position. */ #define USART_BSEL2_bm (1<<2) /* Baud Rate Selection Bits [7:0] bit 2 mask. */ #define USART_BSEL2_bp 2 /* Baud Rate Selection Bits [7:0] bit 2 position. */ #define USART_BSEL3_bm (1<<3) /* Baud Rate Selection Bits [7:0] bit 3 mask. */ #define USART_BSEL3_bp 3 /* Baud Rate Selection Bits [7:0] bit 3 position. */ #define USART_BSEL4_bm (1<<4) /* Baud Rate Selection Bits [7:0] bit 4 mask. */ #define USART_BSEL4_bp 4 /* Baud Rate Selection Bits [7:0] bit 4 position. */ #define USART_BSEL5_bm (1<<5) /* Baud Rate Selection Bits [7:0] bit 5 mask. */ #define USART_BSEL5_bp 5 /* Baud Rate Selection Bits [7:0] bit 5 position. */ #define USART_BSEL6_bm (1<<6) /* Baud Rate Selection Bits [7:0] bit 6 mask. */ #define USART_BSEL6_bp 6 /* Baud Rate Selection Bits [7:0] bit 6 position. */ #define USART_BSEL7_bm (1<<7) /* Baud Rate Selection Bits [7:0] bit 7 mask. */ #define USART_BSEL7_bp 7 /* Baud Rate Selection Bits [7:0] bit 7 position. */ /* USART.BAUDCTRLB bit masks and bit positions */ #define USART_BSCALE_gm 0xF0 /* Baud Rate Scale group mask. */ #define USART_BSCALE_gp 4 /* Baud Rate Scale group position. */ #define USART_BSCALE0_bm (1<<4) /* Baud Rate Scale bit 0 mask. */ #define USART_BSCALE0_bp 4 /* Baud Rate Scale bit 0 position. */ #define USART_BSCALE1_bm (1<<5) /* Baud Rate Scale bit 1 mask. */ #define USART_BSCALE1_bp 5 /* Baud Rate Scale bit 1 position. */ #define USART_BSCALE2_bm (1<<6) /* Baud Rate Scale bit 2 mask. */ #define USART_BSCALE2_bp 6 /* Baud Rate Scale bit 2 position. */ #define USART_BSCALE3_bm (1<<7) /* Baud Rate Scale bit 3 mask. */ #define USART_BSCALE3_bp 7 /* Baud Rate Scale bit 3 position. */ /* USART_BSEL Predefined. */ /* USART_BSEL Predefined. */ /* SPI - Serial Peripheral Interface */ /* SPI.CTRL bit masks and bit positions */ #define SPI_CLK2X_bm 0x80 /* Enable Double Speed bit mask. */ #define SPI_CLK2X_bp 7 /* Enable Double Speed bit position. */ #define SPI_ENABLE_bm 0x40 /* Enable Module bit mask. */ #define SPI_ENABLE_bp 6 /* Enable Module bit position. */ #define SPI_DORD_bm 0x20 /* Data Order Setting bit mask. */ #define SPI_DORD_bp 5 /* Data Order Setting bit position. */ #define SPI_MASTER_bm 0x10 /* Master Operation Enable bit mask. */ #define SPI_MASTER_bp 4 /* Master Operation Enable bit position. */ #define SPI_MODE_gm 0x0C /* SPI Mode group mask. */ #define SPI_MODE_gp 2 /* SPI Mode group position. */ #define SPI_MODE0_bm (1<<2) /* SPI Mode bit 0 mask. */ #define SPI_MODE0_bp 2 /* SPI Mode bit 0 position. */ #define SPI_MODE1_bm (1<<3) /* SPI Mode bit 1 mask. */ #define SPI_MODE1_bp 3 /* SPI Mode bit 1 position. */ #define SPI_PRESCALER_gm 0x03 /* Prescaler group mask. */ #define SPI_PRESCALER_gp 0 /* Prescaler group position. */ #define SPI_PRESCALER0_bm (1<<0) /* Prescaler bit 0 mask. */ #define SPI_PRESCALER0_bp 0 /* Prescaler bit 0 position. */ #define SPI_PRESCALER1_bm (1<<1) /* Prescaler bit 1 mask. */ #define SPI_PRESCALER1_bp 1 /* Prescaler bit 1 position. */ /* SPI.INTCTRL bit masks and bit positions */ #define SPI_INTLVL_gm 0x03 /* Interrupt level group mask. */ #define SPI_INTLVL_gp 0 /* Interrupt level group position. */ #define SPI_INTLVL0_bm (1<<0) /* Interrupt level bit 0 mask. */ #define SPI_INTLVL0_bp 0 /* Interrupt level bit 0 position. */ #define SPI_INTLVL1_bm (1<<1) /* Interrupt level bit 1 mask. */ #define SPI_INTLVL1_bp 1 /* Interrupt level bit 1 position. */ /* SPI.STATUS bit masks and bit positions */ #define SPI_IF_bm 0x80 /* Interrupt Flag bit mask. */ #define SPI_IF_bp 7 /* Interrupt Flag bit position. */ #define SPI_WRCOL_bm 0x40 /* Write Collision bit mask. */ #define SPI_WRCOL_bp 6 /* Write Collision bit position. */ /* IRCOM - IR Communication Module */ /* IRCOM.CTRL bit masks and bit positions */ #define IRCOM_EVSEL_gm 0x0F /* Event Channel Select group mask. */ #define IRCOM_EVSEL_gp 0 /* Event Channel Select group position. */ #define IRCOM_EVSEL0_bm (1<<0) /* Event Channel Select bit 0 mask. */ #define IRCOM_EVSEL0_bp 0 /* Event Channel Select bit 0 position. */ #define IRCOM_EVSEL1_bm (1<<1) /* Event Channel Select bit 1 mask. */ #define IRCOM_EVSEL1_bp 1 /* Event Channel Select bit 1 position. */ #define IRCOM_EVSEL2_bm (1<<2) /* Event Channel Select bit 2 mask. */ #define IRCOM_EVSEL2_bp 2 /* Event Channel Select bit 2 position. */ #define IRCOM_EVSEL3_bm (1<<3) /* Event Channel Select bit 3 mask. */ #define IRCOM_EVSEL3_bp 3 /* Event Channel Select bit 3 position. */ /* FUSE - Fuses and Lockbits */ /* NVM_FUSES.FUSEBYTE1 bit masks and bit positions */ #define NVM_FUSES_WDWP_gm 0xF0 /* Watchdog Window Timeout Period group mask. */ #define NVM_FUSES_WDWP_gp 4 /* Watchdog Window Timeout Period group position. */ #define NVM_FUSES_WDWP0_bm (1<<4) /* Watchdog Window Timeout Period bit 0 mask. */ #define NVM_FUSES_WDWP0_bp 4 /* Watchdog Window Timeout Period bit 0 position. */ #define NVM_FUSES_WDWP1_bm (1<<5) /* Watchdog Window Timeout Period bit 1 mask. */ #define NVM_FUSES_WDWP1_bp 5 /* Watchdog Window Timeout Period bit 1 position. */ #define NVM_FUSES_WDWP2_bm (1<<6) /* Watchdog Window Timeout Period bit 2 mask. */ #define NVM_FUSES_WDWP2_bp 6 /* Watchdog Window Timeout Period bit 2 position. */ #define NVM_FUSES_WDWP3_bm (1<<7) /* Watchdog Window Timeout Period bit 3 mask. */ #define NVM_FUSES_WDWP3_bp 7 /* Watchdog Window Timeout Period bit 3 position. */ #define NVM_FUSES_WDP_gm 0x0F /* Watchdog Timeout Period group mask. */ #define NVM_FUSES_WDP_gp 0 /* Watchdog Timeout Period group position. */ #define NVM_FUSES_WDP0_bm (1<<0) /* Watchdog Timeout Period bit 0 mask. */ #define NVM_FUSES_WDP0_bp 0 /* Watchdog Timeout Period bit 0 position. */ #define NVM_FUSES_WDP1_bm (1<<1) /* Watchdog Timeout Period bit 1 mask. */ #define NVM_FUSES_WDP1_bp 1 /* Watchdog Timeout Period bit 1 position. */ #define NVM_FUSES_WDP2_bm (1<<2) /* Watchdog Timeout Period bit 2 mask. */ #define NVM_FUSES_WDP2_bp 2 /* Watchdog Timeout Period bit 2 position. */ #define NVM_FUSES_WDP3_bm (1<<3) /* Watchdog Timeout Period bit 3 mask. */ #define NVM_FUSES_WDP3_bp 3 /* Watchdog Timeout Period bit 3 position. */ /* NVM_FUSES.FUSEBYTE2 bit masks and bit positions */ #define NVM_FUSES_BOOTRST_bm 0x40 /* Boot Loader Section Reset Vector bit mask. */ #define NVM_FUSES_BOOTRST_bp 6 /* Boot Loader Section Reset Vector bit position. */ #define NVM_FUSES_TOSCSEL_bm 0x20 /* Timer Oscillator pin location bit mask. */ #define NVM_FUSES_TOSCSEL_bp 5 /* Timer Oscillator pin location bit position. */ #define NVM_FUSES_BODPD_gm 0x03 /* BOD Operation in Power-Down Mode group mask. */ #define NVM_FUSES_BODPD_gp 0 /* BOD Operation in Power-Down Mode group position. */ #define NVM_FUSES_BODPD0_bm (1<<0) /* BOD Operation in Power-Down Mode bit 0 mask. */ #define NVM_FUSES_BODPD0_bp 0 /* BOD Operation in Power-Down Mode bit 0 position. */ #define NVM_FUSES_BODPD1_bm (1<<1) /* BOD Operation in Power-Down Mode bit 1 mask. */ #define NVM_FUSES_BODPD1_bp 1 /* BOD Operation in Power-Down Mode bit 1 position. */ /* NVM_FUSES.FUSEBYTE4 bit masks and bit positions */ #define NVM_FUSES_RSTDISBL_bm 0x10 /* External Reset Disable bit mask. */ #define NVM_FUSES_RSTDISBL_bp 4 /* External Reset Disable bit position. */ #define NVM_FUSES_SUT_gm 0x0C /* Start-up Time group mask. */ #define NVM_FUSES_SUT_gp 2 /* Start-up Time group position. */ #define NVM_FUSES_SUT0_bm (1<<2) /* Start-up Time bit 0 mask. */ #define NVM_FUSES_SUT0_bp 2 /* Start-up Time bit 0 position. */ #define NVM_FUSES_SUT1_bm (1<<3) /* Start-up Time bit 1 mask. */ #define NVM_FUSES_SUT1_bp 3 /* Start-up Time bit 1 position. */ #define NVM_FUSES_WDLOCK_bm 0x02 /* Watchdog Timer Lock bit mask. */ #define NVM_FUSES_WDLOCK_bp 1 /* Watchdog Timer Lock bit position. */ /* NVM_FUSES.FUSEBYTE5 bit masks and bit positions */ #define NVM_FUSES_BODACT_gm 0x30 /* BOD Operation in Active Mode group mask. */ #define NVM_FUSES_BODACT_gp 4 /* BOD Operation in Active Mode group position. */ #define NVM_FUSES_BODACT0_bm (1<<4) /* BOD Operation in Active Mode bit 0 mask. */ #define NVM_FUSES_BODACT0_bp 4 /* BOD Operation in Active Mode bit 0 position. */ #define NVM_FUSES_BODACT1_bm (1<<5) /* BOD Operation in Active Mode bit 1 mask. */ #define NVM_FUSES_BODACT1_bp 5 /* BOD Operation in Active Mode bit 1 position. */ #define NVM_FUSES_EESAVE_bm 0x08 /* Preserve EEPROM Through Chip Erase bit mask. */ #define NVM_FUSES_EESAVE_bp 3 /* Preserve EEPROM Through Chip Erase bit position. */ #define NVM_FUSES_BODLVL_gm 0x07 /* Brownout Detection Voltage Level group mask. */ #define NVM_FUSES_BODLVL_gp 0 /* Brownout Detection Voltage Level group position. */ #define NVM_FUSES_BODLVL0_bm (1<<0) /* Brownout Detection Voltage Level bit 0 mask. */ #define NVM_FUSES_BODLVL0_bp 0 /* Brownout Detection Voltage Level bit 0 position. */ #define NVM_FUSES_BODLVL1_bm (1<<1) /* Brownout Detection Voltage Level bit 1 mask. */ #define NVM_FUSES_BODLVL1_bp 1 /* Brownout Detection Voltage Level bit 1 position. */ #define NVM_FUSES_BODLVL2_bm (1<<2) /* Brownout Detection Voltage Level bit 2 mask. */ #define NVM_FUSES_BODLVL2_bp 2 /* Brownout Detection Voltage Level bit 2 position. */ /* LOCKBIT - Fuses and Lockbits */ /* NVM_LOCKBITS.LOCKBITS bit masks and bit positions */ #define NVM_LOCKBITS_BLBB_gm 0xC0 /* Boot Lock Bits - Boot Section group mask. */ #define NVM_LOCKBITS_BLBB_gp 6 /* Boot Lock Bits - Boot Section group position. */ #define NVM_LOCKBITS_BLBB0_bm (1<<6) /* Boot Lock Bits - Boot Section bit 0 mask. */ #define NVM_LOCKBITS_BLBB0_bp 6 /* Boot Lock Bits - Boot Section bit 0 position. */ #define NVM_LOCKBITS_BLBB1_bm (1<<7) /* Boot Lock Bits - Boot Section bit 1 mask. */ #define NVM_LOCKBITS_BLBB1_bp 7 /* Boot Lock Bits - Boot Section bit 1 position. */ #define NVM_LOCKBITS_BLBA_gm 0x30 /* Boot Lock Bits - Application Section group mask. */ #define NVM_LOCKBITS_BLBA_gp 4 /* Boot Lock Bits - Application Section group position. */ #define NVM_LOCKBITS_BLBA0_bm (1<<4) /* Boot Lock Bits - Application Section bit 0 mask. */ #define NVM_LOCKBITS_BLBA0_bp 4 /* Boot Lock Bits - Application Section bit 0 position. */ #define NVM_LOCKBITS_BLBA1_bm (1<<5) /* Boot Lock Bits - Application Section bit 1 mask. */ #define NVM_LOCKBITS_BLBA1_bp 5 /* Boot Lock Bits - Application Section bit 1 position. */ #define NVM_LOCKBITS_BLBAT_gm 0x0C /* Boot Lock Bits - Application Table group mask. */ #define NVM_LOCKBITS_BLBAT_gp 2 /* Boot Lock Bits - Application Table group position. */ #define NVM_LOCKBITS_BLBAT0_bm (1<<2) /* Boot Lock Bits - Application Table bit 0 mask. */ #define NVM_LOCKBITS_BLBAT0_bp 2 /* Boot Lock Bits - Application Table bit 0 position. */ #define NVM_LOCKBITS_BLBAT1_bm (1<<3) /* Boot Lock Bits - Application Table bit 1 mask. */ #define NVM_LOCKBITS_BLBAT1_bp 3 /* Boot Lock Bits - Application Table bit 1 position. */ #define NVM_LOCKBITS_LB_gm 0x03 /* Lock Bits group mask. */ #define NVM_LOCKBITS_LB_gp 0 /* Lock Bits group position. */ #define NVM_LOCKBITS_LB0_bm (1<<0) /* Lock Bits bit 0 mask. */ #define NVM_LOCKBITS_LB0_bp 0 /* Lock Bits bit 0 position. */ #define NVM_LOCKBITS_LB1_bm (1<<1) /* Lock Bits bit 1 mask. */ #define NVM_LOCKBITS_LB1_bp 1 /* Lock Bits bit 1 position. */ // Generic Port Pins #define PIN0_bm 0x01 #define PIN0_bp 0 #define PIN1_bm 0x02 #define PIN1_bp 1 #define PIN2_bm 0x04 #define PIN2_bp 2 #define PIN3_bm 0x08 #define PIN3_bp 3 #define PIN4_bm 0x10 #define PIN4_bp 4 #define PIN5_bm 0x20 #define PIN5_bp 5 #define PIN6_bm 0x40 #define PIN6_bp 6 #define PIN7_bm 0x80 #define PIN7_bp 7 /* ========== Interrupt Vector Definitions ========== */ /* Vector 0 is the reset vector */ /* OSC interrupt vectors */ #define OSC_OSCF_vect_num 1 #define OSC_OSCF_vect _VECTOR(1) /* Oscillator Failure Interrupt (NMI) */ /* PORTC interrupt vectors */ #define PORTC_INT0_vect_num 2 #define PORTC_INT0_vect _VECTOR(2) /* External Interrupt 0 */ #define PORTC_INT1_vect_num 3 #define PORTC_INT1_vect _VECTOR(3) /* External Interrupt 1 */ /* PORTR interrupt vectors */ #define PORTR_INT0_vect_num 4 #define PORTR_INT0_vect _VECTOR(4) /* External Interrupt 0 */ #define PORTR_INT1_vect_num 5 #define PORTR_INT1_vect _VECTOR(5) /* External Interrupt 1 */ /* RTC interrupt vectors */ #define RTC_OVF_vect_num 10 #define RTC_OVF_vect _VECTOR(10) /* Overflow Interrupt */ #define RTC_COMP_vect_num 11 #define RTC_COMP_vect _VECTOR(11) /* Compare Interrupt */ /* TWIC interrupt vectors */ #define TWIC_TWIS_vect_num 12 #define TWIC_TWIS_vect _VECTOR(12) /* TWI Slave Interrupt */ #define TWIC_TWIM_vect_num 13 #define TWIC_TWIM_vect _VECTOR(13) /* TWI Master Interrupt */ /* TCC0 interrupt vectors */ #define TCC0_OVF_vect_num 14 #define TCC0_OVF_vect _VECTOR(14) /* Overflow Interrupt */ /* TCC2 interrupt vectors */ #define TCC2_LUNF_vect_num 14 #define TCC2_LUNF_vect _VECTOR(14) /* Low Byte Underflow Interrupt */ /* TCC0 interrupt vectors */ #define TCC0_ERR_vect_num 15 #define TCC0_ERR_vect _VECTOR(15) /* Error Interrupt */ /* TCC2 interrupt vectors */ #define TCC2_HUNF_vect_num 15 #define TCC2_HUNF_vect _VECTOR(15) /* High Byte Underflow Interrupt */ /* TCC0 interrupt vectors */ #define TCC0_CCA_vect_num 16 #define TCC0_CCA_vect _VECTOR(16) /* Compare or Capture A Interrupt */ /* TCC2 interrupt vectors */ #define TCC2_LCMPA_vect_num 16 #define TCC2_LCMPA_vect _VECTOR(16) /* Low Byte Compare A Interrupt */ /* TCC0 interrupt vectors */ #define TCC0_CCB_vect_num 17 #define TCC0_CCB_vect _VECTOR(17) /* Compare or Capture B Interrupt */ /* TCC2 interrupt vectors */ #define TCC2_LCMPB_vect_num 17 #define TCC2_LCMPB_vect _VECTOR(17) /* Low Byte Compare B Interrupt */ /* TCC0 interrupt vectors */ #define TCC0_CCC_vect_num 18 #define TCC0_CCC_vect _VECTOR(18) /* Compare or Capture C Interrupt */ /* TCC2 interrupt vectors */ #define TCC2_LCMPC_vect_num 18 #define TCC2_LCMPC_vect _VECTOR(18) /* Low Byte Compare C Interrupt */ /* TCC0 interrupt vectors */ #define TCC0_CCD_vect_num 19 #define TCC0_CCD_vect _VECTOR(19) /* Compare or Capture D Interrupt */ /* TCC2 interrupt vectors */ #define TCC2_LCMPD_vect_num 19 #define TCC2_LCMPD_vect _VECTOR(19) /* Low Byte Compare D Interrupt */ /* TCC1 interrupt vectors */ #define TCC1_OVF_vect_num 20 #define TCC1_OVF_vect _VECTOR(20) /* Overflow Interrupt */ #define TCC1_ERR_vect_num 21 #define TCC1_ERR_vect _VECTOR(21) /* Error Interrupt */ #define TCC1_CCA_vect_num 22 #define TCC1_CCA_vect _VECTOR(22) /* Compare or Capture A Interrupt */ #define TCC1_CCB_vect_num 23 #define TCC1_CCB_vect _VECTOR(23) /* Compare or Capture B Interrupt */ /* SPIC interrupt vectors */ #define SPIC_INT_vect_num 24 #define SPIC_INT_vect _VECTOR(24) /* SPI Interrupt */ /* USARTC0 interrupt vectors */ #define USARTC0_RXC_vect_num 25 #define USARTC0_RXC_vect _VECTOR(25) /* Reception Complete Interrupt */ #define USARTC0_DRE_vect_num 26 #define USARTC0_DRE_vect _VECTOR(26) /* Data Register Empty Interrupt */ #define USARTC0_TXC_vect_num 27 #define USARTC0_TXC_vect _VECTOR(27) /* Transmission Complete Interrupt */ /* NVM interrupt vectors */ #define NVM_EE_vect_num 32 #define NVM_EE_vect _VECTOR(32) /* EE Interrupt */ #define NVM_SPM_vect_num 33 #define NVM_SPM_vect _VECTOR(33) /* SPM Interrupt */ /* PORTB interrupt vectors */ #define PORTB_INT0_vect_num 34 #define PORTB_INT0_vect _VECTOR(34) /* External Interrupt 0 */ #define PORTB_INT1_vect_num 35 #define PORTB_INT1_vect _VECTOR(35) /* External Interrupt 1 */ /* PORTE interrupt vectors */ #define PORTE_INT0_vect_num 43 #define PORTE_INT0_vect _VECTOR(43) /* External Interrupt 0 */ #define PORTE_INT1_vect_num 44 #define PORTE_INT1_vect _VECTOR(44) /* External Interrupt 1 */ /* TWIE interrupt vectors */ #define TWIE_TWIS_vect_num 45 #define TWIE_TWIS_vect _VECTOR(45) /* TWI Slave Interrupt */ #define TWIE_TWIM_vect_num 46 #define TWIE_TWIM_vect _VECTOR(46) /* TWI Master Interrupt */ /* TCE0 interrupt vectors */ #define TCE0_OVF_vect_num 47 #define TCE0_OVF_vect _VECTOR(47) /* Overflow Interrupt */ /* TCE2 interrupt vectors */ #define TCE2_LUNF_vect_num 47 #define TCE2_LUNF_vect _VECTOR(47) /* Low Byte Underflow Interrupt */ /* TCE0 interrupt vectors */ #define TCE0_ERR_vect_num 48 #define TCE0_ERR_vect _VECTOR(48) /* Error Interrupt */ /* TCE2 interrupt vectors */ #define TCE2_HUNF_vect_num 48 #define TCE2_HUNF_vect _VECTOR(48) /* High Byte Underflow Interrupt */ /* TCE0 interrupt vectors */ #define TCE0_CCA_vect_num 49 #define TCE0_CCA_vect _VECTOR(49) /* Compare or Capture A Interrupt */ /* TCE2 interrupt vectors */ #define TCE2_LCMPA_vect_num 49 #define TCE2_LCMPA_vect _VECTOR(49) /* Low Byte Compare A Interrupt */ /* TCE0 interrupt vectors */ #define TCE0_CCB_vect_num 50 #define TCE0_CCB_vect _VECTOR(50) /* Compare or Capture B Interrupt */ /* TCE2 interrupt vectors */ #define TCE2_LCMPB_vect_num 50 #define TCE2_LCMPB_vect _VECTOR(50) /* Low Byte Compare B Interrupt */ /* TCE0 interrupt vectors */ #define TCE0_CCC_vect_num 51 #define TCE0_CCC_vect _VECTOR(51) /* Compare or Capture C Interrupt */ /* TCE2 interrupt vectors */ #define TCE2_LCMPC_vect_num 51 #define TCE2_LCMPC_vect _VECTOR(51) /* Low Byte Compare C Interrupt */ /* TCE0 interrupt vectors */ #define TCE0_CCD_vect_num 52 #define TCE0_CCD_vect _VECTOR(52) /* Compare or Capture D Interrupt */ /* TCE2 interrupt vectors */ #define TCE2_LCMPD_vect_num 52 #define TCE2_LCMPD_vect _VECTOR(52) /* Low Byte Compare D Interrupt */ /* USARTE0 interrupt vectors */ #define USARTE0_RXC_vect_num 58 #define USARTE0_RXC_vect _VECTOR(58) /* Reception Complete Interrupt */ #define USARTE0_DRE_vect_num 59 #define USARTE0_DRE_vect _VECTOR(59) /* Data Register Empty Interrupt */ #define USARTE0_TXC_vect_num 60 #define USARTE0_TXC_vect _VECTOR(60) /* Transmission Complete Interrupt */ /* PORTD interrupt vectors */ #define PORTD_INT0_vect_num 64 #define PORTD_INT0_vect _VECTOR(64) /* External Interrupt 0 */ #define PORTD_INT1_vect_num 65 #define PORTD_INT1_vect _VECTOR(65) /* External Interrupt 1 */ /* PORTA interrupt vectors */ #define PORTA_INT0_vect_num 66 #define PORTA_INT0_vect _VECTOR(66) /* External Interrupt 0 */ #define PORTA_INT1_vect_num 67 #define PORTA_INT1_vect _VECTOR(67) /* External Interrupt 1 */ /* ACA interrupt vectors */ #define ACA_AC0_vect_num 68 #define ACA_AC0_vect _VECTOR(68) /* AC0 Interrupt */ #define ACA_AC1_vect_num 69 #define ACA_AC1_vect _VECTOR(69) /* AC1 Interrupt */ #define ACA_ACW_vect_num 70 #define ACA_ACW_vect _VECTOR(70) /* ACW Window Mode Interrupt */ /* ADCA interrupt vectors */ #define ADCA_CH0_vect_num 71 #define ADCA_CH0_vect _VECTOR(71) /* Interrupt 0 */ /* TCD0 interrupt vectors */ #define TCD0_OVF_vect_num 77 #define TCD0_OVF_vect _VECTOR(77) /* Overflow Interrupt */ /* TCD2 interrupt vectors */ #define TCD2_LUNF_vect_num 77 #define TCD2_LUNF_vect _VECTOR(77) /* Low Byte Underflow Interrupt */ /* TCD0 interrupt vectors */ #define TCD0_ERR_vect_num 78 #define TCD0_ERR_vect _VECTOR(78) /* Error Interrupt */ /* TCD2 interrupt vectors */ #define TCD2_HUNF_vect_num 78 #define TCD2_HUNF_vect _VECTOR(78) /* High Byte Underflow Interrupt */ /* TCD0 interrupt vectors */ #define TCD0_CCA_vect_num 79 #define TCD0_CCA_vect _VECTOR(79) /* Compare or Capture A Interrupt */ /* TCD2 interrupt vectors */ #define TCD2_LCMPA_vect_num 79 #define TCD2_LCMPA_vect _VECTOR(79) /* Low Byte Compare A Interrupt */ /* TCD0 interrupt vectors */ #define TCD0_CCB_vect_num 80 #define TCD0_CCB_vect _VECTOR(80) /* Compare or Capture B Interrupt */ /* TCD2 interrupt vectors */ #define TCD2_LCMPB_vect_num 80 #define TCD2_LCMPB_vect _VECTOR(80) /* Low Byte Compare B Interrupt */ /* TCD0 interrupt vectors */ #define TCD0_CCC_vect_num 81 #define TCD0_CCC_vect _VECTOR(81) /* Compare or Capture C Interrupt */ /* TCD2 interrupt vectors */ #define TCD2_LCMPC_vect_num 81 #define TCD2_LCMPC_vect _VECTOR(81) /* Low Byte Compare C Interrupt */ /* TCD0 interrupt vectors */ #define TCD0_CCD_vect_num 82 #define TCD0_CCD_vect _VECTOR(82) /* Compare or Capture D Interrupt */ /* TCD2 interrupt vectors */ #define TCD2_LCMPD_vect_num 82 #define TCD2_LCMPD_vect _VECTOR(82) /* Low Byte Compare D Interrupt */ /* SPID interrupt vectors */ #define SPID_INT_vect_num 87 #define SPID_INT_vect _VECTOR(87) /* SPI Interrupt */ /* USARTD0 interrupt vectors */ #define USARTD0_RXC_vect_num 88 #define USARTD0_RXC_vect _VECTOR(88) /* Reception Complete Interrupt */ #define USARTD0_DRE_vect_num 89 #define USARTD0_DRE_vect _VECTOR(89) /* Data Register Empty Interrupt */ #define USARTD0_TXC_vect_num 90 #define USARTD0_TXC_vect _VECTOR(90) /* Transmission Complete Interrupt */ /* PORTF interrupt vectors */ #define PORTF_INT0_vect_num 104 #define PORTF_INT0_vect _VECTOR(104) /* External Interrupt 0 */ #define PORTF_INT1_vect_num 105 #define PORTF_INT1_vect _VECTOR(105) /* External Interrupt 1 */ /* TCF0 interrupt vectors */ #define TCF0_OVF_vect_num 108 #define TCF0_OVF_vect _VECTOR(108) /* Overflow Interrupt */ /* TCF2 interrupt vectors */ #define TCF2_LUNF_vect_num 108 #define TCF2_LUNF_vect _VECTOR(108) /* Low Byte Underflow Interrupt */ /* TCF0 interrupt vectors */ #define TCF0_ERR_vect_num 109 #define TCF0_ERR_vect _VECTOR(109) /* Error Interrupt */ /* TCF2 interrupt vectors */ #define TCF2_HUNF_vect_num 109 #define TCF2_HUNF_vect _VECTOR(109) /* High Byte Underflow Interrupt */ /* TCF0 interrupt vectors */ #define TCF0_CCA_vect_num 110 #define TCF0_CCA_vect _VECTOR(110) /* Compare or Capture A Interrupt */ /* TCF2 interrupt vectors */ #define TCF2_LCMPA_vect_num 110 #define TCF2_LCMPA_vect _VECTOR(110) /* Low Byte Compare A Interrupt */ /* TCF0 interrupt vectors */ #define TCF0_CCB_vect_num 111 #define TCF0_CCB_vect _VECTOR(111) /* Compare or Capture B Interrupt */ /* TCF2 interrupt vectors */ #define TCF2_LCMPB_vect_num 111 #define TCF2_LCMPB_vect _VECTOR(111) /* Low Byte Compare B Interrupt */ /* TCF0 interrupt vectors */ #define TCF0_CCC_vect_num 112 #define TCF0_CCC_vect _VECTOR(112) /* Compare or Capture C Interrupt */ /* TCF2 interrupt vectors */ #define TCF2_LCMPC_vect_num 112 #define TCF2_LCMPC_vect _VECTOR(112) /* Low Byte Compare C Interrupt */ /* TCF0 interrupt vectors */ #define TCF0_CCD_vect_num 113 #define TCF0_CCD_vect _VECTOR(113) /* Compare or Capture D Interrupt */ /* TCF2 interrupt vectors */ #define TCF2_LCMPD_vect_num 113 #define TCF2_LCMPD_vect _VECTOR(113) /* Low Byte Compare D Interrupt */ /* USB interrupt vectors */ #define USB_BUSEVENT_vect_num 125 #define USB_BUSEVENT_vect _VECTOR(125) /* SOF, suspend, resume, reset bus event interrupts, crc, underflow, overflow and stall error interrupts */ #define USB_TRNCOMPL_vect_num 126 #define USB_TRNCOMPL_vect _VECTOR(126) /* Transaction complete interrupt */ #define _VECTOR_SIZE 4 /* Size of individual vector. */ #define _VECTORS_SIZE (127 * _VECTOR_SIZE) /* ========== Constants ========== */ #define PROGMEM_START (0x0000) #define PROGMEM_SIZE (270336) #define PROGMEM_END (PROGMEM_START + PROGMEM_SIZE - 1) #define APP_SECTION_START (0x0000) #define APP_SECTION_SIZE (262144) #define APP_SECTION_PAGE_SIZE (512) #define APP_SECTION_END (APP_SECTION_START + APP_SECTION_SIZE - 1) #define APPTABLE_SECTION_START (0x3E000) #define APPTABLE_SECTION_SIZE (8192) #define APPTABLE_SECTION_PAGE_SIZE (512) #define APPTABLE_SECTION_END (APPTABLE_SECTION_START + APPTABLE_SECTION_SIZE - 1) #define BOOT_SECTION_START (0x40000) #define BOOT_SECTION_SIZE (8192) #define BOOT_SECTION_PAGE_SIZE (512) #define BOOT_SECTION_END (BOOT_SECTION_START + BOOT_SECTION_SIZE - 1) #define DATAMEM_START (0x0000) #define DATAMEM_SIZE (24576) #define DATAMEM_END (DATAMEM_START + DATAMEM_SIZE - 1) #define IO_START (0x0000) #define IO_SIZE (4096) #define IO_PAGE_SIZE (0) #define IO_END (IO_START + IO_SIZE - 1) #define MAPPED_EEPROM_START (0x1000) #define MAPPED_EEPROM_SIZE (4096) #define MAPPED_EEPROM_PAGE_SIZE (0) #define MAPPED_EEPROM_END (MAPPED_EEPROM_START + MAPPED_EEPROM_SIZE - 1) #define INTERNAL_SRAM_START (0x2000) #define INTERNAL_SRAM_SIZE (16384) #define INTERNAL_SRAM_PAGE_SIZE (0) #define INTERNAL_SRAM_END (INTERNAL_SRAM_START + INTERNAL_SRAM_SIZE - 1) #define EEPROM_START (0x0000) #define EEPROM_SIZE (4096) #define EEPROM_PAGE_SIZE (32) #define EEPROM_END (EEPROM_START + EEPROM_SIZE - 1) #define SIGNATURES_START (0x0000) #define SIGNATURES_SIZE (3) #define SIGNATURES_PAGE_SIZE (0) #define SIGNATURES_END (SIGNATURES_START + SIGNATURES_SIZE - 1) #define FUSES_START (0x0000) #define FUSES_SIZE (6) #define FUSES_PAGE_SIZE (0) #define FUSES_END (FUSES_START + FUSES_SIZE - 1) #define LOCKBITS_START (0x0000) #define LOCKBITS_SIZE (1) #define LOCKBITS_PAGE_SIZE (0) #define LOCKBITS_END (LOCKBITS_START + LOCKBITS_SIZE - 1) #define USER_SIGNATURES_START (0x0000) #define USER_SIGNATURES_SIZE (512) #define USER_SIGNATURES_PAGE_SIZE (512) #define USER_SIGNATURES_END (USER_SIGNATURES_START + USER_SIGNATURES_SIZE - 1) #define PROD_SIGNATURES_START (0x0000) #define PROD_SIGNATURES_SIZE (64) #define PROD_SIGNATURES_PAGE_SIZE (512) #define PROD_SIGNATURES_END (PROD_SIGNATURES_START + PROD_SIGNATURES_SIZE - 1) #define FLASHSTART PROGMEM_START #define FLASHEND PROGMEM_END #define SPM_PAGESIZE 512 #define RAMSTART INTERNAL_SRAM_START #define RAMSIZE INTERNAL_SRAM_SIZE #define RAMEND INTERNAL_SRAM_END #define E2END EEPROM_END #define E2PAGESIZE EEPROM_PAGE_SIZE /* ========== Fuses ========== */ #define FUSE_MEMORY_SIZE 6 /* Fuse Byte 0 Reserved */ /* Fuse Byte 1 */ #define FUSE_WDP0 (unsigned char)~_BV(0) /* Watchdog Timeout Period Bit 0 */ #define FUSE_WDP1 (unsigned char)~_BV(1) /* Watchdog Timeout Period Bit 1 */ #define FUSE_WDP2 (unsigned char)~_BV(2) /* Watchdog Timeout Period Bit 2 */ #define FUSE_WDP3 (unsigned char)~_BV(3) /* Watchdog Timeout Period Bit 3 */ #define FUSE_WDWP0 (unsigned char)~_BV(4) /* Watchdog Window Timeout Period Bit 0 */ #define FUSE_WDWP1 (unsigned char)~_BV(5) /* Watchdog Window Timeout Period Bit 1 */ #define FUSE_WDWP2 (unsigned char)~_BV(6) /* Watchdog Window Timeout Period Bit 2 */ #define FUSE_WDWP3 (unsigned char)~_BV(7) /* Watchdog Window Timeout Period Bit 3 */ #define FUSE1_DEFAULT (0xFF) /* Fuse Byte 2 */ #define FUSE_BODPD0 (unsigned char)~_BV(0) /* BOD Operation in Power-Down Mode Bit 0 */ #define FUSE_BODPD1 (unsigned char)~_BV(1) /* BOD Operation in Power-Down Mode Bit 1 */ #define FUSE_TOSCSEL (unsigned char)~_BV(5) /* Timer Oscillator pin location */ #define FUSE_BOOTRST (unsigned char)~_BV(6) /* Boot Loader Section Reset Vector */ #define FUSE2_DEFAULT (0xFF) /* Fuse Byte 3 Reserved */ /* Fuse Byte 4 */ #define FUSE_WDLOCK (unsigned char)~_BV(1) /* Watchdog Timer Lock */ #define FUSE_SUT0 (unsigned char)~_BV(2) /* Start-up Time Bit 0 */ #define FUSE_SUT1 (unsigned char)~_BV(3) /* Start-up Time Bit 1 */ #define FUSE_RSTDISBL (unsigned char)~_BV(4) /* External Reset Disable */ #define FUSE4_DEFAULT (0xFF) /* Fuse Byte 5 */ #define FUSE_BODLVL0 (unsigned char)~_BV(0) /* Brownout Detection Voltage Level Bit 0 */ #define FUSE_BODLVL1 (unsigned char)~_BV(1) /* Brownout Detection Voltage Level Bit 1 */ #define FUSE_BODLVL2 (unsigned char)~_BV(2) /* Brownout Detection Voltage Level Bit 2 */ #define FUSE_EESAVE (unsigned char)~_BV(3) /* Preserve EEPROM Through Chip Erase */ #define FUSE_BODACT0 (unsigned char)~_BV(4) /* BOD Operation in Active Mode Bit 0 */ #define FUSE_BODACT1 (unsigned char)~_BV(5) /* BOD Operation in Active Mode Bit 1 */ #define FUSE5_DEFAULT (0xFF) /* ========== Lock Bits ========== */ #define __LOCK_BITS_EXIST #define __BOOT_LOCK_APPLICATION_TABLE_BITS_EXIST #define __BOOT_LOCK_APPLICATION_BITS_EXIST #define __BOOT_LOCK_BOOT_BITS_EXIST /* ========== Signature ========== */ #define SIGNATURE_0 0x1E #define SIGNATURE_1 0x98 #define SIGNATURE_2 0x46 /* ========== Power Reduction Condition Definitions ========== */ /* PR.PRGEN */ #define __AVR_HAVE_PRGEN (PR_USB_bm|PR_AES_bm|PR_RTC_bm|PR_EVSYS_bm|PR_DMA_bm) #define __AVR_HAVE_PRGEN_USB #define __AVR_HAVE_PRGEN_AES #define __AVR_HAVE_PRGEN_RTC #define __AVR_HAVE_PRGEN_EVSYS #define __AVR_HAVE_PRGEN_DMA /* PR.PRPA */ #define __AVR_HAVE_PRPA (PR_ADC_bm|PR_AC_bm) #define __AVR_HAVE_PRPA_ADC #define __AVR_HAVE_PRPA_AC /* PR.PRPC */ #define __AVR_HAVE_PRPC (PR_TWI_bm|PR_USART1_bm|PR_USART0_bm|PR_SPI_bm|PR_HIRES_bm|PR_TC1_bm|PR_TC0_bm) #define __AVR_HAVE_PRPC_TWI #define __AVR_HAVE_PRPC_USART1 #define __AVR_HAVE_PRPC_USART0 #define __AVR_HAVE_PRPC_SPI #define __AVR_HAVE_PRPC_HIRES #define __AVR_HAVE_PRPC_TC1 #define __AVR_HAVE_PRPC_TC0 /* PR.PRPD */ #define __AVR_HAVE_PRPD (PR_USART0_bm|PR_SPI_bm|PR_TC0_bm) #define __AVR_HAVE_PRPD_USART0 #define __AVR_HAVE_PRPD_SPI #define __AVR_HAVE_PRPD_TC0 /* PR.PRPE */ #define __AVR_HAVE_PRPE (PR_TWI_bm|PR_USART0_bm|PR_TC0_bm) #define __AVR_HAVE_PRPE_TWI #define __AVR_HAVE_PRPE_USART0 #define __AVR_HAVE_PRPE_TC0 /* PR.PRPF */ #define __AVR_HAVE_PRPF (PR_USART0_bm|PR_TC0_bm) #define __AVR_HAVE_PRPF_USART0 #define __AVR_HAVE_PRPF_TC0 #endif /* #ifdef _AVR_ATXMEGA256C3_H_INCLUDED */
Premik/pysimavr
pysimavr/swig/include/avr/iox256c3.h
C
gpl-3.0
281,925
FROM fedora:22 RUN dnf -y groupinstall 'Xfce Desktop' && \ dnf -y install \ supervisor \ xrdp \ && dnf clean all RUN useradd foo && \ echo foo:bar | chpasswd # http://sigkillit.com/2013/02/26/how-to-remotely-access-linux-from-windows/ COPY etc/ /etc/ # Allow all users to connect via RDP. RUN sed -i '/TerminalServerUsers/d' /etc/xrdp/sesman.ini && \ sed -i '/TerminalServerAdmins/d' /etc/xrdp/sesman.ini EXPOSE 3389 CMD ["supervisord", "-n"] ARG CI_BUILD_URL ARG BUILD_DATE ARG VCS_REF LABEL \ io.github.jumanjiman.ci-build-url=${CI_BUILD_URL} \ io.github.jumanjiman.build-date=${BUILD_DATE} \ io.github.jumanjiman.vcs-ref=${VCS_REF} \ io.github.jumanjiman.version="Fedora" \ io.github.jumanjiman.license="GPL v3" \ io.github.jumanjiman.docker.dockerfile="/fedora/Dockerfile" \ io.github.jumanjiman.vcs-type="Git" \ io.github.jumanjiman.vcs-url="https://github.com/jumanjiman/docker-xrdp.git"
jumanjiman/docker-xrdp
fedora/Dockerfile
Dockerfile
gpl-3.0
957
#!/bin/bash ############################################################################### # Build the sample Qt Widgets Application that comes with Qt Creator ############################################################################### cd tests/QtWidgetsApplication/ if [ -e build/ ] ; then rm -rf build/ fi mkdir build cd build/ qmake ../QtWidgetsApplication.pro make -j2 cd ../../../ ############################################################################### # Build the sample Qt Quick Controls 2 Application that comes with Qt Creator ############################################################################### cd tests/QtQuickControls2Application/ if [ -e build/ ] ; then rm -rf build/ fi mkdir build cd build/ qmake ../QtQuickControls2Application.pro make -j2 cd ../../../ ############################################################################### # Build the sample Qt WebEngine Application ############################################################################### cd tests/QtWebEngineApplication/ if [ -e build/ ] ; then rm -rf build/ fi mkdir build cd build/ qmake ../QtWebEngineApplication.pro make -j2 cd ../../../ ############################################################################### # Workaround for: # https://github.com/probonopd/linuxdeployqt/issues/65 ############################################################################### unset QT_PLUGIN_PATH unset LD_LIBRARY_PATH unset QTDIR ############################################################################### # Test bundling the sample Qt Widgets Application that comes with Qt Creator ############################################################################### cd tests/QtWidgetsApplication/build/ mkdir -p nonfhs fhs/usr/bin cp QtWidgetsApplication nonfhs/ ../../../linuxdeployqt-*-x86_64.AppImage nonfhs/QtWidgetsApplication ldd nonfhs/QtWidgetsApplication find nonfhs/ LD_DEBUG=libs nonfhs/QtWidgetsApplication & sleep 5 killall QtWidgetsApplication && echo "SUCCESS" cp QtWidgetsApplication fhs/usr/bin/ ../../../linuxdeployqt-*-x86_64.AppImage fhs/usr/bin/QtWidgetsApplication ldd fhs/usr/bin/QtWidgetsApplication find fhs/ LD_DEBUG=libs fhs/usr/bin/QtWidgetsApplication & sleep 5 killall QtWidgetsApplication && echo "SUCCESS" cd ../../../ ############################################################################### # Test bundling the sample Qt Quick Controls 2 Application that comes with Qt Creator ############################################################################### cd tests/QtQuickControls2Application/build/ mkdir -p nonfhs fhs/usr/bin cp QtQuickControls2Application nonfhs/ ../../../linuxdeployqt-*-x86_64.AppImage nonfhs/QtQuickControls2Application -qmldir=../ ../../../linuxdeployqt-*-x86_64.AppImage nonfhs/QtQuickControls2Application -qmldir=../ # FIXME, Workaround for: https://github.com/probonopd/linuxdeployqt/issues/25 ldd nonfhs/QtQuickControls2Application find nonfhs/ LD_DEBUG=libs nonfhs/QtQuickControls2Application & sleep 10 killall QtQuickControls2Application && echo "SUCCESS" cp QtQuickControls2Application fhs/usr/bin/ ../../../linuxdeployqt-*-x86_64.AppImage fhs/usr/bin/QtQuickControls2Application -qmldir=../ ../../../linuxdeployqt-*-x86_64.AppImage fhs/usr/bin/QtQuickControls2Application -qmldir=../ # FIXME, Workaround for: https://github.com/probonopd/linuxdeployqt/issues/25 ldd fhs/usr/bin/QtQuickControls2Application find fhs/ LD_DEBUG=libs fhs/usr/bin/QtQuickControls2Application & sleep 10 killall QtQuickControls2Application && echo "SUCCESS" cd ../../../ ############################################################################### # Test bundling the sample Qt WebEngine Application ############################################################################### cd tests/QtWebEngineApplication/build/ mkdir -p nonfhs fhs/usr/bin cp QtWebEngineApplication nonfhs/ ../../../linuxdeployqt-*-x86_64.AppImage nonfhs/QtWebEngineApplication -qmldir=../ ../../../linuxdeployqt-*-x86_64.AppImage nonfhs/QtWebEngineApplication -qmldir=../ # FIXME, Workaround for: https://github.com/probonopd/linuxdeployqt/issues/25 ldd nonfhs/QtWebEngineApplication find nonfhs/ LD_DEBUG=libs nonfhs/QtWebEngineApplication & sleep 10 killall QtWebEngineApplication && echo "SUCCESS" cp QtWebEngineApplication fhs/usr/bin/ ../../../linuxdeployqt-*-x86_64.AppImage fhs/usr/bin/QtWebEngineApplication -qmldir=../ ../../../linuxdeployqt-*-x86_64.AppImage fhs/usr/bin/QtWebEngineApplication -qmldir=../ # FIXME, Workaround for: https://github.com/probonopd/linuxdeployqt/issues/25 ldd fhs/usr/bin/QtWebEngineApplication find fhs/ LD_DEBUG=libs fhs/usr/bin/QtWebEngineApplication & sleep 10 killall QtWebEngineApplication && echo "SUCCESS" cd ../../../
hipersayanX/linuxdeployqt
tests/tests.sh
Shell
gpl-3.0
4,736
# eoss-catalog-theme/sass/var This folder contains variable declaration files named by their component class.
eoss-cloud/madxxx_catalog_client
extgui/packages/local/eoss-catalog-theme/sass/var/Readme.md
Markdown
gpl-3.0
111
[![Stories in Ready](https://badge.waffle.io/nemestats/nemestats.png?label=ready&title=Ready)](https://waffle.io/nemestats/nemestats) NemeStats [![Build status](https://ci.appveyor.com/api/projects/status/q5d26a5d8v7occ16?svg=true)](https://ci.appveyor.com/project/cracker4o/nemestats) [![Code Triagers Badge](https://www.codetriage.com/nemestats/nemestats/badges/users.svg)](https://www.codetriage.com/nemestats/nemestats) =============== NemeStats.com was created as a fun and completely free website for tracking games played and won among a fairly stable group of players. Recording your games will reveal each player's Nemesis (and their Minions), will assign Champions to games (and other badges), will award [Achievements](https://nemestats.com/achievements) and will provide many other interesting statistics. NemeStats has [a full-featured REST API](http://docs.nemestatsapiversion2.apiary.io/#) which you are completely entitled to use as a back-end for your own site or application. The API is currently at version 2. For more information on the REST API, check out the [Apiary documentation](http://docs.nemestatsapiversion2.apiary.io/#). The site is actively being developed by a number off contributors. The code base is being constantly refactored in an effort to maintain a clean and sustainable project. We encourage constructive feedback, feature requests, or even pull requests if you'd like to add a feature yourself (but please TDD or at least unit test it :)). The following GitHub projects and corresponding NuGet packages were spawned as a result of building NemeStats.com: * [Universal Analytics for DotNet](https://github.com/RIDGIDSoftwareSolutions/Universal-Analytics-For-DotNet) - This is a .NET wrapper over Google's Universal Analytics Measurement Protocol and is used to push custom events to Universal Analytics from the server side. * [Versioned REST API](https://github.com/RIDGIDSoftwareSolutions/versioned-rest-api) - This simple project allows us to easily handle versioning of the REST API via the url (e.g. /api/v2/Players). If you are interested in contributing, check out [the contributors readme](https://github.com/NemeStats/NemeStats/blob/master/Contributors.md) Catch us @nemestats or @jakejgordon on Twitter, or via nemestats@gmail.com. ### Manually Regenerating Sitemaps To manually regenerate sitemap.xml files, run the RegenerateSitemapsIntegrationTests.It_Regenerates_All_Of_The_Sitemaps_And_The_Sitemap_Index_Files() integration test with the BusinessLogic.Tests app.config pointed to the production database. Files will be placed in the designated location from the app.config sitemapLocationFilePath app setting. These files then need to be copied into the Web.UI/sitemaps/ folder to overwrite that is there. Make sure you don't check in the production database connection string!
NemeStats/NemeStats
README.md
Markdown
gpl-3.0
2,843
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import Menu from '../Menu'; describe('Pure', () => { describe('Menu.ItemLabel', () => { it('should be: <span>OK</span>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.ItemLabel label='OK' />); h.should.be.equal('<span>OK</span>'); }); it('should be: <span>OK</span>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.ItemLabel label={{text: 'OK'}} />); h.should.be.equal('<span>OK</span>'); }); it('should be: <a href="#" class="pure-menu-link">OK</a>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.ItemLabel label={{text: 'OK', url: '#'}} />); h.should.be.equal('<a href="#" class="pure-menu-link">OK</a>'); }); it('should be: <span class="pure-menu-heading">OK</span>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.ItemLabel label={{text: 'OK', heading: true}} />); h.should.be.equal('<span class="pure-menu-heading">OK</span>'); }); it('should be: <a href="#" class="pure-menu-link pure-menu-heading">OK</a>', () => { var label = {text: 'OK', url: '#', heading: true}; const h = ReactDOMServer.renderToStaticMarkup(<Menu.ItemLabel label={label} />); h.should.be.equal('<a href="#" class="pure-menu-link pure-menu-heading">OK</a>'); }); }); describe('Menu.Item', () => { it('should be: <li class="pure-menu-item"><span>OK</span></li>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.Item label='OK' />); h.should.be.equal('<li class="pure-menu-item"><span>OK</span></li>'); }); it('should be: <li class="pure-menu-item pure-menu-allow-hover"><span>OK</span></li>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.Item allowHover={true} label='OK' />); h.should.be.equal('<li class="pure-menu-item pure-menu-allow-hover"><span>OK</span></li>'); }); it('should be: <li class="pure-menu-item pure-menu-disabled"><span>OK</span></li>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.Item disabled={true} label="OK" />); h.should.be.equal('<li class="pure-menu-item pure-menu-disabled"><span>OK</span></li>'); }); it('should be: <ul class="pure-menu-children"></ul>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.Item items={[]} label="OK" />); h.should.be.equal([ '<li class="pure-menu-item pure-menu-has-children"><span>OK</span>', '<ul class="pure-menu-children"></ul></li>' ].join('')); }); it('should has: <li class="pure-menu-item"><span>Sub1</span></li><li class="pure-menu-item"><span>Sub2</span></li>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.Item items={[{label: 'Sub1'}, {label: 'Sub2'}]} label="OK" />); h.should.be.equal([ '<li class="pure-menu-item pure-menu-has-children"><span>OK</span>', '<ul class="pure-menu-children">', '<li class="pure-menu-item"><span>Sub1</span></li>', '<li class="pure-menu-item"><span>Sub2</span></li>', '</ul></li>' ].join('')); }); it('should be: <li class="pure-menu-item pure-menu-selected"><span>OK</span></li>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu.Item selected={true} label="OK" />); h.should.be.equal('<li class="pure-menu-item pure-menu-selected"><span>OK</span></li>'); }); }); describe('Menu', () => { it('should be: <div class="pure-menu"><ul class="pure-menu-list"></ul></div>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu items={[]} />); h.should.be.equal('<div class="pure-menu"><ul class="pure-menu-list"></ul></div>'); }); it('should has: <li class="pure-menu-item"><span>Sub1</span></li><li class="pure-menu-item"><span>Sub2</span></li>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu items={[{label: 'Sub1'}, {label: 'Sub2'}]} />); h.should.be.equal([ '<div class="pure-menu">', '<ul class="pure-menu-list">', '<li class="pure-menu-item"><span>Sub1</span></li>', '<li class="pure-menu-item"><span>Sub2</span></li>', '</ul></div>' ].join('')); }); it('should be: <div class="pure-menu"><span>Main</span><ul class="pure-menu-list"></ul></div>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu label="Main" items={[]} />); h.should.be.equal('<div class="pure-menu"><span>Main</span><ul class="pure-menu-list"></ul></div>'); }); it('should be: <div class="pure-menu pure-menu-horizontal"><ul class="pure-menu-list"></ul></div>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu horizontal={true} items={[]} />); h.should.be.equal('<div class="pure-menu pure-menu-horizontal"><ul class="pure-menu-list"></ul></div>'); }); it('should be: <div class="pure-menu pure-menu-scrollable"><ul class="pure-menu-list"></ul></div>', () => { const h = ReactDOMServer.renderToStaticMarkup(<Menu scrollable={true} items={[]} />); h.should.be.equal('<div class="pure-menu pure-menu-scrollable"><ul class="pure-menu-list"></ul></div>'); }); }); });
panlw/react-lab
src/lib/theme/pure/__tests__/Menu-test.js
JavaScript
gpl-3.0
5,223
A UDT for holding a Date and Time
AdvancedHMI/AdvancedHMICodeSamples
EthernetIPforCLXCom/WriteUDT/DateTimeType/README.md
Markdown
gpl-3.0
34
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Reloj_Digital.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
VictorPisciotti/Asistente-Lucy
Speech Lucy/Reloj Digital/Reloj Digital/Properties/Settings.Designer.cs
C#
gpl-3.0
1,100
/* Copyright (c) 2004-2006, The Dojo Foundation All Rights Reserved. Licensed under the Academic Free License version 2.1 or above OR the modified BSD license. For more information on Dojo licensing, see: http://dojotoolkit.org/community/licensing.shtml */ { hello: "Aloha" }
calaos/calaos_web
dojo-0.4.1-widget/tests/i18n/nls/en-us-hawaii/salutations.js
JavaScript
gpl-3.0
286
var app = app || {}; $(function(){ "use-strict"; var ShiftGridApplication = Backbone.Marionette.Application.extend({ initialize: function(options) { this.shiftData = new app.GridRows(options.rows); this.shiftLayout = this.initializeLayout(options.el); // Shift Grid var gridView = new app.GridView({ collection: this.shiftData }); this.shiftLayout.grid.show(gridView); this.listenTo(gridView, "cell:click", this.initializeModal); // Pagination var paginationView = new app.GridPaginationView({ model: new app.GridPageInfo(this.shiftData.getPageInfo()) }); this.shiftLayout.pagination.show(paginationView); gridView.listenTo(paginationView.model, "change:selectedDate", gridView.changeDate); }, initializeModal: function(cellView) { /* * The cell click event is bubbled all the way up to here, where * we show the modal window where they can claim the shift. */ var cellModal = new app.ModalCellView({ model: cellView.model, collection: cellView.model.get("roles"), }); cellView.listenToOnce(cellModal, "dismiss", cellView.render); cellModal.once("show", function() { this.$el.parents(".modal").modal("show"); }); this.shiftLayout.cell_modal.show(cellModal); }, initializeLayout: function(el) { return new app.ShiftGridLayout({ application: this, el: el }); }, }); app.ShiftGridApplication = ShiftGridApplication; });
Apogaea/voldb
volunteer/static/js/shift-grid/app.js
JavaScript
gpl-3.0
1,790
# CORE: COde for Romps in Evolutionary data ### A mixture of scripts and libraries to help with sequence data manipulation, tree parsing, and other things. ## About These scripts can be used for many tasks including sequence handling, tree making, and sequence alignment. Some of these programs are mainly used as wrappers to easily run other genomics or phylogenetics programs on a bunch of files. ## CORE | Directory | Description | | ------ | ----------- | | legacy/ | Previous versions of scripts and libraries as well as defunct scripts and libraries that are no longer maintained. | | python/ | Standalone Python scripts and libraries with functions pertaining to running genomics programs, sequence handling, and tree manipulation. Also contains scripts to generate commands for many files from some common programs and an associated SLURM submission script. | | r/ | Standalone R scripts for tree manipulation and figure design. | | utils/ | Various other tools as shell scripts. |
gwct/core
README.md
Markdown
gpl-3.0
994
<!DOCTYPE html> <html lang="en"> <head> <title>Tremaine Buchanan | Resume </title> <!-- Meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Tremaine Buchanan software architect resume freelancer web developer"> <meta name="author" content="Tremaine Buchanan"> <link rel="shortcut icon" href="assets/images/favicon.ico"> <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,400italic,300italic,300,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Global CSS --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css"> <!-- Plugins CSS --> <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css"> <!-- Theme CSS --> <link id="theme-style" rel="stylesheet" href="assets/css/styles.css"> <link rel="icon" type="image/png" href="assets/images/favicon.png" sizes="32x32" /> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-81628068-1', 'auto'); ga('send', 'pageview'); </script> </head> <body> <div class="wrapper"> <div class="sidebar-wrapper"> <div class="profile-container"> <img class="profile" src="assets/images/profile.jpg" title="Tremaine Buchanan" alt="Tremaine Buchanan" /> <h1 class="name">Tremaine Buchanan</h1> <h3 class="tagline">Full Stack Web Developer / Mobile Application Developer</h3> </div><!--//profile-container--> <div class="contact-container container-block"> <ul class="list-unstyled contact-list"> <li class="phone"><i class="fa fa-phone"></i><a href="tel:876 447 7877">876 447 7877</a></li> <li class="twitter"><i class="fa fa-twitter"></i><a href="http://bit.ly/2aSw3O6" target="_blank">@tremainekb</a></li> <li class="linkedin"><i class="fa fa-linkedin"></i><a href="http://bit.ly/22c8eUH" target="_blank">http://bit.ly/22c8eUH</a></li> <li class="github"><i class="fa fa-github"></i><a href="http://bit.ly/1YtS5Yv" target="_blank">http://bit.ly/1YtS5Yv</a></li> <li><i class="fa fa-medium" aria-hidden="true"></i> <a href="http://bit.ly/2aEK4lH">http://bit.ly/2aEK4lH</a></li> <li class="email"><i class="fa fa-envelope"></i><a href="mailto: tremainekbuchanan@gmail.com">tremainekbuchanan@gmail.com</a></li> </ul> </div><!--//contact-container--> <div class="education-container container-block"> <h2 class="container-block-title">Education</h2> <div class="item"> <h4 class="degree">Bsc in Management Information Systems</h4> <h5 class="meta">Excelsior Community College</h5> <div class="time">2006 - 2011</div> </div><!--//item--> </div><!--//education-container--> <div class="languages-container container-block"> <h2 class="container-block-title">Languages</h2> <ul class="list-unstyled interests-list"> <li>English <span class="lang-desc">(Native)</span></li> </ul> </div><!--//interests--> <div class="interests-container container-block"> <h2 class="container-block-title">Interests</h2> <ul class="list-unstyled interests-list"> <li>Track and field</li> <li>Entrepreneurship</li> <li>Volunteerism</li> </ul> </div><!--//interests--> </div><!--//sidebar-wrapper--> <div class="main-wrapper"> <section class="section experiences-section"> <h2 class="section-title"><i class="fa fa-briefcase"></i>Experience</h2> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Founder/Lead Software Architect</h3> <div class="time">January 2015 - Present</div> </div><!--//upper-row--> <div class="company">876devs, Portmore, Jamaica</div> </div><!--//meta--> <div class="details"> <ul> <li>Develop web applications using the MEAN stack</li> <li>Develop mobile applications using the Android SDK and PhoneGap/Cordova/Ionic framework</li> <li>Develop RESTful APIs using PHP and Nodejs</li> </ul> </div><!--//details--> </div><!--//item--> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Web Developer</h3> <div class="time">March 2016 - Present</div> </div><!--//upper-row--> <div class="company">Ministry of Economic Growth and Job Creation, Kingston, Jamaica</div> </div><!--//meta--> <div class="details"> <li>Develop website and web applications using Bootstrap, AngularJs, JavaScript, MYSQL, PHP and Wordpress</li> <li>Develop and maintain RESTful APIs using PHP (Slim Framework)</li> <li>Provide software support for various off the shelf software packages</li> <li>Conduct requirements gathering</li> <li>Develop and document software/web applications based on requirements gathered </li> <li>Maintain existing web applications</li> </div><!--//details--> </div><!--//item--> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Software Engineer</h3> <div class="time">July 2015 - March 2016</div> </div><!--//upper-row--> <div class="company">SlashRoots Foundation, Kingston, Jamaica</div> </div><!--//meta--> <div class="details"> <li>Developed web applications using AngularJs, ExpressJs, NodeJs and MongoDB (MEAN stack) based on detailed technical requirements</li> <li>Conducted code reviews </li> <li>Lead developer coaching and training </li> <li>Participated in conferences and developer community meetups</li> </div><!--//details--> </div><!--//item--> </section><!--//section--> <section class="section projects-section"> <h2 class="section-title"><i class="fa fa-archive"></i>Projects</h2> <div class="intro"> <p>In my spare time, I create websites for profit and non-profit organizations within Jamaica and the Caribbean. I am also a Technical Director at <a href="http://youthcandoit.net/" target="_blank">YouthCanDoIt!</a> where I deliver sessions and workshops in web application development. Below are a few projects I've worked on during my career.</p> </div><!--//intro--> <div class="item"> <span class="project-title"> <a href="https://play.google.com/store/apps/details?id=com.tremainebuchanan.register" target="_blank">Register</a></span> - <span class="project-tagline">Student attendance management mobile application. Currently in beta testing at the <a href = "http://www.excelsiorhighja.com/">Excelsior High School</a></span> </div> <div class="item"> <span class="project-title"> <a href="https://jas-mis-app-staging.herokuapp.com/" target="_blank">JAMIS</a></span> - <span class="project-tagline">Marketing information system built while employed at the SlashRoots Foundation.</span> </div><!--//item--> <div class="item"> <span class="project-title"> <a href="https://coi-mapping-staging.herokuapp.com/" target="_blank">Caribbean Tech Ecosystem Map</a> </span> - <span class="project-tagline">The Caribbean Tech Ecosystem Map is an interactive, searchable, centralized database of ICT, mobile and open data stakeholders and initiatives from across the Caribbean, built while employed at SlashRoots Foundation. </span> </div><!--//item--> <div class="item"> <span class="project-title"> <a href="http://www.slashroots.org/#/" target="_blank">SlashRoots Foundation</a></span> - <span class="project-tagline">SlashRoots Foundation website used to promote and share work done by the non-profit, built while employed at SlashRoots Foundation. </span> </div><!--//item--> <div class="item"> <span class="project-title"> <a href="https://www.startuprobot.com/#/" target="_blank">StartUp Robot</a></span> - <span class="project-tagline">StartupRobot uses technology to make it really easy to set up and maintain a compliant business in Jamaica.</span> </div><!--//item--> </section><!--//section--> <section class="skills-section section"> <h2 class="section-title"><i class="fa fa-rocket"></i>Skills &amp; Proficiency</h2> <div class="skillset"> <div class="item"> <h3 class="level-title">HTML5 &amp; CSS</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="95%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Twitter Bootstrap</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="80%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Angular 1.5</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="80%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Javascript</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="80%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Nodejs</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="80%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">MongoDB</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="80%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Git, Github</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="80%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Gulp</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="60%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">Java</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="60%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">PHP</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="40%"> </div> </div><!--//level-bar--> </div><!--//item--> <div class="item"> <h3 class="level-title">MYSQL</h3> <div class="level-bar"> <div class="level-bar-inner" data-level="40%"> </div> </div><!--//level-bar--> </div><!--//item--> </div> </section><!--//skills-section--> <section class="section projects-section"> <h2 class="section-title"> <i class="fa fa-trophy" aria-hidden="true"></i>Awards</h2> <div class="item"> <span class="project-title"> <a href>May 2015</a></span> - <span class="project-tagline">Awarded 3rd place at the PitchIt Caribbean 24 hour Mobile Application Development competition. Built a web application that will assist consumers of electricity to determine total monthly consumption based on appliances inputted.</span> </div><!--//item--> <div class="item"> <span class="project-title"> <a href >March 2015</a> </span> - <span class="project-tagline">Awarded 3rd place at the Caribbean Open Data Conference and 24 hour code sprint. Built a mobile application using open shopping data to assist customers in peforming grocery store price comparisons.</span> </div><!--//item--> <div class="item"> <span class="project-title"> <a href>Principal’s Award</a></span> - <span class="project-tagline">Received award two (2) consecutive years for outstanding academic achievement whilst attending the Excelsior Community College.</span> </div><!--//item--> <div class="item"> <span class="project-title"> <a href>Academic Scholarship</a></span> - <span class="project-tagline"> Awarded academic scholarship for outstanding academic achievement attending the Excelsior Community College.</span> </div><!--//item--> </section><!--//section--> </div><!--//main-body--> </div> <footer class="footer"> <div class="text-center"> <small class="copyright">Designed with <i class="fa fa-heart"></i> by <a href="http://themes.3rdwavemedia.com" target="_blank">Xiaoying Riley</a> for developers</small> </div><!--//container--> </footer><!--//footer--> <!-- Javascript --> <script type="text/javascript" src="assets/plugins/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="assets/plugins/bootstrap/js/bootstrap.min.js"></script> <!-- custom js --> <script type="text/javascript" src="assets/js/main.js"></script> </body> </html>
tremainebuchanan/resume
public/index.html
HTML
gpl-3.0
16,823
using System; using System.Windows.Forms; using System.Threading; using System.Diagnostics; using System.Xml.Linq; using System.Net; using System.Text; using System.IO; using System.Security.Cryptography.X509Certificates; using Newegg.Oversea.Framework.JobConsole.Client; using IPPOversea.Invoicemgmt.SyncDataToFinancePay.Biz; namespace IPPOversea.Invoicemgmt.SyncDataToFinancePay { public class SyncDataToFinancePayJob : IJobAction { static ILog log = LogerManger.GetLoger(); static JobContext CurrentContext = null; static void Main(string[] args) { Start(); } /// <summary> /// 记录日志方法 /// </summary> /// <param name="info">需要记录的信息</param> static void WriteLog(string info) { log.WriteLog(info); Console.WriteLine(info); if (CurrentContext!=null) { CurrentContext.Message += info + Environment.NewLine; } } #region IJobAction Members public void Run(JobContext context) { CurrentContext = context; Start(); } private static void Start() { Stopwatch sw = new Stopwatch(); Console.ForegroundColor = ConsoleColor.Green; WriteLog("************************************************"); WriteLog("*"); WriteLog("* 在没有提示可以安全退出时,不要人为退出程序。"); WriteLog("*"); WriteLog("************************************************"); Console.ResetColor(); AutoResetEvent are = new AutoResetEvent(false); SyncDataBL.ShowInfo = new SyncDataBL.ShowMsg(WriteLog); sw.Start(); try { SyncDataBL.DoWork(are); } catch (Exception ex) { WriteLog(ex.ToString()); are.Set(); } are.WaitOne(); sw.Stop(); WriteLog("本轮结束!"); WriteLog(string.Format("本次任务共耗时 {0} 秒", sw.Elapsed.TotalSeconds)); } #endregion } }
ZeroOne71/ql
02_ECCentral/06_Job_Move/08_Invoice/IPP.InvoiceMgmt.SyncDataToFinancePay/SyncDataToFinancePay/SyncDataToFinancePayJob.cs
C#
gpl-3.0
2,297
/* * PatientView * * Copyright (c) Worth Solutions Limited 2004-2013 * * This file is part of PatientView. * * PatientView 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. * PatientView 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 PatientView in a file * titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package PatientView * @link http://www.patientview.org * @author PatientView <info@patientview.org> * @copyright Copyright (c) 2004-2013, Worth Solutions Limited * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ package org.patientview.test.utils; import org.patientview.patientview.utils.TimestampUtils; import org.joda.time.DateTime; import org.joda.time.IllegalFieldValueException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(JUnit4.class) public class TimestampUtilsTest { @Test public void testCreateTimestampGoodDay() { assertEquals("Timestamp not equal", "2012-03-15T00:00:00", new DateTime((TimestampUtils .createTimestamp("2012-03-15")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampGoodDayHourMin() { assertEquals("Timestamp not equal", "2012-03-15T04:34:00", new DateTime((TimestampUtils .createTimestamp("2012-03-15T04:34")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampGoodDayHourMinSec() { assertEquals("Timestamp not equal", "2012-03-15T14:56:45", new DateTime((TimestampUtils .createTimestamp("2012-03-15T14:56:45")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampGoodDaySlash() { assertEquals("Timestamp not equal", "2011-05-22T00:00:00", new DateTime((TimestampUtils .createTimestamp("22/05/2011")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampGoodDaySlashBackwards() { assertEquals("Timestamp not equal", "2011-05-22T00:00:00", new DateTime((TimestampUtils .createTimestamp("2011/05/22")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampGoodDayDash() { assertEquals("Timestamp not equal", "2011-05-22T00:00:00", new DateTime((TimestampUtils .createTimestamp("22-05-2011")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampBadDayOfMonth() { assertNull(TimestampUtils.createTimestamp("2012-02-32")); } @Test public void testCreateTimestampBadMonth() { assertNull(TimestampUtils.createTimestamp("2012-13-15")); } @Test public void testCreateTimestampBadDate() throws IllegalFieldValueException { assertNull(TimestampUtils.createTimestamp("asdasdasasd")); } @Test public void testCreateTimestampStartDay() { assertEquals("Timestamp not equal", "2012-03-15T00:00:00", new DateTime((TimestampUtils .createTimestampStartDay("2012-03-15")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampStartDayWithHoursEtc() { assertEquals("Timestamp not equal", "2012-03-15T00:00:00", new DateTime((TimestampUtils .createTimestampStartDay("2012-03-15T12:43:54.878")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampEndDay() { assertEquals("Timestamp not equal", "2012-03-15T23:59:59", new DateTime((TimestampUtils .createTimestampEndDay("2012-03-15")).getTime().getTime()).toString().substring(0, 19)); } @Test public void testCreateTimestampEndDayWithHoursEtc() { assertEquals("Timestamp not equal", "2012-03-15T23:59:59", new DateTime((TimestampUtils .createTimestampEndDay("2012-03-15T12:43:54.878")).getTime().getTime()).toString().substring(0, 19)); } }
robworth/patientview
patientview-parent/patientview/src/test/java/org/patientview/test/utils/TimestampUtilsTest.java
Java
gpl-3.0
4,603
// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : StaticData.h // @ Date : 2017/9/29 // @ Author : ouo // // #if !defined(_STATICDATA_H) #define _STATICDATA_H class StaticData { public: static StaticData sharedStaticData(); static viod purge(); int intValueFormKey(std::string key); char stringValueFromKey(std::string key); float floatValueFromKey(std::string key); bool booleanFromKey(std::string key); cocos2d::CCPoint pointFromKey(std::string key); cocos2d::CCRect rectFromKey(std::string key); cocos2d::CCSize sizeFromKey(std::string key); protected: const cocos2d::CCDictionary _dictionary; std::string _staticFileName; bool init(); private: ~StaticData(); StaticData(); }; #endif //_STATICDATA_H
ouopoi/StaticData
StaticData/StaticData.h
C
gpl-3.0
804
<?php /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com> * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com> * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@capnetworks.com> * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr> * Copyright (C) 2010-2012 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr> * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro> * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr> * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file htdocs/compta/facture/list.php * \ingroup facture * \brief Page to create/see an invoice */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } $langs->load('bills'); $langs->load('companies'); $langs->load('products'); $langs->load('main'); $sall=trim(GETPOST('sall')); $projectid=(GETPOST('projectid')?GETPOST('projectid','int'):0); $id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility $ref=GETPOST('ref','alpha'); $socid=GETPOST('socid','int'); $action=GETPOST('action','alpha'); $confirm=GETPOST('confirm','alpha'); $lineid=GETPOST('lineid','int'); $userid=GETPOST('userid','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); $search_refcustomer=GETPOST('search_refcustomer','alpha'); $search_societe=GETPOST('search_societe','alpha'); $search_montant_ht=GETPOST('search_montant_ht','alpha'); $search_montant_ttc=GETPOST('search_montant_ttc','alpha'); $search_status=GETPOST('search_status','alpha'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); if ($page == -1) { $page = 0; } $offset = $conf->liste_limit * $page; if (! $sortorder) $sortorder='DESC'; if (! $sortfield) $sortfield='f.datef'; $limit = $conf->liste_limit; $pageprev = $page - 1; $pagenext = $page + 1; $search_user = GETPOST('search_user','int'); $search_sale = GETPOST('search_sale','int'); $day = GETPOST('day','int'); $month = GETPOST('month','int'); $year = GETPOST('year','int'); $day_lim = GETPOST('day_lim','int'); $month_lim = GETPOST('month_lim','int'); $year_lim = GETPOST('year_lim','int'); $filtre = GETPOST('filtre'); // Security check $fieldid = (! empty($ref)?'facnumber':'rowid'); if (! empty($user->societe_id)) $socid=$user->societe_id; $result = restrictedArea($user, 'facture', $id,'','','fk_soc',$fieldid); $object=new Facture($db); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('invoicelist')); $now=dol_now(); /* * Actions */ $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // Do we click on purge search criteria ? if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { $search_categ=''; $search_user=''; $search_sale=''; $search_ref=''; $search_refcustomer=''; $search_societe=''; $search_montant_ht=''; $search_montant_ttc=''; $search_status=''; $year=''; $month=''; } /* * View */ llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes'); $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); $bankaccountstatic=new Account($db); $facturestatic=new Facture($db); if (! $sall) $sql = 'SELECT'; else $sql = 'SELECT DISTINCT'; $sql.= ' f.rowid as facid, f.facnumber, f.ref_client, f.type, f.note_private, f.increment, f.total as total_ht, f.tva as total_tva, f.total_ttc,'; $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,'; $sql.= ' f.paye as paye, f.fk_statut,'; $sql.= ' s.nom as name, s.rowid as socid, s.code_client, s.client '; if (! $sall) $sql.= ', SUM(pf.amount) as am'; // To be able to sort on status $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; else $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as fd ON fd.fk_facture = f.rowid'; // We'll need this table joined to the select in order to filter by sale if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= " AND f.entity = ".$conf->entity; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid) $sql.= ' AND s.rowid = '.$socid; if ($userid) { if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; else $sql.=' AND f.fk_user_author = '.$userid; } if ($filtre) { $aFilter = explode(',', $filtre); foreach ($aFilter as $filter) { $filt = explode(':', $filter); $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]); } } if ($search_ref) { $sql .= natural_search('f.facnumber', $search_ref); } if ($search_refcustomer) { $sql .= natural_search('f.ref_client', $search_refcustomer); } if ($search_societe) { $sql .= natural_search('s.nom', $search_societe); } if ($search_montant_ht != '') { $sql.= natural_search('f.total', $search_montant_ht, 1); } if ($search_montant_ttc != '') { $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); } if ($search_status != '') { $sql.= " AND f.fk_statut = '".$db->escape($search_status)."'"; } if ($month > 0) { if ($year > 0 && empty($day)) $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; else if ($year > 0 && ! empty($day)) $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; else $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; } else if ($year > 0) { $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_lim > 0) { if ($year_lim > 0 && empty($day_lim)) $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,$month_lim,false))."' AND '".$db->idate(dol_get_last_day($year_lim,$month_lim,false))."'"; else if ($year_lim > 0 && ! empty($day_lim)) $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_lim, $day_lim, $year_lim))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_lim, $day_lim, $year_lim))."'"; else $sql.= " AND date_format(f.date_lim_reglement, '%m') = '".$month_lim."'"; } else if ($year_lim > 0) { $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,1,false))."' AND '".$db->idate(dol_get_last_day($year_lim,12,false))."'"; } if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } if (! $sall) { $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.increment, f.total, f.tva, f.total_ttc,'; $sql.= ' f.datef, f.date_lim_reglement,'; $sql.= ' f.paye, f.fk_statut,'; $sql.= ' s.nom, s.rowid, s.code_client, s.client'; } else { $sql .= natural_search(array('s.nom', 'f.facnumber', 'f.note_public', 'fd.description'), $sall); } $sql.= ' ORDER BY '; $listfield=explode(',',$sortfield); foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.','; $sql.= ' f.rowid DESC '; $nbtotalofrecords = 0; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1,$offset); //print $sql; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); if ($socid) { $soc = new Societe($db); $soc->fetch($socid); } $param='&socid='.$socid; if ($month) $param.='&month='.$month; if ($year) $param.='&year=' .$year; if ($search_ref) $param.='&search_ref=' .$search_ref; if ($search_refcustomer) $param.='&search_refcustomer=' .$search_refcustomer; if ($search_societe) $param.='&search_societe=' .$search_societe; if ($search_sale > 0) $param.='&search_sale=' .$search_sale; if ($search_user > 0) $param.='&search_user=' .$search_user; if ($search_montant_ht != '') $param.='&search_montant_ht='.$search_montant_ht; if ($search_montant_ttc != '') $param.='&search_montant_ttc='.$search_montant_ttc; print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_accountancy.png'); $i = 0; print '<form method="GET" action="'.$_SERVER["PHP_SELF"].'">'."\n"; print '<table class="liste" width="100%">'; // If the user can view prospects other than his' $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user); $moreforfilter.=' &nbsp; &nbsp; &nbsp; '; } // If the user can view prospects other than his' if ($user->rights->societe->client->voir || $socid) { $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; $moreforfilter.=$form->select_dolusers($search_user,'search_user',1); } if ($moreforfilter) { print '<tr class="liste_titre">'; print '<td class="liste_titre" colspan="10">'; print $moreforfilter; print '</td></tr>'; } print '<tr class="liste_titre">'; print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('RefCustomer'),$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Date'),$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateDue"),$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('ThirdParty'),$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountHT'),$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountVAT'),$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountTTC'),$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Received'),$_SERVER['PHP_SELF'],'am','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut,paye,am','',$param,'align="right"',$sortfield,$sortorder); //print '<td class="liste_titre">&nbsp;</td>'; print '</tr>'; // Filters lines print '<tr class="liste_titre">'; print '<td class="liste_titre" align="left">'; print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; print '</td>'; print '<td class="liste_titre">'; print '<input class="flat" size="6" type="text" name="search_refcustomer" value="'.$search_refcustomer.'">'; print '</td>'; print '<td class="liste_titre" align="center">'; if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">'; print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; $formother->select_year($year?$year:-1,'year',1, 20, 5); print '</td>'; print '<td class="liste_titre" align="center">'; if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.$day_lim.'">'; print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.$month_lim.'">'; $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); print '</td>'; print '<td class="liste_titre" align="left"><input class="flat" type="text" size="8" name="search_societe" value="'.$search_societe.'"></td>'; print '<td class="liste_titre" align="right"><input class="flat" type="text" size="6" name="search_montant_ht" value="'.$search_montant_ht.'"></td>'; print '<td class="liste_titre" align="right">&nbsp;</td>'; print '<td class="liste_titre" align="right"><input class="flat" type="text" size="6" name="search_montant_ttc" value="'.$search_montant_ttc.'"></td>'; print '<td class="liste_titre" align="right">&nbsp;</td>'; print '<td class="liste_titre" align="right"><input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">'; print '<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">'; print "</td></tr>\n"; if ($num > 0) { $var=true; $total_ht=0; $total_tva=0; $total_ttc=0; $totalrecu=0; while ($i < min($num,$limit)) { $objp = $db->fetch_object($resql); $var=!$var; $datelimit=$db->jdate($objp->datelimite); print '<tr '.$bc[$var].'>'; print '<td class="nowrap">'; $facturestatic->id=$objp->facid; $facturestatic->ref=$objp->facnumber; $facturestatic->type=$objp->type; $notetoshow=dol_string_nohtmltag(($user->societe_id>0?$objp->note_public:$objp->note),1); $paiement = $facturestatic->getSommePaiement(); print '<table class="nobordernopadding"><tr class="nocellnopadd">'; print '<td class="nobordernopadding nowrap">'; print $facturestatic->getNomUrl(1,'',200,0,$notetoshow); print $objp->increment; print '</td>'; print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; if (! empty($objp->note_private)) { print ' <span class="note">'; print '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$objp->facid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; print '</span>'; } $filename=dol_sanitizeFileName($objp->facnumber); $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($objp->facnumber); $urlsource=$_SERVER['PHP_SELF'].'?id='.$objp->facid; print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); print '</td>'; print '</tr>'; print '</table>'; print "</td>\n"; // Customer ref print '<td class="nowrap">'; print $objp->ref_client; print '</td>'; // Date print '<td align="center" class="nowrap">'; print dol_print_date($db->jdate($objp->df),'day'); print '</td>'; // Date limit print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day'); if ($datelimit < ($now - $conf->facture->client->warning_delay) && ! $objp->paye && $objp->fk_statut == 1 && ! $paiement) { print img_warning($langs->trans('Late')); } print '</td>'; print '<td>'; $thirdparty=new Societe($db); $thirdparty->id=$objp->socid; $thirdparty->name=$objp->name; $thirdparty->client=$objp->client; $thirdparty->code_client=$objp->code_client; print $thirdparty->getNomUrl(1,'customer'); print '</td>'; print '<td align="right">'.price($objp->total_ht,0,$langs).'</td>'; print '<td align="right">'.price($objp->total_tva,0,$langs).'</td>'; print '<td align="right">'.price($objp->total_ttc,0,$langs).'</td>'; print '<td align="right">'.(! empty($paiement)?price($paiement,0,$langs):'&nbsp;').'</td>'; // Affiche statut de la facture print '<td align="right" class="nowrap">'; print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$paiement,$objp->type); print "</td>"; //print "<td>&nbsp;</td>"; print "</tr>\n"; $total_ht+=$objp->total_ht; $total_tva+=$objp->total_tva; $total_ttc+=$objp->total_ttc; $totalrecu+=$paiement; $i++; } if (($offset + $num) <= $limit) { // Print total print '<tr class="liste_total">'; print '<td class="liste_total" colspan="5" align="left">'.$langs->trans('Total').'</td>'; print '<td class="liste_total" align="right">'.price($total_ht,0,$langs).'</td>'; print '<td class="liste_total" align="right">'.price($total_tva,0,$langs).'</td>'; print '<td class="liste_total" align="right">'.price($total_ttc,0,$langs).'</td>'; print '<td class="liste_total" align="right">'.price($totalrecu,0,$langs).'</td>'; print '<td class="liste_total" align="center">&nbsp;</td>'; print '</tr>'; } } print "</table>\n"; print "</form>\n"; $db->free($resql); } else { dol_print_error($db); } llxFooter(); $db->close();
atm-maximep/dolibarr
htdocs/compta/facture/list.php
PHP
gpl-3.0
20,275
// Expects to be preceeded by javascript that creates a variable called selectRange that // defines the segment to be wrapped and replaced. // create custom range object for wrapSelection var replaceRange = $.fn.range; replaceRange.ClearVariables(); replaceRange.startContainer = selectRange.startContainer; replaceRange.startOffset = selectRange.startOffset; replaceRange.endContainer = selectRange.endContainer; replaceRange.endOffset = selectRange.endOffset; replaceRange.collapsed = selectRange.collapsed; // Wrap the text to be replaced in a set of custom spans. // This is done so we can operate on this text even if it extends over different // inline tags. var selectMarker = 'SigilReplace_' + new Date().getTime(); $().wrapSelection({fitToWord: false, selectClass: selectMarker, wrapRange: replaceRange}); // First, store the old contents so they can be undone, and then // insert the new text in the first element of the wrapped range and clear the rest. $('.'+selectMarker).each(function(n) { if(n==0){ $(this).data('undo', $(this).html()); $(this).html("$ESCAPED_TEXT_HERE"); } else { $(this).data('undo', $(this).html()); // Assign an id so that this element isn't automatically deleted. $(this).attr("id",selectMarker+n); $(this).html(''); } }); // We need to normalize the text nodes since they're screwed up now selectRange.startContainer.parentNode.normalize(); // Set the cursor to point to the end of the replaced text. selectRange.collapse( false ); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(selectRange); //Scroll to the cursor var from_top = window.innerHeight / 2; $.scrollTo( selectRange.startContainer, 0, {offset: {top:-from_top, left:0 } } ); // Return the unique class name used to identify these elements so the change can be undone. selectMarker.valueOf();
nemoisperfect/sigil
src/Sigil/Resource_Files/javascript/replace_wrapped.js
JavaScript
gpl-3.0
1,894
#pragma once #include "alarmHandler.h" #include "trans.h" #include "file.h" #include "time.h" #define ALARM_NUM 6 void alarm_load() { for (int i = 0; i < ALARM_NUM; i++) { char c[] = "ALARM_0.txt"; c[6] = i + 48; if (SD.exists(c)) { Serial.print(c); Serial.println(" exists."); myFile = SD.open(c); alarms[i].openOrNot = (bool)(strToInt(myFile.readStringUntil('\n'))); String modeStr = myFile.readStringUntil('\n'); for (int j = 0; j < 7; j++) alarms[i].mode[j] = (bool)(modeStr[j] - 48); alarms[i].repeatOrNot = (bool)(strToInt(myFile.readStringUntil('\n'))); alarms[i].h = (byte)(strToInt(myFile.readStringUntil('\n'))); alarms[i].m = (byte)(strToInt(myFile.readStringUntil('\n'))); alarms[i].repeatAllow = 1; if (alarms[i].repeatOrNot) alarms[i].repeatOnce = alarms[i].repeatTwice = 1; else alarms[i].repeatOnce = alarms[i].repeatTwice = 0; // Serial.print(alarms[i].openOrNot); // Serial.print(" "); // Serial.print(alarms[i].repeatOrNot); // Serial.print(" "); // Serial.print(modeStr); // Serial.print(" "); // Serial.print(alarms[i].h); // Serial.print(" "); // Serial.print(alarms[i].m); // Serial.print(" "); // Serial.print(alarms[i].repeatAllow); // Serial.print(" "); // Serial.print(alarms[i].repeatOnce); // Serial.print(" "); // Serial.println(alarms[i].repeatTwice); myFile.close(); } // else // { // Serial.print(c); // Serial.println(" doesn't exist."); // } } } void alarm_check() { for (int i = 0; i < ALARM_NUM; i++) { bool onAlarm = false; if (!alarms[i].openOrNot || !alarms[i].repeatAllow) continue; if (time_compare(alarms[i].h, alarms[i].m, weekday(now()) * alarms[i].mode[weekday(now()) - 1])) { onAlarm = true; } else if (alarms[i].repeatOrNot) { if (alarms[i].repeatOnce && time_compare(alarms[i].h, alarms[i].m, weekday(now()) * alarms[i].mode[weekday(now()) - 1], 1) ) { // Serial.print(alarms[i].repeatOrNot); // Serial.println(" repeat detect 1"); alarms[i].repeatOnce = 0; onAlarm = true; alarmHandler.reset_tone_now(); } else if (alarms[i].repeatTwice && time_compare(alarms[i].h, alarms[i].m, weekday(now()) * alarms[i].mode[weekday(now()) - 1], 2) ) { // Serial.println(" repeat detect 2"); alarms[i].repeatTwice = 0; onAlarm = true; alarmHandler.reset_tone_now(); } } if (onAlarm && alarmHandler.get_tone_now() != i) { // Serial.print(alarmHandler.get_tone_now()); // Serial.print(" alarm tone No: "); // Serial.println(i); alarmHandler.start_alarm(i); } } }
sqyx008/SmartBelt-Microduino-Wearable
alarm.h
C
gpl-3.0
2,816
/*==================================================================* * ___ _ _ _ _ _ * * / __(_)_ __ ___ | |__ _ _| |_ _(_)_ __ | |_ ___ _ __ * * / _\ | | '_ ` _ \| '_ \| | | | \ \ /\ / / | '_ \| __/ _ \ '__| * * / / | | | | | | | |_) | |_| | |\ V V /| | | | | || __/ | * * \/ |_|_| |_| |_|_.__/ \__,_|_| \_/\_/ |_|_| |_|\__\___|_| * * * * ------------------------------------------------------------------* * Emulator * * ------------------------------------------------------------------* * Licenced under GNU GPL v3 * * ----------------------------------------------------------------- * * Client infos Modules * * ==================================================================*/ #pragma once #include "../Common/show_message.hpp" #include "../Common/packets.hpp" #include <iostream> #include <cstdlib> #include "ZoneServer.hpp" /*! \brief Talk Area * \author Fimbulwinter Development Team * \date 31/12/11 **/ typedef enum talkarea { COMMONTALK_AREA = 0, }TalkArea; /*! \brief TypeChat * \author Fimbulwinter Development Team * \date 31/12/11 **/ typedef enum typechat { NORMAL_CHAT = 0, PARTY_CHAT, GUILD_CHAT, WHISPER_CHAT, }TypeChat; void packet_ticksend(tcp_connection::pointer cl, ZoneSessionData *sd); void packet_loadendack(tcp_connection::pointer cl, ZoneSessionData *sd); void packet_lesseffect(tcp_connection::pointer cl, ZoneSessionData *sd); void packet_wanttoconnect(tcp_connection::pointer cl, ZoneSessionData *sd); void packet_chatpackets(tcp_connection::pointer cl, struct ZoneSessionData* zd, enum typechat tc);
Fimbulwinter/Fimbulwinter
src/ZoneServer/PacketHandling.hpp
C++
gpl-3.0
1,787
@echo off if "%1"=="dbg" goto dbg bochs -q -f set/bochsrc.bxrc exit :dbg bochsdbg -q -f set/DBG_bochsrc.bxrc exit
LastAvenger/OS67
script/_bochs.bat
Batchfile
gpl-3.0
124
""" .. module: FSRStools.rraman :platform: Windows .. moduleauthor:: Daniel Dietze <daniel.dietze@berkeley.edu> Resonance Raman excitation profile calculation based on the time-domain picture of resonance Raman. See Myers and Mathies in *Biological Applications of Raman Spectroscopy*, Vol. 2, pp. 1-58 (John Wiley and Sons, New York, 1987) for details (referred to as Myers in the following). The code is mainly based on Myers' Fortran 77 code (see Appendix of PhD Thesis of K. M. Spillane, 2011, UC Berkeley for source code). **Changelog:** *10-7-2015:* - Added / modified functions for calculating fluorescence spectra. - Added a convenience function to calculate Raman spectra from a set of excitation profiles. - Added some more damping functions and phenomenological support for Stokes shift in simple homogeneous damping function. *10-21-2015:* - Some bug fixes concerning the prefactors and the normalization of the fluorescence spectra. - Fixed a bug regarding the Raman overlaps. **Example Code** Here is a short example calculating Myers' *Gedankenmolecule* from Myers and Mathies:: import numpy as np import FSRStools.rraman as rr # parameters: # ----------- # displacements D = np.array([1.27, 0.3, 0.7, 0.53]) # ground state frequencies RMg = np.array([1550.0, 1300.0, 1150.0, 1000.0]) # excited state frequencies RMe = np.array([1550.0, 1300.0, 1150.0, 1000.0]) # electronic zero-zero energy E0 = 20700.0 # homogeneous linewidth and shape parameter Gamma = 200.0 halpha = 0 # inhomogeneous linewidth and shape parameter sig = 400.0 ialpha = 1 # electronic transition dipole length M = 0.8 # index of refraction of surrounding medium IOR = 1.0 # time axis parameters for integrations tmax = 5000 dt = 0.2 # just calculate fundamentals nquanta = np.identity(len(RMg)) sshift = np.dot(nquanta, RMg) # calculation part # ---------------- # create axes t, wn = rr.getAxes(tmax, dt) # zero-zero energy and damping # add here all time domain stuff TDpart = rr.getHomogeneousDamping(t, Gamma, halpha) # time dependent overlap integrals OVLPS = rr.getOverlaps(t, D, RMg, RMe, nquanta) # calculate cross-sections sigmaA, sigmaR, kF = rr.getCrossSections(t, wn, E0, OVLPS, sshift, M, IOR, TDpart, sig, ialpha) .. This file is part of the FSRStools python module. The FSRStools python module 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. The FSRStools python module 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 the FSRStools python module. If not, see <http://www.gnu.org/licenses/>. Copyright 2014, 2015 Daniel Dietze <daniel.dietze@berkeley.edu>. """ import numpy as np # some constants hbar = 5308.880986 #: Planck's constant over 2 pi, hbar, in `cm-1 fs` c0 = 2.99792458e-5 #: speed of light in `cm / fs` kB = 0.695 #: Boltzman's constant in `cm-1 / K` # ------------------------------------------------------------------------------------------------------------------- # some useful functions def radperfs2wn(w): """Angular frequency (rad / fs) to wavenumber (cm-1). """ return hbar * w def wn2radperfs(e): """Wavenumber (cm-1) to angular frequency (rad / fs). """ return e / hbar def wn2lambda(w): """Convert wavenumber (cm-1) to wavelength (nm). """ return 1e7 / w def lambda2wn(w): """Convert wavelength (nm) to wavenumber (cm-1). """ return 1e7 / w def getWnIndex(wn, wn0): """Get the index into an array of wavenumbers wn with wavenumber closest to wn0. Use this function for :py:func:`getRamanSpectrum`. """ if np.amin(wn) > wn0 or np.amax(wn) < wn0: print "Warning: wn0 lies outside of wn." return np.argmin(np.absolute(wn - wn0)) def getAxes(tmax, dt): """Create time and frequency axes for the resonance Raman calculations. :param float tmax: Endpoint for time domain calculation (fs). This value should be high enough to capture the full dephasing. :param float dt: Increment of time axis (fs). This value should be small enough to capture the highest vibronic feature in the excited state. :returns: Time axis (fs) and frequency axis (cm-1). """ t = np.arange(0, tmax + dt, dt) numPoints = len(t) wn = np.arange(numPoints) / (c0 * dt * numPoints) return t, wn def molarExtinction2AbsCS(eSpctr, IOR): """Convert molar extinction (cm-1 / M) to molecular absorption cross section (A**2 / molec). See McHale, Resonance Raman Spectroscopy, Wiley, (2002), p. 545 or Myers & Mathies for details. The absorption cross section in solution has to be scaled by index of refraction unless the molar extinction has not been corrected. :param array eSpctr: Extinction spectrum in (cm-1 / M). :param float IOR: Index of refraction of surrounding solvent / medium. :returns: Absorption spectrum in units of (A**2 / molec.), same shape as eSpcrt. """ return 1e3 * np.log(10.0) * eSpctr / 6.0221e23 * 1e8 * 1e8 / IOR def diff2absRamanCS(diffRaCS, rho): """Convert the differential Raman cross section (A**2/molec sr) to absolute Raman cross section in (A**2 / molec) for a given depolarization ratio rho. :param float diffRaCS: Differential Raman cross section (A**2/molec sr). :param float rho: Associated depolarization ratio of this Raman mode. :returns: Absolute Raman cross section in (A**2 / molec). """ return 8.0 * np.pi / 3.0 * (1.0 + 2.0 * rho) / (1.0 + rho) * diffRaCS def getRamanSpectrum(wn, iEL, RMg, nquanta, sigmaR, dw=10.0, alpha=0): """ Convenience function to calculate the Raman spectrum. The spectrum is scattered power per infinitesimal frequency normalized to incident power times molecular density (cm-3) times path length (cm). See Myers, *Chem. Phys.* **180**, 215 (1994), Eq. 7 for details. :param array wn: Wavenumber axis (Stokes shift, not electronic). :param int iEL: Index into sigmaR corresponding to the pump energy of the laser. :param array RMg: Ground state Raman frequencies :param array nquanta: M x N array containing the quanta of the N possible Raman modes for the M Raman lines to calculate. Use :py:func:`numpy.identity` to just calculate the fundamentals. Possible values are 0, 1, 2. :param array sigmaR: Array of M Raman cross sections that have been calculated by :py:func:`getCrossSections` (in A**2 / molec). :param float dw: Phenomenological FWHM linewidth of the Raman lines in cm-1 (default = 10 cm-1). :param float alpha: Line shape parameter to be used for the Raman spectrum: - 1 = Gaussian - 0 = Lorentzian (default) :returns: Calculated Raman spectrum (same shape as wn). """ spectrum = np.zeros(len(wn)) if iEL < 0 or iEL >= len(sigmaR[0]): print "Error: iEL is out of range!" return spectrum # iterate over all M modes for i, nM in enumerate(nquanta): # get frequency of this mode wR = np.sum(nM * RMg) # add Lorentzian part of lineshape spectrum = spectrum + (1.0 - alpha) * sigmaR[i][iEL] * 1e-16 * (dw / (2.0 * np.pi * ((wn - wR)**2 + dw**2 / 4.0))) # add Gaussian part of lineshape spectrum = spectrum + alpha * sigmaR[i][iEL] * 1e-16 * ((2.0 * np.sqrt(np.log(2) / np.pi)) / dw * np.exp(-4.0 * np.log(2.0) * (wn - wR)**2 / dw**2)) return spectrum # ----------------------------------------------------------------------------------------------------------------------------------- # time dependent overlap integrals with equal ground and excited state vibrational frequencies # the t00 overlap does not contain the factors exp(-1j wVIB t) nor exp(-1j E0/hbar t) as these are taken care of when assembling the cross section # Myers eqs. (37) - (39) # Delta = displacement in dimensionless coordinates # eVIB = vibrational frequency (cm-1) # t = time axis in fs def t00A(t, Delta, eVIB): """Time dependent overlap integral between vibrational ground states of electronic ground and excited state with equal ground and excited state vibrational frequencies. :param array t: Time axis in (fs). :param float Delta: Displacement of excited state potential energy surface along this vibrational coordinate in dimensionless coordinates. :param float eVIB: Vibrational frequency (cm-1). :returns: 0-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (37) - (39). """ # The 0-0 overlap does not contain the factors :math:`e^{-j w_{VIB} t}` nor :math:`e^{-j E_0 / \\hbar t}` as these are taken care of when assembling the cross section. return np.exp(-Delta**2 / 2.0 * (1.0 - np.exp(-1j * eVIB / hbar * t))) def t10A(t, Delta, eVIB): """Time dependent overlap integral between vibrational ground and first excited state of electronic ground and excited state with equal ground and excited state vibrational frequencies. :param array t: Time axis in (fs). :param float Delta: Displacement of excited state potential energy surface along this vibrational coordinate in dimensionless coordinates. :param float eVIB: Vibrational frequency (cm-1). :returns: 1-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (37) - (39). """ return Delta / np.sqrt(2) * (np.exp(-1j * eVIB / hbar * t) - 1.0) # * t00A(t, Delta, eVIB) def t20A(t, Delta, eVIB): """Time dependent overlap integral between vibrational ground and second excited state of electronic ground and excited state with equal ground and excited state vibrational frequencies. :param array t: Time axis in (fs). :param float Delta: Displacement of excited state potential energy surface along this vibrational coordinate in dimensionless coordinates. :param float eVIB: Vibrational frequency (cm-1). :returns: 2-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (37) - (39). """ return Delta**2 / (2 * np.sqrt(2)) * (np.exp(-1j * eVIB / hbar * t) - 1.0)**2 # * t00A(t, Delta, eVIB) # ------------------------------------------------------------------------------------------------------------------------------------------------- # same with different frequency in ground and excited state # Myers eqs. (42) - (44) # Delta = displacement in dimensionless coordinates # eg = ground state vibrational frequency (cm-1) # ee = excited state vibrational frequency (cm-1) # t = time axis in fs def t00B(t, Delta, eg, ee): """Time dependent overlap integral between vibrational ground states of electronic ground and excited state with different ground and excited state vibrational frequencies. :param array t: Time axis in (fs). :param float Delta: Displacement of excited state potential energy surface along this vibrational coordinate in dimensionless coordinates. :param float eg: Vibrational frequency in the ground state (cm-1). :param float ee: Vibrational frequency in the excited state (cm-1). :returns: 0-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (42) - (44). """ wg = eg / hbar we = ee / hbar swe = np.sin(we * t) cwe = np.cos(we * t) pt = we / wg * Delta * swe qt = Delta * (1 - cwe) # the log reduces to 0.5 * eg / hbar * t when eg = ee # this is the factor that is taken out in the t00A case, as it cancels with the exp in the integral later on # however, np.log returns values such that -pi < arg(log(..)) < pi gt = 1j / 2.0 * np.log(1j * wg / we * swe + cwe) + pt * (qt - Delta) / 2.0 # skip -E0 t / hbar # gt = gt + wg * t / 2.0 # add +w t / 2 using ground state frequency as this compensates the -w t / 2.0 term coming from the FFT # add the following term to recover t00A for eg = ee gt = gt - 1j / 2.0 * np.log(1j * np.sin(wg * t) + np.cos(wg * t)) at = -0.5 * 1j * (1j * cwe - (we / wg) * swe) / (1j * (wg / we) * swe + cwe) a = at + 0.5 pp = pt - 2.0 * 1j * at * qt gp = 1j * at * qt**2 - pt * qt + gt return a**(-0.5) * np.exp(-pp**2 / (4.0 * a)) * np.exp(1j * gp) def t10B(t, Delta, eg, ee): """Time dependent overlap integral between vibrational ground and first excited state of electronic ground and excited state with different ground and excited state vibrational frequencies. :param array t: Time axis in (fs). :param float Delta: Displacement of excited state potential energy surface along this vibrational coordinate in dimensionless coordinates. :param float eg: Vibrational frequency in the ground state (cm-1). :param float ee: Vibrational frequency in the excited state (cm-1). :returns: 1-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (42) - (44). """ wg = eg / hbar we = ee / hbar swe = np.sin(we * t) cwe = np.cos(we * t) pt = we / wg * Delta * swe qt = Delta * (1 - cwe) at = -0.5 * 1j * (1j * cwe - (we / wg) * swe) / (1j * (wg / we) * swe + cwe) a = at + 0.5 pp = pt - 2.0 * 1j * at * qt return 2**(-0.5) * pp / (1j * a) # * t00B(t, Delta, eg, ee) def t20B(t, Delta, eg, ee): """Time dependent overlap integral between vibrational ground and second excited state of electronic ground and excited state with different ground and excited state vibrational frequencies. :param array t: Time axis in (fs). :param float Delta: Displacement of excited state potential energy surface along this vibrational coordinate in dimensionless coordinates. :param float eg: Vibrational frequency in the ground state (cm-1). :param float ee: Vibrational frequency in the excited state (cm-1). :returns: 2-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (42) - (44). """ wg = eg / hbar we = ee / hbar swe = np.sin(we * t) cwe = np.cos(we * t) pt = we / wg * Delta * swe qt = Delta * (1 - cwe) at = -0.5 * 1j * (1j * cwe - (we / wg) * swe) / (1j * (wg / we) * swe + cwe) a = at + 0.5 pp = pt - 2.0 * 1j * at * qt return -8**(-0.5) * (pp**2 / a**2 + 2. * (1. - 1. / a)) # * t00B(t, Delta, eg, ee) # ---------------------------------------------------------------------------------------------------------------------------------- # same for linear dissociative excited state surfaces # Myers eqs. (52) - (54) # beta = slope of potential energy surface (dV / dq) in cm-1 (q is dimensionless coordinate) # eVIB = vibrational frequency (cm-1) def t00D(t, beta, eVIB): """Time dependent overlap integral between vibrational ground states of electronic ground and excited state with a linear dissociative excited state surface along this vibrational coordinate. :param array t: Time axis in (fs). :param float beta: Slope of excited state potential energy surface (dV / dq) in (cm-1) (q is dimensionless coordinate). :param float eVIB: Vibrational frequency (cm-1). :returns: 0-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (52) - (54). """ tmp = (1.0 + 1j * eVIB / hbar * t / 2.0)**(-0.5) * np.exp(-beta**2 * (6 * t**2 + 1j * eVIB / hbar * t**3) / (24 * hbar**2)) tmp = tmp * np.exp(1j * eVIB / hbar * t / 2.0) # add this term to compensate for the -1j w t / 2 term coming from the FFt return tmp def t10D(t, beta, eVIB): """Time dependent overlap integral between vibrational ground and first excited state of electronic ground and excited state with a linear dissociative excited state surface along this vibrational coordinate. :param array t: Time axis in (fs). :param float beta: Slope of excited state potential energy surface (dV / dq) in (cm-1) (q is dimensionless coordinate). :param float eVIB: Vibrational frequency (cm-1). :returns: 1-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (52) - (54). """ return -1j * 2**(-0.5) * (beta * t / hbar) # * t00D(t, beta, eVIB) def t20D(t, beta, eVIB): """Time dependent overlap integral between vibrational ground and second excited state of electronic ground and excited state with a linear dissociative excited state surface along this vibrational coordinate. :param array t: Time axis in (fs). :param float beta: Slope of excited state potential energy surface (dV / dq) in (cm-1) (q is dimensionless coordinate). :param float eVIB: Vibrational frequency (cm-1). :returns: 2-0 overlap integral as function of time (same shape as t). .. seealso:: Myers, Eqs. (52) - (54). """ return -2**(-0.5) * (beta**2 * t**2 / (2.0 * hbar**2) - 1j * eVIB / hbar * t / (2.0 + 1j * eVIB / hbar * t)) # * t00D(t, beta, eVIB) # --------------------------------------------------------------------------------------------------------------------------------- def getOverlaps(t, D, RMg, RMe, nquanta): """Calculate the time dependent overlap integrals / Franck-Condon factors :math:`<i|i(t)>_k` and :math:`<f|i(t)>_k`. .. versionchanged:: 10-07-2015 Format of return value changed. :param array t: Time axis in (fs). :param array D: Array of N normalized displacements of excited state surfaces (deltas), or slope of linear dissociative excited state surface. :param array RMg: N Raman ground state frequencies (cm-1). :param array RMe: N Raman excited state frequencies (cm-1) or -1 if excited state surface is dissociative. :param array nquanta: M x N array containing the quanta of the N possible Raman modes for the M Raman lines to calculate. Use :py:func:`numpy.identity` to just calculate the fundamentals. Possible values are 0 (no excitation), 1 (fundamental), 2 (first overtone). :returns: M + 2 - dimensional array containing the Rayleigh, fluorescence and M Raman overlaps. """ ovlps = [] N = len(D) M = nquanta.shape[0] # Frank-Condon factors <i|i(t)>_k and <f|i(t)>_k FC0 = [] FC0p = [] FC1 = [] FC2 = [] for i in range(N): if(RMg[i] == RMe[i]): FC0.append(t00A(t, D[i], RMg[i])) FC0p.append(FC0[-1]) # fluorescence overlap is identical to absorption overlap when frequencies are equal FC1.append(t10A(t, D[i], RMg[i])) FC2.append(t20A(t, D[i], RMg[i])) elif(RMe[i] == -1): FC0.append(t00D(t, D[i], RMg[i])) FC0p.append(np.zeros(len(t))) # fluorescence is negligible from dissociative surface FC1.append(t10D(t, D[i], RMg[i])) FC2.append(t20D(t, D[i], RMg[i])) else: FC0.append(t00B(t, D[i], RMg[i], RMe[i])) FC0p.append(t00B(t, D[i], RMe[i], RMg[i])) # fluorescence overlap has excited state and ground state Raman frequencies switched FC1.append(t10B(t, D[i], RMg[i], RMe[i])) FC2.append(t20B(t, D[i], RMg[i], RMe[i])) # go to numpy array.. FC0 = np.array(FC0) FC0p = np.array(FC0p) FC1 = np.array(FC1) FC2 = np.array(FC2) # Rayleigh / absorption overlap oabs = 1.0 + 0.0 * 1j # reuse this term for the raman overlaps for i in range(N): oabs = oabs * FC0[i] ovlps.append(oabs) # fluorescence overlap o = 1.0 + 0.0 * 1j for i in range(N): o = o * FC0p[i] ovlps.append(o) # actual Raman overlaps for j in range(M): o = 1.0 * oabs # all raman modes are based on this product and additional terms given by the excited modes for i in range(N): if(nquanta[j][i] == 1): o = o * FC1[i] elif(nquanta[j][i] == 2): o = o * FC2[i] ovlps.append(o) return ovlps # --------------------------------------------------------------------------------------------------------------------------------- def getZeroZeroEnergy(t, E0): """Calculate the oscillation term in the time domain due to the electronic zero-zero energy E0. :param array t: Time axis (fs). :param float E0: Difference between excited and ground state vibrational ground state energies, *zero-zero energy* (cm-1). """ return np.exp(-1j * E0 / hbar * t) # ----------------------------------------------------------------------------------------------------------------------------- # Calculate the damping terms as function of time t. def getHomogeneousDamping(t, Gamma, alpha=0, lmbda=0): """Calculates the damping term arising from the homogeneous linewidth of the electronic transition. Offers phenomenological support for Stokes shift. .. note:: Added phenomenological Stokes shift to input parameters on 10-12-2015. See for example *New J Phys* **11**, 015001 (2009), Eqs. (1) and (2). :param array t: Time axis (fs). :param float Gamma: Decay rate according to :math:`1 / \\tau` in (cm-1), where :math:`tau` is exponential dephasing time. :param float alpha: Line shape parameter: - 1 = Gaussian - 0 = Lorentzian :param float lmbda: Phenomenological Stokes shift (cm-1) which is added as imaginary part to g(t). Compared to the Brownian oscillator models, lmbda **is** the observed Stokes shift. (default = 0) :returns: Damping term in the time domain, :math:`e^{-g(t) - i \lambda t / 2 \hbar}`. """ g = alpha * (Gamma**2 / hbar**2 * t**2) + (1 - alpha) * (Gamma / hbar * t) + 1j * lmbda / 2.0 * t / hbar return np.exp(-g) def getKuboDamping(t, Delta, Lambda): """Calculates the damping term using Kubo's *stochastic model*. This model describes the broadening, but does not yield solvent induced Stokes shifts. :param array t: Time axis (fs). :param float Delta: Magnitude of solvent energy gap fluctuations (cm-1). This parameter also controls the effective line shape: - Delta >> Lambda = Lorentzian - Delta << Lambda = Gaussian :param float Lambda: Effective frequency of solvent fluctuations (cm-1). :returns: Damping term in the time domain, :math:`e^{-g(t)}`. .. seealso:: Myers, *J. Raman. Spectrosc.* **28**, 389 (1997) """ return np.exp(-(Delta / Lambda)**2 * (np.exp(-Lambda / hbar * t) + Lambda / hbar * t - 1.0)) def getBrownianDamping(t, kappa, T, egamma, cutoff=1e-6): """Calculate the damping term using Mukamel's Brownian oscillator model based on Myers Fortran code. The real part of g(t) leads to a Gaussian broadening of the spectra, while the imaginary part leads to a solvent induced Stokes shift. :param array t: Time axis (fs). :param float kappa: Lineshape parameter: - kappa >> 1 = Lorentzian, - kappa << 1 = Gaussian. :param float T: Temperature in K. :param float egamma: Electronic homogeneous linewidth (**FWHM**, cm-1). :param float cutoff: Cutoff for sum over Brownian oscillators. Typically between 1e-6 (default) and 1e-8. Check for convergence by re-running with different values. :returns: Damping term in the time domain, :math:`e^{-g(t)}`. .. seealso:: Myers, *J. Raman. Spectrosc.* **28**, 389 (1997) """ temp = np.absolute(T) # ---------------------------------------------------------- # 1: derive Mukamel's parameters from kappa, temp and egamma # I do not have a reference for this part - it's taken from Myers fortran code # Boltzmann beta beta = 1.0 / (kB * temp) # 1/cm-1 # some 'a' parameter (this comes from Myers Fortran program) a = (2.355 + 1.76 * kappa) / (1.0 + 0.85 * kappa + 0.88 * kappa**2) # these are Mukamel's parameters in Myers, J. Raman. Spec. 28, 389 (1997), eqs. (35) to (38) Lambda = kappa * egamma / a # cm-1 lmbda = beta * (Lambda / kappa)**2 / 2.0 # cm-1 # ---------------------------------------------------------- # 2: calculate the sum over n Brownian oscillators vs = np.zeros(len(t)) # this is the sum over the n oscillators as function of time in (cm-1)**-3 n = 0 while(True): n = n + 1 vn = 2.0 * np.pi * n / beta # cm-1 vinc = (np.exp(-vn / hbar * t) + vn / hbar * t - 1) / (vn * (vn**2 - Lambda**2)) vs = vs + vinc if(np.amax(np.absolute(vinc[1:] / vs[1:])) < cutoff): # the first element of vs is always 0 break # ---------------------------------------------------------- # 3: calculate the damping function g(t) gexp = np.exp(-Lambda / hbar * t) + Lambda / hbar * t - 1.0 # dimensionless greal = (lmbda / Lambda) / np.tan(beta * Lambda / 2.0) * gexp # dimensionless greal = greal + 4.0 * lmbda * Lambda / beta * vs # dimensionless gimag = -(lmbda / Lambda) * gexp # dimensionless g = greal + 1j * gimag # dimensionless return np.exp(-g) def getBrownianDamping2(t, lmbda, Lambda, T=298.0, cutoff=1e-6): """Calculate pure electronic dephasing due to interaction with solvent using frictionally overdamped Brownian oscillator model. The real part of g(t) leads to a Gaussian broadening of the spectra, while the imaginary part leads to a solvent induced Stokes shift. :param array t: Time axis in fs. :param float lmbda: Solvent contribution to reorganization energy (cm-1). :param float Lambda: Inverse of characteristic time scale for solvent fluctuations (fs-1). :param float T: Temperature (K, default = 298 K). :param float cutoff: Cutoff value for summation over brownian oscillators (default 1e-6). :returns: Damping term in the time domain, :math:`e^{-g(t)}`. .. seealso:: This implementation is taken from Kulinowksi, *J Phys Chem* **99**, 9017 (1995), Eqs. (10a) to (10d). """ beta = 1.0 / (kB * np.absolute(T)) lmb = lmbda / hbar # convert to fs-1 # calculate real part as sum over oscillators gR = 0.0 i = 1.0 while(1): nun = 2.0 * np.pi / (hbar * beta) * i # frequency of ith oscillator dg = (np.exp(-nun * t) + nun * t - 1.0) / (nun * (nun**2 - Lambda**2)) gR = gR + dg i = i + 1.0 if np.sum(np.absolute(np.dg)) / np.sum(np.absolute(gR)) < cutoff: break gR = gR * 4.0 * lmb * Lambda / (hbar * beta) gR = gR + (lmb / Lambda) * np.cot(hbar * beta * Lambda / 2.0) * (np.exp(-Lambda * t) + Lambda * t - 1.0) # calculate imaginary part = Stokes shift gI = -(lmb / Lambda) * (np.exp(-Lambda * t) - 1.0) # assemble g = gR + 1j * gI # dimensionless return np.exp(-g) def getBrownianDampingSlowMod(t, lmbda, T=298.0): """Calculate pure electronic dephasing due to interaction with solvent using frictionally overdamped Brownian oscillator model in the high-temperature and slow-modulation limit. The real part of g(t) leads to a Gaussian broadening of the spectra, while the imaginary part leads to a solvent induced Stokes shift. :param array t: Time axis in fs. :param float lmbda: Solvent contribution to reorganization energy (cm-1). :param float T: Temperature (K, default = 298 K). :returns: Damping term in the time domain, :math:`e^{-g(t)}`. .. seealso:: This implementation is taken from Kulinowksi, *J Phys Chem* **99**, 9017 (1995), Eq. (11). """ lmb = lmbda / hbar # convert to fs-1 return np.exp(-(lmb * kB * np.absolute(T) * t**2 / hbar + 1j * lmb * t)) # --------------------------------------------------------------------------------------------------------------------------------- # def applyInhomogeneousBroadening(wn, y, sig, alpha=1): """Convolute a spectrum with a Gaussian/Lorentzian to account for inhomogeneous broadening. :param array wn: Frequency axis in same units as sig (cm-1). :param array y: Input spectrum, same shape as wn. :param float sig: Width of convolution function in same units as x (standard deviation of Gaussian distribution). Must not be zero. :param float alpha: Lineshape parameter: - 1 = Gaussian, - 0 = Lorentzian. :returns: Convoluted spectrum (same shape as y). """ ck = alpha / (sig * np.sqrt(2 * np.pi)) * np.exp(-(wn - (wn[-1] + wn[0]) / 2.0)**2 / (2.0 * sig**2)) ck += (1 - alpha) * sig / (np.pi * ((wn - (wn[-1] + wn[0]) / 2)**2 + sig**2)) # np.convolve uses a sum, whereas the function we want uses an integral; wn[1] - wn[0] is dwn return (wn[1] - wn[0]) * np.convolve(y, ck, 'same') # -------------------------------------------------------------------------------------------------------------------------------- def prefA(eEL, M, IOR, dt): """Return the prefactor for the absorption cross section calculation in (A**2 / molec). :param array eEL: Laser excitation energy in (cm-1). May also be a single float value. :param float M: Electronic transition dipole length in (A). :param float IOR: Index of refraction of surrounding solvent / medium. :param float dt: Time increment used for integration (fs). :returns: Prefactor for absorption cross section calculation. .. seealso:: Myers, Eq. (35). """ # to convert from esu to SI divide by 4 pi eps0 # the factor / 2 arises from the normalization of numpy of the rfft to match the amplitude of fft # so rfft is not completely identical to half-sided FT integral return 5.7579e-6 * M**2 * eEL * dt / IOR / 2.0 # ------------------------------------------------------------------------------------------------------------------------------- def prefR(eEL, M, eR, dt): """Return the prefactor for the Raman excitation profile calculation (A**2 / molec). :param array eEL: Laser excitation energies in (cm-1). Can also be a single floating point value. :param float M: Electronic transition dipole moment in (A). :param float eR: Stokes shift of the Raman line in (cm-1). :param float dt: Time increment for the integration (fs). :returns: The prefactor for the Raman excitation profile calculation. .. seealso:: Myers, Eq. (34) and following text. """ # get energy of stokes shifted photons eES = eEL - eR # the 1e-6 is for fs instead of ps in the integral and is consistent with Myers fortran code (it is different however from the 1e4 factor in Valley & Hoffman code!!) # to convert from esu to SI divide by (4 pi eps0)**2 return 2.0831e-20 * 1e-6 * M**4 * eES**3 * eEL * dt**2 # -------------------------------------------------------------------------------------------------------------------------------- def prefF(eEF, M, IOR, dt): """Return the prefactor for the fluorescence efficiency calculation (unitless). See :py:func:`getCrossSections` for more details. :param array eEF: Fluorescence energy in (cm-1). May also be a single float value. :param float M: Electronic transition dipole length in (A). :param float IOR: Index of refraction of surrounding solvent / medium. :param float dt: Time increment used for integration (fs). :returns: Prefactor for fluorescence efficiency calculation. .. seealso:: Myers, *Chem. Phys.* **180**, 215 (1994), Eqs. (6) and (26). """ # to convert from esu to SI divide by 4 pi eps0 # the factor / 2 arises from the normalization of numpy of the rfft to match the amplitude of fft # so rfft is not completely identical to half-sided FT integral return 3.6656e-22 * IOR * M**2 * eEF**3 * dt / 2.0 # ---------------------------------------------------------------------------------------------------------------------------- def getCrossSections(t, wn, E0, ovlps, sshift, M, IOR, damp=1, sig=0, ialpha=1): """Calculate the absorption and Raman cross-sections and the fluorescence efficiency. The latter is a unitless quantity which may be used to calculate the fluorescence rate (=rate of spontaneous emission) by integrating over the frequency axis (see Myers, *Chem. Phys.* **180**, 215 (1994) Eq. 6 and discussion). .. note:: Changed shape of input parameters and shape of return values on 10-07-2015. :param array t: Time axis in (fs). This axis is used for the calculation of the zero-zero energy term in the time domain. :param array wn: Wavenumber axis in (cm-1). Same shape as t. :param array E0: Zero-zero energy. This function then calculates the time domain part using `getZeroZeroEnergy`. :param array ovlps: M + 2 Absorption, fluorescence and Raman overlap integrals. :param float sshift: Vibrational freqencies of M Raman modes to calculate (cm-1). :param float M: Electronic transition dipole length (A). :param float IOR: Index of refraction of surrounding medium / solvent. :param array damp: Damping function in the time domain. Same shape as t. Set to 1 if no damping is used (default). :param float sig: Linewidth for inhomogeneous damping (standard deviation of Gaussian), set to zero if not used (default). :param float ialpha: Lineshape parameter for inhomogeneous damping: - 1 = Gaussian (default), - 0 = Lorentzian. :returns: Absorption (sigmaA), M Raman cross sections (sigmaR[M]), both in A**2 / mol., and fluorescence efficiency spectrum, kF (arrays have same shape as wn); all as function of excitation wavenumber. """ Npoints = len(wn) dt = t[1] - t[0] # caluclate zero-zero time domain part tdpart = getZeroZeroEnergy(t, E0) # absorption cross section - using the half sided FT (equivalent to rfft) tmp = np.real(Npoints * np.fft.irfft(ovlps[0] * tdpart * damp, Npoints)) if(sig > 0): tmp = applyInhomogeneousBroadening(wn, tmp, sig, ialpha) sigmaA = prefA(wn, M, IOR, dt) * tmp # fluorescence rate / intensity - using half sided FT - similar to absorption # in order to account for the sign change, the zero-zero energy time domain part and the damping term had to be separated; # use the tdpart conjugated and change irfft by hfft to get the factor exp(-1j w t) # numpy does not normalize the forward FFT, so no factor Npoints tmp = np.real(np.fft.hfft(ovlps[1] * np.conjugate(tdpart) * damp, Npoints)) if(sig > 0): tmp = applyInhomogeneousBroadening(wn, tmp, sig, ialpha) kF = prefF(wn, M, IOR, dt) * tmp # Raman cross sections - using a standard FT sigmaR = [] for i, ovlp in enumerate(ovlps[2:]): # iterate over all lines tmp = np.absolute(Npoints * np.fft.ifft(ovlp * tdpart * damp, Npoints))**2 # use again the inverse transform to get "exp(1j w t)" if(sig > 0): tmp = applyInhomogeneousBroadening(wn, tmp, sig, ialpha) sigmaR.append(prefR(wn, M, sshift[i], dt) * tmp) return sigmaA, sigmaR, kF
ddietze/FSRStools
rraman/__init__.py
Python
gpl-3.0
36,173
<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="it"> <head> <meta http-equiv="pics-label" content="(pics-1.1 &quot;http://www.icra.org/ratingsv02.html&quot; l gen true for &quot;http://www.hypertrek.info/&quot; r (cz 1 lz 1 nz 1 oz 1 vj 1) &quot;http://www.rsac.org/ratingsv01.html&quot; l gen true for &quot;http://www.hypertrek.info/&quot; r (n 0 s 0 v 1 l 0))"> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>HyperTrek * VOY * Scorpion - Part I</title> <link rel="STYLESHEET" href="../style/voy.css" type="text/css"> <base target="main"> </head> <body> <table border="0" width="100%" class="titolo"> <tr> <td width="22"><a href="voy067.html" rel="prev"><img src="../skin/sx.gif" alt="Episodio Precedente" border="0" width="22" height="42"></a></td> <td width="52"><a target="nav" href="index.html"><img src="../skin/voy.gif" alt="VOY" border="0" width="52" height="42"></a></td> <td width="17"><img src="../skin/s-3.gif" alt="Terza stagione" border="0" width="17" height="42"></td> <td> <h1>168 - Scorpion - Part I</h1> </td> <td width="22"><a href="voy069.html" rel="next"><img src="../skin/dx.gif" alt="Episodio Successivo" border="0" width="22" height="42"></a></td> </tr> </table> <table border="0" class="xr" align="right" cellspacing="0" cellpadding="3"> <tr> <td class="xrdettaglio"><a href="#iqe">In questo episodio...</a><br> <a href="#Note">Note</a> <br> <a href="#a47">47</a><br> <a href="#YATI">YATI</a><br> <a href="#Versioneitaliana">Versione italiana</a><br> <a href="#citazioni">Citazioni</a></td> </tr> <tr> <td class="xrtestata">Episodi</td> </tr> <tr> <td class="xrdettaglio"><a href="voy157.html">Shattered</a></td> </tr> <tr> <td class="xrtestata">Specie</td> </tr> <tr> <td class="xrdettaglio"><a href="../specie/09/8472.html">8472</a><br> <a href="../specie/b/breen.html">Breen</a></td> </tr> <tr> <td class="xrtestata">Organizzazioni</td> </tr> <tr> <td class="xrdettaglio"><a href="../organizzazioni/borg.html">Borg</a></td> </tr> <tr> <td class="xrtestata">Astronavi</td> </tr> <tr> <td class="xrdettaglio"><a href="../astronavi/8472/altre.html"> Specie 8472</a></td> </tr> <tr> <td class="xrtestata">Holodeck</td> </tr> <tr> <td class="xrdettaglio"> <a href="../tech/holodeck/software.html#daVinci">da Vinci Workshop</a></td> </tr> <tr> <td class="xrtestata">Quante volte...</td> </tr> <tr> <td class="xrdettaglio"> <a href="../etc/qv/qv17.html">Incontriamo alieni non umanoidi?</a><br> <a href="qv/qv06.html">L'equipaggio della <i>Voyager</i> utilizza le nanosonde Borg?</a></td> </tr> </table> <table border="0" cellpadding="3" class="standard"> <tr> <td>SEQ</td> <td colspan="2"><b>68</b></td> </tr> <tr> <td>UPN</td> <td colspan="2"><b>21.05.1997</b></td> </tr> <tr> <td>RAI</td> <td colspan="2"><b>04.09.2000</b></td> </tr> <tr> <td>VHS</td> <td colspan="2"><b>3.13 (PG)</b></td> </tr> <tr> <td>STO</td> <td colspan="2"><b><a href="../xr/b/braga.html">Brannon Braga</a><br> <a href="../xr/m/menosky.html">Joe Menosky</a></b></td> </tr> <tr> <td>REG</td> <td colspan="2"><b><a href="../xr/l/livingston.html">David Livingston</a></b></td> </tr> <tr> <td>GUS</td> <td>Leonardo da Vinci</td> <td><b><a href="../xr/r/rhysd.html">John Rhys-Davies</a></b></td> </tr> <tr> <td>IT</td> <td colspan="2"><b>Il patto dello scorpione - Prima parte</b></td> </tr> <tr> <td>DE</td> <td colspan="2"><b>Skorpion - Teil 1</b></td> </tr> <tr><td>BR</td><td colspan="2"><b>Escorpião, Parte I</b></td></tr> <tr> <td>JP</td> <td colspan="2"><b>Seimeitai 8472 (Species 8472)</b></td> </tr> </table> <p><b>Data Stellare 50984.3</b>: La <i>Voyager</i> è costretta ad attraversare il territorio dei <a href="../organizzazioni/borg.html">Borg</a> per tornare verso la <a href="../pianeti/t/terra.html">Terra</a>. Mentre il dottore sembra aver scoperto un sistema per evitare l'assimilazione, quindici <a href="../astronavi/borg/cubo.html">navi borg</a> fanno rotta alla massima velocità in direzione della <i>Voyager</i>, ma la nave federale non è il loro obiettivo.</p> <h4><a name="iqe">In questo episodio...</a></h4> <ul> <li>Debutta la <a href="../specie/09/8472.html">Specie 8472</a>.</li> <li>B'Elanna effettua un <a target="nav" rel="contents" class="nav" href="../tech/teletrasporto/index.html">teletrasporto</a> agganciando lo scheletro del soggetto da teletrasportare.</li> <li>La <i>Voyager</i> ha una riserva di 32 siluri fotonici con testata esplosiva di classe 6, per una potenza esplosiva di 200 isotoni.</li> <li>Debutta il programma olografico di <a href="../tech/holodeck/software.html#daVinci">Leonardo da Vinci</a>.</li> <li>Kes riesce a ricevere dei messaggi telepatici dalla <a href="../specie/09/8472.html">Specie 8472</a>.</li> </ul> <h4><a name="Note">Note</a></h4> <table border="0" align="right" cellspacing="0" cellpadding="0"> <tr> <td> <img border="0" src="img/001-mccarthy.jpg" alt="Jeff McCarthy in Caretaker" width="170" height="127"></td> </tr> <tr> <td> <img border="0" src="img/068-mccarthy.jpg" alt="Jeff McCarthy in Scorpion" width="170" height="127"></td> </tr> </table> <ul> <li><a href="../xr/m/mccarthy.html">Jeff McCarthy</a>, che in <a href="voy001.html">Caretaker</a> interpreta l'ufficiale medico della <i> Voyager</i>, lo si rivede in questo episodio con un'uniforme diversa, come appare dalle due immagini a lato</li> </ul> <p><br clear="all"> </p> <h4><a name="a47">47</a></h4> <ul> <li>Per due volte il Dottore esamina la tecnica delle nanosonde Borg su un monitor etichettato <i>Image Enhancement 047</i>.</li> <li>Durante il primo meeting in sala tattica, quando Chakotay è in piedi con lo schermo alle sue spalle proprio sopra la sua spalla destra c'è il numero azzurro 472.</li> <li>Quando, contattati i Borg, Janeway fa cenno a B'Elanna di inviare la trasmissione delle nanosonde modificate, sulla barra superiore del monitor di B'Elanna, al posto della scritta <i>Image Enhancement 047</i> compare per alcuni secondi <i>SUBSPACE FREQ. 40.77</i>.</li> <li>Quando Janeway consulta i rapporti della <a target="nav" class="nav" href="../starfleet/index.html">Flotta Stellare</a> sui <a href="../organizzazioni/borg.html">Borg</a>, sulla barra superiore del monitor si legge il numero 9521 (95 - 21 = 74).</li> <li>Sette di Nove dice che la flotta di bionavi intercetterà la <i>Voyager</i> tra 3 ore e 17 minuti (3 + 1 = 4).</li> <li>La data stellare dell'episodio è 51003.7 (510 + 037 = 547).</li> </ul> <h4><a name="YATI">YATI</a></h4> <ul> <li>All'inizio dell'episodio, quando la <i>Voyager</i> esce brutalmente dalla curvatura la flotta dei 15 cubi Borg è a 2.1 anni luce in avvicinamento (lo dice Kim). Dopo pochissimi istanti si vedono arrivare i cubi ad alta velocità verso la Voyager e c'è un'inquadratura con la <i>Voyager</i> ferma in cui sfrecciano i cubi (che, quindi, non erano in curvatura, né tanto meno in trans-curvatura). È strano che i cubi, per sfuggire al vascello della specie 8472, o per andare in soccorso di qualche cubo sotto attacco, vadano a velocità sub-luce e non a curvatura. Inoltre sarebbe stato impossibile coprire 2.1 anni-luce in pochi istanti a velocità sub-luce [T:10:01].</li> </ul> <h4><a name="Versioneitaliana">Versione italiana</a></h4> <ul> <li>La prima volta che la RAI ha mandato in onda l'episodio, l'ha trasmesso per intero senza tagli tra le due parti.</li> <li>Quando riprende la rotta dopo il primo contatto coi 15 cubi Borg, Janeway comunica agli ufficiali di plancia che si sarebbe recata nella sala tattica, ma poi, si vede Chakotay raggiungerla nel suo ufficio [T:11.59].</li> <li>Nella versione italiana, la storiella della volpe e dello scorpione diventa della rana e lo scorpione.</li> </ul> <h4><a name="citazioni">Citazioni</a></h4> <p><b>da Vinci</b>: Che cazzo! [T:02:43]</p> <p><b>Kim</b>: I'm reading two Borg vessels. Make that three, ...four, ...no, five. Fifteen Borg vessels. [T:10:01]</p> <p><b>Janeway</b>: That's why the Borg can't assimilate them!<br> <b>Dottore</b>: Resistance, in this case, is far from futile! [T:27:58]</p> <p><b>Chakotay</b>: A scorpion was walking along the bank of a river, wondering how to get to the other side. Suddenly he saw a fox. He asked the fox to take him on his back across the river. The fox said, &quot;No, if I do that you'll sting me and I'll drown&quot;. The scorpion assured him, &quot;If I did that we'd both drown&quot;. So the fox thought about it, finally agreed. So the scorpion climbed up on his back and the fox began to swim. But halfway across the river the scorpion stung him. As the poison filled his veins, the fox turned to the scorpion, said &quot;Why did you do that? Now you'll drown too&quot;. &quot;I couldn't help it&quot;, said the scorpion, &quot;it's my nature&quot;... There are other kinds of courage, like the courage to accept that there are some situations beyond your control. Not every problem has an immediate solution. [T:37:50]</p> <p><b>Janeway</b>: I've made my decision, now... do I have your support?<br> <b>Chakotay</b>: You're the captain. I'm the first officer; I'll follow your orders. But that doesn't change my belief that we're making a fatal mistake.<br> <b>Janeway</b>: Then I guess I am alone, after all. Dismissed. [T:40.48]</p> <hr> <script language="JavaScript" type="text/javascript">document.write("<h6>Ultima modifica: ",document.lastModified,"<\/h6>") </script></li> </body> </html>
luigirosa/hypertrek
ultimo_sito_html/voy/voy068.html
HTML
gpl-3.0
10,114
<?php /** * Manager Class * * @package WordPress * @subpackage Plugin * @author Chris W. <chrisw@null.net> * @license GNU GPLv3 * @link /LICENSE */ namespace MsRobotstxtManager; if ( false === defined( 'ABSPATH' ) ) { exit; } use MsRobotstxtManager\Trait_Security_Check as TraitSecurityCheck; use MsRobotstxtManager\Option_Manager as OptionManager; /** * Save Freemius SDK Rules. */ final class Do_Save_Sdk { use TraitSecurityCheck; /** * Plugin Admin Post Object. * * @var array */ public $post_object = []; /** * Post Action To Take. * * @var string */ public $post_action = []; /** * Option_Manager Class. * * @var object */ public $option_manager = []; /** * Setup Class * * @param array $post_object Cleaned Post Object. */ public function __construct( $post_object = [] ) { if ( true === empty( $post_object ) || true === empty( $post_object['action'] ) ) { return; } $this->post_action = $post_object['action']; $this->post_object = $post_object; $this->option_manager = new OptionManager(); }//end __construct() /** * Init Update Action */ public function init() { if ( true === empty( $this->post_object ) ) { return; } /* * Fires as an admin screen or script is being initialized. * https://developer.wordpress.org/reference/hooks/admin_init/ */ add_action( 'admin_init', [ $this, 'update', ] ); }//end init() /** * Security Check & Update On Action */ public function update() { $this->security_check(); if ( 'reconnect' === $this->post_action ) { $this->reconnect_action(); } if ( 'sdk' === $this->post_action ) { if ( true !== empty( $this->post_object['optin'] ) && '1' === $this->post_object['optin'] ) { $this->optin_action(); } if ( true !== empty( $this->post_object['dismiss'] ) && '1' === $this->post_object['dismiss'] ) { $this->dismiss_action(); } } }//end update() /** * SDK Reconnect Again */ private function reconnect_action() { $this->option_manager->update_site_setting( 'sdk_action', 'optin' ); msrtm_fs()->connect_again(); }//end reconnect_action() /** * SDK Opt In */ private function optin_action() { $this->option_manager->update_site_setting( 'sdk_action', 'optin' ); msrtm_fs()->opt_in(); }//end optin_action() /** * SDK Opt Out */ private function dismiss_action() { $this->option_manager->update_site_setting( 'sdk_action', 'skip' ); }//end dismiss_action() }//end class
tribalNerd/multisite-robotstxt-manager
inc/classes/class-do-save-sdk.php
PHP
gpl-3.0
2,538
#include <stdio.h> #include <stdlib.h> int count(FILE *f){ int prew, cur, inseq=0, c=0; fscanf(f, "%d", &prew); while(fscanf(f, "%d", &cur)==1){ if(cur>prew){ if(!inseq){ c++; inseq=1; } }else{ inseq=0; } prew=cur; } return c; } int main(void){ char name[80]; printf("enter filename:\n"); scanf("%s",name); FILE *f = fopen(name, "r"); printf("%d\n", count(f)); fclose(f); return 0; }
micabressan/trabajo_final
codes/ef0hCTEs.C
C++
gpl-3.0
456
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WpfMath { // Atom representing whitespace. internal class SpaceAtom : Atom { // Collection of unit conversion functions. private static UnitConversion[] unitConversions = new UnitConversion[] { new UnitConversion(e => e.TexFont.GetXHeight(e.Style, e.LastFontId)), new UnitConversion(e => e.TexFont.GetXHeight(e.Style, e.LastFontId)), new UnitConversion(e => 1.0 / e.TexFont.Size), new UnitConversion(e => TexFontUtilities.PixelsPerPoint / e.TexFont.Size), new UnitConversion(e => (12 * TexFontUtilities.PixelsPerPoint) / e.TexFont.Size), new UnitConversion(e => { var texFont = e.TexFont; return texFont.GetQuad(texFont.GetMuFontId(), e.Style) / 18; }), }; private delegate double UnitConversion(TexEnvironment environment); public static void CheckUnit(TexUnit unit) { if ((int)unit < 0 || (int)unit >= unitConversions.Length) throw new InvalidOperationException("No conversion for this unit exists."); } // True to represent hard space (actual space character). private bool isHardSpace; private double width; private double height; private double depth; private TexUnit widthUnit; private TexUnit heightUnit; private TexUnit depthUnit; public SpaceAtom(TexUnit widthUnit, double width, TexUnit heightUnit, double height, TexUnit depthUnit, double depth) : base() { CheckUnit(widthUnit); CheckUnit(heightUnit); CheckUnit(depthUnit); this.isHardSpace = false; this.widthUnit = widthUnit; this.heightUnit = heightUnit; this.depthUnit = depthUnit; this.width = width; this.height = height; this.depth = depth; } public SpaceAtom(TexUnit unit, double width, double height, double depth) : base() { CheckUnit(unit); this.isHardSpace = false; this.widthUnit = unit; this.heightUnit = unit; this.depthUnit = unit; this.width = width; this.height = height; this.depth = depth; } public SpaceAtom() : base() { this.isHardSpace = true; } public override Box CreateBox(TexEnvironment environment) { if (isHardSpace) return new StrutBox(environment.TexFont.GetSpace(environment.Style), 0, 0, 0); else return new StrutBox(width * GetConversionFactor(widthUnit, environment), height * GetConversionFactor( heightUnit, environment), depth * GetConversionFactor(depthUnit, environment), 0); } private double GetConversionFactor(TexUnit unit, TexEnvironment environment) { return unitConversions[(int)unit](environment); } } }
Civa/Zenith
src/Shared/Zenith.Global/ThirdParty/SpaceAtom.cs
C#
gpl-3.0
3,264
(function () { angular .module('mainModule') .controller('mainVagasController', mainVagasController); function mainVagasController($state, $http, BASE_URL_API) { var vm = this; vm.vagas = []; vm.abrirVaga = abrirVaga; ativar(); function ativar() { $http .get(BASE_URL_API+"Vagas") .then( function (result) { vm.vagas = result.data; }, function (error) { } ) .finally(function () { vm.mostraLoad = false; }); } function abrirVaga(id) { $state.go('vagaDetalhe', { id: id }); } } })();
gabriel-society/clak.vagas
src/src/Clak.Vagas/wwwroot/app/vagas/main.vagas.controller.js
JavaScript
gpl-3.0
793
// replication-manager - Replication Manager Monitoring and CLI for MariaDB and MySQL // Authors: Guillaume Lefranc <guillaume@signal18.io> // Stephane Varoqui <stephane.varoqui@mariadb.com> // This source code is licensed under the GNU General Public License, version 3. // Redistribution/Reuse of this code is permitted under the GNU v3 license, as // an additional term, ALL code must carry the original Author(s) credit in comment form. // See LICENSE in this directory for the integral text. package cluster import ( "encoding/binary" "os" ) type stateFile struct { Handle *os.File Name string Count int32 Timestamp int64 } func newStateFile(name string) *stateFile { sf := new(stateFile) sf.Name = name return sf } func (sf *stateFile) access() error { var err error sf.Handle, err = os.OpenFile(sf.Name, os.O_RDWR|os.O_CREATE, 0666) if err != nil { return err } return nil } func (sf *stateFile) write() error { err := sf.Handle.Truncate(0) sf.Handle.Seek(0, 0) if err != nil { return err } err = binary.Write(sf.Handle, binary.LittleEndian, sf.Count) if err != nil { return err } err = binary.Write(sf.Handle, binary.LittleEndian, sf.Timestamp) if err != nil { return err } return nil } func (sf *stateFile) read() error { sf.Handle.Seek(0, 0) err := binary.Read(sf.Handle, binary.LittleEndian, &sf.Count) if err != nil { return err } err = binary.Read(sf.Handle, binary.LittleEndian, &sf.Timestamp) if err != nil { return err } return nil }
mysolo/replication-manager
cluster/statefile.go
GO
gpl-3.0
1,524
#include "global.h" //ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ // Detection of available video modes //ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ /* struct _modos { short ancho; short alto; short modo; }; struct _modos modos[32]; int num_modos; int VersionVesa; char marcavga[128]; */ //ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ int compare_mode(void const *aa, void const *bb) { short *a,*b; a=(short*)aa; b=(short*)bb; return((int)(*a)*10000+*(a+1)>(int)(*b)*10000+*(b+1)); } void detectar_vesa(void) { // Detects available video modes short *modelist; int n; OSDEP_VMode **modes; int i; num_modos=0; modes=OSDEP_ListModes(); /* Check is there are any modes available */ if(modes == 0 || modes == -1) { // none, just list some standard ones for use in windowed mode. modos[0].ancho=320; modos[0].alto=240; modos[0].modo=1; modos[1].ancho=640; modos[1].alto=480; modos[1].modo=1; modos[2].ancho=800; modos[2].alto=600; modos[2].modo=1; modos[3].ancho=1024; modos[3].alto=768; modos[3].modo=1; modos[4].ancho=1280; modos[4].alto=1024; modos[4].modo=1; modos[5].ancho=1920; modos[5].alto=1080; modos[5].modo=1; modos[6].ancho=1280; modos[6].alto=720; modos[6].modo=1; modos[7].ancho=376; modos[7].alto=282; modos[7].modo=1; } else { for(i=0;modes[i];++i) { modos[i].ancho=modes[i]->w; modos[i].alto=modes[i]->h; modos[i].modo=1; } num_modos=i-1; } sprintf(marcavga,"SDL Video Driver"); qsort((void*)&(modos[0].ancho),num_modos,sizeof(struct _modos),compare_mode); }
DIVGAMES/DIV-Games-Studio
src/det_vesa.c
C
gpl-3.0
1,636
package com.tygrewolf.randomtp.reference; /** * Created by TygreWolf on 4/19/2016. */ public class Reference { public static final String MOD_ID = "randomtp"; public static final String MOD_NAME = "Random Teleport"; public static final String LOWERCASE_MOD_ID = MOD_ID.toLowerCase(); public static final String FINGERPRINT = "@FINGERPRINT@"; public static final String VERSION = "@VERSION@"; public static final String SERVER_PROXY_CLASS = "com.tygrewolf.randomtp.proxy.ServerProxy"; public static final String CLIENT_PROXY_CLASS = "com.tygrewolf.randomtp.proxy.ClientProxy"; public static final String GUI_FACTORY_CLASS = "com.tygrewolf.randomtp.client.gui.GuiFactory"; public static final String CATEGORY_NAME_GENERAL = "Category.General"; public static final String CATEGORY_NAME_OTHER = "Category.Other"; }
TygreWolf/RandomTP
src/main/java/com/tygrewolf/randomtp/reference/Reference.java
Java
gpl-3.0
854
#****************************************************************************** # ALX - Skies of Arcadia Legends Examiner # Copyright (C) 2022 Marcel Renner # # This file is part of ALX. # # ALX 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. # # ALX 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 ALX. If not, see <http://www.gnu.org/licenses/>. #****************************************************************************** #============================================================================== # REQUIREMENTS #============================================================================== require_relative('stdentry.rb') # -- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -- module ALX #============================================================================== # CLASS #============================================================================== # Class to handle an armor. class Armor < StdEntry #============================================================================== # PUBLIC #============================================================================== public # Constructs an Armor. def initialize super init_props init_procs end #============================================================================== # PROTECTED #============================================================================== protected # Initialize the entry properties. def init_props add_name_props self[VOC.character_flags] = IntProp.new(:u8, 0, base: 2, width: 10) VOC.characters.each_value do |_name| self[VOC.character_opt(_name.chr)] = StrProp.new(nil, '', dmy: true) end self[VOC.sell ] = IntProp.new(:i8, 0) self[VOC.order[[cid, 1]]] = IntProp.new(:i8, -1) self[VOC.order[[cid, 2]]] = IntProp.new(:i8, -1) if jp? || us? self[padding_hdr] = IntProp.new(:i8, 0) end self[VOC.buy] = IntProp.new(:u16, 0) (1..4).each do |_i| self[VOC.trait_id(_i) ] = IntProp.new( :i8, 0 ) self[VOC.trait_name(_i) ] = StrProp.new( nil, '', dmy: true) self[padding_hdr ] = IntProp.new( :i8, 0 ) self[VOC.trait_value(_i)] = IntProp.new(:i16, 0 ) end if eu? self[padding_hdr] = IntProp.new(:i8, 0) self[padding_hdr] = IntProp.new(:i8, 0) end add_dscr_props end # Initialize the entry procs. def init_procs fetch(VOC.character_flags).proc = Proc.new do |_flags| VOC.characters.each do |_id, _name| _key = VOC.character_opt(_name.chr) self[_key] = (_flags & (0x20 >> _id) != 0) ? 'X' : '' end end (1..4).each do |_i| fetch(VOC.trait_id(_i)).proc = Proc.new do |_id| self[VOC.trait_name(_i)] = VOC.traits(_id) end end end end # class Armor # -- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -- end # module ALX
Taikocuya/ALX
lib/alx/armor.rb
Ruby
gpl-3.0
3,665
/* * Copyright (c) 2017 "Neo4j, Inc." <http://neo4j.com> * * This file is part of Neo4j Graph Algorithms <http://github.com/neo4j-contrib/neo4j-graph-algorithms>. * * Neo4j Graph Algorithms is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphalgo.impl.louvain; import com.carrotsearch.hppc.IntObjectMap; import com.carrotsearch.hppc.IntObjectScatterMap; import com.carrotsearch.hppc.IntScatterSet; import com.carrotsearch.hppc.LongDoubleScatterMap; import org.neo4j.graphalgo.api.Graph; import org.neo4j.graphalgo.api.WeightMapping; import org.neo4j.graphalgo.core.utils.ProgressLogger; import org.neo4j.graphalgo.core.utils.RawValues; import org.neo4j.graphalgo.core.utils.TerminationFlag; import org.neo4j.graphalgo.core.utils.paged.AllocationTracker; import org.neo4j.graphalgo.impl.Algorithm; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Louvain Clustering Algorithm. * <p> * The algo performs modularity optimization as long as the * modularity keeps incrementing. Every optimization step leads * to an array of length nodeCount containing the nodeId->community mapping. * <p> * After each step a new graph gets built from the actual community mapping * and is used as input for the next step. * * @author mknblch */ public class Louvain extends Algorithm<Louvain> { private final int rootNodeCount; private int level; private final ExecutorService pool; private final int concurrency; private final AllocationTracker tracker; private ProgressLogger progressLogger; private TerminationFlag terminationFlag; private int[] communities; private double[] modularities; private int[][] dendrogram; private double[] nodeWeights; private Graph root; private int communityCount; public Louvain(Graph graph, ExecutorService pool, int concurrency, AllocationTracker tracker) { this.root = graph; this.pool = pool; this.concurrency = concurrency; this.tracker = tracker; rootNodeCount = Math.toIntExact(graph.nodeCount()); communities = new int[rootNodeCount]; nodeWeights = new double[rootNodeCount]; tracker.add(4 * rootNodeCount); communityCount = rootNodeCount; Arrays.setAll(communities, i -> i); } public Louvain compute(int maxLevel, int maxIterations) { return compute(maxLevel, maxIterations, false); } public Louvain compute(int maxLevel, int maxIterations, boolean rnd) { // temporary graph Graph graph = this.root; // result arrays dendrogram = new int[maxLevel][]; modularities = new double[maxLevel]; int nodeCount = rootNodeCount; for (level = 0; level < maxLevel; level++) { // start modularity optimization final ModularityOptimization modularityOptimization = new ModularityOptimization(graph, nodeId -> nodeWeights[nodeId], pool, concurrency, tracker, System.currentTimeMillis()) .withProgressLogger(progressLogger) .withTerminationFlag(terminationFlag) .withRandomNeighborOptimization(rnd) .compute(maxIterations); // rebuild graph based on the community structure final int[] communityIds = modularityOptimization.getCommunityIds(); communityCount = LouvainUtils.normalize(communityIds); // release the old algo instance modularityOptimization.release(); progressLogger.log( "level: " + (level + 1) + " communities: " + communityCount + " q: " + modularityOptimization.getModularity()); if (communityCount >= nodeCount) { break; } nodeCount = communityCount; dendrogram[level] = rebuildCommunityStructure(communityIds); modularities[level] = modularityOptimization.getModularity(); graph = rebuildGraph(graph, communityIds, communityCount); } dendrogram = Arrays.copyOf(dendrogram, level); return this; } public Louvain compute(WeightMapping communityMap, int maxLevel, int maxIterations, boolean rnd) { BitSet comCount = new BitSet(); Arrays.setAll(communities, i -> { final int t = (int) communityMap.get(i, -1.0); final int c = t == -1 ? i : t; comCount.set(c); return c; }); // temporary graph int nodeCount = comCount.cardinality(); LouvainUtils.normalize(communities); Graph graph = rebuildGraph(this.root, communities, nodeCount); // result arrays dendrogram = new int[maxLevel][]; modularities = new double[maxLevel]; for (level = 0; level < maxLevel && terminationFlag.running(); level++) { // start modularity optimization final ModularityOptimization modularityOptimization = new ModularityOptimization(graph, nodeId -> nodeWeights[nodeId], pool, concurrency, tracker, System.currentTimeMillis()) .withProgressLogger(progressLogger) .withTerminationFlag(terminationFlag) .withRandomNeighborOptimization(rnd) .compute(maxIterations); // rebuild graph based on the community structure final int[] communityIds = modularityOptimization.getCommunityIds(); communityCount = LouvainUtils.normalize(communityIds); // release the old algo instance modularityOptimization.release(); progressLogger.log( "level: " + (level + 1) + " communities: " + communityCount + " q: " + modularityOptimization.getModularity()); if (communityCount >= nodeCount) { break; } nodeCount = communityCount; dendrogram[level] = rebuildCommunityStructure(communityIds); modularities[level] = modularityOptimization.getModularity(); graph = rebuildGraph(graph, communityIds, communityCount); } dendrogram = Arrays.copyOf(dendrogram, level); return this; } /** * create a virtual graph based on the community structure of the * previous louvain round * * @param graph previous graph * @param communityIds community structure * @return a new graph built from a community structure */ private Graph rebuildGraph(Graph graph, int[] communityIds, int communityCount) { // count and normalize community structure final int nodeCount = communityIds.length; // bag of nodeId->{nodeId, ..} final IntObjectMap<IntScatterSet> relationships = new IntObjectScatterMap<>(nodeCount); // accumulated weights final LongDoubleScatterMap relationshipWeights = new LongDoubleScatterMap(nodeCount); // for each node in the current graph for (int i = 0; i < nodeCount; i++) { // map node nodeId to community nodeId final int sourceCommunity = communityIds[i]; // get transitions from current node graph.forEachOutgoing(i, (s, t, r) -> { // mapping final int targetCommunity = communityIds[t]; final double value = graph.weightOf(s, t); if (sourceCommunity == targetCommunity) { nodeWeights[sourceCommunity] += value; } // add IN and OUT relation putIfAbsent(relationships, targetCommunity).add(sourceCommunity); putIfAbsent(relationships, sourceCommunity).add(targetCommunity); relationshipWeights.addTo(RawValues.combineIntInt(sourceCommunity, targetCommunity), value / 2); // TODO validate relationshipWeights.addTo(RawValues.combineIntInt(targetCommunity, sourceCommunity), value / 2); return true; }); } // create temporary graph return new LouvainGraph(communityCount, relationships, relationshipWeights); } private int[] rebuildCommunityStructure(int[] communityIds) { // rebuild community array assert rootNodeCount == communities.length; final int[] ints = new int[rootNodeCount]; Arrays.setAll(ints, i -> communityIds[communities[i]]); communities = ints; return communities; } /** * nodeId to community mapping array * * @return */ public int[] getCommunityIds() { return communities; } public int[] getCommunityIds(int level) { return dendrogram[level]; } public int[][] getDendrogram() { return dendrogram; } public double[] getModularities() { return Arrays.copyOfRange(modularities, 0, level); } public double getFinalModularity() { return modularities[level-1]; } /** * number of outer iterations * * @return */ public int getLevel() { return level; } /** * number of distinct communities * * @return */ public long getCommunityCount() { return communityCount; } /** * result stream * * @return */ public Stream<Result> resultStream() { return IntStream.range(0, rootNodeCount) .mapToObj(i -> new Result(i, communities[i])); } public Stream<StreamingResult> dendrogramStream(boolean includeIntermediateCommunities) { return IntStream.range(0, rootNodeCount) .mapToObj(i -> { List<Long> communitiesList = null; if (includeIntermediateCommunities) { communitiesList = new ArrayList<>(dendrogram.length); for (int[] community : dendrogram) { communitiesList.add((long) community[i]); } } return new StreamingResult(root.toOriginalNodeId(i), communitiesList, communities[i]); }); } @Override public Louvain me() { return this; } @Override public Louvain release() { tracker.add(4 * rootNodeCount); communities = null; return this; } @Override public Louvain withProgressLogger(ProgressLogger progressLogger) { this.progressLogger = progressLogger; return this; } @Override public Louvain withTerminationFlag(TerminationFlag terminationFlag) { this.terminationFlag = terminationFlag; return this; } private static IntScatterSet putIfAbsent(IntObjectMap<IntScatterSet> relationships, int community) { final IntScatterSet intCursors = relationships.get(community); if (null == intCursors) { final IntScatterSet newSet = new IntScatterSet(); relationships.put(community, newSet); return newSet; } return intCursors; } /** * result object */ public static final class Result { public final long nodeId; public final long community; public Result(long id, long community) { this.nodeId = id; this.community = community; } } public static final class StreamingResult { public final long nodeId; public final List<Long> communities; public final long community; public StreamingResult(long nodeId, List<Long> communities, long community) { this.nodeId = nodeId; this.communities = communities; this.community = community; } } }
neo4j-contrib/neo4j-graph-algorithms
algo/src/main/java/org/neo4j/graphalgo/impl/louvain/Louvain.java
Java
gpl-3.0
12,980
/* Copyright 2017 SINTEF ICT, Applied Mathematics. Copyright 2017 Statoil ASA. This file is part of the Open Porous Media Project (OPM). OPM 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. OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ #if HAVE_CONFIG_H #include <config.h> #endif // HAVE_CONFIG_H #define NVERBOSE #define BOOST_TEST_MODULE TEST_ECLPVTCOMMON_UNITCONV #include <opm/common/utility/platform_dependent/disable_warnings.h> #include <boost/test/unit_test.hpp> #include <opm/common/utility/platform_dependent/reenable_warnings.h> #include <opm/utility/ECLPvtCommon.hpp> #include <opm/utility/ECLUnitHandling.hpp> #include <exception> #include <stdexcept> struct ConvertToSI { explicit ConvertToSI(const ::Opm::ECLUnits::UnitSystem& usys); double dens { 0.0 }; double press { 0.0 }; double compr { 0.0 }; double disgas { 0.0 }; double vapoil { 0.0 }; double recipFvf { 0.0 }; double recipFvfDerivPress { 0.0 }; double recipFvfDerivVapOil { 0.0 }; double recipFvfVisc { 0.0 }; double recipFvfViscDerivPress { 0.0 }; double recipFvfViscDerivVapOil { 0.0 }; double recipFvfGas { 0.0 }; double recipFvfGasDerivPress { 0.0 }; double recipFvfGasDerivVapOil { 0.0 }; double recipFvfGasVisc { 0.0 }; double recipFvfGasViscDerivPress { 0.0 }; double recipFvfGasViscDerivVapOil { 0.0 }; }; ConvertToSI::ConvertToSI(const ::Opm::ECLUnits::UnitSystem& usys) { using Cvrt = ::Opm::ECLPVT::CreateUnitConverter::ToSI; auto apply = [](const ::Opm::ECLPVT::ConvertUnits::Converter& cnv) { return cnv(1.0); }; // Mass density this->dens = apply(Cvrt::density(usys)); // Pressure this->press = apply(Cvrt::pressure(usys)); // Compressibility this->compr = apply(Cvrt::compressibility(usys)); // Dissolved gas-oil ratio (Rs) this->disgas = apply(Cvrt::disGas(usys)); // Vaporised oil-gas ratio (Rv) this->vapoil = apply(Cvrt::vapOil(usys)); // Reciprocal formation volume factor (1/B) this->recipFvf = apply(Cvrt::recipFvf(usys)); // Derivative of reciprocal formation volume factor (1/B) with respect // to fluid (phase) pressure. this->recipFvfDerivPress = apply(Cvrt::recipFvfDerivPress(usys)); // Derivative of reciprocal formation volume factor (1/B) with respect // to vaporised oil-gas ratio. this->recipFvfDerivVapOil = apply(Cvrt::recipFvfDerivVapOil(usys)); // Reciprocal product of formation volume factor and viscosity // (1/(B*mu)). this->recipFvfVisc = apply(Cvrt::recipFvfVisc(usys)); // Derivative of reciprocal product of formation volume factor and // viscosity (1/(B*mu)) with respect to fluid (phase) pressure. this->recipFvfViscDerivPress = apply(Cvrt::recipFvfViscDerivPress(usys)); // Derivative of reciprocal product of formation volume factor and // viscosity (1/(B*mu)) with respect to vaporised oil-gas ratio. this->recipFvfViscDerivVapOil = apply(Cvrt::recipFvfViscDerivVapOil(usys)); // Reciprocal formation volume factor for gas (1/Bg) this->recipFvfGas = apply(Cvrt::recipFvfGas(usys)); // Derivative of reciprocal formation volume factor for gas (1/Bg) with // respect to fluid (phase) pressure. this->recipFvfGasDerivPress = apply(Cvrt::recipFvfGasDerivPress(usys)); // Derivative of reciprocal formation volume factor for gas (1/Bg) with // respect to vaporised oil-gas ratio. this->recipFvfGasDerivVapOil = apply(Cvrt::recipFvfGasDerivVapOil(usys)); // Reciprocal product of formation volume factor for gas and viscosity // (1/(Bg*mu_g)). this->recipFvfGasVisc = apply(Cvrt::recipFvfGasVisc(usys)); // Derivative of reciprocal product of formation volume factor for gas // and viscosity (1/(Bg*mu_g)) with respect to fluid (phase) pressure. this->recipFvfGasViscDerivPress = apply(Cvrt::recipFvfGasViscDerivPress(usys)); // Derivative of reciprocal product of formation volume factor for gas // and viscosity (1/(Bg*mu_g)) with respect to vaporised oil-gas ratio. this->recipFvfGasViscDerivVapOil = apply(Cvrt::recipFvfGasViscDerivVapOil(usys)); } template <std::size_t N> using DVec = ::Opm::ECLPVT::DenseVector<N>; // ===================================================================== BOOST_AUTO_TEST_SUITE (Basic_Conversion) BOOST_AUTO_TEST_CASE (Metric) { const auto usys = ::Opm::ECLUnits::createUnitSystem(1); const auto scale = ConvertToSI(*usys); // Mass density BOOST_CHECK_CLOSE(scale.dens, 1.0, 1.0e-10); // Pressure BOOST_CHECK_CLOSE(scale.press, 1.0e5, 1.0e-10); // Compressibility BOOST_CHECK_CLOSE(scale.compr, 1.0e-5, 1.0e-10); // Dissolved Gas-Oil Ratio (Rs) BOOST_CHECK_CLOSE(scale.disgas, 1.0, 1.0e-10); // Vaporised Oil-Gas Ratio (Rv) BOOST_CHECK_CLOSE(scale.vapoil, 1.0, 1.0e-10); // Reciprocal Formation Volume Factor (1 / B) BOOST_CHECK_CLOSE(scale.recipFvf, 1.0, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfDerivPress, 1.0e-5, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfDerivVapOil, 1.0, 1.0e-10); // Reciprocal Product of FVF and Viscosity (1 / (B*mu)). BOOST_CHECK_CLOSE(scale.recipFvfVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfViscDerivPress, 1.0e-2, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfViscDerivVapOil, 1.0e3, 1.0e-10); // Reciprocal Formation Volume Factor for Gas (1 / Bg) BOOST_CHECK_CLOSE(scale.recipFvfGas, 1.0, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasDerivPress, 1.0e-5, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg ) w.r.t. Vaporised // Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasDerivVapOil, 1.0, 1.0e-10); // Reciprocal Product of FVF for Gas and Viscosity (1 / (Bg*mu_g)). BOOST_CHECK_CLOSE(scale.recipFvfGasVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivPress, 1.0e-2, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivVapOil, 1.0e3, 1.0e-10); } BOOST_AUTO_TEST_CASE (Field) { const auto usys = ::Opm::ECLUnits::createUnitSystem(2); const auto scale = ConvertToSI(*usys); // Mass density BOOST_CHECK_CLOSE(scale.dens, 1.601846337396014e+01, 1.0e-10); // Pressure BOOST_CHECK_CLOSE(scale.press, 6.894757293168360e+03, 1.0e-10); // Compressibility BOOST_CHECK_CLOSE(scale.compr, 1.450377377302092e-04, 1.0e-10); // Dissolved Gas-Oil Ratio (Rs) BOOST_CHECK_CLOSE(scale.disgas, 1.781076066790352e+02, 1.0e-10); // Vaporised Oil-Gas Ratio (Rv) BOOST_CHECK_CLOSE(scale.vapoil, 5.614583333333335e-03, 1.0e-10); // Reciprocal Formation Volume Factor (1 / B) BOOST_CHECK_CLOSE(scale.recipFvf, 1.0, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfDerivPress, 1.450377377302092e-04, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfDerivVapOil, 1.781076066790352e+02, 1.0e-10); // Reciprocal Product of FVF and Viscosity (1 / (B*mu)). BOOST_CHECK_CLOSE(scale.recipFvfVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfViscDerivPress, 1.450377377302093e-01, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfViscDerivVapOil, 1.781076066790352e+05, 1.0e-10); // Reciprocal Formation Volume Factor for Gas (1 / Bg) BOOST_CHECK_CLOSE(scale.recipFvfGas, 1.781076066790352e+02, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasDerivPress, 2.583232434526917e-02, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg ) w.r.t. Vaporised // Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasDerivVapOil, 3.172231955693390e+04, 1.0e-10); // Reciprocal Product of FVF for Gas and Viscosity (1 / (Bg*mu_g)). BOOST_CHECK_CLOSE(scale.recipFvfGasVisc, 1.781076066790352e+05, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivPress, 2.583232434526917e+01, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivVapOil, 3.172231955693390e+07, 1.0e-10); } BOOST_AUTO_TEST_CASE (Lab) { const auto usys = ::Opm::ECLUnits::createUnitSystem(3); const auto scale = ConvertToSI(*usys); // Mass density BOOST_CHECK_CLOSE(scale.dens, 1.0e3, 1.0e-10); // Pressure BOOST_CHECK_CLOSE(scale.press, 101.325e3, 1.0e-10); // Compressibility BOOST_CHECK_CLOSE(scale.compr, 9.869232667160129e-06, 1.0e-10); // Dissolved Gas-Oil Ratio (Rs) BOOST_CHECK_CLOSE(scale.disgas, 1.0, 1.0e-10); // Vaporised Oil-Gas Ratio (Rv) BOOST_CHECK_CLOSE(scale.vapoil, 1.0, 1.0e-10); // Reciprocal Formation Volume Factor (1 / B) BOOST_CHECK_CLOSE(scale.recipFvf, 1.0, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfDerivPress, 9.869232667160129e-06, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfDerivVapOil, 1.0, 1.0e-10); // Reciprocal Product of FVF and Viscosity (1 / (B*mu)). BOOST_CHECK_CLOSE(scale.recipFvfVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfViscDerivPress, 9.869232667160128e-03, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfViscDerivVapOil, 1.0e3, 1.0e-10); // Reciprocal Formation Volume Factor for Gas (1 / Bg) BOOST_CHECK_CLOSE(scale.recipFvfGas, 1.0, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasDerivPress, 9.869232667160129e-06, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg) w.r.t. Vaporised // Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasDerivVapOil, 1.0, 1.0e-10); // Reciprocal Product of FVF for Gas and Viscosity (1 / (Bg*mu_g)). BOOST_CHECK_CLOSE(scale.recipFvfGasVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivPress, 9.869232667160128e-03, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivVapOil, 1.0e3, 1.0e-10); } BOOST_AUTO_TEST_CASE (PVT_M) { const auto usys = ::Opm::ECLUnits::createUnitSystem(4); const auto scale = ConvertToSI(*usys); // Mass density BOOST_CHECK_CLOSE(scale.dens, 1.0, 1.0e-10); // Pressure BOOST_CHECK_CLOSE(scale.press, 101.325e3, 1.0e-10); // Compressibility BOOST_CHECK_CLOSE(scale.compr, 9.869232667160129e-06, 1.0e-10); // Dissolved Gas-Oil Ratio (Rs) BOOST_CHECK_CLOSE(scale.disgas, 1.0, 1.0e-10); // Vaporised Oil-Gas Ratio (Rv) BOOST_CHECK_CLOSE(scale.vapoil, 1.0, 1.0e-10); // Reciprocal Formation Volume Factor (1 / B) BOOST_CHECK_CLOSE(scale.recipFvf, 1.0, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfDerivPress, 9.869232667160129e-06, 1.0e-10); // Derivative of Reciprocal FVF (1 / B) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfDerivVapOil, 1.0, 1.0e-10); // Reciprocal Product of FVF and Viscosity (1 / (B*mu)). BOOST_CHECK_CLOSE(scale.recipFvfVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfViscDerivPress, 9.869232667160128e-03, 1.0e-10); // Derivative of Reciprocal Product of FVF and Viscosity (1 / (B*mu)) // w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfViscDerivVapOil, 1.0e3, 1.0e-10); // Reciprocal Formation Volume Factor for Gas (1 / Bg) BOOST_CHECK_CLOSE(scale.recipFvfGas, 1.0, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasDerivPress, 9.869232667160129e-06, 1.0e-10); // Derivative of Reciprocal FVF for Gas (1 / Bg ) w.r.t. Vaporised // Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasDerivVapOil, 1.0, 1.0e-10); // Reciprocal Product of FVF for Gas and Viscosity (1 / (Bg*mu_g)). BOOST_CHECK_CLOSE(scale.recipFvfGasVisc, 1.0e3, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Pressure BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivPress, 9.869232667160128e-03, 1.0e-10); // Derivative of Reciprocal Product of FVF for Gas and Viscosity (1 / // (Bg*mu_g)) w.r.t. Vaporised Oil-Gas Ratio. BOOST_CHECK_CLOSE(scale.recipFvfGasViscDerivVapOil, 1.0e3, 1.0e-10); } BOOST_AUTO_TEST_SUITE_END () // ===================================================================== BOOST_AUTO_TEST_SUITE (DenseVector) BOOST_AUTO_TEST_CASE (Construct) { // DenseVector<1> { const auto x = DVec<1>{ std::array<double, 1>{ { 1.0 } } }; BOOST_CHECK_CLOSE(x.array()[0], 1.0, 1.0e-10); } // DenseVector<2> { const auto x = DVec<2>{ std::array<double, 2>{ { 2.0, -1.0 } } }; BOOST_CHECK_CLOSE(x.array()[0], 2.0, 1.0e-10); BOOST_CHECK_CLOSE(x.array()[1], -1.0, 1.0e-10); } } BOOST_AUTO_TEST_CASE (Addition) { const auto x = DVec<2>{ std::array<double,2>{ 0.1, 2.3 } }; const auto two_x = x + x; BOOST_CHECK_CLOSE(two_x.array()[0], 0.2, 1.0e-10); BOOST_CHECK_CLOSE(two_x.array()[1], 4.6, 1.0e-10); } BOOST_AUTO_TEST_CASE (Subtraction) { const auto x = DVec<2>{ std::array<double,2>{ 0.1, 2.3 } }; const auto y = DVec<2>{ std::array<double,2>{ 10.9, 8.7 } }; const auto x_minus_y = x - y; BOOST_CHECK_CLOSE(x_minus_y.array()[0], -10.8, 1.0e-10); BOOST_CHECK_CLOSE(x_minus_y.array()[1], - 6.4, 1.0e-10); } BOOST_AUTO_TEST_CASE (Mult_By_Scalar) { // x *= a { auto x = DVec<2> { std::array<double,2>{ 0.1, 2.3 } }; x *= 5.0; BOOST_CHECK_CLOSE(x.array()[0], 0.5, 1.0e-10); BOOST_CHECK_CLOSE(x.array()[1], 11.5, 1.0e-10); } // y <- x * a { const auto x = DVec<2> { std::array<double,2>{ 0.1, 2.3 } }; { const auto y = x * 5.0; BOOST_CHECK_CLOSE(y.array()[0], 0.5, 1.0e-10); BOOST_CHECK_CLOSE(y.array()[1], 11.5, 1.0e-10); } { const auto y = 2.5 * x; BOOST_CHECK_CLOSE(y.array()[0], 0.25, 1.0e-10); BOOST_CHECK_CLOSE(y.array()[1], 5.75, 1.0e-10); } } } BOOST_AUTO_TEST_CASE (Divide_By_Scalar) { // x /= a { auto x = DVec<2> { std::array<double,2>{ 0.5, 11.5 } }; x /= 5.0; BOOST_CHECK_CLOSE(x.array()[0], 0.1, 1.0e-10); BOOST_CHECK_CLOSE(x.array()[1], 2.3, 1.0e-10); } // y <- x / a { const auto x = DVec<2> { std::array<double,2>{ 0.25, 5.75 } }; const auto y = x / 2.5; BOOST_CHECK_CLOSE(y.array()[0], 0.1, 1.0e-10); BOOST_CHECK_CLOSE(y.array()[1], 2.3, 1.0e-10); } } BOOST_AUTO_TEST_SUITE_END ()
OPM/ResInsight
ThirdParty/custom-opm-flowdiag-app/opm-flowdiagnostics-applications/tests/test_eclpvtcommon.cpp
C++
gpl-3.0
17,572
# PTG - Project Template Generator # Copyright (C) 2009 Mariusz Ceier # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. CC = gcc CFLAGS += -g -I. `xml2-config --cflags` -Wall -pedantic -pedantic-errors -DPTG_EXTRA_CHECKS=1 LDFLAGS += `xml2-config --libs` SRCS = PTG/Main.c PTG/ListIDs.c PTG/OS.c PTG/Status.c PTG/List.c PTG/Option.c PTG/Options.c PTG/Class.c PTG/Classes.c PTG/Namespace.c PTG/Namespaces.c PTG/Project.c PTG/Projects.c PTG/Workspace.c PTG/Generator.c PTG/XML.c PTG/Template.c OBJS = $(SRCS:.c=.o) PROGRAM = ptg .PHONY: all all: $(PROGRAM) $(PROGRAM): $(OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $(PROGRAM) $(OBJS) %.o: %.c $(CC) $(CFLAGS) -o $@ -c $< .PHONY: docs clean distclean depend rebuild package docs: doxygen Doxyfile clean: -rm -f $(PROGRAM) -rm -f $(OBJS) -rm -f .deps distclean: clean -rm -r -f Docs docs $(PROGRAM).tar.gz depend: $(CC) $(CFLAGS) -MM -MT $(SRCS) > .deps rebuild: clean all package: distclean @mkdir .tmp tar -zcvf .tmp/$(PROGRAM).tar.gz --exclude .tmp $(PWD) @mv .tmp/$(PROGRAM).tar.gz . @rm -r .tmp -include .deps
mceier/ptg
Makefile
Makefile
gpl-3.0
1,691
/* Copyright (C) 2015 William Breathitt Gray * * This file is part of Mission Accomplished. * * Mission Accomplished 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. * * Mission Accomplished 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 Mission Accomplished. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef TEXTURE_H #define TEXTURE_H #include "SDL.h" struct Texture{ SDL_Texture *texture; Texture(SDL_Renderer *renderer, const char *file); ~Texture(); Texture(const Texture&) = delete; Texture& operator=(const Texture&) = delete; Texture(Texture&&) = delete; Texture& operator=(Texture&&) = delete; }; #endif
vilhelmgray/MissionAccomplished
src/Texture.h
C
gpl-3.0
1,098
//namespace FDM.InputOutput //{ // public class SGPropertyNode // { // private int MAX_STRING_LEN = 1024; // // Property value types. // enum PropertyValeType // { // NONE = 0, // ALIAS, // BOOL, // INT, // LONG, // FLOAT, // DOUBLE, // STRING, // UNSPECIFIED // }; // /** // * Access mode attributes. // * // * <p>The ARCHIVE attribute is strictly advisory, and controls // * whether the property should normally be saved and restored.</p> // */ // enum AccessModeAttribute { // READ = 1, // WRITE = 2, // ARCHIVE = 4, // REMOVED = 8, // TRACE_READ = 16, // TRACE_WRITE = 32, // USERARCHIVE = 64 // }; // /** // * Last used attribute // * Update as needed when enum Attribute is changed // */ // static const int LAST_USED_ATTRIBUTE; // /** // * Default constructor. // */ // public SGPropertyNode() // { // } // /** // * Copy constructor. // */ // public SGPropertyNode(SGPropertyNode node) // { // } // /** // * Test whether this node contains a primitive leaf value. // */ // public bool HasValue() // { // return (_type != NONE); // } // /** // * Get the node's simple (XML) name. // */ // public string GetName() // { // return _name.c_str(); // } // /** // * Get the node's pretty display name, with subscript when needed. // */ // const char * getDisplayName (bool simplify = false) const; // /** // * Get the node's integer index. // */ // int getIndex () const { return _index; } // /** // * Get a non-const pointer to the node's parent. // */ // SGPropertyNode * getParent () { return _parent; } // /** // * Get a const pointer to the node's parent. // */ // const SGPropertyNode * getParent () const { return _parent; } // // // // Children. // // // /** // * Get the number of child nodes. // */ // int nChildren () const { return (int)_children.size(); } // /** // * Get a child node by position (*NOT* index). // */ // SGPropertyNode * getChild (int position); // /** // * Get a const child node by position (*NOT* index). // */ // const SGPropertyNode * getChild (int position) const; // /** // * Test whether a named child exists. // */ // bool hasChild (const char * name, int index = 0) const // { // return (getChild(name, index) != 0); // } // /** // * Get a child node by name and index. // */ // SGPropertyNode * getChild (const char * name, int index = 0, // bool create = false); // /** // * Get a const child node by name and index. // */ // const SGPropertyNode * getChild (const char * name, int index = 0) const; // /** // * Get a vector of all children with the specified name. // */ // vector<SGPropertyNode_ptr> getChildren (const char * name) const; // /** // * Remove child by position. // */ // SGPropertyNode_ptr removeChild (int pos, bool keep = true); // /** // * Remove a child node // */ // SGPropertyNode_ptr removeChild (const char * name, int index = 0, // bool keep = true); // /** // * Remove all children with the specified name. // */ // vector<SGPropertyNode_ptr> removeChildren (const char * name, // bool keep = true); // // // // Alias support. // // // /** // * Alias this node's leaf value to another's. // */ // bool alias (SGPropertyNode * target); // /** // * Alias this node's leaf value to another's by relative path. // */ // bool alias (const char * path); // /** // * Remove any alias for this node. // */ // bool unalias (); // /** // * Test whether the node's leaf value is aliased to another's. // */ // bool isAlias () const { return (_type == ALIAS); } // /** // * Get a non-const pointer to the current alias target, if any. // */ // SGPropertyNode * getAliasTarget (); // /** // * Get a const pointer to the current alias target, if any. // */ // const SGPropertyNode * getAliasTarget () const; // // // // Path information. // // // /** // * Get the path to this node from the root. // */ // const char * getPath (bool simplify = false) const; // /** // * Get a pointer to the root node. // */ // SGPropertyNode * getRootNode (); // /** // * Get a const pointer to the root node. // */ // const SGPropertyNode * getRootNode () const; // /** // * Get a pointer to another node by relative path. // */ // SGPropertyNode * getNode (const char * relative_path, bool create = false); // /** // * Get a pointer to another node by relative path. // * // * This method leaves the index off the last member of the path, // * so that the user can specify it separately (and save some // * string building). For example, getNode("/bar[1]/foo", 3) is // * exactly equivalent to getNode("bar[1]/foo[3]"). The index // * provided overrides any given in the path itself for the last // * component. // */ // SGPropertyNode * getNode (const char * relative_path, int index, // bool create = false); // /** // * Get a const pointer to another node by relative path. // */ // const SGPropertyNode * getNode (const char * relative_path) const; // /** // * Get a const pointer to another node by relative path. // * // * This method leaves the index off the last member of the path, // * so that the user can specify it separate. // */ // const SGPropertyNode * getNode (const char * relative_path, // int index) const; // // // // Access Mode. // // // /** // * Check a single mode attribute for the property node. // */ // bool getAttribute (Attribute attr) const { return ((_attr & attr) != 0); } // /** // * Set a single mode attribute for the property node. // */ // void setAttribute (Attribute attr, bool state) { // (state ? _attr |= attr : _attr &= ~attr); // } // /** // * Get all of the mode attributes for the property node. // */ // int getAttributes () const { return _attr; } // /** // * Set all of the mode attributes for the property node. // */ // void setAttributes (int attr) { _attr = attr; } // // // // Leaf Value (primitive). // // // /** // * Get the type of leaf value, if any, for this node. // */ // Type getType () const; // /** // * Get a bool value for this node. // */ // bool getBoolValue () const; // /** // * Get an int value for this node. // */ // int getIntValue () const; // /** // * Get a long int value for this node. // */ // long getLongValue () const; // /** // * Get a float value for this node. // */ // float getFloatValue () const; // /** // * Get a double value for this node. // */ // double getDoubleValue () const; // /** // * Get a string value for this node. // */ // const char * getStringValue () const; // /** // * Set a bool value for this node. // */ // bool setBoolValue (bool value); // /** // * Set an int value for this node. // */ // bool setIntValue (int value); // /** // * Set a long int value for this node. // */ // bool setLongValue (long value); // /** // * Set a float value for this node. // */ // bool setFloatValue (float value); // /** // * Set a double value for this node. // */ // bool setDoubleValue (double value); // /** // * Set a string value for this node. // */ // bool setStringValue (const char * value); // /** // * Set a value of unspecified type for this node. // */ // bool setUnspecifiedValue (const char * value); // // // // Data binding. // // // /** // * Test whether this node is bound to an external data source. // */ // bool isTied () const { return _tied; } // /** // * Bind this node to an external bool source. // */ // bool tie (const SGRawValue<bool> &rawValue, bool useDefault = true); // /** // * Bind this node to an external int source. // */ // bool tie (const SGRawValue<int> &rawValue, bool useDefault = true); // /** // * Bind this node to an external long int source. // */ // bool tie (const SGRawValue<long> &rawValue, bool useDefault = true); // /** // * Bind this node to an external float source. // */ // bool tie (const SGRawValue<float> &rawValue, bool useDefault = true); // /** // * Bind this node to an external double source. // */ // bool tie (const SGRawValue<double> &rawValue, bool useDefault = true); // /** // * Bind this node to an external string source. // */ // bool tie (const SGRawValue<const char *> &rawValue, bool useDefault = true); // /** // * Unbind this node from any external data source. // */ // bool untie (); // // // // Convenience methods using paths. // // TODO: add attribute methods // // // /** // * Get another node's type. // */ // Type getType (const char * relative_path) const; // /** // * Test whether another node has a leaf value. // */ // bool hasValue (const char * relative_path) const; // /** // * Get another node's value as a bool. // */ // bool getBoolValue (const char * relative_path, // bool defaultValue = false) const; // /** // * Get another node's value as an int. // */ // int getIntValue (const char * relative_path, // int defaultValue = 0) const; // /** // * Get another node's value as a long int. // */ // long getLongValue (const char * relative_path, // long defaultValue = 0L) const; // /** // * Get another node's value as a float. // */ // float getFloatValue (const char * relative_path, // float defaultValue = 0.0) const; // /** // * Get another node's value as a double. // */ // double getDoubleValue (const char * relative_path, // double defaultValue = 0.0L) const; // /** // * Get another node's value as a string. // */ // const char * getStringValue (const char * relative_path, // const char * defaultValue = "") const; // /** // * Set another node's value as a bool. // */ // bool setBoolValue (const char * relative_path, bool value); // /** // * Set another node's value as an int. // */ // bool setIntValue (const char * relative_path, int value); // /** // * Set another node's value as a long int. // */ // bool setLongValue (const char * relative_path, long value); // /** // * Set another node's value as a float. // */ // bool setFloatValue (const char * relative_path, float value); // /** // * Set another node's value as a double. // */ // bool setDoubleValue (const char * relative_path, double value); // /** // * Set another node's value as a string. // */ // bool setStringValue (const char * relative_path, const char * value); // /** // * Set another node's value with no specified type. // */ // bool setUnspecifiedValue (const char * relative_path, const char * value); // /** // * Test whether another node is bound to an external data source. // */ // bool isTied (const char * relative_path) const; // /** // * Bind another node to an external bool source. // */ // bool tie (const char * relative_path, const SGRawValue<bool> &rawValue, // bool useDefault = true); // /** // * Bind another node to an external int source. // */ // bool tie (const char * relative_path, const SGRawValue<int> &rawValue, // bool useDefault = true); // /** // * Bind another node to an external long int source. // */ // bool tie (const char * relative_path, const SGRawValue<long> &rawValue, // bool useDefault = true); // /** // * Bind another node to an external float source. // */ // bool tie (const char * relative_path, const SGRawValue<float> &rawValue, // bool useDefault = true); // /** // * Bind another node to an external double source. // */ // bool tie (const char * relative_path, const SGRawValue<double> &rawValue, // bool useDefault = true); // /** // * Bind another node to an external string source. // */ // bool tie (const char * relative_path, const SGRawValue<const char *> &rawValue, // bool useDefault = true); // /** // * Unbind another node from any external data source. // */ // bool untie (const char * relative_path); // /** // * Add a change listener to the property. If "initial" is set call the // * listener initially. // */ // void addChangeListener (SGPropertyChangeListener * listener, // bool initial = false); // /** // * Remove a change listener from the property. // */ // void removeChangeListener (SGPropertyChangeListener * listener); // /** // * Fire a value change event to all listeners. // */ // void fireValueChanged (); // /** // * Fire a child-added event to all listeners. // */ // void fireChildAdded (SGPropertyNode * child); // /** // * Fire a child-removed event to all listeners. // */ // void fireChildRemoved (SGPropertyNode * child); // /** // * Clear any existing value and set the type to NONE. // */ // void clearValue (); //protected: // void fireValueChanged (SGPropertyNode * node); // void fireChildAdded (SGPropertyNode * parent, SGPropertyNode * child); // void fireChildRemoved (SGPropertyNode * parent, SGPropertyNode * child); // /** // * Protected constructor for making new nodes on demand. // */ // SGPropertyNode (const char * name, int index, SGPropertyNode * parent); //private: // // Get the raw value // bool get_bool () const; // int get_int () const; // long get_long () const; // float get_float () const; // double get_double () const; // const char * get_string () const; // // Set the raw value // bool set_bool (bool value); // bool set_int (int value); // bool set_long (long value); // bool set_float (float value); // bool set_double (double value); // bool set_string (const char * value); // /** // * Get the value as a string. // */ // const char * make_string () const; // /** // * Trace a read access. // */ // void trace_read () const; // /** // * Trace a write access. // */ // void trace_write () const; // class hash_table; // int _index; // string _name; // mutable string _display_name; // /// To avoid cyclic reference counting loops this shall not be a reference // /// counted pointer // SGPropertyNode * _parent; // vector<SGPropertyNode_ptr> _children; // vector<SGPropertyNode_ptr> _removedChildren; // mutable string _path; // mutable string _buffer; // hash_table * _path_cache; // Type _type; // bool _tied; // int _attr; // // The right kind of pointer... // union { // SGPropertyNode * alias; // SGRawValue<bool> * bool_val; // SGRawValue<int> * int_val; // SGRawValue<long> * long_val; // SGRawValue<float> * float_val; // SGRawValue<double> * double_val; // SGRawValue<const char *> * string_val; // } _value; // union { // bool bool_val; // int int_val; // long long_val; // float float_val; // double double_val; // char * string_val; // } _local_val; // vector <SGPropertyChangeListener *> * _listeners; // /** // * A very simple hash table with no remove functionality. // */ // class hash_table { // public: // /** // * An entry in a bucket in a hash table. // */ // class entry { // public: // entry (); // ~entry (); // const char * get_key () { return _key.c_str(); } // void set_key (const char * key); // SGPropertyNode * get_value () { return _value; } // void set_value (SGPropertyNode * value); // private: // string _key; // SGSharedPtr<SGPropertyNode> _value; // }; // /** // * A bucket in a hash table. // */ // class bucket { // public: // bucket (); // ~bucket (); // entry * get_entry (const char * key, bool create = false); // void erase(const char * key); // private: // int _length; // entry ** _entries; // }; // friend class bucket; // hash_table (); // ~hash_table (); // SGPropertyNode * get (const char * key); // void put (const char * key, SGPropertyNode * value); // void erase(const char * key); // private: // unsigned int hashcode (const char * key); // unsigned int _data_length; // bucket ** _data; // }; //}; ////////////////////////////////////////////////////////////////////////// //// Private methods from SGPropertyNode (may be inlined for speed). ////////////////////////////////////////////////////////////////////////// //inline bool //SGPropertyNode::get_bool () const //{ // if (_tied) // return _value.bool_val->getValue(); // else // return _local_val.bool_val; //} //inline int //SGPropertyNode::get_int () const //{ // if (_tied) // return _value.int_val->getValue(); // else // return _local_val.int_val; //} //inline long //SGPropertyNode::get_long () const //{ // if (_tied) // return _value.long_val->getValue(); // else // return _local_val.long_val; //} //inline float //SGPropertyNode::get_float () const //{ // if (_tied) // return _value.float_val->getValue(); // else // return _local_val.float_val; //} //inline double //SGPropertyNode::get_double () const //{ // if (_tied) // return _value.double_val->getValue(); // else // return _local_val.double_val; //} //inline const char * //SGPropertyNode::get_string () const //{ // if (_tied) // return _value.string_val->getValue(); // else // return _local_val.string_val; //} //inline bool //SGPropertyNode::set_bool (bool val) //{ // if (_tied) { // if (_value.bool_val->setValue(val)) { // fireValueChanged(); // return true; // } else { // return false; // } // } else { // _local_val.bool_val = val; // fireValueChanged(); // return true; // } //} //inline bool //SGPropertyNode::set_int (int val) //{ // if (_tied) { // if (_value.int_val->setValue(val)) { // fireValueChanged(); // return true; // } else { // return false; // } // } else { // _local_val.int_val = val; // fireValueChanged(); // return true; // } //} //inline bool //SGPropertyNode::set_long (long val) //{ // if (_tied) { // if (_value.long_val->setValue(val)) { // fireValueChanged(); // return true; // } else { // return false; // } // } else { // _local_val.long_val = val; // fireValueChanged(); // return true; // } //} //inline bool //SGPropertyNode::set_float (float val) //{ // if (_tied) { // if (_value.float_val->setValue(val)) { // fireValueChanged(); // return true; // } else { // return false; // } // } else { // _local_val.float_val = val; // fireValueChanged(); // return true; // } //} //inline bool //SGPropertyNode::set_double (double val) //{ // if (_tied) { // if (_value.double_val->setValue(val)) { // fireValueChanged(); // return true; // } else { // return false; // } // } else { // _local_val.double_val = val; // fireValueChanged(); // return true; // } //} //inline bool //SGPropertyNode::set_string (const char * val) //{ // if (_tied) { // if (_value.string_val->setValue(val)) { // fireValueChanged(); // return true; // } else { // return false; // } // } else { // delete [] _local_val.string_val; // _local_val.string_val = copy_string(val); // fireValueChanged(); // return true; // } //} //void //SGPropertyNode::clearValue () //{ // switch (_type) { // case NONE: // break; // case ALIAS: // _value.alias = 0; // break; // case BOOL: // if (_tied) { // delete _value.bool_val; // _value.bool_val = 0; // } // _local_val.bool_val = SGRawValue<bool>::DefaultValue; // break; // case INT: // if (_tied) { // delete _value.int_val; // _value.int_val = 0; // } // _local_val.int_val = SGRawValue<int>::DefaultValue; // break; // case LONG: // if (_tied) { // delete _value.long_val; // _value.long_val = 0L; // } // _local_val.long_val = SGRawValue<long>::DefaultValue; // break; // case FLOAT: // if (_tied) { // delete _value.float_val; // _value.float_val = 0; // } // _local_val.float_val = SGRawValue<float>::DefaultValue; // break; // case DOUBLE: // if (_tied) { // delete _value.double_val; // _value.double_val = 0; // } // _local_val.double_val = SGRawValue<double>::DefaultValue; // break; // case STRING: // case UNSPECIFIED: // if (_tied) { // delete _value.string_val; // _value.string_val = 0; // } else { // delete [] _local_val.string_val; // } // _local_val.string_val = 0; // break; // } // _tied = false; // _type = NONE; //} ///** // * Get the value as a string. // */ //const char * //SGPropertyNode::make_string () const //{ // if (!getAttribute(READ)) // return ""; // switch (_type) { // case ALIAS: // return _value.alias->getStringValue(); // case BOOL: // if (get_bool()) // return "true"; // else // return "false"; // case INT: // { // stringstream sstr; // sstr << get_int(); // _buffer = sstr.str(); // return _buffer.c_str(); // } // case LONG: // { // stringstream sstr; // sstr << get_long(); // _buffer = sstr.str(); // return _buffer.c_str(); // } // case FLOAT: // { // stringstream sstr; // sstr << get_float(); // _buffer = sstr.str(); // return _buffer.c_str(); // } // case DOUBLE: // { // stringstream sstr; // sstr.precision( 10 ); // sstr << get_double(); // _buffer = sstr.str(); // return _buffer.c_str(); // } // case STRING: // case UNSPECIFIED: // return get_string(); // case NONE: // default: // return ""; // } //} ///** // * Trace a write access for a property. // */ //void //SGPropertyNode::trace_write () const //{ //#if PROPS_STANDALONE // cerr << "TRACE: Write node " << getPath () << ", value\"" // << make_string() << '"' << endl; //#else // SG_LOG(SG_GENERAL, SG_INFO, "TRACE: Write node " << getPath() // << ", value\"" << make_string() << '"'); //#endif //} ///** // * Trace a read access for a property. // */ //void //SGPropertyNode::trace_read () const //{ //#if PROPS_STANDALONE // cerr << "TRACE: Write node " << getPath () << ", value \"" // << make_string() << '"' << endl; //#else // SG_LOG(SG_GENERAL, SG_INFO, "TRACE: Read node " << getPath() // << ", value \"" << make_string() << '"'); //#endif //} ////////////////////////////////////////////////////////////////////////// //// Public methods from SGPropertyNode. ////////////////////////////////////////////////////////////////////////// ///** // * Last used attribute // * Update as needed when enum Attribute is changed // */ //const int SGPropertyNode::LAST_USED_ATTRIBUTE = TRACE_WRITE; ///** // * Default constructor: always creates a root node. // */ //SGPropertyNode::SGPropertyNode () // : _index(0), // _parent(0), // _path_cache(0), // _type(NONE), // _tied(false), // _attr(READ|WRITE), // _listeners(0) //{ // _local_val.string_val = 0; //} ///** // * Copy constructor. // */ //SGPropertyNode::SGPropertyNode (const SGPropertyNode &node) // : _index(node._index), // _name(node._name), // _parent(0), // don't copy the parent // _path_cache(0), // _type(node._type), // _tied(node._tied), // _attr(node._attr), // _listeners(0) // CHECK!! //{ // _local_val.string_val = 0; // switch (_type) { // case NONE: // break; // case ALIAS: // _value.alias = node._value.alias; // _tied = false; // break; // case BOOL: // if (_tied) { // _tied = true; // _value.bool_val = node._value.bool_val->clone(); // } else { // _tied = false; // set_bool(node.get_bool()); // } // break; // case INT: // if (_tied) { // _tied = true; // _value.int_val = node._value.int_val->clone(); // } else { // _tied = false; // set_int(node.get_int()); // } // break; // case LONG: // if (_tied) { // _tied = true; // _value.long_val = node._value.long_val->clone(); // } else { // _tied = false; // set_long(node.get_long()); // } // break; // case FLOAT: // if (_tied) { // _tied = true; // _value.float_val = node._value.float_val->clone(); // } else { // _tied = false; // set_float(node.get_float()); // } // break; // case DOUBLE: // if (_tied) { // _tied = true; // _value.double_val = node._value.double_val->clone(); // } else { // _tied = false; // set_double(node.get_double()); // } // break; // case STRING: // case UNSPECIFIED: // if (_tied) { // _tied = true; // _value.string_val = node._value.string_val->clone(); // } else { // _tied = false; // set_string(node.get_string()); // } // break; // } //} ///** // * Convenience constructor. // */ //SGPropertyNode::SGPropertyNode (const char * name, // int index, // SGPropertyNode * parent) // : _index(index), // _parent(parent), // _path_cache(0), // _type(NONE), // _tied(false), // _attr(READ|WRITE), // _listeners(0) //{ // _name = name; // _local_val.string_val = 0; //} ///** // * Destructor. // */ //SGPropertyNode::~SGPropertyNode () //{ // delete _path_cache; // clearValue(); // delete _listeners; //} ///** // * Alias to another node. // */ //bool //SGPropertyNode::alias (SGPropertyNode * target) //{ // if (target == 0 || _type == ALIAS || _tied) // return false; // clearValue(); // _value.alias = target; // _type = ALIAS; // return true; //} ///** // * Alias to another node by path. // */ //bool //SGPropertyNode::alias (const char * path) //{ // return alias(getNode(path, true)); //} ///** // * Remove an alias. // */ //bool //SGPropertyNode::unalias () //{ // if (_type != ALIAS) // return false; // _type = NONE; // _value.alias = 0; // return true; //} ///** // * Get the target of an alias. // */ //SGPropertyNode * //SGPropertyNode::getAliasTarget () //{ // return (_type == ALIAS ? _value.alias : 0); //} //const SGPropertyNode * //SGPropertyNode::getAliasTarget () const //{ // return (_type == ALIAS ? _value.alias : 0); //} ///** // * Get a non-const child by index. // */ //SGPropertyNode * //SGPropertyNode::getChild (int position) //{ // if (position >= 0 && position < nChildren()) // return _children[position]; // else // return 0; //} ///** // * Get a const child by index. // */ //const SGPropertyNode * //SGPropertyNode::getChild (int position) const //{ // if (position >= 0 && position < nChildren()) // return _children[position]; // else // return 0; //} ///** // * Get a non-const child by name and index, creating if necessary. // */ //SGPropertyNode * //SGPropertyNode::getChild (const char * name, int index, bool create) //{ // int pos = find_child(name, index, _children); // if (pos >= 0) { // return _children[pos]; // } else if (create) { // SGPropertyNode_ptr node; // pos = find_child(name, index, _removedChildren); // if (pos >= 0) { // vector<SGPropertyNode_ptr>::iterator it = _removedChildren.begin(); // it += pos; // node = _removedChildren[pos]; // _removedChildren.erase(it); // node->setAttribute(REMOVED, false); // } else { // node = new SGPropertyNode(name, index, this); // } // _children.push_back(node); // fireChildAdded(node); // return node; // } else { // return 0; // } //} ///** // * Get a const child by name and index. // */ //const SGPropertyNode * //SGPropertyNode::getChild (const char * name, int index) const //{ // int pos = find_child(name, index, _children); // if (pos >= 0) // return _children[pos]; // else // return 0; //} ///** // * Get all children with the same name (but different indices). // */ //vector<SGPropertyNode_ptr> //SGPropertyNode::getChildren (const char * name) const //{ // vector<SGPropertyNode_ptr> children; // int max = _children.size(); // for (int i = 0; i < max; i++) // if (compare_strings(_children[i]->getName(), name)) // children.push_back(_children[i]); // sort(children.begin(), children.end(), CompareIndices()); // return children; //} ///** // * Remove child by position. // */ //SGPropertyNode_ptr //SGPropertyNode::removeChild (int pos, bool keep) //{ // SGPropertyNode_ptr node; // if (pos < 0 || pos >= (int)_children.size()) // return node; // vector<SGPropertyNode_ptr>::iterator it = _children.begin(); // it += pos; // node = _children[pos]; // _children.erase(it); // if (keep) { // _removedChildren.push_back(node); // } // if (_path_cache) // _path_cache->erase(node->getName()); // EMH - TODO: Take "index" into account! // node->setAttribute(REMOVED, true); // node->clearValue(); // fireChildRemoved(node); // return node; //} ///** // * Remove a child node // */ //SGPropertyNode_ptr //SGPropertyNode::removeChild (const char * name, int index, bool keep) //{ // SGPropertyNode_ptr ret; // int pos = find_child(name, index, _children); // if (pos >= 0) // ret = removeChild(pos, keep); // return ret; //} ///** // * Remove all children with the specified name. // */ //vector<SGPropertyNode_ptr> //SGPropertyNode::removeChildren (const char * name, bool keep) //{ // vector<SGPropertyNode_ptr> children; // for (int pos = _children.size() - 1; pos >= 0; pos--) // if (compare_strings(_children[pos]->getName(), name)) // children.push_back(removeChild(pos, keep)); // sort(children.begin(), children.end(), CompareIndices()); // return children; //} //const char * //SGPropertyNode::getDisplayName (bool simplify) const //{ // _display_name = _name; // if (_index != 0 || !simplify) { // stringstream sstr; // sstr << '[' << _index << ']'; // _display_name += sstr.str(); // } // return _display_name.c_str(); //} //const char * //SGPropertyNode::getPath (bool simplify) const //{ // // Calculate the complete path only once. // if (_parent != 0 && _path.empty()) { // _path = _parent->getPath(simplify); // _path += '/'; // _path += getDisplayName(simplify); // } // return _path.c_str(); //} //SGPropertyNode::Type //SGPropertyNode::getType () const //{ // if (_type == ALIAS) // return _value.alias->getType(); // else // return _type; //} //bool //SGPropertyNode::getBoolValue () const //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == BOOL) // return get_bool(); // if (getAttribute(TRACE_READ)) // trace_read(); // if (!getAttribute(READ)) // return SGRawValue<bool>::DefaultValue; // switch (_type) { // case ALIAS: // return _value.alias->getBoolValue(); // case BOOL: // return get_bool(); // case INT: // return get_int() == 0 ? false : true; // case LONG: // return get_long() == 0L ? false : true; // case FLOAT: // return get_float() == 0.0 ? false : true; // case DOUBLE: // return get_double() == 0.0L ? false : true; // case STRING: // case UNSPECIFIED: // return (compare_strings(get_string(), "true") || getDoubleValue() != 0.0L); // case NONE: // default: // return SGRawValue<bool>::DefaultValue; // } //} //int //SGPropertyNode::getIntValue () const //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == INT) // return get_int(); // if (getAttribute(TRACE_READ)) // trace_read(); // if (!getAttribute(READ)) // return SGRawValue<int>::DefaultValue; // switch (_type) { // case ALIAS: // return _value.alias->getIntValue(); // case BOOL: // return int(get_bool()); // case INT: // return get_int(); // case LONG: // return int(get_long()); // case FLOAT: // return int(get_float()); // case DOUBLE: // return int(get_double()); // case STRING: // case UNSPECIFIED: // return atoi(get_string()); // case NONE: // default: // return SGRawValue<int>::DefaultValue; // } //} //long //SGPropertyNode::getLongValue () const //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == LONG) // return get_long(); // if (getAttribute(TRACE_READ)) // trace_read(); // if (!getAttribute(READ)) // return SGRawValue<long>::DefaultValue; // switch (_type) { // case ALIAS: // return _value.alias->getLongValue(); // case BOOL: // return long(get_bool()); // case INT: // return long(get_int()); // case LONG: // return get_long(); // case FLOAT: // return long(get_float()); // case DOUBLE: // return long(get_double()); // case STRING: // case UNSPECIFIED: // return strtol(get_string(), 0, 0); // case NONE: // default: // return SGRawValue<long>::DefaultValue; // } //} //float //SGPropertyNode::getFloatValue () const //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == FLOAT) // return get_float(); // if (getAttribute(TRACE_READ)) // trace_read(); // if (!getAttribute(READ)) // return SGRawValue<float>::DefaultValue; // switch (_type) { // case ALIAS: // return _value.alias->getFloatValue(); // case BOOL: // return float(get_bool()); // case INT: // return float(get_int()); // case LONG: // return float(get_long()); // case FLOAT: // return get_float(); // case DOUBLE: // return float(get_double()); // case STRING: // case UNSPECIFIED: // return atof(get_string()); // case NONE: // default: // return SGRawValue<float>::DefaultValue; // } //} //double //SGPropertyNode::getDoubleValue () const //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == DOUBLE) // return get_double(); // if (getAttribute(TRACE_READ)) // trace_read(); // if (!getAttribute(READ)) // return SGRawValue<double>::DefaultValue; // switch (_type) { // case ALIAS: // return _value.alias->getDoubleValue(); // case BOOL: // return double(get_bool()); // case INT: // return double(get_int()); // case LONG: // return double(get_long()); // case FLOAT: // return double(get_float()); // case DOUBLE: // return get_double(); // case STRING: // case UNSPECIFIED: // return strtod(get_string(), 0); // case NONE: // default: // return SGRawValue<double>::DefaultValue; // } //} //const char * //SGPropertyNode::getStringValue () const //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == STRING) // return get_string(); // if (getAttribute(TRACE_READ)) // trace_read(); // if (!getAttribute(READ)) // return SGRawValue<const char *>::DefaultValue; // return make_string(); //} //bool //SGPropertyNode::setBoolValue (bool value) //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == BOOL) // return set_bool(value); // bool result = false; // TEST_WRITE; // if (_type == NONE || _type == UNSPECIFIED) { // clearValue(); // _tied = false; // _type = BOOL; // } // switch (_type) { // case ALIAS: // result = _value.alias->setBoolValue(value); // break; // case BOOL: // result = set_bool(value); // break; // case INT: // result = set_int(int(value)); // break; // case LONG: // result = set_long(long(value)); // break; // case FLOAT: // result = set_float(float(value)); // break; // case DOUBLE: // result = set_double(double(value)); // break; // case STRING: // case UNSPECIFIED: // result = set_string(value ? "true" : "false"); // break; // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::setIntValue (int value) //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == INT) // return set_int(value); // bool result = false; // TEST_WRITE; // if (_type == NONE || _type == UNSPECIFIED) { // clearValue(); // _type = INT; // _local_val.int_val = 0; // } // switch (_type) { // case ALIAS: // result = _value.alias->setIntValue(value); // break; // case BOOL: // result = set_bool(value == 0 ? false : true); // break; // case INT: // result = set_int(value); // break; // case LONG: // result = set_long(long(value)); // break; // case FLOAT: // result = set_float(float(value)); // break; // case DOUBLE: // result = set_double(double(value)); // break; // case STRING: // case UNSPECIFIED: { // char buf[128]; // sprintf(buf, "%d", value); // result = set_string(buf); // break; // } // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::setLongValue (long value) //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == LONG) // return set_long(value); // bool result = false; // TEST_WRITE; // if (_type == NONE || _type == UNSPECIFIED) { // clearValue(); // _type = LONG; // _local_val.long_val = 0L; // } // switch (_type) { // case ALIAS: // result = _value.alias->setLongValue(value); // break; // case BOOL: // result = set_bool(value == 0L ? false : true); // break; // case INT: // result = set_int(int(value)); // break; // case LONG: // result = set_long(value); // break; // case FLOAT: // result = set_float(float(value)); // break; // case DOUBLE: // result = set_double(double(value)); // break; // case STRING: // case UNSPECIFIED: { // char buf[128]; // sprintf(buf, "%ld", value); // result = set_string(buf); // break; // } // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::setFloatValue (float value) //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == FLOAT) // return set_float(value); // bool result = false; // TEST_WRITE; // if (_type == NONE || _type == UNSPECIFIED) { // clearValue(); // _type = FLOAT; // _local_val.float_val = 0; // } // switch (_type) { // case ALIAS: // result = _value.alias->setFloatValue(value); // break; // case BOOL: // result = set_bool(value == 0.0 ? false : true); // break; // case INT: // result = set_int(int(value)); // break; // case LONG: // result = set_long(long(value)); // break; // case FLOAT: // result = set_float(value); // break; // case DOUBLE: // result = set_double(double(value)); // break; // case STRING: // case UNSPECIFIED: { // char buf[128]; // sprintf(buf, "%f", value); // result = set_string(buf); // break; // } // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::setDoubleValue (double value) //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == DOUBLE) // return set_double(value); // bool result = false; // TEST_WRITE; // if (_type == NONE || _type == UNSPECIFIED) { // clearValue(); // _local_val.double_val = value; // _type = DOUBLE; // } // switch (_type) { // case ALIAS: // result = _value.alias->setDoubleValue(value); // break; // case BOOL: // result = set_bool(value == 0.0L ? false : true); // break; // case INT: // result = set_int(int(value)); // break; // case LONG: // result = set_long(long(value)); // break; // case FLOAT: // result = set_float(float(value)); // break; // case DOUBLE: // result = set_double(value); // break; // case STRING: // case UNSPECIFIED: { // char buf[128]; // sprintf(buf, "%f", value); // result = set_string(buf); // break; // } // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::setStringValue (const char * value) //{ // // Shortcut for common case // if (_attr == (READ|WRITE) && _type == STRING) // return set_string(value); // bool result = false; // TEST_WRITE; // if (_type == NONE || _type == UNSPECIFIED) { // clearValue(); // _type = STRING; // } // switch (_type) { // case ALIAS: // result = _value.alias->setStringValue(value); // break; // case BOOL: // result = set_bool((compare_strings(value, "true") // || atoi(value)) ? true : false); // break; // case INT: // result = set_int(atoi(value)); // break; // case LONG: // result = set_long(strtol(value, 0, 0)); // break; // case FLOAT: // result = set_float(atof(value)); // break; // case DOUBLE: // result = set_double(strtod(value, 0)); // break; // case STRING: // case UNSPECIFIED: // result = set_string(value); // break; // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::setUnspecifiedValue (const char * value) //{ // bool result = false; // TEST_WRITE; // if (_type == NONE) { // clearValue(); // _type = UNSPECIFIED; // } // switch (_type) { // case ALIAS: // result = _value.alias->setUnspecifiedValue(value); // break; // case BOOL: // result = set_bool((compare_strings(value, "true") // || atoi(value)) ? true : false); // break; // case INT: // result = set_int(atoi(value)); // break; // case LONG: // result = set_long(strtol(value, 0, 0)); // break; // case FLOAT: // result = set_float(atof(value)); // break; // case DOUBLE: // result = set_double(strtod(value, 0)); // break; // case STRING: // case UNSPECIFIED: // result = set_string(value); // break; // case NONE: // default: // break; // } // if (getAttribute(TRACE_WRITE)) // trace_write(); // return result; //} //bool //SGPropertyNode::tie (const SGRawValue<bool> &rawValue, bool useDefault) //{ // if (_type == ALIAS || _tied) // return false; // useDefault = useDefault && hasValue(); // bool old_val = false; // if (useDefault) // old_val = getBoolValue(); // clearValue(); // _type = BOOL; // _tied = true; // _value.bool_val = rawValue.clone(); // if (useDefault) // setBoolValue(old_val); // return true; //} //bool //SGPropertyNode::tie (const SGRawValue<int> &rawValue, bool useDefault) //{ // if (_type == ALIAS || _tied) // return false; // useDefault = useDefault && hasValue(); // int old_val = 0; // if (useDefault) // old_val = getIntValue(); // clearValue(); // _type = INT; // _tied = true; // _value.int_val = rawValue.clone(); // if (useDefault) // setIntValue(old_val); // return true; //} //bool //SGPropertyNode::tie (const SGRawValue<long> &rawValue, bool useDefault) //{ // if (_type == ALIAS || _tied) // return false; // useDefault = useDefault && hasValue(); // long old_val = 0; // if (useDefault) // old_val = getLongValue(); // clearValue(); // _type = LONG; // _tied = true; // _value.long_val = rawValue.clone(); // if (useDefault) // setLongValue(old_val); // return true; //} //bool //SGPropertyNode::tie (const SGRawValue<float> &rawValue, bool useDefault) //{ // if (_type == ALIAS || _tied) // return false; // useDefault = useDefault && hasValue(); // float old_val = 0.0; // if (useDefault) // old_val = getFloatValue(); // clearValue(); // _type = FLOAT; // _tied = true; // _value.float_val = rawValue.clone(); // if (useDefault) // setFloatValue(old_val); // return true; //} //bool //SGPropertyNode::tie (const SGRawValue<double> &rawValue, bool useDefault) //{ // if (_type == ALIAS || _tied) // return false; // useDefault = useDefault && hasValue(); // double old_val = 0.0; // if (useDefault) // old_val = getDoubleValue(); // clearValue(); // _type = DOUBLE; // _tied = true; // _value.double_val = rawValue.clone(); // if (useDefault) // setDoubleValue(old_val); // return true; //} //bool //SGPropertyNode::tie (const SGRawValue<const char *> &rawValue, bool useDefault) //{ // if (_type == ALIAS || _tied) // return false; // useDefault = useDefault && hasValue(); // string old_val; // if (useDefault) // old_val = getStringValue(); // clearValue(); // _type = STRING; // _tied = true; // _value.string_val = rawValue.clone(); // if (useDefault) // setStringValue(old_val.c_str()); // return true; //} //bool //SGPropertyNode::untie () //{ // if (!_tied) // return false; // switch (_type) { // case BOOL: { // bool val = getBoolValue(); // clearValue(); // _type = BOOL; // _local_val.bool_val = val; // break; // } // case INT: { // int val = getIntValue(); // clearValue(); // _type = INT; // _local_val.int_val = val; // break; // } // case LONG: { // long val = getLongValue(); // clearValue(); // _type = LONG; // _local_val.long_val = val; // break; // } // case FLOAT: { // float val = getFloatValue(); // clearValue(); // _type = FLOAT; // _local_val.float_val = val; // break; // } // case DOUBLE: { // double val = getDoubleValue(); // clearValue(); // _type = DOUBLE; // _local_val.double_val = val; // break; // } // case STRING: // case UNSPECIFIED: { // string val = getStringValue(); // clearValue(); // _type = STRING; // _local_val.string_val = copy_string(val.c_str()); // break; // } // case NONE: // default: // break; // } // _tied = false; // return true; //} //SGPropertyNode * //SGPropertyNode::getRootNode () //{ // if (_parent == 0) // return this; // else // return _parent->getRootNode(); //} //const SGPropertyNode * //SGPropertyNode::getRootNode () const //{ // if (_parent == 0) // return this; // else // return _parent->getRootNode(); //} //SGPropertyNode * //SGPropertyNode::getNode (const char * relative_path, bool create) //{ // if (_path_cache == 0) // _path_cache = new hash_table; // SGPropertyNode * result = _path_cache->get(relative_path); // if (result == 0) { // vector<PathComponent> components; // parse_path(relative_path, components); // result = find_node(this, components, 0, create); // if (result != 0) // _path_cache->put(relative_path, result); // } // return result; //} //SGPropertyNode * //SGPropertyNode::getNode (const char * relative_path, int index, bool create) //{ // vector<PathComponent> components; // parse_path(relative_path, components); // if (components.size() > 0) // components.back().index = index; // return find_node(this, components, 0, create); //} //const SGPropertyNode * //SGPropertyNode::getNode (const char * relative_path) const //{ // return ((SGPropertyNode *)this)->getNode(relative_path, false); //} //const SGPropertyNode * //SGPropertyNode::getNode (const char * relative_path, int index) const //{ // return ((SGPropertyNode *)this)->getNode(relative_path, index, false); //} ////////////////////////////////////////////////////////////////////////// //// Convenience methods using relative paths. ////////////////////////////////////////////////////////////////////////// ///** // * Test whether another node has a value attached. // */ //bool //SGPropertyNode::hasValue (const char * relative_path) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? false : node->hasValue()); //} ///** // * Get the value type for another node. // */ //SGPropertyNode::Type //SGPropertyNode::getType (const char * relative_path) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? UNSPECIFIED : (Type)(node->getType())); //} ///** // * Get a bool value for another node. // */ //bool //SGPropertyNode::getBoolValue (const char * relative_path, // bool defaultValue) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? defaultValue : node->getBoolValue()); //} ///** // * Get an int value for another node. // */ //int //SGPropertyNode::getIntValue (const char * relative_path, // int defaultValue) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? defaultValue : node->getIntValue()); //} ///** // * Get a long value for another node. // */ //long //SGPropertyNode::getLongValue (const char * relative_path, // long defaultValue) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? defaultValue : node->getLongValue()); //} ///** // * Get a float value for another node. // */ //float //SGPropertyNode::getFloatValue (const char * relative_path, // float defaultValue) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? defaultValue : node->getFloatValue()); //} ///** // * Get a double value for another node. // */ //double //SGPropertyNode::getDoubleValue (const char * relative_path, // double defaultValue) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? defaultValue : node->getDoubleValue()); //} ///** // * Get a string value for another node. // */ //const char * //SGPropertyNode::getStringValue (const char * relative_path, // const char * defaultValue) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? defaultValue : node->getStringValue()); //} ///** // * Set a bool value for another node. // */ //bool //SGPropertyNode::setBoolValue (const char * relative_path, bool value) //{ // return getNode(relative_path, true)->setBoolValue(value); //} ///** // * Set an int value for another node. // */ //bool //SGPropertyNode::setIntValue (const char * relative_path, int value) //{ // return getNode(relative_path, true)->setIntValue(value); //} ///** // * Set a long value for another node. // */ //bool //SGPropertyNode::setLongValue (const char * relative_path, long value) //{ // return getNode(relative_path, true)->setLongValue(value); //} ///** // * Set a float value for another node. // */ //bool //SGPropertyNode::setFloatValue (const char * relative_path, float value) //{ // return getNode(relative_path, true)->setFloatValue(value); //} ///** // * Set a double value for another node. // */ //bool //SGPropertyNode::setDoubleValue (const char * relative_path, double value) //{ // return getNode(relative_path, true)->setDoubleValue(value); //} ///** // * Set a string value for another node. // */ //bool //SGPropertyNode::setStringValue (const char * relative_path, const char * value) //{ // return getNode(relative_path, true)->setStringValue(value); //} ///** // * Set an unknown value for another node. // */ //bool //SGPropertyNode::setUnspecifiedValue (const char * relative_path, // const char * value) //{ // return getNode(relative_path, true)->setUnspecifiedValue(value); //} ///** // * Test whether another node is tied. // */ //bool //SGPropertyNode::isTied (const char * relative_path) const //{ // const SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? false : node->isTied()); //} ///** // * Tie a node reached by a relative path, creating it if necessary. // */ //bool //SGPropertyNode::tie (const char * relative_path, // const SGRawValue<bool> &rawValue, // bool useDefault) //{ // return getNode(relative_path, true)->tie(rawValue, useDefault); //} ///** // * Tie a node reached by a relative path, creating it if necessary. // */ //bool //SGPropertyNode::tie (const char * relative_path, // const SGRawValue<int> &rawValue, // bool useDefault) //{ // return getNode(relative_path, true)->tie(rawValue, useDefault); //} ///** // * Tie a node reached by a relative path, creating it if necessary. // */ //bool //SGPropertyNode::tie (const char * relative_path, // const SGRawValue<long> &rawValue, // bool useDefault) //{ // return getNode(relative_path, true)->tie(rawValue, useDefault); //} ///** // * Tie a node reached by a relative path, creating it if necessary. // */ //bool //SGPropertyNode::tie (const char * relative_path, // const SGRawValue<float> &rawValue, // bool useDefault) //{ // return getNode(relative_path, true)->tie(rawValue, useDefault); //} ///** // * Tie a node reached by a relative path, creating it if necessary. // */ //bool //SGPropertyNode::tie (const char * relative_path, // const SGRawValue<double> &rawValue, // bool useDefault) //{ // return getNode(relative_path, true)->tie(rawValue, useDefault); //} ///** // * Tie a node reached by a relative path, creating it if necessary. // */ //bool //SGPropertyNode::tie (const char * relative_path, // const SGRawValue<const char *> &rawValue, // bool useDefault) //{ // return getNode(relative_path, true)->tie(rawValue, useDefault); //} ///** // * Attempt to untie another node reached by a relative path. // */ //bool //SGPropertyNode::untie (const char * relative_path) //{ // SGPropertyNode * node = getNode(relative_path); // return (node == 0 ? false : node->untie()); //} //void //SGPropertyNode::addChangeListener (SGPropertyChangeListener * listener, // bool initial) //{ // if (_listeners == 0) // _listeners = new vector<SGPropertyChangeListener*>; // _listeners->push_back(listener); // listener->register_property(this); // if (initial) // listener->valueChanged(this); //} //void //SGPropertyNode::removeChangeListener (SGPropertyChangeListener * listener) //{ // vector<SGPropertyChangeListener*>::iterator it = // find(_listeners->begin(), _listeners->end(), listener); // if (it != _listeners->end()) { // _listeners->erase(it); // listener->unregister_property(this); // if (_listeners->empty()) { // vector<SGPropertyChangeListener*>* tmp = _listeners; // _listeners = 0; // delete tmp; // } // } //} //void //SGPropertyNode::fireValueChanged () //{ // fireValueChanged(this); //} //void //SGPropertyNode::fireChildAdded (SGPropertyNode * child) //{ // fireChildAdded(this, child); //} //void //SGPropertyNode::fireChildRemoved (SGPropertyNode * child) //{ // fireChildRemoved(this, child); //} //void //SGPropertyNode::fireValueChanged (SGPropertyNode * node) //{ // if (_listeners != 0) { // for (unsigned int i = 0; i < _listeners->size(); i++) { // (*_listeners)[i]->valueChanged(node); // } // } // if (_parent != 0) // _parent->fireValueChanged(node); //} //void //SGPropertyNode::fireChildAdded (SGPropertyNode * parent, // SGPropertyNode * child) //{ // if (_listeners != 0) { // for (unsigned int i = 0; i < _listeners->size(); i++) { // (*_listeners)[i]->childAdded(parent, child); // } // } // if (_parent != 0) // _parent->fireChildAdded(parent, child); //} //void //SGPropertyNode::fireChildRemoved (SGPropertyNode * parent, // SGPropertyNode * child) //{ // if (_listeners != 0) { // for (unsigned int i = 0; i < _listeners->size(); i++) { // (*_listeners)[i]->childRemoved(parent, child); // } // } // if (_parent != 0) // _parent->fireChildRemoved(parent, child); //} ////////////////////////////////////////////////////////////////////////// //// Simplified hash table for caching paths. ////////////////////////////////////////////////////////////////////////// //#define HASH_TABLE_SIZE 199 //SGPropertyNode::hash_table::entry::entry () // : _value(0) //{ //} //SGPropertyNode::hash_table::entry::~entry () //{ // // Don't delete the value; we don't own // // the pointer. //} //void //SGPropertyNode::hash_table::entry::set_key (const char * key) //{ // _key = key; //} //void //SGPropertyNode::hash_table::entry::set_value (SGPropertyNode * value) //{ // _value = value; //} //SGPropertyNode::hash_table::bucket::bucket () // : _length(0), // _entries(0) //{ //} //SGPropertyNode::hash_table::bucket::~bucket () //{ // for (int i = 0; i < _length; i++) // delete _entries[i]; // delete [] _entries; //} //SGPropertyNode::hash_table::entry * //SGPropertyNode::hash_table::bucket::get_entry (const char * key, bool create) //{ // int i; // for (i = 0; i < _length; i++) { // if (!strcmp(_entries[i]->get_key(), key)) // return _entries[i]; // } // if (create) { // entry ** new_entries = new entry*[_length+1]; // for (i = 0; i < _length; i++) { // new_entries[i] = _entries[i]; // } // delete [] _entries; // _entries = new_entries; // _entries[_length] = new entry; // _entries[_length]->set_key(key); // _length++; // return _entries[_length - 1]; // } else { // return 0; // } //} //void //SGPropertyNode::hash_table::bucket::erase (const char * key) //{ // int i; // for (i = 0; i < _length; i++) { // if (!strcmp(_entries[i]->get_key(), key)) // break; // } // if (i < _length) { // for (++i; i < _length; i++) { // _entries[i-1] = _entries[i]; // } // _length--; // } //} //SGPropertyNode::hash_table::hash_table () // : _data_length(0), // _data(0) //{ //} //SGPropertyNode::hash_table::~hash_table () //{ // for (unsigned int i = 0; i < _data_length; i++) // delete _data[i]; // delete [] _data; //} //SGPropertyNode * //SGPropertyNode::hash_table::get (const char * key) //{ // if (_data_length == 0) // return 0; // unsigned int index = hashcode(key) % _data_length; // if (_data[index] == 0) // return 0; // entry * e = _data[index]->get_entry(key); // if (e == 0) // return 0; // else // return e->get_value(); //} //void //SGPropertyNode::hash_table::put (const char * key, SGPropertyNode * value) //{ // if (_data_length == 0) { // _data = new bucket*[HASH_TABLE_SIZE]; // _data_length = HASH_TABLE_SIZE; // for (unsigned int i = 0; i < HASH_TABLE_SIZE; i++) // _data[i] = 0; // } // unsigned int index = hashcode(key) % _data_length; // if (_data[index] == 0) { // _data[index] = new bucket; // } // entry * e = _data[index]->get_entry(key, true); // e->set_value(value); //} //void //SGPropertyNode::hash_table::erase (const char * key) //{ // if (_data_length == 0) // return; // unsigned int index = hashcode(key) % _data_length; // if (_data[index] == 0) // return; // _data[index]->erase(key); //} //unsigned int //SGPropertyNode::hash_table::hashcode (const char * key) //{ // unsigned int hash = 0; // while (*key != 0) { // hash = 31 * hash + *key; // key++; // } // return hash; //}
roadbikeaddict/FDM
FDM/InputOutput/SGPropertyNode.cs
C#
gpl-3.0
59,585
#include <cstdio> #include <cmath> #include <climits> #include <iostream> #include <algorithm> #include <assert.h> #include <cstdlib> #include <cstring> #define CLEAR(a) memset((a),0,sizeof(a)) #define FLAG(a) memset((a) , -1 , sizeof(a)) #define varName(x) #x #define deBug(exp) cout<< " == > " << #exp<<" : "<< (exp) << endl using namespace std; typedef double int_t; double const eps = 1e-8; double const PI = acos(-1.0); inline int dcmp(double x){if(x > eps) return 1;return x < -eps ? -1 : 0;} inline double toRad( double angle ){ return (angle/180*PI);} struct point_t{ int_t x,y; point_t( int_t xx=0,int_t yy=0 ): x(xx),y(yy){}; // point_t( point_t const&a ): x(a.x),y(a.y) {}; bool operator == ( point_t const&a )const {return dcmp(a.x-x) == 0 && dcmp(a.y-y) == 0;} bool operator != ( point_t const&a )const {return ! (*this == a ); } bool operator < ( point_t const&a )const {return a.x != x ? x < a.x : y < a.y;} friend ostream &operator<<(ostream &os,const point_t &p){os << "(" << p.x << ","<< p.y << ")" << endl;return os;} }; typedef point_t vector_t; vector_t operator-( vector_t a,vector_t b ) {return point_t( a.x-b.x,a.y-b.y);} vector_t operator*( vector_t a,double t ) { return point_t( a.x*t,a.y*t);} vector_t operator+( vector_t a,vector_t b ) {return point_t( a.x+b.x,a.y+b.y);} struct segment_t{ point_t s,e; segment_t ( point_t aa = point_t(0,0),point_t bb = point_t(0,0) ):s(aa),e(bb) {}; bool operator < ( segment_t const&sg )const{ return s != sg.s ? s < sg.s : e < sg.e; } }; struct line_t{ point_t a,b; double angle; void cal(){angle = atan2(b.y-a.y, b.x-a.x);} line_t ( point_t aa = point_t(0,0),point_t bb = point_t(0,0) ):a(aa),b(bb) {angle = atan2(b.y-a.y, b.x-a.x);} bool operator < ( line_t const&c ) const { return angle < c.angle ;}; }; struct circle_t { point_t p; int_t r; circle_t( point_t pp= point_t(0,0),int_t rr=0): p(pp),r(rr) {}; // circle_t( int_t xx=0,int_t yy=0,int_t rr=0): x(xx),y(yy),r(rr) {}; }; /**< ²æ»ý oa * ob */ inline int_t cross(point_t const &O,point_t const &A,point_t const &B){return (A.x - O.x) * (B.y - O.y) - (B.x - O.x) * (A.y - O.y);} /**< µãµ½µãµÄ¾àÀë */ inline int_t Point2Point(point_t const &a, point_t const &b) {return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));} /**< Ï߶εÄÖеã */ inline point_t SegmentMid(point_t const &a, point_t const &b) {return point_t ( (a.x+b.x)/2.0 , (a.y+b.y)/2.0 );} /**< ÏòÁ¿µÄµã»ý */ double vector_dot ( vector_t const&a,vector_t const&b ){return a.x*b.x + a.y*b.y;} /**< ÏòÁ¿µÄ³¤¶È */ double vector_length( vector_t const&a ){return sqrt(vector_dot(a,a));} /**< ÏòÁ¿µÄ¼Ð½Ç */ double vector_angle( vector_t const&a,vector_t const&b ){return acos(vector_dot(a,b)/vector_length(a)/vector_length(b));} /**< ÏòÁ¿µÄ·¨Ïß ÊäÈëÒª±£Ö¤²»ÊÇÁãÏòÁ¿ */ vector_t vector_normal( vector_t const&a ){ double L = vector_length(a); return vector_t( -a.y/L , a.x/L ); } /**< ÏòÁ¿Ðýת ÏòÁ¿aÄæÊ±ÕëÐýתrad */ vector_t vector_rotate( vector_t const&a, double rad ){return vector_t( a.x*cos(rad)-a.y*sin(rad) , a.x*sin(rad)+a.y*cos(rad) );} /**< µãpµ½Ïß¶Îa,bµÄ¾àÀë */ int_t Point2Segment( point_t const&a,point_t const&b,point_t const&p){ if( a == b ) return Point2Point(a,p); vector_t v1 = b-a , v2 = p-a, v3 = p-b; if ( dcmp( vector_dot(v1,v2) ) < 0 ) return vector_length(v2); else if ( dcmp( vector_dot(v1,v3)) > 0 ) return vector_length(v3); return fabs( cross( a, b, p ) ) / vector_length(v1); } /**< µãµ½Ö±ÏߵľàÀë */ int_t Point2Line( point_t const&p,point_t const&a,point_t const&b){ vector_t v1 = b-a,v2 = p-a; return fabs(cross(point_t(0,0),v1,v2)) / vector_length(v1) ; } /**< µãpoÊÇ·ñÔÚÏß¶ÎabÉÏ */ bool PointOnSegment( point_t const&a,point_t const&b, point_t const&po ){return dcmp( cross(po,a,b) ) == 0 && dcmp( vector_dot(a-po,b-po) ) < 0 ;} /**< µãpoÊÇ·ñÔÚ¼òµ¥¶à±ßÐÎ(͹)ÖÐ ,µãpÐèÒªÏÈgraham ÅÅÐò */ bool PointInSimple( point_t * p ,int n , point_t const&po ){ p[n] = p[0]; bool flag = 0; int tmp; for ( int i = 0; i < n;++i ){ if ( PointOnSegment( p[i] , p[i+1] , po ) ) return true; if ( p[i].y == p[i+1].y ) continue; p[i].y < p[i+1].y ? tmp = i+1 : tmp = i ; if ( po.y == p[tmp].y && po.x < p[tmp].x ) flag ^= 1; p[i].y > p[i+1].y ? tmp = i+1 : tmp = i ; if ( po.y == p[tmp].y && po.x < p[tmp].x ) continue ; if ( po.x < max( p[i].x , p[i+1].x ) && po.y > min( p[i].y , p[i+1].y ) && po.y < max( p[i].y , p[i+1].y ) ) flag ^= 1; } return flag; } /**< µãµ½¼òµ¥¶à±ßÐεľàÀë */ double Point2Simple( point_t * p ,int n , point_t const&po ){ if ( PointInSimple( p,n,po ) ) return 0; double ans = Point2Segment( p[0],p[1] ,po); p[n] = p[0]; for (int i = 1;i < n ;++i) ans = min( ans, Point2Segment( p[i] , p[i+1] ,po) ); return ans; } /**< Ïß¶ÎÏཻ */ inline bool SegmentOnSegment(segment_t const&u,segment_t const&v){ return max(u.s.x,u.e.x) >= min(v.s.x,v.e.x) && max(v.s.x,v.e.x) >= min(u.s.x,u.e.x) && max(u.s.y,u.e.y) >= min(v.s.y,v.e.y) && max(v.s.y,v.e.y) >= min(u.s.y,u.e.y) /**< ¿¼Âǽ»µãÊǶ˵ã */ && cross(v.s,u.e,v.e) * cross(v.s,v.e,u.s) >= 0 && cross(u.s,v.e,u.e) * cross(u.s,u.e,v.s) >= 0; } inline double Segment2Segment(segment_t const&u,segment_t const&v){ return min(min(Point2Segment(u.s,u.e,v.s),Point2Segment(u.s,u.e,v.e)), min(Point2Segment(v.s,v.e,u.s),Point2Segment(v.s,v.e,u.e))); } /**< Ö±ÏßÊÇ·ñÓëÏß¶ÎÏཻ */ /**< ×¢ÒâÏòÁ¿Òª´óÓÚ0 */ inline bool LineOnSegment( point_t const&p,vector_t const&v,segment_t const &s ){ return cross(p,p+v,s.s)*cross(p,s.e,p+v) >= 0; } /**< Ö±ÏßÓëÖ±ÏߵĽ»µã */ point_t lineCrossline( line_t const&l1,line_t const&l2) { point_t p0(0,0); vector_t v = l1.b - l1.a; vector_t w = l2.b - l2.a; double t = cross( l2.a , l2.b , l1.a )/cross( p0,v,w ); return l1.a + v * t; } /**< Èý½ÇÐεÄÃæ»ý ÓÐÏòÃæ»ý */ double TriangleArea( point_t const&a,point_t const&b, point_t const&c){return 0.5 * cross(a,b,c);} /**< ¼ÆËã¶à±ßÐÎÃæ»ý ,µãpÐèÒªÏÈgraham ÅÅÐò*/ double PolygonArea(point_t p[], int n) { double area = 0; for (int i = 0 ;i < n-1;++i ) area += cross(p[0] , p[i] , p[i+1] ); return area / 2.0; } /**< ¶à±ßÐεÄÖܳ¤ */ int_t PolygonSideLength(point_t p[], int n){ double length = 0; for (int i = 0 ;i < n-1;++i ) length += Point2Point(p[i],p[i+1]); return length + Point2Point(p[n-1],p[0]); } /**< AÈç¹û±ÈB¸ü¿¿Ï¸ü¿¿×ó·µ»ØÕæ */ inline bool isLowLeft(point_t const&A,point_t const&B){return A.y < B.y || ( A.y == B.y && A.x < B.x );} /**< °´ÕÕ¶ÔÓÚpOµÄ¼«½ÇÅÅÐò£¬¼«½ÇÏàµÈµÄ¾àÀëÔ¶µÄÅÅÔÚÇ°Ãæ£¬ÒòΪºóÃæÒª×öÒ»¸öunique */ point_t* pO; inline bool comp4Graham(point_t const&A,point_t const&B){ int_t t = cross(*pO,A,B); if ( t ) return t > 0LL; int_t a1 = A.x > pO->x ? A.x - pO->x : pO->x - A.x; int_t a2 = B.x > pO->x ? B.x - pO->x : pO->x - B.x; if ( a1 != a2 ) return a1 > a2; // if ( a1 != a2 ) return a1 < a2; //°ÑÕâ¸ö±ä³É½üµÄ·ÅÇ°Ãæ ( ²»Ñϸñ͹°ü ) a1 = A.y > pO->y ? A.y - pO->y : pO->y - A.y; a2 = B.y > pO->y ? B.y - pO->y : pO->y - B.y; return a1 > a2; } /**< Ïà¶ÔÓÚpOÊÇ·ñ¼«½ÇÏàµÈ */ inline bool isEqPolar(point_t const&A,point_t const&B){return 0LL == cross(*pO,A,B);} /** \brief * ĬÈÏÊÇÑϸñ͹°ü¶à±ßÐεÄÅÅÐò * Ñϸñ͹°üÊÇÔÚ¼«½ÇÅÅÐòµÄʱºòÌáǰ×öÁË´¦Àí£¬ËùÒÔÎÒÃÇÖ»Òª°Ñ´¦ÀíÈ¡·´¼´¿É£¬ * ´úÂëÉÏÖ»Òª°Ñ¼«½ÇÏàµÈµÄʱºò¸Ä³É½üµÄ·ÅÇ°Ãæ£¬È¥µôuniqueº¯Êý <= ¸Ä³É < ¡£ */ /**< GrahamÇó͹°ü£¬½á¹ûµ±ÖÐûÓй²Ïߵ㣬Æðµã×ÜÊÇ×îÏÂ×î×óµã */ int Graham(point_t P[],int n){ if ( 1 == n ) return 1; //ѰÕÒ×îÏÂ×î×óµã point_t *p = min_element(P,P+n,isLowLeft); //½»»» swap(*p,P[0]); if ( 2 == n ) return 2; //°´¼«½ÇÅÅÐò£¬¼«½ÇÏàµÈ£¬¾àÀë½üµÄÅÅÔÚÇ°Ãæ pO = P; sort(P+1,P+n,comp4Graham); //½«Ïà¶ÔÓÚpOµÄ¹²Ïßµã¾ùÌÞ³ý£¬Ö»±£Áô×îºóÒ»¸ö ( Ñϸñ͹°ü ) p = unique(P+1,P+n,isEqPolar); n = p - P; //ÕæÕýµÄGrahamÑ­»· int top = 2; for(int i=2;i<n;++i){ /**< ²»Ñϸñ Õâ¸ö<= Òª¸Ä³É < */ while( top > 1 && cross(P[top-2],P[top-1],P[i]) <= 0LL ) --top; P[top++] = P[i]; } return top; } /**< Ô²ÓëÖ±ÏßµÄÇÐÏß ,·µ»ØÏòÁ¿µÄÊýÁ¿ */ int LineTangentCircle(point_t const&p , circle_t const&c, vector_t *v){ vector_t u = c.p - p; double dist = vector_length(u); if ( dist < c.r )return 0; else if ( dcmp(dist-c.r) == 0 ){ v[0] = vector_rotate(u,PI/2); return 1; }else { double ang = asin(c.r/dist); v[0] = vector_rotate(u,-ang); v[1] = vector_rotate(u,+ang); return 2; } } /**< CircleIntersectArea Á½¸öÔ²µÄÃæ»ý²¢ */ double CIA(circle_t const&a, circle_t const&b) { double d = Point2Point( a.p,b.p ); if (d >= a.r + b.r) return 0; if (d <= fabs(a.r - b.r)) { int_t r = a.r < b.r ? a.r : b.r; return PI * r * r; } double ang1 = acos((a.r * a.r + d * d - b.r * b.r) / 2. / a.r / d); double ang2 = acos((b.r * b.r + d * d - a.r * a.r) / 2. / b.r / d); return ang1 * a.r * a.r + ang2 * b.r * b.r - d * a.r * sin(ang1); } /**< ÓÐÏòÃæ»ý½»,ÓÐÕý¸º */ /**< ConvexPolygonIntersectArea */ int_t CPIA(point_t a[], point_t b[], int na, int nb) { point_t p[20], tmp[20]; int tn, sflag, eflag; a[na] = a[0], b[nb] = b[0]; memcpy(p,b,sizeof(point_t)*(nb + 1)); for(int i = 0; i < na && nb > 2; i++){ sflag = dcmp(cross(a[i],a[i + 1], p[0])); for(int j = tn = 0; j < nb; j++, sflag = eflag){ if(sflag>=0) tmp[tn++] = p[j]; eflag = dcmp(cross(a[i],a[i + 1], p[j + 1])); if((sflag ^ eflag) == -2) tmp[tn++] = lineCrossline( line_t( a[i], a[i + 1]),line_t(p[j], p[j + 1]) ); ///Çó½»µã } memcpy(p, tmp, sizeof(point_t) * tn); nb = tn, p[nb] = p[0]; } if(nb < 3) return 0.0; return PolygonArea(p, nb); } /**< ÓÐÏòÃæ»ý½»,ÓÐÕý¸º */ /**< SimplePolygonIntersectArea µ÷Óô˺¯Êý */ int_t SPIA(point_t a[], point_t b[], int na, int nb) { int i, j; point_t t1[4], t2[4]; int_t res = 0, num1, num2; a[na] = t1[0] = a[0], b[nb] = t2[0] = b[0]; for(i = 2; i < na; i++) { t1[1] = a[i-1], t1[2] = a[i]; num1 = dcmp(cross(t1[0],t1[1], t1[2])); if(num1 < 0) swap(t1[1], t1[2]); for(j = 2; j < nb; j++) { t2[1] = b[j - 1], t2[2] = b[j]; num2 = dcmp(cross(t2[0],t2[1], t2[2])); if(num2 < 0) swap(t2[1], t2[2]); res += CPIA(t1, t2, 3, 3) * num1 * num2; } } return res; } /**< Ðýת¿¨¿Ç·¨Çó͹°üµÄ×µã¶Ô ¼´Í¹°üµÄÖ±¾¶*/ double Rotating_calipers( point_t *p ,int n ){ int q = 1; double ans = 0; p[n] = p[0]; point_t p1,p2; for (int i = 0 ;i < n;++i ){ while ( fabs(TriangleArea(p[i],p[i+1],p[q+1])) > fabs(TriangleArea(p[i],p[i+1],p[q] )) ) q = (q+1) % n; // deBug(p[i]);deBug(p[q]); // deBug(p[i+1]);deBug(p[q+1]); ans = max( ans ,max( Point2Point(p[i],p[q]), Point2Point(p[i+1],p[q+1]) ) ); } return ans; } /**< Ðýת¿¨¿Ç·¨Çó͹°üÖÐ×î´óÈý½ÇÐÎ ×¢ÒâÍøÉϺܶ඼ÊÇ´íµÄ,Õâ¸öËäÈ»ÂýÁ˵ã,µ«ÊǸú±©Á¦µÃµ½µÄ´ð°¸ÆðÂëÊÇÒ»ÑùµÄ */ double max_TriangleArea( point_t *p,int n ){ double ans = 0; p[n] = p[0]; for (int i = 0; i < n; i ++) { int k = 2; for (int j = i + 1; j <= n; j ++) { while(TriangleArea(p[i], p[j], p[k]) < TriangleArea(p[i], p[j], p[(k + 1) % n])) k = (k + 1) % n; ans = max(ans,TriangleArea(p[i], p[j], p[k])); } } return ans; } /**< Á½¸ö͹°üµÄ×î½ü¾àÀë */ void _getTOP_DOWN( point_t *p1 ,int n1,int &l, point_t *p2,int n2,int &r ){ l=r=0; for( int i=0;i<n1;i++ ) if((dcmp(p1[i].y-p1[l].y))<0) l = i; for( int i=0;i<n2;i++ ) if((dcmp(p2[i].y-p2[r].y))>0) r = i; } double _docp( point_t *p1 ,int n1,int l, point_t *p2,int n2,int r ){ double ans = 1e90; int tmp; p1[n1] = p1[0]; p2[n2] = p2[0]; // auto f = [](const double&x)->int{ return dcmp(x); }; for ( int i = 0;i < n1;++i ){ if ( dcmp(ans) == 0 ) return 0; // while ( tmp = dcmp( fabs( TriangleArea(p1[l],p1[l+1],p2[r+1]) ) - fabs( TriangleArea(p1[l],p1[l+1],p2[r]) ) ) < 0 ) // r = (r+1) % n2; while ( 1 ){ double s1 = TriangleArea(p1[l],p1[l+1],p2[r+1]); double s2 = TriangleArea(p1[l],p1[l+1],p2[r]) ; // if ( f(s1) * f(s2) < 0 ) ans = 0; if ( SegmentOnSegment( segment_t(p1[l],p1[l+1]),segment_t(p2[r],p2[r+1]) ) ) ans = 0; s1 = fabs(s1); s2 = fabs(s2); tmp = dcmp( s1-s2); if ( tmp < 0 ) r = (r+1)%n2; else break; } if ( tmp == 0 ) ans = min( ans ,Segment2Segment( segment_t( p1[l],p1[l+1] ) , segment_t(p2[r],p2[r+1]) ) ); else ans = min( ans ,Point2Segment( p1[l],p1[l+1],p2[r])); l = (l+1)%n1; } return ans; } /**< distence of Convex polygon*/ /**< Ðýת¿¨¿Ç·¨ ¼ÆËã Á½¸ö͹°üµÄ×î½ü¾àÀë ,ÕâÀïÅжÏÁËËÄ´Î, ×¢Òâ°üº¬µÄÇé¿ö,´Ë´¦°üº¬²»Ëã0 */ double DOCP( point_t *p1 ,int n1, point_t *p2,int n2 ){ int l,r; _getTOP_DOWN( p1,n1,l,p2,n2,r ); double ans = INT_MAX; ans = min( ans , _docp(p1,n1,l,p2,n2,r)); // deBug(ans); ans = min(ans , _docp(p2,n2,r,p1,n1,l)) ; // deBug(ans); _getTOP_DOWN( p2,n2,r,p1,n1,l ); ans = min( ans , _docp(p2,n2,r,p1,n1,l)) ; // deBug(ans); ans = min( ans , _docp(p1,n1,l,p2,n2,r)); // deBug(ans); return ans; } /**< Á½µã¼ÆËã Ö±ÏßÒ»°ãʽ·½³Ì */ void LineEquation(point_t const&a,point_t const&b ,int_t&A,int_t&B,int_t&C ){ assert( !(a==b) ); // assert( !(a.x==b.x)); A = b.y - a.y; B = a.x - b.x; C = b.x*a.y - a.x*b.y; } const int _SIZE = 30000; point_t _p[_SIZE]; line_t _q[_SIZE]; //auto OnLeft = [](line_t const&L,point_t const&p )->bool{ return cross( L.a, L.b, p ) > 0; }; inline bool OnLeft(line_t const&L,point_t const&p ){ return cross( L.a, L.b, p ) > 0; }; /**< °ëÆ½Ãæ½», ×¢ÒâlineÒª³õʼ»¯angle, _sizeµÄ´óС*4 */ /**< lµÄ·½Ïò Ö±Ïßa->b µÄ×ó±ßΪ°ëÆ½ÃæÇøÓò Êä³öÄæÐò,grahamÐò */ int HalfplaneIntersection( line_t * l , int n ,point_t *poly ){ sort( l,l+n ); int first = 0,last = 0; _q[first] = l[0]; for ( int i = 1;i < n;++i ){ while ( first < last && !OnLeft(l[i],_p[last-1])) last--; while ( first < last && !OnLeft(l[i],_p[first] )) first++; _q[++last] = l[i]; if ( fabs(cross( point_t(0,0) ,(_q[last].b-_q[last].a) ,(_q[last-1].b-_q[last-1].a) )) < eps ){ last--; if ( OnLeft( _q[last],l[i].a ) ) _q[last] = l[i]; } if ( first < last ) _p[last-1] = lineCrossline( _q[last-1] , _q[last] ); } while ( first < last && !OnLeft( _q[first] , _p[last-1]) ) last--; if ( last-first <= 1 ) return 0; _p[last] = lineCrossline(_q[last],_q[first]); int m = 0; for (int i = first ;i <= last ;++i ) poly[m++] = _p[i]; return m; } /**< Èý½ÇÐÎÍâ½ÓÔ² */ circle_t CircumscribedCircle(point_t p1, point_t p2, point_t p3) { double Bx = p2.x - p1.x, By = p2.y - p1.y; double Cx = p3.x - p1.x, Cy = p3.y - p1.y; double D = 2 * (Bx*Cy - By*Cx); double cx = (Cy*(Bx*Bx + By*By) - By*(Cx*Cx + Cy*Cy)) / D + p1.x; double cy = (Bx*(Cx*Cx + Cy*Cy) - Cx*(Bx*Bx + By*By)) / D + p1.y; point_t _p = point_t(cx, cy); return circle_t(_p, Point2Point(p1,_p)); } //Èý½ÇÐÎÍâ½ÓÔ² /** Ïß¶ÎÉϵÄÕûÊýµã * Á½¸ö¶Ëµã×ø±ê²îµÄ¾ø¶ÔÖµµÄ gcd + 1 */ /** pick ¹«Ê½ * Ãæ»ý = ±ß½çµãÊý ¡Â 2 £« ÄÚ²¿µãÊý £­ 1 */ /// - - - - - - - - - - - - - - - - - - Code line - - - - - - - - - - - - - - - - - - - - - - - /// //int father[SIZE]; //void init( int n ){for (int i = 0 ;i <= n;++i) father[i] = i;} //int find( int x ){return father[x] == x ? x : father[x] = find( father[x] );} //void unite( int x,int y){father[ find(x) ] = find(y);} // int gcd( int a,int b ){ return b == 0 ? a : gcd( b,a%b); } const int SIZE = 55000; point_t p[SIZE],p1[SIZE]; line_t l[SIZE]; int n; point_t A, B, C; void print(double num) { if (dcmp(num) < 0) { printf("- "); num = -num; } else printf("+ "); printf("%.3f", num); } //Êä³ö int isin[SIZE]; segment_t sg[SIZE]; int main() { int m ,x1,x2,y1,y2; int t = 0; while(scanf("%d",&n)!=EOF &&n) { if (t++ != 0)printf("\n"); scanf("%d%d%d%d%d",&m,&x1,&y1,&x2,&y2); // memset(isin,0,sizeof(bool)*(m+5)); double u,v; sg[0] = segment_t( point_t(x1,y1),point_t(x1,y2)); for (int i = 1 ; i <= n ; ++i ){ scanf("%lf%lf",&u,&v); sg[i] = segment_t( point_t(u,y1) , point_t(v,y2) ); } CLEAR(isin); sg[n+1] = segment_t( point_t(x2,y1),point_t(x2,y2) ); for (int i = 0;i < m ;++i ){ scanf("%lf%lf",&p[i].x,&p[i].y); } // deBug( cross(p[0],sg[1].e,sg[2].s ) ); for (int i = 0;i < m;++i ){ for (int j = 0;j <= n;++j ){ if ( cross(p[i],sg[j].s,sg[j].e ) >= 0 && cross(p[i],sg[j].e,sg[j+1].e ) >= 0 && cross(p[i],sg[j+1].e,sg[j+1].s ) >= 0 && cross(p[i],sg[j+1].s,sg[j].s ) >= 0 ){ isin[j]++; break; } } } for (int i = 0;i <= n;++ i ){ printf("%d: %d\n",i,isin[i]); } } } /* ios.sync_with_stdio(false); /// ÄÇôcin, ¾Í²»ÄܸúCµÄ scanf£¬sscanf, getchar, fgetsÖ®ÀàµÄÒ»ÆðʹÓÃÁË¡£ freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); */
bitwater1997/ACM
poj/poj2318/main.cpp
C++
gpl-3.0
17,780
# Copyright (c) 2008 testtools developers. See LICENSE for details. """Test results and related things.""" __metaclass__ = type __all__ = [ 'ExtendedToOriginalDecorator', 'MultiTestResult', 'TestResult', 'ThreadsafeForwardingResult', ] import datetime import sys import unittest from testtools.compat import all, _format_exc_info, str_is_unicode, _u # From http://docs.python.org/library/datetime.html _ZERO = datetime.timedelta(0) # A UTC class. class UTC(datetime.tzinfo): """UTC""" def utcoffset(self, dt): return _ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return _ZERO utc = UTC() class TestResult(unittest.TestResult): """Subclass of unittest.TestResult extending the protocol for flexability. This test result supports an experimental protocol for providing additional data to in test outcomes. All the outcome methods take an optional dict 'details'. If supplied any other detail parameters like 'err' or 'reason' should not be provided. The details dict is a mapping from names to MIME content objects (see testtools.content). This permits attaching tracebacks, log files, or even large objects like databases that were part of the test fixture. Until this API is accepted into upstream Python it is considered experimental: it may be replaced at any point by a newer version more in line with upstream Python. Compatibility would be aimed for in this case, but may not be possible. :ivar skip_reasons: A dict of skip-reasons -> list of tests. See addSkip. """ def __init__(self): # startTestRun resets all attributes, and older clients don't know to # call startTestRun, so it is called once here. # Because subclasses may reasonably not expect this, we call the # specific version we want to run. TestResult.startTestRun(self) def addExpectedFailure(self, test, err=None, details=None): """Called when a test has failed in an expected manner. Like with addSuccess and addError, testStopped should still be called. :param test: The test that has been skipped. :param err: The exc_info of the error that was raised. :return: None """ # This is the python 2.7 implementation self.expectedFailures.append( (test, self._err_details_to_string(test, err, details))) def addError(self, test, err=None, details=None): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). :param details: Alternative way to supply details about the outcome. see the class docstring for more information. """ self.errors.append((test, self._err_details_to_string(test, err, details))) def addFailure(self, test, err=None, details=None): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). :param details: Alternative way to supply details about the outcome. see the class docstring for more information. """ self.failures.append((test, self._err_details_to_string(test, err, details))) def addSkip(self, test, reason=None, details=None): """Called when a test has been skipped rather than running. Like with addSuccess and addError, testStopped should still be called. This must be called by the TestCase. 'addError' and 'addFailure' will not call addSkip, since they have no assumptions about the kind of errors that a test can raise. :param test: The test that has been skipped. :param reason: The reason for the test being skipped. For instance, u"pyGL is not available". :param details: Alternative way to supply details about the outcome. see the class docstring for more information. :return: None """ if reason is None: reason = details.get('reason') if reason is None: reason = 'No reason given' else: reason = ''.join(reason.iter_text()) skip_list = self.skip_reasons.setdefault(reason, []) skip_list.append(test) def addSuccess(self, test, details=None): """Called when a test succeeded.""" def addUnexpectedSuccess(self, test, details=None): """Called when a test was expected to fail, but succeed.""" self.unexpectedSuccesses.append(test) def wasSuccessful(self): """Has this result been successful so far? If there have been any errors, failures or unexpected successes, return False. Otherwise, return True. Note: This differs from standard unittest in that we consider unexpected successes to be equivalent to failures, rather than successes. """ return not (self.errors or self.failures or self.unexpectedSuccesses) if str_is_unicode: # Python 3 and IronPython strings are unicode, use parent class method _exc_info_to_unicode = unittest.TestResult._exc_info_to_string else: # For Python 2, need to decode components of traceback according to # their source, so can't use traceback.format_exception # Here follows a little deep magic to copy the existing method and # replace the formatter with one that returns unicode instead from types import FunctionType as __F, ModuleType as __M __f = unittest.TestResult._exc_info_to_string.im_func __g = dict(__f.func_globals) __m = __M("__fake_traceback") __m.format_exception = _format_exc_info __g["traceback"] = __m _exc_info_to_unicode = __F(__f.func_code, __g, "_exc_info_to_unicode") del __F, __M, __f, __g, __m def _err_details_to_string(self, test, err=None, details=None): """Convert an error in exc_info form or a contents dict to a string.""" if err is not None: return self._exc_info_to_unicode(err, test) return _details_to_str(details, special='traceback') def _now(self): """Return the current 'test time'. If the time() method has not been called, this is equivalent to datetime.now(), otherwise its the last supplied datestamp given to the time() method. """ if self.__now is None: return datetime.datetime.now(utc) else: return self.__now def startTestRun(self): """Called before a test run starts. New in Python 2.7. The testtools version resets the result to a pristine condition ready for use in another test run. Note that this is different from Python 2.7's startTestRun, which does nothing. """ super(TestResult, self).__init__() self.skip_reasons = {} self.__now = None # -- Start: As per python 2.7 -- self.expectedFailures = [] self.unexpectedSuccesses = [] # -- End: As per python 2.7 -- def stopTestRun(self): """Called after a test run completes New in python 2.7 """ def time(self, a_datetime): """Provide a timestamp to represent the current time. This is useful when test activity is time delayed, or happening concurrently and getting the system time between API calls will not accurately represent the duration of tests (or the whole run). Calling time() sets the datetime used by the TestResult object. Time is permitted to go backwards when using this call. :param a_datetime: A datetime.datetime object with TZ information or None to reset the TestResult to gathering time from the system. """ self.__now = a_datetime def done(self): """Called when the test runner is done. deprecated in favour of stopTestRun. """ class MultiTestResult(TestResult): """A test result that dispatches to many test results.""" def __init__(self, *results): TestResult.__init__(self) self._results = list(map(ExtendedToOriginalDecorator, results)) def __repr__(self): return '<%s (%s)>' % ( self.__class__.__name__, ', '.join(map(repr, self._results))) def _dispatch(self, message, *args, **kwargs): return tuple( getattr(result, message)(*args, **kwargs) for result in self._results) def startTest(self, test): return self._dispatch('startTest', test) def stopTest(self, test): return self._dispatch('stopTest', test) def addError(self, test, error=None, details=None): return self._dispatch('addError', test, error, details=details) def addExpectedFailure(self, test, err=None, details=None): return self._dispatch( 'addExpectedFailure', test, err, details=details) def addFailure(self, test, err=None, details=None): return self._dispatch('addFailure', test, err, details=details) def addSkip(self, test, reason=None, details=None): return self._dispatch('addSkip', test, reason, details=details) def addSuccess(self, test, details=None): return self._dispatch('addSuccess', test, details=details) def addUnexpectedSuccess(self, test, details=None): return self._dispatch('addUnexpectedSuccess', test, details=details) def startTestRun(self): return self._dispatch('startTestRun') def stopTestRun(self): return self._dispatch('stopTestRun') def time(self, a_datetime): return self._dispatch('time', a_datetime) def done(self): return self._dispatch('done') def wasSuccessful(self): """Was this result successful? Only returns True if every constituent result was successful. """ return all(self._dispatch('wasSuccessful')) class TextTestResult(TestResult): """A TestResult which outputs activity to a text stream.""" def __init__(self, stream): """Construct a TextTestResult writing to stream.""" super(TextTestResult, self).__init__() self.stream = stream self.sep1 = '=' * 70 + '\n' self.sep2 = '-' * 70 + '\n' def _delta_to_float(self, a_timedelta): return (a_timedelta.days * 86400.0 + a_timedelta.seconds + a_timedelta.microseconds / 1000000.0) def _show_list(self, label, error_list): for test, output in error_list: self.stream.write(self.sep1) self.stream.write("%s: %s\n" % (label, test.id())) self.stream.write(self.sep2) self.stream.write(output) def startTestRun(self): super(TextTestResult, self).startTestRun() self.__start = self._now() self.stream.write("Tests running...\n") def stopTestRun(self): if self.testsRun != 1: plural = 's' else: plural = '' stop = self._now() self._show_list('ERROR', self.errors) self._show_list('FAIL', self.failures) for test in self.unexpectedSuccesses: self.stream.write( "%sUNEXPECTED SUCCESS: %s\n%s" % ( self.sep1, test.id(), self.sep2)) self.stream.write("\nRan %d test%s in %.3fs\n" % (self.testsRun, plural, self._delta_to_float(stop - self.__start))) if self.wasSuccessful(): self.stream.write("OK\n") else: self.stream.write("FAILED (") details = [] details.append("failures=%d" % ( sum(map(len, ( self.failures, self.errors, self.unexpectedSuccesses))))) self.stream.write(", ".join(details)) self.stream.write(")\n") super(TextTestResult, self).stopTestRun() class ThreadsafeForwardingResult(TestResult): """A TestResult which ensures the target does not receive mixed up calls. This is used when receiving test results from multiple sources, and batches up all the activity for a single test into a thread-safe batch where all other ThreadsafeForwardingResult objects sharing the same semaphore will be locked out. Typical use of ThreadsafeForwardingResult involves creating one ThreadsafeForwardingResult per thread in a ConcurrentTestSuite. These forward to the TestResult that the ConcurrentTestSuite run method was called with. target.done() is called once for each ThreadsafeForwardingResult that forwards to the same target. If the target's done() takes special action, care should be taken to accommodate this. """ def __init__(self, target, semaphore): """Create a ThreadsafeForwardingResult forwarding to target. :param target: A TestResult. :param semaphore: A threading.Semaphore with limit 1. """ TestResult.__init__(self) self.result = ExtendedToOriginalDecorator(target) self.semaphore = semaphore def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self.result) def _add_result_with_semaphore(self, method, test, *args, **kwargs): self.semaphore.acquire() try: self.result.time(self._test_start) self.result.startTest(test) self.result.time(self._now()) try: method(test, *args, **kwargs) finally: self.result.stopTest(test) finally: self.semaphore.release() def addError(self, test, err=None, details=None): self._add_result_with_semaphore(self.result.addError, test, err, details=details) def addExpectedFailure(self, test, err=None, details=None): self._add_result_with_semaphore(self.result.addExpectedFailure, test, err, details=details) def addFailure(self, test, err=None, details=None): self._add_result_with_semaphore(self.result.addFailure, test, err, details=details) def addSkip(self, test, reason=None, details=None): self._add_result_with_semaphore(self.result.addSkip, test, reason, details=details) def addSuccess(self, test, details=None): self._add_result_with_semaphore(self.result.addSuccess, test, details=details) def addUnexpectedSuccess(self, test, details=None): self._add_result_with_semaphore(self.result.addUnexpectedSuccess, test, details=details) def startTestRun(self): self.semaphore.acquire() try: self.result.startTestRun() finally: self.semaphore.release() def stopTestRun(self): self.semaphore.acquire() try: self.result.stopTestRun() finally: self.semaphore.release() def done(self): self.semaphore.acquire() try: self.result.done() finally: self.semaphore.release() def startTest(self, test): self._test_start = self._now() super(ThreadsafeForwardingResult, self).startTest(test) def wasSuccessful(self): return self.result.wasSuccessful() class ExtendedToOriginalDecorator(object): """Permit new TestResult API code to degrade gracefully with old results. This decorates an existing TestResult and converts missing outcomes such as addSkip to older outcomes such as addSuccess. It also supports the extended details protocol. In all cases the most recent protocol is attempted first, and fallbacks only occur when the decorated result does not support the newer style of calling. """ def __init__(self, decorated): self.decorated = decorated def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self.decorated) def __getattr__(self, name): return getattr(self.decorated, name) def addError(self, test, err=None, details=None): self._check_args(err, details) if details is not None: try: return self.decorated.addError(test, details=details) except TypeError: # have to convert err = self._details_to_exc_info(details) return self.decorated.addError(test, err) def addExpectedFailure(self, test, err=None, details=None): self._check_args(err, details) addExpectedFailure = getattr( self.decorated, 'addExpectedFailure', None) if addExpectedFailure is None: return self.addSuccess(test) if details is not None: try: return addExpectedFailure(test, details=details) except TypeError: # have to convert err = self._details_to_exc_info(details) return addExpectedFailure(test, err) def addFailure(self, test, err=None, details=None): self._check_args(err, details) if details is not None: try: return self.decorated.addFailure(test, details=details) except TypeError: # have to convert err = self._details_to_exc_info(details) return self.decorated.addFailure(test, err) def addSkip(self, test, reason=None, details=None): self._check_args(reason, details) addSkip = getattr(self.decorated, 'addSkip', None) if addSkip is None: return self.decorated.addSuccess(test) if details is not None: try: return addSkip(test, details=details) except TypeError: # extract the reason if it's available try: reason = ''.join(details['reason'].iter_text()) except KeyError: reason = _details_to_str(details) return addSkip(test, reason) def addUnexpectedSuccess(self, test, details=None): outcome = getattr(self.decorated, 'addUnexpectedSuccess', None) if outcome is None: try: test.fail("") except test.failureException: return self.addFailure(test, sys.exc_info()) if details is not None: try: return outcome(test, details=details) except TypeError: pass return outcome(test) def addSuccess(self, test, details=None): if details is not None: try: return self.decorated.addSuccess(test, details=details) except TypeError: pass return self.decorated.addSuccess(test) def _check_args(self, err, details): param_count = 0 if err is not None: param_count += 1 if details is not None: param_count += 1 if param_count != 1: raise ValueError("Must pass only one of err '%s' and details '%s" % (err, details)) def _details_to_exc_info(self, details): """Convert a details dict to an exc_info tuple.""" return ( _StringException, _StringException(_details_to_str(details, special='traceback')), None) def done(self): try: return self.decorated.done() except AttributeError: return def progress(self, offset, whence): method = getattr(self.decorated, 'progress', None) if method is None: return return method(offset, whence) @property def shouldStop(self): return self.decorated.shouldStop def startTest(self, test): return self.decorated.startTest(test) def startTestRun(self): try: return self.decorated.startTestRun() except AttributeError: return def stop(self): return self.decorated.stop() def stopTest(self, test): return self.decorated.stopTest(test) def stopTestRun(self): try: return self.decorated.stopTestRun() except AttributeError: return def tags(self, new_tags, gone_tags): method = getattr(self.decorated, 'tags', None) if method is None: return return method(new_tags, gone_tags) def time(self, a_datetime): method = getattr(self.decorated, 'time', None) if method is None: return return method(a_datetime) def wasSuccessful(self): return self.decorated.wasSuccessful() class _StringException(Exception): """An exception made from an arbitrary string.""" if not str_is_unicode: def __init__(self, string): if type(string) is not unicode: raise TypeError("_StringException expects unicode, got %r" % (string,)) Exception.__init__(self, string) def __str__(self): return self.args[0].encode("utf-8") def __unicode__(self): return self.args[0] # For 3.0 and above the default __str__ is fine, so we don't define one. def __hash__(self): return id(self) def __eq__(self, other): try: return self.args == other.args except AttributeError: return False def _format_text_attachment(name, text): if '\n' in text: return "%s: {{{\n%s\n}}}\n" % (name, text) return "%s: {{{%s}}}" % (name, text) def _details_to_str(details, special=None): """Convert a details dict to a string. :param details: A dictionary mapping short names to ``Content`` objects. :param special: If specified, an attachment that should have special attention drawn to it. The primary attachment. Normally it's the traceback that caused the test to fail. :return: A formatted string that can be included in text test results. """ empty_attachments = [] binary_attachments = [] text_attachments = [] special_content = None # sorted is for testing, may want to remove that and use a dict # subclass with defined order for items instead. for key, content in sorted(details.items()): if content.content_type.type != 'text': binary_attachments.append((key, content.content_type)) continue text = _u('').join(content.iter_text()).strip() if not text: empty_attachments.append(key) continue # We want the 'special' attachment to be at the bottom. if key == special: special_content = '%s\n' % (text,) continue text_attachments.append(_format_text_attachment(key, text)) if text_attachments and not text_attachments[-1].endswith('\n'): text_attachments.append('') if special_content: text_attachments.append(special_content) lines = [] if binary_attachments: lines.append('Binary content:\n') for name, content_type in binary_attachments: lines.append(' %s (%s)\n' % (name, content_type)) if empty_attachments: lines.append('Empty attachments:\n') for name in empty_attachments: lines.append(' %s\n' % (name,)) if (binary_attachments or empty_attachments) and text_attachments: lines.append('\n') lines.append('\n'.join(text_attachments)) return _u('').join(lines)
lauria/Samba4
lib/testtools/testtools/testresult/real.py
Python
gpl-3.0
23,481
<?php /** * @link https://github.com/old-town/workflow-zf2 * @author Malofeykin Andrey <and-rey2@yandex.ru> */ namespace OldTown\Workflow\ZF2\Options\Exception; /** * Class InvalidManagerNameException * * @package OldTown\Workflow\ZF2\Options\Exception */ class InvalidManagerNameException extends InvalidArgumentException { }
old-town/workflow-zf2
src/Options/Exception/InvalidManagerNameException.php
PHP
gpl-3.0
338
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.web.wicket.flowlayout; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.projectforge.web.wicket.WicketUtils; /** * Represents a simple text panel enclosed in a div element. * @author Kai Reinhard (k.reinhard@micromata.de) * */ public class DivTextPanel extends Panel { private static final long serialVersionUID = 4900467057369413432L; public static final String WICKET_ID = "text"; private final Label label; private final WebMarkupContainer div; public DivTextPanel(final String id, final String text, final Behavior... behaviors) { super(id); add(div = new WebMarkupContainer("div")); label = new Label(WICKET_ID, text); init(behaviors); } public DivTextPanel(final String id, final IModel<String> text, final Behavior... behaviors) { super(id); add(div = new WebMarkupContainer("div")); label = new Label(WICKET_ID, text); init(behaviors); } public DivTextPanel(final String id, final Label label) { super(id); add(div = new WebMarkupContainer("div")); this.label = label; div.add(label); } /** * Calls setRenderBodyOnly(false) and setOutputMarkupId(true) for the enclosed label. * @return the label */ public Label getLabel4Ajax() { label.setRenderBodyOnly(false).setOutputMarkupId(true); return label; } /** * @return the label */ public Label getLabel() { return label; } /** * @return the div */ public WebMarkupContainer getDiv() { return div; } /** * @see org.apache.wicket.Component#setMarkupId(java.lang.String) */ @Override public DivTextPanel setMarkupId(final String markupId) { label.setOutputMarkupId(true); label.setMarkupId(markupId); return this; } /** * @see WicketUtils#setStrong(org.apache.wicket.markup.html.form.FormComponent) * @return this for chaining. */ public DivTextPanel setStrong() { WicketUtils.setStrong(label); return this; } private void init(final Behavior... behaviors) { label.add(behaviors); div.add(label); } }
developerleo/ProjectForge-2nd
src/main/java/org/projectforge/web/wicket/flowlayout/DivTextPanel.java
Java
gpl-3.0
3,261
/* * C++ Primer * Chap. 6 Ex. 6.25 * Hao Zhang * 2016.09.02 * main.cpp */ #include <iostream> using std::cout; using std::cerr; using std::endl; #include <string> using std::string; int main(int argc, char *argv[]) { if (argc != 3) { cerr << "Wrong # of arguments" << endl; return -1; } string s1 = argv[1]; string s2 = argv[2]; string cat = s1 + " " + s2; cout << cat << endl; return 0; }
HaoMood/cpp-primer
ch06/ex6.25/main.cpp
C++
gpl-3.0
444
package arcadeflex.libc; import WIP.arcadeflex.libc_v2.UBytePtr; /** * * @author shadow */ public class cstring { /** * Get string length * * @param str * @return */ public static int strlen(String str) { return str.length(); } /** * memset * * @param dst * @param value * @param size */ public static void memset(char[] dst, int value, int size) { for (int mem = 0; mem < size; mem++) { dst[mem] = (char) value; } } public static void memset(int[] dst, int value, int size) { for (int mem = 0; mem < size; mem++) { dst[mem] = value; } } public static void memset(UBytePtr ptr, int value, int length) { for (int i = 0; i < length; i++) { ptr.write(i, value); } } /** * memcpy */ public static void memcpy(UBytePtr dst, int dstoffs, UBytePtr src, int srcoffs, int size) { for (int i = 0; i < Math.min(size, src.memory.length); i++) { dst.write(i + dstoffs, src.read(i + srcoffs)); } } public static void memcpy(UBytePtr dst, int dstoffs, UBytePtr src, int size) { for (int i = 0; i < Math.min(size, src.memory.length); i++) { dst.write(i + dstoffs, src.read(i)); } } public static void memcpy(UBytePtr dst, UBytePtr src, int srcoffs, int size) { for (int i = 0; i < Math.min(size, src.memory.length); i++) { dst.write(i, src.read(i + srcoffs)); } } public static void memcpy(UBytePtr dst, UBytePtr src, int size) { for (int i = 0; i < Math.min(size, src.memory.length); i++) { dst.write(i, src.read(i)); } } }
georgemoralis/arcadeflex037b7
emulator_complete/src/arcadeflex/libc/cstring.java
Java
gpl-3.0
1,767
#include <stack> #include <iostream> #include <string> #include <deque> #include <string.h> #ifdef MACOSX #include <strings.h> #endif #include <stdlib.h> #include "TPTScriptInterface.h" #include "gui/game/GameModel.h" #include "simulation/Air.h" TPTScriptInterface::TPTScriptInterface(GameController * c, GameModel * m): CommandInterface(c, m) { } int TPTScriptInterface::Command(std::string command) { lastError = ""; std::deque<std::string> words; std::deque<AnyType> commandWords; int retCode; //Split command into words, put them on the stack char * rawCommand; rawCommand = (char*)calloc(command.length()+1, 1); memcpy(rawCommand, (char*)command.c_str(), command.length()); char * currentWord = rawCommand; char * currentCommand = rawCommand; while((currentCommand = strchr(currentCommand, ' '))) { currentCommand[0] = 0; words.push_back(std::string(currentWord)); currentWord = ++currentCommand; } words.push_back(std::string(currentWord)); while(!words.empty()) { try { commandWords.push_back(eval(&words)); } catch (GeneralException & e) { retCode = -1; lastError = e.GetExceptionMessage(); break; } } free(rawCommand); if(commandWords.size()) { retCode = 0; lastError = ((StringType)commandWords.front()).Value(); } //Evaluate return retCode; } ValueType TPTScriptInterface::testType(std::string word) { size_t i = 0; char * rawWord = (char *)word.c_str(); //Function if (word == "set") return TypeFunction; else if (word == "create") return TypeFunction; else if (word == "delete") return TypeFunction; else if (word == "kill") return TypeFunction; else if (word == "load") return TypeFunction; else if (word == "reset") return TypeFunction; else if (word == "bubble") return TypeFunction; else if (word == "quit") return TypeFunction; //Basic type for (i = 0; i < word.length(); i++) { if (!(rawWord[i] >= '0' && rawWord[i] <= '9') && !(rawWord[i] == '-' && !i)) { if (rawWord[i] == '.' && rawWord[i+1]) goto parseFloat; else if (rawWord[i] == ',' && rawWord[i+1] >= '0' && rawWord[i+1] <= '9') goto parsePoint; else if ((rawWord[i] == '#' || (i && rawWord[i-1] == '0' && rawWord[i] == 'x')) && ((rawWord[i+1] >= '0' && rawWord[i+1] <= '9') || (rawWord[i+1] >= 'a' && rawWord[i+1] <= 'f') || (rawWord[i+1] >= 'A' && rawWord[i+1] <= 'F'))) goto parseNumberHex; else goto parseString; } } return TypeNumber; parseFloat: for (i++; i < word.length(); i++) if (!((rawWord[i] >= '0' && rawWord[i] <= '9') || (rawWord[i] >= 'a' && rawWord[i] <= 'f') || (rawWord[i] >= 'A' && rawWord[i] <= 'F'))) { goto parseString; } return TypeFloat; parseNumberHex: for (i++; i < word.length(); i++) if (!((rawWord[i] >= '0' && rawWord[i] <= '9') || (rawWord[i] >= 'a' && rawWord[i] <= 'f') || (rawWord[i] >= 'A' && rawWord[i] <= 'F'))) { goto parseString; } return TypeNumber; parsePoint: for (i++; i < word.length(); i++) if (!(rawWord[i] >= '0' && rawWord[i] <= '9')) { goto parseString; } return TypePoint; parseString: return TypeString; } int TPTScriptInterface::parseNumber(char * stringData) { char cc; int base = 10; int currentNumber = 0; if (stringData[0] == '#') { stringData++; base = 16; } else if (stringData[0] == '0' && stringData[1] == 'x') { stringData+=2; base = 16; } if (base == 16) { while ((cc = *(stringData++))) { currentNumber *= base; if (cc >= '0' && cc <= '9') currentNumber += cc - '0'; else if (cc >= 'a' && cc <= 'f') currentNumber += (cc - 'a') + 10; else if (cc >= 'A' && cc <= 'F') currentNumber += (cc - 'A') + 10; else break; } } else { return atoi(stringData); } return currentNumber; } AnyType TPTScriptInterface::eval(std::deque<std::string> * words) { if(words->size() < 1) return AnyType(TypeNull, ValueValue()); std::string word = words->front(); words->pop_front(); char * rawWord = (char *)word.c_str(); ValueType wordType = testType(word); switch(wordType) { case TypeFunction: if(word == "set") return tptS_set(words); else if(word == "create") return tptS_create(words); else if(word == "delete" || word == "kill") return tptS_delete(words); else if(word == "load") return tptS_load(words); else if(word == "reset") return tptS_reset(words); else if(word == "bubble") return tptS_bubble(words); else if(word == "quit") return tptS_quit(words); break; case TypeNumber: return NumberType(parseNumber(rawWord)); case TypeFloat: return FloatType(atof(rawWord)); case TypePoint: { int pointX, pointY; sscanf(rawWord, "%d,%d", &pointX, &pointY); return PointType(pointX, pointY); } case TypeString: return StringType(word); default: break; } return StringType(word); } std::string TPTScriptInterface::FormatCommand(std::string command) { std::deque<std::string> words; std::deque<AnyType> commandWords; std::string outputData; //Split command into words, put them on the stack char * rawCommand; rawCommand = (char*)calloc(command.length()+1, 1); memcpy(rawCommand, (char*)command.c_str(), command.length()); char * currentWord = rawCommand; char * currentCommand = rawCommand; while((currentCommand = strchr(currentCommand, ' '))) { currentCommand[0] = 0; words.push_back(std::string(currentWord)); currentWord = ++currentCommand; } words.push_back(std::string(currentWord)); free(rawCommand); while(!words.empty()) { ValueType cType = testType(words.front()); switch(cType) { case TypeFunction: outputData += "\bt"; break; case TypeNumber: case TypePoint: outputData += "\bo"; break; case TypeString: outputData += "\bg"; break; default: outputData += "\bw"; break; } outputData += words.front() + " "; words.pop_front(); } return outputData; } AnyType TPTScriptInterface::tptS_set(std::deque<std::string> * words) { //Arguments from stack StringType property = eval(words); AnyType selector = eval(words); AnyType value = eval(words); Simulation * sim = m->GetSimulation(); unsigned char * partsBlock = (unsigned char*)&sim->parts[0]; int returnValue = 0; FormatType propertyFormat; int propertyOffset = GetPropertyOffset(property.Value(), propertyFormat); if (propertyOffset == -1) throw GeneralException("Invalid property"); //Selector int newValue; float newValuef; if (value.GetType() == TypeNumber) { newValuef = newValue = ((NumberType)value).Value(); } else if (value.GetType() == TypeFloat) { newValue = newValuef = ((FloatType)value).Value(); } else if(value.GetType() == TypeString) { if (property.Value() == "temp") { std::string newString = ((StringType)value).Value(); if (newString.at(newString.length()-1) == 'C') newValuef = atof(newString.substr(0, newString.length()-1).c_str())+273.15; else if (newString.at(newString.length()-1) == 'F') newValuef = (atof(newString.substr(0, newString.length()-1).c_str())-32.0f)*5/9+273.15f; else throw GeneralException("Invalid value for assignment"); } else { newValue = GetParticleType(((StringType)value).Value()); if (newValue < 0 || newValue >= PT_NUM) { // TODO: add element CAKE to invalidate this if (!strcasecmp(((StringType)value).Value().c_str(),"cake")) throw GeneralException("Cake is a lie, not an element"); throw GeneralException("Invalid element"); } } } else throw GeneralException("Invalid value for assignment"); if (property.Value() == "type" && (newValue < 0 || newValue >= PT_NUM || !sim->elements[newValue].Enabled)) throw GeneralException("Invalid element"); if (selector.GetType() == TypePoint || selector.GetType() == TypeNumber) { int partIndex = -1; if(selector.GetType() == TypePoint) { ui::Point tempPoint = ((PointType)selector).Value(); if(tempPoint.X<0 || tempPoint.Y<0 || tempPoint.Y >= YRES || tempPoint.X >= XRES) throw GeneralException("Invalid position"); } else partIndex = ((NumberType)selector).Value(); if(partIndex<0 || partIndex>NPART || sim->parts[partIndex].type==0) throw GeneralException("Invalid particle"); switch(propertyFormat) { case FormatInt: *((int*)(partsBlock+(partIndex*sizeof(Particle))+propertyOffset)) = newValue; break; case FormatFloat: *((float*)(partsBlock+(partIndex*sizeof(Particle))+propertyOffset)) = newValuef; break; case FormatElement: sim->part_change_type(partIndex, sim->parts[partIndex].x, sim->parts[partIndex].y, newValue); break; default: break; } returnValue = 1; } else if (selector.GetType() == TypeString && ((StringType)selector).Value() == "all") { switch(propertyFormat) { case FormatInt: { for(int j = 0; j < NPART; j++) if(sim->parts[j].type) { returnValue++; *((int*)(partsBlock+(j*sizeof(Particle))+propertyOffset)) = newValue; } } break; case FormatFloat: { for(int j = 0; j < NPART; j++) if(sim->parts[j].type) { returnValue++; *((float*)(partsBlock+(j*sizeof(Particle))+propertyOffset)) = newValuef; } } break; case FormatElement: { for (int j = 0; j < NPART; j++) if (sim->parts[j].type) { returnValue++; sim->part_change_type(j, sim->parts[j].x, sim->parts[j].y, newValue); } } break; default: break; } } else if(selector.GetType() == TypeString || selector.GetType() == TypeNumber) { int type; if (selector.GetType() == TypeNumber) type = ((NumberType)selector).Value(); else if (selector.GetType() == TypeString) type = GetParticleType(((StringType)selector).Value()); if (type<0 || type>=PT_NUM) throw GeneralException("Invalid particle type"); if (type==0) throw GeneralException("Cannot set properties of particles that do not exist"); std::cout << propertyOffset << std::endl; switch(propertyFormat) { case FormatInt: { for (int j = 0; j < NPART; j++) if (sim->parts[j].type == type) { returnValue++; *((int*)(partsBlock+(j*sizeof(Particle))+propertyOffset)) = newValue; } } break; case FormatFloat: { for (int j = 0; j < NPART; j++) if (sim->parts[j].type == type) { returnValue++; *((float*)(partsBlock+(j*sizeof(Particle))+propertyOffset)) = newValuef; } } break; case FormatElement: { for (int j = 0; j < NPART; j++) if (sim->parts[j].type == type) { returnValue++; sim->part_change_type(j, sim->parts[j].x, sim->parts[j].y, newValue); } } break; default: break; } } else throw GeneralException("Invalid selector"); return NumberType(returnValue); } AnyType TPTScriptInterface::tptS_create(std::deque<std::string> * words) { //Arguments from stack AnyType createType = eval(words); PointType position = eval(words); Simulation * sim = m->GetSimulation(); int type; if(createType.GetType() == TypeNumber) type = ((NumberType)createType).Value(); else if(createType.GetType() == TypeString) type = GetParticleType(((StringType)createType).Value()); else throw GeneralException("Invalid type"); if(type == -1) throw GeneralException("Invalid particle type"); ui::Point tempPoint = position.Value(); if(tempPoint.X<0 || tempPoint.Y<0 || tempPoint.Y >= YRES || tempPoint.X >= XRES) throw GeneralException("Invalid position"); int returnValue = sim->create_part(-1, tempPoint.X, tempPoint.Y, type); return NumberType(returnValue); } AnyType TPTScriptInterface::tptS_delete(std::deque<std::string> * words) { //Arguments from stack AnyType partRef = eval(words); Simulation * sim = m->GetSimulation(); if(partRef.GetType() == TypePoint) { ui::Point deletePoint = ((PointType)partRef).Value(); if(deletePoint.X<0 || deletePoint.Y<0 || deletePoint.Y >= YRES || deletePoint.X >= XRES) throw GeneralException("Invalid position"); sim->delete_part(deletePoint.X, deletePoint.Y); } else if(partRef.GetType() == TypeNumber) { int partIndex = ((NumberType)partRef).Value(); if(partIndex < 0 || partIndex >= NPART) throw GeneralException("Invalid particle index"); sim->kill_part(partIndex); } else throw GeneralException("Invalid particle reference"); return NumberType(0); } AnyType TPTScriptInterface::tptS_load(std::deque<std::string> * words) { //Arguments from stack NumberType saveID = eval(words); if (saveID.Value() > 0) { c->OpenSavePreview(saveID.Value(), 0, false); return NumberType(0); } else throw GeneralException("Invalid save ID"); } AnyType TPTScriptInterface::tptS_bubble(std::deque<std::string> * words) { //Arguments from stack PointType bubblePosA = eval(words); ui::Point bubblePos = bubblePosA.Value(); if(bubblePos.X<0 || bubblePos.Y<0 || bubblePos.Y >= YRES || bubblePos.X >= XRES) throw GeneralException("Invalid position"); Simulation * sim = m->GetSimulation(); int first, rem1, rem2; first = sim->create_part(-1, bubblePos.X+18, bubblePos.Y, PT_SOAP); rem1 = first; for (int i = 1; i<=30; i++) { rem2 = sim->create_part(-1, bubblePos.X+18*cosf(i/5.0), bubblePos.Y+18*sinf(i/5.0), PT_SOAP); sim->parts[rem1].ctype = 7; sim->parts[rem1].tmp = rem2; sim->parts[rem2].tmp2 = rem1; rem1 = rem2; } sim->parts[rem1].ctype = 7; sim->parts[rem1].tmp = first; sim->parts[first].tmp2 = rem1; sim->parts[first].ctype = 7; return NumberType(0); } AnyType TPTScriptInterface::tptS_reset(std::deque<std::string> * words) { //Arguments from stack StringType reset = eval(words); std::string resetStr = reset.Value(); Simulation * sim = m->GetSimulation(); if (resetStr == "pressure") { for (int nx = 0; nx < XRES/CELL; nx++) for (int ny = 0; ny < YRES/CELL; ny++) { sim->air->pv[ny][nx] = 0; } } else if (resetStr == "velocity") { for (int nx = 0; nx < XRES/CELL; nx++) for (int ny = 0; ny < YRES/CELL; ny++) { sim->air->vx[ny][nx] = 0; sim->air->vy[ny][nx] = 0; } } else if (resetStr == "sparks") { c->ResetSpark(); } else if (resetStr == "temp") { for (int i = 0; i < NPART; i++) { if (sim->parts[i].type) { sim->parts[i].temp = sim->elements[sim->parts[i].type].Temperature; } } } else { throw GeneralException("Unknown reset command"); } return NumberType(0); } AnyType TPTScriptInterface::tptS_quit(std::deque<std::string> * words) { ui::Engine::Ref().Exit(); return NumberType(0); } TPTScriptInterface::~TPTScriptInterface() { }
PraeluceantBoreus/The-Powder-Toy
src/lua/TPTScriptInterface.cpp
C++
gpl-3.0
14,581
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; using Kontract.Interface; namespace Kontract { public static class Tools { public static string LoadFilters(IEnumerable<IFilePlugin> plugins) { var alltypes = plugins.Select(x => new { x.Description, Extension = x.Extension.ToLower() }).OrderBy(o => o.Description).ToList(); // Add two special cases at start and end if (alltypes.Count > 0) alltypes.Insert(0, new { Description = "All Supported Files", Extension = string.Join(";", alltypes.Select(x => x.Extension).Distinct()) }); alltypes.Add(new { Description = "All Files", Extension = "*.*" }); return string.Join("|", alltypes.Select(x => $"{x.Description} ({x.Extension})|{x.Extension}")); } public static List<IGameHandler> LoadGameHandlers(string pluginPath, ToolStripDropDownButton tsb, System.Drawing.Image noGameIcon, EventHandler selectedIndexChanged) { tsb.DropDownItems.Clear(); var gameHandlers = new List<IGameHandler> { new DefaultGameHandler(noGameIcon) }; var gameHandlerPlugins = PluginLoader<IGameHandler>.LoadPlugins(pluginPath, "game*.dll").ToList(); gameHandlerPlugins.Sort((lhs, rhs) => string.Compare(lhs.Name, rhs.Name, StringComparison.Ordinal)); gameHandlers.AddRange(gameHandlerPlugins); foreach (var gameHandler in gameHandlers) { var tsiGameHandler = new ToolStripMenuItem(gameHandler.Name, gameHandler.Icon, selectedIndexChanged) {Tag = gameHandler}; tsb.DropDownItems.Add(tsiGameHandler); } return gameHandlers; } public static void LoadSupportedEncodings(ComboBox cmb, Encoding encoding) { List<ListItem> items = new List<ListItem>(); foreach (EncodingInfo enc in Encoding.GetEncodings()) { string name = enc.GetEncoding().EncodingName; if (name.Contains("ASCII") || name.Contains("Shift-JIS") || (name.Contains("Unicode") && !name.Contains("32"))) items.Add(new ListItem(name.Replace("US-", ""), enc.GetEncoding())); } items.Sort(); cmb.DisplayMember = "Text"; cmb.ValueMember = "Value"; cmb.DataSource = items; cmb.SelectedValue = encoding; } public static TreeNode FindNodeByTextEntry(this TreeView tre, TextEntry entry) { TreeNode result = null; foreach (TreeNode node in tre.Nodes) { if (node.Tag == entry) result = node; if (result == null) foreach (TreeNode subNode in node.Nodes) if (subNode.Tag == entry) { result = subNode; break; } if (result != null) break; } return result; } public static void SelectNodeByTextEntry(this TreeView tre, TextEntry entry) { TreeNode result = null; foreach (TreeNode node in tre.Nodes) { if (node.Tag == entry) result = node; if (result == null) foreach (TreeNode subNode in node.Nodes) if (subNode.Tag == entry) { result = subNode; break; } if (result != null) break; } tre.SelectedNode = result; } public static void SelectNodeByNodeName(this TreeView tre, string name) { TreeNode result = null; foreach (TreeNode node in tre.Nodes) { if (node.Text == name) result = node; if (result == null) foreach (TreeNode subNode in node.Nodes) if (subNode.Text == name) { result = subNode; break; } if (result != null) break; } tre.SelectedNode = result; } public static void DoubleBuffer(Control ctrl, bool doubleBuffered) { ctrl.GetType().GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ctrl, doubleBuffered, null); } } }
IcySon55/Kuriimu
src/Kontract/Tools.cs
C#
gpl-3.0
4,789
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KitBoxAPP { public partial class OrderStep8 : Form { private DBManager mgr; public OrderStep8(DBManager mgr) { this.mgr = mgr; InitializeComponent(); button_home8.BackColor = System.Drawing.Color.DarkRed; button_yes8.BackColor = System.Drawing.Color.Green; button_no8.BackColor = System.Drawing.Color.Red; } private void label_step81_Click(object sender, EventArgs e) { OrderStep1 optionForm = new OrderStep1(this.mgr); this.Hide(); optionForm.Show(); } private void label_step82_Click(object sender, EventArgs e) { OrderStep2 optionForm = new OrderStep2(this.mgr); this.Hide(); optionForm.Show(); } private void label_step83_Click(object sender, EventArgs e) { OrderStep3 optionForm = new OrderStep3(this.mgr); this.Hide(); optionForm.Show(); } private void label_step84_Click(object sender, EventArgs e) { OrderStep4 optionForm = new OrderStep4(this.mgr); this.Hide(); optionForm.Show(); } private void label_step85_Click(object sender, EventArgs e) { OrderStep5 optionForm = new OrderStep5(this.mgr); this.Hide(); optionForm.Show(); } private void label_step86_Click(object sender, EventArgs e) { OrderStep6 optionForm = new OrderStep6(this.mgr); this.Hide(); optionForm.Show(); } private void label_step87_Click(object sender, EventArgs e) { OrderStep7 optionForm = new OrderStep7(this.mgr); this.Hide(); optionForm.Show(); } private void button_home8_Click(object sender, EventArgs e) { Home_client optionForm = new Home_client(this.mgr); this.Hide(); optionForm.Show(); } } }
jbarreravega/KitboxAppECAM
KitBoxAPP/KitBoxAPP/OrderStep8.cs
C#
gpl-3.0
2,285
class SeguridadController < ApplicationController include AccesoHelpers def index session[:roles] = "root" acceso end end
wilxsv/acrasame-zp
app/controllers/seguridad_controller.rb
Ruby
gpl-3.0
139
package de.gnox.rovy.server; import java.util.concurrent.TimeUnit; public class RovyUtility { public static void sleep(long millis) { try { TimeUnit.MILLISECONDS.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
petlutz/rovy
rovy_server/src/de/gnox/rovy/server/RovyUtility.java
Java
gpl-3.0
258
using UnityEngine; using System.Collections; //TODO: Doc and change inputController to be an inputCalibratorController which takes // care of all calibration (not game) stuff so this class only focus on transition and refresh view. public class CalibrationController : MonoBehaviour { public PlayerController playerController; public LevelController levelController; private float smoothTime=20.0f; private float yVelocity=0.0f; private float xVelocity=0.0f; private CalibrationState state=CalibrationState.WAITING; private InputController_I inputController; private float volume; private static float volumeMaxCalibrated; private float thresholdFactor=0.5f; private float maxVolume=Breathing.SupposedPatientMaxVolume; public Animator characterAnimator; public Bar calibrationBar; // Use this for initialization void Start () { //inputController = new FlapiInputController (exercice, GetComponent<AudioSource>()); inputController = new KeyboardSimpleInputController (10.0f); } // Update is called once per frame void Update () { inputController.Update (); DetectStateChanging (); UpdateState (); } private void DetectStateChanging(){ switch (state) { case CalibrationState.WAITING: if (inputController.GetInputState()==BreathingState.EXPIRATION){ state=CalibrationState.CHARGING; characterAnimator.SetBool("isExpiring", true); Update(); } break; case CalibrationState.CHARGING: if(inputController.GetInputState()!=BreathingState.EXPIRATION){ characterAnimator.SetBool("isExpiring", false); if (volume>=thresholdFactor*maxVolume){ characterAnimator.SetBool("isThresholdReached", true); state=CalibrationState.TO_GAME_ANIMATION; volumeMaxCalibrated=volume; inputController.SetCalibrationFactor(CalibrationController.StrengthCalibrationFactor); levelController.BuildAndStart(); calibrationBar.gameObject.SetActive(false); } else{ state=CalibrationState.FAIL_ANIMATION; characterAnimator.SetBool("isThresholdReached", false); } volume=0.0f; } break; case CalibrationState.TO_GAME_ANIMATION: if (characterAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.name.Equals("Player_Swim")){ levelController.GameState=GameState.GAME; levelController.VolumeMaxCalibrated=volumeMaxCalibrated; this.enabled=false; } break; case CalibrationState.FAIL_ANIMATION: if(characterAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.name.Equals("Player_Calibration_Idle")){ state=CalibrationState.WAITING; volume=0.0f; calibrationBar.Update(volume); } break; } } private void UpdateState(){ switch (state) { case CalibrationState.WAITING: break; case CalibrationState.CHARGING: volume+=inputController.GetStrength()*Time.deltaTime*Breathing.StrengthToVolumeFactor; calibrationBar.Update(volume/maxVolume); break; } } public void Move(GameObject objectToMove, Vector3 destination, ref Vector3 velocity, float smoothTime){ float vX = velocity.x; float vY = velocity.y; float vZ = velocity.z; float x = Mathf.SmoothDamp (objectToMove.transform.position.x, destination.x, ref vX, smoothTime * Time.deltaTime); float y = Mathf.SmoothDamp (objectToMove.transform.position.y, destination.y, ref vY, smoothTime * Time.deltaTime); float z = Mathf.SmoothDamp (objectToMove.transform.position.z, destination.z, ref vZ, smoothTime * Time.deltaTime); objectToMove.transform.position = new Vector3 (x, y, z); velocity = new Vector3 (vX, vY, vZ); } public static float VolumeMaxCalibrated{ get{ return volumeMaxCalibrated;} } public static float StrengthCalibrationFactor{ get{return Breathing.SupposedPatientMaxVolume/volumeMaxCalibrated;} } }
nicolaswenk/cf_heritage
Assets/Scripts/Controller/CalibrationController.cs
C#
gpl-3.0
3,788
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <!-- $Id: htmlquickstart.kmdr 768844 2008-01-30 19:21:23Z amantia $ --> <head> <title>{{ page_title }}</title> <meta name="GENERATOR" content="Quanta Plus" /> <meta name="AUTHOR" content="Tomáš Pecina" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="cs" /> <style type="text/css"> /* <![CDATA[ */ body, h1, h2 { color: #303030; background-color: #fbfbfb; font-family: Verdana, "DejaVu Sans", sans-serif; } body { margin: 0; font-size: 15px; } h1, h2 { text-align: center; } table { border-collapse: collapse; } td { padding: 1px 3px; } h1 { font-size: 21px; font-weight: bold; margin-top: 24px; } h2 { font-size: 17px; font-weight: normal; } table.big * { font-size: 13px; } table.inline * { font-size: 15px; } table.inline td { padding-right: 0; } tr.header, tr.footer, tr.topline { background-color: #202020; } tr.header { color: #ffffff } a { color: #808080; font-weight: bold; text-decoration: none; } tr.footer a, span.pager { color: #ffffff; } span.pager { font-weight: normal; } a:hover, tr.footer a:hover { color: #ff4000; } .grayed { color: #808080; } tr.even { background-color: #f4f4f4; } tr.odd { background-color: #ffffff; } tr.even td, tr.odd td, th, tr.footer td { padding: 3px 13px; } #detail td, #detail th { padding: 3px 10px; } .topline * { font-size: 12px; } .res { font-style: italic; text-align: center; font-size: 15px; margin-bottom: 15px; } p.foot { font-size: 11px; text-align: center; } label.err, span.err { color: #e00000; } label.err { font-weight: bold; } input.err, textarea.err { background: #ffecec; } .ok { } {{ css }} /* ]]> */ </style> </head> <body> <table style="width: 90%; margin: auto;"> <tr><td> {% block page_contents %}{% endblock %} </td></tr> </table> {% include 'notice.html' %} </body> </html>
tompecina/petition
petition/templates/main.html
HTML
gpl-3.0
2,146
import abc import subprocess import logging from observables import BLOperator, MCObservable from data import BLDataChannel, GIDataChannel import util class Channel(metaclass=abc.ABCMeta): ISOSPIN_MAP = { 'singlet': "0", 'doublet': "1h", 'triplet': "1", 'quartet': "3h", 'quintet': "2", 'sextet': "5h" } def __init__(self, *, particle_type=None, isospin, strangeness=None, laph_query="laph_query", sigmond_query="sigmond_query"): self.particle_type = particle_type self.strangeness = strangeness self.isospin = isospin self.laph_query = laph_query self.sigmond_query = sigmond_query # @ADH - I think I am going to have the DataHandler deal with these in the future self.raw_data_channels = list() @staticmethod def initialize(*, data_file, laph_query="laph_query", sigmond_query="sigmond_query", is_basic_laph=True): if is_basic_laph: query_result = subprocess.check_output([laph_query, '-i', data_file]).decode() laph_xml = util.queryToXML(query_result) operator = BLOperator.createFromXML(laph_xml.find(".//Operator")) if 'special' in data_file.split('/'): return SpecialChannel(particle_type=operator.particle_type, isospin=operator.isospin, strangeness=operator.strangeness, flavor=operator.flavor, laph_query=laph_query, sigmond_query=sigmond_query) elif operator.psq > 0: return MovingChannel(particle_type=operator.particle_type, isospin=operator.isospin, strangeness=operator.strangeness, psq=operator.psq, lg_irrep=operator.lg_irrep, laph_query=laph_query, sigmond_query=sigmond_query) else: return AtRestChannel(particle_type=operator.particle_type, isospin=operator.isospin, strangeness=operator.strangeness, lg_irrep=operator.lg_irrep, laph_query=laph_query, sigmond_query=sigmond_query) else: query_result = subprocess.check_output([sigmond_query, '-k', data_file]).decode() try: records = query_result.split('Record') observable = MCObservable.createFromXML(util.queryToXML(records[1])) if observable.psq > 0: return MovingChannel(isospin=observable.isospin, psq=observable.psq, lg_irrep=observable.lg_irrep, laph_query=laph_query, sigmond_query=sigmond_query) else: return AtRestChannel(isospin=observable.isospin, lg_irrep=observable.lg_irrep, laph_query=laph_query, sigmond_query=sigmond_query) except IndexError: logging.warning("%s contains no records", data_file) except AttributeError: logging.warning("%s contains Observables", data_file) return None def addRawDataChannel(self, path, is_basic_laph=True): if is_basic_laph: self.raw_data_channels.append(BLDataChannel(path, self.laph_query)) else: self.raw_data_channels.append(GIDataChannel(path, self.sigmond_query)) @property @abc.abstractmethod def channel_string(self): pass @property def is_special(self): return isinstance(self, SpecialChannel) @property def is_atrest(self): return isinstance(self, AtRestChannel) @property def is_moving(self): return isinstance(self, MovingChannel) def __hash__(self): return hash(self.__repr__()) def __str__(self): return self.channel_string # @ADH - Should be checking that 'other' is an instance of an object # derived from Channel. I'm not sure how to best do that right now. # So, this will suffice for the moment. def __eq__(self, other): return self.__repr__() == other.__repr__() def __ne__(self, other): return self.__repr__() != other.__repr__() def __lt__(self, other): return self.__repr__() < other.__repr__() def __gt__(self, other): return self.__repr__() > other.__repr__() def __le__(self, other): return self.__repr__() <= other.__repr__() def __ge__(self, other): return self.__repr__() >= other.__repr__() class SpecialChannel(Channel): def __init__(self, *, particle_type, isospin, strangeness, flavor, laph_query="laph_query", sigmond_query="sigmond_query"): super().__init__(particle_type=particle_type, isospin=isospin, strangeness=strangeness, laph_query=laph_query, sigmond_query=sigmond_query) self.flavor = flavor @property def channel_string(self): if self.particle_type == "boson": particle_type = "B" elif self.particle_type == "fermion": particle_type = "F" strangeness = str(self.strangeness).replace('-', 'm') return "{p_type}_{flavor}_I{isospin}_S{strangeness}_special".format( p_type=particle_type, flavor=self.flavor, isospin=self.ISOSPIN_MAP[self.isospin], strangeness=strangeness) def __repr__(self): return "SP_{}".format(self.channel_string) class AtRestChannel(Channel): def __init__(self, *, particle_type=None, isospin, strangeness=None, lg_irrep, laph_query="laph_query", sigmond_query="sigmond_query"): super().__init__(particle_type=particle_type, isospin=isospin, strangeness=strangeness, laph_query=laph_query, sigmond_query=sigmond_query) self.psq = 0 self.lg_irrep = lg_irrep @property def channel_string(self): if self.particle_type == "boson": particle_type = "B_" elif self.particle_type == "fermion": particle_type = "F_" else: particle_type = "" if self.strangeness is not None: strangeness = "S{}_".format(self.strangeness).replace('-', 'm') else: strangeness = "" return "{p_type}I{isospin}_{strangeness}P0_{irrep}".format( p_type=particle_type, isospin=self.ISOSPIN_MAP[self.isospin], strangeness=strangeness, irrep=self.lg_irrep) def __repr__(self): return "AR_{}".format(self.channel_string) class MovingChannel(Channel): def __init__(self, *, particle_type=None, isospin, strangeness=None, psq, lg_irrep, laph_query="laph_query", sigmond_query="sigmond_query"): super().__init__(particle_type=particle_type, isospin=isospin, strangeness=strangeness, laph_query=laph_query, sigmond_query=sigmond_query) self.psq = psq self.lg_irrep = lg_irrep @property def channel_string(self): if self.particle_type == "boson": particle_type = "B_" elif self.particle_type == "fermion": particle_type = "F_" else: particle_type = "" if self.strangeness is not None: strangeness = "S{}_".format(self.strangeness).replace('-', 'm') else: strangeness = "" return "{p_type}I{isospin}_{strangeness}PSQ{psq}_{irrep}".format( p_type=particle_type, isospin=self.ISOSPIN_MAP[self.isospin], strangeness=strangeness, psq=self.psq, irrep=self.lg_irrep) def __repr__(self): return "MV_{}".format(self.channel_string)
andrewhanlon/QCD_scripts
sigmond/channel.py
Python
gpl-3.0
7,175
<div class="grid-container-controls"> {{^isSidebar}} <span class="grid-container-title"> {{title_short}} {{#titleurl}}<span class="icon-link" title="{{titleurl}}"></span>{{/titleurl}} {{#style}}<span class="grid-container-style">({{style_label}})</span>{{/style}} </span> {{#right_move}} <span class="grid-container-sorthandle hide-grid-container-editor"><i class="icon-drag"></i></span> {{/right_move}} {{#reused}}<span class="grid-container-reused" title="${reusetitle}"><i class="icon-reused"></i></span>{{/reused}} {{#right_options}} <div class="grid-container-options"> <span class="grid-container-options-icon">Options <i class="icon-options"></i></span> <ul class="grid-container-options-list"> {{^reused}} {{#right_edit}} <li class="grid-container-options-list-item" role="edit"><i class="icon-edit"></i> Edit</li> <li class="grid-container-options-list-item" role="reuse"><i class="icon-reuse"></i> Reuse</li> <li class="grid-container-options-list-item" role="toggleslotstyles"><i class="icon-style"></i> Slot styles</li> {{/right_edit}} {{/reused}} {{#right_delete}} <li class="grid-container-options-list-item" role="trash"><i class="icon-trash"></i> Delete</li> {{/right_delete}} </ul> </div> {{/right_options}} {{/isSidebar}} {{#isSidebar}} <span class="grid-container-title">Sidebars are not supported anymore since Grid Version 2.x <button role="trash"><i class="icon-trash"></i> Delete sidebar container</button></span> {{/isSidebar}} </div> {{^isSidebar}} <div class="grid-container-content"> {{#prolog_short}} <div class="grid-container-before"> <div class="grid-container-prolog">{{&prolog_short}}</div> </div> {{/prolog_short}} <div class="grid-slots-wrapper"></div> <!-- Rebuild in SlotsView --> {{#epilog_short}} <div class="grid-container-after"> <div class="grid-container-epilog">{{&epilog_short}}</div> </div> {{/epilog_short}} {{#reused}} <div class="grid-container-reused-layer"> <span class="grid-container-reused-label">{{reusetitle}}<i class="icon-reuse"></i></span> </div> {{/reused}} </div> {{/isSidebar}}
palasthotel/grid
templates/editor/ich.container.html
HTML
gpl-3.0
2,169
/* This file is part of Mumoro. Mumoro 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. Mumoro 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 Mumoro. If not, see <http://www.gnu.org/licenses/>. © Université de Toulouse 1 2010 Author: Tristram Gräbener*/ #include "graph_wrapper.h" #include <iostream> #include <fstream> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/adj_list_serialize.hpp> #include <boost/foreach.hpp> Edge::Edge() : distance(0), elevation(0), mode_change(0), cost(0), line_change(0), co2(0) { } Duration::Duration(float d) : const_duration(d) {} Duration::Duration() : const_duration(-1) {} void Duration::append(float start, float arrival, const std::string & services) { BOOST_ASSERT(start < arrival); timetable.push_back(Time(start, arrival, Services(services))); } bool compare_times(const Time & a, const Time & b) { return get<0>(a) < get<0>(b); } void Duration::sort() { if(const_duration == -1) { std::sort(timetable.begin(), timetable.end(), compare_times); } } float Duration::operator()(float start, int day) const { float next_day = 0; int run = 0; if (const_duration >= 0) return start + const_duration; else { std::vector<Time>::const_iterator it; for(it = timetable.begin(); it != timetable.end(); it++) { float tt_start, tt_arrival; Services s; boost::tie(tt_start, tt_arrival, s) = *it; // std::cout << s << " " << tt_start << " " << tt_arrival << std::endl; if (tt_start >= start && s[day]) { // std::cout << "Ret : " << tt_arrival << std::endl; return tt_arrival; } if (next_day != 0 && s[day+1]) { next_day = start + 24*3600; } } if(next_day > 0) { // std::cout << "Next day: " << next_day << std::endl; return next_day; } else { // std::cout << "No traffic on day " << day << std::endl; throw No_traffic(); } } } Graph::Graph(const std::string & filename) { load(filename); } Graph::Graph(int nb_nodes) : g(nb_nodes) { } void Graph::add_edge(int source, int target, const Edge & e) { boost::add_edge(source, target, e, g); } bool Graph::public_transport_edge(int source, int target, float start, float arrival, const std::string & services) { edge_t e; bool b; tie(e, b) = edge(source, target, g); if(!b) { bool c; tie(e, c) = boost::add_edge(source, target, g); } g[e].duration.append(start, arrival, services); return !b; } struct found_goal { }; // exception for termination // visitor that terminates when we find the goal class dijkstra_goal_visitor : public boost::default_dijkstra_visitor { public: dijkstra_goal_visitor(int goal) : m_goal(goal) { } template <class Graph_t> void examine_vertex(int u, Graph_t& g) { if (u == m_goal) throw found_goal(); } private: int m_goal; }; float calc_duration(float in, Duration d) { return d(in, 0); } struct Comp { bool operator()(float a, float b) const {return a<b;} bool operator()(const Duration &, float) const {return false;} }; bool Graph::dijkstra(int source, int target) { std::vector<int> p(boost::num_vertices(g)); std::vector<float> d(boost::num_vertices(g)); try{ boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&p[0]) .distance_map(&d[0]) .weight_map(get(&Edge::duration, g)) .visitor(dijkstra_goal_visitor(target)) .distance_zero(30000) .distance_combine(&calc_duration) .distance_compare(Comp()) ); return false; } catch(found_goal) { return true; } } void Graph::sort() { BOOST_FOREACH(edge_t e, boost::edges(g)) { g[e].duration.sort(); } } void Graph::load(const std::string & filename) { std::cout << "Loading graph from file " << filename << std::endl; std::ifstream ifile(filename.c_str()); boost::archive::binary_iarchive iArchive(ifile); iArchive >> g; //graph; std::cout << " " << boost::num_vertices(g) << " nodes" << std::endl; std::cout << " " << boost::num_edges(g) << " edges" << std::endl; } void Graph::save(const std::string & filename) const { std::ofstream ofile(filename.c_str()); boost::archive::binary_oarchive oArchive(ofile); oArchive << g; }
Tristramg/mumoro
lib/core/graph_wrapper.cpp
C++
gpl-3.0
5,281
package android_pmp_sandbox.photoapp; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
cfarrend/android-pmp-sandbox
photoapp/app/src/test/java/android_pmp_sandbox/photoapp/ExampleUnitTest.java
Java
gpl-3.0
406
/* This is the basic linkfollowing script. * Its pretty stable, and you configure which keys to use for hinting * * TODO: Some pages mess around a lot with the zIndex which * lets some hints in the background. * TODO: Some positions are not calculated correctly (mostly * because of uber-fancy-designed-webpages. Basic HTML and CSS * works good * TODO: Still some links can't be followed/unexpected things * happen. Blame some freaky webdesigners ;) */ //Just some shortcuts and globals var uzblid = 'uzbl_link_hint'; var uzbldivid = uzblid + '_div_container'; var doc = document; var win = window; var links = document.links; var forms = document.forms; //Make onlick-links "clickable" try { HTMLElement.prototype.click = function() { if (typeof this.onclick == 'function') { this.onclick({ type: 'click' }); } }; } catch(e) {} //Catch the ESC keypress to stop linkfollowing function keyPressHandler(e) { var kC = window.event ? event.keyCode: e.keyCode; var Esc = window.event ? 27 : e.DOM_VK_ESCAPE; if (kC == Esc) { removeAllHints(); } } //Calculate element position to draw the hint //Pretty accurate but on fails in some very fancy cases function elementPosition(el) { var up = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while (el.offsetParent) { el = el.offsetParent; up += el.offsetTop; left += el.offsetLeft; } return [up, left, width, height]; } //Calculate if an element is visible function isVisible(el) { if (el == doc) { return true; } if (!el) { return false; } if (!el.parentNode) { return false; } if (el.style) { if (el.style.display == 'none') { return false; } if (el.style.visibility == 'hidden') { return false; } } return isVisible(el.parentNode); } //Calculate if an element is on the viewport. function elementInViewport(el) { offset = elementPosition(el); var up = offset[0]; var left = offset[1]; var width = offset[2]; var height = offset[3]; return up < window.pageYOffset + window.innerHeight && left < window.pageXOffset + window.innerWidth && (up + height) > window.pageYOffset && (left + width) > window.pageXOffset; } //Removes all hints/leftovers that might be generated //by this script. function removeAllHints() { var elements = doc.getElementById(uzbldivid); if (elements) { elements.parentNode.removeChild(elements); } } //Generate a hint for an element with the given label //Here you can play around with the style of the hints! function generateHint(el, label) { var pos = elementPosition(el); var hint = doc.createElement('div'); hint.setAttribute('name', uzblid); hint.innerText = label; hint.style.display = 'inline'; hint.style.backgroundColor = '#B9FF00'; hint.style.border = '2px solid #4A6600'; hint.style.color = 'black'; hint.style.fontSize = '9px'; hint.style.fontWeight = 'bold'; hint.style.lineHeight = '9px'; hint.style.margin = '0px'; hint.style.width = 'auto'; // fix broken rendering on w3schools.com hint.style.padding = '1px'; hint.style.position = 'absolute'; hint.style.zIndex = '1000'; // hint.style.textTransform = 'uppercase'; hint.style.left = pos[1] + 'px'; hint.style.top = pos[0] + 'px'; // var img = el.getElementsByTagName('img'); // if (img.length > 0) { // hint.style.top = pos[1] + img[0].height / 2 - 6 + 'px'; // } hint.style.textDecoration = 'none'; // hint.style.webkitBorderRadius = '6px'; // slow // Play around with this, pretty funny things to do :) // hint.style.webkitTransform = 'scale(1) rotate(0deg) translate(-6px,-5px)'; return hint; } //Here we choose what to do with an element if we //want to "follow" it. On form elements we "select" //or pass the focus, on links we try to perform a click, //but at least set the href of the link. (needs some improvements) function clickElem(item) { removeAllHints(); if (item) { var name = item.tagName; if (name == 'A') { item.click(); window.location = item.href; } else if (name == 'INPUT') { var type = item.getAttribute('type').toUpperCase(); if (type == 'TEXT' || type == 'FILE' || type == 'PASSWORD') { item.focus(); item.select(); } else { item.click(); } } else if (name == 'TEXTAREA' || name == 'SELECT') { item.focus(); item.select(); } else { item.click(); window.location = item.href; } } } //Returns a list of all links (in this version //just the elements itself, but in other versions, we //add the label here. function addLinks() { res = [[], []]; for (var l = 0; l < links.length; l++) { var li = links[l]; if (isVisible(li) && elementInViewport(li)) { res[0].push(li); } } return res; } //Same as above, just for the form elements function addFormElems() { res = [[], []]; for (var f = 0; f < forms.length; f++) { for (var e = 0; e < forms[f].elements.length; e++) { var el = forms[f].elements[e]; if (el && ['INPUT', 'TEXTAREA', 'SELECT'].indexOf(el.tagName) + 1 && isVisible(el) && elementInViewport(el)) { res[0].push(el); } } } return res; } //Draw all hints for all elements passed. "len" is for //the number of chars we should use to avoid collisions function reDrawHints(elems, chars) { removeAllHints(); var hintdiv = doc.createElement('div'); hintdiv.setAttribute('id', uzbldivid); for (var i = 0; i < elems[0].length; i++) { if (elems[0][i]) { var label = elems[1][i].substring(chars); var h = generateHint(elems[0][i], label); hintdiv.appendChild(h); } } if (document.body) { document.body.appendChild(hintdiv); } } // pass: number of keys // returns: key length function labelLength(n) { var oldn = n; var keylen = 0; if(n < 2) { return 1; } n -= 1; // our highest key will be n-1 while(n) { keylen += 1; n = Math.floor(n / charset.length); } return keylen; } // pass: number // returns: label function intToLabel(n) { var label = ''; do { label = charset.charAt(n % charset.length) + label; n = Math.floor(n / charset.length); } while(n); return label; } // pass: label // returns: number function labelToInt(label) { var n = 0; var i; for(i = 0; i < label.length; ++i) { n *= charset.length; n += charset.indexOf(label[i]); } return n; } //Put it all together function followLinks(follow) { // if(follow.charAt(0) == 'l') { // follow = follow.substr(1); // charset = 'thsnlrcgfdbmwvz-/'; // } var s = follow.split(''); var linknr = labelToInt(follow); if (document.body) document.body.setAttribute('onkeyup', 'keyPressHandler(event)'); var linkelems = addLinks(); var formelems = addFormElems(); var elems = [linkelems[0].concat(formelems[0]), linkelems[1].concat(formelems[1])]; var len = labelLength(elems[0].length); var oldDiv = doc.getElementById(uzbldivid); var leftover = [[], []]; if (s.length == len && linknr < elems[0].length && linknr >= 0) { clickElem(elems[0][linknr]); } else { for (var j = 0; j < elems[0].length; j++) { var b = true; var label = intToLabel(j); var n = label.length; for (n; n < len; n++) { label = charset.charAt(0) + label; } for (var k = 0; k < s.length; k++) { b = b && label.charAt(k) == s[k]; } if (b) { leftover[0].push(elems[0][j]); leftover[1].push(label); } } reDrawHints(leftover, s.length); } } //Parse input: first argument is follow keys, second is user input. var args = '%s'.split(' '); var charset = args[0]; followLinks(args[1]);
matthewbauer/uzbl
examples/data/scripts/follow.js
JavaScript
gpl-3.0
8,286
CREATE PROCEDURE [FAQ].[Question_Insert] @QuestionText nvarchar(MAX), @AuthorId int, @AuthorName nvarchar(200), @AuthorEmail nvarchar(200), @RespondentId int, @AnswerText nvarchar(MAX), @Moderated bit AS INSERT INTO [FAQ].[Question] ([QuestionText], [AuthorId], [AuthorName], [AuthorEmail], [RespondentId], [AnswerText], [AnswerSentToAuthor], [Moderated]) VALUES (@QuestionText, @AuthorId, @AuthorName, @AuthorEmail, @RespondentId, @AnswerText, 0, @Moderated) SELECT @@IDENTITY
synweb/rocms
FAQ/RoCMS.FAQ.Database/Stored Procedures/Question_Insert.sql
SQL
gpl-3.0
484
Router.map(function() { this.route('index.view', { path: '/', onBeforeAction: function () { if (Meteor.isClient) { Session.set('siteTitle', 'Vazco SlideDeck!'); }; this.next(); } }); this.route('slideshow.view', { path: '/slideshow', onBeforeAction: function () { if (Meteor.isClient) { Session.set('siteTitle', 'Vazco SlideDeck! - Slideshow!'); }; this.next(); } }); this.route('priv.slideshow.view', { path: '/priv-slideshow', onBeforeAction: function () { var settings = App.SlidesSettings.findOne(); if (settings && settings.isPrivViewEnabled) { if (Meteor.isClient) { Session.set('siteTitle', 'Vazco SlideDeck! - Private Slideshow!'); }; this.next(); } else { Router.go('/'); } } }); this.route('login.view', { path: '/login', onBeforeAction: function () { if (Meteor.isClient) { Session.set('siteTitle', 'Vazco SlideDeck! - Admin Login!'); }; this.next(); } }); });
vazco/vsd-meteor-intro
common/router/routes.js
JavaScript
gpl-3.0
1,287
<?php /** * @file * Contains \Drupal\Core\Installer\InstallerServiceProvider. */ namespace Drupal\Core\Installer; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ServiceProviderInterface; use Drupal\Core\DependencyInjection\ServiceModifierInterface; use Symfony\Component\DependencyInjection\Reference; /** * Service provider for the early installer environment. * * This class is manually added by install_begin_request() via * $conf['container_service_providers'] and required to prevent various services * from trying to retrieve data from storages that do not exist yet. */ class InstallerServiceProvider implements ServiceProviderInterface, ServiceModifierInterface { /** * {@inheritdoc} */ public function register(ContainerBuilder $container) { // Inject the special configuration storage for the installer. // This special implementation MUST NOT be used anywhere else than the early // installer environment. $container->register('config.storage', 'Drupal\Core\Config\InstallStorage'); // Replace services with in-memory implementations. $definition = $container->getDefinition('cache_factory'); $definition->setClass('Drupal\Core\Cache\MemoryBackendFactory'); $definition->setArguments(array()); $definition->setMethodCalls(array()); $container ->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueMemoryFactory'); $container ->register('keyvalue.expirable', 'Drupal\Core\KeyValueStore\KeyValueNullExpirableFactory'); // Replace services with no-op implementations. $container ->register('lock', 'Drupal\Core\Lock\NullLockBackend'); $container ->register('url_generator', 'Drupal\Core\Routing\NullGenerator') ->addArgument(new Reference('request_stack')); $container ->register('router.dumper', 'Drupal\Core\Routing\NullMatcherDumper'); // Remove the cache tags invalidator tag from the cache tags storage, so // that we don't call it when cache tags are invalidated very early in the // installer. $container->getDefinition('cache_tags.invalidator.checksum') ->clearTag('cache_tags_invalidator'); // Replace the route builder with an empty implementation. // @todo Convert installer steps into routes; add an installer.routing.yml. $definition = $container->getDefinition('router.builder'); $definition->setClass('Drupal\Core\Installer\InstallerRouteBuilder') // The core router builder, but there is no reason here to be lazy, so // we don't need to ship with a custom proxy class. ->setLazy(FALSE); } /** * {@inheritdoc} */ public function alter(ContainerBuilder $container) { // Disable Twig cache (php storage does not exist yet). $twig_config = $container->getParameter('twig.config'); $twig_config['cache'] = FALSE; $container->setParameter('twig.config', $twig_config); // No service may persist when the early installer kernel is rebooted into // the production environment. // @todo The DrupalKernel reboot performed by drupal_install_system() is // actually not a "regular" reboot (like ModuleHandler::install()), so // services are not actually persisted. foreach ($container->findTaggedServiceIds('persist') as $id => $tags) { $definition = $container->getDefinition($id); $definition->clearTag('persist'); } } }
mbarcia/drupsible-org
core/lib/Drupal/Core/Installer/InstallerServiceProvider.php
PHP
gpl-3.0
3,440
/* * pathfinder.h - Path finder functions * * Copyright (C) 2012 Jon Lund Steffensen <jonlst@gmail.com> * * This file is part of freeserf. * * freeserf 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. * * freeserf 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 freeserf. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SRC_PATHFINDER_H_ #define SRC_PATHFINDER_H_ #include "src/map.h" road_t pathfinder_map(map_t *map, map_pos_t start, map_pos_t end); #endif // SRC_PATHFINDER_H_
tomsoftware/freeserf
src/pathfinder.h
C
gpl-3.0
959
UnitTesterTester ================ Unit Tester Tester scripts for VPL on Moodle Moodle is a popular LMS VPL is an activity module for Moodle that has great out of the box support for collecting, running, and grading (I/O cases) programming assignments for a variety of languages. This set of scritps extends the grading capabilites. In particular it includes scripts to not only enable unit testing, but also more complex testing of student unit tests. Directories ----------- baseCode - holds utilitiy files for transporting scripts to VPL and the core of the scripts readyCode - holds vpl_evaluate.sh scripts for each of the situations you might want one. Directories indicate the langauge or time (unit test or unit tester-tester) exampleCode - holds ready to go example to get you started - mirror the directory structure of readyCode. Using Examples --------------
michaelkbradshaw/UnitTesterTester
README.md
Markdown
gpl-3.0
883
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils.data import flt, nowdate, getdate, cint class MoneyTransfere(Document): def on_submit(self): self.validate_transfere() def validate(self): self.get_dummy_accounts() def get_dummy_accounts(self): dummy_to = frappe.db.get_values("Account", {"name": "حساب استلام من"+" - "+self.from_company + " - "+self.abbr_to, "company": self.to_company, "parent_account":"حساب استلام من"+" - "+self.abbr_to }) self.dummy_to=dummy_to[0][0] dummy_from = frappe.db.get_values("Account", {"name": "حساب ارسال الي"+" - "+self.to_company + " - "+self.abbr, "company": self.from_company, "parent_account":"حساب ارسال"+" - "+self.abbr }) self.dummy_from=dummy_from[0][0] def before_cancel(self): pe = frappe.get_value("Payment Entry", filters = {"transfere_reference": self.name}, fieldname = "name") if pe: pe_doc = frappe.get_doc("Payment Entry", pe) pe_doc.cancel() je = frappe.get_value("Journal Entry Account", filters = {"reference_name": self.name}, fieldname = "parent") if je: je_doc = frappe.get_doc("Journal Entry", je) je_doc.cancel() def validate_transfere(self): if self.from_company != self.to_company: # sending_account = "حساب ارسال الى " + self.to_company # receiving_account = "حساب استلام من " + self.from_company # self.add_account_for_company(sending_account, self.to_company, "Liability") # self.add_account_for_company(receiving_account, self.from_company, "Expense") self.add_payment_entry(self.from_account, self.dummy_from, self.from_company) self.add_journal_entry(self.to_account,self.dummy_to, self.to_company) else: self.add_payment_entry(self.from_account, self.to_account, self.from_company) def add_account_for_company(self, account, company, r_type): pass # pacc_name = "" # if r_type == "Expense": # pacc_name = "حساب ارسال - E" # elif r_type == "Liability": # pacc_name = "حساب استقبال - o" # # if not frappe.db.exists("Account", pacc_name): # # pacc = frappe.new_doc("Account") # # pacc.account_name = pacc_name # # pacc.root_type = r_type # # pacc.is_group = 1 # # pacc.parent_account = "" # # pacc.company = company # # pacc.flags.ignore_validate = True # # pacc.insert() # if not frappe.db.exists("Account", account): # acc = frappe.new_doc("Account") # acc.account_name = account # acc.company = company # acc.parent_account = pacc_name # acc.is_group = 0 # acc.insert() def add_payment_entry(self, paid_from, paid_to, company): pe = frappe.new_doc("Payment Entry") pe.payment_type = "Internal Transfer" pe.company = company pe.paid_from = paid_from pe.paid_to = paid_to pe.paid_amount = self.transfered_amount pe.received_amount = self.transfered_amount pe.posting_date = nowdate() pe.mode_of_payment = self.mode_of_payment pe.transfere_reference = self.name pe.insert() pe.submit() # pe.setup_party_account_field() # pe.set_missing_values() # pe.set_exchange_rate() # pe.set_amounts() # self.assertEquals(pe.difference_amount, 500) # pe.append("deductions", { # "account": "_Test Exchange Gain/Loss - _TC", # "cost_center": "_Test Cost Center - _TC", # "amount": 500 # }) def add_journal_entry(self, account1, account2, company): default_cost = frappe.get_value("Company", filters = {"name":company}, fieldname = "cost_center") jv = frappe.new_doc("Journal Entry") jv.posting_date = nowdate() jv.company = company jv.voucher_type = "Opening Entry" jv.set("accounts", [ { "account": account2, "credit_in_account_currency": self.transfered_amount, "cost_center": default_cost, "reference_type": "Money Transfere", "reference_name": self.name }, { "account": account1, "debit_in_account_currency": self.transfered_amount, "cost_center": default_cost, "reference_type": "Money Transfere", "reference_name": self.name } ]) jv.insert() jv.submit()
ahmadRagheb/goldenHR
erpnext/accounts/doctype/money_transfere/money_transfere.py
Python
gpl-3.0
4,294
/***************************************************************************** * * Monitoring check_users plugin * * License: GPL * Copyright (c) 2000-2012 Monitoring Plugins Development Team * * Description: * * This file contains the check_users plugin * * This plugin checks the number of users currently logged in on the local * system and generates an error if the number exceeds the thresholds * specified. * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * *****************************************************************************/ const char *progname = "check_users"; const char *copyright = "2000-2007"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" #if HAVE_UTMPX_H # include <utmpx.h> #else # include "popen.h" #endif #define possibly_set(a,b) ((a) == 0 ? (b) : 0) int process_arguments (int, char **); void print_help (void); void print_usage (void); int wusers = -1; int cusers = -1; int main (int argc, char **argv) { int users = -1; int result = STATE_UNKNOWN; char *perf; #if HAVE_UTMPX_H struct utmpx *putmpx; #else char input_buffer[MAX_INPUT_BUFFER]; #endif setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); perf = strdup (""); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); users = 0; #if HAVE_UTMPX_H /* get currently logged users from utmpx */ setutxent (); while ((putmpx = getutxent ()) != NULL) if (putmpx->ut_type == USER_PROCESS) users++; endutxent (); #else /* run the command */ child_process = spopen (WHO_COMMAND); if (child_process == NULL) { printf (_("Could not open pipe: %s\n"), WHO_COMMAND); return STATE_UNKNOWN; } child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); if (child_stderr == NULL) printf (_("Could not open stderr for %s\n"), WHO_COMMAND); while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { /* increment 'users' on all lines except total user count */ if (input_buffer[0] != '#') { users++; continue; } /* get total logged in users */ if (sscanf (input_buffer, _("# users=%d"), &users) == 1) break; } /* check STDERR */ if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) result = possibly_set (result, STATE_UNKNOWN); (void) fclose (child_stderr); /* close the pipe */ if (spclose (child_process)) result = possibly_set (result, STATE_UNKNOWN); #endif /* check the user count against warning and critical thresholds */ if (users > cusers) result = STATE_CRITICAL; else if (users > wusers) result = STATE_WARNING; else if (users >= 0) result = STATE_OK; if (result == STATE_UNKNOWN) printf ("%s\n", _("Unable to read output")); else { xasprintf (&perf, "%s", perfdata ("users", users, "", TRUE, wusers, TRUE, cusers, TRUE, 0, FALSE, 0)); printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result), users, perf); } return result; } /* process command-line arguments */ int process_arguments (int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; if (argc < 2) usage ("\n"); while (1) { c = getopt_long (argc, argv, "+hVvc:w:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'c': /* critical */ if (!is_intnonneg (optarg)) usage4 (_("Critical threshold must be a positive integer")); else cusers = atoi (optarg); break; case 'w': /* warning */ if (!is_intnonneg (optarg)) usage4 (_("Warning threshold must be a positive integer")); else wusers = atoi (optarg); break; } } c = optind; if (wusers == -1 && argc > c) { if (is_intnonneg (argv[c]) == FALSE) usage4 (_("Warning threshold must be a positive integer")); else wusers = atoi (argv[c++]); } if (cusers == -1 && argc > c) { if (is_intnonneg (argv[c]) == FALSE) usage4 (_("Warning threshold must be a positive integer")); else cusers = atoi (argv[c]); } return OK; } void print_help (void) { print_revision (progname, NP_VERSION); printf ("Copyright (c) 1999 Ethan Galstad\n"); printf (COPYRIGHT, copyright, email); printf ("%s\n", _("This plugin checks the number of users currently logged in on the local")); printf ("%s\n", _("system and generates an error if the number exceeds the thresholds specified.")); printf ("\n\n"); print_usage (); printf (UT_HELP_VRSN); printf (UT_EXTRA_OPTS); printf (" %s\n", "-w, --warning=INTEGER"); printf (" %s\n", _("Set WARNING status if more than INTEGER users are logged in")); printf (" %s\n", "-c, --critical=INTEGER"); printf (" %s\n", _("Set CRITICAL status if more than INTEGER users are logged in")); printf (UT_SUPPORT); } void print_usage (void) { printf ("%s\n", _("Usage:")); printf ("%s -w <users> -c <users>\n", progname); }
dermoth/monitoring-plugins
plugins/check_users.c
C
gpl-3.0
6,005
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ //! \addtogroup op_shift //! @{ template<typename T1> inline void op_shift_vec::apply(Mat<typename T1::elem_type>& out, const Op<T1, op_shift_vec>& in) { arma_extra_debug_sigprint(); const unwrap<T1> U(in.m); const uword len = in.aux_uword_a; const uword neg = in.aux_uword_b; const uword dim = (T1::is_xvec) ? uword(U.M.is_rowvec() ? 1 : 0) : uword((T1::is_row) ? 1 : 0); op_shift::apply_direct(out, U.M, len, neg, dim); } template<typename T1> inline void op_shift::apply(Mat<typename T1::elem_type>& out, const Op<T1, op_shift>& in) { arma_extra_debug_sigprint(); const unwrap<T1> U(in.m); const uword len = in.aux_uword_a; const uword neg = in.aux_uword_b; const uword dim = in.aux_uword_c; arma_debug_check((dim > 1), "shift(): parameter 'dim' must be 0 or 1"); op_shift::apply_direct(out, U.M, len, neg, dim); } template<typename eT> inline void op_shift::apply_direct(Mat<eT>& out, const Mat<eT>& X, const uword len, const uword neg, const uword dim) { arma_extra_debug_sigprint(); arma_debug_check_bounds(((dim == 0) && (len >= X.n_rows)), "shift(): shift amount out of bounds"); arma_debug_check_bounds(((dim == 1) && (len >= X.n_cols)), "shift(): shift amount out of bounds"); if(&out == &X) { op_shift::apply_alias(out, len, neg, dim); } else { op_shift::apply_noalias(out, X, len, neg, dim); } } template<typename eT> inline void op_shift::apply_noalias(Mat<eT>& out, const Mat<eT>& X, const uword len, const uword neg, const uword dim) { arma_extra_debug_sigprint(); out.copy_size(X); const uword X_n_rows = X.n_rows; const uword X_n_cols = X.n_cols; if(dim == 0) { if(neg == 0) { for(uword col = 0; col < X_n_cols; ++col) { eT* out_ptr = out.colptr(col); const eT* X_ptr = X.colptr(col); for(uword out_row = len, row = 0; row < (X_n_rows - len); ++row, ++out_row) { out_ptr[out_row] = X_ptr[row]; } for(uword out_row = 0, row = (X_n_rows - len); row < X_n_rows; ++row, ++out_row) { out_ptr[out_row] = X_ptr[row]; } } } else if(neg == 1) { for(uword col = 0; col < X_n_cols; ++col) { eT* out_ptr = out.colptr(col); const eT* X_ptr = X.colptr(col); for(uword out_row = 0, row = len; row < X_n_rows; ++row, ++out_row) { out_ptr[out_row] = X_ptr[row]; } for(uword out_row = (X_n_rows - len), row = 0; row < len; ++row, ++out_row) { out_ptr[out_row] = X_ptr[row]; } } } } else if(dim == 1) { if(neg == 0) { if(X_n_rows == 1) { eT* out_ptr = out.memptr(); const eT* X_ptr = X.memptr(); for(uword out_col = len, col = 0; col < (X_n_cols - len); ++col, ++out_col) { out_ptr[out_col] = X_ptr[col]; } for(uword out_col = 0, col = (X_n_cols - len); col < X_n_cols; ++col, ++out_col) { out_ptr[out_col] = X_ptr[col]; } } else { for(uword out_col = len, col = 0; col < (X_n_cols - len); ++col, ++out_col) { arrayops::copy(out.colptr(out_col), X.colptr(col), X_n_rows); } for(uword out_col = 0, col = (X_n_cols - len); col < X_n_cols; ++col, ++out_col) { arrayops::copy(out.colptr(out_col), X.colptr(col), X_n_rows); } } } else if(neg == 1) { if(X_n_rows == 1) { eT* out_ptr = out.memptr(); const eT* X_ptr = X.memptr(); for(uword out_col = 0, col = len; col < X_n_cols; ++col, ++out_col) { out_ptr[out_col] = X_ptr[col]; } for(uword out_col = (X_n_cols - len), col = 0; col < len; ++col, ++out_col) { out_ptr[out_col] = X_ptr[col]; } } else { for(uword out_col = 0, col = len; col < X_n_cols; ++col, ++out_col) { arrayops::copy(out.colptr(out_col), X.colptr(col), X_n_rows); } for(uword out_col = (X_n_cols - len), col = 0; col < len; ++col, ++out_col) { arrayops::copy(out.colptr(out_col), X.colptr(col), X_n_rows); } } } } } template<typename eT> inline void op_shift::apply_alias(Mat<eT>& X, const uword len, const uword neg, const uword dim) { arma_extra_debug_sigprint(); // TODO: replace with better implementation Mat<eT> tmp; op_shift::apply_noalias(tmp, X, len, neg, dim); X.steal_mem(tmp); } //! @}
TLCFEM/suanPan
Include/armadillo/armadillo_bits/op_shift_meat.hpp
C++
gpl-3.0
4,804
import numpy as np def min_max_model(power, use, battery_capacity): """ Minimal maximum battery model, obsoleted :param power: Pandas TimeSeries, total power from renewable system :param use: float, unit W fixed load of the power system :param battery_capacity: float, unit Wh battery capacity :return: list, energy history in battery """ power = power.tolist() energy = 0 energy_history = [] for p in power: energy = min(battery_capacity, max(0, energy + (p - use) * 1)) energy_history.append(energy) return energy_history def soc_model_fixed_load( power, use, battery_capacity, depth_of_discharge=1, discharge_rate=0.005, battery_eff=0.9, discharge_eff=0.8, ): """ Battery state of charge model with fixed load. (Obsolete) :param power: Pandas TimeSeries of total power from renewable system :param use: float unit W fixed load of the power system :param battery_capacity: float unit Wh battery capacity :param depth_of_discharge: float 0 to 1 maximum allowed discharge depth :param discharge_rate: self discharge rate :param battery_eff: optional 0 to 1 battery energy store efficiency default 0.9 :param discharge_eff: battery discharge efficiency 0 to 1 default 0.8 :return: tuple SOC: state of charge, energy history: E in battery, unmet_history: unmet energy history, waste_history: waste energy history """ DOD = depth_of_discharge power = power.tolist() use_history = [] waste_history = [] unmet_history = [] energy_history = [] energy = 0 for p in power: if p >= use: use_history.append(use) unmet_history.append(0) energy_new = energy * (1 - discharge_rate) + (p - use) * battery_eff if energy_new < battery_capacity: energy = energy_new # battery energy got update waste_history.append(0) else: waste_history.append(p - use) energy = energy elif p < use: energy_new = energy * (1 - discharge_rate) + (p - use) / discharge_eff if energy_new > (1 - DOD) * battery_capacity: energy = energy_new unmet_history.append(0) waste_history.append(0) use_history.append(use) elif energy * (1 - discharge_rate) + p * battery_eff < battery_capacity: energy = energy * (1 - discharge_rate) + p * battery_eff unmet_history.append(use - p) use_history.append(0) waste_history.append(0) else: unmet_history.append(use - p) use_history.append(0) waste_history.append(p) energy = energy energy_history.append(energy) if battery_capacity == 0: SOC = np.array(energy_history) else: SOC = np.array(energy_history) / battery_capacity return SOC, energy_history, unmet_history, waste_history, use_history class Battery: """ A simple finite state based energy flow battery model. """ def __init__(self, capacity, config={}): """ Initialise the battery with a given capacity and configuration. :param capacity: float, unit Wh :param config: options including DOD, depth of discharge; sigma, self-discharge rate; eta_in, charge efficiency; eta_out, discharge efficiency; init_charge, percentage of the battery pre-charge; where all values shall between 0 and 1 """ self.capacity = capacity self.config = config self.set_parameters() def set_parameters(self): """ Setup the parameters using the config file, options including DOD, depth of discharge; sigma, self-discharge rate; eta_in, charge efficiency; eta_out, discharge efficiency; init_charge, percentage of the battery pre-charge; where all values shall between 0 and 1. """ try: self.depth_of_discharge = self.config['simulation']['battery']['DOD'] self.discharge_rate = self.config['simulation']['battery']['sigma'] self.battery_eff = self.config['simulation']['battery']['eta_in'] self.discharge_eff = self.config['simulation']['battery']['eta_out'] self.init_charge = self.config['simulation']['battery']['B0'] except KeyError: print('Parameter is not found in config file, default values are used.') self.depth_of_discharge = 1 self.discharge_rate = 0.005 self.battery_eff = 0.9 self.discharge_eff = 0.8 self.init_charge = 1 def run(self, power, use): """ Run the battery model with a list of power generation and usage. :param power: list, power generation unit in W :param use: list, power usage unit in W :return: None """ DOD = self.depth_of_discharge battery_capacity = self.capacity discharge_rate = self.discharge_rate discharge_eff = self.discharge_eff battery_eff = self.battery_eff use_history = [] waste_history = [] unmet_history = [] energy_history = [] SOC = [] energy = self.init_charge * self.capacity for p, u in zip(power, use): if p >= u: use_history.append(u) unmet_history.append(0) energy_new = energy * (1 - discharge_rate) + (p - u) * battery_eff if energy_new < battery_capacity: energy = energy_new # battery energy got update waste_history.append(0) else: waste_history.append(p - u) energy = energy elif p < u: energy_new = energy * (1 - discharge_rate) + (p - u) / discharge_eff if energy_new > (1 - DOD) * battery_capacity: energy = energy_new unmet_history.append(0) waste_history.append(0) use_history.append(u) elif energy * (1 - discharge_rate) + p * battery_eff < battery_capacity: energy = energy * (1 - discharge_rate) + p * battery_eff unmet_history.append(u - p) use_history.append(0) waste_history.append(0) else: unmet_history.append(u - p) use_history.append(0) waste_history.append(p) energy = energy energy_history.append(energy) SOC.append(energy / battery_capacity) self.SOC = SOC self.energy_history = energy_history self.unmet_history = unmet_history self.waste_history = waste_history self.use_history = use_history def battery_history(self): """ Return the history of the battery. :return: np array, the SOC, energy in the battery, unmet power supply, wasted power and the supplied power unit in W """ history = np.vstack( ( np.array(self.SOC), np.array(self.energy_history), np.array(self.unmet_history), np.array(self.waste_history), np.array(self.use_history), ) ) return history def lost_power_supply_probability(self): """ Return the lost power supply probability (LPSP) using the battery history. :return: float, LPSP """ LPSP = 1 - self.unmet_history.count(0) / len(self.energy_history) return LPSP class Battery_managed: """ Battery managed is a the basic class for the demand load controllable battery model. """ def __init__(self, capacity, config={}): """ :param capacity: float, unit Wh :param config: options including DOD, depth of discharge; sigma, self-discharge rate; eta_in, charge efficiency; eta_out, discharge efficiency; init_charge, percentage of the battery pre-charge; where all values shall between 0 and 1 """ self.capacity = capacity self.config = config self.set_parameters() self.init_history() self.init_simulation() self.status = [] self.states_list = [] def set_parameters(self): """ Setup the parameters using the config file, options including DOD, depth of discharge; sigma, self-discharge rate; eta_in, charge efficiency; eta_out, discharge efficiency; init_charge, percentage of the battery pre-charge; where all values shall between 0 and 1. """ try: self.depth_of_discharge = self.config['simulation']['battery']['DOD'] self.discharge_rate = self.config['simulation']['battery']['sigma'] self.battery_eff = self.config['simulation']['battery']['eta_in'] self.discharge_eff = self.config['simulation']['battery']['eta_out'] self.init_charge = self.config['simulation']['battery']['B0'] self.DOD = self.depth_of_discharge except KeyError: print('Parameter is not found in config file, default values are used.') self.depth_of_discharge = 1 self.discharge_rate = 0.005 self.battery_eff = 0.9 self.discharge_eff = 0.8 self.init_charge = 1 self.DOD = self.depth_of_discharge def reset(self): """ Reset the battery state to the start of simulation. :return: """ self.init_history() self.init_simulation() def init_simulation(self): self.energy = self.init_charge * self.capacity def init_history(self): self.supply_history = [] self.waste_history = [] self.unmet_history = [] self.battery_energy_history = [] self.SOC = [] def step(self, plan, generated, gym = False): """ Run the finite state battery model on one time step. :param plan: float, planned power usage in W :param generated: float, power generation unit in W :param gym: optional, set True to using in OpenAI gym mode :return: float, the supplied power in W """ if gym == True: plan = plan[0][0] if generated >= plan: self.supply_history.append(plan) self.unmet_history.append(0) energy_new = self.energy * (1 - self.discharge_rate) + (generated - plan) * self.battery_eff if energy_new < self.capacity: self.energy = energy_new # battery energy got update self.waste_history.append(0) self.status.append("""Demand can be meet by generation, also battery is not full. Supply {demand}, charge {diff}.""".format(demand=plan, diff=generated - plan) ) self.state = 'charge' else: self.waste_history.append(generated - plan - (self.capacity - self.energy)) self.energy = self.capacity self.status.append("""Demand can be meet by generation, but battery is already full. Supply {demand}, charge battery to full waste {diff}.""".format( demand=plan, diff=generated - plan) ) self.state = 'float' elif generated < plan: energy_new = self.energy * (1 - self.discharge_rate) + (generated - plan) / self.discharge_eff if energy_new > (1 - self.DOD) * self.capacity: self.energy = energy_new self.unmet_history.append(0) self.waste_history.append(0) self.supply_history.append(plan) self.status.append("""Demand can not meet by generation, power in battery can make up difference. Supply {demand} by discharge from battery""".format(demand=plan)) self.state = 'discharge' elif self.energy * (1 - self.discharge_rate) + generated * self.battery_eff < self.capacity: self.energy = self.energy * (1 - self.discharge_rate) + generated * self.battery_eff self.unmet_history.append(plan - generated) self.supply_history.append(0) self.waste_history.append(0) self.status.append("""Demand can not meet by generation, also power in battery can not make up difference. Charge {diff} to battery to avoid waste""".format(diff=generated)) self.state = 'unmet' else: self.unmet_history.append(plan - generated) self.supply_history.append(0) self.waste_history.append(generated - (self.capacity - self.energy)) self.energy = self.capacity self.status.append("""Demand can not meet by generation, also power in battery can not make up difference. Charge {diff} to make battery full""".format( diff=self.capacity-self.energy)) self.state = 'unmet' self.states_list.append(self.state) self.battery_energy_history.append(self.energy) self.SOC.append(self.energy / self.capacity) self.supply = self.supply_history[-1] return self.supply def history(self): """ Get the history of the managed battery. :return: np array including the history of the battery: SOC, battery energy, unmet and wasted energy, supplied power """ battery_history = np.vstack( ( np.array(self.SOC), np.array(self.battery_energy_history), np.array(self.unmet_history), np.array(self.waste_history), np.array(self.supply_history), ) ) return battery_history def observation(self): """ Observation :return: """ battery_state = { 'current_energy': self.energy, 'usable_capacity': self.DOD * self.capacity, } return battery_state def story_board(self): """ For the use of explainable AI in power management system. :return: the status of battery """ return self.status def lost_power_supply_probability(self): """ Get the lost power supply probability of the managed battery after run. :return: float, LPSP """ LPSP = 1 - self.unmet_history.count(0) / len(self.SOC) return LPSP def copy(self): """ Make a copy of battery model. :return: Copied version of battery with same capacity and configuration """ return Battery_managed(self.capacity, self.config) class Soc_model_variable_load: """ Obsolete basic class. """ def __init__(self, battery, power, load): self.battery = battery self.battery.run(power, load) def get_lost_power_supply_probability(self): return self.battery.lost_power_supply_probability() def get_battery_history(self): return self.battery.battery_history() def get_quality_performance_index(self): pass def soc_model_variable_load( power, use, battery_capacity, depth_of_discharge=1, discharge_rate=0.005, battery_eff=0.9, discharge_eff=0.8, ): """ Battery state of charge model with fixed load. :param power: Pandas TimeSeries of total power from renewable system :param use: float unit W fixed load of the power system :param battery_capacity: float unit Wh battery capacity :param depth_of_discharge: float 0 to 1 maximum allowed discharge depth :param discharge_rate: self discharge rate :param battery_eff: optional 0 to 1 battery energy store efficiency default 0.9 :param discharge_eff: battery discharge efficiency 0 to 1 default 0.8 :return: tuple SOC: state of charge, energy history: E in battery, unmet_history: unmet energy history, waste_history: waste energy history """ DOD = depth_of_discharge power = power.tolist() use = use.tolist() use_history = [] waste_history = [] unmet_history = [] energy_history = [] energy = 0 for p, u in zip(power, use): if p >= u: use_history.append(u) unmet_history.append(0) energy_new = energy * (1 - discharge_rate) + (p - u) * battery_eff if energy_new < battery_capacity: energy = energy_new # battery energy got update waste_history.append(0) else: waste_history.append(p - u) energy = energy elif p < u: energy_new = energy * (1 - discharge_rate) + (p - u) / discharge_eff if energy_new > (1 - DOD) * battery_capacity: energy = energy_new unmet_history.append(0) waste_history.append(0) use_history.append(use) elif energy * (1 - discharge_rate) + p * battery_eff < battery_capacity: energy = energy * (1 - discharge_rate) + p * battery_eff unmet_history.append(u - p) use_history.append(0) waste_history.append(0) else: unmet_history.append(u - p) use_history.append(0) waste_history.append(p) energy = energy energy_history.append(energy) if battery_capacity == 0: SOC = np.array(energy_history) else: SOC = np.array(energy_history) / battery_capacity return SOC, energy_history, unmet_history, waste_history, use_history if __name__ == '__main__': b1 = Battery(10) b1.run([1, 1, 1], [1, 1, 1]) b1.run([1, 1, 1], [10, 10, 10]) print(b1.lost_power_supply_probability())
tsaoyu/D3HRE
D3HRE/core/battery_models.py
Python
gpl-3.0
18,409
<!DOCTYPE html> <html> <head> <title>Nameaero | Buy Cheap Domain Names - Free Domain Name Register Template</title> <meta name="description" content="Buy Cheap Domain Names - Free Domain Name Register Template"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="author" content="Nameaero"> <link rel="stylesheet" href="style/normalize.css"> <link rel="stylesheet" href="style/simple.css"> <link rel="stylesheet" href="style/style.css"> <!--- <script src="#" type="text/javascript" language="JavaScript"></script> --> <link rel="icon" type="image/png" href="img/fav.png"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> </head> <body> <header> <div class="header"> <div class="header-inner"> <a href="index.html"><img src="img/nameaero_logo.png" class="logo"></a> </div> <div class="header-inner-2"> <nav> <ul> <li><a href="pricing.html">Domains</a></li> <li class="separation">/</li> <li><a href="apps.html">Apps</a></li> <li class="separation">/</li> <li><a href="about.html">About</a></li> <li class="separation">/</li> <li><a href="contact.html">Contact</a></li> <li class="separation">/</li> <li><a href="blog.html">Blog</a></li> </ul> </nav> </div> <div class="header-inner-3"> <a href="clientarea.html">Welcome User,</a> </div> </div> </header> <!--- Header Ends --> <div class="container"> <div class="main-body"> <h2 class="search-heading">Welcome User, Here You Can Manage Your Domains.</h2> </div> <div class="inner-body inner-body-domain" style="overflow-x:auto;"> <table class="domain-list-ca"> <tr> <td><b>Domain Name</b></td> <td><b>Expiry Date</b></td> <td><b>Status</b></td> <td><b>Manage</b></td> </tr> <tr> <td><b>nameaero.com</b></td> <td>2017/03/30</td> <td><b><font color="green">Active</font></b></td> <td><a href="dnsmanager.html" class="button">Manage</a></td> </tr> <tr> <td><b>nameaero.net</b></td> <td>2017/03/30</td> <td><b><font color="red">InActive</font></b></td> <td><a href="dnsmanager.html" class="button">Manage</a></td> </tr> </table> </div> </div> <!--- Main Container ends --> <footer> <div class="footer"> <div class="footer-inner"> <div class="three columns"> <h6 class="footer-heading">Quick Links</h6> <div class="footer-text"> Domain pricing<br> Transfer your domains to us<br> New domain extensions &amp; launch dates<br> One-click web services<br> October discounts<br> </div> <div class="footer-text-2"> Copyright &copy; 2018. </div> </div> <div class="three columns"> <h6 class="footer-heading">Company</h6> <div class="footer-text"> About nameaero<br> Blog/Guides<br> Twitter / Facebook / Newsletter<br> Work for us<br> Terms &amp; privacy policy<br> </div> <div class="footer-text-2"> <form autocomplete="off"> <div class="footer-search-container"> <input type="searchbar" class="search-bar" placeholder="Search..." /> <button type="submit" class="search-button"> <i class="fa fa-search"></i> </button> </div> </form> </div> </div> <div class="three columns"> <h6 class="footer-heading">Support</h6> <div class="footer-text"> Help center Q&amp;A<br> Website status<br> Contact a human<br> </div> </div> <div class="three columns"> <h6 class="footer-heading">Extras</h6> <div class="footer-text"> Affiliate program<br> Developer API<br> Website hosting<br> SSL certificates<br> </div> <div class="footer-text-2"> All Prices Are In USD. </div> </div> </div> </div> </footer> <!-- Footer Ends --> </body> </html>
rudrax-khanal/nameaero
clientarea.html
HTML
gpl-3.0
4,064
IPython to Pelican Converter ============================ ##### Usage as standalone $ ipytopelican.py infile.ipynb or $ ipytopelican.py infile.ipynb -o outfile.md ##### Usage as library ```python from ipytopelican import convert convert('infile.ipynb') ``` You can set up your notebook with Pelican metadata by putting it in the first cell: Title: My Notebook, Automatically Published Date: 2014-04-11 5:30 Category: Experiments Tags: data science
alexbyrnes/ipython-to-pelican-converter
README.md
Markdown
gpl-3.0
485
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2021 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef analyzerH #define analyzerH #include <string> #include <vector> class Token; template<class T> class ValuePtr; struct Analyzer { struct Action { Action() : mFlag(0) {} // cppcheck-suppress noExplicitConstructor Action(unsigned int f) : mFlag(f) {} enum { None = 0, Read = (1 << 0), Write = (1 << 1), Invalid = (1 << 2), Inconclusive = (1 << 3), Match = (1 << 4), Idempotent = (1 << 5), Incremental = (1 << 6), SymbolicMatch = (1 << 7), }; void set(unsigned int f, bool state = true) { mFlag = state ? mFlag | f : mFlag & ~f; } bool get(unsigned int f) const { return ((mFlag & f) != 0); } bool isRead() const { return get(Read); } bool isWrite() const { return get(Write); } bool isInvalid() const { return get(Invalid); } bool isInconclusive() const { return get(Inconclusive); } bool isNone() const { return mFlag == None; } bool isModified() const { return isWrite() || isInvalid(); } bool isIdempotent() const { return get(Idempotent); } bool isIncremental() const { return get(Incremental); } bool isSymbolicMatch() const { return get(SymbolicMatch); } bool matches() const { return get(Match); } Action& operator|=(Action a) { set(a.mFlag); return *this; } friend Action operator|(Action a, Action b) { a |= b; return a; } friend bool operator==(Action a, Action b) { return a.mFlag == b.mFlag; } friend bool operator!=(Action a, Action b) { return a.mFlag != b.mFlag; } private: unsigned int mFlag; }; enum class Terminate { None, Bail, Escape, Modified, Inconclusive, Conditional }; struct Result { Result(Action action = Action::None, Terminate terminate = Terminate::None) : action(action), terminate(terminate) {} Action action; Terminate terminate; void update(Result rhs) { if (terminate == Terminate::None) terminate = rhs.terminate; action |= rhs.action; } }; enum class Direction { Forward, Reverse }; struct Assume { enum Flags { None = 0, Quiet = (1 << 0), Absolute = (1 << 1), ContainerEmpty = (1 << 2), }; }; enum class Evaluate { Integral, ContainerEmpty }; /// Analyze a token virtual Action analyze(const Token* tok, Direction d) const = 0; /// Update the state of the value virtual void update(Token* tok, Action a, Direction d) = 0; /// Try to evaluate the value of a token(most likely a condition) virtual std::vector<int> evaluate(Evaluate e, const Token* tok, const Token* ctx = nullptr) const = 0; std::vector<int> evaluate(const Token* tok, const Token* ctx = nullptr) const { return evaluate(Evaluate::Integral, tok, ctx); } /// Lower any values to possible virtual bool lowerToPossible() = 0; /// Lower any values to inconclusive virtual bool lowerToInconclusive() = 0; /// If the analysis is unsure whether to update a scope, this will return true if the analysis should bifurcate the scope virtual bool updateScope(const Token* endBlock, bool modified) const = 0; /// Called when a scope will be forked virtual void forkScope(const Token* /*endBlock*/) {} /// If the value is conditional virtual bool isConditional() const = 0; /// The condition that will be assumed during analysis virtual void assume(const Token* tok, bool state, unsigned int flags = 0) = 0; /// Return analyzer for expression at token virtual ValuePtr<Analyzer> reanalyze(Token* tok, const std::string& msg = "") const = 0; virtual ~Analyzer() {} }; #endif
boos/cppcheck
lib/analyzer.h
C
gpl-3.0
4,984
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class ConsumableStartupDecisions : ConsumableTransitions { public ConsumableStartupDecisions(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/ConsumableStartupDecisions.cs
C#
gpl-3.0
254
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.34014 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Expunger.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
xenon92/expunger
Expunger/My Project/Resources.Designer.vb
Visual Basic
gpl-3.0
2,714
using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace UniversalDriver { public abstract class USBDevice : Device { public USBDevice () { } private USBDeviceIdentity.USBDeviceIdentityCollection mvarIdentities = new USBDeviceIdentity.USBDeviceIdentityCollection(); public USBDeviceIdentity.USBDeviceIdentityCollection Identities { get { return mvarIdentities; } } protected abstract void ReadPacket(System.IO.BinaryReader br); private System.Threading.Thread _thread = null; private void _thread_ThreadStart() { switch (System.Environment.OSVersion.Platform) { case PlatformID.MacOSX: case PlatformID.Unix: { /* System.IO.FileStream file = System.IO.File.Open(mvarPath, System.IO.FileMode.Open); System.IO.BinaryReader br = new System.IO.BinaryReader(file); while (true) { ReadPacket(br); } */ break; } case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: { string pathName = null; // devicePaths[devicePaths.Count - 1]; IntPtr fileHandle = Internal.Windows.Methods.CreateFile(pathName, Internal.Windows.Constants.CreateFileDesiredAccess.GenericRead, Internal.Windows.Constants.CreateFileShareMode.Read, IntPtr.Zero, Internal.Windows.Constants.CreateFileCreationDisposition.OpenExisting, Internal.Windows.Constants.CreateFileAttributes.Normal, IntPtr.Zero); int err = Internal.Windows.Methods.GetLastError(); if (err != 0) throw new System.ComponentModel.Win32Exception(err); byte[] xbuffer = new byte[1024]; int readLength = 0; bool retval1 = Internal.Windows.Methods.ReadFile(fileHandle, xbuffer, xbuffer.Length, ref readLength, IntPtr.Zero); err = Internal.Windows.Methods.GetLastError(); if (err != 0) throw new System.ComponentModel.Win32Exception(err); break; } default: { throw new PlatformNotSupportedException(); } } } public void Start() { if (_thread == null) _thread = new System.Threading.Thread(_thread_ThreadStart); _thread.Start(); } public void Stop() { if (_thread == null) return; _thread.Abort(); } public static USBDevice[] Get() { List<USBDevice> list = new List<USBDevice>(); switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: { IntPtr hDevInfo = Internal.Windows.Methods.SetupDiGetClassDevs(ref Internal.Windows.Constants.DeviceClassGUID.UsbDevice, null, IntPtr.Zero, Internal.Windows.Constants.SetupDiGetClassDevsFlags.DeviceInterfaces | Internal.Windows.Constants.SetupDiGetClassDevsFlags.Present); System.Collections.Generic.List<Internal.Windows.Structures.SP_DEVICE_INTERFACE_DATA> listDevs = new System.Collections.Generic.List<Internal.Windows.Structures.SP_DEVICE_INTERFACE_DATA>(); System.Collections.Generic.List<string> devicePaths = new System.Collections.Generic.List<string>(); int devinfo_memberIndex = 0; while (true) { int memberIndex = 0; Internal.Windows.Structures.SP_DEVINFO_DATA devinfo_data = new Internal.Windows.Structures.SP_DEVINFO_DATA(); devinfo_data.cbSize = Marshal.SizeOf(devinfo_data); bool devinfo_retval = Internal.Windows.Methods.SetupDiEnumDeviceInfo(hDevInfo, devinfo_memberIndex, out devinfo_data); int devinfo_lastError = Internal.Windows.Methods.GetLastError(); if (devinfo_lastError == 259) { // no more data is available break; } if (devinfo_lastError != 0) throw new System.ComponentModel.Win32Exception(devinfo_lastError); while (true) { Internal.Windows.Structures.SP_DEVICE_INTERFACE_DATA data = new Internal.Windows.Structures.SP_DEVICE_INTERFACE_DATA(); data.cbSize = Marshal.SizeOf(data); bool retval = Internal.Windows.Methods.SetupDiEnumDeviceInterfaces(hDevInfo, ref devinfo_data, ref Internal.Windows.Constants.DeviceClassGUID.UsbDevice, memberIndex, out data); int lastError = Internal.Windows.Methods.GetLastError(); if (lastError == 259) { // no more data is available break; } if (lastError != 0) throw new System.ComponentModel.Win32Exception(lastError); listDevs.Add(data); memberIndex++; } devinfo_memberIndex++; } for (int i = 0; i < listDevs.Count; i++) { Internal.Windows.Structures.SP_DEVICE_INTERFACE_DATA data = listDevs[i]; Internal.Windows.Structures.SP_DEVINFO_DATA devinfo_data = new Internal.Windows.Structures.SP_DEVINFO_DATA(); devinfo_data.cbSize = Marshal.SizeOf(devinfo_data); int requiredSize = 0; bool retval = Internal.Windows.Methods.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref data, IntPtr.Zero, 0, out requiredSize, ref devinfo_data); if (!retval) { int lastError = Internal.Windows.Methods.GetLastError(); if (lastError == 87) continue; if (lastError != 0 && lastError != 122) throw new System.ComponentModel.Win32Exception(lastError); } int dummy = 0; IntPtr buffer = Marshal.AllocHGlobal(requiredSize); Internal.Windows.Structures.SP_DEVICE_INTERFACE_DETAIL_DATA detail = new Internal.Windows.Structures.SP_DEVICE_INTERFACE_DETAIL_DATA(); detail.cbSize = Marshal.SizeOf(typeof(Internal.Windows.Structures.SP_DEVICE_INTERFACE_DETAIL_DATA)); Marshal.StructureToPtr(detail, buffer, false); retval = Internal.Windows.Methods.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref data, buffer, requiredSize, out dummy, ref devinfo_data); if (!retval) { int lastError = Internal.Windows.Methods.GetLastError(); if (lastError != 0 && lastError != 122) throw new System.ComponentModel.Win32Exception(lastError); } IntPtr pDevicePath = (IntPtr)((int)buffer + Marshal.SizeOf(typeof(int))); string devicePath = Marshal.PtrToStringAuto(pDevicePath); Marshal.FreeHGlobal(buffer); if (String.IsNullOrEmpty(devicePath)) continue; devicePaths.Add(devicePath); } foreach (string devicePath in devicePaths) { string[] parts = devicePath.Split(new char[] { '#' }); if (parts.Length >= 4) { string pathPrefix = parts[0]; string vendorAndProductId = parts[1]; string[] vendorAndProductIdParts = vendorAndProductId.Split(new char[] { '&' }); string strVendorID = vendorAndProductIdParts[0].Substring(4); string strProductID = vendorAndProductIdParts[1].Substring(4); ushort vendorID = UInt16.Parse(strVendorID, System.Globalization.NumberStyles.HexNumber); ushort productID = UInt16.Parse(strProductID, System.Globalization.NumberStyles.HexNumber); string unknown1 = parts[2]; string deviceClassId = parts[3]; // USBDeviceClass deviceClass = USBDeviceClass.GetByIDs(vendorID, productID); } } break; } } return list.ToArray(); } } }
alcexhim/UniversalDriver
UniversalDriver/USBDevice.cs
C#
gpl-3.0
7,464
package macbury.umbrella.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import macbury.umbrella.managers.IntentsManager; import macbury.umbrella.service.CheckWeatherService; /** * Created by macbury on 27.08.14. */ public abstract class SyncStatusBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { CheckWeatherService.SyncStatus status = (CheckWeatherService.SyncStatus)intent.getSerializableExtra(IntentsManager.EXTRA_SYNC_STATUS); onSyncStatus(status); } public abstract void onSyncStatus(CheckWeatherService.SyncStatus status); }
macbury/umbrella.alert
app/src/main/java/macbury/umbrella/receiver/SyncStatusBroadcastReceiver.java
Java
gpl-3.0
685