answer
stringlengths 15
1.25M
|
|---|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_34) on Thu Jan 07 14:13:59 GMT 2016 -->
<TITLE>
Uses of Class org.apache.fop.render.pdf.<API key> (Apache FOP 2.1 API)
</TITLE>
<META NAME="date" CONTENT="2016-01-07">
<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="Uses of Class org.apache.fop.render.pdf.<API key> (Apache FOP 2.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/pdf/<API key>.html" title="class in org.apache.fop.render.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/pdf//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<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>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.fop.render.pdf.<API key></B></H2>
</CENTER>
No usage of org.apache.fop.render.pdf.<API key>
<P>
<HR>
<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="<API key>"></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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/pdf/<API key>.html" title="class in org.apache.fop.render.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/pdf//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<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>
<HR>
Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
|
<div id="configForm">
<ul>
<li><a href="#general">General</a></li>
<li><a href="#content">Downloaders</a></li>
<li><a href="#providers">Providers</a></li>
<li><a href="#quality">Quality</a></li>
<li><a href="#renaming">Renaming</a></li>
<li><a href="#extra">Extras</a></li>
<li><a href="#notifications">Notifications</a></li>
<li><a href="#userscript">Userscript</a></li>
<li><a href="#iphone">iPhone</a></li>
<li><a href="#about">About</a></li>
</ul>
<form class="uniForm" action="${url(controller="config", action="save")}" method="post">
<div class="group general">
<fieldset class="inlineLabels">
<h3>General (need manual restart)</h3>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="global.host" value="${config.get('global', 'host')}" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Port</label>
<input type="text" name="global.port" value="${config.get('global', 'port')}" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="global.username" value="${config.get('global', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="global.password" value="${config.get('global', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Launch browser</label>
<input type="checkbox" name="global.launchbrowser" value="True" ${' checked="checked"' if config.get('global', 'launchbrowser') else ''} />
</div>
<div class="ctrlHolder checkbox">
<label>Use updater</label>
<input type="checkbox" name="global.updater" value="True" ${' checked="checked"' if config.get('global', 'updater') else ''} />
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Search</h3>
<div class="ctrlHolder">
<label>Search every</label>
<input type="text" name="Intervals.search" value="${config.get('Intervals', 'search')}" class="textInput xsmall"/> hour(s)
</div>
<div class="ctrlHolder">
<label>Ignore words</label>
<input type="text" name="global.ignoreWords" value="${config.get('global', 'ignoreWords')}" class="textInput large"/>
<p class="formHint">
Comma seperated. NZB/Torrents containing these words are ignored. Example: GERMAN, DUBBED, HDTV
</p>
</div>
<div class="ctrlHolder">
<label>Preferred words</label>
<input type="text" name="global.preferredWords" value="${config.get('global', 'preferredWords')}" class="textInput large"/>
<p class="formHint">
Comma seperated. NZB/Torrents containing these words are preferred. Example: Diamond, BluRay, DTS
</p>
</div>
<div class="ctrlHolder">
<label>Required words</label>
<input type="text" name="global.requiredWords" value="${config.get('global', 'requiredWords')}" class="textInput large"/>
<p class="formHint">
Comma seperated. NZB/Torrents must contain these words. Example: GERMAN, DTS
</p>
</div>
</fieldset>
</div>
<div class="group content">
<fieldset class="inlineLabels" id="nzbsFieldset">
<h3>NZBs</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZB.enabled" value="True" ${' checked="checked"' if config.get('NZB', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Retention</label>
<input type="text" name="NZB.retention" value="${config.get('NZB', 'retention')}" class="textInput xsmall"/> day(s)
</div>
<div class="ctrlHolder">
<label for="nzbSendTo">Download to</label>
<select name="NZB.sendTo" id="nzbSendTo" class="textInput large">
% for sendTo in ['Sabnzbd','Blackhole','Nzbget']:
<option value="${sendTo}"${' selected="selected"' if str(sendTo) == config.get('NZB', 'sendTo') else ''}>${sendTo}</option>
% endfor
</select>
</div>
<div class="sabnzbd sendTonzb">
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="Sabnzbd.host" value="${config.get('Sabnzbd', 'host')}" class="textInput large"/>
<p class="formHint">
Where does SABnzbd run? Usually <i>localhost:8080</i>
</p>
</div>
<div class="ctrlHolder">
<label>Apikey</label>
<input type="text" name="Sabnzbd.apikey" value="${config.get('Sabnzbd', 'apikey')}" class="textInput large"/>
<p class="formHint">
Can be found in general config on SABnzbd
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Sabnzbd.username" value="${config.get('Sabnzbd', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="Sabnzbd.password" value="${config.get('Sabnzbd', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Category</label>
<input type="text" name="Sabnzbd.category" value="${config.get('Sabnzbd', 'category')}" class="textInput large"/>
<p class="formHint">
Category where NZBs should be put.
</p>
</div>
</div>
<div class="nzbblackhole sendTonzb">
<div class="ctrlHolder">
<label>NZB Directory</label>
<input type="text" name="NZB.blackhole" value="${config.get('NZB', 'blackhole')}" class="textInput large"/>
<p class="formHint">
Folder your download program watches for new .nzb files.
</p>
</div>
</div>
<div class="nzbget sendTonzb">
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="Nzbget.host" value="${config.get('Nzbget', 'host')}" class="textInput large" />
<p class="formHint">
Hostname with port. Usually <i>localhost:6789</i>
</p>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="Nzbget.password" value="${config.get('Nzbget', 'password')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
nzbGet password. Default is <i>tegbzn6789</i>
</p>
</div>
<div class="ctrlHolder">
<label>Category</label>
<input type="text" name="Nzbget.category" value="${config.get('Nzbget', 'category')}" class="textInput large"/>
<p class="formHint">
Category where NZBs should be put.
</p>
</div>
</div>
</fieldset>
<fieldset class="inlineLabels" id="torrentsFieldset">
<h3>Torrents</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="Torrents.enabled" value="True" ${' checked="checked"' if config.get('Torrents', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label for="torrentsSendTo">Download to</label>
<select name="Torrents.sendTo" id="torrentsSendTo" class="textInput large">
% for sendTo in ['Transmission','Blackhole']:
<option value="${sendTo}"${' selected="selected"' if str(sendTo) == config.get('Torrents', 'sendTo') else ''}>${sendTo}</option>
% endfor
</select>
</div>
<div class="transmission sendTotorrents">
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="Transmission.host" value="${config.get('Transmission', 'host')}" class="textInput large"/>
<p class="formHint">
Where does Transmission run? Usually <i>localhost:9091</i>
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Transmission.username" value="${config.get('Transmission', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="Transmission.password" value="${config.get('Transmission', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Download Directory</label>
<input type="text" name="Transmission.directory" value="${config.get('Transmission', 'directory')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
Where should Transmission saved the downloaded files?
</p>
</div>
<div class="ctrlHolder">
<label>Seeding ratio</label>
<input type="text" name="Transmission.ratio" value="${config.get('Transmission', 'ratio')}" autocomplete="off" class="textInput xsmall"/>
<p class="formHint">
Stop transfer when reaching ratio
</p>
</div>
</div>
<div class="torrentsblackhole sendTotorrents">
<div class="ctrlHolder">
<label>Torrent Directory</label>
<input type="text" name="Torrents.blackhole" value="${config.get('Torrents', 'blackhole')}" class="textInput large"/>
<p class="formHint">
Your .torrent watch folder
</p>
</div>
</div>
<div class="ctrlHolder">
<label>Wait</label>
<input type="text" name="Torrents.wait" value="${config.get('Torrents', 'wait')}" class="textInput xsmall"/> hour(s) for nzb
<p class="formHint">
Only if NZB download is enabled.
</p>
</div>
</fieldset>
</div>
<div class="group renaming" id="renamingFieldset">
<fieldset class="inlineLabels">
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="Renamer.enabled" value="True" ${' checked="checked"' if config.get('Renamer', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Download folder</label>
<input type="text" name="Renamer.download" value="${config.get('Renamer', 'download')}" class="textInput large"/>
<p class="formHint">
Your SABnzbd movie download folder
</p>
</div>
<div class="ctrlHolder">
<label>Movie destination</label>
<input type="text" name="Renamer.destination" value="${config.get('Renamer', 'destination')}" class="textInput large"/>
<p class="formHint">
Where the movies should be moved to. <br />
Should NOT be the same as the "Download folder".
</p>
</div>
<div class="ctrlHolder">
<label>Folder naming</label>
<input type="text" name="Renamer.foldernaming" value="${config.get('Renamer', 'foldernaming').replace('<', '<').replace('>', '>')}" class="textInput large"/>
<p class="formHint">
<span id="foldernameResult"><strong>Result</strong>: ${foldernameResult}</span>
<span style="color:red;">Use <strong>at least</strong> the movie name like <thename>/<namethe> in your foldername, or the world is going to end and lots of movies might get deleted..</span>
</p>
</div>
<div class="ctrlHolder">
<label>File naming</label>
<input type="text" name="Renamer.filenaming" value="${config.get('Renamer', 'filenaming').replace('<', '<').replace('>', '>')}" class="textInput large"/>
<p class="formHint">
<span id="filenameResult"><strong>Result</strong>: ${filenameResult}</span><br />
<a href="#" onclick="return false" id="<API key>">Show naming-options</a>
</p>
<p class="formHint" id="fileRenameOptions" style="display: none">
<span><strong>original</strong>: The.Big.Lebowski.1998.1080p.BluRay.x264.DTS-GROUP</span><br />
<span><strong>thename</strong>: The Big Lebowski</span><br />
<span><strong>namethe</strong>: Big Lebowski, The</span><br />
<span><strong>ext</strong>: mkv</span><br />
<span><strong>year</strong>: 2008</span><br />
<span><strong>quality</strong>: 1080p</span><br />
<span><strong>group</strong>: GROUP</span><br />
<span><strong>audio</strong>: DTS</span><br />
<span><strong>video</strong>: x264</span><br />
<span><strong>sourcemedia</strong>: BluRay</span><br />
<span><strong>resolution</strong>: 1920x1080</span><br />
<span><strong>first</strong>: B (First character of movie (without "The"))</span><br />
Only with multiple files:
<span><strong>cd</strong>: cd1</span>
<span><strong>cdNr</strong>: 1</span>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Post-Processing Script</label>
<input type="checkbox" name="Renamer.script_enabled" value="True" ${' checked="checked"' if config.get('Renamer', 'script_enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>File Path</label>
<input type="text" name="Renamer.file_path" value="${config.get('Renamer','file_path')}" class="textInput large"/>
<p class="formHint">
Relative file path to your extra script (starting from CouchPotato install folder)
</p>
</div>
</fieldset>
</fieldset>
<fieldset class="inlineLabels">
<div class="ctrlHolder">
<label>Name separator</label>
<select name="Renamer.separator" class="textInput large">
% for sep, label in {' ':'space', '.':'dot', '-':'dash'}.iteritems():
<option value="${sep}"${' selected="selected"' if sep == config.get('Renamer', 'separator') else ''}>${label}</option>
% endfor
</select>
<p class="formHint">
Replace all the spaces with dots or dashes.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Cleanup</label>
<input type="checkbox" name="Renamer.cleanup" value="True" ${' checked="checked"' if config.get('Renamer', 'cleanup') else ''} />
<p class="formHint">
Remove leftover files/folders in the Download folder.
</p>
</div>
</fieldset>
</div>
<div class="group providers">
<fieldset class="inlineLabels" id="newzbinFieldset">
<h3>Newzbin</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="newzbin.enabled" value="True" ${' checked="checked"' if config.get('newzbin', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="newzbin.username" value="${config.get('newzbin', 'username')}" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="newzbin.password" value="${config.get('newzbin', 'password')}" class="textInput large"/>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nzbmatrixFieldset">
<h3>NZBMatrix.com</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZBMatrix.enabled" value="True" ${' checked="checked"' if config.get('NZBMatrix', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="NZBMatrix.username" value="${config.get('NZBMatrix', 'username')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbmatrix.com/account.php" target="_blank">here</a>, "User Name"
</p>
</div>
<div class="ctrlHolder">
<label>Apikey</label>
<input type="text" name="NZBMatrix.apikey" value="${config.get('NZBMatrix', 'apikey')}" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbmatrix.com/account.php" target="_blank">here</a>, "Current API Key" <br />
You have to be VIP to get an API Key (Hey, that rhymes!).
</p>
</div>
<div class="ctrlHolder checkbox">
<label>English only</label>
<input type="checkbox" name="NZBMatrix.english" value="True" ${' checked="checked"' if config.get('NZBMatrix', 'english') else ''} />
<p class="formHint">
Restrict search to English or unknown NZBs.
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="newznabFieldset">
<h3>Newznab</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="newznab.enabled" value="True" ${' checked="checked"' if config.get('newznab', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="newznab.host" value="${config.get('newznab', 'host')}" class="textInput large"/>
<p class="formHint">
The hostname of your newznab provider. Example: "provider.com" or "provider.com/newznab".
</p>
</div>
<div class="ctrlHolder">
<label>Apikey</label>
<input type="text" name="newznab.apikey" value="${config.get('newznab', 'apikey')}" class="textInput large"/>
<p class="formHint">
Can be found after login on the "API" page, bottom left. The string after "&apikey=".
</p>
</div>
<p class="formHint">
More info can be found at <a href="http://newznab.com" target="_blank">Newznab.com</a>.
</p>
</fieldset>
<fieldset class="inlineLabels" id="nzbsorgFieldset">
<h3>NZBs.org</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZBsorg.enabled" value="True" ${' checked="checked"' if config.get('NZBsorg', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Id</label>
<input type="text" name="NZBsorg.id" value="${config.get('NZBsorg', 'id')}" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbs.org/index.php?action=rss" target="_blank">here</a>, number after "&i="
</p>
</div>
<div class="ctrlHolder">
<label>Key</label>
<input type="text" name="NZBsorg.key" value="${config.get('NZBsorg', 'key')}" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbs.org/index.php?action=rss" target="_blank">here</a>, string after "&h="
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nzbsrusFieldset">
<h3>NZBsRus.com</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZBsRUS.enabled" value="True" ${' checked="checked"' if config.get('NZBsRUS','enabled') else''} />
</div>
<div class="ctrlHolder">
<label>Id</label>
<input type="text" name="NZBsRUS.userid" value="${config.get('NZBsRUS', 'userid')}" class="textInput large" />
<p class="formHint">
Can be found at the bottom of <a href="https:
</p>
</div>
<div class="ctrlHolder">
<label>Hash</label>
<input type="text" name="NZBsRUS.userhash" value="${config.get('NZBsRUS', 'userhash')}" class="textInput large" />
<p class="formHint">
Can be found at the bottom of <a href="https:
</p>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>#alt.binaries.hdtv.x264@EFnet</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="x264.enabled" value="True" ${' checked="checked"' if config.get('x264','enabled') else''} />
<p class="formHint">
HD movies only
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" style="float: right!important;"> <!--Temp layout fix
<h3>MysterBin</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="mysterbin.enabled" value="True" ${' checked="checked"' if config.get('mysterbin','enabled') else''} />
<p class="formHint">
Web Search provider
</p>
</div>
</fieldset>
</div>
<div class="group userscript">
<fieldset class="inlineLabels">
<a href="${baseUrl}CouchPotato.user.js" class="submit userscriptInstall"><img src="${baseUrl}media/images/userscriptPreview.png" /><br />Install UserScript</a>
<p style="font-size:11px">
To use this UserScript, you need <a href="http:
</p>
<p style="font-size:11px">If you're on Safari, see <a href="http://couchpotato.fafoulon.fr/" target="_blank">this (unsupported) Safari extension by Fafoulon</a></p>
</fieldset>
</div>
<div class="group iphone">
<fieldset class="inlineLabels">
<div>Got a jailbroken iPhone? Get the iCouchPotato app on Cydia! <span>(Add our Cydia repo: "<strong>http://cydia.myrepospace.com/couchpotato/</strong>" and search for "<strong>iCouchPotato</strong>")</span></div>
<img src="${baseUrl}media/images/iphone1.png" /><img src="${baseUrl}media/images/iphone2.png" /><img src="${baseUrl}media/images/iphone3.png" />
<div>Why isn't it in the normal Appstore you ask? Because Apple is being a bitch!</div>
</fieldset>
</div>
<div class="group about">
<fieldset class="inlineLabels">
<div>
<a href="${url(controller='config',action='exit')}" class="submit">Shutdown</a><span class="or">or</span>
<a href="${url(controller='config',action='restart')}" class="submit restart">Restart</a>
</div>
<div class="site">
<p>
Need help, got a question or problem?<br />
<a href="http://couchpotato.tenderapp.com/" target="_blank">Find help on the Support Forum</a>
</p>
</div>
<div class="site" style="margin:40px 0 0; font-size: 20px;">
<div>Don't have a usenet account yet? Check these out: </div>
<a href="https://usenetserver.com/partners/?a_aid=couchpotato&a_bid=3f357c6f">UsenetServer</a>,
<a href="http:
<a href="http://easynews.com/free-account?a_aid=couchpotato&a_bid=443b8133">14 day free Easynews trial</a> -->
<span style="color:#aaa; font-size: 15px;">Help support CouchPotato and save some money for yourself by signing up for an account!</span>
</div>
<div id="donate">
<div>I'm building CouchPotato in my spare time, so if you want to buy me a coke while I'm coding, that would be awesome!</div>
<div>PayPal is playing internet police and blocked my account. But you can send me an awesome 'thank you' email instead ;)</div>
</div>
<div class="site">
<a href="http://couchpotatoapp.com" target="_blank">CouchPotatoApp.com</a>
</div>
<div id="versionInfo">
<h3>Version ${updater.getVersion()}</h3>
% if updater.useUpdater():
<a href="${url(controller='config', action='checkForUpdate')}">Check for new version</a>
% endif
</div>
</fieldset>
</div>
<div class="group quality">
<fieldset class="inlineLabels qualityTemplates">
<h3>Quality Profile</h3>
<div>
<a href="#" id="newTemplate">Create a new quality profile.</a>
</div>
<p class="formHint">
Create a list of qualities CouchPotato should go through when searching for a movie.
It will try and download from top to bottom. Using the finish-checkbox will mark the movie as "completed" when this quality is found.
<img src="${baseUrl}media/images/<API key>.png"><br />
When adding a movie, you have to select this profile inside the quality list, so give it a nice name.
</p>
<div class="customList"></div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Default Qualities</h3>
<div class="ctrlHolder">
<label>Default quality</label>
<select name="Quality.default" class="textInput large">
% for qualityItem in Qualities.all():
<option value="${qualityItem.name}"${' selected="selected"' if qualityItem.name == config.get('Quality', 'default') else ''}>${qualityItem.label}</option>
% endfor
</select>
</div>
<div class="ctrlHolder">
<label>Order & hide</label>
<div class="standardQualities">
<% hide = Qualities.conf('hide') %>
<input type="hidden" name="Quality.order" value="" />
<input type="hidden" name="Quality.hide" value="" />
% for template in Qualities.all():
<div class="item" data-id="${template.id}" data-name="${template.name}">
<input type="checkbox" ${' checked="checked"' if not str(template.name) in hide else ''} />
<span class="label">${template.label}</span>
<span class="handle"></span>
</div>
% endfor
</div>
</div>
</fieldset>
<fieldset class="inlineLabels qualitySizes right">
<h3>Quality sizes</h3>
<p class="formHint">
Only download the quality that is between these two sizes.<br />
All that are outside these sizes, will be ignored.
</p>
<div class="ctrlHolder">
<span class="size header">
<span>Minimum</span>
<span>Maximum</span>
</span>
</div>
% for key, quality in Qualities.getTypes():
<div class="ctrlHolder">
<label>${quality['label']}</label>
<span class="size">
<span><input type="text" name="Quality.sMin-${key}" value="${config.get('Quality', 'sMin-'+key)}" class="textInput small"/>MB</span>
<span><input type="text" name="Quality.sMax-${key}" value="${config.get('Quality', 'sMax-'+key)}" class="textInput small"/>MB</span>
</span>
</div>
% endfor
</fieldset>
</div>
<div class="group extra">
<fieldset class="inlineLabels">
<h3>Blu-Ray.com RSS</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="MovieRSS.enabled" value="True" ${' checked="checked"' if config.get('MovieRSS', 'enabled') else ''} />
<p class="formHint">
This will magically add movies to your wanted list that match the options below.
</p>
</div>
<div class="ctrlHolder">
<label>Minimum movie year</label>
<input type="text" name="MovieRSS.minyear" value="${config.get('MovieRSS', 'minyear')}" class="textInput large"/>
<p class="formHint">
Movies released after and including this year will be added to the wanted list
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB rating</label>
<input type="text" name="MovieRSS.minrating" value="${config.get('MovieRSS','minrating')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB rating for a movie to be added
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB votes</label>
<input type="text" name="MovieRSS.minvotes" value="${config.get('MovieRSS','minvotes')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB votes for a movie to be added
</p>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Kinepolis.com RSS</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="KinepolisRSS.enabled" value="True" ${' checked="checked"' if config.get('KinepolisRSS', 'enabled') else ''} />
<p class="formHint">
This will magically add movies to your wanted list that match the options below.
</p>
</div>
<div class="ctrlHolder">
<label>Minimum movie year</label>
<input type="text" name="KinepolisRSS.minyear" value="${config.get('KinepolisRSS', 'minyear')}" class="textInput large"/>
<p class="formHint">
Movies released after and including this year will be added to the wanted list
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB rating</label>
<input type="text" name="KinepolisRSS.minrating" value="${config.get('KinepolisRSS','minrating')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB rating for a movie to be added
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB Votes</label>
<input type="text" name="KinepolisRSS.minvotes" value="${config.get('KinepolisRSS','minvotes')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB votes for a movie to be added
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="subtitleFieldset">
<h3>Subtitles</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="Subtitles.enabled" value="True" ${' checked="checked"' if config.get('Subtitles', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Language</label>
<input type="text" name="Subtitles.languages" value="${config.get('Subtitles', 'languages')}" class="textInput large"/>
<p class="formHint">
Comma seperated 2-letter language code (<a href="http://en.wikipedia.org/wiki/<API key>" target="_blank">ISO 639-1</a>). <br />
Example: "en, nl". Most importent first.
</p>
</div>
<div class="ctrlHolder">
<label>Naming</label>
<select name="Subtitles.name" class="textInput large">
<option value="filename"${' selected="selected"' if 'filename' == config.get('Subtitles', 'name') else ''}>filename.ext</option>
<option value="subtitle"${' selected="selected"' if 'subtitle' == config.get('Subtitles', 'name') else ''}>subtitle.ext</option>
</select>
<p class="formHint">
"There Will Be Blood.srt" or "Subtitle.srt"
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Add language to name</label>
<input type="checkbox" name="Subtitles.addLanguage" value="True" ${' checked="checked"' if config.get('Subtitles', 'addLanguage') else ''} />
<p class="formHint">
Add language shortcode to end of subtitle name. Example: "There Will Be Blood.en.srt"
</p>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Trailers</h3>
<div class="ctrlHolder">
<label>Download trailer</label>
<select name="Trailer.quality" class="textInput large">
<option value="">None</option>
% for format in trailerFormats:
<option value="${format}"${' selected="selected"' if format == config.get('Trailer', 'quality') else ''}>${format}</option>
% endfor
</select>
<p class="formHint">
If None, no trailer will be downloaded.
</p>
</div>
<div class="ctrlHolder">
<label>Naming</label>
<select name="Trailer.name" class="textInput large">
<option value="movie-trailer"${' selected="selected"' if 'movie-trailer' == config.get('Trailer', 'name') else ''}>movie-trailer.ext</option>
<option value="moviename-trailer"${' selected="selected"' if 'moviename-trailer' == config.get('Trailer', 'name') else ''}><filename>-trailer.ext</option>
</select>
</div>
</fieldset>
<fieldset class="inlineLabels" id="traktFieldset">
<h3>Trakt</h3>
<div class="ctrlHolder">
<label>Trakt Username</label>
<input type="text" name="Trakt.username" value="${config.get('Trakt','username')}" class="textInput large"/>
<p class="formHint">
Your Trakt username
</p>
</div>
<div class="ctrlHolder">
<label>Trakt Password</label>
<input type="password" name="Trakt.password" value="${config.get('Trakt', 'password')}" class="textInput large"/>
<p class="formHint">
Your Trakt Password
</p>
</div>
<div class="ctrlHolder">
<label>Trakt API Key</label>
<input type="text" name="Trakt.apikey" value="${config.get('Trakt', 'apikey')}" class="textInput large"/>
<p class="formHint">
Get your key at: <a href="http:
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Grab movies from watchlist</label>
<input type="checkbox" name="Trakt.watchlist_enabled" value="True" ${' checked="checked"' if config.get('Trakt', 'watchlist_enabled') else ''} />
<p class="formHint">
This will add movies from your Trakt watchlist.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Ignore Movies in Trakt Collection</label>
<input type="checkbox" name="Trakt.dontaddcollection" value="True" ${' checked="checked"' if config.get('Trakt', 'dontaddcollection') else ''} />
<p class="formHint">
Don't add movies to CouchPotato from watchlist that are already in Trakt collection
</p>
</div>
<div class="ctrlHolder">
<a href="#traktTest" id="traktTest" class="testNotification">Send a message to Trakt, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Metadata</h3>
<div class="ctrlHolder checkbox">
<label>Save metadata</label>
<input type="checkbox" name="Meta.enabled" value="True" ${' checked="checked"' if config.get('Meta', 'enabled') else ''} />
<p class="formHint">
Thumbnail, poster and .nfo file.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Save URL Only</label>
<input type="checkbox" name="Meta.urlonly" value="True" ${' checked="checked"' if config.get('Meta', 'urlonly') else ''} />
<p class="formHint">Save only the IMBD Url in the nfo file
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Fanart Filename</label>
<input type="text" name="Meta.fanartfilename" value="${config.get('Meta','fanartfilename')}" class="textInput large"/>
</div>
<div class="ctrlHolder checkbox">
<label>Poster Filename</label>
<input type="text" name="Meta.posterfilename" value="${config.get('Meta','posterfilename')}" class="textInput large"/>
</div>
<div class="ctrlHolder checkbox">
<label>NFO Filename</label>
<input type="text" name="Meta.nfofilename" value="${config.get('Meta','nfofilename')}" class="textInput large"/>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>MovieETA</h3>
<div class="ctrlHolder checkbox">
<label>Check VideoETA</label>
<input type="checkbox" name="MovieETA.enabled" value="True" ${' checked="checked"' if config.get('MovieETA', 'enabled') else ''} />
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>IMDB Watchlists</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="IMDBWatchlist.enabled" value="True" ${' checked="checked"' if config.get('IMDBWatchlist', 'enabled') else ''} />
<p class="formHint">
This will magically add movies to your wanted list that appear in public IMDB Watchlist(s) specified below.
</p>
</div>
<div class="ctrlHolder">
<label>IMDB Watchlist URL(s)</label>
<textarea name="IMDBWatchlist.url" cols="50" rows="5" class="textInput large">${config.get('IMDBWatchlist', 'url')}</textarea>
<p class="formHint">
Comma separated list of 'Export this list' links from the public IMDB Watchlist pages
</p>
</div>
</fieldset>
</div>
<div class="group notifications">
<fieldset class="inlineLabels" id="xbmcFieldset">
<h3>XBMC</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="XBMC.enabled" value="True" ${' checked="checked"' if config.get('XBMC', 'enabled') else ''} />
<p class="formHint">
Sends a notification and updates your XBMC library.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="XBMC.onSnatch" value="True" ${' checked="checked"' if config.get('XBMC', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="XBMC.host" value="${config.get('XBMC', 'host')}" class="textInput large"/>
<p class="formHint">
Including port. Example: 192.168.1.20:8080
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="XBMC.username" value="${config.get('XBMC', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="XBMC.password" value="${config.get('XBMC', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<a href="#xbmcTest" id="xbmcTest" class="testNotification">Send a message to XBMC, see if it works.</a>
</div>
<div class="ctrlHolder">
<label>DB Path</label>
<input type="text" name="XBMC.dbpath" value="${config.get('XBMC', 'dbpath')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
Used for checking if you already have a movie in your library, before adding it to your wanted list.
Example: C:\Users\Username\AppData\Roaming\XBMC\userdata\Database
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Use web API</label>
<input type="checkbox" name="XBMC.<API key>" value="True" ${' checked="checked"' if config.get('XBMC', '<API key>') else ''} />
<p class="formHint">
Whether to use web API against XBMC hosts to check if you have a movie in your library before adding it to your wanted list.
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nmjFieldset">
<h3>Networked Media Jukebox</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="NMJ.enabled" value="True" ${' checked="checked"' if config.get('NMJ', 'enabled') else ''} />
<p class="formHint">
Updates your NMJ library.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="NMJ.host" value="${config.get('NMJ', 'host')}" class="textInput large NMJhost"/>
<p class="formHint">
Example: 192.168.1.20
</p>
</div>
<div class="ctrlHolder">
<a href="#nmjAuto" id="nmjAuto" class="testNotification">Autodetect NMJ Database and mount</a>
<p class="formHint">
Popcorn Hour needs to be on, and NMJ must be running.
</p>
</div>
<div class="ctrlHolder">
<label>NMJ Database</label>
<input type="text" name="NMJ.database" value="${config.get('NMJ', 'database')}" autocomplete="off" class="textInput large NMJdatabase" />
<p class="formHint">
Path to the NMJ Database.
</p>
</div>
<div class="ctrlHolder">
<label>NMJ Mount URL</label>
<input type="text" name="NMJ.mount" value="${config.get('NMJ', 'mount')}" autocomplete="off" class="textInput large NMJmount"/>
<p class="formHint">
Only needed when the database is on a network path.
</p>
</div>
<div class="ctrlHolder">
<a href="#nmjTest" id="nmjTest" class="testNotification">Update the NMJ database, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="plexFieldset">
<h3>Plex Media Server</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="PLEX.enabled" value="True" ${' checked="checked"' if config.get('PLEX', 'enabled') else ''} />
<p class="formHint">
Updates your Plex library.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="PLEX.host" value="${config.get('PLEX', 'host')}" class="textInput large PLEXhost"/>
<p class="formHint">
Including port. Example: 192.168.1.20:32400
</p>
</div>
<div class="ctrlHolder">
<a href="#plexTest" id="plexTest" class="testNotification">Update the Plex database, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="prowlFieldset">
<h3>Prowl</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="PROWL.enabled" value="True" ${' checked="checked"' if config.get('PROWL', 'enabled') else ''} />
<p class="formHint">
Sends a notification to Prowl
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="PROWL.onSnatch" value="True" ${' checked="checked"' if config.get('PROWL', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Keys</label>
<input type="text" name="PROWL.keys" value="${config.get('PROWL', 'keys')}" class="textInput large"/>
<p class="ctrlHolder">
<a href="https:
</p>
</div>
<div class="ctrlHolder">
<label>Priority</label>
<select name="PROWL.priority" class="textInput large">
<option value="-2"${' selected="selected"' if config.get('PROWL', 'priority') == '-2' else ''}>Very Low</option>
<option value="-1"${' selected="selected"' if config.get('PROWL', 'priority') == '-1' else ''}>Moderate</option>
<option value="0"${' selected="selected"' if config.get('PROWL', 'priority') == '0' else ''}>Normal</option>
<option value="1"${' selected="selected"' if config.get('PROWL', 'priority') == '1' else ''}>High</option>
<option value="2"${' selected="selected"' if config.get('PROWL', 'priority') == '2' else ''}>Emergency</option>
</select>
</div>
<div class="ctrlHolder">
<a href="#prowlTest" id="prowlTest" class="testNotification">Send a message to Prowl, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="growlFieldset">
<h3>Growl</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="GROWL.enabled" value="True" ${' checked="checked"' if config.get('GROWL', 'enabled') else ''} />
<p class="formHint">
Sends a notification to Growl.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="GROWL.onSnatch" value="True" ${' checked="checked"' if config.get('GROWL', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="GROWL.host" value="${config.get('GROWL', 'host')}" class="textInput large"/>
<p class="formHint">
Example: 192.168.1.20
</p>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="GROWL.password" value="${config.get('GROWL', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<a href="#growlTest" id="growlTest" class="testNotification">Send a message to Growl, see if it works.</a>
</div>
<p class="ctrlHolder formHint">
Be sure to enable "Listen for incoming notifications" in your Growl Settings, under Network.
</p>
</fieldset>
<fieldset class="inlineLabels" id="notifoFieldset">
<h3>Notifo</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Notifo.enabled" value="True" ${' checked="checked"' if config.get('Notifo', 'enabled') else ''} />
<p class="formHint">
Sends a notification to Notifo
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="Notifo.onSnatch" value="True" ${' checked="checked"' if config.get('Notifo', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Notifo.username" value="${config.get('Notifo', 'username')}" class="textInput large" />
</div>
<div class="ctrlHolder">
<label>API Secret</label>
<input type="text" name="Notifo.key" value="${config.get('Notifo', 'key')}" class="textInput large" />
<p class="formHint">
Get your API secret at:
<a href="http:
</p>
</div>
<div class="ctrlHolder">
<a href="#notifoTest" id="notifoTest" class="testNotification">Send a message to Notifo, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="boxcarFieldset">
<h3>Boxcar</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Boxcar.enabled" value="True" ${' checked="checked"' if config.get('Boxcar', 'enabled') else ''} />
<p class="formHint">
Sends a notification to <a href="http://boxcar.io/" target="blank">Boxcar</a>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="Boxcar.onSnatch" value="True" ${' checked="checked"' if config.get('Boxcar', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Boxcar.username" value="${config.get('Boxcar', 'username')}" class="textInput large" />
</div>
<div class="ctrlHolder">
<a href="#boxcarTest" id="boxcarTest" class="testNotification">Send a message to Boxcar, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nmaFieldset">
<h3>NotifyMyAndroid</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="NMA.enabled" value="True" ${' checked="checked"' if config.get('NMA', 'enabled') else ''} />
<p class="formHint">
Sends a notification to NotifyMyAndroid
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="NMA.onSnatch" value="True" ${' checked="checked"' if config.get('NMA', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>API Key</label>
<input type="text" name="NMA.apikey" value="${config.get('NMA', 'apikey')}" class="textInput large" />
<p class="formHint">
Multiple keys must be seperated by a , (comma). Up to a maximum of 5
</p>
</div>
<div class="ctrlHolder">
<a href="#nmaTest" id="nmaTest" class="testNotification">Send a message to NotifyMyAndroid, see if it works.</a>
</div>
<div class="ctrlHolder">
<label>Priority</label>
<select name="NMA.priority" class="textInput large">
<option value="-2"${' selected="selected"' if config.get('NMA', 'priority') == '-2' else ''}>Very Low</option>
<option value="-1"${' selected="selected"' if config.get('NMA', 'priority') == '-1' else ''}>Moderate</option>
<option value="0"${' selected="selected"' if config.get('NMA', 'priority') == '0' else ''}>Normal</option>
<option value="1"${' selected="selected"' if config.get('NMA', 'priority') == '1' else ''}>High</option>
<option value="2"${' selected="selected"' if config.get('NMA', 'priority') == '2' else ''}>Emergency</option>
</select>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nmwpFieldset">
<h3><API key></h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="NMWP.enabled" value="True" ${' checked="checked"' if config.get('NMWP', 'enabled') else ''} />
<p class="formHint">
Sends a notification to <a href="https://<API key>.com"><API key>.com</a>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="NMWP.onSnatch" value="True" ${' checked="checked"' if config.get('NMWP', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>API Key</label>
<input type="text" name="NMWP.apikey" value="${config.get('NMWP', 'apikey')}" class="textInput large" />
<p class="formHint">
Multiple keys must be seperated by a , (comma). Up to a maximum of 5
</p>
</div>
<div class="ctrlHolder">
<a href="#nmwpTest" id="nmwpTest" class="testNotification">Send a message to <API key>, see if it works.</a>
</div>
<div class="ctrlHolder">
<label>Priority</label>
<select name="NMWP.priority" class="textInput large">
<option value="-2"${' selected="selected"' if config.get('NMWP', 'priority') == '-2' else ''}>Very Low</option>
<option value="-1"${' selected="selected"' if config.get('NMWP', 'priority') == '-1' else ''}>Moderate</option>
<option value="0"${' selected="selected"' if config.get('NMWP', 'priority') == '0' else ''}>Normal</option>
<option value="1"${' selected="selected"' if config.get('NMWP', 'priority') == '1' else ''}>High</option>
<option value="2"${' selected="selected"' if config.get('NMWP', 'priority') == '2' else ''}>Emergency</option>
</select>
</div>
</fieldset>
<fieldset class="inlineLabels" id="twitterFieldset">
<h3>Twitter</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Twitter.enabled" value="True" ${' checked="checked"' if config.get('Twitter', 'enabled') else ''} />
<p class="formHint">
Sends a notification on Twitter.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="Twitter.onSnatch" value="True" ${' checked="checked"' if config.get('Twitter', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
% if not config.get('Twitter', 'isAuthenticated'):
<div class"ctrlHolder">
<a href="${url(controller='config', action='twitterReqAuth')}" class="testNotification">Request Authorization</a>
</div>
% endif
<div class="ctrlHolder">
<a href="#twitterTest" id="twitterTest" class="testNotification">Send a notification on Twitter, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="synoIndexFieldset">
<h3>Synology Media Server</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Synoindex.enabled" value="True" ${' checked="checked"' if config.get('Synoindex', 'enabled') else ''} />
<p class="formHint">
Automaticly adds index to Synology Media Server.
</p>
</div>
<p class="ctrlHolder formHint">
This only works if CP is running on a Synology NAS.
</p>
</fieldset>
<fieldset class="inlineLabels" id="<API key>">
<h3>Trakt</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="Trakt.<API key>" value="True" ${' checked="checked"' if config.get('Trakt', '<API key>') else ''} />
<p class="formHint">
Sends a notification and updates your Trakt library. You must fill out the username and password in the extras tab for this to work.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Remove from watchlist</label>
<input type="checkbox" name="Trakt.watchlist_remove" value="True" ${' checked="checked"' if config.get('Trakt', 'watchlist_remove') else ''} />
<p class="formHint">
Removes the downloaded movie from your Trakt watchlist.
</p>
</div>
</fieldset>
</div>
<div class="buttonHolder">
<span class="cancel"><a href="#cancel">Cancel</a> or</span>
<button type="submit" class="primaryAction">
Save »
</button>
</div>
</form>
</div>
<script type="text/javascript">
var form = $('configForm').getElement('form');
window.addEvent('domready', function(){
// Quality sorting and hiding
var sq = form.getElement('.standardQualities')
var <API key> = function(){
data = []
hide = []
sq.getElements('.item').each(function(el){
var checkbox = el.getElement('input[type=checkbox]')
var label = el.getElement('.label')
label.setStyle('opacity', 1)
data.append([el.get('data-id')])
if (!checkbox.get('checked')){
hide.append([el.get('data-name')])
label.setStyle('opacity', 0.6)
}
})
sq.getElement('input[name=Quality.order]').set('value', data)
sq.getElement('input[name=Quality.hide]').set('value', hide)
}
sq.getElements('.item input[type=checkbox]').addEvent('click', <API key>)
var qualitySortable = new Sortables(sq, {
'revert': true,
'clone': true,
'handle': '.handle',
'opacity': 0.5,
'onComplete': <API key>
});
<API key>()
var qt = form.getElement('.qualityTemplates')
<%
import json
types = json.dumps(dict([(v['order'], v) for k, v in Qualities.getTypes()]))
templates = json.dumps(Qualities.getTemplates())
%>
var q = new Quality(qt, ${types}, ${templates});
$('newTemplate').addEvent('click', function(e){
(e).stop()
q.add({
'id':0,
'name': 'New Quality',
'waitFor': 0,
'types': [{
'type':'720p',
'markComplete': true
}]
})
})
var <API key> = form.getElement('a[id=<API key>]')
var <API key> = function(){
var field = form.getElement('p[id=fileRenameOptions]')
if(field.getStyle('display') != 'none'){
field.setStyle('display', 'none')
<API key>.innerText = "Show naming-options"
}
else{
field.setStyle('display', 'block')
<API key>.innerText = "Hide naming-options"
}
}
<API key>.addEvent('click', <API key>)
// Replace Userscript IE
if (Browser.ie){
form.getElement('.userscript fieldset a').setStyle('display', 'none')
}
// Get host and post with Userscript
var usButton = $('configForm').getElement('.userscriptInstall')
usButton.set('href', usButton.get('href')+'?host='+location.href.replace('config/', '')+'&type=CouchPotato.user.js')
// Match label to input, cause i'm lazy
form.getElements('label').each(function(el, nr){
if(!el.get('for')){
var id = 'formItem-'+nr
el.set('for', id)
el.getNext().set('id', id)
}
});
// Form highlight
new Uniform();
// Renaming disabled stuff
var isEnabled = function(checkbox, fieldset){
if (checkbox.get('checked'))
fieldset.getElements('.ctrlHolder').setStyle('opacity', 1)
else {
var first = fieldset.getElement('.ctrlHolder');
fieldset.getElements('.ctrlHolder').each(function(el){
if(el != first) el.setStyle('opacity', 0.5)
});
}
}
Array.each(['renamingFieldset','torrentsFieldset','nzbsFieldset','nzbmatrixFieldset','nzbsorgFieldset','newznabFieldset','subtitleFieldset', 'xbmcFieldset', 'nmjFieldset', 'plexFieldset', 'prowlFieldset', 'growlFieldset', 'notifoFieldset', 'boxcarFieldset', 'nmaFieldset', 'twitterFieldset', 'synoIndexFieldset', '<API key>'],function(item){
var fieldset = $(item)
var checkbox = fieldset.getElement('[type=checkbox]')
isEnabled(checkbox, fieldset)
checkbox.addEvent('change', function(){
isEnabled(checkbox, fieldset)
});
})
// hide unused sendto for nzb
var sendToSelectnzb = $('nzbSendTo')
var sendTonzb = function(){
form.getElements('.sendTonzb').setStyle('display', 'none')
if (sendToSelectnzb.get('value') == 'Sabnzbd')
form.getElement('.sabnzbd').setStyle('display', 'block')
else if (sendToSelectnzb.get('value') == 'Nzbget')
form.getElement('.nzbget').setStyle('display', 'block')
else
form.getElement('.nzbblackhole').setStyle('display', 'block')
}
sendToSelectnzb.addEvent('change', sendTonzb);
sendTonzb();
// hide unused sendto for torrents
var <API key> = $('torrentsSendTo')
var sendTotorrents = function(){
form.getElements('.sendTotorrents').setStyle('display', 'none')
if (<API key>.get('value') == 'Transmission')
form.getElement('.transmission').setStyle('display', 'block')
else
form.getElement('.torrentsblackhole').setStyle('display', 'block')
}
<API key>.addEvent('change', sendTotorrents);
sendTotorrents();
// Cancel button
form.getElements('.cancel a').addEvent('click', function(e){
(e).stop()
history.back();
});
// Shutdown button
form.getElements('.about a.submit').addEvent('click', function(e){
(e).stop()
new Spinner(e.target).show();
new Request({
'url': e.target.get('href'),
'onComplete': function(){
if (e.target.get('text') == 'Restart')
e.target.getParent().set('text', 'CouchPotato will restart in a few seconds.')
else
e.target.getParent().set('text', 'CouchPotato has shutdown.')
new Spinner(e.target).hide();
}
}).send()
});
// Menu
$('configForm').getElements('ul a').addEvent('click', function(e){
(e).stop()
showForm(e.target, e.target.get('href').substr(1))
});
var showForm = function(el, name){
form.getElements('.group').removeClass('current')
form.getElements('.group.'+name).addClass('current')
$('configForm').getElements('ul a').removeClass('current');
el.addClass('current');
}
var firstItem = $('configForm').getElement('ul li:last-child a');
showForm(firstItem, firstItem.get('href').substr(1));
$('xbmcTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testXBMC/',
'data': $('xbmcFieldset')
}).send()
})
$('plexTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testPLEX/',
'data': $('plexFieldset')
}).send()
})
$('prowlTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testPROWL/',
'data': $('prowlFieldset')
}).send()
})
$('growlTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testGROWL/',
'data': $('growlFieldset')
}).send()
})
$('notifoTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testNotifo/',
'data': $('notifoFieldset')
}).send()
})
$('boxcarTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testBoxcar/',
'data': $('boxcarFieldset')
}).send()
})
$('nmjTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testNMJ/',
'data': $('nmjFieldset')
}).send()
})
$('nmjAuto').addEvent('click', function(e){
(e).stop()
if (form.getElement('.NMJhost').value == '') {
alert('Please fill in the Popcorn Hour IP address');
form.getElement('.NMJhost').focus();
return
}
new Request.JSON({
url: './autoNMJ/',
onComplete: function(response){
if (response == null) return
form.getElement('.NMJdatabase').value = response.database;
form.getElement('.NMJmount').value = response.mount;
},
data: $('nmjFieldset')
}).send()
})
$('nmaTest').addEvent('click',function(e){
(e).stop()
new Request({
'url': './testNMA/',
'data': $('nmaFieldset')
}).send()
})
$('nmwpTest').addEvent('click',function(e){
(e).stop()
new Request({
'url': './testNMWP/',
'data': $('nmwpFieldset')
}).send()
})
$('twitterTest').addEvent('click',function(e){
(e).stop()
new Request({
'url': './testTwitter/',
'data': $('twitterFieldset')
}).send()
})
$('traktTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testTrakt/',
'data': $('traktFieldset')
}).send()
})
});
</script>
<%inherit file="/base.html" />
|
<?php
require_once($GLOBALS['g_campsiteDir'].'/classes/Input.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Attachment.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Log.php');
require_once LIBS_DIR . '/MediaList/MediaList.php';
require_once LIBS_DIR . '/MediaPlayer/MediaPlayer.php';
$f_attachment_id = Input::Get('f_attachment_id', 'int', 0);
$translator = \Zend_Registry::get('container')->getService('translator');
if (!Input::IsValid()) {
camp_html_goto_page("/$ADMIN/media-archive/index.php#files");
}
$em = \Zend_Registry::get('container')->getService('em');
$attachment = $em->getRepository('Newscoop\Entity\Attachment')->findOneById($f_attachment_id);
$attachmentService = \Zend_Registry::get('container')->getService('attachment');
$label_text = '';
$crumbs = array();
$crumbs[] = array($translator->trans('Content'), "");
$crumbs[] = array($translator->trans('Media Archive', array(), 'home'), "/$ADMIN/media-archive/index.php#files");
if ($g_user->hasPermission('ChangeImage')) {
$label_text = $translator->trans('Change attachment information', array(), 'media_archive');
}
else {
$label_text = $translator->trans('View attachment', array(), 'media_archive');
}
$crumbs[] = array($label_text, '');
$breadcrumbs = <API key>($crumbs);
$controller->view->headTitle($label_text.' - Newscoop Admin', 'SET');
echo $breadcrumbs;
?>
<?php <API key>(); ?>
<div class="wrapper"><div class="<API key>">
<h2><?php echo $attachment->getName(); ?></h2>
<p class="dates"><?php echo $translator->trans('Created', array(), 'media_archive'); ?>: <?php echo $attachment->getCreated()->format('Y-m-d H:i:s'); ?>, <?php echo $translator->trans('Last modified', array(), 'media_archive'); ?>: <?php echo $attachment->getUpdated()->format('Y-m-d H:i:s'); ?></p>
<?php echo new MediaPlayer($attachmentService->getAttachmentUrl($attachment) . '?g_show_in_browser=1', $attachment->getMimeType()); ?>
<dl class="attachment">
<dt><?php echo $translator->trans('Type'); ?>:</dt>
<dd><?php echo $attachment->getMimeType(); ?></dd>
<dt><?php echo $translator->trans('Size', array(), 'media_archive'); ?>:</dt>
<dd><?php echo MediaList::FormatFileSize($attachment->getSizeInBytes()); ?></dd>
<?php if ($attachment->getHttpCharset()) { ?>
<dt><?php echo $translator->trans('Charset', array(), 'media_archive'); ?>:</dt>
<dd><?php echo $attachment->getHttpCharset(); ?></dd>
<?php } ?>
</dl>
<form name="edit" method="POST" action="/<?php echo $ADMIN; ?>/media-archive/do_edit-attachment.php">
<?php echo SecurityToken::FormParameter(); ?>
<input type="hidden" name="f_attachment_id" value="<?php echo $attachment->getId(); ?>" />
<div class="ui-widget-content big-block block-shadow padded-strong">
<fieldset class="plain">
<legend><?php echo $translator->trans('Change attachment information', array(), 'media_archive'); ?></legend>
<ul>
<li>
<label for="description"><?php echo $translator->trans("Description"); ?>:</label>
<input id="description" type="text" name="f_description" value="<?php echo htmlspecialchars($attachment->getDescription()); ?>" size="50" maxlength="255" class="input_text" />
</li>
<li>
<label><?php echo $translator->trans("Do you want this file to open in the users browser, or to automatically download?", array(), 'media_archive'); ?></label>
<input id="disposition0" class="input_radio" type="radio" name="<API key>" value=""<?php if ($attachment-><API key>() == NULL) { echo ' checked="checked"'; } ?> />
<label for="disposition0" class="inline-style left-floated" style="padding-right:15px"><?php echo $translator->trans("Open in the browser", array(), 'media_archive'); ?></label>
<input id="disposition1" class="input_radio" type="radio" name="<API key>" value="attachment"<?php if ($attachment-><API key>() == 'attachment') { echo ' checked="checked"'; } ?> />
<label for="disposition1" class="inline-style left-floated"><?php echo $translator->trans("Automatically download", array(), 'media_archive'); ?></label>
</li>
<li>
<label> </label>
<input type="submit" name="Save" value="<?php echo $translator->trans('Save'); ?>" class="button" />
</li>
</ul>
</fieldset>
</div>
</form>
</div></div><!-- /.<API key> /.wrapper -->
<?php <API key>(); ?>
</body>
</html>
|
#pragma once
#include "ASyncTCP.h"
#include "P1MeterBase.h"
class P1MeterTCP : public P1MeterBase, ASyncTCP
{
public:
P1MeterTCP(int ID, const std::string &IPAddress, unsigned short usIPPort, bool disable_crc, int ratelimit, const std::string &DecryptionKey);
~P1MeterTCP() override = default;
bool WriteToHardware(const char *pdata, unsigned char length) override;
public:
// signals
boost::signals2::signal<void()> sDisconnected;
private:
bool StartHardware() override;
bool StopHardware() override;
protected:
std::string m_szIPAddress;
unsigned short m_usIPPort;
void Do_Work();
void OnConnect() override;
void OnDisconnect() override;
void OnData(const unsigned char *pData, size_t length) override;
void OnError(const boost::system::error_code &error) override;
std::shared_ptr<std::thread> m_thread;
};
|
#include <nss.h>
#include <string.h>
const char <API key>[] = <API key>;
/* Check that VALUE is either NULL or a NUL-terminated string which
does not contain characters not permitted in NSS database
fields. */
_Bool
internal_function
__nss_valid_field (const char *value)
{
return value == NULL
|| strpbrk (value, <API key>) == NULL;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "xmlrpc_config.h"
#include "xmlparse.h"
#include "codepage.h"
#include "xmlfile.h"
#include "xmltchar.h"
#if MSVCRT
#include <crtdbg.h>
#endif
/* This ensures proper sorting. */
#define NSSEP T('\001')
static void characterData(void *userData, const XML_Char *s, int len)
{
FILE *fp = userData;
for (; len > 0; --len, ++s) {
switch (*s) {
case T('&'):
fputts(T("&"), fp);
break;
case T('<'):
fputts(T("<"), fp);
break;
case T('>'):
fputts(T(">"), fp);
break;
#ifdef W3C14N
case 13:
fputts(T("
"), fp);
break;
#else
case T('"'):
fputts(T("""), fp);
break;
case 9:
case 10:
case 13:
ftprintf(fp, T("&#%d;"), *s);
break;
#endif
default:
puttc(*s, fp);
break;
}
}
}
static void attributeValue(FILE *fp, const XML_Char *s)
{
puttc(T('='), fp);
puttc(T('"'), fp);
for (;;) {
switch (*s) {
case 0:
case NSSEP:
puttc(T('"'), fp);
return;
case T('&'):
fputts(T("&"), fp);
break;
case T('<'):
fputts(T("<"), fp);
break;
case T('"'):
fputts(T("""), fp);
break;
#ifdef W3C14N
case 9:
fputts(T("	"), fp);
break;
case 10:
fputts(T("
"), fp);
break;
case 13:
fputts(T("
"), fp);
break;
#else
case T('>'):
fputts(T(">"), fp);
break;
case 9:
case 10:
case 13:
ftprintf(fp, T("&#%d;"), *s);
break;
#endif
default:
puttc(*s, fp);
break;
}
s++;
}
}
/* Lexicographically comparing UTF-8 encoded attribute values,
is equivalent to lexicographically comparing based on the character number. */
static int attcmp(const void *att1, const void *att2)
{
return tcscmp(*(const XML_Char **)att1, *(const XML_Char **)att2);
}
static void startElement(void *userData, const XML_Char *name, const XML_Char **atts)
{
int nAtts;
const XML_Char **p;
FILE *fp = userData;
puttc(T('<'), fp);
fputts(name, fp);
p = atts;
while (*p)
++p;
nAtts = (p - atts) >> 1;
if (nAtts > 1)
qsort((void *)atts, nAtts, sizeof(XML_Char *) * 2, attcmp);
while (*atts) {
puttc(T(' '), fp);
fputts(*atts++, fp);
attributeValue(fp, *atts);
atts++;
}
puttc(T('>'), fp);
}
static void endElement(void *userData, const XML_Char *name)
{
FILE *fp = userData;
puttc(T('<'), fp);
puttc(T('/'), fp);
fputts(name, fp);
puttc(T('>'), fp);
}
static int nsattcmp(const void *p1, const void *p2)
{
const XML_Char *att1 = *(const XML_Char **)p1;
const XML_Char *att2 = *(const XML_Char **)p2;
int sep1 = (tcsrchr(att1, NSSEP) != 0);
int sep2 = (tcsrchr(att1, NSSEP) != 0);
if (sep1 != sep2)
return sep1 - sep2;
return tcscmp(att1, att2);
}
static void startElementNS(void *userData, const XML_Char *name, const XML_Char **atts)
{
int nAtts;
int nsi;
const XML_Char **p;
FILE *fp = userData;
const XML_Char *sep;
puttc(T('<'), fp);
sep = tcsrchr(name, NSSEP);
if (sep) {
fputts(T("n1:"), fp);
fputts(sep + 1, fp);
fputts(T(" xmlns:n1"), fp);
attributeValue(fp, name);
nsi = 2;
}
else {
fputts(name, fp);
nsi = 1;
}
p = atts;
while (*p)
++p;
nAtts = (p - atts) >> 1;
if (nAtts > 1)
qsort((void *)atts, nAtts, sizeof(XML_Char *) * 2, nsattcmp);
while (*atts) {
name = *atts++;
sep = tcsrchr(name, NSSEP);
puttc(T(' '), fp);
if (sep) {
ftprintf(fp, T("n%d:"), nsi);
fputts(sep + 1, fp);
}
else
fputts(name, fp);
attributeValue(fp, *atts);
if (sep) {
ftprintf(fp, T(" xmlns:n%d"), nsi++);
attributeValue(fp, name);
}
atts++;
}
puttc(T('>'), fp);
}
static void endElementNS(void *userData, const XML_Char *name)
{
FILE *fp = userData;
const XML_Char *sep;
puttc(T('<'), fp);
puttc(T('/'), fp);
sep = tcsrchr(name, NSSEP);
if (sep) {
fputts(T("n1:"), fp);
fputts(sep + 1, fp);
}
else
fputts(name, fp);
puttc(T('>'), fp);
}
#ifndef W3C14N
static void <API key>(void *userData, const XML_Char *target, const XML_Char *data)
{
FILE *fp = userData;
puttc(T('<'), fp);
puttc(T('?'), fp);
fputts(target, fp);
puttc(T(' '), fp);
fputts(data, fp);
puttc(T('?'), fp);
puttc(T('>'), fp);
}
#endif /* not W3C14N */
static void <API key>(XML_Parser parser, const XML_Char *s, int len)
{
XML_DefaultCurrent(parser);
}
static void defaultStartElement(XML_Parser parser, const XML_Char *name, const XML_Char **atts)
{
XML_DefaultCurrent(parser);
}
static void defaultEndElement(XML_Parser parser, const XML_Char *name)
{
XML_DefaultCurrent(parser);
}
static void <API key>(XML_Parser parser, const XML_Char *target, const XML_Char *data)
{
XML_DefaultCurrent(parser);
}
static void nopCharacterData(XML_Parser parser, const XML_Char *s, int len)
{
}
static void nopStartElement(XML_Parser parser, const XML_Char *name, const XML_Char **atts)
{
}
static void nopEndElement(XML_Parser parser, const XML_Char *name)
{
}
static void <API key>(XML_Parser parser, const XML_Char *target, const XML_Char *data)
{
}
static void markup(XML_Parser parser, const XML_Char *s, int len)
{
FILE *fp = XML_GetUserData(parser);
for (; len > 0; --len, ++s)
puttc(*s, fp);
}
static
void metaLocation(XML_Parser parser)
{
const XML_Char *uri = XML_GetBase(parser);
if (uri)
ftprintf(XML_GetUserData(parser), T(" uri=\"%s\""), uri);
ftprintf(XML_GetUserData(parser),
T(" byte=\"%ld\" nbytes=\"%d\" line=\"%d\" col=\"%d\""),
<API key>(parser),
<API key>(parser),
<API key>(parser),
<API key>(parser));
}
static
void metaStartDocument(XML_Parser parser)
{
fputts(T("<document>\n"), XML_GetUserData(parser));
}
static
void metaEndDocument(XML_Parser parser)
{
fputts(T("</document>\n"), XML_GetUserData(parser));
}
static
void metaStartElement(XML_Parser parser, const XML_Char *name, const XML_Char **atts)
{
FILE *fp = XML_GetUserData(parser);
const XML_Char **specifiedAttsEnd
= atts + <API key>(parser);
const XML_Char **idAttPtr;
int idAttIndex = <API key>(parser);
if (idAttIndex < 0)
idAttPtr = 0;
else
idAttPtr = atts + idAttIndex;
ftprintf(fp, T("<starttag name=\"%s\""), name);
metaLocation(parser);
if (*atts) {
fputts(T(">\n"), fp);
do {
ftprintf(fp, T("<attribute name=\"%s\" value=\""), atts[0]);
characterData(fp, atts[1], tcslen(atts[1]));
if (atts >= specifiedAttsEnd)
fputts(T("\" defaulted=\"yes\"/>\n"), fp);
else if (atts == idAttPtr)
fputts(T("\" id=\"yes\"/>\n"), fp);
else
fputts(T("\"/>\n"), fp);
} while (*(atts += 2));
fputts(T("</starttag>\n"), fp);
}
else
fputts(T("/>\n"), fp);
}
static
void metaEndElement(XML_Parser parser, const XML_Char *name)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<endtag name=\"%s\""), name);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser, const XML_Char *target, const XML_Char *data)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<pi target=\"%s\" data=\""), target);
characterData(fp, data, tcslen(data));
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaComment(XML_Parser parser, const XML_Char *data)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<comment data=\""), fp);
characterData(fp, data, tcslen(data));
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<startcdata"), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaEndCdataSection(XML_Parser parser)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<endcdata"), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaCharacterData(XML_Parser parser, const XML_Char *s, int len)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<chars str=\""), fp);
characterData(fp, s, len);
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser, const XML_Char *doctypeName)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<startdoctype name=\"%s\""), doctypeName);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaEndDoctypeDecl(XML_Parser parser)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<enddoctype"), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<entity name=\"%s\""), entityName);
if (publicId)
ftprintf(fp, T(" public=\"%s\""), publicId);
fputts(T(" system=\""), fp);
characterData(fp, systemId, tcslen(systemId));
puttc(T('"'), fp);
ftprintf(fp, T(" notation=\"%s\""), notationName);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaNotationDecl(XML_Parser parser,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<notation name=\"%s\""), notationName);
if (publicId)
ftprintf(fp, T(" public=\"%s\""), publicId);
if (systemId) {
fputts(T(" system=\""), fp);
characterData(fp, systemId, tcslen(systemId));
puttc(T('"'), fp);
}
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<entity name=\"%s\""), entityName);
if (publicId)
ftprintf(fp, T(" public=\"%s\""), publicId);
fputts(T(" system=\""), fp);
characterData(fp, systemId, tcslen(systemId));
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser,
const XML_Char *entityName,
const XML_Char *text,
int textLen)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<entity name=\"%s\""), entityName);
metaLocation(parser);
puttc(T('>'), fp);
characterData(fp, text, textLen);
fputts(T("</entity/>\n"), fp);
}
static
void <API key>(XML_Parser parser,
const XML_Char *prefix,
const XML_Char *uri)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<startns"), fp);
if (prefix)
ftprintf(fp, T(" prefix=\"%s\""), prefix);
if (uri) {
fputts(T(" ns=\""), fp);
characterData(fp, uri, tcslen(uri));
fputts(T("\"/>\n"), fp);
}
else
fputts(T("/>\n"), fp);
}
static
void <API key>(XML_Parser parser, const XML_Char *prefix)
{
FILE *fp = XML_GetUserData(parser);
if (!prefix)
fputts(T("<endns/>\n"), fp);
else
ftprintf(fp, T("<endns prefix=\"%s\"/>\n"), prefix);
}
static
int <API key>(void *data, const char *p)
{
return codepageConvert(*(int *)data, p);
}
static
int unknownEncoding(void *userData,
const XML_Char *name,
XML_Encoding *info)
{
int cp;
static const XML_Char prefixL[] = T("windows-");
static const XML_Char prefixU[] = T("WINDOWS-");
int i;
for (i = 0; prefixU[i]; i++)
if (name[i] != prefixU[i] && name[i] != prefixL[i])
return 0;
cp = 0;
for (; name[i]; i++) {
static const XML_Char digits[] = T("0123456789");
const XML_Char *s = tcschr(digits, name[i]);
if (!s)
return 0;
cp *= 10;
cp += s - digits;
if (cp >= 0x10000)
return 0;
}
if (!codepageMap(cp, info->map))
return 0;
info->convert = <API key>;
/* We could just cast the code page integer to a void *,
and avoid the use of release. */
info->release = free;
info->data = malloc(sizeof(int));
if (!info->data)
return 0;
*(int *)info->data = cp;
return 1;
}
static
int notStandalone(void *userData)
{
return 0;
}
static
void usage(const XML_Char *prog)
{
ftprintf(stderr, T("usage: %s [-n] [-p] [-r] [-s] [-w] [-x] [-d output-dir] [-e encoding] file ...\n"), prog);
exit(1);
}
int tmain(int argc, XML_Char **argv)
{
int i, j;
const XML_Char *outputDir = 0;
const XML_Char *encoding = 0;
unsigned processFlags = XML_MAP_FILE;
int windowsCodePages = 0;
int outputType = 0;
int useNamespaces = 0;
int requireStandalone = 0;
int paramEntityParsing = <API key>;
#if MSVCRT
_CrtSetDbgFlag(<API key>|<API key>);
#endif
i = 1;
j = 0;
while (i < argc) {
if (j == 0) {
if (argv[i][0] != T('-'))
break;
if (argv[i][1] == T('-') && argv[i][2] == T('\0')) {
i++;
break;
}
j++;
}
switch (argv[i][j]) {
case T('r'):
processFlags &= ~XML_MAP_FILE;
j++;
break;
case T('s'):
requireStandalone = 1;
j++;
break;
case T('n'):
useNamespaces = 1;
j++;
break;
case T('p'):
paramEntityParsing = <API key>;
/* fall through */
case T('x'):
processFlags |= <API key>;
j++;
break;
case T('w'):
windowsCodePages = 1;
j++;
break;
case T('m'):
outputType = 'm';
j++;
break;
case T('c'):
outputType = 'c';
useNamespaces = 0;
j++;
break;
case T('t'):
outputType = 't';
j++;
break;
case T('d'):
if (argv[i][j + 1] == T('\0')) {
if (++i == argc)
usage(argv[0]);
outputDir = argv[i];
}
else
outputDir = argv[i] + j + 1;
i++;
j = 0;
break;
case T('e'):
if (argv[i][j + 1] == T('\0')) {
if (++i == argc)
usage(argv[0]);
encoding = argv[i];
}
else
encoding = argv[i] + j + 1;
i++;
j = 0;
break;
case T('\0'):
if (j > 1) {
i++;
j = 0;
break;
}
/* fall through */
default:
usage(argv[0]);
}
}
if (i == argc)
usage(argv[0]);
for (; i < argc; i++) {
FILE *fp = 0;
XML_Char *outName = 0;
int result;
XML_Parser parser;
if (useNamespaces)
parser = XML_ParserCreateNS(encoding, NSSEP);
else
parser = XML_ParserCreate(encoding);
if (requireStandalone)
<API key>(parser, notStandalone);
<API key>(parser, paramEntityParsing);
if (outputType == 't') {
/* This is for doing timings; this gives a more realistic estimate of
the parsing time. */
outputDir = 0;
<API key>(parser, nopStartElement, nopEndElement);
<API key>(parser, nopCharacterData);
<API key>(parser, <API key>);
}
else if (outputDir) {
const XML_Char *file = argv[i];
if (tcsrchr(file, T('/')))
file = tcsrchr(file, T('/')) + 1;
#if MSVCRT
if (tcsrchr(file, T('\\')))
file = tcsrchr(file, T('\\')) + 1;
#endif
outName = malloc((tcslen(outputDir) + tcslen(file) + 2) * sizeof(XML_Char));
tcscpy(outName, outputDir);
tcscat(outName, T("/"));
tcscat(outName, file);
fp = tfopen(outName, T("wb"));
if (!fp) {
tperror(outName);
exit(1);
}
setvbuf(fp, NULL, _IOFBF, 16384);
#ifdef XML_UNICODE
puttc(0xFEFF, fp);
#endif
XML_SetUserData(parser, fp);
switch (outputType) {
case 'm':
<API key>(parser);
<API key>(parser, metaStartElement, metaEndElement);
<API key>(parser, <API key>);
<API key>(parser, metaComment);
<API key>(parser, <API key>, metaEndCdataSection);
<API key>(parser, metaCharacterData);
<API key>(parser, <API key>, metaEndDoctypeDecl);
<API key>(parser, <API key>);
<API key>(parser, metaNotationDecl);
<API key>(parser, <API key>);
<API key>(parser, <API key>);
<API key>(parser, <API key>, <API key>);
metaStartDocument(parser);
break;
case 'c':
<API key>(parser);
<API key>(parser, markup);
<API key>(parser, defaultStartElement, defaultEndElement);
<API key>(parser, <API key>);
<API key>(parser, <API key>);
break;
default:
if (useNamespaces)
<API key>(parser, startElementNS, endElementNS);
else
<API key>(parser, startElement, endElement);
<API key>(parser, characterData);
#ifndef W3C14N
<API key>(parser, <API key>);
#endif /* not W3C14N */
break;
}
}
if (windowsCodePages)
<API key>(parser, unknownEncoding, 0);
result = XML_ProcessFile(parser, argv[i], processFlags);
if (outputDir) {
if (outputType == 'm')
metaEndDocument(parser);
fclose(fp);
if (!result)
tremove(outName);
free(outName);
}
XML_ParserFree(parser);
}
return 0;
}
|
<?php
namespace Hoa\Stream\Wrapper;
use Hoa\Stream;
class Exception extends Stream\Exception
{
}
|
#ifndef __LV2_STORAGE_H__
#define __LV2_STORAGE_H__
#include <stdint.h>
#include <lv2/lv2.h>
#include <lv1/lv1.h>
/* Devices */
#define ATA_HDD 0x101000000000007
#define BDVD_DRIVE 0x101000000000006
#define PATA0_HDD_DRIVE 0x101000000000008
#define PATA0_BDVD_DRIVE BDVD_DRIVE
#define PATA1_HDD_DRIVE ATA_HDD
#define BUILTIN_FLASH 0x100000000000001
#define NAND_FLASH BUILTIN_FLASH
#define NOR_FLASH 0x100000000000004
#define MEMORY_STICK 0x103000000000010
#define SD_CARD 0x103000100000010
#define COMPACT_FLASH 0x103000200000010
#define USB_MASS_STORAGE_1(n) (0x10300000000000A+n) /* For 0-5 */
#define USB_MASS_STORAGE_2(n) (0x10300000000001F+(n-6)) /* For 6-127 */
#define HDD_PARTITION(n) (ATA_HDD | (n<<32))
#define FLASH_PARTITION(n) (BUILTIN_FLASH | (n<<32))
/* Commands for <API key> */
#define <API key> 0x01
#define <API key> 0x10
#define <API key> 0x11
/* Device types returned by <API key> and some scsi commands */
#define DEVICE_TYPE_PS3_DVD 0xFF70
#define DEVICE_TYPE_PS3_BD 0xFF71
#define DEVICE_TYPE_PS2_CD 0xFF60
#define DEVICE_TYPE_PS2_DVD 0xFF61
#define DEVICE_TYPE_PSX_CD 0xFF50
#define DEVICE_TYPE_BDROM 0x40
#define DEVICE_TYPE_BDMR_SR 0x41 /* Sequential record */
#define DEVICE_TYPE_BDMR_RR 0x42 /* Random record */
#define DEVICE_TYPE_BDMRE 0x43
#define DEVICE_TYPE_DVD 0x10 /* DVD-ROM, DVD+-R, DVD+-RW etc, they are differenced by booktype field in some scsi command */
#define DEVICE_TYPE_CD 0x08 /* CD-ROM, CD-DA, CD-R, CD-RW, etc, they are differenced somehow with scsi commands */
typedef uint32_t device_handle_t; // Kernel
typedef uint32_t sys_device_handle_t; // User
typedef struct
{
char *label;
uint32_t unk_08; // 8 0xB8 0x90
uint32_t unk_0C; // 0x0C 0xBC 0x94
uint64_t unk_10; // 0x10 not copied in <API key> 0xC0 unused
uint64_t sector_count; // 0x18 0xC8 0x98
uint32_t sector_size; // 0x20 0xD0 0xA0
uint32_t unk_24; // 0x24 not copied in <API key> 0xD4 unused
uint32_t unk_28; // 0x28 not copied in <API key> 0xD8 unused
uint32_t unk_2C; // 0x2C not copied in <API key> 0xDC unused
uint32_t unk_30; // 0x30 0xE0 0xA4
uint32_t unk_34; // 0x34 not copied in <API key> 0xE4 unused
uint64_t unk_38; // 0x38 not copied in <API key> 0xE8 unused
uint8_t unk_40[8]; // 0x40 0xF0 0xA8
} __attribute__((packed)) device_info_t;
typedef struct
{
uint32_t inlen;
uint32_t unk1;
uint32_t outlen;
uint32_t unk2;
uint32_t unk3;
} __attribute__((packed)) StorageCmdScsiData;
LV2_EXPORT int <API key>(uint64_t device_id, device_info_t *device_info);
LV2_EXPORT int <API key>(int *unk, int *unk2);
// storage_open(0x0101000000000006, 0, &device_handle, 0); // dev_bdvd
LV2_EXPORT int storage_open(uint64_t device_id, uint64_t unk, device_handle_t *device_handle, uint64_t unk2);
LV2_EXPORT int storage_close(device_handle_t device_handle);
// storage_read(3, 0, 0x220, 0x10, buf, &nread, 4); // flash?
// storage_read(0x13, 0, 0x030761E0, 0x80, buf, &nread, 0); // hdd
// storage_read(0x24, 0, 0x3C01, 0x20, buf, &nread, 4); // usb. Raw sector, not partition one.
// storage_read(0x41, 0, 0x10, 0x10, buf, &nread, 0); // dev_bdvd
LV2_EXPORT int storage_read(device_handle_t device_handle, uint64_t unk, uint64_t start_sector, uint32_t sector_count, void *buf, uint32_t *nread, uint64_t flags);
LV2_EXPORT int storage_write(device_handle_t device_handle, uint64_t unk, uint64_t start_sector, uint32_t sector_count, void *buf, uint32_t *nwrite, uint64_t flags);
/* get device type?
command = 0x11
indata = 0x01010071 (also works with indata 00000000)
outdata = 0x0000FF71 PS3 BD game
outdata = 0x00000040 BD-ROM
outdata = 0x00000041 BD-R
outdata = 0x0000FF61 PS2 DVD game
outdata = 0x00000010 DVD (any except ps2)
outdata = 0x00000008 CD (any except ps1?)
*/
LV2_EXPORT int <API key>(device_handle_t device_handle, unsigned int command, void *indata, uint64_t inlen, void *outdata, uint64_t outlen, uint64_t *unkret);
LV2_EXPORT int <API key>(uint64_t device, void *buf, uint64_t size);
LV2_EXPORT int <API key>(uint64_t device, void *buf);
static INLINE uint64_t <API key>(void)
{
uint64_t value, v2;
<API key>(PS3_LPAR_ID_PME, FIELD_FIRST("sys", 0), FIELD("flash", 0), FIELD("ext", 0), 0, &value, &v2);
if (value&1)
return NAND_FLASH;
return NOR_FLASH;
}
#endif /* __LV2_STORAGE_H__ */
|
using System.IO;
using System.Collections.Generic;
using System.Xml;
using <API key>;
namespace PDollarDemo
{
public class GestureIO
{
<summary>
Reads a multistroke gesture from an string representation of xml
</summary>
<param name="xml"></param>
<returns></returns>
public static Gesture ReadXMLGesture(string xml)
{
List<Point> points = new List<Point>();
XmlTextReader xmlReader = null;
int currentStrokeIndex = -1;
string gestureName = "";
try
{
xmlReader = new XmlTextReader(new StringReader(xml));
while (xmlReader.Read())
{
if (xmlReader.NodeType != XmlNodeType.Element) continue;
switch (xmlReader.Name)
{
case "Gesture":
gestureName = xmlReader["Name"];
if (gestureName.Contains("~")) // '~' character is specific to the naming convention of the MMG set
gestureName = gestureName.Substring(0, gestureName.LastIndexOf('~'));
if (gestureName.Contains("_")) // '_' character is specific to the naming convention of the MMG set
gestureName = gestureName.Replace('_', ' ');
break;
case "Stroke":
currentStrokeIndex++;
break;
case "Point":
points.Add(new Point(
float.Parse(xmlReader["X"]),
float.Parse(xmlReader["Y"]),
currentStrokeIndex
));
break;
}
}
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return new Gesture(points.ToArray(), gestureName);
}
<summary>
Reads a multistroke gesture from an XML file
</summary>
<param name="fileName"></param>
<returns></returns>
public static Gesture ReadGesture(string fileName)
{
List<Point> points = new List<Point>();
XmlTextReader xmlReader = null;
int currentStrokeIndex = -1;
string gestureName = "";
try
{
xmlReader = new XmlTextReader(File.OpenText(fileName));
while (xmlReader.Read())
{
if (xmlReader.NodeType != XmlNodeType.Element) continue;
switch (xmlReader.Name)
{
case "Gesture":
gestureName = xmlReader["Name"];
if (gestureName.Contains("~")) // '~' character is specific to the naming convention of the MMG set
gestureName = gestureName.Substring(0, gestureName.LastIndexOf('~'));
if (gestureName.Contains("_")) // '_' character is specific to the naming convention of the MMG set
gestureName = gestureName.Replace('_', ' ');
break;
case "Stroke":
currentStrokeIndex++;
break;
case "Point":
points.Add(new Point(
float.Parse(xmlReader["X"]),
float.Parse(xmlReader["Y"]),
currentStrokeIndex
));
break;
}
}
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return new Gesture(points.ToArray(), gestureName);
}
<summary>
Writes a multistroke gesture to an XML file
</summary>
public static void WriteGesture(<API key>.Point[] points, string gestureName, string fileName)
{
using (StreamWriter sw = new StreamWriter(fileName))
{
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
sw.WriteLine("<Gesture Name = \"{0}\">", gestureName);
int currentStroke = -1;
for (int i = 0; i < points.Length; i++)
{
if (points[i].StrokeID != currentStroke)
{
if (i > 0)
sw.WriteLine("\t</Stroke>");
sw.WriteLine("\t<Stroke>");
currentStroke = points[i].StrokeID;
}
sw.WriteLine("\t\t<Point X = \"{0}\" Y = \"{1}\" T = \"0\" Pressure = \"0\" />",
points[i].X, points[i].Y
);
}
sw.WriteLine("\t</Stroke>");
sw.WriteLine("</Gesture>");
}
}
}
}
|
#ifndef MACTYPES_H
#define MACTYPES_H
#include <stdint.h>
#include <CoreFoundation/CFBase.h>
class _StringHandle;
#if 0 // declared in CFBase.h
typedef int8_t SInt8;
typedef uint8_t UInt8;
typedef int16_t SInt16;
typedef uint16_t UInt16;
typedef int32_t SInt32;
typedef uint32_t UInt32;
typedef int64_t SInt64;
typedef uint64_t UInt64;
typedef float Float32;
typedef double Float64;
#endif
typedef uint32_t OptionBits;
typedef int32_t Fixed; // 16/16
typedef Fixed* FixedPtr;
typedef int32_t Fract; // 2/30
typedef Fract* FractPtr;
typedef uint32_t UnsignedFixed; // 16u/16
typedef UnsignedFixed* UnsignedFixedPtr;
typedef short ShortFixed;
typedef ShortFixed * ShortFixedPtr;
typedef int64_t wide;
typedef uint64_t UnsignedWide;
typedef uint64_t AbsoluteTime;
typedef int32_t Duration; // milliseconds
typedef uint8_t Boolean;
// Pascal strings
typedef unsigned char Str255[256];
typedef unsigned char Str63[64];
typedef unsigned char Str32[33];
typedef unsigned char Str31[32];
typedef unsigned char Str27[28];
typedef unsigned char Str15[16];
typedef unsigned char* StringPtr;
typedef unsigned char** StringHandle;
typedef char* Ptr;
typedef char** Handle;
typedef int16_t OSErr;
typedef int32_t OSStatus;
typedef uint32_t OSType;
#endif
|
// netDxf library
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
using netDxf.Tables;
namespace netDxf.Objects
{
<summary>
Represents an underlay definition.
</summary>
public abstract class UnderlayDefinition :
TableObject
{
#region private fields
private readonly UnderlayType type;
private readonly string file;
#endregion
#region constructor
<summary>
Initializes a new instance of the <c>UnderlayDefinition</c> class.
</summary>
<param name="name">Underlay name.</param>
<param name="file">Underlay file name with full or relative path.</param>
<param name="type">Underlay type.</param>
protected UnderlayDefinition(string name, string file, UnderlayType type)
: base(name, DxfObjectCode.UnderlayDefinition, false)
{
this.file = file;
this.type = type;
switch (type)
{
case UnderlayType.DGN:
this.CodeName = DxfObjectCode.<API key>;
break;
case UnderlayType.DWF:
this.CodeName = DxfObjectCode.<API key>;
break;
case UnderlayType.PDF:
this.CodeName = DxfObjectCode.<API key>;
break;
}
}
#endregion
#region public properties
<summary>
Get the underlay type.
</summary>
public UnderlayType Type
{
get { return this.type; }
}
<summary>
Gets the underlay file.
</summary>
public string File
{
get { return this.file; }
}
#endregion
}
}
|
#include "core/html/forms/URLInputType.h"
#include "core/InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "platform/text/PlatformLocale.h"
namespace blink {
InputType* URLInputType::create(HTMLInputElement& element) {
return new URLInputType(element);
}
void URLInputType::countUsage() {
countUsageIfVisible(UseCounter::InputTypeURL);
}
const AtomicString& URLInputType::formControlType() const {
return InputTypeNames::url;
}
bool URLInputType::typeMismatchFor(const String& value) const {
return !value.isEmpty() && !KURL(KURL(), value).isValid();
}
bool URLInputType::typeMismatch() const {
return typeMismatchFor(element().value());
}
String URLInputType::typeMismatchText() const {
return locale().queryString(WebLocalizedString::<API key>);
}
String URLInputType::sanitizeValue(const String& proposedValue) const {
return BaseTextInputType::sanitizeValue(
<API key>(proposedValue));
}
String URLInputType::<API key>(const String& proposedValue) const {
// Do not call URLInputType::sanitizeValue.
return BaseTextInputType::sanitizeValue(proposedValue);
}
} // namespace blink
|
package org.itadaki.bzip2;
public class HuffmanAllocator {
/**
* FIRST() function
* @param array The code length array
* @param i The input position
* @param nodesToMove The number of internal nodes to be relocated
* @return The smallest {@code k} such that {@code nodesToMove <= k <= i} and
* {@code i <= (array[k] % array.length)}
*/
private static int first (final int[] array, int i, final int nodesToMove) {
final int length = array.length;
final int limit = i;
int k = array.length - 2;
while ((i >= nodesToMove) && ((array[i] % length) > limit)) {
k = i;
i -= (limit - i + 1);
}
i = Math.max (nodesToMove - 1, i);
while (k > (i + 1)) {
int temp = (i + k) >> 1;
if ((array[temp] % length) > limit) {
k = temp;
} else {
i = temp;
}
}
return k;
}
/**
* Fills the code array with extended parent pointers
* @param array The code length array
*/
private static void <API key> (final int[] array) {
final int length = array.length;
array[0] += array[1];
for (int headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) {
int temp;
if ((topNode >= length) || (array[headNode] < array[topNode])) {
temp = array[headNode];
array[headNode++] = tailNode;
} else {
temp = array[topNode++];
}
if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) {
temp += array[headNode];
array[headNode++] = tailNode + length;
} else {
temp += array[topNode++];
}
array[tailNode] = temp;
}
}
/**
* Finds the number of nodes to relocate in order to achieve a given code length limit
* @param array The code length array
* @param maximumLength The maximum bit length for the generated codes
* @return The number of nodes to relocate
*/
private static int findNodesToRelocate (final int[] array, final int maximumLength) {
int currentNode = array.length - 2;
for (int currentDepth = 1; (currentDepth < (maximumLength - 1)) && (currentNode > 1); currentDepth++) {
currentNode = first (array, currentNode - 1, 0);
}
return currentNode;
}
/**
* A final allocation pass with no code length limit
* @param array The code length array
*/
private static void allocateNodeLengths (final int[] array) {
int firstNode = array.length - 2;
int nextNode = array.length - 1;
for (int currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) {
final int lastNode = firstNode;
firstNode = first (array, lastNode - 1, 0);
for (int i = availableNodes - (lastNode - firstNode); i > 0; i
array[nextNode--] = currentDepth;
}
availableNodes = (lastNode - firstNode) << 1;
}
}
/**
* A final allocation pass that relocates nodes in order to achieve a maximum code length limit
* @param array The code length array
* @param nodesToMove The number of internal nodes to be relocated
* @param insertDepth The depth at which to insert relocated nodes
*/
private static void <API key> (final int[] array, final int nodesToMove, final int insertDepth) {
int firstNode = array.length - 2;
int nextNode = array.length - 1;
int currentDepth = (insertDepth == 1) ? 2 : 1;
int nodesLeftToMove = (insertDepth == 1) ? nodesToMove - 2 : nodesToMove;
for (int availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) {
final int lastNode = firstNode;
firstNode = (firstNode <= nodesToMove) ? firstNode : first (array, lastNode - 1, nodesToMove);
int offset = 0;
if (currentDepth >= insertDepth) {
offset = Math.min (nodesLeftToMove, 1 << (currentDepth - insertDepth));
} else if (currentDepth == (insertDepth - 1)) {
offset = 1;
if ((array[firstNode]) == lastNode) {
firstNode++;
}
}
for (int i = availableNodes - (lastNode - firstNode + offset); i > 0; i
array[nextNode--] = currentDepth;
}
nodesLeftToMove -= offset;
availableNodes = (lastNode - firstNode + offset) << 1;
}
}
/**
* Allocates Canonical Huffman code lengths in place based on a sorted frequency array
* @param array On input, a sorted array of symbol frequencies; On output, an array of Canonical
* Huffman code lengths
* @param maximumLength The maximum code length. Must be at least {@code ceil(log2(array.length))}
*/
public static void <API key> (final int[] array, final int maximumLength) {
switch (array.length) {
case 2:
array[1] = 1;
case 1:
array[0] = 1;
return;
}
/* Pass 1 : Set extended parent pointers */
<API key> (array);
/* Pass 2 : Find number of nodes to relocate in order to achieve maximum code length */
int nodesToRelocate = findNodesToRelocate (array, maximumLength);
/* Pass 3 : Generate code lengths */
if ((array[0] % array.length) >= nodesToRelocate) {
allocateNodeLengths (array);
} else {
int insertDepth = maximumLength - (32 - Integer.<API key> (nodesToRelocate - 1));
<API key> (array, nodesToRelocate, insertDepth);
}
}
/**
* Non-instantiable
*/
private HuffmanAllocator() { }
}
|
/*
* Doubly linked list construction and deletion.
*/
#include <stdlib.h>
#include <verifier-builtins.h>
int main() {
struct T {
struct T* next;
struct T* prev;
int data;
};
struct T* x = NULL;
struct T* y = NULL;
x = malloc(sizeof(struct T));
x->next = NULL;
x->prev = NULL;
while (<API key>()) {
y = malloc(sizeof(struct T));
y->next = x;
x->prev = y;
y->prev = NULL;
x = y;
}
__VERIFIER_plot("test-f0028-fixpoint");
while (x) {
y = x->next;
free(x);
x = y;
}
return 0;
}
|
# Authors:
# Petr Vobornik <pvoborni@redhat.com>
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
|
package org.overture.ide.core.resources;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.overture.ide.core.VdmCore;
import org.overture.ide.internal.core.ResourceManager;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ModelBuildPath
{
final IVdmProject vdmProject;
final IProject project;
final File modelPathFile;
List<IContainer> srcPaths = new Vector<IContainer>();
IContainer output;
IContainer library;
public ModelBuildPath(IVdmProject project)
{
this.vdmProject = project;
this.project = (IProject) this.vdmProject.getAdapter(IProject.class);
IPath base = this.project.getLocation();
base = base.append(".modelpath");
this.modelPathFile = base.toFile();
this.output = this.project.getFolder("generated");
this.library = this.project.getFolder("lib");
parse();
}
private boolean hasModelPath()
{
return this.modelPathFile.exists();
}
private IContainer <API key>()
{
return this.project;
}
public List<IContainer> getModelSrcPaths()
{
List<IContainer> tmp = new Vector<IContainer>(srcPaths.size());
tmp.addAll(srcPaths);
return tmp;
}
public synchronized IContainer getOutput()
{
return this.output;
}
public synchronized IContainer getLibrary()
{
return this.library;
}
private synchronized void parse()
{
if (!hasModelPath())
{
srcPaths.add(<API key>());
return;
}
try
{
File file = this.modelPathFile;
<API key> dbf = <API key>.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.<API key>("modelpathentry");
for (int s = 0; s < nodeLst.getLength(); s++)
{
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Node kindAttribute = fstNode.getAttributes().getNamedItem("kind");
String kindValue = kindAttribute.getNodeValue();
if (kindValue != null)
{
if (kindValue.equals("src"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
if(pathValue.equals("."))
{
add(<API key>());
}else
{
add(this.project.getFolder(pathValue));
}
} else if (kindValue.equals("output"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
output = this.project.getFolder(pathValue);
} else if (kindValue.equals("library"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
library = this.project.getFolder(pathValue);
}
}
}
}
if(srcPaths.isEmpty())
{
srcPaths.add(<API key>());
}
} catch (Exception e)
{
VdmCore.log("Faild to parse .modelpath file", e);
}
}
public synchronized void setOutput(IContainer container)
{
this.output = container;
}
public synchronized void setLibrary(IContainer container)
{
this.library = container;
}
public synchronized void add(IContainer container)
{
if(container instanceof IProject)
{
srcPaths.clear();
}
else if(container instanceof IFolder)
{
String fullPath = container.<API key>().toString();
boolean flag = true;
for (IContainer s : srcPaths)
{
flag = flag && s.<API key>().toString().startsWith(fullPath);
}
if(flag)
srcPaths.clear();
}
if (!srcPaths.contains(container))
{
srcPaths.add(container);
}
}
public synchronized void remove(IContainer container)
{
if (srcPaths.contains(container))
{
srcPaths.remove(container);
}
}
public synchronized boolean contains(IContainer container)
{
return srcPaths.contains(container);
}
public synchronized void save() throws CoreException
{
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<modelpath>\n");
for (IContainer src : srcPaths)
{
if (src.<API key>().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"src\" path=\""
+ src.<API key>() + "\"/>\n");
}else if (src instanceof IProject)
{
sb.append("\t<modelpathentry kind=\"src\" path=\".\"/>\n");
}
}
if (output != null
&& output.<API key>().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"output\" path=\""
+ output.<API key>() + "\"/>\n");
}
if (library != null
&& library.<API key>().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"library\" path=\""
+ library.<API key>() + "\"/>\n");
}
sb.append("</modelpath>");
PrintWriter out = null;
try
{
FileWriter outFile = new FileWriter(this.modelPathFile);
out = new PrintWriter(outFile);
out.println(sb.toString());
} catch (IOException e)
{
VdmCore.log("Faild to save .modelpath file", e);
} finally
{
if (out != null)
{
out.close();
}
}
ResourceManager.getInstance().syncBuildPath(vdmProject);
}
/**
* Reload the build path and discard any un-saved changes
*/
public void reload()
{
parse();
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<TITLE>
Uses of Class org.apache.poi.hssf.record.CellRecord (POI API Documentation)
</TITLE>
<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="Uses of Class org.apache.poi.hssf.record.CellRecord (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/record//class-useCellRecord.html" target="_top"><B>FRAMES</B></A>
<A HREF="CellRecord.html" target="_top"><B>NO FRAMES</B></A>
<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>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hssf.record.CellRecord</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.hssf.record"><B>org.apache.poi.hssf.record</B></A></TD>
<TD>Record package contains class representations for XLS binary strutures. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.hssf.record"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A> in <A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A> in <A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/BoolErrRecord.html" title="class in org.apache.poi.hssf.record">BoolErrRecord</A></B></CODE>
<BR>
Creates new BoolErrRecord.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/FormulaRecord.html" title="class in org.apache.poi.hssf.record">FormulaRecord</A></B></CODE>
<BR>
Formula Record (0x0006).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/LabelSSTRecord.html" title="class in org.apache.poi.hssf.record">LabelSSTRecord</A></B></CODE>
<BR>
Title: Label SST Record</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/NumberRecord.html" title="class in org.apache.poi.hssf.record">NumberRecord</A></B></CODE>
<BR>
NUMBER (0x0203) Contains a numeric cell value.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/RKRecord.html" title="class in org.apache.poi.hssf.record">RKRecord</A></B></CODE>
<BR>
Title: RK Record (0x027E)</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</A> with parameters of type <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B>CellRecord.</B><B><A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html#copyBaseFields(org.apache.poi.hssf.record.CellRecord)">copyBaseFields</A></B>(<A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A> rec)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<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="<API key>"></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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/record//class-useCellRecord.html" target="_top"><B>FRAMES</B></A>
<A HREF="CellRecord.html" target="_top"><B>NO FRAMES</B></A>
<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>
<HR>
<i>Copyright 2017 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "encoder_impl.h"
#include <gnuradio/io_signature.h>
#include <stdio.h>
namespace gr {
namespace fec {
encoder::sptr
encoder::make(generic_encoder::sptr my_encoder,
size_t input_item_size,
size_t output_item_size)
{
return gnuradio::get_initial_sptr
(new encoder_impl(my_encoder, input_item_size,
output_item_size));
}
encoder_impl::encoder_impl(generic_encoder::sptr my_encoder,
size_t input_item_size,
size_t output_item_size)
: block("fec_encoder",
io_signature::make(1, 1, input_item_size),
io_signature::make(1, 1, output_item_size)),
d_input_item_size(input_item_size),
d_output_item_size(output_item_size)
{
set_fixed_rate(true);
set_relative_rate((double)my_encoder->get_output_size()/(double)my_encoder->get_input_size());
set_output_multiple(my_encoder->get_output_size());
d_encoder = my_encoder;
d_input_size = d_encoder->get_input_size()*d_input_item_size;
d_output_size = d_encoder->get_output_size()*d_output_item_size;
}
encoder_impl::~encoder_impl()
{
}
int
encoder_impl::<API key>(int ninput)
{
return (int)(0.5 + ninput*relative_rate());
}
int
encoder_impl::<API key>(int noutput)
{
return (int)(0.5 + noutput/relative_rate());
}
void
encoder_impl::forecast(int noutput_items,
gr_vector_int& <API key>)
{
<API key>[0] = <API key>(noutput_items);
}
int
encoder_impl::general_work(int noutput_items,
gr_vector_int& ninput_items,
<API key> &input_items,
gr_vector_void_star &output_items)
{
char *inbuffer = (char*)input_items[0];
char *outbuffer = (char*)output_items[0];
//GR_LOG_DEBUG(d_debug_logger, boost::format("%1%, %2%, %3%") \
// % noutput_items % ninput_items[0] % (noutput_items/output_multiple()));
for(int i = 0; i < noutput_items/output_multiple(); i++) {
d_encoder->generic_work((void*)(inbuffer+(i*d_input_size)),
(void*)(outbuffer+(i*d_output_size)));
}
//GR_LOG_DEBUG(d_debug_logger, boost::format("consuming: %1%") \
// % (<API key>(noutput_items)));
//GR_LOG_DEBUG(d_debug_logger, boost::format("returning: %1%") \
// % (noutput_items));
consume_each(<API key>(noutput_items));
return noutput_items;
}
} /* namespace fec */
} /* namespace gr */
|
#include "includes.h"
/**
* XXX: This is temporary and there should be no callers of this outside of
* this file once smb_filename is plumbed through all path based operations.
* The one legitimate caller currently is smb_fname_str_dbg(), which this
* could be made static for.
*/
NTSTATUS <API key>(TALLOC_CTX *ctx,
const struct smb_filename *smb_fname,
char **full_name)
{
if (smb_fname->stream_name) {
/* stream_name must always be NULL if there is no stream. */
SMB_ASSERT(smb_fname->stream_name[0] != '\0');
*full_name = talloc_asprintf(ctx, "%s%s", smb_fname->base_name,
smb_fname->stream_name);
} else {
*full_name = talloc_strdup(ctx, smb_fname->base_name);
}
if (!*full_name) {
return NT_STATUS_NO_MEMORY;
}
return NT_STATUS_OK;
}
/**
* There are actually legitimate callers of this such as functions that
* enumerate streams using the vfs_streaminfo interface and then want to
* operate on each stream.
*/
struct smb_filename *synthetic_smb_fname(TALLOC_CTX *mem_ctx,
const char *base_name,
const char *stream_name,
const SMB_STRUCT_STAT *psbuf,
uint32_t flags)
{
struct smb_filename smb_fname_loc = { 0, };
/* Setup the base_name/stream_name. */
smb_fname_loc.base_name = discard_const_p(char, base_name);
smb_fname_loc.stream_name = discard_const_p(char, stream_name);
smb_fname_loc.flags = flags;
/* Copy the psbuf if one was given. */
if (psbuf)
smb_fname_loc.st = *psbuf;
/* Let cp_smb_filename() do the heavy lifting. */
return cp_smb_filename(mem_ctx, &smb_fname_loc);
}
/**
* Utility function used by VFS calls that must *NOT* operate
* on a stream filename, only the base_name.
*/
struct smb_filename *<API key>(TALLOC_CTX *mem_ctx,
const struct smb_filename *smb_fname_in)
{
struct smb_filename *smb_fname = cp_smb_filename(mem_ctx,
smb_fname_in);
if (smb_fname == NULL) {
return NULL;
}
TALLOC_FREE(smb_fname->stream_name);
return smb_fname;
}
/**
* There are a few legitimate users of this.
*/
struct smb_filename *<API key>(TALLOC_CTX *ctx,
const char *fname,
bool posix_path)
{
char *stream_name = NULL;
char *base_name = NULL;
struct smb_filename *ret;
bool ok;
if (posix_path) {
/* No stream name looked for. */
return synthetic_smb_fname(ctx,
fname,
NULL,
NULL,
<API key>);
}
ok = <API key>(ctx,
fname,
&base_name,
&stream_name);
if (!ok) {
return NULL;
}
ret = synthetic_smb_fname(ctx, base_name, stream_name, NULL, 0);
TALLOC_FREE(base_name);
TALLOC_FREE(stream_name);
return ret;
}
/**
* Return a string using the talloc_tos()
*/
const char *smb_fname_str_dbg(const struct smb_filename *smb_fname)
{
char *fname = NULL;
NTSTATUS status;
if (smb_fname == NULL) {
return "";
}
status = <API key>(talloc_tos(), smb_fname, &fname);
if (!NT_STATUS_IS_OK(status)) {
return "";
}
return fname;
}
/**
* Return a debug string of the path name of an fsp using the talloc_tos().
*/
const char *fsp_str_dbg(const struct files_struct *fsp)
{
return smb_fname_str_dbg(fsp->fsp_name);
}
/**
* Create a debug string for the fnum of an fsp.
*
* This is allocated to talloc_tos() or a string constant
* in certain corner cases. The returned string should
* hence not be free'd directly but only via the talloc stack.
*/
const char *fsp_fnum_dbg(const struct files_struct *fsp)
{
char *str;
if (fsp == NULL) {
return "fnum [fsp is NULL]";
}
if (fsp->fnum == FNUM_FIELD_INVALID) {
return "fnum [invalid value]";
}
str = talloc_asprintf(talloc_tos(), "fnum %llu",
(unsigned long long)fsp->fnum);
if (str == NULL) {
DEBUG(1, ("%s: talloc_asprintf failed\n", __FUNCTION__));
return "fnum [talloc failed!]";
}
return str;
}
struct smb_filename *cp_smb_filename(TALLOC_CTX *mem_ctx,
const struct smb_filename *in)
{
struct smb_filename *out;
size_t base_len = 0;
size_t stream_len = 0;
size_t lcomp_len = 0;
int num = 0;
/* stream_name must always be NULL if there is no stream. */
if (in->stream_name) {
SMB_ASSERT(in->stream_name[0] != '\0');
}
if (in->base_name != NULL) {
base_len = strlen(in->base_name) + 1;
num += 1;
}
if (in->stream_name != NULL) {
stream_len = strlen(in->stream_name) + 1;
num += 1;
}
if (in->original_lcomp != NULL) {
lcomp_len = strlen(in->original_lcomp) + 1;
num += 1;
}
out = <API key>(mem_ctx, struct smb_filename,
num, stream_len + base_len + lcomp_len);
if (out == NULL) {
return NULL;
}
ZERO_STRUCTP(out);
/*
* The following allocations cannot fail as we
* pre-allocated space for them in the out pooled
* object.
*/
if (in->base_name != NULL) {
out->base_name = talloc_memdup(
out, in->base_name, base_len);
<API key>(out->base_name,
out->base_name);
}
if (in->stream_name != NULL) {
out->stream_name = talloc_memdup(
out, in->stream_name, stream_len);
<API key>(out->stream_name,
out->stream_name);
}
if (in->original_lcomp != NULL) {
out->original_lcomp = talloc_memdup(
out, in->original_lcomp, lcomp_len);
<API key>(out->original_lcomp,
out->original_lcomp);
}
out->flags = in->flags;
out->st = in->st;
return out;
}
bool <API key>(const struct smb_filename *smb_fname)
{
/* stream_name must always be NULL if there is no stream. */
if (smb_fname->stream_name) {
SMB_ASSERT(smb_fname->stream_name[0] != '\0');
}
if (smb_fname->flags & <API key>) {
return false;
}
return smb_fname->stream_name != NULL;
}
bool <API key>(const struct smb_filename *smb_fname)
{
if (!<API key>(smb_fname)) {
return false;
}
return strcasecmp_m(smb_fname->stream_name, "::$DATA") == 0;
}
static char bad_ea_name_chars[] = "\"*+,/:;<=>?[\\]|";
bool <API key>(const char *name)
{
int i;
/* EA name is pulled as ascii so we can examine
individual bytes here. */
for (i = 0; name[i] != 0; i++) {
int val = (name[i] & 0xff);
if (val < ' ' || strchr(bad_ea_name_chars, val)) {
return true;
}
}
return false;
}
bool <API key>(struct ea_list *ea_list)
{
for (;ea_list; ea_list = ea_list->next) {
if (<API key>(ea_list->ea.name)) {
return true;
}
}
return false;
}
bool <API key>(TALLOC_CTX *ctx,
const char *filename_in,
char **filename_out,
char **streamname_out)
{
const char *stream_name = NULL;
char *stream_out = NULL;
char *file_out = NULL;
stream_name = strchr_m(filename_in, ':');
if (stream_name) {
stream_out = talloc_strdup(ctx, stream_name);
if (stream_out == NULL) {
return false;
}
file_out = talloc_strndup(ctx,
filename_in,
PTR_DIFF(stream_name, filename_in));
} else {
file_out = talloc_strdup(ctx, filename_in);
}
if (file_out == NULL) {
TALLOC_FREE(stream_out);
return false;
}
if (filename_out) {
*filename_out = file_out;
}
if (streamname_out) {
*streamname_out = stream_out;
}
return true;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using u8 = System.Byte;
using u16 = System.UInt16;
using s32 = System.Int32;
using u32 = System.UInt32;
using gps_time_t = System.UInt64;
namespace MissionPlanner.Utilities
{
public class rtcm3 : ICorrections
{
const byte RTCM3PREAMB = 0xD3;
int step = 0;
byte[] buffer = new u8[1024 * 4];
u32 payloadlen = 0;
int msglencount = 0;
rtcmpreamble pre;
public int Read(byte data)
{
switch (step)
{
default:
case 0:
if (data == RTCM3PREAMB)
{
step = 1;
buffer[0] = data;
}
break;
case 1:
buffer[1] = data;
step++;
break;
case 2:
buffer[2] = data;
step++;
pre = new rtcmpreamble();
pre.Read(buffer);
payloadlen = pre.length;
msglencount = 0;
// reset on oversize packet
if (payloadlen > buffer.Length)
step = 0;
break;
case 3:
if (msglencount < (payloadlen))
{
buffer[msglencount + 3] = data;
msglencount++;
}
else
{
step++;
goto case 4;
}
break;
case 4:
buffer[payloadlen + 3] = data;
step++;
break;
case 5:
buffer[payloadlen + 3 + 1] = data;
step++;
break;
case 6:
buffer[payloadlen + 3 + 2] = data;
payloadlen = payloadlen + 3;
u32 crc = crc24.crc24q(buffer, payloadlen, 0);
u32 crcpacket = getbitu(buffer, payloadlen * 8, 24);
if (crc == crcpacket)
{
rtcmheader head = new rtcmheader();
head.Read(buffer);
step = 0;
return head.messageno;
}
step = 0;
break;
}
return -1;
}
static uint getbitu(u8[] buff, u32 pos, u32 len)
{
uint bits = 0;
u32 i;
for (i = pos; i < pos + len; i++)
bits = (uint)((bits << 1) + ((buff[i / 8] >> (int)(7 - i % 8)) & 1u));
return bits;
}
static void setbitu(u8[] buff, u32 pos, u32 len, u32 data)
{
u32 mask = 1u << (int)(len - 1);
if (len <= 0 || 32 < len) return;
for (u32 i = pos; i < pos + len; i++, mask >>= 1)
{
if ((data & mask) > 0)
buff[i / 8] |= (byte)(1u << (int)(7 - i % 8));
else
buff[i / 8] &= (byte)(~(1u << (int)(7 - i % 8)));
}
}
public class rtcmpreamble
{
public u8 preamble = RTCM3PREAMB;
public u8 resv1;
public u16 length;
public void Read(byte[] buffer)
{
uint i = 0;
preamble = (byte)getbitu(buffer, i, 8); i += 8;
resv1 = (byte)getbitu(buffer, i, 6); i += 6;
length = (u16)getbitu(buffer, i, 10); i += 10;
}
public byte[] Write(byte[] buffer)
{
uint i = 0;
setbitu(buffer, i, 8, RTCM3PREAMB); i += 8;
setbitu(buffer, i, 6, resv1); i += 6;
setbitu(buffer, i, 10, length); i += 10;
return buffer;
}
}
public class rtcmheader
{
public u16 messageno;
public u16 refstationid;
public u32 epoch;
public u8 sync;
public u8 nsat;
public u8 smoothind;
public u8 smoothint;
public void Read(byte[] buffer)
{
u32 i = 24;
messageno = (u16)getbitu(buffer, i, 12); i += 12; /* message no */
refstationid = (u16)getbitu(buffer, i, 12); i += 12; /* ref station id */
epoch = (u32)getbitu(buffer, i, 30); i += 30; /* gps epoch time */
sync = (u8)getbitu(buffer, i, 1); i += 1; /* synchronous gnss flag */
nsat = (u8)getbitu(buffer, i, 5); i += 5; /* no of satellites */
smoothind = (u8)getbitu(buffer, i, 1); i += 1; /* smoothing indicator */
smoothint = (u8)getbitu(buffer, i, 3); i += 3; /* smoothing interval */
}
public byte[] Write(byte[] buffer)
{
u32 i = 24;
setbitu(buffer, i, 12, messageno); i += 12; /* message no */
setbitu(buffer, i, 12, refstationid); i += 12; /* ref station id */
setbitu(buffer, i, 30, epoch); i += 30; /* gps epoch time */
setbitu(buffer, i, 1, sync); i += 1; /* synchronous gnss flag */
setbitu(buffer, i, 5, nsat); i += 5; /* no of satellites */
setbitu(buffer, i, 1, smoothind); i += 1; /* smoothing indicator */
setbitu(buffer, i, 3, smoothint); i += 3; /* smoothing interval */
return buffer;
}
}
public class crc24
{
static u32[] crc24qtab = new u32[] {
0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC, 0x9F7F17,
0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5, 0x3EFE2E,
0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65, 0x5A319E,
0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C, 0xFBB0A7,
0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205, 0x93AEFE,
0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C, 0x322FC7,
0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C, 0x56E077,
0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5, 0xF7614E,
0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E, 0x86DCC5,
0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107, 0x275DFC,
0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7, 0x43924C,
0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E, 0xE21375,
0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7, 0x8A0D2C,
0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE, 0x2B8C15,
0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E, 0x4F43A5,
0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67, 0xEEC29C,
0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448, 0xAC38B3,
0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571, 0x0DB98A,
0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1, 0x69763A,
0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8, 0xC8F703,
0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1, 0xA0E95A,
0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498, 0x016863,
0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28, 0x65A7D3,
0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11, 0xC426EA,
0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A, 0xB59B61,
0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3, 0x141A58,
0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913, 0x70D5E8,
0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A, 0xD154D1,
0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673, 0xB94A88,
0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A, 0x18CBB1,
0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA, 0x7C0401,
0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3, 0xDD8538
};
/** Calculate Qualcomm 24-bit Cyclical Redundancy Check (CRC-24Q).
*
* The CRC polynomial used is:
* \f[
* x^{24} + x^{23} + x^{18} + x^{17} + x^{14} + x^{11} + x^{10} +
* x^7 + x^6 + x^5 + x^4 + x^3 + x+1
* \f]
* Mask 0x1864CFB, not reversed, not XOR'd
*
* \param buf Array of data to calculate CRC for
* \param len Length of data array
* \param crc Initial CRC value
*
* \return CRC-24Q value
*/
public static u32 crc24q(u8[] buf, u32 len, u32 crc)
{
for (u32 i = 0; i < len; i++)
crc = ((crc << 8) & 0xFFFFFF) ^ crc24qtab[(crc >> 16) ^ buf[i]];
return crc;
}
}
public s32 length
{
get { return (s32)(payloadlen + 2 + 1); }
}
public u8[] packet
{
get { return buffer; }
}
}
}
|
#ifndef <API key>
#define <API key>
#include "allegro5/base.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Type: <API key>
*/
typedef struct <API key>
{
int width;
int height;
int format;
int refresh_rate;
} <API key>;
AL_FUNC(int, <API key>, (void));
AL_FUNC(<API key>*, al_get_display_mode, (int index,
<API key> *mode));
#ifdef __cplusplus
}
#endif
#endif
/* vim: set ts=8 sts=3 sw=3 et: */
|
// Set iterators produces entries in the order they were inserted.
var set = Set();
var i;
for (i = 7; i !== 1; i = i * 7 % 1117)
set.add(i);
assertEq(set.size, 557);
i = 7;
for (var v of set) {
assertEq(v, i);
i = i * 7 % 1117;
}
assertEq(i, 1);
|
% include base.dockerfile
RUN \
apt-get install -qy --<API key> \
# Testing decisionlib (see etc/taskcluster/mock.py)
python3-coverage \
# Multiple C/C++ dependencies built from source
g++ \
make \
cmake \
# ANGLE
xorg-dev \
# mozjs (SpiderMonkey)
autoconf2.13 \
# Bindgen (for SpiderMonkey bindings)
clang \
# GStreamer
<API key>.0-dev \
# OpenSSL
libssl1.0-dev \
# blurz
libdbus-1-dev \
# Skia
libglu1-mesa-dev \
libbz2-dev \
&& \
curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain none -y && \
curl -sSfL \
https://github.com/mozilla/sccache/releases/download/0.2.7/sccache-0.2.<API key>.tar.gz \
| tar -xz --strip-components=1 -C /usr/local/bin/ \
sccache-0.2.<API key>/sccache
|
package org.openmrs.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Place it on classes which you want to be beans created conditionally based on
* OpenMRS version and/or started modules.
*
* @since 1.10, 1.9.8, 1.8.5, 1.7.5
*/
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OpenmrsProfile {
public String openmrsVersion() default "";
public String[] modules() default {};
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unicode tests - reference rending</title>
<style>
/* work around unreliable form-control rendering on Gtk+3 (see bug 1223198): */
input { -moz-appearance: none; }
</style>
</head>
<body>
<div><p lang="hi">स्टार</p></div>
<input disabled>
</body>
</html>
|
<!
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
<!DOCTYPE html>
<html>
<head>
<title>CSS Masking: Test clip-path and polygon with margin-box</title>
<link rel="author" title="Dirk Schulze" href="mailto:dschulze@adobe.com">
<link rel="help" href="http://www.w3.org/TR/css-masking-1/#clipping-paths">
<link rel="help" href="http://www.w3.org/TR/css-masking-1/#propdef-clip-path">
<link rel="match" href="<API key>.html">
<meta name="assert" content="The clip-path property allows specifying
basic shapes and reference boxes. This test checks the usage of the correct
reference box 'margin-box' for the polygon() function by mixing percentage
and absolute values as coordinates. On sucess you should see a green
vertical stripe next to a lime green vertical stripe. Both should be of equal
size.">
</head>
<style>
div {
width: 50px;
height: 50px;
background-color: green;
padding: 25px;
margin: 25px;
border: red solid 25px;
border-left: lime solid 25px;
}
</style>
<body>
<p>The test passes if you see a green vertical stripe next to a lime green vertical stripe, both stripes should be of equal size and there should be no red.</p>
<div style="clip-path: polygon(12.5% 25%, 37.5% 50px, 75px 50%, 25px 100px) margin-box"></div>
</body>
</html>
|
use std::any::Any;
use std::boxed::FnBox;
use std::cell::RefCell;
use std::panic::{PanicInfo, take_hook, set_hook};
use std::sync::{Once, ONCE_INIT};
use std::thread;
// only set the panic hook once
static HOOK_SET: Once = ONCE_INIT;
TLS data pertaining to how failures should be reported
pub struct PanicHandlerLocal {
failure handler passed through <API key>
pub fail: Box<FnBox(&Any)>
}
thread_local!(pub static LOCAL_INFO: RefCell<Option<PanicHandlerLocal>> = RefCell::new(None));
Set the thread-local panic hook
pub fn <API key>(local: Box<FnBox(&Any)>) {
LOCAL_INFO.with(|i| *i.borrow_mut() = Some(PanicHandlerLocal { fail: local }));
}
Initiates the custom panic hook
Should be called in main() after arguments have been parsed
pub fn initiate_panic_hook() {
// Set the panic handler only once. It is global.
HOOK_SET.call_once(|| {
// The original backtrace-printing hook. We still want to call this
let hook = take_hook();
let new_hook = move |info: &PanicInfo| {
let payload = info.payload();
let name = thread::current().name().unwrap_or("<unknown thread>").to_string();
// Notify error handlers stored in LOCAL_INFO if any
LOCAL_INFO.with(|i| {
if let Some(local_info) = i.borrow_mut().take() {
debug!("Thread `{}` failed, notifying error handlers", name);
(local_info.fail).call_box((payload, ));
} else {
hook(&info);
}
});
};
set_hook(Box::new(new_hook));
});
}
|
package tc.oc.commons.core.plugin;
import java.util.Set;
import tc.oc.commons.core.commands.CommandRegistry;
import tc.oc.commons.core.commands.Commands;
import tc.oc.commons.core.commands.NestedCommands;
import tc.oc.minecraft.api.event.Activatable;
import tc.oc.commons.core.inject.Facet;
/**
* Something that needs to be enabled and disabled (along with a plugin).
*
* Each plugin has a private set of facets, configured through a {@link PluginFacetBinder}.
* To get the instances, @Inject a {@link Set< PluginFacet >}.
*
* Facets are automatically enabled and disabled at the same time as the
* plugin they are bound to.
*
* If a facet implements the {@link tc.oc.minecraft.api.event.Listener} interfaces,
* it will also be registered to receive events.
*
* If it implements {@link Commands} or {@link NestedCommands}, it will be registered
* through a {@link CommandRegistry}.
*
* Specific plugins may do other automatic things with their own facets, be we
* don't yet have a framework for extending facets across all plugins.
*/
public interface PluginFacet extends Facet, Activatable {
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http:
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>OHLC Charts</title>
<!--[if IE]><script language="javascript" type="text/javascript" src="../excanvas.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../jquery.jqplot.css" />
<link rel="stylesheet" type="text/css" href="examples.css" />
<!-- BEGIN: load jquery -->
<script language="javascript" type="text/javascript" src="../jquery-1.4.2.min.js"></script>
<!-- END: load jquery -->
<!-- BEGIN: load jqplot -->
<script language="javascript" type="text/javascript" src="../jquery.jqplot.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.dateAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.<API key>.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.ohlcRenderer.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.highlighter.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.cursor.js"></script>
<style type="text/css">
.jqplot-target {
margin-bottom: 2em;
}
pre {
background: #D8F4DC;
border: 1px solid rgb(200, 200, 200);
padding-top: 1em;
padding-left: 3em;
padding-bottom: 1em;
margin-top: 1em;
margin-bottom: 4em;
}
p {
margin: 2em 0;
}
.note {
font-size: 0.8em;
}
</style>
<!-- END: load jqplot -->
<script class="common" type="text/javascript">
$.jqplot.config.enablePlugins = true;
ohlc = [['07/06/09', 138.7, 139.68, 135.18, 135.4],
['06/29/09', 143.46, 144.66, 139.79, 140.02],
['06/22/09', 140.67, 143.56, 132.88, 142.44],
['06/15/09', 136.01, 139.5, 134.53, 139.48],
['06/08/09', 143.82, 144.56, 136.04, 136.97],
['06/01/09', 136.47, 146.4, 136, 144.67],
['05/26/09', 124.76, 135.9, 124.55, 135.81],
['05/18/09', 123.73, 129.31, 121.57, 122.5],
['05/11/09', 127.37, 130.96, 119.38, 122.42],
['05/04/09', 128.24, 133.5, 126.26, 129.19],
['04/27/09', 122.9, 127.95, 122.66, 127.24],
['04/20/09', 121.73, 127.2, 118.6, 123.9],
['04/13/09', 120.01, 124.25, 115.76, 123.42],
['04/06/09', 114.94, 120, 113.28, 119.57],
['03/30/09', 104.51, 116.13, 102.61, 115.99],
['03/23/09', 102.71, 109.98, 101.75, 106.85],
['03/16/09', 96.53, 103.48, 94.18, 101.59],
['03/09/09', 84.18, 97.2, 82.57, 95.93],
['03/02/09', 88.12, 92.77, 82.33, 85.3],
['02/23/09', 91.65, 92.92, 86.51, 89.31],
['02/17/09', 96.87, 97.04, 89, 91.2],
['02/09/09', 100, 103, 95.77, 99.16],
['02/02/09', 89.1, 100, 88.9, 99.72],
['01/26/09', 88.86, 95, 88.3, 90.13],
['01/20/09', 81.93, 90, 78.2, 88.36],
['01/12/09', 90.46, 90.99, 80.05, 82.33],
['01/05/09', 93.17, 97.17, 90.04, 90.58],
['12/29/08', 86.52, 91.04, 84.72, 90.75],
['12/22/08', 90.02, 90.03, 84.55, 85.81],
['12/15/08', 95.99, 96.48, 88.02, 90],
['12/08/08', 97.28, 103.6, 92.53, 98.27],
['12/01/08', 91.3, 96.23, 86.5, 94],
['11/24/08', 85.21, 95.25, 84.84, 92.67],
['11/17/08', 88.48, 91.58, 79.14, 82.58],
['11/10/08', 100.17, 100.4, 86.02, 90.24],
['11/03/08', 105.93, 111.79, 95.72, 98.24],
['10/27/08', 95.07, 112.19, 91.86, 107.59],
['10/20/08', 99.78, 101.25, 90.11, 96.38],
['10/13/08', 104.55, 116.4, 85.89, 97.4],
['10/06/08', 91.96, 101.5, 85, 96.8],
['09/29/08', 119.62, 119.68, 94.65, 97.07],
['09/22/08', 139.94, 140.25, 123, 128.24],
['09/15/08', 142.03, 147.69, 120.68, 140.91],
['09/08/08', 164.57, 164.89, 146, 148.94]
];
ohlc_b = [['07/06/09', 138.7, 139.68, 135.18, 135.4, 'j'],
['06/29/09', 143.46, 144.66, 139.79, 140.02, 'q'],
['06/22/09', 140.67, 143.56, 132.88, 142.44, 'p'],
['06/15/09', 136.01, 139.5, 134.53, 139.48, 'l'],
['06/08/09', 143.82, 144.56, 136.04, 136.97, 'o'],
['06/01/09', 136.47, 146.4, 136, 144.67, 't'],
['05/26/09', 124.76, 135.9, 124.55, 135.81, '_'],
['05/18/09', 123.73, 129.31, 121.57, 122.5, 'c'],
['05/11/09', 127.37, 130.96, 119.38, 122.42, 'h'],
['05/04/09', 128.24, 133.5, 126.26, 129.19, 'a'],
['04/27/09', 122.9, 127.95, 122.66, 127.24, 'r'],
['04/20/09', 121.73, 127.2, 118.6, 123.9, 't'],
['04/13/09', 120.01, 124.25, 115.76, 123.42, 's']
];
hlc = [['07/06/09', 139.68, 135.18, 135.4],
['06/29/09', 144.66, 139.79, 140.02],
['06/22/09', 143.56, 132.88, 142.44],
['06/15/09', 139.5, 134.53, 139.48],
['06/08/09', 144.56, 136.04, 136.97],
['06/01/09', 146.4, 136, 144.67],
['05/26/09', 135.9, 124.55, 135.81],
['05/18/09', 129.31, 121.57, 122.5],
['05/11/09', 130.96, 119.38, 122.42],
['05/04/09', 133.5, 126.26, 129.19],
['04/27/09', 127.95, 122.66, 127.24],
['04/20/09', 127.2, 118.6, 123.9],
['04/13/09', 124.25, 115.76, 123.42],
['04/06/09', 120, 113.28, 119.57],
['03/30/09', 116.13, 102.61, 115.99],
['03/23/09', 109.98, 101.75, 106.85],
['03/16/09', 103.48, 94.18, 101.59],
['03/09/09', 97.2, 82.57, 95.93],
['03/02/09', 92.77, 82.33, 85.3],
['02/23/09', 92.92, 86.51, 89.31],
['02/17/09', 97.04, 89, 91.2],
['02/09/09', 103, 95.77, 99.16],
['02/02/09', 100, 88.9, 99.72],
['01/26/09', 95, 88.3, 90.13],
['01/20/09', 90, 78.2, 88.36],
['01/12/09', 90.99, 80.05, 82.33],
['01/05/09', 97.17, 90.04, 90.58],
['12/29/08', 91.04, 84.72, 90.75],
['12/22/08', 90.03, 84.55, 85.81],
['12/15/08', 96.48, 88.02, 90],
['12/08/08', 103.6, 92.53, 98.27],
['12/01/08', 96.23, 86.5, 94],
['11/24/08', 95.25, 84.84, 92.67],
['11/17/08', 91.58, 79.14, 82.58],
['11/10/08', 100.4, 86.02, 90.24],
['11/03/08', 111.79, 95.72, 98.24],
['10/27/08', 112.19, 91.86, 107.59],
['10/20/08', 101.25, 90.11, 96.38],
['10/13/08', 116.4, 85.89, 97.4],
['10/06/08', 101.5, 85, 96.8],
['09/29/08', 119.68, 94.65, 97.07],
['09/22/08', 140.25, 123, 128.24],
['09/15/08', 147.69, 120.68, 140.91],
['09/08/08', 164.89, 146, 148.94]
];
</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot1 = $.jqplot('chart1',[ohlc],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot2 = $.jqplot('chart2',[ohlc],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{candleStick:true}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
},
highlighter: {
showMarker:false,
tooltipAxes: 'xy',
yvalues: 4,
formatString:'<table class="jqplot-highlighter"> \
<tr><td>date:</td><td>%s</td></tr> \
<tr><td>open:</td><td>%s</td></tr> \
<tr><td>hi:</td><td>%s</td></tr> \
<tr><td>low:</td><td>%s</td></tr> \
<tr><td>close:</td><td>%s</td></tr></table>'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot2b = $.jqplot('chart2b',[ohlc_b],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{candleStick:true}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
},
highlighter: {
showMarker:false,
tooltipAxes: 'xy',
yvalues: 5,
formatString:'<table class="jqplot-highlighter"> \
<tr><td>date:</td><td>%s</td></tr> \
<tr><td>open:</td><td>%s</td></tr> \
<tr><td>hi:</td><td>%s</td></tr> \
<tr><td>low:</td><td>%s</td></tr> \
<tr><td>close:</td><td>%s</td></tr> \
<tr><td>letter:</td><td>%s</td></tr></table>'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot3 = $.jqplot('chart3',[hlc],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%Y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
var catOHLC = [[1, 138.7, 139.68, 135.18, 135.4],
[2, 143.46, 144.66, 139.79, 140.02],
[3, 140.67, 143.56, 132.88, 142.44],
[4, 136.01, 139.5, 134.53, 139.48],
[5, 143.82, 144.56, 136.04, 136.97],
[6, 136.47, 146.4, 136, 144.67],
[7, 124.76, 135.9, 124.55, 135.81],
[8, 123.73, 129.31, 121.57, 122.5]];
var ticks = ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue'];
plot4 = $.jqplot('chart4',[catOHLC],{
axes: {
xaxis: {
renderer:$.jqplot.<API key>,
ticks:ticks
},
yaxis: {
tickOptions:{formatString:'$%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{candleStick:true}}]
});
});</script>
<script type="text/javascript">
$(document).ready(function(){
$('script.code').each(function(index) {
$('pre.code').eq(index).text($(this).html());
});
$('script.common').each(function(index) {
$('pre.common').eq(index).html($(this).html());
});
$(document).unload(function() {$('*').unbind(); });
});
</script>
</head>
<body>
<?php include "nav.inc"; ?>
<div id="chart1" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart2" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart2b" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart3" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart4" class="code" style="margin:20px;height:320px; width:500px;"></div>
<pre class="code"></pre>
<p>The examples below use the folowing code:</p>
<pre class="common"></pre>
</body>
</html>
|
import os.path
import time
from django.core.management.base import BaseCommand
from django.conf import settings
import mitxmako.middleware as middleware
from django.core.mail import send_mass_mail
import sys
import datetime
middleware.MakoMiddleware()
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
class Command(BaseCommand):
help = \
'''Sends an e-mail to all users in a text file.
E.g.
manage.py userlist.txt message logfile.txt rate
userlist.txt -- list of all users
message -- prefix for template with message
logfile.txt -- where to log progress
rate -- messages per second
'''
log_file = None
def hard_log(self, text):
self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n')
def handle(self, *args, **options):
(user_file, message_base, logfilename, ratestr) = args
users = [u.strip() for u in open(user_file).readlines()]
message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render()
subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip()
rate = int(ratestr)
self.log_file = open(logfilename, "a+", buffering=0)
i = 0
for users in chunks(users, rate):
emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users]
self.hard_log(" ".join(users))
send_mass_mail(emails, fail_silently=False)
time.sleep(1)
print datetime.datetime.utcnow().isoformat(), i
i = i + len(users)
# Emergency interruptor
if os.path.exists("/tmp/stopemails.txt"):
self.log_file.close()
sys.exit(-1)
self.log_file.close()
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
// This Source Code Form is subject to the terms of the Mozilla
#ifndef EIGEN_STABLENORM_H
#define EIGEN_STABLENORM_H
namespace Eigen {
namespace internal {
template<typename ExpressionType, typename Scalar>
inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale)
{
using std::max;
Scalar maxCoeff = bl.cwiseAbs().maxCoeff();
if (maxCoeff>scale)
{
ssq = ssq * numext::abs2(scale/maxCoeff);
Scalar tmp = Scalar(1)/maxCoeff;
if(tmp > NumTraits<Scalar>::highest())
{
invScale = NumTraits<Scalar>::highest();
scale = Scalar(1)/invScale;
}
else
{
scale = maxCoeff;
invScale = tmp;
}
}
// TODO if the maxCoeff is much much smaller than the current scale,
// then we can neglect this sub vector
if(scale>Scalar(0)) // if scale==0, then bl is 0
ssq += (bl*invScale).squaredNorm();
}
template<typename Derived>
inline typename NumTraits<typename traits<Derived>::Scalar>::Real
blueNorm_impl(const EigenBase<Derived>& _vec)
{
typedef typename Derived::RealScalar RealScalar;
typedef typename Derived::Index Index;
using std::pow;
<API key>(min);
<API key>(max);
using std::sqrt;
using std::abs;
const Derived& vec(_vec.derived());
static bool initialized = false;
static RealScalar b1, b2, s1m, s2m, overfl, rbig, relerr;
if(!initialized)
{
int ibeta, it, iemin, iemax, iexp;
RealScalar eps;
// This program calculates the machine-dependent constants
// bl, b2, slm, s2m, relerr overfl
// from the "basic" machine-dependent numbers
// nbig, ibeta, it, iemin, iemax, rbig.
// The following define the basic machine-dependent constants.
// For portability, the PORT subprograms "ilmaeh" and "rlmach"
// are used. For any specific computer, each of the assignment
// statements can be replaced
ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers
it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa
iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent
iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent
rbig = (std::numeric_limits<RealScalar>::max)(); // largest floating-point number
iexp = -((1-iemin)/2);
b1 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // lower boundary of midrange
iexp = (iemax + 1 - it)/2;
b2 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // upper boundary of midrange
iexp = (2-iemin)/2;
s1m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for lower range
iexp = - ((iemax+it)/2);
s2m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for upper range
overfl = rbig*s2m; // overflow boundary for abig
eps = RealScalar(pow(double(ibeta), 1-it));
relerr = sqrt(eps); // tolerance for neglecting asml
initialized = true;
}
Index n = vec.size();
RealScalar ab2 = b2 / RealScalar(n);
RealScalar asml = RealScalar(0);
RealScalar amed = RealScalar(0);
RealScalar abig = RealScalar(0);
for(typename Derived::InnerIterator it(vec, 0); it; ++it)
{
RealScalar ax = abs(it.value());
if(ax > ab2) abig += numext::abs2(ax*s2m);
else if(ax < b1) asml += numext::abs2(ax*s1m);
else amed += numext::abs2(ax);
}
if(abig > RealScalar(0))
{
abig = sqrt(abig);
if(abig > overfl)
{
return rbig;
}
if(amed > RealScalar(0))
{
abig = abig/s2m;
amed = sqrt(amed);
}
else
return abig/s2m;
}
else if(asml > RealScalar(0))
{
if (amed > RealScalar(0))
{
abig = sqrt(amed);
amed = sqrt(asml) / s1m;
}
else
return sqrt(asml)/s1m;
}
else
return sqrt(amed);
asml = (min)(abig, amed);
abig = (max)(abig, amed);
if(asml <= abig*relerr)
return abig;
else
return abig * sqrt(RealScalar(1) + numext::abs2(asml/abig));
}
} // end namespace internal
/** \returns the \em l2 norm of \c *this avoiding underflow and overflow.
* This version use a blockwise two passes algorithm:
* 1 - find the absolute largest coefficient \c s
* 2 - compute \f$ s \Vert \frac{*this}{s} \Vert \f$ in a standard way
*
* For architecture/scalar types supporting vectorization, this version
* is faster than blueNorm(). Otherwise the blueNorm() is much faster.
*
* \sa norm(), blueNorm(), hypotNorm()
*/
template<typename Derived>
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
MatrixBase<Derived>::stableNorm() const
{
<API key>(min);
using std::sqrt;
const Index blockSize = 4096;
RealScalar scale(0);
RealScalar invScale(1);
RealScalar ssq(0); // sum of square
enum {
Alignment = (int(Flags)&DirectAccessBit) || (int(Flags)&AlignedBit) ? 1 : 0
};
Index n = size();
Index bi = internal::first_aligned(derived());
if (bi>0)
internal::stable_norm_kernel(this->head(bi), ssq, scale, invScale);
for (; bi<n; bi+=blockSize)
internal::stable_norm_kernel(this->segment(bi,(min)(blockSize, n - bi)).template <API key><Alignment>(), ssq, scale, invScale);
return scale * sqrt(ssq);
}
/** \returns the \em l2 norm of \c *this using the Blue's algorithm.
* A Portable Fortran Program to Find the Euclidean Norm of a Vector,
* ACM TOMS, Vol 4, Issue 1, 1978.
*
* For architecture/scalar types without vectorization, this version
* is much faster than stableNorm(). Otherwise the stableNorm() is faster.
*
* \sa norm(), stableNorm(), hypotNorm()
*/
template<typename Derived>
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
MatrixBase<Derived>::blueNorm() const
{
return internal::blueNorm_impl(*this);
}
/** \returns the \em l2 norm of \c *this avoiding undeflow and overflow.
* This version use a concatenation of hypot() calls, and it is very slow.
*
* \sa norm(), stableNorm()
*/
template<typename Derived>
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
MatrixBase<Derived>::hypotNorm() const
{
return this->cwiseAbs().redux(internal::scalar_hypot_op<RealScalar>());
}
} // end namespace Eigen
#endif // EIGEN_STABLENORM_H
|
# -*- coding: utf-8 -*-
# OpenERP, Open Source Management Solution
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import itertools
import logging
from functools import partial
from itertools import repeat
from lxml import etree
from lxml.builder import E
import openerp
from openerp import SUPERUSER_ID, models
from openerp import tools
import openerp.exceptions
from openerp.osv import fields, osv, expression
from openerp.tools.translate import _
from openerp.http import request
_logger = logging.getLogger(__name__)
# Basic res.groups and res.users
class res_groups(osv.osv):
_name = "res.groups"
_description = "Access Groups"
_rec_name = 'full_name'
_order = 'name'
def _get_full_name(self, cr, uid, ids, field, arg, context=None):
res = {}
for g in self.browse(cr, uid, ids, context):
if g.category_id:
res[g.id] = '%s / %s' % (g.category_id.name, g.name)
else:
res[g.id] = g.name
return res
def _search_group(self, cr, uid, obj, name, args, context=None):
operand = args[0][2]
operator = args[0][1]
lst = True
if isinstance(operand, bool):
domains = [[('name', operator, operand)], [('category_id.name', operator, operand)]]
if operator in expression.<API key> == (not operand):
return expression.AND(domains)
else:
return expression.OR(domains)
if isinstance(operand, basestring):
lst = False
operand = [operand]
where = []
for group in operand:
values = filter(bool, group.split('/'))
group_name = values.pop().strip()
category_name = values and '/'.join(values).strip() or group_name
group_domain = [('name', operator, lst and [group_name] or group_name)]
category_domain = [('category_id.name', operator, lst and [category_name] or category_name)]
if operator in expression.<API key> and not values:
category_domain = expression.OR([category_domain, [('category_id', '=', False)]])
if (operator in expression.<API key>) == (not values):
sub_where = expression.AND([group_domain, category_domain])
else:
sub_where = expression.OR([group_domain, category_domain])
if operator in expression.<API key>:
where = expression.AND([where, sub_where])
else:
where = expression.OR([where, sub_where])
return where
_columns = {
'name': fields.char('Name', required=True, translate=True),
'users': fields.many2many('res.users', '<API key>', 'gid', 'uid', 'Users'),
'model_access': fields.one2many('ir.model.access', 'group_id', 'Access Controls'),
'rule_groups': fields.many2many('ir.rule', 'rule_group_rel',
'group_id', 'rule_group_id', 'Rules', domain=[('global', '=', False)]),
'menu_access': fields.many2many('ir.ui.menu', '<API key>', 'gid', 'menu_id', 'Access Menu'),
'view_access': fields.many2many('ir.ui.view', '<API key>', 'group_id', 'view_id', 'Views'),
'comment' : fields.text('Comment', size=250, translate=True),
'category_id': fields.many2one('ir.module.category', 'Application', select=True),
'full_name': fields.function(_get_full_name, type='char', string='Group Name', fnct_search=_search_group),
}
_sql_constraints = [
('name_uniq', 'unique (category_id, name)', 'The name of the group must be unique within an application!')
]
def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
# add explicit ordering if search is sorted on full_name
if order and order.startswith('full_name'):
ids = super(res_groups, self).search(cr, uid, args, context=context)
gs = self.browse(cr, uid, ids, context)
gs.sort(key=lambda g: g.full_name, reverse=order.endswith('DESC'))
gs = gs[offset:offset+limit] if limit else gs[offset:]
return map(int, gs)
return super(res_groups, self).search(cr, uid, args, offset, limit, order, context, count)
def copy(self, cr, uid, id, default=None, context=None):
group_name = self.read(cr, uid, [id], ['name'])[0]['name']
default.update({'name': _('%s (copy)')%group_name})
return super(res_groups, self).copy(cr, uid, id, default, context)
def write(self, cr, uid, ids, vals, context=None):
if 'name' in vals:
if vals['name'].startswith('-'):
raise osv.except_osv(_('Error'),
_('The name of the group can not start with "-"'))
res = super(res_groups, self).write(cr, uid, ids, vals, context=context)
self.pool['ir.model.access'].<API key>(cr)
self.pool['res.users'].has_group.clear_cache(self.pool['res.users'])
return res
class res_users(osv.osv):
""" User class. A res.users record models an OpenERP user and is different
from an employee.
res.users class now inherits from res.partner. The partner model is
used to store the data related to the partner: lang, name, address,
avatar, ... The user model is now dedicated to technical data.
"""
__admin_ids = {}
_uid_cache = {}
_inherits = {
'res.partner': 'partner_id',
}
_name = "res.users"
_description = 'Users'
def _set_new_password(self, cr, uid, id, name, value, args, context=None):
if value is False:
# Do not update the password if no value is provided, ignore silently.
# For example web client submits False values for all empty fields.
return
if uid == id:
# To change their own password users must use the client-specific change password wizard,
# so that the new password is immediately used for further RPC requests, otherwise the user
# will face unexpected 'Access Denied' exceptions.
raise osv.except_osv(_('Operation Canceled'), _('Please use the change password wizard (in User Preferences or User menu) to change your own password.'))
self.write(cr, uid, id, {'password': value})
def _get_password(self, cr, uid, ids, arg, karg, context=None):
return dict.fromkeys(ids, '')
_columns = {
'id': fields.integer('ID'),
'login_date': fields.date('Latest connection', select=1, copy=False),
'partner_id': fields.many2one('res.partner', required=True,
string='Related Partner', ondelete='restrict',
help='Partner-related data of the user', auto_join=True),
'login': fields.char('Login', size=64, required=True,
help="Used to log into the system"),
'password': fields.char('Password', size=64, invisible=True, copy=False,
help="Keep empty if you don't want the user to be able to connect on the system."),
'new_password': fields.function(_get_password, type='char', size=64,
fnct_inv=_set_new_password, string='Set Password',
help="Specify a value only when creating a user or if you're "\
"changing the user's password, otherwise leave empty. After "\
"a change of password, the user has to login again."),
'signature': fields.html('Signature'),
'active': fields.boolean('Active'),
'action_id': fields.many2one('ir.actions.actions', 'Home Action', help="If specified, this action will be opened at log on for this user, in addition to the standard menu."),
'groups_id': fields.many2many('res.groups', '<API key>', 'uid', 'gid', 'Groups'),
# Special behavior for this field: res.company.search() will only return the companies
# available to the current user (should be the user's companies?), when the user_preference
# context is set.
'company_id': fields.many2one('res.company', 'Company', required=True,
help='The company this user is currently working for.', context={'user_preference': True}),
'company_ids':fields.many2many('res.company','<API key>','user_id','cid','Companies'),
}
# overridden inherited fields to bypass access rights, in case you have
# access to the user but not its corresponding partner
name = openerp.fields.Char(related='partner_id.name', inherited=True)
email = openerp.fields.Char(related='partner_id.email', inherited=True)
def on_change_login(self, cr, uid, ids, login, context=None):
if login and tools.single_email_re.match(login):
return {'value': {'email': login}}
return {}
def onchange_state(self, cr, uid, ids, state_id, context=None):
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool.get('res.partner').onchange_state(cr, uid, partner_ids, state_id, context=context)
def onchange_type(self, cr, uid, ids, is_company, context=None):
""" Wrapper on the user.partner onchange_type, because some calls to the
partner form view applied to the user may trigger the
partner.onchange_type method, but applied to the user object.
"""
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool['res.partner'].onchange_type(cr, uid, partner_ids, is_company, context=context)
def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
""" Wrapper on the user.partner onchange_address, because some calls to the
partner form view applied to the user may trigger the
partner.onchange_type method, but applied to the user object.
"""
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool['res.partner'].onchange_address(cr, uid, partner_ids, use_parent_address, parent_id, context=context)
def _check_company(self, cr, uid, ids, context=None):
return all(((this.company_id in this.company_ids) or not this.company_ids) for this in self.browse(cr, uid, ids, context))
_constraints = [
(_check_company, 'The chosen company is not in the allowed companies for this user', ['company_id', 'company_ids']),
]
_sql_constraints = [
('login_key', 'UNIQUE (login)', 'You can not have two users with the same login !')
]
def _get_company(self,cr, uid, context=None, uid2=False):
if not uid2:
uid2 = uid
# Use read() to compute default company, and pass load=_classic_write to
# avoid useless name_get() calls. This will avoid prefetching fields
# while computing default values for new db columns, as the
# db backend may not be fully initialized yet.
user_data = self.pool['res.users'].read(cr, uid, uid2, ['company_id'],
context=context, load='_classic_write')
comp_id = user_data['company_id']
return comp_id or False
def _get_companies(self, cr, uid, context=None):
c = self._get_company(cr, uid, context)
if c:
return [c]
return False
def _get_group(self,cr, uid, context=None):
dataobj = self.pool.get('ir.model.data')
result = []
try:
dummy,group_id = dataobj.<API key>(cr, SUPERUSER_ID, 'base', 'group_user')
result.append(group_id)
dummy,group_id = dataobj.<API key>(cr, SUPERUSER_ID, 'base', '<API key>')
result.append(group_id)
except ValueError:
# If these groups does not exists anymore
pass
return result
def _get_default_image(self, cr, uid, context=None):
return self.pool['res.partner']._get_default_image(cr, uid, False, colorize=True, context=context)
_defaults = {
'password': '',
'active': True,
'customer': False,
'company_id': _get_company,
'company_ids': _get_companies,
'groups_id': _get_group,
'image': _get_default_image,
}
# User can write on a few of his own fields (but not his groups for example)
<API key> = ['password', 'signature', 'action_id', 'company_id', 'email', 'name', 'image', 'image_medium', 'image_small', 'lang', 'tz']
# User can read a few of his own fields
<API key> = ['signature', 'company_id', 'login', 'email', 'name', 'image', 'image_medium', 'image_small', 'lang', 'tz', 'tz_offset', 'groups_id', 'partner_id', '__last_update']
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
def override_password(o):
if 'password' in o and ('id' not in o or o['id'] != uid):
o['password'] = '********'
return o
if fields and (ids == [uid] or ids == uid):
for key in fields:
if not (key in self.<API key> or key.startswith('context_')):
break
else:
# safe fields only, so we read as super-user to bypass access rights
uid = SUPERUSER_ID
result = super(res_users, self).read(cr, uid, ids, fields=fields, context=context, load=load)
canwrite = self.pool['ir.model.access'].check(cr, uid, 'res.users', 'write', False)
if not canwrite:
if isinstance(ids, (int, long)):
result = override_password(result)
else:
result = map(override_password, result)
return result
def create(self, cr, uid, vals, context=None):
user_id = super(res_users, self).create(cr, uid, vals, context=context)
user = self.browse(cr, uid, user_id, context=context)
if user.partner_id.company_id:
user.partner_id.write({'company_id': user.company_id.id})
return user_id
def write(self, cr, uid, ids, values, context=None):
if not hasattr(ids, '__iter__'):
ids = [ids]
if ids == [uid]:
for key in values.keys():
if not (key in self.<API key> or key.startswith('context_')):
break
else:
if 'company_id' in values:
user = self.browse(cr, SUPERUSER_ID, uid, context=context)
if not (values['company_id'] in user.company_ids.ids):
del values['company_id']
uid = 1 # safe fields only, so we write as super-user to bypass access rights
res = super(res_users, self).write(cr, uid, ids, values, context=context)
if 'company_id' in values:
for user in self.browse(cr, uid, ids, context=context):
# if partner is global we keep it that way
if user.partner_id.company_id and user.partner_id.company_id.id != values['company_id']:
user.partner_id.write({'company_id': user.company_id.id})
# clear caches linked to the users
self.pool['ir.model.access'].<API key>(cr)
clear = partial(self.pool['ir.rule'].clear_cache, cr)
map(clear, ids)
db = cr.dbname
if db in self._uid_cache:
for id in ids:
if id in self._uid_cache[db]:
del self._uid_cache[db][id]
self.context_get.clear_cache(self)
self.has_group.clear_cache(self)
return res
def unlink(self, cr, uid, ids, context=None):
if 1 in ids:
raise osv.except_osv(_('Can not remove root user!'), _('You can not remove the admin user as it is used internally for resources created by Odoo (updates, module installation, ...)'))
db = cr.dbname
if db in self._uid_cache:
for id in ids:
if id in self._uid_cache[db]:
del self._uid_cache[db][id]
return super(res_users, self).unlink(cr, uid, ids, context=context)
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args=[]
if not context:
context={}
ids = []
if name and operator in ['=', 'ilike']:
ids = self.search(cr, user, [('login','=',name)]+ args, limit=limit, context=context)
if not ids:
ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context)
return self.name_get(cr, user, ids, context=context)
def copy(self, cr, uid, id, default=None, context=None):
user2copy = self.read(cr, uid, [id], ['login','name'])[0]
default = dict(default or {})
if ('name' not in default) and ('partner_id' not in default):
default['name'] = _("%s (copy)") % user2copy['name']
if 'login' not in default:
default['login'] = _("%s (copy)") % user2copy['login']
return super(res_users, self).copy(cr, uid, id, default, context)
@tools.ormcache(skiparg=2)
def context_get(self, cr, uid, context=None):
user = self.browse(cr, SUPERUSER_ID, uid, context)
result = {}
for k in self._fields:
if k.startswith('context_'):
context_key = k[8:]
elif k in ['lang', 'tz']:
context_key = k
else:
context_key = False
if context_key:
res = getattr(user, k) or False
if isinstance(res, models.BaseModel):
res = res.id
result[context_key] = res or False
return result
def action_get(self, cr, uid, context=None):
dataobj = self.pool['ir.model.data']
data_id = dataobj._get_id(cr, SUPERUSER_ID, 'base', 'action_res_users_my')
return dataobj.browse(cr, uid, data_id, context=context).res_id
def check_super(self, passwd):
if passwd == tools.config['admin_passwd']:
return True
else:
raise openerp.exceptions.AccessDenied()
def check_credentials(self, cr, uid, password):
""" Override this method to plug additional authentication methods"""
res = self.search(cr, SUPERUSER_ID, [('id','=',uid),('password','=',password)])
if not res:
raise openerp.exceptions.AccessDenied()
def _login(self, db, login, password):
if not password:
return False
user_id = False
cr = self.pool.cursor()
try:
# autocommit: our single update request will be performed atomically.
# (In this way, there is no opportunity to have two transactions
# interleaving their cr.execute()..cr.commit() calls and have one
# of them rolled back due to a concurrent access.)
cr.autocommit(True)
# check if user exists
res = self.search(cr, SUPERUSER_ID, [('login','=',login)])
if res:
user_id = res[0]
# check credentials
self.check_credentials(cr, user_id, password)
# We effectively unconditionally write the res_users line.
# Even w/ autocommit there's a chance the user row will be locked,
# in which case we can't delay the login just for the purpose of
# update the last login date - hence we use FOR UPDATE NOWAIT to
# try to get the lock - fail-fast
# Failing to acquire the lock on the res_users row probably means
# another request is holding it. No big deal, we don't want to
# prevent/delay login in that case. It will also have been logged
# as a SQL error, if anyone cares.
try:
update_clause = 'NO KEY UPDATE' if cr._cnx.server_version >= 90300 else 'UPDATE'
cr.execute("SELECT id FROM res_users WHERE id=%%s FOR %s NOWAIT" % update_clause, (user_id,), log_exceptions=False)
cr.execute("UPDATE res_users SET login_date = now() AT TIME ZONE 'UTC' WHERE id=%s", (user_id,))
self.invalidate_cache(cr, user_id, ['login_date'], [user_id])
except Exception:
_logger.debug("Failed to update last_login for db:%s login:%s", db, login, exc_info=True)
except openerp.exceptions.AccessDenied:
_logger.info("Login failed for db:%s login:%s", db, login)
user_id = False
finally:
cr.close()
return user_id
def authenticate(self, db, login, password, user_agent_env):
"""Verifies and returns the user ID corresponding to the given
``login`` and ``password`` combination, or False if there was
no matching user.
:param str db: the database on which user is trying to authenticate
:param str login: username
:param str password: user password
:param dict user_agent_env: environment dictionary describing any
relevant environment attributes
"""
uid = self._login(db, login, password)
if uid == openerp.SUPERUSER_ID:
# Successfully logged in as admin!
# Attempt to guess the web base url...
if user_agent_env and user_agent_env.get('base_location'):
cr = self.pool.cursor()
try:
base = user_agent_env['base_location']
ICP = self.pool['ir.config_parameter']
if not ICP.get_param(cr, uid, 'web.base.url.freeze'):
ICP.set_param(cr, uid, 'web.base.url', base)
cr.commit()
except Exception:
_logger.exception("Failed to update web.base.url configuration parameter")
finally:
cr.close()
return uid
def check(self, db, uid, passwd):
"""Verifies that the given (uid, password) is authorized for the database ``db`` and
raise an exception if it is not."""
if not passwd:
# empty passwords disallowed for obvious security reasons
raise openerp.exceptions.AccessDenied()
if self._uid_cache.get(db, {}).get(uid) == passwd:
return
cr = self.pool.cursor()
try:
self.check_credentials(cr, uid, passwd)
if self._uid_cache.has_key(db):
self._uid_cache[db][uid] = passwd
else:
self._uid_cache[db] = {uid:passwd}
finally:
cr.close()
def change_password(self, cr, uid, old_passwd, new_passwd, context=None):
"""Change current user password. Old password must be provided explicitly
to prevent hijacking an existing user session, or for cases where the cleartext
password is not used to authenticate requests.
:return: True
:raise: openerp.exceptions.AccessDenied when old password is wrong
:raise: except_osv when new password is not set or empty
"""
self.check(cr.dbname, uid, old_passwd)
if new_passwd:
return self.write(cr, uid, uid, {'password': new_passwd})
raise osv.except_osv(_('Warning!'), _("Setting empty passwords is not allowed for security reasons!"))
def preference_save(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.client',
'tag': 'reload_context',
}
def <API key>(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.client',
'tag': 'change_password',
'target': 'new',
}
@tools.ormcache(skiparg=2)
def has_group(self, cr, uid, group_ext_id):
"""Checks whether user belongs to given group.
:param str group_ext_id: external ID (XML ID) of the group.
Must be provided in fully-qualified form (``module.ext_id``), as there
is no implicit module to use..
:return: True if the current user is a member of the group with the
given external ID (XML ID), else False.
"""
assert group_ext_id and '.' in group_ext_id, "External ID must be fully qualified"
module, ext_id = group_ext_id.split('.')
cr.execute("""SELECT 1 FROM <API key> WHERE uid=%s AND gid IN
(SELECT res_id FROM ir_model_data WHERE module=%s AND name=%s)""",
(uid, module, ext_id))
return bool(cr.fetchone())
# Implied groups
# Extension of res.groups and res.users with a relation for "implied"
# or "inherited" groups. Once a user belongs to a group, it
# automatically belongs to the implied groups (transitively).
class cset(object):
""" A cset (constrained set) is a set of elements that may be constrained to
be a subset of other csets. Elements added to a cset are automatically
added to its supersets. Cycles in the subset constraints are supported.
"""
def __init__(self, xs):
self.supersets = set()
self.elements = set(xs)
def subsetof(self, other):
if other is not self:
self.supersets.add(other)
other.update(self.elements)
def update(self, xs):
xs = set(xs) - self.elements
if xs: # xs will eventually be empty in case of a cycle
self.elements.update(xs)
for s in self.supersets:
s.update(xs)
def __iter__(self):
return iter(self.elements)
concat = itertools.chain.from_iterable
class groups_implied(osv.osv):
_inherit = 'res.groups'
def _get_trans_implied(self, cr, uid, ids, field, arg, context=None):
"computes the transitive closure of relation implied_ids"
memo = {} # use a memo for performance and cycle avoidance
def computed_set(g):
if g not in memo:
memo[g] = cset(g.implied_ids)
for h in g.implied_ids:
computed_set(h).subsetof(memo[g])
return memo[g]
res = {}
for g in self.browse(cr, SUPERUSER_ID, ids, context):
res[g.id] = map(int, computed_set(g))
return res
_columns = {
'implied_ids': fields.many2many('res.groups', '<API key>', 'gid', 'hid',
string='Inherits', help='Users of this group automatically inherit those groups'),
'trans_implied_ids': fields.function(_get_trans_implied,
type='many2many', relation='res.groups', string='Transitively inherits'),
}
def create(self, cr, uid, values, context=None):
users = values.pop('users', None)
gid = super(groups_implied, self).create(cr, uid, values, context)
if users:
# delegate addition of users to add implied groups
self.write(cr, uid, [gid], {'users': users}, context)
return gid
def write(self, cr, uid, ids, values, context=None):
res = super(groups_implied, self).write(cr, uid, ids, values, context)
if values.get('users') or values.get('implied_ids'):
# add all implied groups (to all users of each group)
for g in self.browse(cr, uid, ids, context=context):
gids = map(int, g.trans_implied_ids)
vals = {'users': [(4, u.id) for u in g.users]}
super(groups_implied, self).write(cr, uid, gids, vals, context)
return res
class users_implied(osv.osv):
_inherit = 'res.users'
def create(self, cr, uid, values, context=None):
groups = values.pop('groups_id', None)
user_id = super(users_implied, self).create(cr, uid, values, context)
if groups:
# delegate addition of groups to add implied groups
self.write(cr, uid, [user_id], {'groups_id': groups}, context)
self.pool['ir.ui.view'].clear_cache()
return user_id
def write(self, cr, uid, ids, values, context=None):
if not isinstance(ids,list):
ids = [ids]
res = super(users_implied, self).write(cr, uid, ids, values, context)
if values.get('groups_id'):
# add implied groups for all users
for user in self.browse(cr, uid, ids):
gs = set(concat(g.trans_implied_ids for g in user.groups_id))
vals = {'groups_id': [(4, g.id) for g in gs]}
super(users_implied, self).write(cr, uid, [user.id], vals, context)
self.pool['ir.ui.view'].clear_cache()
return res
# Vitrual checkbox and selection for res.user form view
# Extension of res.groups and res.users for the special groups view in the users
# form. This extension presents groups with selection and boolean widgets:
# - Groups are shown by application, with boolean and/or selection fields.
# Selection fields typically defines a role "Name" for the given application.
# - Uncategorized groups are presented as boolean fields and grouped in a
# section "Others".
# the inherited view replaces the field 'groups_id' by a set of reified group
# fields (boolean or selection fields). The arch of that view is regenerated
# each time groups are changed.
# Naming conventions for reified groups fields:
# - boolean field 'in_group_ID' is True iff
# ID is in 'groups_id'
# - selection field 'sel_groups_ID1_..._IDk' is ID iff
# ID is in 'groups_id' and ID is maximal in the set {ID1, ..., IDk}
def name_boolean_group(id):
return 'in_group_' + str(id)
def <API key>(ids):
return 'sel_groups_' + '_'.join(map(str, ids))
def is_boolean_group(name):
return name.startswith('in_group_')
def is_selection_groups(name):
return name.startswith('sel_groups_')
def is_reified_group(name):
return is_boolean_group(name) or is_selection_groups(name)
def get_boolean_group(name):
return int(name[9:])
def <API key>(name):
return map(int, name[11:].split('_'))
def partition(f, xs):
"return a pair equivalent to (filter(f, xs), filter(lambda x: not f(x), xs))"
yes, nos = [], []
for x in xs:
(yes if f(x) else nos).append(x)
return yes, nos
def parse_m2m(commands):
"return a list of ids corresponding to a many2many value"
ids = []
for command in commands:
if isinstance(command, (tuple, list)):
if command[0] in (1, 4):
ids.append(command[2])
elif command[0] == 5:
ids = []
elif command[0] == 6:
ids = list(command[2])
else:
ids.append(command)
return ids
class groups_view(osv.osv):
_inherit = 'res.groups'
def create(self, cr, uid, values, context=None):
res = super(groups_view, self).create(cr, uid, values, context)
self.<API key>(cr, uid, context)
return res
def write(self, cr, uid, ids, values, context=None):
res = super(groups_view, self).write(cr, uid, ids, values, context)
self.<API key>(cr, uid, context)
return res
def unlink(self, cr, uid, ids, context=None):
res = super(groups_view, self).unlink(cr, uid, ids, context)
self.<API key>(cr, uid, context)
return res
def <API key>(self, cr, uid, context=None):
# the view with id 'base.user_groups_view' inherits the user form view,
# and introduces the reified group fields
# we have to try-catch this, because at first init the view does not exist
# but we are already creating some basic groups
view = self.pool['ir.model.data'].xmlid_to_object(cr, SUPERUSER_ID, 'base.user_groups_view', context=context)
if view and view.exists() and view._name == 'ir.ui.view':
xml1, xml2 = [], []
xml1.append(E.separator(string=_('Application'), colspan="4"))
for app, kind, gs in self.<API key>(cr, uid, context):
# hide groups in category 'Hidden' (except to group_no_one)
attrs = {'groups': 'base.group_no_one'} if app and app.xml_id == 'base.<API key>' else {}
if kind == 'selection':
# application name with a selection field
field_name = <API key>(map(int, gs))
xml1.append(E.field(name=field_name, **attrs))
xml1.append(E.newline())
else:
# application separator with boolean fields
app_name = app and app.name or _('Other')
xml2.append(E.separator(string=app_name, colspan="4", **attrs))
for g in gs:
field_name = name_boolean_group(g.id)
xml2.append(E.field(name=field_name, **attrs))
xml = E.field(*(xml1 + xml2), name="groups_id", position="replace")
xml.addprevious(etree.Comment("GENERATED AUTOMATICALLY BY GROUPS"))
xml_content = etree.tostring(xml, pretty_print=True, xml_declaration=True, encoding="utf-8")
view.write({'arch': xml_content})
return True
def <API key>(self, cr, uid, domain=None, context=None):
return self.search(cr, uid, domain or [])
def <API key>(self, cr, uid, context=None):
""" return all groups classified by application (module category), as a list of pairs:
[(app, kind, [group, ...]), ...],
where app and group are browse records, and kind is either 'boolean' or 'selection'.
Applications are given in sequence order. If kind is 'selection', the groups are
given in reverse implication order.
"""
def linearized(gs):
gs = set(gs)
# determine sequence order: a group should appear after its implied groups
order = dict.fromkeys(gs, 0)
for g in gs:
for h in gs.intersection(g.trans_implied_ids):
order[h] -= 1
# check whether order is total, i.e., sequence orders are distinct
if len(set(order.itervalues())) == len(gs):
return sorted(gs, key=lambda g: order[g])
return None
# classify all groups by application
gids = self.<API key>(cr, uid, context=context)
by_app, others = {}, []
for g in self.browse(cr, uid, gids, context):
if g.category_id:
by_app.setdefault(g.category_id, []).append(g)
else:
others.append(g)
# build the result
res = []
apps = sorted(by_app.iterkeys(), key=lambda a: a.sequence or 0)
for app in apps:
gs = linearized(by_app[app])
if gs:
res.append((app, 'selection', gs))
else:
res.append((app, 'boolean', by_app[app]))
if others:
res.append((False, 'boolean', others))
return res
class users_view(osv.osv):
_inherit = 'res.users'
def create(self, cr, uid, values, context=None):
values = self.<API key>(values)
return super(users_view, self).create(cr, uid, values, context)
def write(self, cr, uid, ids, values, context=None):
values = self.<API key>(values)
return super(users_view, self).write(cr, uid, ids, values, context)
def <API key>(self, values):
""" return `values` without reified group fields """
add, rem = [], []
values1 = {}
for key, val in values.iteritems():
if is_boolean_group(key):
(add if val else rem).append(get_boolean_group(key))
elif is_selection_groups(key):
rem += <API key>(key)
if val:
add.append(val)
else:
values1[key] = val
if 'groups_id' not in values and (add or rem):
# remove group ids in `rem` and add group ids in `add`
values1['groups_id'] = zip(repeat(3), rem) + zip(repeat(4), add)
return values1
def default_get(self, cr, uid, fields, context=None):
group_fields, fields = partition(is_reified_group, fields)
fields1 = (fields + ['groups_id']) if group_fields else fields
values = super(users_view, self).default_get(cr, uid, fields1, context)
self._add_reified_groups(group_fields, values)
# add "default_groups_ref" inside the context to set default value for group_id with xml values
if 'groups_id' in fields and isinstance(context.get("default_groups_ref"), list):
groups = []
ir_model_data = self.pool.get('ir.model.data')
for group_xml_id in context["default_groups_ref"]:
group_split = group_xml_id.split('.')
if len(group_split) != 2:
raise osv.except_osv(_('Invalid context value'), _('Invalid context default_groups_ref value (model.name_id) : "%s"') % group_xml_id)
try:
temp, group_id = ir_model_data.<API key>(cr, uid, group_split[0], group_split[1])
except ValueError:
group_id = False
groups += [group_id]
values['groups_id'] = groups
return values
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
# determine whether reified groups fields are required, and which ones
fields1 = fields or self.fields_get(cr, uid, context=context).keys()
group_fields, other_fields = partition(is_reified_group, fields1)
# read regular fields (other_fields); add 'groups_id' if necessary
drop_groups_id = False
if group_fields and fields:
if 'groups_id' not in other_fields:
other_fields.append('groups_id')
drop_groups_id = True
else:
other_fields = fields
res = super(users_view, self).read(cr, uid, ids, other_fields, context=context, load=load)
# post-process result to add reified group fields
if group_fields:
for values in (res if isinstance(res, list) else [res]):
self._add_reified_groups(group_fields, values)
if drop_groups_id:
values.pop('groups_id', None)
return res
def _add_reified_groups(self, fields, values):
""" add the given reified group fields into `values` """
gids = set(parse_m2m(values.get('groups_id') or []))
for f in fields:
if is_boolean_group(f):
values[f] = get_boolean_group(f) in gids
elif is_selection_groups(f):
selected = [gid for gid in <API key>(f) if gid in gids]
values[f] = selected and selected[-1] or False
def fields_get(self, cr, uid, allfields=None, context=None, write_access=True):
res = super(users_view, self).fields_get(cr, uid, allfields, context, write_access)
# add reified groups fields
for app, kind, gs in self.pool['res.groups'].<API key>(cr, uid, context):
if kind == 'selection':
# selection group field
tips = ['%s: %s' % (g.name, g.comment) for g in gs if g.comment]
res[<API key>(map(int, gs))] = {
'type': 'selection',
'string': app and app.name or _('Other'),
'selection': [(False, '')] + [(g.id, g.name) for g in gs],
'help': '\n'.join(tips),
'exportable': False,
'selectable': False,
}
else:
# boolean group fields
for g in gs:
res[name_boolean_group(g.id)] = {
'type': 'boolean',
'string': g.name,
'help': g.comment,
'exportable': False,
'selectable': False,
}
return res
# change password wizard
class <API key>(osv.TransientModel):
"""
A wizard to manage the change of users' passwords
"""
_name = "change.password.wizard"
_description = "Change Password Wizard"
_columns = {
'user_ids': fields.one2many('change.password.user', 'wizard_id', string='Users'),
}
def _default_user_ids(self, cr, uid, context=None):
if context is None:
context = {}
user_model = self.pool['res.users']
user_ids = context.get('active_model') == 'res.users' and context.get('active_ids') or []
return [
(0, 0, {'user_id': user.id, 'user_login': user.login})
for user in user_model.browse(cr, uid, user_ids, context=context)
]
_defaults = {
'user_ids': _default_user_ids,
}
def <API key>(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids, context=context)[0]
need_reload = any(uid == user.user_id.id for user in wizard.user_ids)
line_ids = [user.id for user in wizard.user_ids]
self.pool.get('change.password.user').<API key>(cr, uid, line_ids, context=context)
if need_reload:
return {
'type': 'ir.actions.client',
'tag': 'reload'
}
return {'type': 'ir.actions.act_window_close'}
class <API key>(osv.TransientModel):
"""
A model to configure users in the change password wizard
"""
_name = 'change.password.user'
_description = 'Change Password Wizard User'
_columns = {
'wizard_id': fields.many2one('change.password.wizard', string='Wizard', required=True),
'user_id': fields.many2one('res.users', string='User', required=True),
'user_login': fields.char('User Login', readonly=True),
'new_passwd': fields.char('New Password'),
}
_defaults = {
'new_passwd': '',
}
def <API key>(self, cr, uid, ids, context=None):
for line in self.browse(cr, uid, ids, context=context):
line.user_id.write({'password': line.new_passwd})
# don't keep temporary passwords in the database longer than necessary
self.write(cr, uid, ids, {'new_passwd': False}, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
YUI.add('tree-openable', function (Y, NAME) {
/*jshint expr:true, onevar:false */
/**
Extension for `Tree` that adds the concept of open/closed state for nodes.
@module tree
@submodule tree-openable
@main tree-openable
**/
/**
Extension for `Tree` that adds the concept of open/closed state for nodes.
@class Tree.Openable
@constructor
@extensionfor Tree
**/
/**
Fired when a node is closed.
@event close
@param {Tree.Node} node Node being closed.
@param {String} src Source of the event.
@preventable _defCloseFn
**/
var EVT_CLOSE = 'close';
/**
Fired when a node is opened.
@event open
@param {Tree.Node} node Node being opened.
@param {String} src Source of the event.
@preventable _defOpenFn
**/
var EVT_OPEN = 'open';
function Openable() {}
Openable.prototype = {
initializer: function () {
this.nodeExtensions = this.nodeExtensions.concat(Y.Tree.Node.Openable);
},
/**
Closes the specified node if it isn't already closed.
@method closeNode
@param {Tree.Node} node Node to close.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `close` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
closeNode: function (node, options) {
if (node.canHaveChildren && node.isOpen()) {
this._fireTreeEvent(EVT_CLOSE, {
node: node,
src : options && options.src
}, {
defaultFn: this._defCloseFn,
silent : options && options.silent
});
}
return this;
},
/**
Opens the specified node if it isn't already open.
@method openNode
@param {Tree.Node} node Node to open.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `open` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
openNode: function (node, options) {
if (node.canHaveChildren && !node.isOpen()) {
this._fireTreeEvent(EVT_OPEN, {
node: node,
src : options && options.src
}, {
defaultFn: this._defOpenFn,
silent : options && options.silent
});
}
return this;
},
/**
Toggles the open/closed state of the specified node, closing it if it's
currently open or opening it if it's currently closed.
@method toggleOpenNode
@param {Tree.Node} node Node to toggle.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, events will be
suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
toggleOpenNode: function (node, options) {
return node.isOpen() ? this.closeNode(node, options) :
this.openNode(node, options);
},
/**
Default handler for the `close` event.
@method _defCloseFn
@param {EventFacade} e
@protected
**/
_defCloseFn: function (e) {
delete e.node.state.open;
},
/**
Default handler for the `open` event.
@method _defOpenFn
@param {EventFacade} e
@protected
**/
_defOpenFn: function (e) {
e.node.state.open = true;
}
};
Y.Tree.Openable = Openable;
/**
@module tree
@submodule tree-openable
**/
/**
`Tree.Node` extension that adds methods useful for nodes in trees that use the
`Tree.Openable` extension.
@class Tree.Node.Openable
@constructor
@extensionfor Tree.Node
**/
function NodeOpenable() {}
NodeOpenable.prototype = {
/**
Closes this node if it's currently open.
@method close
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `close` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
close: function (options) {
this.tree.closeNode(this, options);
return this;
},
/**
Returns `true` if this node is currently open.
Note: the root node of a tree is always considered to be open.
@method isOpen
@return {Boolean} `true` if this node is currently open, `false` otherwise.
**/
isOpen: function () {
return !!this.state.open || this.isRoot();
},
/**
Opens this node if it's currently closed.
@method open
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `open` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
open: function (options) {
this.tree.openNode(this, options);
return this;
},
/**
Toggles the open/closed state of this node, closing it if it's currently
open or opening it if it's currently closed.
@method toggleOpen
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, events will be
suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
toggleOpen: function (options) {
this.tree.toggleOpenNode(this, options);
return this;
}
};
Y.Tree.Node.Openable = NodeOpenable;
}, '3.11.0', {"requires": ["tree"]});
|
<?php
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
require_once('include/DetailView/DetailView.php');
require_once('modules/Campaigns/Charts.php');
global $mod_strings;
global $app_strings;
global $app_list_strings;
global $sugar_version, $sugar_config;
global $theme;
$GLOBALS['log']->info("Campaign detail view");
$xtpl=new XTemplate('modules/Campaigns/PopupCampaignRoi.html');
//_pp($_REQUEST['id']);
$campaign_id=$_REQUEST['id'];
$campaign = new Campaign();
$opp_query1 = "select camp.name, camp.actual_cost,camp.budget,camp.expected_revenue,count(*) opp_count,SUM(opp.amount) as Revenue, SUM(camp.actual_cost) as Investment,
ROUND((SUM(opp.amount) - SUM(camp.actual_cost))/(SUM(camp.actual_cost)), 2)*100 as ROI";
$opp_query1 .= " from opportunities opp";
$opp_query1 .= " right join campaigns camp on camp.id = opp.campaign_id";
$opp_query1 .= " where opp.sales_stage = 'Closed Won' and camp.id='$campaign_id'";
$opp_query1 .= " group by camp.name";
//$opp_query1 .= " and deleted=0";
$opp_result1=$campaign->db->query($opp_query1);
$opp_data1=$campaign->db->fetchByAssoc($opp_result1);
//get the click-throughs
$query_click = "SELECT count(*) hits ";
$query_click.= " FROM campaign_log ";
$query_click.= " WHERE campaign_id = '$campaign_id' AND activity_type='link' AND related_type='CampaignTrackers' AND archived=0 AND deleted=0";
//if $marketing id is specified, then lets filter the chart by the value
if (!empty($marketing_id)) {
$query_click.= " AND marketing_id ='$marketing_id'";
}
$query_click.= " GROUP BY activity_type, target_type";
$query_click.= " ORDER BY activity_type, target_type";
$result = $campaign->db->query($query_click);
$xtpl->assign("OPP_COUNT", $opp_data1['opp_count']);
$xtpl->assign("ACTUAL_COST", $opp_data1['actual_cost']);
$xtpl->assign("PLANNED_BUDGET", $opp_data1['budget']);
$xtpl->assign("EXPECTED_REVENUE", $opp_data1['expected_revenue']);
$currency = new Currency();
if (isset($focus->currency_id) && !empty($focus->currency_id)) {
$currency->retrieve($focus->currency_id);
if ($currency->deleted != 1) {
$xtpl->assign("CURRENCY", $currency->iso4217 .' '.$currency->symbol);
} else {
$xtpl->assign("CURRENCY", $currency->getDefaultISO4217() .' '.$currency-><API key>());
}
} else {
$xtpl->assign("CURRENCY", $currency->getDefaultISO4217() .' '.$currency-><API key>());
}
global $current_user;
if (is_admin($current_user) && $_REQUEST['module'] != 'DynamicLayout' && !empty($_SESSION['editinplace'])) {
$xtpl->assign("ADMIN_EDIT", "<a href='index.php?action=index&module=DynamicLayout&from_action=".$_REQUEST['action'] ."&from_module=".$_REQUEST['module'] ."&record=".$_REQUEST['record']. "'>".SugarThemeRegistry::current()->getImage("EditLayout", "border='0' align='bottom'", null, null, '.gif', $mod_strings['LBL_EDIT_LAYOUT'])."</a>");
}
//$detailView-><API key>($xtpl, "CAMPAIGN", $offset, $focus->is_AuditEnabled());
// adding custom fields:
//require_once('modules/DynamicFields/templates/Files/DetailView.php');
/* we need to build the dropdown of related marketing values
$latest_marketing_id = '';
$<API key> = '';
if(isset($_REQUEST['mkt_id'])) $<API key> = $_REQUEST['mkt_id'];
$options_str = '<option value="all">--None--</option>';
//query for all email marketing records related to this campaign
$<API key> = "select id, name, date_modified from email_marketing where campaign_id = '$focus->id' order by date_modified desc";
//build string with value(s) retrieved
$result =$campaign->db->query($<API key>);
if ($row = $campaign->db->fetchByAssoc($result)){
//first, populated the latest marketing id variable, as this
// variable will be used to build chart and subpanels
$latest_marketing_id = $row['id'];
//fill in first option value
$options_str .= '<option value="'. $row['id'] .'"';
// if the marketing id is same as selected marketing id, set this option to render as "selected"
if (!empty($<API key>) && $<API key> == $row['id']) {
$options_str .=' selected>'. $row['name'] .'</option>';
// if the marketing id is empty then set this first option to render as "selected"
}elseif(empty($<API key>)){
$options_str .=' selected>'. $row['name'] .'</option>';
// if the marketing is not empty, but not same as selected marketing id, then..
//.. do not set this option to render as "selected"
}else{
$options_str .='>'. $row['name'] .'</option>';
}
}
//process rest of records, if they exist
while ($row = $campaign->db->fetchByAssoc($result)){
//add to list of option values
$options_str .= '<option value="'. $row['id'] .'"';
//if the marketing id is same as selected marketing id, then set this option to render as "selected"
if (!empty($<API key>) && $<API key> == $row['id']) {
$options_str .=' selected>'. $row['name'] .'</option>';
}else{
$options_str .=' >'. $row['name'] .'</option>';
}
}
//populate the dropdown
$xtpl->assign("MKT_DROP_DOWN",$options_str);
*/
//add chart
$seps = array("-", "/");
$dates = array(date($GLOBALS['timedate']->dbDayFormat), $GLOBALS['timedate']->dbDayFormat);
$dateFileNameSafe = str_replace($seps, "_", $dates);
$cache_file_name_roi = $current_user->getUserPrivGuid()."<API key>".$dateFileNameSafe[0]."_".$dateFileNameSafe[1].".xml";
$chart= new campaign_charts();
//ob_start();
//if marketing id has been selected, then set "latest_marketing_id" to the selected value
//latest marketing id will be passed in to filter the charts and subpanels
if (!empty($<API key>)) {
$latest_marketing_id = $<API key>;
}
if (empty($latest_marketing_id) || $latest_marketing_id === 'all') {
$xtpl->assign("MY_CHART_ROI", $chart-><API key>($app_list_strings['roi_type_dom'], $app_list_strings['roi_type_dom'], $campaign_id, sugar_cached("xml/") . $cache_file_name_roi, true));
} else {
$xtpl->assign("MY_CHART_ROI", $chart-><API key>($app_list_strings['roi_type_dom'], $app_list_strings['roi_type_dom'], $campaign_id, sugar_cached("xml/") .$cache_file_name_roi, true));
}
//$output_html .= ob_get_contents();
//ob_end_clean();
//_ppd($xtpl);
//end chart
$xtpl->parse("main");
$xtpl->out("main");
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('organizations', '<API key>'),
('notifications', '<API key>'),
]
operations = [
migrations.AlterField(
model_name='notification',
name='location',
field=models.ForeignKey(verbose_name='facility', to='organizations.Facility'),
),
migrations.RenameField(
model_name='notification',
old_name='location',
new_name='facility',
),
migrations.AlterField(
model_name='notification',
name='facility',
field=models.ForeignKey(to='organizations.Facility'),
),
]
|
/* Hide default login label, so it doesn't visibly switch from one to the other with the JS */
#login_form label[for=<API key>]>span { display: none; }
|
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,400italic,700);
h1, h2, h3, h4, h5, h6 {
font-family:'Open Sans', Helvetica, Arial, sans-serif;
}
a {
color: #c7231d;
}
a:hover {
color: #bc130e;
}
.navbar .logo-icon img {
margin-top: 6px;
margin-right: 8px;
height: 34px;
}
.navbar .brand {
font-family:'Open Sans', Helvetica, Arial, sans-serif;
font-style:italic;
font-size:18px;
font-weight:400;
letter-spacing:-1px;
line-height: 32px;
}
.navbar .nav > li > a {
padding: 15px 10px;
}
.navbar .divider-vertical {
height: 50px;
}
.navbar-inner {
height:50px;
background: #303030; /* Old browsers */
background: -moz-linear-gradient(top, #303030 0%, #2d2d2d 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#303030), color-stop(100%,#2d2d2d)); /* Chrome,Safari4+ */
background: -<API key>(top, #303030 0%,#2d2d2d 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #303030 0%,#2d2d2d 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #303030 0%,#2d2d2d 100%); /* IE10+ */
background: linear-gradient(top, #303030 0%,#2d2d2d 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#303030', endColorstr='#2d2d2d',GradientType=0 ); /* IE6-9 */
-webkit-box-shadow:none;
-moz-box-shadow: none;
box-shadow: none;
}
body {
padding-top: 60px;
}
section {
padding-top:20px;
}
.home-page.page-header {
margin-top:-10px;
background: #2d2d2d; /* Old browsers */
background: -moz-linear-gradient(top, #2d2d2d 0%, #040404 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#2d2d2d), color-stop(100%,#040404)); /* Chrome,Safari4+ */
background: -<API key>(top, #2d2d2d 0%,#040404 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #2d2d2d 0%,#040404 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #2d2d2d 0%,#040404 100%); /* IE10+ */
background: linear-gradient(top, #2d2d2d 0%,#040404 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#2d2d2d', endColorstr='#040404',GradientType=0 ); /* IE6-9 */
color:#FFF;
padding:0px;
margin-bottom:0px;
border:none;
font-family:'Open Sans', Helvetica, Arial, sans-serif;
padding: 60px;
padding-bottom: 200px;
/* hide crocodile top to footer on front page */
margin-bottom: -30px;
}
.home-page.page-header a {
color:#FFF;
}
.home-page.page-header a.dotted {
border-color:#FFF;
}
.home-page.page-header .container {
background-image: url(images/header-screen.png);
background-repeat: no-repeat;
background-position: -3px 0px;
}
.home-page.page-header .inner {
padding:0px 0px 30px 40px;
font-size:16px;
line-height: 23px;
width: 400px;
}
.home-page.page-header:after {
margin-top:-14px;
}
section.grey {
background-color:#f5f5f5;
}
section.grey:after {
background-position: center -50px;
}
.footer {
background-color:#040404;
color:#CCC;
margin-top: 30px;
}
.footer:before {
content: " ";
height:14px;
display:block;
background-image: url(images/zigzags.png);
background-repeat: repeat-x;
background-position: center -100px;
margin-top:-34px;
}
.footer:after {
display:none;
}
.footer .row {
margin-top:15px;
margin-bottom:15px;
}
.footer a {
color:#CCC;
}
.footer a.btn {
color:#333333;
}
.tutorials .well {
height: 60px;
}
.tutorials:last-child {
margin-bottom: 200px;
}
/** Code / Pre **/
.container pre {
padding: 10px 15px;
border: 1px solid #ccc;
background: white;
color: #444;
box-shadow: 0 0 15px #ddd;
-moz-box-shadow: 0 0 15px #ddd;
-webkit-box-shadow: 0 0 15px #ddd;
-<API key>: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.doc-ex-rendered {
margin-bottom: 20px;
}
|
CKEDITOR.plugins.setLang( 'blockquote', 'af', {
toolbar: 'Sitaatblok'
} );
|
-- Tigase Jabber/XMPP Server
-- This program is free software: you can redistribute it and/or modify
-- This program is distributed in the hope that it will be useful,
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- along with this program. Look for COPYING file in the top folder.
-- If not, see http:
-- $Rev: $
-- Database stored procedures and fucntions for Tigase schema version 4.0.0
-- QUERY START:
CREATE OR REPLACE FUNCTION public.<API key> ()
RETURNS TEXT
AS $$
CREATE LANGUAGE plpgsql;
SELECT 'language plpgsql created'::TEXT;
$$
LANGUAGE 'sql';
SELECT CASE WHEN
(SELECT true::BOOLEAN
FROM pg_language
WHERE lanname='plpgsql')
THEN
(SELECT 'language already installed'::TEXT)
ELSE
(SELECT public.<API key>())
END;
DROP FUNCTION public.<API key> ();
-- QUERY END:
-- QUERY START:
-- Database properties get - function
create or replace function TigGetDBProperty(varchar(255)) returns text as '
declare
_result text;
_tkey alias for $1;
begin
select pval into _result from tig_pairs, tig_users
where (pkey = _tkey) AND (lower(user_id) = lower(''db-properties''))
AND (tig_pairs.uid = tig_users.uid);
return _result;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Database properties set - procedure
create or replace function TigPutDBProperty(varchar(255), text) returns void as '
declare
_tkey alias for $1;
_tval alias for $2;
begin
if exists( select pval from tig_pairs, tig_users where
(lower(user_id) = lower(''db-properties'')) AND (tig_users.uid = tig_pairs.uid)
AND (pkey = _tkey))
then
update tig_pairs set pval = _tval from tig_users
where (lower(tig_users.user_id) = lower(''db-properties''))
AND (tig_users.uid = tig_pairs.uid)
AND (pkey = _tkey);
else
insert into tig_pairs (pkey, pval, uid)
select _tkey, _tval, uid from tig_users
where (lower(user_id) = lower(''db-properties''));
end if;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- The initialization of the database.
-- The procedure should be called manually somehow before starting the
-- server. In theory the server could call the procedure automatically
-- at the startup time but I don't know yet how to solve the problem
-- with multiple cluster nodes starting at later time when the server
-- is already running.
create or replace function TigInitdb() returns void as '
begin
update tig_users set online_status = 0;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Add a new user to the database assuming the user password is already
-- encoded properly according to the database settings.
-- If password is not encoded TigAddUserPlainPw should be used instead.
create or replace function TigAddUser(varchar(2049), varchar(255))
returns bigint as '
declare
_user_id alias for $1;
_user_pw alias for $2;
_res_uid bigint;
begin
if exists( select uid from tig_users where
(lower(user_id) = lower(_user_id)) AND (user_pw = _user_pw) )
then
return null;
else
insert into tig_users (user_id, user_pw)
values (_user_id, _user_pw);
select currval(''tig_users_uid_seq'') into _res_uid;
insert into tig_nodes (parent_nid, uid, node)
values (NULL, _res_uid, ''root'');
return _res_uid as uid;
end if;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Takes plain text user password and converts it to internal representation
-- and creates a new user account.
create or replace function TigAddUserPlainPw(varchar(2049), varchar(255))
returns bigint as '
declare
_user_id alias for $1;
_user_pw alias for $2;
_enc text;
_res_uid bigint;
begin
select TigGetDBProperty(''password-encoding'') into _enc;
select
case _enc
when ''MD5-PASSWORD'' then TigAddUser(_user_id, MD5(_user_pw))
when ''MD5-USERID-PASSWORD'' then TigAddUser(_user_id, MD5(_user_id || _user_pw))
when ''<API key>'' then
TigAddUser(_user_id, MD5(split_part(_user_id, ''@'', 1) || _user_pw))
else TigAddUser(_user_id, _user_pw)
end into _res_uid;
return _res_uid as uid;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Low level database user id as big number. Used only for performance reasons
-- and save database space. Besides JID is too large to server as UID
create or replace function TigGetUserDBUid(varchar(2049)) returns bigint as '
declare
_user_id alias for $1;
res_uid bigint;
begin
select uid into res_uid from tig_users where lower(user_id) = lower(_user_id);
return res_uid;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Removes a user from the database
create or replace function TigRemoveUser(varchar(2049)) returns void as '
declare
_user_id alias for $1;
res_uid bigint;
begin
select uid into res_uid from tig_users where lower(user_id) = lower(_user_id);
delete from tig_pairs where uid = res_uid;
delete from tig_nodes where uid = res_uid;
delete from tig_users where uid = res_uid;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Returns user's password from the database
create or replace function TigGetPassword(varchar(2049)) returns varchar(255) as '
declare
_user_id alias for $1;
res_pw varchar(255);
begin
select user_pw into res_pw from tig_users where lower(user_id) = lower(_user_id);
return res_pw;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Takes plain text user password and converts it to internal representation
create or replace function <API key>(varchar(2049), varchar(255))
returns void as '
declare
_user_id alias for $1;
_user_pw alias for $2;
_enc text;
begin
select TigGetDBProperty(''password-encoding'') into _enc;
perform
case _enc
when ''MD5-PASSWORD'' then TigUpdatePassword(_user_id, MD5(_user_pw))
when ''MD5-USERID-PASSWORD'' then
TigUpdatePassword(_user_id, MD5(_user_id || _user_pw))
when ''<API key>'' then
TigUpdatePassword(_user_id, MD5(split_part(_user_id, ''@'', 1) || _user_pw))
else TigUpdatePassword(_user_id, _user_pw)
end;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Variant of <API key> SP with parameters in reverse order.
-- Some implementations require the parameters to be in the same order as
-- the update query.
create or replace function <API key>(varchar(255), varchar(2049))
returns void as '
declare
_user_pw alias for $1;
_user_id alias for $2;
begin
perform <API key>(_user_id, _user_pw);
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Update user password
create or replace function TigUpdatePassword(varchar(2049), varchar(255))
returns void as '
declare
_user_id alias for $1;
_user_pw alias for $2;
begin
update tig_users set user_pw = _user_pw where lower(user_id) = lower(_user_id);
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- List all online users
create or replace function TigOnlineUsers() returns void as '
begin
return;
select user_id, last_login, last_logout, online_status, failed_logins, account_status
from tig_users where online_status > 0;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- List all offline users
create or replace function TigOfflineUsers() returns void as '
begin
return;
select user_id, last_login, last_logout, online_status, failed_logins, account_status
from tig_users where online_status = 0;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- List of all users in database
create or replace function TigAllUsers() returns setof varchar(2049) as
'select user_id from tig_users;'
LANGUAGE 'sql';
-- create or replace function TigAllUsers() returns void as '
-- begin
-- return;
-- select user_id, last_login, last_logout, online_status, failed_logins, account_status
-- from tig_users;
-- end;
-- ' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- All users count
create or replace function TigAllUsersCount() returns bigint as '
declare
res_cnt bigint;
begin
select count(*) into res_cnt from tig_users;
return res_cnt;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Performs user login for a plain text password, converting it to an internal
-- representation if necessary
create or replace function TigUserLoginPlainPw(varchar(2049), varchar(255))
returns varchar(2049) as '
declare
_user_id alias for $1;
_user_pw alias for $2;
res_user_id varchar(2049);
_enc text;
begin
select TigGetDBProperty(''password-encoding'') into _enc;
select
case _enc
when ''MD5-PASSWORD'' then TigUserLogin(_user_id, MD5(_user_pw))
when ''MD5-USERID-PASSWORD'' then
TigUserLogin(_user_id, MD5(_user_id || _user_pw))
when ''<API key>'' then
TigUserLogin(_user_id, MD5(split_part(_user_id, ''@'', 1) || _user_pw))
else TigUserLogin(_user_id, _user_pw)
end into res_user_id;
return res_user_id;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Perforrm user login. It returns user_id uppon success and NULL
-- on failure.
-- If the login is successful it also increases online_status and sets
-- last_login time to the current timestamp
create or replace function TigUserLogin(varchar(2049), varchar(255))
returns varchar(2049) as '
declare
_user_id alias for $1;
_user_pw alias for $2;
res_user_id varchar(2049);
begin
if exists(select user_id from tig_users
where (account_status > 0) AND (lower(user_id) = lower(_user_id)) AND (user_pw = _user_pw))
then
update tig_users
set online_status = online_status + 1, last_login = now()
where user_id = _user_id;
select _user_id into res_user_id;
else
update tig_users set failed_logins = failed_logins + 1 where user_id = _user_id;
select NULL into res_user_id;
end if;
return res_user_id;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- It decreases online_status and sets last_logout time to the current timestamp
create or replace function TigUserLogout(varchar(2049)) returns void as '
declare
_user_id alias for $1;
begin
update tig_users
set online_status = greatest(online_status - 1, 0),
last_logout = now()
where user_id = _user_id;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Disable user account
create or replace function TigDisableAccount(varchar(2049)) returns void as '
declare
_user_id alias for $1;
begin
update tig_users set account_status = 0 where lower(user_id) = lower(_user_id);
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Enable user account
create or replace function TigEnableAccount(varchar(2049)) returns void as '
declare
_user_id alias for $1;
begin
update tig_users set account_status = 1 where lower(user_id) = lower(_user_id);
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Get list of all active user accounts
create or replace function TigActiveAccounts() returns void as '
begin
return;
select user_id, last_login, last_logout, online_status, failed_logins, account_status
from tig_users where account_status > 0;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Get list of all disabled user accounts
create or replace function TigDisabledAccounts() returns void as '
begin
return;
select user_id, last_login, last_logout, online_status, failed_logins, account_status
from tig_users where account_status = 0;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
-- Helper procedure for adding a new node
create or replace function TigAddNode(bigint, bigint, varchar(255))
returns bigint as '
declare
_parent_nid alias for $1;
_uid alias for $2;
_node alias for $3;
res_nid bigint;
begin
insert into tig_nodes (parent_nid, uid, node)
values (_parent_nid, _uid, _node);
select currval(''tig_nodes_nid_seq'') into res_nid;
return res_nid;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
create or replace function <API key>() returns void as '
declare
user_row RECORD;
begin
for user_row in
select user_id, pval as password
from tig_users, tig_pairs
where tig_users.uid = tig_pairs.uid and pkey = ''password'' loop
perform <API key>(user_row.user_id, user_row.password);
END LOOP;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
-- QUERY START:
create or replace function TigUpdatePairs(bigint, bigint, varchar(255), text) returns void as '
declare
_nid alias for $1;
_uid alias for $2;
_tkey alias for $3;
_tval alias for $4;
begin
if exists(select 1 from tig_pairs where nid = _nid and uid = _uid and pkey = _tkey)
then
update tig_pairs set pval = _tval where nid = _nid and uid = _uid and pkey = _tkey;
else
insert into tig_pairs (nid, uid, pkey, pval) values (_nid, _uid, _tkey, _tval);
end if;
return;
end;
' LANGUAGE 'plpgsql';
-- QUERY END:
|
package org.cbioportal.service.impl;
import java.math.BigDecimal;
import java.util.*;
import org.cbioportal.model.*;
import org.cbioportal.model.meta.GenericAssayMeta;
import org.cbioportal.persistence.<API key>;
import org.cbioportal.service.GeneService;
import org.cbioportal.service.GenericAssayService;
import org.cbioportal.service.<API key>;
import org.cbioportal.service.SampleService;
import org.cbioportal.service.exception.<API key>;
import org.cbioportal.service.util.<API key>;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class <API key> extends BaseServiceImplTest {
@InjectMocks
private <API key> <API key>;
@Mock
private SampleService sampleService;
@Mock
private <API key> <API key>;
@Mock
private <API key> <API key>;
@Mock
private GeneService geneService;
@Spy
@InjectMocks
private <API key> <API key>;
@Mock
private GenericAssayService genericAssayService;
CancerStudy cancerStudy = new CancerStudy();
MolecularProfile <API key> = new MolecularProfile();
<API key> <API key> = new <API key>();
List<Sample> samples = new ArrayList<>();
Map<String, List<<API key>>> <API key> = new HashMap<>();
Map<String, List<<API key>>> <API key> = new HashMap<>();
// patient level only data
public static final String SAMPLE_ID5 = "sample_id5";
@Before
public void setup() throws <API key> {
cancerStudy.setReferenceGenome(ReferenceGenome.<API key>);
cancerStudy.<API key>(STUDY_ID);
<API key>.<API key>(STUDY_ID);
<API key>.setStableId(<API key>);
<API key>.setCancerStudy(cancerStudy);
<API key>.<API key>(<API key>);
<API key>.<API key>("1,2,3,4");
Sample sample1 = new Sample();
sample1.setStableId(SAMPLE_ID1);
sample1.setInternalId(1);
sample1.<API key>(STUDY_ID);
sample1.setPatientId(1);
samples.add(sample1);
Sample sample2 = new Sample();
sample2.setStableId(SAMPLE_ID2);
sample2.setInternalId(2);
sample2.<API key>(STUDY_ID);
sample2.setPatientId(2);
samples.add(sample2);
Sample sample3 = new Sample();
sample3.setStableId(SAMPLE_ID3);
sample3.setInternalId(3);
sample3.<API key>(STUDY_ID);
sample3.setPatientId(3);
samples.add(sample3);
Sample sample4 = new Sample();
sample4.setStableId(SAMPLE_ID4);
sample4.setInternalId(4);
sample4.<API key>(STUDY_ID);
sample4.setPatientId(4);
samples.add(sample4);
List<<API key>> <API key> = new ArrayList<>();
List<<API key>> <API key> = new ArrayList<>();
List<<API key>> <API key> = new ArrayList<>();
<API key> caseIdentifier1 = new <API key>();
caseIdentifier1.<API key>(<API key>);
caseIdentifier1.setCaseId(SAMPLE_ID1);
<API key>.add(caseIdentifier1);
<API key> caseIdentifier2 = new <API key>();
caseIdentifier2.<API key>(<API key>);
caseIdentifier2.setCaseId(SAMPLE_ID2);
<API key>.add(caseIdentifier2);
<API key> caseIdentifier3 = new <API key>();
caseIdentifier3.<API key>(<API key>);
caseIdentifier3.setCaseId(SAMPLE_ID3);
<API key>.add(caseIdentifier3);
<API key>.add(caseIdentifier3);
<API key> caseIdentifier4 = new <API key>();
caseIdentifier4.<API key>(<API key>);
caseIdentifier4.setCaseId(SAMPLE_ID4);
<API key>.add(caseIdentifier4);
<API key>.add(caseIdentifier4);
// patient level only data
<API key> caseIdentifier5 = new <API key>();
caseIdentifier5.<API key>(<API key>);
caseIdentifier5.setCaseId(SAMPLE_ID5);
<API key>.add(caseIdentifier5);
<API key>.put("altered samples", <API key>);
<API key>.put("unaltered samples", <API key>);
<API key>.put("altered samples", <API key>);
<API key>.put("unaltered samples", <API key>);
Mockito.when(<API key>.getMolecularProfile(<API key>))
.thenReturn(<API key>);
Mockito.when(<API key>.<API key>(<API key>))
.thenReturn(<API key>);
Mockito.when(sampleService.fetchSamples(Arrays.asList(STUDY_ID, STUDY_ID, STUDY_ID, STUDY_ID),
Arrays.asList(SAMPLE_ID3, SAMPLE_ID4, SAMPLE_ID1, SAMPLE_ID2), "ID")).thenReturn(samples);
}
@Test
public void <API key>() throws Exception {
<API key>.<API key>(MolecularProfile.<API key>.MRNA_EXPRESSION);
List<<API key>> molecularDataList = new ArrayList<<API key>>();
<API key> <API key> = new <API key>();
<API key>.setEntrezGeneId(ENTREZ_GENE_ID_2);
<API key>.setValues("2,3,2.1,3");
molecularDataList.add(<API key>);
<API key> <API key> = new <API key>();
<API key>.setEntrezGeneId(ENTREZ_GENE_ID_3);
<API key>.setValues("1.1,5,2.3,3");
molecularDataList.add(<API key>);
Mockito.when(<API key>.<API key>(<API key>))
.thenReturn(molecularDataList);
List<Gene> expectedGeneList = new ArrayList<>();
Gene gene1 = new Gene();
gene1.setEntrezGeneId(ENTREZ_GENE_ID_2);
gene1.setHugoGeneSymbol(HUGO_GENE_SYMBOL_2);
expectedGeneList.add(gene1);
Gene gene2 = new Gene();
gene2.setEntrezGeneId(ENTREZ_GENE_ID_3);
gene2.setHugoGeneSymbol(HUGO_GENE_SYMBOL_3);
expectedGeneList.add(gene2);
Mockito.when(geneService.fetchGenes(Arrays.asList("2", "3"), "ENTREZ_GENE_ID", "SUMMARY"))
.thenReturn(expectedGeneList);
List<GenomicEnrichment> result = <API key>.<API key>(<API key>,
<API key>, EnrichmentType.SAMPLE);
Assert.assertEquals(2, result.size());
GenomicEnrichment <API key> = result.get(0);
Assert.assertEquals(ENTREZ_GENE_ID_2, <API key>.getEntrezGeneId());
Assert.assertEquals(HUGO_GENE_SYMBOL_2, <API key>.getHugoGeneSymbol());
Assert.assertEquals(null, <API key>.getCytoband());
Assert.assertEquals(2, <API key>.getGroupsStatistics().size());
GroupStatistics unalteredGroupStats = <API key>.getGroupsStatistics().get(0);
Assert.assertEquals("unaltered samples", unalteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.55"), unalteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.6363961030678927"), unalteredGroupStats.<API key>());
GroupStatistics alteredGroupStats = <API key>.getGroupsStatistics().get(1);
Assert.assertEquals("altered samples", alteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.5"), alteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.7071067811865476"), alteredGroupStats.<API key>());
Assert.assertEquals(new BigDecimal("0.9475795430163914"), <API key>.getpValue());
<API key> = result.get(1);
Assert.assertEquals(ENTREZ_GENE_ID_3, <API key>.getEntrezGeneId());
Assert.assertEquals(HUGO_GENE_SYMBOL_3, <API key>.getHugoGeneSymbol());
Assert.assertEquals(null, <API key>.getCytoband());
Assert.assertEquals(2, <API key>.getGroupsStatistics().size());
unalteredGroupStats = <API key>.getGroupsStatistics().get(0);
Assert.assertEquals("unaltered samples", unalteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.65"), unalteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.4949747468305834"), unalteredGroupStats.<API key>());
alteredGroupStats = <API key>.getGroupsStatistics().get(1);
Assert.assertEquals("altered samples", alteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("3.05"), alteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("2.7577164466275352"), alteredGroupStats.<API key>());
Assert.assertEquals(new BigDecimal("0.8716148250471419"), <API key>.getpValue());
}
@Test
public void <API key>() throws Exception {
<API key>.<API key>(MolecularProfile.<API key>.GENERIC_ASSAY);
List<<API key>> molecularDataList = new ArrayList<<API key>>();
<API key> <API key> = new <API key>();
<API key>.<API key>(HUGO_GENE_SYMBOL_1);
<API key>.setValues("2,3,2.1,3");
molecularDataList.add(<API key>);
<API key> <API key> = new <API key>();
<API key>.<API key>(HUGO_GENE_SYMBOL_2);
<API key>.setValues("1.1,5,2.3,3");
molecularDataList.add(<API key>);
Mockito.when(<API key>.<API key>(<API key>, null,
"SUMMARY")).thenReturn(molecularDataList);
Mockito.when(genericAssayService.<API key>(
Arrays.asList(HUGO_GENE_SYMBOL_1, HUGO_GENE_SYMBOL_2),
Arrays.asList(<API key>, <API key>), "SUMMARY"))
.thenReturn(Arrays.asList(new GenericAssayMeta(HUGO_GENE_SYMBOL_1),
new GenericAssayMeta(HUGO_GENE_SYMBOL_2)));
List<<API key>> result = <API key>.<API key>(<API key>,
<API key>, EnrichmentType.SAMPLE);
Assert.assertEquals(2, result.size());
<API key> <API key> = result.get(0);
Assert.assertEquals(HUGO_GENE_SYMBOL_1, <API key>.getStableId());
Assert.assertEquals(2, <API key>.getGroupsStatistics().size());
GroupStatistics unalteredGroupStats = <API key>.getGroupsStatistics().get(0);
Assert.assertEquals("unaltered samples", unalteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.55"), unalteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.6363961030678927"), unalteredGroupStats.<API key>());
GroupStatistics alteredGroupStats = <API key>.getGroupsStatistics().get(1);
Assert.assertEquals("altered samples", alteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.5"), alteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.7071067811865476"), alteredGroupStats.<API key>());
Assert.assertEquals(new BigDecimal("0.9475795430163914"), <API key>.getpValue());
<API key> = result.get(1);
Assert.assertEquals(HUGO_GENE_SYMBOL_2, <API key>.getStableId());
Assert.assertEquals(2, <API key>.getGroupsStatistics().size());
unalteredGroupStats = <API key>.getGroupsStatistics().get(0);
Assert.assertEquals("unaltered samples", unalteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.65"), unalteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.4949747468305834"), unalteredGroupStats.<API key>());
alteredGroupStats = <API key>.getGroupsStatistics().get(1);
Assert.assertEquals("altered samples", alteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("3.05"), alteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("2.7577164466275352"), alteredGroupStats.<API key>());
Assert.assertEquals(new BigDecimal("0.8716148250471419"), <API key>.getpValue());
}
@Test
public void <API key>() throws Exception {
<API key>.<API key>(MolecularProfile.<API key>.GENERIC_ASSAY);
<API key>.setPatientLevel(true);
List<<API key>> molecularDataList = new ArrayList<<API key>>();
<API key> <API key> = new <API key>();
<API key>.<API key>(HUGO_GENE_SYMBOL_1);
<API key>.setValues("2,3,2.1,3,3,3");
molecularDataList.add(<API key>);
<API key> <API key> = new <API key>();
<API key>.<API key>(HUGO_GENE_SYMBOL_2);
<API key>.setValues("1.1,5,2.3,3,3");
molecularDataList.add(<API key>);
Mockito.when(<API key>.<API key>(<API key>, null,
"SUMMARY")).thenReturn(molecularDataList);
Mockito.when(genericAssayService.<API key>(
Arrays.asList(HUGO_GENE_SYMBOL_1, HUGO_GENE_SYMBOL_2),
Arrays.asList(<API key>, <API key>), "SUMMARY"))
.thenReturn(Arrays.asList(new GenericAssayMeta(HUGO_GENE_SYMBOL_1),
new GenericAssayMeta(HUGO_GENE_SYMBOL_2)));
// add 5th sample which is the second sample of patient 4
Sample sample5 = new Sample();
sample5.setStableId(SAMPLE_ID5);
sample5.setInternalId(5);
sample5.<API key>(STUDY_ID);
sample5.setPatientId(4);
samples.add(sample5);
Mockito.when(sampleService.fetchSamples(Arrays.asList(STUDY_ID, STUDY_ID, STUDY_ID, STUDY_ID, STUDY_ID), Arrays.asList(SAMPLE_ID3, SAMPLE_ID4, SAMPLE_ID5, SAMPLE_ID1, SAMPLE_ID2), "ID")).thenReturn(samples);
List<<API key>> result = <API key>.<API key>(<API key>, <API key>, EnrichmentType.SAMPLE);
Assert.assertEquals(2, result.size());
<API key> <API key> = result.get(0);
Assert.assertEquals(HUGO_GENE_SYMBOL_1, <API key>.getStableId());
Assert.assertEquals(2, <API key>.getGroupsStatistics().size());
GroupStatistics unalteredGroupStats = <API key>.getGroupsStatistics().get(0);
Assert.assertEquals("unaltered samples", unalteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.55"), unalteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.6363961030678927"), unalteredGroupStats.<API key>());
GroupStatistics alteredGroupStats = <API key>.getGroupsStatistics().get(1);
Assert.assertEquals("altered samples", alteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.5"), alteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.7071067811865476"), alteredGroupStats.<API key>());
Assert.assertEquals(new BigDecimal("0.9475795430163914"), <API key>.getpValue());
<API key> = result.get(1);
Assert.assertEquals(HUGO_GENE_SYMBOL_2, <API key>.getStableId());
Assert.assertEquals(2, <API key>.getGroupsStatistics().size());
unalteredGroupStats = <API key>.getGroupsStatistics().get(0);
Assert.assertEquals("unaltered samples", unalteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("2.65"), unalteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("0.4949747468305834"), unalteredGroupStats.<API key>());
alteredGroupStats = <API key>.getGroupsStatistics().get(1);
Assert.assertEquals("altered samples", alteredGroupStats.getName());
Assert.assertEquals(new BigDecimal("3.05"), alteredGroupStats.getMeanExpression());
Assert.assertEquals(new BigDecimal("2.7577164466275352"), alteredGroupStats.<API key>());
Assert.assertEquals(new BigDecimal("0.8716148250471419"), <API key>.getpValue());
}
}
|
# Numenta Platform for Intelligent Computing (NuPIC)
# following terms and conditions apply:
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from cStringIO import StringIO
import sys
import tempfile
import unittest2 as unittest
import numpy
from nupic.encoders.base import defaultDtype
from nupic.data import <API key>
from nupic.data.fieldmeta import FieldMetaType
from nupic.support.unittesthelpers.<API key> import getSeed
from nupic.encoders.<API key> import (
<API key>
)
try:
import capnp
except ImportError:
capnp = None
if capnp:
from nupic.encoders.<API key> import (
<API key>
)
# Disable warnings about accessing protected members
# pylint: disable=W0212
def computeOverlap(x, y):
"""
Given two binary arrays, compute their overlap. The overlap is the number
of bits where x[i] and y[i] are both 1
"""
return (x & y).sum()
def validateEncoder(encoder, subsampling):
"""
Given an encoder, calculate overlaps statistics and ensure everything is ok.
We don't check every possible combination for speed reasons.
"""
for i in range(encoder.minIndex, encoder.maxIndex+1, 1):
for j in range(i+1, encoder.maxIndex+1, subsampling):
if not encoder._overlapOK(i, j):
return False
return True
class <API key>(unittest.TestCase):
"""
Unit tests for <API key> class.
"""
def testEncoding(self):
"""
Test basic encoding functionality. Create encodings without crashing and
check they contain the correct number of on and off bits. Check some
encodings for expected overlap. Test that encodings for old values don't
change once we generate new buckets.
"""
# Initialize with non-default parameters and encode with a number close to
# the offset
encoder = <API key>(name="encoder", resolution=1.0,
w=23, n=500, offset=0.0)
e0 = encoder.encode(-0.1)
self.assertEqual(e0.sum(), 23, "Number of on bits is incorrect")
self.assertEqual(e0.size, 500, "Width of the vector is incorrect")
self.assertEqual(encoder.getBucketIndices(0.0)[0], encoder._maxBuckets / 2,
"Offset doesn't correspond to middle bucket")
self.assertEqual(len(encoder.bucketMap), 1, "Number of buckets is not 1")
# Encode with a number that is resolution away from offset. Now we should
# have two buckets and this encoding should be one bit away from e0
e1 = encoder.encode(1.0)
self.assertEqual(len(encoder.bucketMap), 2, "Number of buckets is not 2")
self.assertEqual(e1.sum(), 23, "Number of on bits is incorrect")
self.assertEqual(e1.size, 500, "Width of the vector is incorrect")
self.assertEqual(computeOverlap(e0, e1), 22, "Overlap is not equal to w-1")
# Encode with a number that is resolution*w away from offset. Now we should
# have many buckets and this encoding should have very little overlap with
e25 = encoder.encode(25.0)
self.assertGreater(len(encoder.bucketMap), 23,
"Number of buckets is not 2")
self.assertEqual(e25.sum(), 23, "Number of on bits is incorrect")
self.assertEqual(e25.size, 500, "Width of the vector is incorrect")
self.assertLess(computeOverlap(e0, e25), 4, "Overlap is too high")
# Test encoding consistency. The encodings for previous numbers
# shouldn't change even though we have added additional buckets
self.assertTrue(numpy.array_equal(e0, encoder.encode(-0.1)),
"Encodings are not consistent - they have changed after new buckets "
"have been created")
self.assertTrue(numpy.array_equal(e1, encoder.encode(1.0)),
"Encodings are not consistent - they have changed after new buckets "
"have been created")
def testMissingValues(self):
"""
Test that missing values and NaN return all zero's.
"""
encoder = <API key>(name="encoder", resolution=1.0)
empty = encoder.encode(<API key>)
self.assertEqual(empty.sum(), 0)
empty = encoder.encode(float("nan"))
self.assertEqual(empty.sum(), 0)
def testResolution(self):
"""
Test that numbers within the same resolution return the same encoding.
Numbers outside the resolution should return different encodings.
"""
encoder = <API key>(name="encoder", resolution=1.0)
# Since 23.0 is the first encoded number, it will be the offset.
# Since resolution is 1, 22.9 and 23.4 should have the same bucket index and
# encoding.
e23 = encoder.encode(23.0)
e23p1 = encoder.encode(23.1)
e22p9 = encoder.encode(22.9)
e24 = encoder.encode(24.0)
self.assertEqual(e23.sum(), encoder.w)
self.assertEqual((e23 == e23p1).sum(), encoder.getWidth(),
"Numbers within resolution don't have the same encoding")
self.assertEqual((e23 == e22p9).sum(), encoder.getWidth(),
"Numbers within resolution don't have the same encoding")
self.assertNotEqual((e23 == e24).sum(), encoder.getWidth(),
"Numbers outside resolution have the same encoding")
e22p9 = encoder.encode(22.5)
self.assertNotEqual((e23 == e22p9).sum(), encoder.getWidth(),
"Numbers outside resolution have the same encoding")
def <API key>(self):
"""
Test that <API key> works and that max buckets and
clipping are handled properly.
"""
encoder = <API key>(resolution=1.0, w=11, n=150)
# Set a low number of max buckets
encoder.<API key>(10, None)
encoder.encode(0.0)
encoder.encode(-7.0)
encoder.encode(7.0)
self.assertEqual(len(encoder.bucketMap), encoder._maxBuckets,
"_maxBuckets exceeded")
self.assertTrue(
numpy.array_equal(encoder.<API key>(-1),
encoder.bucketMap[0]),
"<API key> did not handle negative"
" index")
self.assertTrue(
numpy.array_equal(encoder.<API key>(1000),
encoder.bucketMap[9]),
"<API key> did not handle negative index")
e23 = encoder.encode(23.0)
e6 = encoder.encode(6)
self.assertEqual((e23 == e6).sum(), encoder.getWidth(),
"Values not clipped correctly during encoding")
ep8 = encoder.encode(-8)
ep7 = encoder.encode(-7)
self.assertEqual((ep8 == ep7).sum(), encoder.getWidth(),
"Values not clipped correctly during encoding")
self.assertEqual(encoder.getBucketIndices(-8)[0], 0,
"getBucketIndices returned negative bucket index")
self.assertEqual(encoder.getBucketIndices(23)[0], encoder._maxBuckets-1,
"getBucketIndices returned bucket index that is too"
" large")
def testParameterChecks(self):
"""
Test that some bad construction parameters get handled.
"""
# n must be >= 6*w
with self.assertRaises(ValueError):
<API key>(name="mv", resolution=1.0, n=int(5.9*21))
# n must be an int
with self.assertRaises(ValueError):
<API key>(name="mv", resolution=1.0, n=5.9*21)
# w can't be negative
with self.assertRaises(ValueError):
<API key>(name="mv", resolution=1.0, w=-1)
# resolution can't be negative
with self.assertRaises(ValueError):
<API key>(name="mv", resolution=-2)
def <API key>(self):
"""
Check that the overlaps for the encodings are within the expected range.
Here we ask the encoder to create a bunch of representations under somewhat
stressful conditions, and then verify they are correct. We rely on the fact
that the _overlapOK and <API key> methods are working correctly.
"""
seed = getSeed()
# Generate about 600 encodings. Set n relatively low to increase
# chance of false overlaps
encoder = <API key>(resolution=1.0, w=11, n=150,
seed=seed)
encoder.encode(0.0)
encoder.encode(-300.0)
encoder.encode(300.0)
self.assertTrue(validateEncoder(encoder, subsampling=3),
"Illegal overlap encountered in encoder")
def testGetMethods(self):
"""
Test that the getWidth, getDescription, and <API key>
methods work.
"""
encoder = <API key>(name="theName", resolution=1.0, n=500)
self.assertEqual(encoder.getWidth(), 500,
"getWidth doesn't return the correct result")
self.assertEqual(encoder.getDescription(), [("theName", 0)],
"getDescription doesn't return the correct result")
self.assertEqual(encoder.<API key>(),
(FieldMetaType.float, ),
"<API key> doesn't return the correct"
" result")
def testOffset(self):
"""
Test that offset is working properly
"""
encoder = <API key>(name="encoder", resolution=1.0)
encoder.encode(23.0)
self.assertEqual(encoder._offset, 23.0,
"Offset not specified and not initialized to first input")
encoder = <API key>(name="encoder", resolution=1.0,
offset=25.0)
encoder.encode(23.0)
self.assertEqual(encoder._offset, 25.0,
"Offset not initialized to specified constructor"
" parameter")
def testSeed(self):
"""
Test that initializing twice with the same seed returns identical encodings
and different when not specified
"""
encoder1 = <API key>(name="encoder1", resolution=1.0,
seed=42)
encoder2 = <API key>(name="encoder2", resolution=1.0,
seed=42)
encoder3 = <API key>(name="encoder3", resolution=1.0,
seed=-1)
encoder4 = <API key>(name="encoder4", resolution=1.0,
seed=-1)
e1 = encoder1.encode(23.0)
e2 = encoder2.encode(23.0)
e3 = encoder3.encode(23.0)
e4 = encoder4.encode(23.0)
self.assertEqual((e1 == e2).sum(), encoder1.getWidth(),
"Same seed gives rise to different encodings")
self.assertNotEqual((e1 == e3).sum(), encoder1.getWidth(),
"Different seeds gives rise to same encodings")
self.assertNotEqual((e3 == e4).sum(), encoder1.getWidth(),
"seeds of -1 give rise to same encodings")
def <API key>(self):
"""
Test that the internal method <API key> works as expected.
"""
# Create a fake set of encodings.
encoder = <API key>(name="encoder", resolution=1.0,
w=5, n=5*20)
midIdx = encoder._maxBuckets/2
encoder.bucketMap[midIdx-2] = numpy.array(range(3, 8))
encoder.bucketMap[midIdx-1] = numpy.array(range(4, 9))
encoder.bucketMap[midIdx] = numpy.array(range(5, 10))
encoder.bucketMap[midIdx+1] = numpy.array(range(6, 11))
encoder.bucketMap[midIdx+2] = numpy.array(range(7, 12))
encoder.bucketMap[midIdx+3] = numpy.array(range(8, 13))
encoder.minIndex = midIdx - 2
encoder.maxIndex = midIdx + 3
# Indices must exist
with self.assertRaises(ValueError):
encoder.<API key>(midIdx-3, midIdx-2)
with self.assertRaises(ValueError):
encoder.<API key>(midIdx-2, midIdx-3)
# Test some overlaps
self.assertEqual(encoder.<API key>(midIdx-2, midIdx-2), 5,
"<API key> didn't work")
self.assertEqual(encoder.<API key>(midIdx-1, midIdx-2), 4,
"<API key> didn't work")
self.assertEqual(encoder.<API key>(midIdx+1, midIdx-2), 2,
"<API key> didn't work")
self.assertEqual(encoder.<API key>(midIdx-2, midIdx+3), 0,
"<API key> didn't work")
def testOverlapOK(self):
"""
Test that the internal method _overlapOK works as expected.
"""
# Create a fake set of encodings.
encoder = <API key>(name="encoder", resolution=1.0,
w=5, n=5*20)
midIdx = encoder._maxBuckets/2
encoder.bucketMap[midIdx-3] = numpy.array(range(4, 9)) # Not ok with
# midIdx-1
encoder.bucketMap[midIdx-2] = numpy.array(range(3, 8))
encoder.bucketMap[midIdx-1] = numpy.array(range(4, 9))
encoder.bucketMap[midIdx] = numpy.array(range(5, 10))
encoder.bucketMap[midIdx+1] = numpy.array(range(6, 11))
encoder.bucketMap[midIdx+2] = numpy.array(range(7, 12))
encoder.bucketMap[midIdx+3] = numpy.array(range(8, 13))
encoder.minIndex = midIdx - 3
encoder.maxIndex = midIdx + 3
self.assertTrue(encoder._overlapOK(midIdx, midIdx-1),
"_overlapOK didn't work")
self.assertTrue(encoder._overlapOK(midIdx-2, midIdx+3),
"_overlapOK didn't work")
self.assertFalse(encoder._overlapOK(midIdx-3, midIdx-1),
"_overlapOK didn't work")
# We'll just use our own numbers
self.assertTrue(encoder._overlapOK(100, 50, 0),
"_overlapOK didn't work for far values")
self.assertTrue(encoder._overlapOK(100, 50, encoder._maxOverlap),
"_overlapOK didn't work for far values")
self.assertFalse(encoder._overlapOK(100, 50, encoder._maxOverlap+1),
"_overlapOK didn't work for far values")
self.assertTrue(encoder._overlapOK(50, 50, 5),
"_overlapOK didn't work for near values")
self.assertTrue(encoder._overlapOK(48, 50, 3),
"_overlapOK didn't work for near values")
self.assertTrue(encoder._overlapOK(46, 50, 1),
"_overlapOK didn't work for near values")
self.assertTrue(encoder._overlapOK(45, 50, encoder._maxOverlap),
"_overlapOK didn't work for near values")
self.assertFalse(encoder._overlapOK(48, 50, 4),
"_overlapOK didn't work for near values")
self.assertFalse(encoder._overlapOK(48, 50, 2),
"_overlapOK didn't work for near values")
self.assertFalse(encoder._overlapOK(46, 50, 2),
"_overlapOK didn't work for near values")
self.assertFalse(encoder._overlapOK(50, 50, 6),
"_overlapOK didn't work for near values")
def testCountOverlap(self):
"""
Test that the internal method _countOverlap works as expected.
"""
encoder = <API key>(name="encoder", resolution=1.0,
n=500)
r1 = numpy.array([1, 2, 3, 4, 5, 6])
r2 = numpy.array([1, 2, 3, 4, 5, 6])
self.assertEqual(encoder._countOverlap(r1, r2), 6,
"_countOverlap result is incorrect")
r1 = numpy.array([1, 2, 3, 4, 5, 6])
r2 = numpy.array([1, 2, 3, 4, 5, 7])
self.assertEqual(encoder._countOverlap(r1, r2), 5,
"_countOverlap result is incorrect")
r1 = numpy.array([1, 2, 3, 4, 5, 6])
r2 = numpy.array([6, 5, 4, 3, 2, 1])
self.assertEqual(encoder._countOverlap(r1, r2), 6,
"_countOverlap result is incorrect")
r1 = numpy.array([1, 2, 8, 4, 5, 6])
r2 = numpy.array([1, 2, 3, 4, 9, 6])
self.assertEqual(encoder._countOverlap(r1, r2), 4,
"_countOverlap result is incorrect")
r1 = numpy.array([1, 2, 3, 4, 5, 6])
r2 = numpy.array([1, 2, 3])
self.assertEqual(encoder._countOverlap(r1, r2), 3,
"_countOverlap result is incorrect")
r1 = numpy.array([7, 8, 9, 10, 11, 12])
r2 = numpy.array([1, 2, 3, 4, 5, 6])
self.assertEqual(encoder._countOverlap(r1, r2), 0,
"_countOverlap result is incorrect")
def testVerbosity(self):
"""
Test that nothing is printed out when verbosity=0
"""
_stdout = sys.stdout
sys.stdout = _stringio = StringIO()
encoder = <API key>(name="mv", resolution=1.0,
verbosity=0)
output = numpy.zeros(encoder.getWidth(), dtype=defaultDtype)
encoder.encodeIntoArray(23.0, output)
encoder.getBucketIndices(23.0)
sys.stdout = _stdout
self.assertEqual(len(_stringio.getvalue()), 0,
"zero verbosity doesn't lead to zero output")
def <API key>(self):
encoder = <API key>(name="encoder", resolution=1.0,
verbosity=0)
with self.assertRaises(TypeError):
encoder.encode("String")
@unittest.skipUnless(
capnp, "pycapnp is not installed, skipping serialization test.")
def testWriteRead(self):
original = <API key>(
name="encoder", resolution=1.0, w=23, n=500, offset=0.0)
originalValue = original.encode(1)
proto1 = <API key>.new_message()
original.write(proto1)
# Write the proto to a temp file and read it back into a new proto
with tempfile.TemporaryFile() as f:
proto1.write(f)
f.seek(0)
proto2 = <API key>.read(f)
encoder = <API key>.read(proto2)
self.assertIsInstance(encoder, <API key>)
self.assertEqual(encoder.resolution, original.resolution)
self.assertEqual(encoder.w, original.w)
self.assertEqual(encoder.n, original.n)
self.assertEqual(encoder.name, original.name)
self.assertEqual(encoder.verbosity, original.verbosity)
self.assertEqual(encoder.minIndex, original.minIndex)
self.assertEqual(encoder.maxIndex, original.maxIndex)
encodedFromOriginal = original.encode(1)
encodedFromNew = encoder.encode(1)
self.assertTrue(numpy.array_equal(encodedFromNew, originalValue))
self.assertEqual(original.decode(encodedFromNew),
encoder.decode(encodedFromOriginal))
self.assertEqual(original.random.getSeed(), encoder.random.getSeed())
for key, value in original.bucketMap.items():
self.assertTrue(numpy.array_equal(value, encoder.bucketMap[key]))
if __name__ == "__main__":
unittest.main()
|
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <mach/clock.h>
#include <mach/mach.h>
/* CSP includes */
#include "pthread_queue.h"
pthread_queue_t * <API key>(int length, size_t item_size) {
pthread_queue_t * q = malloc(sizeof(pthread_queue_t));
if (q != NULL) {
q->buffer = malloc(length*item_size);
if (q->buffer != NULL) {
q->size = length;
q->item_size = item_size;
q->items = 0;
q->in = 0;
q->out = 0;
if (pthread_mutex_init(&(q->mutex), NULL) || pthread_cond_init(&(q->cond_full), NULL) || pthread_cond_init(&(q->cond_empty), NULL)) {
free(q->buffer);
free(q);
q = NULL;
}
} else {
free(q);
q = NULL;
}
}
return q;
}
void <API key>(pthread_queue_t * q) {
if (q == NULL)
return;
free(q->buffer);
free(q);
return;
}
int <API key>(pthread_queue_t * queue, void * value, uint32_t timeout) {
int ret;
/* Calculate timeout */
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
<API key>(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
<API key>(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
uint32_t sec = timeout / 1000;
uint32_t nsec = (timeout - 1000 * sec) * 1000000;
ts.tv_sec += sec;
if (ts.tv_nsec + nsec > 1000000000)
ts.tv_sec++;
ts.tv_nsec = (ts.tv_nsec + nsec) % 1000000000;
/* Get queue lock */
pthread_mutex_lock(&(queue->mutex));
while (queue->items == queue->size) {
ret = <API key>(&(queue->cond_full), &(queue->mutex), &ts);
if (ret != 0) {
<API key>(&(queue->mutex));
return PTHREAD_QUEUE_FULL;
}
}
/* Coby object from input buffer */
memcpy(queue->buffer+(queue->in * queue->item_size), value, queue->item_size);
queue->items++;
queue->in = (queue->in + 1) % queue->size;
<API key>(&(queue->mutex));
/* Nofify blocked threads */
<API key>(&(queue->cond_empty));
return PTHREAD_QUEUE_OK;
}
int <API key>(pthread_queue_t * queue, void * buf, uint32_t timeout) {
int ret;
/* Calculate timeout */
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
<API key>(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
<API key>(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
uint32_t sec = timeout / 1000;
uint32_t nsec = (timeout - 1000 * sec) * 1000000;
ts.tv_sec += sec;
if (ts.tv_nsec + nsec > 1000000000)
ts.tv_sec++;
ts.tv_nsec = (ts.tv_nsec + nsec) % 1000000000;
/* Get queue lock */
pthread_mutex_lock(&(queue->mutex));
while (queue->items == 0) {
ret = <API key>(&(queue->cond_empty), &(queue->mutex), &ts);
if (ret != 0) {
<API key>(&(queue->mutex));
return PTHREAD_QUEUE_EMPTY;
}
}
/* Coby object to output buffer */
memcpy(buf, queue->buffer+(queue->out * queue->item_size), queue->item_size);
queue->items
queue->out = (queue->out + 1) % queue->size;
<API key>(&(queue->mutex));
/* Nofify blocked threads */
<API key>(&(queue->cond_full));
return PTHREAD_QUEUE_OK;
}
int pthread_queue_items(pthread_queue_t * queue) {
pthread_mutex_lock(&(queue->mutex));
int items = queue->items;
<API key>(&(queue->mutex));
return items;
}
|
#include "clar_libgit2.h"
#include "git2/merge.h"
#include "buffer.h"
#include "merge.h"
#include "../merge_helpers.h"
#include "posix.h"
#define TEST_REPO_PATH "merge-resolve"
#define MERGE_BRANCH_OID "<SHA1-like>"
#define <API key> \
"this file is changed in master\n" \
"this file is automergeable\n" \
"this file is automergeable\n" \
"this file is automergeable\n" \
"this file is automergeable\n" \
"this file is automergeable\n" \
"this file is automergeable\n" \
"this file is automergeable\n" \
"this file is changed in branch\n"
#define <API key> \
"changed in branch\n"
static git_repository *repo;
static git_index *repo_index;
static char *unaffected[][4] = {
{ "added-in-master.txt", NULL },
{ "changed-in-master.txt", NULL },
{ "unchanged.txt", NULL },
{ "added-in-master.txt", "changed-in-master.txt", NULL },
{ "added-in-master.txt", "unchanged.txt", NULL },
{ "changed-in-master.txt", "unchanged.txt", NULL },
{ "added-in-master.txt", "changed-in-master.txt", "unchanged.txt", NULL },
{ "new_file.txt", NULL },
{ "new_file.txt", "unchanged.txt", NULL },
{ NULL },
};
static char *affected[][5] = {
{ "automergeable.txt", NULL },
{ "changed-in-branch.txt", NULL },
{ "conflicting.txt", NULL },
{ "removed-in-branch.txt", NULL },
{ "automergeable.txt", "changed-in-branch.txt", NULL },
{ "automergeable.txt", "conflicting.txt", NULL },
{ "automergeable.txt", "removed-in-branch.txt", NULL },
{ "changed-in-branch.txt", "conflicting.txt", NULL },
{ "changed-in-branch.txt", "removed-in-branch.txt", NULL },
{ "conflicting.txt", "removed-in-branch.txt", NULL },
{ "automergeable.txt", "changed-in-branch.txt", "conflicting.txt", NULL },
{ "automergeable.txt", "changed-in-branch.txt", "removed-in-branch.txt", NULL },
{ "automergeable.txt", "conflicting.txt", "removed-in-branch.txt", NULL },
{ "changed-in-branch.txt", "conflicting.txt", "removed-in-branch.txt", NULL },
{ "automergeable.txt", "changed-in-branch.txt", "conflicting.txt", "removed-in-branch.txt", NULL },
{ NULL },
};
static char *result_contents[4][6] = {
{ "automergeable.txt", <API key>, NULL, NULL },
{ "changed-in-branch.txt", <API key>, NULL, NULL },
{ "automergeable.txt", <API key>, "changed-in-branch.txt", <API key>, NULL, NULL },
{ NULL }
};
void <API key>(void)
{
repo = cl_git_sandbox_init(TEST_REPO_PATH);
<API key>(&repo_index, repo);
}
void <API key>(void)
{
git_index_free(repo_index);
<API key>();
}
static void <API key>(git_repository *repo, bool value)
{
git_config *cfg;
cl_git_pass(<API key>(&cfg, repo));
cl_git_pass(git_config_set_bool(cfg, "core.autocrlf", value));
git_config_free(cfg);
}
static int merge_branch(void)
{
git_oid their_oids[1];
<API key> *their_head;
git_merge_options merge_opts = <API key>;
<API key> checkout_opts = <API key>;
int error;
cl_git_pass(git_oid_fromstr(&their_oids[0], MERGE_BRANCH_OID));
cl_git_pass(<API key>(&their_head, repo, &their_oids[0]));
checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
error = git_merge(repo, (const <API key> **)&their_head, 1, &merge_opts, &checkout_opts);
<API key>(their_head);
return error;
}
static void write_files(char *files[])
{
char *filename;
git_buf path = GIT_BUF_INIT, content = GIT_BUF_INIT;
size_t i;
for (i = 0, filename = files[i]; filename; filename = files[++i]) {
git_buf_clear(&path);
git_buf_clear(&content);
git_buf_printf(&path, "%s/%s", TEST_REPO_PATH, filename);
git_buf_printf(&content, "This is a dirty file in the working directory!\n\n"
"It will not be staged! Its filename is %s.\n", filename);
cl_git_mkfile(path.ptr, content.ptr);
}
git_buf_free(&path);
git_buf_free(&content);
}
static void hack_index(char *files[])
{
char *filename;
struct stat statbuf;
git_buf path = GIT_BUF_INIT;
git_index_entry *entry;
size_t i;
/* Update the index to suggest that checkout placed these files on
* disk, keeping the object id but updating the cache, which will
* emulate a Git implementation's different filter.
*/
for (i = 0, filename = files[i]; filename; filename = files[++i]) {
git_buf_clear(&path);
cl_assert(entry = (git_index_entry *)
<API key>(repo_index, filename, 0));
cl_git_pass(git_buf_printf(&path, "%s/%s", TEST_REPO_PATH, filename));
cl_git_pass(p_stat(path.ptr, &statbuf));
entry->ctime.seconds = (git_time_t)statbuf.st_ctime;
entry->ctime.nanoseconds = 0;
entry->mtime.seconds = (git_time_t)statbuf.st_mtime;
entry->mtime.nanoseconds = 0;
entry->dev = statbuf.st_dev;
entry->ino = statbuf.st_ino;
entry->uid = statbuf.st_uid;
entry->gid = statbuf.st_gid;
entry->file_size = statbuf.st_size;
}
git_buf_free(&path);
}
static void stage_random_files(char *files[])
{
char *filename;
size_t i;
write_files(files);
for (i = 0, filename = files[i]; filename; filename = files[++i])
cl_git_pass(<API key>(repo_index, filename));
}
static void stage_content(char *content[])
{
git_reference *head;
git_object *head_object;
git_buf path = GIT_BUF_INIT;
char *filename, *text;
size_t i;
cl_git_pass(git_repository_head(&head, repo));
cl_git_pass(git_reference_peel(&head_object, head, GIT_OBJ_COMMIT));
cl_git_pass(git_reset(repo, head_object, GIT_RESET_HARD, NULL));
for (i = 0, filename = content[i], text = content[++i];
filename && text;
filename = content[++i], text = content[++i]) {
git_buf_clear(&path);
cl_git_pass(git_buf_printf(&path, "%s/%s", TEST_REPO_PATH, filename));
cl_git_mkfile(path.ptr, text);
cl_git_pass(<API key>(repo_index, filename));
}
git_object_free(head_object);
git_reference_free(head);
git_buf_free(&path);
}
static int merge_dirty_files(char *dirty_files[])
{
git_reference *head;
git_object *head_object;
int error;
cl_git_pass(git_repository_head(&head, repo));
cl_git_pass(git_reference_peel(&head_object, head, GIT_OBJ_COMMIT));
cl_git_pass(git_reset(repo, head_object, GIT_RESET_HARD, NULL));
write_files(dirty_files);
error = merge_branch();
git_object_free(head_object);
git_reference_free(head);
return error;
}
static int <API key>(char *files[])
{
git_reference *head;
git_object *head_object;
int error;
cl_git_pass(git_repository_head(&head, repo));
cl_git_pass(git_reference_peel(&head_object, head, GIT_OBJ_COMMIT));
cl_git_pass(git_reset(repo, head_object, GIT_RESET_HARD, NULL));
write_files(files);
hack_index(files);
cl_git_pass(git_index_write(repo_index));
error = merge_branch();
git_object_free(head_object);
git_reference_free(head);
return error;
}
static int merge_staged_files(char *staged_files[])
{
stage_random_files(staged_files);
return merge_branch();
}
void <API key>(void)
{
char **files;
size_t i;
for (i = 0, files = unaffected[i]; files[0]; files = unaffected[++i])
cl_git_pass(merge_dirty_files(files));
}
void <API key>(void)
{
git_reference *head;
git_object *head_object;
cl_git_pass(git_repository_head(&head, repo));
cl_git_pass(git_reference_peel(&head_object, head, GIT_OBJ_COMMIT));
cl_git_pass(git_reset(repo, head_object, GIT_RESET_HARD, NULL));
cl_git_pass(p_unlink("merge-resolve/unchanged.txt"));
cl_git_pass(merge_branch());
git_object_free(head_object);
git_reference_free(head);
}
void <API key>(void)
{
char **files;
size_t i;
for (i = 0, files = affected[i]; files[0]; files = affected[++i])
cl_git_fail(merge_dirty_files(files));
}
void <API key>(void)
{
char **files;
size_t i;
for (i = 0, files = unaffected[i]; files[0]; files = unaffected[++i])
cl_git_fail(merge_staged_files(files));
for (i = 0, files = affected[i]; files[0]; files = affected[++i])
cl_git_fail(merge_staged_files(files));
}
void <API key>(void)
{
char **content;
size_t i;
<API key>(repo, false);
for (i = 0, content = result_contents[i]; content[0]; content = result_contents[++i]) {
stage_content(content);
git_index_write(repo_index);
cl_git_pass(merge_branch());
}
}
void <API key>(void)
{
char **files;
size_t i;
for (i = 0, files = affected[i]; files[0]; files = affected[++i])
cl_git_pass(<API key>(files));
}
|
// @(#)root/cont:$Id$
#ifndef ROOT_TProcessID
#define ROOT_TProcessID
// TProcessID //
// Process Identifier object //
#ifndef ROOT_TNamed
#include "TNamed.h"
#endif
#ifndef ROOT_TObjArray
#include "TObjArray.h"
#endif
#include <atomic>
#include <type_traits>
class TExMap;
namespace ROOT {
namespace Internal {
/**
* \class ROOT::Internal::TAtomicPointer
* \brief Helper class to manage atomic pointers.
* \tparam T Pointer type to be made atomic
*
* Helper class to manage atomic pointers. The class enforces that the templated type
* is a pointer.
*/
template <typename T> class TAtomicPointer {
private:
std::atomic<T> fAtomic;
public:
TAtomicPointer() : fAtomic(nullptr)
{
static_assert(std::is_pointer<T>::value, "Only pointer types supported");
}
~TAtomicPointer() { delete fAtomic.load(); }
T operator->() const { return fAtomic; }
operator T() const { return fAtomic; }
T operator=(const T& t)
{
fAtomic = t;
return t;
}
};
} // End of namespace Internal
} // End of namespace ROOT
class TProcessID : public TNamed {
private:
TProcessID(const TProcessID &ref); // TProcessID are not copiable.
TProcessID& operator=(const TProcessID &ref); // TProcessID are not copiable.
protected:
std::atomic_int fCount; //!Reference count to this object (from TFile)
ROOT::Internal::TAtomicPointer<TObjArray*> fObjects; //!Array pointing to the referenced objects
std::atomic_flag fLock; //!Spin lock for initialization of fObjects
static TProcessID *fgPID; //Pointer to current session ProcessID
static TObjArray *fgPIDs; //Table of ProcessIDs
static TExMap *fgObjPIDs; //Table pointer to pids
static UInt_t fgNumber; //Referenced objects count
public:
TProcessID();
virtual ~TProcessID();
void CheckInit();
virtual void Clear(Option_t *option="");
Int_t DecrementCount();
Int_t IncrementCount();
Int_t GetCount() const {return fCount;}
TObjArray *GetObjects() const {return fObjects;}
TObject *GetObjectWithID(UInt_t uid);
void PutObjectWithID(TObject *obj, UInt_t uid=0);
virtual void RecursiveRemove(TObject *obj);
static TProcessID *AddProcessID();
static UInt_t AssignID(TObject *obj);
static void Cleanup();
static UInt_t GetNProcessIDs();
static TProcessID *GetPID();
static TObjArray *GetPIDs();
static TProcessID *GetProcessID(UShort_t pid);
static TProcessID *GetProcessWithUID(const TObject *obj);
static TProcessID *GetProcessWithUID(UInt_t uid,const void *obj);
static TProcessID *GetSessionProcessID();
static UInt_t GetObjectCount();
static Bool_t IsValid(TProcessID *pid);
static void SetObjectCount(UInt_t number);
ClassDef(TProcessID,1) //Process Unique Identifier in time and space
};
#endif
|
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
#ifndef <API key>
#define <API key>
#include "Action.h"
class <API key>;
template <>
InputParameters validParams<<API key>>();
class <API key> : public Action
{
public:
<API key>(InputParameters params);
virtual void act() override;
};
#endif // <API key>
|
package org.jboss.hal.testsuite.test.configuration.undertow;
import org.apache.commons.lang.RandomStringUtils;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.testsuite.category.Shared;
import org.jboss.hal.testsuite.page.config.UndertowServletPage;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.online.operations.Address;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
@RunWith(Arquillian.class)
@Category(Shared.class)
public class <API key> extends <API key> {
@Page
private UndertowServletPage page;
//identifiers
private static final String <API key> = "<API key>";
private static final String <API key> = "<API key>";
private static final String DEFAULT_ENCODING = "default-encoding";
private static final String <API key> = "<API key>";
private static final String DIRECTORY_LISTING = "directory-listing";
private static final String <API key> = "<API key>";
private static final String <API key> = "<API key>";
private static final String IGNORE_FLUSH = "ignore-flush";
private static final String <API key> = "<API key>";
private static final String <API key> = "<API key>";
//values
private static final String <API key> = "all";
private static final String SERVLET_CONTAINER = "servlet-container_" + RandomStringUtils.randomAlphanumeric(5);
private static final Address <API key> = UNDERTOW_ADDRESS.and("servlet-container", SERVLET_CONTAINER);
@BeforeClass
public static void setUp() throws <API key>, IOException, TimeoutException {
operations.add(<API key>);
}
@Before
public void before() {
page.navigate();
page.<API key>(SERVLET_CONTAINER);
}
@AfterClass
public static void tearDown() throws <API key>, IOException, TimeoutException, OperationException {
operations.remove(<API key>);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, true);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, false);
}
@Test
public void <API key>() throws Exception {
editTextAndVerify(<API key>, <API key>, undertowOps.createBufferCache());
}
@Test
public void editDefaultEncoding() throws Exception {
editTextAndVerify(<API key>, DEFAULT_ENCODING);
}
@Test
public void <API key>() throws Exception {
editTextAndVerify(<API key>, <API key>, 42);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, "54sdfg");
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, DIRECTORY_LISTING, true);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, DIRECTORY_LISTING, false);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, true);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, false);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, IGNORE_FLUSH, true);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, IGNORE_FLUSH, false);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, true);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, false);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, <API key>);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, true);
}
@Test
public void <API key>() throws Exception {
<API key>(<API key>, <API key>, false);
}
}
|
#include <geos/util/<API key>.h>
#include <geos/algorithm/CGAlgorithms.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/<API key>.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/<API key>.h>
#include <geos/geom/CoordinateFilter.h>
#include <geos/geom/Dimension.h>
#include <geos/geom/GeometryFilter.h>
#include <geos/geom/<API key>.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Point.h>
#include <geos/geom/MultiPoint.h> // for getBoundary
#include <geos/geom/Envelope.h>
#include <algorithm>
#include <typeinfo>
#include <memory>
#include <cassert>
using namespace std;
using namespace geos::algorithm;
namespace geos {
namespace geom { // geos::geom
/*protected*/
LineString::LineString(const LineString &ls)
:
Geometry(ls),
points(ls.points->clone())
{
//points=ls.points->clone();
}
Geometry*
LineString::reverse() const
{
assert(points.get());
CoordinateSequence* seq = points->clone();
CoordinateSequence::reverse(seq);
assert(getFactory());
return getFactory()->createLineString(seq);
}
/*private*/
void
LineString::<API key>()
{
if (points.get()==NULL)
{
points.reset(getFactory()-><API key>()->create());
return;
}
if (points->size()==1)
{
throw util::<API key>("point array must contain 0 or >1 elements\n");
}
}
/*protected*/
LineString::LineString(CoordinateSequence *newCoords,
const GeometryFactory *factory)
:
Geometry(factory),
points(newCoords)
{
<API key>();
}
/*public*/
LineString::LineString(CoordinateSequence::AutoPtr newCoords,
const GeometryFactory *factory)
:
Geometry(factory),
points(newCoords)
{
<API key>();
}
LineString::~LineString()
{
//delete points;
}
CoordinateSequence*
LineString::getCoordinates() const
{
assert(points.get());
return points->clone();
//return points;
}
const CoordinateSequence*
LineString::getCoordinatesRO() const
{
assert(0 != points.get());
return points.get();
}
const Coordinate&
LineString::getCoordinateN(int n) const
{
assert(points.get());
return points->getAt(n);
}
Dimension::DimensionType
LineString::getDimension() const
{
return Dimension::L; // line
}
int
LineString::<API key>() const
{
return (int) points->getDimension();
}
int
LineString::<API key>() const
{
if (isClosed()) {
return Dimension::False;
}
return 0;
}
bool
LineString::isEmpty() const
{
assert(points.get());
return points->isEmpty();
}
size_t
LineString::getNumPoints() const
{
assert(points.get());
return points->getSize();
}
Point*
LineString::getPointN(size_t n) const
{
assert(getFactory());
assert(points.get());
return getFactory()->createPoint(points->getAt(n));
}
Point*
LineString::getStartPoint() const
{
if (isEmpty()) {
return NULL;
//return new Point(NULL,NULL);
}
return getPointN(0);
}
Point*
LineString::getEndPoint() const
{
if (isEmpty()) {
return NULL;
//return new Point(NULL,NULL);
}
return getPointN(getNumPoints() - 1);
}
bool
LineString::isClosed() const
{
if (isEmpty()) {
return false;
}
return getCoordinateN(0).equals2D(getCoordinateN(getNumPoints()-1));
}
bool
LineString::isRing() const
{
return isClosed() && isSimple();
}
string
LineString::getGeometryType() const
{
return "LineString";
}
Geometry*
LineString::getBoundary() const
{
if (isEmpty()) {
return getFactory()->createMultiPoint();
}
// using the default OGC_SFS MOD2 rule, the boundary of a
// closed LineString is empty
if (isClosed()) {
return getFactory()->createMultiPoint();
}
vector<Geometry*> *pts=new vector<Geometry*>();
pts->push_back(getStartPoint());
pts->push_back(getEndPoint());
MultiPoint *mp = getFactory()->createMultiPoint(pts);
return mp;
}
bool
LineString::isCoordinate(Coordinate& pt) const
{
assert(points.get());
std::size_t npts=points->getSize();
for (std::size_t i = 0; i<npts; i++) {
if (points->getAt(i)==pt) {
return true;
}
}
return false;
}
/*protected*/
Envelope::AutoPtr
LineString::<API key>() const
{
if (isEmpty()) {
// We don't return NULL here
// as it would indicate "unknown"
// envelope. In this case we
// *know* the envelope is EMPTY.
return Envelope::AutoPtr(new Envelope());
}
assert(points.get());
const Coordinate& c=points->getAt(0);
double minx = c.x;
double miny = c.y;
double maxx = c.x;
double maxy = c.y;
std::size_t npts=points->getSize();
for (std::size_t i=1; i<npts; i++) {
const Coordinate &c=points->getAt(i);
minx = minx < c.x ? minx : c.x;
maxx = maxx > c.x ? maxx : c.x;
miny = miny < c.y ? miny : c.y;
maxy = maxy > c.y ? maxy : c.y;
}
// caller expects a newly allocated Envelope.
// this function won't be called twice, unless
// cached Envelope is invalidated (set to NULL)
return Envelope::AutoPtr(new Envelope(minx, maxx, miny, maxy));
}
bool
LineString::equalsExact(const Geometry *other, double tolerance) const
{
if (!isEquivalentClass(other)) {
return false;
}
const LineString *otherLineString=dynamic_cast<const LineString*>(other);
assert(otherLineString);
size_t npts=points->getSize();
if (npts!=otherLineString->points->getSize()) {
return false;
}
for (size_t i=0; i<npts; ++i) {
if (!equal(points->getAt(i),otherLineString->points->getAt(i),tolerance)) {
return false;
}
}
return true;
}
void
LineString::apply_rw(const CoordinateFilter *filter)
{
assert(points.get());
points->apply_rw(filter);
}
void
LineString::apply_ro(CoordinateFilter *filter) const
{
assert(points.get());
points->apply_ro(filter);
}
void LineString::apply_rw(GeometryFilter *filter)
{
assert(filter);
filter->filter_rw(this);
}
void LineString::apply_ro(GeometryFilter *filter) const
{
assert(filter);
filter->filter_ro(this);
}
/*public*/
void
LineString::normalize()
{
assert(points.get());
std::size_t npts=points->getSize();
std::size_t n=npts/2;
for (std::size_t i=0; i<n; i++) {
std::size_t j = npts - 1 - i;
if (!(points->getAt(i)==points->getAt(j))) {
if (points->getAt(i).compareTo(points->getAt(j)) > 0) {
CoordinateSequence::reverse(points.get());
}
return;
}
}
}
int
LineString::compareToSameClass(const Geometry *ls) const
{
const LineString *line=dynamic_cast<const LineString*>(ls);
assert(line);
// MD - optimized implementation
std::size_t mynpts=points->getSize();
std::size_t othnpts=line->points->getSize();
if ( mynpts > othnpts ) return 1;
if ( mynpts < othnpts ) return -1;
for (std::size_t i=0; i<mynpts; i++)
{
int cmp=points->getAt(i).compareTo(line->points->getAt(i));
if (cmp) return cmp;
}
return 0;
}
const Coordinate*
LineString::getCoordinate() const
{
if (isEmpty()) return NULL;
return &(points->getAt(0));
}
double
LineString::getLength() const
{
return CGAlgorithms::length(points.get());
}
void
LineString::apply_rw(<API key> *filter)
{
assert(filter);
filter->filter_rw(this);
}
void
LineString::apply_ro(<API key> *filter) const
{
assert(filter);
filter->filter_ro(this);
}
void
LineString::apply_rw(<API key>& filter)
{
size_t npts=points->size();
if (!npts) return;
for (size_t i = 0; i<npts; ++i)
{
filter.filter_rw(*points, i);
if (filter.isDone()) break;
}
if (filter.isGeometryChanged()) geometryChanged();
}
void
LineString::apply_ro(<API key>& filter) const
{
size_t npts=points->size();
if (!npts) return;
for (size_t i = 0; i<npts; ++i)
{
filter.filter_ro(*points, i);
if (filter.isDone()) break;
}
//if (filter.isGeometryChanged()) geometryChanged();
}
GeometryTypeId
LineString::getGeometryTypeId() const
{
return GEOS_LINESTRING;
}
} // namespace geos::geom
} // namespace geos
|
# <API key>: (Apache-2.0 OR MIT)
from spack import *
class PyIlmbase(AutotoolsPackage):
"""The PyIlmBase libraries provides python bindings for the IlmBase libraries."""
homepage = "https://github.com/<API key>/openexr/tree/v2.3.0/PyIlmBase"
url = "https://github.com/<API key>/openexr/releases/download/v2.3.0/pyilmbase-2.3.0.tar.gz"
version('2.3.0', sha256='<SHA256-like>')
depends_on('ilmbase')
depends_on('boost+python')
parallel = False
def configure_args(self):
spec = self.spec
args = [
'--<API key>=boost_python{0}'.format(
spec['python'].version.up_to(2).joined)
]
return args
|
// This file is part of the deal.II library.
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// the top level of the deal.II distribution.
// check SparseMatrix::matrix_norm_square
#include "../tests.h"
#include <deal.II/base/utilities.h>
#include <deal.II/lac/trilinos_vector.h>
#include <deal.II/lac/<API key>.h>
#include <iostream>
#include <vector>
void test (TrilinosWrappers::MPI::Vector &v,
TrilinosWrappers::MPI::Vector &w,
TrilinosWrappers::MPI::Vector &x)
{
TrilinosWrappers::SparseMatrix m(v.size(),v.size(),v.size());
for (unsigned int i=0; i<m.m(); ++i)
for (unsigned int j=0; j<m.m(); ++j)
m.set (i,j, i+2*j);
for (unsigned int i=0; i<v.size(); ++i)
{
v(i) = i;
w(i) = i+1;
}
m.compress (VectorOperation::insert);
v.compress (VectorOperation::insert);
w.compress (VectorOperation::insert);
// x=w-Mv
const double s = m.residual (x, v, w);
// make sure we get the expected result
for (unsigned int i=0; i<v.size(); ++i)
{
AssertThrow (v(i) == i, ExcInternalError());
AssertThrow (w(i) == i+1, ExcInternalError());
double result = i+1;
for (unsigned int j=0; j<m.m(); ++j)
result -= (i+2*j)*j;
AssertThrow (x(i) == result, ExcInternalError());
}
AssertThrow (s == x.l2_norm(), ExcInternalError());
deallog << "OK" << std::endl;
}
int main (int argc, char **argv)
{
initlog();
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, <API key>());
try
{
{
TrilinosWrappers::MPI::Vector v;
v.reinit(complete_index_set(100), MPI_COMM_WORLD);
TrilinosWrappers::MPI::Vector w;
w.reinit(complete_index_set(100), MPI_COMM_WORLD);
TrilinosWrappers::MPI::Vector x;
x.reinit(complete_index_set(100), MPI_COMM_WORLD);
test (v,w,x);
}
}
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl << std::endl
<< "
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "
<< std::endl;
return 1;
};
}
|
FullSolveMultiApp::solveStep(Real , Real , bool auto_advance)
|
# This program is licenced under the same licence as Ruby-GNOME2.
# $Id: <API key>.rb,v 1.1 2005/10/12 05:38:30 ktou Exp $
=begin
= cairo/Self Intersect
This demo shows how to use GDK and cairo to show cross.
From http://cairographics.org/samples/xxx_self_intersect.html.
=end
require 'common'
module Demo
class CairoSelfIntersect < CairoWindow
def initialize
super('cairo self intersect')
end
def draw(cr)
cr.move_to(0.3, 0.3)
cr.line_to(0.7, 0.3)
cr.line_to(0.5, 0.3)
cr.line_to(0.5, 0.7)
cr.set_line_width(0.22)
cr.set_line_cap(Cairo::LINE_CAP_ROUND)
cr.set_line_join(Cairo::LINE_JOIN_ROUND)
cr.stroke
end
end
end
|
#include "bookmarkfiltermodel.h"
#include "bookmarkitem.h"
#include "bookmarkmodel.h"
BookmarkFilterModel::BookmarkFilterModel(QObject *parent)
: QAbstractProxyModel(parent)
, hideBookmarks(true)
, sourceModel(0)
{
}
void BookmarkFilterModel::setSourceModel(QAbstractItemModel *_sourceModel)
{
beginResetModel();
if (sourceModel) {
disconnect(sourceModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
this, SLOT(changed(QModelIndex, QModelIndex)));
disconnect(sourceModel, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SLOT(rowsInserted(QModelIndex, int, int)));
disconnect(sourceModel,
SIGNAL(<API key>(QModelIndex, int, int)), this,
SLOT(<API key>(QModelIndex, int, int)));
disconnect(sourceModel, SIGNAL(rowsRemoved(QModelIndex, int, int)),
this, SLOT(rowsRemoved(QModelIndex, int, int)));
disconnect(sourceModel, SIGNAL(<API key>()), this,
SLOT(<API key>()));
disconnect(sourceModel, SIGNAL(layoutChanged()), this,
SLOT(layoutChanged()));
disconnect(sourceModel, SIGNAL(modelAboutToBeReset()), this,
SLOT(modelAboutToBeReset()));
disconnect(sourceModel, SIGNAL(modelReset()), this, SLOT(modelReset()));
}
QAbstractProxyModel::setSourceModel(sourceModel);
sourceModel = qobject_cast<BookmarkModel*> (_sourceModel);
connect(sourceModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this,
SLOT(changed(QModelIndex, QModelIndex)));
connect(sourceModel, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SLOT(rowsInserted(QModelIndex, int, int)));
connect(sourceModel, SIGNAL(<API key>(QModelIndex, int, int)),
this, SLOT(<API key>(QModelIndex, int, int)));
connect(sourceModel, SIGNAL(rowsRemoved(QModelIndex, int, int)), this,
SLOT(rowsRemoved(QModelIndex, int, int)));
connect(sourceModel, SIGNAL(<API key>()), this,
SLOT(<API key>()));
connect(sourceModel, SIGNAL(layoutChanged()), this,
SLOT(layoutChanged()));
connect(sourceModel, SIGNAL(modelAboutToBeReset()), this,
SLOT(modelAboutToBeReset()));
connect(sourceModel, SIGNAL(modelReset()), this, SLOT(modelReset()));
if (sourceModel)
setupCache(sourceModel->index(0, 0, QModelIndex()).parent());
endResetModel();
}
int BookmarkFilterModel::rowCount(const QModelIndex &index) const
{
Q_UNUSED(index)
return cache.count();
}
int BookmarkFilterModel::columnCount(const QModelIndex &index) const
{
Q_UNUSED(index)
if (sourceModel)
return sourceModel->columnCount();
return 0;
}
QModelIndex BookmarkFilterModel::mapToSource(const QModelIndex &proxyIndex) const
{
const int row = proxyIndex.row();
if (proxyIndex.isValid() && row >= 0 && row < cache.count())
return cache[row];
return QModelIndex();
}
QModelIndex BookmarkFilterModel::mapFromSource(const QModelIndex &sourceIndex) const
{
return index(cache.indexOf(sourceIndex), 0, QModelIndex());
}
QModelIndex BookmarkFilterModel::parent(const QModelIndex &child) const
{
Q_UNUSED(child)
return QModelIndex();
}
QModelIndex BookmarkFilterModel::index(int row, int column,
const QModelIndex &index) const
{
Q_UNUSED(index)
if (row < 0 || column < 0 || cache.count() <= row
|| !sourceModel || sourceModel->columnCount() <= column) {
return QModelIndex();
}
return createIndex(row, 0);
}
Qt::DropActions BookmarkFilterModel::<API key> () const
{
if (sourceModel)
return sourceModel-><API key>();
return Qt::IgnoreAction;
}
Qt::ItemFlags BookmarkFilterModel::flags(const QModelIndex &index) const
{
if (sourceModel)
return sourceModel->flags(index);
return Qt::NoItemFlags;
}
QVariant BookmarkFilterModel::data(const QModelIndex &index, int role) const
{
if (sourceModel)
return sourceModel->data(mapToSource(index), role);
return QVariant();
}
bool BookmarkFilterModel::setData(const QModelIndex &index, const QVariant &value,
int role)
{
if (sourceModel)
return sourceModel->setData(mapToSource(index), value, role);
return false;
}
void BookmarkFilterModel::filterBookmarks()
{
if (sourceModel) {
beginResetModel();
hideBookmarks = true;
setupCache(sourceModel->index(0, 0, QModelIndex()).parent());
endResetModel();
}
}
void BookmarkFilterModel::<API key>()
{
if (sourceModel) {
beginResetModel();
hideBookmarks = false;
setupCache(sourceModel->index(0, 0, QModelIndex()).parent());
endResetModel();
}
}
void BookmarkFilterModel::changed(const QModelIndex &topLeft,
const QModelIndex &bottomRight)
{
emit dataChanged(mapFromSource(topLeft), mapFromSource(bottomRight));
}
void BookmarkFilterModel::rowsInserted(const QModelIndex &parent, int start,
int end)
{
if (!sourceModel)
return;
QModelIndex cachePrevious = parent;
if (BookmarkItem *parentItem = sourceModel->itemFromIndex(parent)) {
BookmarkItem *newItem = parentItem->child(start);
// iterate over tree hirarchie to find the previous folder
for (int i = 0; i < parentItem->childCount(); ++i) {
if (BookmarkItem *child = parentItem->child(i)) {
const QModelIndex &tmp = sourceModel->indexFromItem(child);
if (tmp.data(UserRoleFolder).toBool() && child != newItem)
cachePrevious = tmp;
}
}
const QModelIndex &newIndex = sourceModel->indexFromItem(newItem);
const bool isFolder = newIndex.data(UserRoleFolder).toBool();
if ((isFolder && hideBookmarks) || (!isFolder && !hideBookmarks)) {
beginInsertRows(mapFromSource(parent), start, end);
const int index = cache.indexOf(cachePrevious) + 1;
if (cache.value(index, <API key>()) != newIndex)
cache.insert(index, newIndex);
endInsertRows();
}
}
}
void BookmarkFilterModel::<API key>(const QModelIndex &parent,
int start, int end)
{
if (!sourceModel)
return;
if (BookmarkItem *parentItem = sourceModel->itemFromIndex(parent)) {
if (BookmarkItem *child = parentItem->child(start)) {
indexToRemove = sourceModel->indexFromItem(child);
if (cache.contains(indexToRemove))
beginRemoveRows(mapFromSource(parent), start, end);
}
}
}
void BookmarkFilterModel::rowsRemoved(const QModelIndex &/*parent*/, int, int)
{
if (cache.contains(indexToRemove)) {
cache.removeAll(indexToRemove);
endRemoveRows();
}
}
void BookmarkFilterModel::<API key>()
{
// TODO: ???
}
void BookmarkFilterModel::layoutChanged()
{
// TODO: ???
}
void BookmarkFilterModel::modelAboutToBeReset()
{
beginResetModel();
}
void BookmarkFilterModel::modelReset()
{
if (sourceModel)
setupCache(sourceModel->index(0, 0, QModelIndex()).parent());
endResetModel();
}
void BookmarkFilterModel::setupCache(const QModelIndex &parent)
{
cache.clear();
for (int i = 0; i < sourceModel->rowCount(parent); ++i)
collectItems(sourceModel->index(i, 0, parent));
}
void BookmarkFilterModel::collectItems(const QModelIndex &parent)
{
if (parent.isValid()) {
bool isFolder = sourceModel->data(parent, UserRoleFolder).toBool();
if ((isFolder && hideBookmarks) || (!isFolder && !hideBookmarks))
cache.append(parent);
if (sourceModel->hasChildren(parent)) {
for (int i = 0; i < sourceModel->rowCount(parent); ++i)
collectItems(sourceModel->index(i, 0, parent));
}
}
}
// -- BookmarkTreeModel
BookmarkTreeModel::BookmarkTreeModel(QObject *parent)
: <API key>(parent)
{
}
int BookmarkTreeModel::columnCount(const QModelIndex &parent) const
{
return qMin(1, <API key>::columnCount(parent));
}
bool BookmarkTreeModel::filterAcceptsRow(int row, const QModelIndex &parent) const
{
Q_UNUSED(row)
BookmarkModel *model = qobject_cast<BookmarkModel*> (sourceModel());
if (model->rowCount(parent) > 0
&& model->data(model->index(row, 0, parent), UserRoleFolder).toBool())
return true;
return false;
}
|
// chat_client.cpp
#include <cstdlib>
#include <deque>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include "chat_message.hpp"
using boost::asio::ip::tcp;
typedef std::deque<chat_message> chat_message_queue;
class chat_client
{
public:
chat_client(boost::asio::io_service& io_service,
tcp::resolver::iterator endpoint_iterator)
: io_service_(io_service),
socket_(io_service)
{
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint,
boost::bind(&chat_client::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
void write(const chat_message& msg)
{
io_service_.post(boost::bind(&chat_client::do_write, this, msg));
}
void close()
{
io_service_.post(boost::bind(&chat_client::do_close, this));
}
private:
void handle_connect(const boost::system::error_code& error,
tcp::resolver::iterator endpoint_iterator)
{
if (!error)
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::handle_read_header, this,
boost::asio::placeholders::error));
}
else if (endpoint_iterator != tcp::resolver::iterator())
{
socket_.close();
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint,
boost::bind(&chat_client::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
}
void handle_read_header(const boost::system::error_code& error)
{
if (!error && read_msg_.decode_header())
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
boost::bind(&chat_client::handle_read_body, this,
boost::asio::placeholders::error));
}
else
{
do_close();
}
}
void handle_read_body(const boost::system::error_code& error)
{
if (!error)
{
std::cout.write(read_msg_.body(), read_msg_.body_length());
std::cout << "\n";
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::handle_read_header, this,
boost::asio::placeholders::error));
}
else
{
do_close();
}
}
void do_write(chat_message msg)
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error));
}
}
void handle_write(const boost::system::error_code& error)
{
if (!error)
{
write_msgs_.pop_front();
if (!write_msgs_.empty())
{
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error));
}
}
else
{
do_close();
}
}
void do_close()
{
socket_.close();
}
private:
boost::asio::io_service& io_service_;
tcp::socket socket_;
chat_message read_msg_;
chat_message_queue write_msgs_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: chat_client <host> <port>\n";
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);
chat_client c(io_service, iterator);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
char line[chat_message::max_body_length + 1];
while (std::cin.getline(line, chat_message::max_body_length + 1))
{
using namespace std; // For strlen and memcpy.
chat_message msg;
msg.body_length(strlen(line));
memcpy(msg.body(), line, msg.body_length());
msg.encode_header();
c.write(msg);
}
c.close();
t.join();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
// This file is part of the deal.II library.
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// the top level of the deal.II distribution.
// Test Legendre expansion in 2D and 3D for a function given using Legendre
// coefficients.
#include "../tests.h"
#include <iostream>
#include <deal.II/base/function.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/hp/dof_handler.h>
#include <deal.II/fe/fe_series.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/lac/vector.h>
#include <deal.II/hp/q_collection.h>
#include <deal.II/numerics/vector_tools.h>
#include <gsl/gsl_sf_legendre.h>
using namespace dealii;
template <int dim>
class LegendreFunction : public Function<dim>
{
public:
LegendreFunction(const Table<dim,double> &coefficients)
:
dealii::Function<dim>(1),
coefficients(coefficients)
{
}
virtual double value(const Point<dim> &point,
const unsigned int component = 0 ) const;
const Table<dim,double> &get_coefficients() const
{
return coefficients;
}
private:
const Table<dim,double> coefficients;
};
// copy-paste from fe_series.cc
template <int dim>
double Lh(const Point<dim> &x_q,
const TableIndices<dim> &indices)
{
double res = 1.0;
for (unsigned int d = 0; d < dim; d++)
{
const double x = 2.0*(x_q[d]-0.5);
Assert ( (x_q[d] <= 1.0) && (x_q[d] >= 0.),
ExcMessage("x_q is not in [0,1]" +
Utilities::to_string(x_q[d])));
const int ind = indices[d];
res *= sqrt(2.0) * gsl_sf_legendre_Pl (ind, x);
}
return res;
}
template <>
double LegendreFunction<2>::value(const dealii::Point<2> &point,
const unsigned int ) const
{
double f = 0.0;
for (unsigned int i = 0; i < coefficients.size(0); i++)
for (unsigned int j = 0; j < coefficients.size(1); j++)
f+= Lh(point, TableIndices<2>(i,j)) * coefficients(i,j);
return f;
}
template <>
double LegendreFunction<3>::value(const dealii::Point<3> &point,
const unsigned int ) const
{
double f = 0.0;
for (unsigned int i = 0; i < coefficients.size(0); i++)
for (unsigned int j = 0; j < coefficients.size(1); j++)
for (unsigned int k = 0; k < coefficients.size(2); k++)
f+= Lh(point, TableIndices<3>(i,j,k)) * coefficients(i,j,k);
return f;
}
void print(const Table<2,double> &coeff)
{
for (unsigned int i = 0; i < coeff.size(0); i++)
for (unsigned int j = 0; j < coeff.size(1); j++)
deallog << coeff(i,j) << " ";
deallog << std::endl;
}
void print(const Table<3,double> &coeff)
{
for (unsigned int i = 0; i < coeff.size(0); i++)
for (unsigned int j = 0; j < coeff.size(1); j++)
for (unsigned int k = 0; k < coeff.size(2); k++)
deallog << coeff(i,j,k) << " ";
deallog << std::endl;
}
void resize(Table<2,double> &coeff, const unsigned int N)
{
coeff.reinit(N,N);
}
void resize(Table<3,double> &coeff, const unsigned int N)
{
TableIndices<3> size;
for (unsigned int d=0; d<3; d++)
size[d] = N;
coeff.reinit(size);
}
template <int dim>
void test(const LegendreFunction<dim> &func,
const unsigned int poly_degree)
{
const unsigned int max_poly = poly_degree+3;
deallog <<"
deallog << dim <<"d, p="<<poly_degree<<", max_p="<<max_poly<<std::endl;
deallog <<"
Triangulation<dim> triangulation;
hp::DoFHandler<dim> dof_handler(triangulation);
hp::FECollection<dim> fe_collection;
hp::QCollection<dim> quadrature_formula;
// add some extra FEs in fe_collection
for (unsigned int p = 1; p <= max_poly; p++)
{
fe_collection.push_back(FE_Q<dim>(p));
quadrature_formula.push_back(QGauss<dim>(p+1+5));
}
GridGenerator::hyper_cube (triangulation,0.0,1.0); // reference cell
const unsigned int fe_index = poly_degree-1;
dof_handler.begin_active()->set_active_fe_index(fe_index);
dof_handler.distribute_dofs (fe_collection);
Vector<double> values(dof_handler.n_dofs());
VectorTools::interpolate (dof_handler,func,values);
const unsigned int N = poly_degree+1;
FESeries::Legendre<dim> legendre(N,
fe_collection,
quadrature_formula);
const Table<dim,double> &coeff_in = func.get_coefficients();
Table<dim,double> coeff_out;
resize(coeff_out,N);
Vector<double> local_dof_values;
typename hp::DoFHandler<dim>::<API key>
cell = dof_handler.begin_active();
{
const unsigned int cell_n_dofs = cell->get_fe().dofs_per_cell;
const unsigned int <API key> = cell->active_fe_index();
local_dof_values.reinit (cell_n_dofs);
cell->get_dof_values (values, local_dof_values);
legendre.calculate(local_dof_values,
<API key>,
coeff_out);
}
deallog << "calculated:" << std::endl;
print(coeff_out);
deallog <<"exact:"<<std::endl;
print(coeff_in);
dof_handler.clear();
}
int main ()
{
std::ofstream logfile("output");
dealii::deallog.attach(logfile,/*do not print job id*/false);
dealii::deallog.depth_console(0);
{
const unsigned int dim = 2;
const unsigned int coeff_1d = 2;
const unsigned int p = 1;
Table<dim,double> coeff_in(coeff_1d,coeff_1d);
unsigned int ind = 0;
for (unsigned int i = 0; i < coeff_1d; i++)
for (unsigned int j = 0; j < coeff_1d; j++)
coeff_in(i,j) = 1.0 + ind++;
LegendreFunction<dim> function(coeff_in);
test(function,p);
}
{
const unsigned int dim = 2;
const unsigned int coeff_1d = 3;
const unsigned int p = 2;
Table<dim,double> coeff_in(coeff_1d,coeff_1d);
unsigned int ind = 0;
for (unsigned int i = 0; i < coeff_1d; i++)
for (unsigned int j = 0; j < coeff_1d; j++)
coeff_in(i,j) = 1.0 + ind++;
LegendreFunction<dim> function(coeff_in);
test(function,p);
}
{
const unsigned int dim = 3;
const unsigned int coeff_1d = 2;
const unsigned int p = 1;
Table<dim,double> coeff_in(coeff_1d,coeff_1d,coeff_1d);
unsigned int ind = 0;
for (unsigned int i = 0; i < coeff_1d; i++)
for (unsigned int j = 0; j < coeff_1d; j++)
for (unsigned int k = 0; k < coeff_1d; k++)
coeff_in(i,j,k) = 1.0 + ind++;
LegendreFunction<dim> function(coeff_in);
test(function,p);
}
{
const unsigned int dim = 3;
const unsigned int coeff_1d = 3;
const unsigned int p = 2;
Table<dim,double> coeff_in(coeff_1d,coeff_1d,coeff_1d);
unsigned int ind = 0;
for (unsigned int i = 0; i < coeff_1d; i++)
for (unsigned int j = 0; j < coeff_1d; j++)
for (unsigned int k = 0; k < coeff_1d; k++)
coeff_in(i,j,k) = 1.0 + ind++;
LegendreFunction<dim> function(coeff_in);
test(function,p);
}
dealii::deallog << "Ok"<<std::endl;
}
|
package org.exist.management;
import org.exist.management.impl.PerInstanceMBean;
import org.exist.storage.BrokerPool;
import org.exist.util.<API key>;
/**
* A dummy agent which will be used if JMX is disabled. It just acts as an empty
* placeholder.
*/
public class DummyAgent implements Agent {
@Override
public void initDBInstance(final BrokerPool instance) {
// do nothing
}
@Override
public void closeDBInstance(final BrokerPool instance) {
// nothing to do
}
@Override
public void addMBean(final PerInstanceMBean mbean) throws <API key> {
// just do nothing
}
@Override
public void changeStatus(final BrokerPool instance, final TaskStatus actualStatus) {
// nothing to do
}
@Override
public void updateStatus(final BrokerPool instance, final int percentage) {
// nothing to do
}
}
|
{% if level_1 == 'ubuntu' %}{% endif %}
{% if level_1 == 'business' %}{% endif %}
{% if level_1 == 'devices' %}{% endif %}
{% if level_1 == 'cloud' %}{% endif %}
{% if level_1 == 'download' %}{% endif %}
{% if level_1 == 'support' %}{% endif %}
{% if level_1 == 'project' %}{% endif %}
{% if level_1 == 'community' %}{% endif %}
{% if level_1 == 'partners' %}{% endif %}
|
package org.alfresco.repo.management.subsystems;
import java.io.IOException;
/**
* @author Andy
*
*/
public class <API key> extends <API key>
{
/* (non-Javadoc)
* @see org.alfresco.repo.management.subsystems.<API key>#createInitialState()
*/
@Override
protected <API key> createInitialState() throws IOException
{
return new <API key>(true);
}
protected void destroy(boolean isPermanent)
{
super.destroy(isPermanent);
doInit();
}
}
|
package org.alfresco.repo.template;
import java.io.StringReader;
import org.alfresco.error.<API key>;
import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.NodeRef;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* Provides functionality to execute a Lucene search string and return TemplateNode objects.
*
* @author Kevin Roast
*/
public class <API key> extends <API key>
{
/**
* Constructor
*
* @param parent The parent TemplateNode to execute searches from
* @param services The ServiceRegistry to use
*/
public <API key>(TemplateNode parent, ServiceRegistry services)
{
super(parent, services);
}
/**
* @see org.alfresco.repo.template.BaseTemplateMap#get(java.lang.Object)
*/
public Object get(Object key)
{
// execute the search
return query(key.toString());
}
}
|
#include <libopencm3/stm32/crc.h>
#include <libopencm3/stm32/common/crc_common_all.h>
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="manual.css">
</head>
<body>
<h1>Event</h1>
<h2>Request</h2>
<h3>Path</h3>
<table>
<tr>
<td>/events</td>
</tr>
</table>
<h3>Parameters</h3>
<table>
<tr>
<td>nothing</td>
</tr>
</table>
<h2>Response</h2>
<table>
<tr>
<th>Key</th>
<th>Value type</th>
<th>Brief</th>
<th>Reply</th>
</tr>
<tr>
<td>result</td>
<td>Boolean</td>
<td>True on success. Otherwise False.</td>
<td>A</td>
</tr>
<tr>
<td>message</td>
<td>String</td>
<td>Error message. This key is reply only when result is False.</td>
<td>F</td>
</tr>
<tr>
<td>numberOfEvents</td>
<td>Number</td>
<td>The number of events.</td>
<td>T</td>
</tr>
<tr>
<td>events</td>
<td>Array</td>
<td>The array of event object.</td>
<td>T</td>
</tr>
</table>
A: always, T: only when result is True, F: only when result is False.
<h3>Event Object</h3>
<table>
<tr>
<th>Key</th>
<th>Value type</th>
<th>Brief</th>
</tr>
<tr>
<td>serverId</td>
<td>Number</td>
<td>A unique server ID.</td>
</tr>
<tr>
<td>time</td>
<td>Number</td>
<td></td>
</tr>
<tr>
<td>eventValue</td>
<td>Number</td>
<td></td>
</tr>
<tr>
<td>triggerId</td>
<td>Number</td>
<td></td>
</tr>
<tr>
<td>status</td>
<td>Number</td>
<td></td>
</tr>
<tr>
<td>severity</td>
<td>Number</td>
<td></td>
</tr>
<tr>
<td>lastChangeTime</td>
<td>Number</td>
<td></td>
</tr>
<tr>
<td>hostId</td>
<td>String</td>
<td></td>
</tr>
<tr>
<td>hostName</td>
<td>String</td>
<td></td>
</tr>
<tr>
<td>brief</td>
<td>String</td>
<td>Brief of the event(trigger).</td>
</tr>
</body>
</html>
|
// RUN: %clang_cc1 -triple armv7-apple-darwin9 -emit-llvm -o - %s | FileCheck %s
// This isn't really testing anything ARM-specific; it's just a convenient
// 32-bit platform.
#define SWIFTCALL __attribute__((swiftcall))
#define OUT __attribute__((<API key>))
#define ERROR __attribute__((swift_error_result))
#define CONTEXT __attribute__((swift_context))
SWIFTCALL void indirect_result_1(OUT int *arg0, OUT float *arg1) {}
// CHECK-LABEL: define {{.*}} void @indirect_result_1(i32* noalias sret align 4 dereferenceable(4){{.*}}, float* noalias align 4 dereferenceable(4){{.*}})
// TODO: maybe this shouldn't suppress sret.
SWIFTCALL int indirect_result_2(OUT int *arg0, OUT float *arg1) { <API key>(); }
// CHECK-LABEL: define {{.*}} i32 @indirect_result_2(i32* noalias align 4 dereferenceable(4){{.*}}, float* noalias align 4 dereferenceable(4){{.*}})
typedef struct { char array[1024]; } struct_reallybig;
SWIFTCALL struct_reallybig indirect_result_3(OUT int *arg0, OUT float *arg1) { <API key>(); }
// CHECK-LABEL: define {{.*}} void @indirect_result_3({{.*}}* noalias sret {{.*}}, i32* noalias align 4 dereferenceable(4){{.*}}, float* noalias align 4 dereferenceable(4){{.*}})
SWIFTCALL void context_1(CONTEXT void *self) {}
// CHECK-LABEL: define {{.*}} void @context_1(i8* swiftself
SWIFTCALL void context_2(void *arg0, CONTEXT void *self) {}
// CHECK-LABEL: define {{.*}} void @context_2(i8*{{.*}}, i8* swiftself
SWIFTCALL void context_error_1(CONTEXT int *self, ERROR float **error) {}
// CHECK-LABEL: define {{.*}} void @context_error_1(i32* swiftself{{.*}}, float** swifterror)
// CHECK: [[TEMP:%.*]] = alloca float*, align 4
// CHECK: [[T0:%.*]] = load float*, float** [[ERRORARG:%.*]], align 4
// CHECK: store float* [[T0]], float** [[TEMP]], align 4
// CHECK: [[T0:%.*]] = load float*, float** [[TEMP]], align 4
// CHECK: store float* [[T0]], float** [[ERRORARG]], align 4
void <API key>() {
int x;
float *error;
context_error_1(&x, &error);
}
// CHECK-LABEL: define void @<API key>()
// CHECK: [[X:%.*]] = alloca i32, align 4
// CHECK: [[ERROR:%.*]] = alloca float*, align 4
// CHECK: [[TEMP:%.*]] = alloca swifterror float*, align 4
// CHECK: [[T0:%.*]] = load float*, float** [[ERROR]], align 4
// CHECK: store float* [[T0]], float** [[TEMP]], align 4
// CHECK: call [[SWIFTCC:swiftcc]] void @context_error_1(i32* swiftself [[X]], float** swifterror [[TEMP]])
// CHECK: [[T0:%.*]] = load float*, float** [[TEMP]], align 4
// CHECK: store float* [[T0]], float** [[ERROR]], align 4
SWIFTCALL void context_error_2(short s, CONTEXT int *self, ERROR float **error) {}
// CHECK-LABEL: define {{.*}} void @context_error_2(i16{{.*}}, i32* swiftself{{.*}}, float** swifterror)
typedef float float4 __attribute__((ext_vector_type(4)));
typedef float float8 __attribute__((ext_vector_type(8)));
typedef double double2 __attribute__((ext_vector_type(2)));
typedef double double4 __attribute__((ext_vector_type(4)));
typedef int int3 __attribute__((ext_vector_type(3)));
typedef int int4 __attribute__((ext_vector_type(4)));
typedef int int5 __attribute__((ext_vector_type(5)));
typedef int int8 __attribute__((ext_vector_type(8)));
#define TEST(TYPE) \
SWIFTCALL TYPE return_##TYPE(void) { \
TYPE result = {}; \
return result; \
} \
SWIFTCALL void take_##TYPE(TYPE v) { \
} \
void test_##TYPE() { \
take_##TYPE(return_##TYPE()); \
}
typedef struct {
} struct_empty;
TEST(struct_empty);
// CHECK-LABEL: define {{.*}} @return_struct_empty()
// CHECK: ret void
// CHECK-LABEL: define {{.*}} @take_struct_empty()
// CHECK: ret void
typedef struct {
int x;
char c0;
char c1;
float f0;
float f1;
} struct_1;
TEST(struct_1);
// CHECK-LABEL: define {{.*}} @return_struct_1()
// CHECK: [[RET:%.*]] = alloca [[REC:%.*]], align 4
// CHECK: [[VAR:%.*]] = alloca [[REC]], align 4
// CHECK: @llvm.memset
// CHECK: @llvm.memcpy
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ i32, i16, \[2 x i8\], float, float }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i16, i16* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[THIRD:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK: [[FOURTH:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = insertvalue [[UAGG:{ i32, i16, float, float }]] undef, i32 [[FIRST]], 0
// CHECK: [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i16 [[SECOND]], 1
// CHECK: [[T2:%.*]] = insertvalue [[UAGG]] [[T1]], float [[THIRD]], 2
// CHECK: [[T3:%.*]] = insertvalue [[UAGG]] [[T2]], float [[FOURTH]], 3
// CHECK: ret [[UAGG]] [[T3]]
// CHECK-LABEL: define {{.*}} @take_struct_1(i32, i16, float, float)
// CHECK: [[V:%.*]] = alloca [[REC]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store i32 %0, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: store i16 %1, i16* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: store float %2, float* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK: store float %3, float* [[T0]], align 4
// CHECK: ret void
// CHECK-LABEL: define void @test_struct_1()
// CHECK: [[TMP:%.*]] = alloca [[REC]], align 4
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG]] @return_struct_1()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store i32 [[T1]], i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store i16 [[T1]], i16* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 2
// CHECK: store float [[T1]], float* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 3
// CHECK: store float [[T1]], float* [[T0]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i16, i16* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[THIRD:%.*]] = load float, float* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK: [[FOURTH:%.*]] = load float, float* [[T0]], align 4
// CHECK: call [[SWIFTCC]] void @take_struct_1(i32 [[FIRST]], i16 [[SECOND]], float [[THIRD]], float [[FOURTH]])
// CHECK: ret void
typedef struct {
int x;
char c0;
__attribute__((aligned(2))) char c1;
float f0;
float f1;
} struct_2;
TEST(struct_2);
// CHECK-LABEL: define {{.*}} @return_struct_2()
// CHECK: [[RET:%.*]] = alloca [[REC:%.*]], align 4
// CHECK: [[VAR:%.*]] = alloca [[REC]], align 4
// CHECK: @llvm.memcpy
// CHECK: @llvm.memcpy
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ i32, i32, float, float }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[THIRD:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[FOURTH:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = insertvalue [[UAGG:{ i32, i32, float, float }]] undef, i32 [[FIRST]], 0
// CHECK: [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i32 [[SECOND]], 1
// CHECK: [[T2:%.*]] = insertvalue [[UAGG]] [[T1]], float [[THIRD]], 2
// CHECK: [[T3:%.*]] = insertvalue [[UAGG]] [[T2]], float [[FOURTH]], 3
// CHECK: ret [[UAGG]] [[T3]]
// CHECK-LABEL: define {{.*}} @take_struct_2(i32, i32, float, float)
// CHECK: [[V:%.*]] = alloca [[REC]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store i32 %0, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: store i32 %1, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: store float %2, float* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: store float %3, float* [[T0]], align 4
// CHECK: ret void
// CHECK-LABEL: define void @test_struct_2()
// CHECK: [[TMP:%.*]] = alloca [[REC]], align 4
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG]] @return_struct_2()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store i32 [[T1]], i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store i32 [[T1]], i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 2
// CHECK: store float [[T1]], float* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 3
// CHECK: store float [[T1]], float* [[T0]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[THIRD:%.*]] = load float, float* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[FOURTH:%.*]] = load float, float* [[T0]], align 4
// CHECK: call [[SWIFTCC]] void @take_struct_2(i32 [[FIRST]], i32 [[SECOND]], float [[THIRD]], float [[FOURTH]])
// CHECK: ret void
// There's no way to put a field randomly in the middle of an otherwise
// empty storage unit in C, so that case has to be tested in C++, which
// can use empty structs to introduce arbitrary padding. (In C, they end up
// with size 0 and so don't affect layout.)
// Misaligned data rule.
typedef struct {
char c0;
__attribute__((packed)) float f;
} struct_misaligned_1;
TEST(struct_misaligned_1)
// CHECK-LABEL: define {{.*}} @<API key>()
// CHECK: [[RET:%.*]] = alloca [[REC:%.*]], align
// CHECK: [[VAR:%.*]] = alloca [[REC]], align
// CHECK: @llvm.memset
// CHECK: @llvm.memcpy
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ i32, i8 }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i8, i8* [[T0]], align
// CHECK: [[T0:%.*]] = insertvalue [[UAGG:{ i32, i8 }]] undef, i32 [[FIRST]], 0
// CHECK: [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i8 [[SECOND]], 1
// CHECK: ret [[UAGG]] [[T1]]
// CHECK-LABEL: define {{.*}} @<API key>(i32, i8)
// CHECK: [[V:%.*]] = alloca [[REC]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store i32 %0, i32* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: store i8 %1, i8* [[T0]], align
// CHECK: ret void
// Too many scalars.
typedef struct {
int x[5];
} struct_big_1;
TEST(struct_big_1)
// CHECK-LABEL: define {{.*}} void @return_struct_big_1({{.*}} noalias sret
// Should not be byval.
// CHECK-LABEL: define {{.*}} void @take_struct_big_1({{.*}}*{{( %.*)?}})
typedef union {
float f;
double d;
} union_het_fp;
TEST(union_het_fp)
// CHECK-LABEL: define {{.*}} @return_union_het_fp()
// CHECK: [[RET:%.*]] = alloca [[REC:%.*]], align 4
// CHECK: [[VAR:%.*]] = alloca [[REC]], align 4
// CHECK: @llvm.memcpy
// CHECK: @llvm.memcpy
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ i32, i32 }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = insertvalue [[UAGG:{ i32, i32 }]] undef, i32 [[FIRST]], 0
// CHECK: [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i32 [[SECOND]], 1
// CHECK: ret [[UAGG]] [[T1]]
// CHECK-LABEL: define {{.*}} @take_union_het_fp(i32, i32)
// CHECK: [[V:%.*]] = alloca [[REC]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store i32 %0, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: store i32 %1, i32* [[T0]], align 4
// CHECK: ret void
// CHECK-LABEL: define void @test_union_het_fp()
// CHECK: [[TMP:%.*]] = alloca [[REC]], align 4
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG]] @return_union_het_fp()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store i32 [[T1]], i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store i32 [[T1]], i32* [[T0]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align 4
// CHECK: call [[SWIFTCC]] void @take_union_het_fp(i32 [[FIRST]], i32 [[SECOND]])
// CHECK: ret void
typedef union {
float f1;
float f2;
} union_hom_fp;
TEST(union_hom_fp)
// CHECK-LABEL: define void @test_union_hom_fp()
// CHECK: [[TMP:%.*]] = alloca [[REC:%.*]], align 4
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] float @return_union_hom_fp()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG:{ float }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store float [[CALL]], float* [[T0]], align 4
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load float, float* [[T0]], align 4
// CHECK: call [[SWIFTCC]] void @take_union_hom_fp(float [[FIRST]])
// CHECK: ret void
typedef union {
float f1;
float4 fv2;
} <API key>;
TEST(<API key>)
// CHECK-LABEL: define void @<API key>()
// CHECK: [[TMP:%.*]] = alloca [[REC:%.*]], align 16
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG:{ float, float, float, float }]] @<API key>()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG:{ float, float, float, float }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store float [[T1]], float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store float [[T1]], float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 2
// CHECK: store float [[T1]], float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 3
// CHECK: store float [[T1]], float* [[T0]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[THIRD:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[FOURTH:%.*]] = load float, float* [[T0]], align
// CHECK: call [[SWIFTCC]] void @<API key>(float [[FIRST]], float [[SECOND]], float [[THIRD]], float [[FOURTH]])
// CHECK: ret void
typedef union {
struct { int x, y; } f1;
float4 fv2;
} <API key>;
TEST(<API key>)
// CHECK-LABEL: define void @<API key>()
// CHECK: [[TMP:%.*]] = alloca [[REC:%.*]], align 16
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG:{ i32, i32, float, float }]] @<API key>()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG:{ i32, i32, float, float }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store i32 [[T1]], i32* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store i32 [[T1]], i32* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 2
// CHECK: store float [[T1]], float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 3
// CHECK: store float [[T1]], float* [[T0]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load i32, i32* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK: [[THIRD:%.*]] = load float, float* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 3
// CHECK: [[FOURTH:%.*]] = load float, float* [[T0]], align
// CHECK: call [[SWIFTCC]] void @<API key>(i32 [[FIRST]], i32 [[SECOND]], float [[THIRD]], float [[FOURTH]])
// CHECK: ret void
TEST(int4)
// CHECK-LABEL: define {{.*}} <4 x i32> @return_int4()
// CHECK-LABEL: define {{.*}} @take_int4(<4 x i32>
TEST(int8)
// CHECK-LABEL: define {{.*}} @return_int8()
// CHECK: [[RET:%.*]] = alloca [[REC:<8 x i32>]], align 32
// CHECK: [[VAR:%.*]] = alloca [[REC]], align
// CHECK: store
// CHECK: load
// CHECK: store
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ <4 x i32>, <4 x i32> }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load <4 x i32>, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load <4 x i32>, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = insertvalue [[UAGG:{ <4 x i32>, <4 x i32> }]] undef, <4 x i32> [[FIRST]], 0
// CHECK: [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], <4 x i32> [[SECOND]], 1
// CHECK: ret [[UAGG]] [[T1]]
// CHECK-LABEL: define {{.*}} @take_int8(<4 x i32>, <4 x i32>)
// CHECK: [[V:%.*]] = alloca [[REC]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store <4 x i32> %0, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: store <4 x i32> %1, <4 x i32>* [[T0]], align
// CHECK: ret void
// CHECK-LABEL: define void @test_int8()
// CHECK: [[TMP1:%.*]] = alloca [[REC]], align
// CHECK: [[TMP2:%.*]] = alloca [[REC]], align
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG]] @return_int8()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP1]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store <4 x i32> [[T1]], <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store <4 x i32> [[T1]], <4 x i32>* [[T0]], align
// CHECK: [[V:%.*]] = load [[REC]], [[REC]]* [[TMP1]], align
// CHECK: store [[REC]] [[V]], [[REC]]* [[TMP2]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP2]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load <4 x i32>, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load <4 x i32>, <4 x i32>* [[T0]], align
// CHECK: call [[SWIFTCC]] void @take_int8(<4 x i32> [[FIRST]], <4 x i32> [[SECOND]])
// CHECK: ret void
TEST(int5)
// CHECK-LABEL: define {{.*}} @return_int5()
// CHECK: [[RET:%.*]] = alloca [[REC:<5 x i32>]], align 32
// CHECK: [[VAR:%.*]] = alloca [[REC]], align
// CHECK: store
// CHECK: load
// CHECK: store
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ <4 x i32>, i32 }]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load <4 x i32>, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align
// CHECK: [[T0:%.*]] = insertvalue [[UAGG:{ <4 x i32>, i32 }]] undef, <4 x i32> [[FIRST]], 0
// CHECK: [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i32 [[SECOND]], 1
// CHECK: ret [[UAGG]] [[T1]]
// CHECK-LABEL: define {{.*}} @take_int5(<4 x i32>, i32)
// CHECK: [[V:%.*]] = alloca [[REC]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: store <4 x i32> %0, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: store i32 %1, i32* [[T0]], align
// CHECK: ret void
// CHECK-LABEL: define void @test_int5()
// CHECK: [[TMP1:%.*]] = alloca [[REC]], align
// CHECK: [[TMP2:%.*]] = alloca [[REC]], align
// CHECK: [[CALL:%.*]] = call [[SWIFTCC]] [[UAGG]] @return_int5()
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP1]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK: store <4 x i32> [[T1]], <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK: store i32 [[T1]], i32* [[T0]], align
// CHECK: [[V:%.*]] = load [[REC]], [[REC]]* [[TMP1]], align
// CHECK: store [[REC]] [[V]], [[REC]]* [[TMP2]], align
// CHECK: [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP2]] to [[AGG]]*
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK: [[FIRST:%.*]] = load <4 x i32>, <4 x i32>* [[T0]], align
// CHECK: [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 1
// CHECK: [[SECOND:%.*]] = load i32, i32* [[T0]], align
// CHECK: call [[SWIFTCC]] void @take_int5(<4 x i32> [[FIRST]], i32 [[SECOND]])
// CHECK: ret void
typedef struct {
int x;
int3 v __attribute__((packed));
} misaligned_int3;
TEST(misaligned_int3)
// CHECK-LABEL: define {{.*}} @<API key>(i32, i32, i32, i32)
|
import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the <API key> function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
from getpass import getuser
import ctypes
from ctypes.util import find_library
from ctypes import c_void_p, c_uint32, POINTER, c_bool, byref
from .core_foundation import CoreFoundation, unicode_to_cfstring, cfstring_to_unicode
from .._types import str_cls, type_name
od_path = find_library('OpenDirectory')
OpenDirectory = ctypes.CDLL(od_path, use_errno=True)
ODAttributeType = CoreFoundation.CFStringRef
ODMatchType = c_uint32
ODRecordType = CoreFoundation.CFStringRef
ODSessionRef = c_void_p
ODNodeRef = c_void_p
ODQueryRef = c_void_p
ODRecordRef = c_void_p
OpenDirectory.ODSessionCreate.argtypes = [
CoreFoundation.CFAllocatorRef,
CoreFoundation.CFDictionaryRef,
POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.ODSessionCreate.restype = ODSessionRef
OpenDirectory.<API key>.argtypes = [
CoreFoundation.CFAllocatorRef,
ODSessionRef,
CoreFoundation.CFStringRef,
POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.<API key>.restype = ODNodeRef
OpenDirectory.<API key>.argtypes = [
CoreFoundation.CFAllocatorRef,
ODNodeRef,
CoreFoundation.CFTypeRef,
ODAttributeType,
ODMatchType,
CoreFoundation.CFTypeRef,
CoreFoundation.CFTypeRef,
CoreFoundation.CFIndex,
POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.<API key>.restype = ODQueryRef
OpenDirectory.ODQueryCopyResults.argtypes = [
ODQueryRef,
c_bool,
POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.ODQueryCopyResults.restype = CoreFoundation.CFArrayRef
OpenDirectory.ODRecordCopyValues.argtypes = [
ODRecordRef,
ODAttributeType,
POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.ODRecordCopyValues.restype = CoreFoundation.CFArrayRef
kODMatchEqualTo = ODMatchType(0x2001)
kODRecordTypeUsers = ODRecordType.in_dll(OpenDirectory, 'kODRecordTypeUsers')
<API key> = ODAttributeType.in_dll(OpenDirectory, '<API key>')
<API key> = ODAttributeType.in_dll(OpenDirectory, '<API key>')
_login_shells = {}
def <API key>(username=None):
"""
Uses OS X's OpenDirectory.framework to get the user's login shell
:param username:
A unicode string of the user to get the shell for - None for the
current user
:return:
A unicode string of the user's login shell
"""
if username is None:
username = getuser()
if not isinstance(username, str_cls):
username = username.decode('utf-8')
if not isinstance(username, str_cls):
raise TypeError('username must be a unicode string, not %s' % type_name(username))
if username not in _login_shells:
error_ref = CoreFoundation.CFErrorRef()
session = OpenDirectory.ODSessionCreate(
CoreFoundation.kCFAllocatorDefault,
None,
byref(error_ref)
)
if bool(error_ref):
raise OSError('Error!')
node = OpenDirectory.<API key>(
CoreFoundation.kCFAllocatorDefault,
session,
unicode_to_cfstring("/Local/Default"),
byref(error_ref)
)
if bool(error_ref):
raise OSError('Error!')
query = OpenDirectory.<API key>(
CoreFoundation.kCFAllocatorDefault,
node,
kODRecordTypeUsers,
<API key>,
kODMatchEqualTo,
unicode_to_cfstring(username),
<API key>,
1,
byref(error_ref)
)
if bool(error_ref):
raise OSError('Error!')
results = OpenDirectory.ODQueryCopyResults(
query,
False,
byref(error_ref)
)
if bool(error_ref):
raise OSError('Error!')
login_shell = None
num_results = CoreFoundation.CFArrayGetCount(results)
if num_results == 1:
od_record = CoreFoundation.<API key>(results, 0)
attributes = OpenDirectory.ODRecordCopyValues(od_record, <API key>, byref(error_ref))
if bool(error_ref):
raise OSError('Error!')
num_attributes = CoreFoundation.CFArrayGetCount(results)
if num_attributes == 1:
string_ref = CoreFoundation.<API key>(attributes, 0)
login_shell = cfstring_to_unicode(string_ref)
_login_shells[username] = login_shell
return _login_shells.get(username)
|
import { expect } from 'chai';
import { spec } from 'modules/yieldoneBidAdapter.js';
import { newBidder } from 'src/adapters/bidderFactory.js';
import { deepClone } from 'src/utils.js';
const ENDPOINT = 'https://y.one.impact-ad.jp/h_bid';
const USER_SYNC_URL = 'https://y.one.impact-ad.jp/push_sync';
const VIDEO_PLAYER_URL = 'https://img.ak.impact-ad.jp/ic/pone/ivt/firstview/js/dac-video-prebid.min.js';
const DEFAULT_VIDEO_SIZE = {w: 640, h: 360};
describe('yieldoneBidAdapter', function() {
const adapter = newBidder(spec);
describe('isBidRequestValid', function () {
let bid = {
'bidder': 'yieldone',
'params': {
placementId: '36891'
},
'adUnitCode': 'adunit-code',
'sizes': [[300, 250], [336, 280]],
'bidId': '23beaa6af6cdde',
'bidderRequestId': '19c0c1efdf37e7',
'auctionId': '<API key>',
};
it('should return true when required params found', function () {
expect(spec.isBidRequestValid(bid)).to.equal(true);
});
it('should return false when placementId not passed correctly', function () {
bid.params.placementId = '';
expect(spec.isBidRequestValid(bid)).to.equal(false);
});
it('should return false when require params are not passed', function () {
let bid = Object.assign({}, bid);
bid.params = {};
expect(spec.isBidRequestValid(bid)).to.equal(false);
});
});
describe('buildRequests', function () {
const bidderRequest = {
refererInfo: {
numIframes: 0,
reachedTop: true,
referer: 'http://example.com',
stack: ['http://example.com']
}
};
describe('Basic', function () {
const bidRequests = [
{
'bidder': 'yieldone',
'params': {placementId: '36891'},
'adUnitCode': 'adunit-code1',
'bidId': '23beaa6af6cdde',
'bidderRequestId': '19c0c1efdf37e7',
'auctionId': '<API key>',
},
{
'bidder': 'yieldone',
'params': {placementId: '47919'},
'adUnitCode': 'adunit-code2',
'bidId': '382091349b149f"',
'bidderRequestId': '"1f9c98192de251"',
'auctionId': '<API key>',
}
];
const request = spec.buildRequests(bidRequests, bidderRequest);
it('sends bid request to our endpoint via GET', function () {
expect(request[0].method).to.equal('GET');
expect(request[1].method).to.equal('GET');
});
it('attaches source and version to endpoint URL as query params', function () {
expect(request[0].url).to.equal(ENDPOINT);
expect(request[1].url).to.equal(ENDPOINT);
});
it('adUnitCode should be sent as uc parameters on any requests', function () {
expect(request[0].data.uc).to.equal('adunit-code1');
expect(request[1].data.uc).to.equal('adunit-code2');
});
});
describe('Old Format', function () {
const bidRequests = [
{
params: {placementId: '0'},
mediaType: 'banner',
sizes: [[300, 250], [336, 280]],
},
{
params: {placementId: '1'},
mediaType: 'banner',
sizes: [[336, 280]],
},
{
// It doesn't actually exist.
params: {placementId: '2'},
},
{
params: {placementId: '3'},
mediaType: 'video',
sizes: [[1280, 720], [1920, 1080]],
},
{
params: {placementId: '4'},
mediaType: 'video',
sizes: [[1920, 1080]],
},
{
params: {placementId: '5'},
mediaType: 'video',
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
it('parameter sz has more than one size on banner requests', function () {
expect(request[0].data.sz).to.equal('300x250,336x280');
expect(request[1].data.sz).to.equal('336x280');
expect(request[2].data.sz).to.equal('');
expect(request[3].data).to.not.have.property('sz');
expect(request[4].data).to.not.have.property('sz');
expect(request[5].data).to.not.have.property('sz');
});
it('width and height should be set as separate parameters on outstream requests', function () {
expect(request[0].data).to.not.have.property('w');
expect(request[1].data).to.not.have.property('w');
expect(request[2].data).to.not.have.property('w');
expect(request[3].data.w).to.equal(1280);
expect(request[3].data.h).to.equal(720);
expect(request[4].data.w).to.equal(1920);
expect(request[4].data.h).to.equal(1080);
expect(request[5].data.w).to.equal(DEFAULT_VIDEO_SIZE.w);
expect(request[5].data.h).to.equal(DEFAULT_VIDEO_SIZE.h);
});
});
describe('New Format', function () {
const bidRequests = [
{
params: {placementId: '0'},
mediaTypes: {
banner: {
sizes: [[300, 250], [336, 280]],
},
},
},
{
params: {placementId: '1'},
mediaTypes: {
banner: {
sizes: [[336, 280]],
},
},
},
{
// It doesn't actually exist.
params: {placementId: '2'},
mediaTypes: {
banner: {
},
},
},
{
params: {placementId: '3'},
mediaTypes: {
video: {
context: 'outstream',
playerSize: [[1280, 720], [1920, 1080]],
},
},
},
{
params: {placementId: '4'},
mediaTypes: {
video: {
context: 'outstream',
playerSize: [1920, 1080],
},
},
},
{
params: {placementId: '5'},
mediaTypes: {
video: {
context: 'outstream',
},
},
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
it('parameter sz has more than one size on banner requests', function () {
expect(request[0].data.sz).to.equal('300x250,336x280');
expect(request[1].data.sz).to.equal('336x280');
expect(request[2].data.sz).to.equal('');
expect(request[3].data).to.not.have.property('sz');
expect(request[4].data).to.not.have.property('sz');
expect(request[5].data).to.not.have.property('sz');
});
it('width and height should be set as separate parameters on outstream requests', function () {
expect(request[0].data).to.not.have.property('w');
expect(request[1].data).to.not.have.property('w');
expect(request[2].data).to.not.have.property('w');
expect(request[3].data.w).to.equal(1280);
expect(request[3].data.h).to.equal(720);
expect(request[4].data.w).to.equal(1920);
expect(request[4].data.h).to.equal(1080);
expect(request[5].data.w).to.equal(DEFAULT_VIDEO_SIZE.w);
expect(request[5].data.h).to.equal(DEFAULT_VIDEO_SIZE.h);
});
});
describe('Multiple Format', function () {
const bidRequests = [
{
// It will be treated as a banner.
params: {
placementId: '0',
},
mediaTypes: {
banner: {
sizes: [[300, 250], [336, 280]],
},
video: {
context: 'outstream',
playerSize: [1920, 1080],
},
},
},
{
// It will be treated as a video.
params: {
placementId: '1',
playerParams: {},
},
mediaTypes: {
banner: {
sizes: [[300, 250], [336, 280]],
},
video: {
context: 'outstream',
playerSize: [1920, 1080],
},
},
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
it('parameter sz has more than one size on banner requests', function () {
expect(request[0].data.sz).to.equal('300x250,336x280');
expect(request[1].data).to.not.have.property('sz');
});
it('width and height should be set as separate parameters on outstream requests', function () {
expect(request[0].data).to.not.have.property('w');
expect(request[1].data.w).to.equal(1920);
expect(request[1].data.h).to.equal(1080);
});
});
describe('FLUX Format', function () {
const bidRequests = [
{
// It will be treated as a banner.
params: {
placementId: '0',
},
mediaTypes: {
banner: {
sizes: [[300, 250], [336, 280]],
},
video: {
context: 'outstream',
playerSize: [[1, 1]],
},
},
},
{
// It will be treated as a video.
params: {
placementId: '1',
playerParams: {},
playerSize: [1920, 1080],
},
mediaTypes: {
banner: {
sizes: [[300, 250], [336, 280]],
},
video: {
context: 'outstream',
playerSize: [[1, 1]],
},
},
},
{
// It will be treated as a video.
params: {
placementId: '2',
playerParams: {},
},
mediaTypes: {
banner: {
sizes: [[300, 250], [336, 280]],
},
video: {
context: 'outstream',
playerSize: [[1, 1]],
},
},
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
it('parameter sz has more than one size on banner requests', function () {
expect(request[0].data.sz).to.equal('300x250,336x280');
expect(request[1].data).to.not.have.property('sz');
expect(request[2].data).to.not.have.property('sz');
});
it('width and height should be set as separate parameters on outstream requests', function () {
expect(request[0].data).to.not.have.property('w');
expect(request[1].data.w).to.equal(1920);
expect(request[1].data.h).to.equal(1080);
expect(request[2].data.w).to.equal(DEFAULT_VIDEO_SIZE.w);
expect(request[2].data.h).to.equal(DEFAULT_VIDEO_SIZE.h);
});
});
describe('LiveRampID', function () {
it('dont send LiveRampID if undefined', function () {
const bidRequests = [
{
params: {placementId: '0'},
},
{
params: {placementId: '1'},
userId: {},
},
{
params: {placementId: '2'},
userId: undefined,
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
expect(request[0].data).to.not.have.property('lr_env');
expect(request[1].data).to.not.have.property('lr_env');
expect(request[2].data).to.not.have.property('lr_env');
});
it('should send LiveRampID if available', function () {
const bidRequests = [
{
params: {placementId: '0'},
userId: {idl_env: 'idl_env_sample'},
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
expect(request[0].data.lr_env).to.equal('idl_env_sample');
});
});
describe('IMID', function () {
it('dont send IMID if undefined', function () {
const bidRequests = [
{
params: {placementId: '0'},
},
{
params: {placementId: '1'},
userId: {},
},
{
params: {placementId: '2'},
userId: undefined,
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
expect(request[0].data).to.not.have.property('imuid');
expect(request[1].data).to.not.have.property('imuid');
expect(request[2].data).to.not.have.property('imuid');
});
it('should send IMID if available', function () {
const bidRequests = [
{
params: {placementId: '0'},
userId: {imuid: 'imuid_sample'},
},
];
const request = spec.buildRequests(bidRequests, bidderRequest);
expect(request[0].data.imuid).to.equal('imuid_sample');
});
});
});
describe('interpretResponse', function () {
let bidRequestBanner = [
{
'method': 'GET',
'url': 'https://y.one.impact-ad.jp/h_bid',
'data': {
'v': 'hb1',
'p': '36891',
'sz': '300x250,336x280',
'cb': 12892917383,
'r': 'http%3A%2F%2Flocalhost%3A9876%2F%3Fid%3D74552836',
'uid': '23beaa6af6cdde',
't': 'i'
}
}
];
let <API key> = {
body: {
'adTag': '<!-- adtag -->',
'uid': '23beaa6af6cdde',
'height': 250,
'width': 300,
'cpm': 0.0536616,
'crid': '2494768',
'currency': 'JPY',
'statusMessage': 'Bid available',
'dealId': 'P1-FIX-7800-DSP-MON',
'admoain': [
'www.example.com'
]
}
};
it('should get the correct bid response for banner', function () {
let expectedResponse = [{
'requestId': '23beaa6af6cdde',
'cpm': 53.6616,
'width': 300,
'height': 250,
'creativeId': '2494768',
'dealId': 'P1-FIX-7800-DSP-MON',
'currency': 'JPY',
'netRevenue': true,
'ttl': 3000,
'referrer': '',
'meta': {
'advertiserDomains': [
'www.example.com'
]
},
'mediaType': 'banner',
'ad': '<!-- adtag -->'
}];
let result = spec.interpretResponse(<API key>, bidRequestBanner[0]);
expect(Object.keys(result[0])).to.deep.equal(Object.keys(expectedResponse[0]));
expect(result[0].mediaType).to.equal(expectedResponse[0].mediaType);
});
let serverResponseVideo = {
body: {
'uid': '23beaa6af6cdde',
'height': 360,
'width': 640,
'cpm': 0.0536616,
'dealId': 'P1-FIX-766-DSP-MON',
'crid': '2494768',
'currency': 'JPY',
'statusMessage': 'Bid available',
'adm': '<!-- vast -->'
}
};
let bidRequestVideo = [
{
'method': 'GET',
'url': 'https://y.one.impact-ad.jp/h_bid',
'data': {
'v': 'hb1',
'p': '41993',
'w': '640',
'h': '360',
'cb': 12892917383,
'r': 'http%3A%2F%2Flocalhost%3A9876%2F%3Fid%3D74552836',
'uid': '23beaa6af6cdde',
't': 'i'
}
}
];
it('should get the correct bid response for video', function () {
let expectedResponse = [{
'requestId': '23beaa6af6cdde',
'cpm': 53.6616,
'width': 640,
'height': 360,
'creativeId': '2494768',
'dealId': 'P1-FIX-7800-DSP-MON',
'currency': 'JPY',
'netRevenue': true,
'ttl': 3000,
'referrer': '',
'meta': {
'advertiserDomains': []
},
'mediaType': 'video',
'vastXml': '<!-- vast -->',
'renderer': {
id: '23beaa6af6cdde',
url: VIDEO_PLAYER_URL
}
}];
let result = spec.interpretResponse(serverResponseVideo, bidRequestVideo[0]);
expect(Object.keys(result[0])).to.deep.equal(Object.keys(expectedResponse[0]));
expect(result[0].mediaType).to.equal(expectedResponse[0].mediaType);
expect(result[0].renderer.id).to.equal(expectedResponse[0].renderer.id);
expect(result[0].renderer.url).to.equal(expectedResponse[0].renderer.url);
});
it('handles empty bid response', function () {
let response = {
body: {
'uid': '2c0b634db95a01',
'height': 0,
'crid': '',
'statusMessage': 'Bid returned empty or error response',
'width': 0,
'cpm': 0
}
};
let result = spec.interpretResponse(response, bidRequestBanner[0]);
expect(result.length).to.equal(0);
});
});
describe('getUserSyncs', function () {
it('handles empty sync options', function () {
expect(spec.getUserSyncs({})).to.be.undefined;
});
it('should return a sync url if iframe syncs are enabled', function () {
expect(spec.getUserSyncs({
'iframeEnabled': true
})).to.deep.equal([{
type: 'iframe', url: USER_SYNC_URL
}]);
});
});
});
|
#include "vocabulary.h"
namespace extractor {
Vocabulary::~Vocabulary() {}
int Vocabulary::GetTerminalIndex(const string& word) {
int word_id = -1;
#pragma omp critical (vocabulary)
{
auto it = dictionary.find(word);
if (it != dictionary.end()) {
word_id = it->second;
} else {
word_id = words.size();
dictionary[word] = word_id;
words.push_back(word);
}
}
return word_id;
}
int Vocabulary::GetNonterminalIndex(int position) {
return -position;
}
bool Vocabulary::IsTerminal(int symbol) {
return symbol >= 0;
}
string Vocabulary::GetTerminalValue(int symbol) {
string word;
#pragma omp critical (vocabulary)
word = words[symbol];
return word;
}
bool Vocabulary::operator==(const Vocabulary& other) const {
return words == other.words && dictionary == other.dictionary;
}
} // namespace extractor
|
#ifndef <API key>
#define <API key>
CL_CLASS_DEF(search,Similarity)
CL_CLASS_DEF(search,HitCollector)
CL_CLASS_DEF(search,Explanation)
CL_NS_DEF(search)
/**
* Expert: Common scoring functionality for different types of queries.
*
* <p>
* A <code>Scorer</code> either iterates over documents matching a
* query in increasing order of doc Id, or provides an explanation of
* the score for a query for a given document.
* </p>
* <p>
* Document scores are computed using a given <code>Similarity</code>
* implementation.
* </p>
* @see BooleanQuery#<API key>
*/
class CLUCENE_EXPORT Scorer {
private:
Similarity* similarity;
protected:
/** Constructs a Scorer.
* @param similarity The <code>Similarity</code> implementation used by this scorer.
*/
Scorer(Similarity* _similarity);
public:
virtual ~Scorer();
/** Returns the Similarity implementation used by this scorer. */
Similarity* getSimilarity() const;
/** Scores and collects all matching documents.
* @param hc The collector to which all matching documents are passed through
* {@link HitCollector#collect(int, float)}.
* <br>When this method is used the {@link #explain(int)} method should not be used.
*/
virtual void score(HitCollector* hc) ;
/** Expert: Collects matching documents in a range. Hook for optimization.
* Note that {@link #next()} must be called once before this method is called
* for the first time.
* @param hc The collector to which all matching documents are passed through
* {@link HitCollector#collect(int, float)}.
* @param max Do not score documents past this.
* @return true if more matching documents may remain.
*/
virtual bool score( HitCollector* results, const int32_t maxDoc );
/**
* Advances to the document matching this Scorer with the lowest doc Id
* greater than the current value of {@link #doc()} (or to the matching
* document with the lowest doc Id if next has never been called on
* this Scorer).
*
* <p>
* When this method is used the {@link #explain(int)} method should not
* be used.
* </p>
*
* @return true iff there is another document matching the query.
* @see BooleanQuery#<API key>
*/
virtual bool next() = 0;
/** Returns the current document number matching the query.
* Initially invalid, until {@link #next()} is called the first time.
*/
virtual int32_t doc() const = 0;
/** Returns the score of the current document matching the query.
* Initially invalid, until {@link #next()} or {@link #skipTo(int)}
* is called the first time.
*/
virtual float_t score() = 0;
/**
* Skips to the document matching this Scorer with the lowest doc Id
* greater than or equal to a given target.
*
* <p>
* The behavior of this method is undefined if the target specified is
* less than or equal to the current value of {@link #doc()}.
* <p>
* Behaves as if written:
* <pre>
* boolean skipTo(int target) {
* do {
* if (!next())
* return false;
* } while (target > doc());
* return true;
* }
* </pre>
* Most implementations are considerably more efficient than that.
* </p>
*
* <p>
* When this method is used the {@link #explain(int)} method should not
* be used.
* </p>
*
* @param target The target document number.
* @return true iff there is such a match.
* @see BooleanQuery#<API key>
*/
virtual bool skipTo(int32_t target) = 0;
/** Returns an explanation of the score for a document.
* <br>When this method is used, the {@link #next()}, {@link #skipTo(int)} and
* {@link #score(HitCollector)} methods should not be used.
* @param doc The document number for the explanation.
*/
virtual Explanation* explain(int32_t doc) = 0;
/** Returns a string which explains the object */
virtual TCHAR* toString() = 0;
static bool sort(const Scorer* elem1, const Scorer* elem2);
};
CL_NS_END
#endif
|
"""Provides device automations for ZHA devices that emit events."""
import voluptuous as vol
import homeassistant.components.automation.event as event
from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA
from homeassistant.components.device_automation.exceptions import (
<API key>,
)
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from . import DOMAIN
from .core.helpers import <API key>
CONF_SUBTYPE = "subtype"
DEVICE = "device"
DEVICE_IEEE = "device_ieee"
ZHA_EVENT = "zha_event"
TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend(
{vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str}
)
async def <API key>(hass, config):
"""Validate config."""
config = TRIGGER_SCHEMA(config)
if "zha" in hass.config.components:
trigger = (config[CONF_TYPE], config[CONF_SUBTYPE])
try:
zha_device = await <API key>(hass, config[CONF_DEVICE_ID])
except (KeyError, AttributeError):
raise <API key>
if (
zha_device.<API key> is None
or trigger not in zha_device.<API key>
):
raise <API key>
return config
async def <API key>(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
trigger = (config[CONF_TYPE], config[CONF_SUBTYPE])
try:
zha_device = await <API key>(hass, config[CONF_DEVICE_ID])
except (KeyError, AttributeError):
return None
if trigger not in zha_device.<API key>:
return None
trigger = zha_device.<API key>[trigger]
event_config = {
event.CONF_PLATFORM: "event",
event.CONF_EVENT_TYPE: ZHA_EVENT,
event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger},
}
event_config = event.TRIGGER_SCHEMA(event_config)
return await event.<API key>(
hass, event_config, action, automation_info, platform_type="device"
)
async def async_get_triggers(hass, device_id):
"""List device triggers.
Make sure the device supports device automations and
if it does return the trigger list.
"""
zha_device = await <API key>(hass, device_id)
if not zha_device.<API key>:
return
triggers = []
for trigger, subtype in zha_device.<API key>.keys():
triggers.append(
{
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_PLATFORM: DEVICE,
CONF_TYPE: trigger,
CONF_SUBTYPE: subtype,
}
)
return triggers
|
$(document).ready(
function()
{
var $roles = $(".role_change");
$roles.each(
function()
{
var str = $(this).find("input").val();
var en_role_index = getRoleIndex(str,"EN");
var cn_role_str = indexToRole(en_role_index,"CN");
$(this).find("span").append(cn_role_str);
}
);
}
);
|
package elastic
import (
"fmt"
"net/url"
"strings"
"golang.org/x/net/context"
"gopkg.in/olivere/elastic.v5/uritemplates"
)
// <API key> allows to delete existing indices.
// for details.
type <API key> struct {
client *Client
pretty bool
index []string
timeout string
masterTimeout string
}
// <API key> creates and initializes a new <API key>.
func <API key>(client *Client) *<API key> {
return &<API key>{
client: client,
index: make([]string, 0),
}
}
// Index adds the list of indices to delete.
// Use `_all` or `*` string to delete all indices.
func (s *<API key>) Index(index []string) *<API key> {
s.index = index
return s
}
// Timeout is an explicit operation timeout.
func (s *<API key>) Timeout(timeout string) *<API key> {
s.timeout = timeout
return s
}
// MasterTimeout specifies the timeout for connection to master.
func (s *<API key>) MasterTimeout(masterTimeout string) *<API key> {
s.masterTimeout = masterTimeout
return s
}
// Pretty indicates that the JSON response be indented and human readable.
func (s *<API key>) Pretty(pretty bool) *<API key> {
s.pretty = pretty
return s
}
// buildURL builds the URL for the operation.
func (s *<API key>) buildURL() (string, url.Values, error) {
// Build URL
path, err := uritemplates.Expand("/{index}", map[string]string{
"index": strings.Join(s.index, ","),
})
if err != nil {
return "", url.Values{}, err
}
// Add query string parameters
params := url.Values{}
if s.pretty {
params.Set("pretty", "1")
}
if s.timeout != "" {
params.Set("timeout", s.timeout)
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
}
return path, params, nil
}
// Validate checks if the operation is valid.
func (s *<API key>) Validate() error {
var invalid []string
if len(s.index) == 0 {
invalid = append(invalid, "Index")
}
if len(invalid) > 0 {
return fmt.Errorf("missing required fields: %v", invalid)
}
return nil
}
// Do executes the operation.
func (s *<API key>) Do(ctx context.Context) (*<API key>, error) {
// Check pre-conditions
if err := s.Validate(); err != nil {
return nil, err
}
// Get URL for request
path, params, err := s.buildURL()
if err != nil {
return nil, err
}
// Get HTTP response
res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil)
if err != nil {
return nil, err
}
// Return operation response
ret := new(<API key>)
if err := s.client.decoder.Decode(res.Body, ret); err != nil {
return nil, err
}
return ret, nil
}
// -- Result of a delete index request.
// <API key> is the response of <API key>.Do.
type <API key> struct {
Acknowledged bool `json:"acknowledged"`
}
|
// modification, are permitted provided that the following conditions are
// met:
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// 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.
// Google Mock - a framework for writing C++ mock classes.
// This file defines some utilities useful for implementing Google
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
#include "gmock/internal/<API key>.h"
#include <ctype.h>
#include <ostream> // NOLINT
#include <string>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
namespace internal {
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
switch (fields.size()) {
case 0:
return "";
case 1:
return fields[0];
default:
std::string result = "(" + fields[0];
for (size_t i = 1; i < fields.size(); i++) {
result += ", ";
result += fields[i];
}
result += ")";
return result;
}
}
// Converts an identifier name to a space-separated list of lower-case
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word. For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string <API key>(const char* id_name) {
std::string result;
char prev_char = '\0';
for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
// We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && result != "")
result += ' ';
result += ToLower(*p);
}
}
return result;
}
// This class reports Google Mock failures as Google Test failures. A
// user can define another class in a similar fashion if they intend to
// use Google Mock with a testing framework other than Google Test.
class <API key> : public <API key> {
public:
virtual void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) {
AssertHelper(type == kFatal ?
TestPartResult::kFatalFailure :
TestPartResult::kNonFatalFailure,
file,
line,
message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
}
};
// Returns the global failure reporter. Will create a
// <API key> and return it the first time called.
GTEST_API_ <API key>* GetFailureReporter() {
// Points to the global failure reporter used by Google Mock. gcc
// guarantees that the following use of failure_reporter is
// thread-safe. We may need to add additional synchronization to
// protect failure_reporter if we port Google Mock to other
// compilers.
static <API key>* const failure_reporter =
new <API key>();
return failure_reporter;
}
// Protects global resources (stdout in particular) used by Log().
static <API key>(g_log_mutex);
// Returns true iff a log with the given severity is visible according
// to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
// Always show the log if --gmock_verbose=info.
return true;
} else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
// Always hide it if --gmock_verbose=error.
return false;
} else {
// If --gmock_verbose is neither "info" nor "error", we treat it
// as "warning" (its default value).
return severity == kWarning;
}
}
// Prints the given message to stdout iff 'severity' >= the level
// specified by the --gmock_verbose flag. If <API key> >=
// 0, also prints the stack trace excluding the top
// <API key> frames. In opt mode, any positive
// <API key> is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int <API key>) {
if (!LogIsVisible(severity))
return;
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);
// "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
// macro.
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
std::cout << "\nGMOCK WARNING:";
}
// Pre-pends a new-line to message if it doesn't start with one.
if (message.empty() || message[0] != '\n') {
std::cout << "\n";
}
std::cout << message;
if (<API key> >= 0) {
#ifdef NDEBUG
// In opt mode, we have to be conservative and skip no stack frame.
const int actual_to_skip = 0;
#else
// In dbg mode, we can do what the caller tell us to do (plus one
// for skipping this function's stack frame).
const int actual_to_skip = <API key> + 1;
#endif // NDEBUG
// Appends a new-line to message if it doesn't end with one.
if (!message.empty() && *message.rbegin() != '\n') {
std::cout << "\n";
}
std::cout << "Stack trace:\n"
<< ::testing::internal::<API key>(
::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
internal::Assert(
false, file, line,
"You are using DoDefault() inside a composite action like "
"DoAll() or WithArgs(). This is not supported for technical "
"reasons. Please instead spell out the default action, or "
"assign the default action to an Action variable and use "
"the variable in various places.");
}
} // namespace internal
} // namespace testing
|
<div class="l-wrapper">
<div class="l-btn-group">
<button *ngFor="let tab of tabList" [class.active]="isActive(tab.key)" (click)="onClickTab(tab.key)">
{{tab.display}}
</button>
<button (click)="openDetailView()">Mixed View <i class="fas <API key>" aria-hidden="true"></i></button>
<button class="l-log-info" (click)="openLogView()" [class.disabled]="!hasInfo()" *ngIf="hasLogView()">{{<API key>.logButtonName}} <i [ngClass]="getLogIcon()" aria-hidden="true"></i></button>
</div>
<span class="l-transaction-state" [hidden]="!hasState()" [ngClass]="getStateClass()"><i class="fas fa-th-list"></i> {{<API key>?.completeState}}</span>
</div>
|
<!doctype html>
<html xmlns="http:
<head>
<title>Halogen Example - Todo list</title>
<style>
body {
font-family: sans-serif;
max-width: 570px;
margin: auto;
}
ul {
list-style: none;
padding: 0;
}
li {
margin-bottom: 5px;
}
input, button {
font-family: sans-serif;
font-size: 14px;
}
input[type=text] {
width: 500px;
margin: 0px 4px;
}
</style>
</head>
<body>
<script src="example.js"></script>
</body>
</html>
|
<?php
class attachment {
var $contentid;
var $module;
var $catid;
var $attachments;
var $field;
var $imageexts = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
var $uploadedfiles = array();
var $downloadedfiles = array();
var $error;
var $upload_root;
var $siteid;
var $site = array();
function __construct($module='', $catid = 0,$siteid = 0,$upload_dir = '') {
$this->catid = intval($catid);
$this->siteid = intval($siteid)== 0 ? 1 : intval($siteid);
$this->module = $module ? $module : 'content';
pc_base::load_sys_func('dir');
pc_base::load_sys_class('image','','0');
$this->upload_root = pc_base::load_config('system','upload_path');
$this->upload_func = 'copy';
$this->upload_dir = $upload_dir;
}
/**
*
* @param $field
* @param $alowexts
* @param $maxsize
* @param $overwrite
* @param $thumb_setting
* @param $watermark_enable
*/
function upload($field, $alowexts = '', $maxsize = 0, $overwrite = 0,$thumb_setting = array(), $watermark_enable = 1) {
if(!isset($_FILES[$field])) {
$this->error = UPLOAD_ERR_OK;
return false;
}
if(empty($alowexts) || $alowexts == '') {
$site_setting = $this->_get_site_setting($this->siteid);
$alowexts = $site_setting['upload_allowext'];
}
$fn = $_GET['CKEditorFuncNum'] ? $_GET['CKEditorFuncNum'] : '1';
$this->field = $field;
$this->savepath = $this->upload_root.$this->upload_dir.date('Y/md/');
$this->alowexts = $alowexts;
$this->maxsize = $maxsize;
$this->overwrite = $overwrite;
$uploadfiles = array();
$description = isset($GLOBALS[$field.'_description']) ? $GLOBALS[$field.'_description'] : array();
if(is_array($_FILES[$field]['error'])) {
$this->uploads = count($_FILES[$field]['error']);
foreach($_FILES[$field]['error'] as $key => $error) {
if($error === UPLOAD_ERR_NO_FILE) continue;
if($error !== UPLOAD_ERR_OK) {
$this->error = $error;
return false;
}
$uploadfiles[$key] = array('tmp_name' => $_FILES[$field]['tmp_name'][$key], 'name' => $_FILES[$field]['name'][$key], 'type' => $_FILES[$field]['type'][$key], 'size' => $_FILES[$field]['size'][$key], 'error' => $_FILES[$field]['error'][$key], 'description'=>$description[$key],'fn'=>$fn);
}
} else {
$this->uploads = 1;
if(!$description) $description = '';
$uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description'=>$description,'fn'=>$fn);
}
if(!dir_create($this->savepath)) {
$this->error = '8';
return false;
}
if(!is_dir($this->savepath)) {
$this->error = '8';
return false;
}
@chmod($this->savepath, 0777);
if(!is_writeable($this->savepath)) {
$this->error = '9';
return false;
}
if(!$this->is_allow_upload()) {
$this->error = '13';
return false;
}
$aids = array();
foreach($uploadfiles as $k=>$file) {
$fileext = fileext($file['name']);
if($file['error'] != 0) {
$this->error = $file['error'];
return false;
}
if(!preg_match("/^(".$this->alowexts.")$/", $fileext)) {
$this->error = '10';
return false;
}
if($this->maxsize && $file['size'] > $this->maxsize) {
$this->error = '11';
return false;
}
if(!$this->isuploadedfile($file['tmp_name'])) {
$this->error = '12';
return false;
}
$temp_filename = $this->getname($fileext);
$savefile = $this->savepath.$temp_filename;
$savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);
$filepath = preg_replace(new_addslashes("|^".$this->upload_root."|"), "", $savefile);
if(!$this->overwrite && file_exists($savefile)) continue;
$upload_func = $this->upload_func;
if(@$upload_func($file['tmp_name'], $savefile)) {
$this->uploadeds++;
@chmod($savefile, 0644);
@unlink($file['tmp_name']);
$file['name'] = iconv("utf-8",CHARSET,$file['name']);
$file['name'] = safe_replace($file['name']);
$uploadedfile = array('filename'=>$file['name'], 'filepath'=>$filepath, 'filesize'=>$file['size'], 'fileext'=>$fileext, 'fn'=>$file['fn']);
$thumb_enable = is_array($thumb_setting) && ($thumb_setting[0] > 0 || $thumb_setting[1] > 0 ) ? 1 : 0;
$image = new image($thumb_enable,$this->siteid);
if($thumb_enable) {
$image->thumb($savefile,'',$thumb_setting[0],$thumb_setting[1]);
}
if($watermark_enable) {
$image->watermark($savefile, $savefile);
}
$aids[] = $this->add($uploadedfile);
}
}
return $aids;
}
/**
*
* Enter description here ...
* @param $field
* @param $value
* @param $watermark
* @param $ext
* @param $absurl
* @param $basehref
*/
function download($field, $value,$watermark = '0',$ext = 'gif|jpg|jpeg|bmp|png', $absurl = '', $basehref = '')
{
global $image_d;
$this->att_db = pc_base::load_model('attachment_model');
$upload_url = pc_base::load_config('system','upload_url');
$this->field = $field;
$dir = date('Y/md/');
$uploadpath = $upload_url.$dir;
$uploaddir = $this->upload_root.$dir;
$string = new_stripslashes($value);
if(!preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $string, $matches)) return $value;
$remotefileurls = array();
foreach($matches[3] as $matche)
{
if(strpos($matche, ':
dir_create($uploaddir);
$remotefileurls[$matche] = $this->fillurl($matche, $absurl, $basehref);
}
unset($matches, $string);
$remotefileurls = array_unique($remotefileurls);
$oldpath = $newpath = array();
foreach($remotefileurls as $k=>$file) {
if(strpos($file, ':
$filename = fileext($file);
$file_name = basename($file);
$filename = $this->getname($filename);
$newfile = $uploaddir.$filename;
$upload_func = $this->upload_func;
if($upload_func($file, $newfile)) {
$oldpath[] = $k;
$GLOBALS['downloadfiles'][] = $newpath[] = $uploadpath.$filename;
@chmod($newfile, 0777);
$fileext = fileext($filename);
if($watermark){
watermark($newfile, $newfile,$this->siteid);
}
$filepath = $dir.$filename;
$downloadedfile = array('filename'=>$filename, 'filepath'=>$filepath, 'filesize'=>filesize($newfile), 'fileext'=>$fileext);
$aid = $this->add($downloadedfile);
$this->downloadedfiles[$aid] = $filepath;
}
}
return str_replace($oldpath, $newpath, $value);
}
/**
*
* @param $where sql
*/
function delete($where) {
$this->att_db = pc_base::load_model('attachment_model');
$result = $this->att_db->select($where);
foreach($result as $r) {
$image = $this->upload_root.$r['filepath'];
@unlink($image);
/**
*
* @param $uploadedfile
*/
function add($uploadedfile) {
$this->att_db = pc_base::load_model('attachment_model');
$uploadedfile['module'] = $this->module;
$uploadedfile['catid'] = $this->catid;
$uploadedfile['siteid'] = $this->siteid;
$uploadedfile['userid'] = $this->userid;
$uploadedfile['uploadtime'] = SYS_TIME;
$uploadedfile['uploadip'] = ip();
$uploadedfile['status'] = pc_base::load_config('system','attachment_stat') ? 0 : 1;
$uploadedfile['authcode'] = md5($uploadedfile['filepath']);
$uploadedfile['filename'] = strlen($uploadedfile['filename'])>49 ? $this->getname($uploadedfile['fileext']) : $uploadedfile['filename'];
$uploadedfile['isimage'] = in_array($uploadedfile['fileext'], $this->imageexts) ? 1 : 0;
$aid = $this->att_db->api_add($uploadedfile);
$this->uploadedfiles[] = $uploadedfile;
return $aid;
}
function set_userid($userid) {
$this->userid = $userid;
}
/**
* ..
* @param $image
*/
function get_thumb($image){
return str_replace('.', '_thumb.', $image);
}
/**
*
* @param $fileext
*/
function getname($fileext){
return date('Ymdhis').rand(100, 999).'.'.$fileext;
}
/**
*
* @param $filesize
*/
function size($filesize) {
if($filesize >= 1073741824) {
$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
} elseif($filesize >= 1048576) {
$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
} elseif($filesize >= 1024) {
$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
} else {
$filesize = $filesize . ' Bytes';
}
return $filesize;
}
/**
* HTTP POST
*
* @param string $file
* @return bool HTTP POST TRUE
*/
function isuploadedfile($file) {
return is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file));
}
/**
*
*
* @param string $surl
* @param string $absurl
* @param string $basehref
* @return string
*/
function fillurl($surl, $absurl, $basehref = '') {
if($basehref != '') {
$preurl = strtolower(substr($surl,0,6));
if($preurl=='http:
return $surl;
else
return $basehref.'/'.$surl;
}
$i = 0;
$dstr = '';
$pstr = '';
$okurl = '';
$pathStep = 0;
$surl = trim($surl);
if($surl=='') return '';
$urls = @parse_url(SITE_URL);
$HomeUrl = $urls['host'];
$BaseUrlPath = $HomeUrl.$urls['path'];
$BaseUrlPath = preg_replace("/\/([^\/]*)\.(.*)$/",'/',$BaseUrlPath);
$BaseUrlPath = preg_replace("/\/$/",'',$BaseUrlPath);
$pos = strpos($surl,'
if($pos>0) $surl = substr($surl,0,$pos);
if($surl[0]=='/') {
$okurl = 'http://'.$HomeUrl.'/'.$surl;
} elseif($surl[0] == '.') {
if(strlen($surl)<=2) return '';
elseif($surl[0]=='/') {
$okurl = 'http://'.$BaseUrlPath.'/'.substr($surl,2,strlen($surl)-2);
} else {
$urls = explode('/',$surl);
foreach($urls as $u) {
if($u=="..") $pathStep++;
else if($i<count($urls)-1) $dstr .= $urls[$i].'/';
else $dstr .= $urls[$i];
$i++;
}
$urls = explode('/', $BaseUrlPath);
if(count($urls) <= $pathStep)
return '';
else {
$pstr = 'http:
for($i=0;$i<count($urls)-$pathStep;$i++) {
$pstr .= $urls[$i].'/';
}
$okurl = $pstr.$dstr;
}
}
} else {
$preurl = strtolower(substr($surl,0,6));
if(strlen($surl)<7)
$okurl = 'http://'.$BaseUrlPath.'/'.$surl;
elseif($preurl=="http:/"||$preurl=='ftp://' ||$preurl=='mms://' || $preurl=="rtsp://" || $preurl=='thunde' || $preurl=='emule:'|| $preurl=='ed2k:/')
$okurl = $surl;
else
$okurl = 'http://'.$BaseUrlPath.'/'.$surl;
}
$preurl = strtolower(substr($okurl,0,6));
if($preurl=='ftp://' || $preurl=='mms://' || $preurl=='rtsp://' || $preurl=='thunde' || $preurl=='emule:'|| $preurl=='ed2k:/') {
return $okurl;
} else {
$okurl = preg_replace('/^(http:\/\/)/i','',$okurl);
$okurl = preg_replace('/\/{1,}/i','/',$okurl);
return 'http://'.$okurl;
}
}
function is_allow_upload() {
if($_groupid == 1) return true;
$starttime = SYS_TIME-86400;
$site_setting = $this->_get_site_setting($this->siteid);
return ($uploads < $site_setting['upload_maxsize']);
}
function error() {
$UPLOAD_ERROR = array(
0 => L('att_upload_succ'),
1 => L('<API key>'),
2 => L('<API key>'),
3 => L('<API key>'),
4 => L('att_upload_nofile'),
5 => '',
6 => L('att_upload_notemp'),
7 => L('att_upload_temp_w_f'),
8 => L('<API key>'),
9 => L('<API key>'),
10 => L('<API key>'),
11 => L('<API key>'),
12 => L('<API key>'),
13 => L('<API key>'),
);
return iconv(CHARSET,"utf-8",$UPLOAD_ERROR[$this->error]);
}
/**
* ck
* @param $fn
* @param $fileurl
* @param $message
*/
function mkhtml($fn,$fileurl,$message) {
$str='<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$fn.', \''.$fileurl.'\', \''.$message.'\');</script>';
exit($str);
}
/**
* flash
* @param $id
*/
function uploaderror($id = 0) {
file_put_contents(PHPCMS_PATH.'xxx.txt', $id);
}
/**
*
* @param $siteid id
*/
private function _get_site_setting($siteid) {
$siteinfo = getcache('sitelist', 'commons');
return string2array($siteinfo[$siteid]['setting']);
}
}
?>
|
/*
* WARNING! DO NOT EDIT THIS FILE DIRECTLY!
*
* This file was generated automatically and any changes may be lost.
*/
#ifndef <API key>
#define <API key>
#include "regs.h"
/*
* MK70F12 CMP
*
* High-Speed Comparator (CMP), Voltage Reference (VREF) Digital-to-Analog Converter (DAC), and Analog Mux (ANMUX)
*
* Registers defined in this header file:
* - HW_CMP_CR0 - CMP Control Register 0
* - HW_CMP_CR1 - CMP Control Register 1
* - HW_CMP_FPR - CMP Filter Period Register
* - HW_CMP_SCR - CMP Status and Control Register
* - HW_CMP_DACCR - DAC Control Register
* - HW_CMP_MUXCR - MUX Control Register
*
* - hw_cmp_t - Struct containing all module registers.
*/
//! @name Module base addresses
#ifndef REGS_CMP_BASE
#define <API key> (4U) //!< Number of instances of the CMP module.
#define HW_CMP0 (0U) //!< Instance number for CMP0.
#define HW_CMP1 (1U) //!< Instance number for CMP1.
#define HW_CMP2 (2U) //!< Instance number for CMP2.
#define HW_CMP3 (3U) //!< Instance number for CMP3.
#define REGS_CMP0_BASE (0x40073000U) //!< Base address for CMP0.
#define REGS_CMP1_BASE (0x40073008U) //!< Base address for CMP1.
#define REGS_CMP2_BASE (0x40073010U) //!< Base address for CMP2.
#define REGS_CMP3_BASE (0x40073018U) //!< Base address for CMP3.
//! @brief Table of base addresses for CMP instances.
static const uint32_t <API key>[] = {
REGS_CMP0_BASE,
REGS_CMP1_BASE,
REGS_CMP2_BASE,
REGS_CMP3_BASE,
};
//! @brief Get the base address of CMP by instance number.
//! @param x CMP instance number, from 0 through 3.
#define REGS_CMP_BASE(x) (<API key>[(x)])
//! @brief Get the instance number given a base address.
//! @param b Base address for an instance of CMP.
#define REGS_CMP_INSTANCE(b) ((b) == REGS_CMP0_BASE ? HW_CMP0 : (b) == REGS_CMP1_BASE ? HW_CMP1 : (b) == REGS_CMP2_BASE ? HW_CMP2 : (b) == REGS_CMP3_BASE ? HW_CMP3 : 0)
#endif
// HW_CMP_CR0 - CMP Control Register 0
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_CMP_CR0 - CMP Control Register 0 (RW)
*
* Reset value: 0x00U
*/
typedef union _hw_cmp_cr0
{
uint8_t U;
struct <API key>
{
uint8_t HYSTCTR : 2; //!< [1:0] Comparator hard block hysteresis
//! control
uint8_t RESERVED0 : 2;
uint8_t FILTER_CNT : 3; //!< [6:4] Filter Sample Count
uint8_t RESERVED1 : 1;
} B;
} hw_cmp_cr0_t;
#endif
/*!
* @name Constants and macros for entire CMP_CR0 register
*/
#define HW_CMP_CR0_ADDR(x) (REGS_CMP_BASE(x) + 0x0U)
#ifndef __LANGUAGE_ASM__
#define HW_CMP_CR0(x) (*(__IO hw_cmp_cr0_t *) HW_CMP_CR0_ADDR(x))
#define HW_CMP_CR0_RD(x) (HW_CMP_CR0(x).U)
#define HW_CMP_CR0_WR(x, v) (HW_CMP_CR0(x).U = (v))
#define HW_CMP_CR0_SET(x, v) (HW_CMP_CR0_WR(x, HW_CMP_CR0_RD(x) | (v)))
#define HW_CMP_CR0_CLR(x, v) (HW_CMP_CR0_WR(x, HW_CMP_CR0_RD(x) & ~(v)))
#define HW_CMP_CR0_TOG(x, v) (HW_CMP_CR0_WR(x, HW_CMP_CR0_RD(x) ^ (v)))
#endif
/*
* Constants & macros for individual CMP_CR0 bitfields
*/
/*!
* @name Register CMP_CR0, field HYSTCTR[1:0] (RW)
*
* Defines the programmable hysteresis level. The hysteresis values associated
* with each level is device-specific. See the device's data sheet for the exact
* values.
*
* Values:
* - 00 - Level 0
* - 01 - Level 1
* - 10 - Level 2
* - 11 - Level 3
*/
#define BP_CMP_CR0_HYSTCTR (0U) //!< Bit position for CMP_CR0_HYSTCTR.
#define BM_CMP_CR0_HYSTCTR (0x03U) //!< Bit mask for CMP_CR0_HYSTCTR.
#define BS_CMP_CR0_HYSTCTR (2U) //!< Bit field size in bits for CMP_CR0_HYSTCTR.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR0_HYSTCTR field.
#define BR_CMP_CR0_HYSTCTR(x) (HW_CMP_CR0(x).B.HYSTCTR)
#endif
//! @brief Format value for bitfield CMP_CR0_HYSTCTR.
#define BF_CMP_CR0_HYSTCTR(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR0_HYSTCTR), uint8_t) & BM_CMP_CR0_HYSTCTR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the HYSTCTR field to a new value.
#define BW_CMP_CR0_HYSTCTR(x, v) (HW_CMP_CR0_WR(x, (HW_CMP_CR0_RD(x) & ~BM_CMP_CR0_HYSTCTR) | BF_CMP_CR0_HYSTCTR(v)))
#endif
#define <API key> (4U) //!< Bit position for CMP_CR0_FILTER_CNT.
#define <API key> (0x70U) //!< Bit mask for CMP_CR0_FILTER_CNT.
#define <API key> (3U) //!< Bit field size in bits for CMP_CR0_FILTER_CNT.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR0_FILTER_CNT field.
#define <API key>(x) (HW_CMP_CR0(x).B.FILTER_CNT)
#endif
//! @brief Format value for bitfield CMP_CR0_FILTER_CNT.
#define <API key>(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << <API key>), uint8_t) & <API key>)
#ifndef __LANGUAGE_ASM__
//! @brief Set the FILTER_CNT field to a new value.
#define <API key>(x, v) (HW_CMP_CR0_WR(x, (HW_CMP_CR0_RD(x) & ~<API key>) | <API key>(v)))
#endif
// HW_CMP_CR1 - CMP Control Register 1
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_CMP_CR1 - CMP Control Register 1 (RW)
*
* Reset value: 0x00U
*/
typedef union _hw_cmp_cr1
{
uint8_t U;
struct <API key>
{
uint8_t EN : 1; //!< [0] Comparator Module Enable
uint8_t OPE : 1; //!< [1] Comparator Output Pin Enable
uint8_t COS : 1; //!< [2] Comparator Output Select
uint8_t INV : 1; //!< [3] Comparator INVERT
uint8_t PMODE : 1; //!< [4] Power Mode Select
uint8_t RESERVED0 : 1;
uint8_t WE : 1; //!< [6] Windowing Enable
uint8_t SE : 1; //!< [7] Sample Enable
} B;
} hw_cmp_cr1_t;
#endif
/*!
* @name Constants and macros for entire CMP_CR1 register
*/
#define HW_CMP_CR1_ADDR(x) (REGS_CMP_BASE(x) + 0x1U)
#ifndef __LANGUAGE_ASM__
#define HW_CMP_CR1(x) (*(__IO hw_cmp_cr1_t *) HW_CMP_CR1_ADDR(x))
#define HW_CMP_CR1_RD(x) (HW_CMP_CR1(x).U)
#define HW_CMP_CR1_WR(x, v) (HW_CMP_CR1(x).U = (v))
#define HW_CMP_CR1_SET(x, v) (HW_CMP_CR1_WR(x, HW_CMP_CR1_RD(x) | (v)))
#define HW_CMP_CR1_CLR(x, v) (HW_CMP_CR1_WR(x, HW_CMP_CR1_RD(x) & ~(v)))
#define HW_CMP_CR1_TOG(x, v) (HW_CMP_CR1_WR(x, HW_CMP_CR1_RD(x) ^ (v)))
#endif
/*
* Constants & macros for individual CMP_CR1 bitfields
*/
/*!
* @name Register CMP_CR1, field EN[0] (RW)
*
* The EN bit enables the Analog Comparator Module. When the module is not
* enabled, it remains in the off state, and consumes no power. When you select the
* same input from analog mux to the positive and negative port, the comparator is
* disabled automatically.
*
* Values:
* - 0 - Analog Comparator disabled.
* - 1 - Analog Comparator enabled.
*/
#define BP_CMP_CR1_EN (0U) //!< Bit position for CMP_CR1_EN.
#define BM_CMP_CR1_EN (0x01U) //!< Bit mask for CMP_CR1_EN.
#define BS_CMP_CR1_EN (1U) //!< Bit field size in bits for CMP_CR1_EN.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_EN field.
#define BR_CMP_CR1_EN(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_EN))
#endif
//! @brief Format value for bitfield CMP_CR1_EN.
#define BF_CMP_CR1_EN(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_EN), uint8_t) & BM_CMP_CR1_EN)
#ifndef __LANGUAGE_ASM__
//! @brief Set the EN field to a new value.
#define BW_CMP_CR1_EN(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_EN) = (v))
#endif
/*!
* @name Register CMP_CR1, field OPE[1] (RW)
*
* Values:
* - 0 - The comparator output (CMPO) is not available on the associated CMPO
* output pin.
* - 1 - The comparator output (CMPO) is available on the associated CMPO output
* pin.
*/
#define BP_CMP_CR1_OPE (1U) //!< Bit position for CMP_CR1_OPE.
#define BM_CMP_CR1_OPE (0x02U) //!< Bit mask for CMP_CR1_OPE.
#define BS_CMP_CR1_OPE (1U) //!< Bit field size in bits for CMP_CR1_OPE.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_OPE field.
#define BR_CMP_CR1_OPE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_OPE))
#endif
//! @brief Format value for bitfield CMP_CR1_OPE.
#define BF_CMP_CR1_OPE(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_OPE), uint8_t) & BM_CMP_CR1_OPE)
#ifndef __LANGUAGE_ASM__
//! @brief Set the OPE field to a new value.
#define BW_CMP_CR1_OPE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_OPE) = (v))
#endif
/*!
* @name Register CMP_CR1, field COS[2] (RW)
*
* Values:
* - 0 - Set CMPO to equal COUT (filtered comparator output).
* - 1 - Set CMPO to equal COUTA (unfiltered comparator output).
*/
#define BP_CMP_CR1_COS (2U) //!< Bit position for CMP_CR1_COS.
#define BM_CMP_CR1_COS (0x04U) //!< Bit mask for CMP_CR1_COS.
#define BS_CMP_CR1_COS (1U) //!< Bit field size in bits for CMP_CR1_COS.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_COS field.
#define BR_CMP_CR1_COS(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_COS))
#endif
//! @brief Format value for bitfield CMP_CR1_COS.
#define BF_CMP_CR1_COS(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_COS), uint8_t) & BM_CMP_CR1_COS)
#ifndef __LANGUAGE_ASM__
//! @brief Set the COS field to a new value.
#define BW_CMP_CR1_COS(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_COS) = (v))
#endif
/*!
* @name Register CMP_CR1, field INV[3] (RW)
*
* This bit allows you to select the polarity of the analog comparator function.
* It is also driven to the COUT output (on both the device pin and as
* SCR[COUT]) when CR1[OPE]=0.
*
* Values:
* - 0 - Does not invert the comparator output.
* - 1 - Inverts the comparator output.
*/
#define BP_CMP_CR1_INV (3U) //!< Bit position for CMP_CR1_INV.
#define BM_CMP_CR1_INV (0x08U) //!< Bit mask for CMP_CR1_INV.
#define BS_CMP_CR1_INV (1U) //!< Bit field size in bits for CMP_CR1_INV.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_INV field.
#define BR_CMP_CR1_INV(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_INV))
#endif
//! @brief Format value for bitfield CMP_CR1_INV.
#define BF_CMP_CR1_INV(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_INV), uint8_t) & BM_CMP_CR1_INV)
#ifndef __LANGUAGE_ASM__
//! @brief Set the INV field to a new value.
#define BW_CMP_CR1_INV(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_INV) = (v))
#endif
/*!
* @name Register CMP_CR1, field PMODE[4] (RW)
*
* Refer to the device data sheet's CMP electrical specifications table for
* details on the impact of the modes below.
*
* Values:
* - 0 - Low Speed (LS) comparison mode selected. In this mode, CMP has slower
* output propagation delay and lower current consumption.
* - 1 - High Speed (HS) comparison mode selected. In this mode, CMP has faster
* output propagation delay and higher current consumption.
*/
#define BP_CMP_CR1_PMODE (4U) //!< Bit position for CMP_CR1_PMODE.
#define BM_CMP_CR1_PMODE (0x10U) //!< Bit mask for CMP_CR1_PMODE.
#define BS_CMP_CR1_PMODE (1U) //!< Bit field size in bits for CMP_CR1_PMODE.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_PMODE field.
#define BR_CMP_CR1_PMODE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_PMODE))
#endif
//! @brief Format value for bitfield CMP_CR1_PMODE.
#define BF_CMP_CR1_PMODE(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_PMODE), uint8_t) & BM_CMP_CR1_PMODE)
#ifndef __LANGUAGE_ASM__
//! @brief Set the PMODE field to a new value.
#define BW_CMP_CR1_PMODE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_PMODE) = (v))
#endif
/*!
* @name Register CMP_CR1, field WE[6] (RW)
*
* At any given time, either SE or WE can be set. If a write to this register
* attempts to set both, then SE is set and WE is cleared. However, avoid writing
* ones to both bit locations because this "11" case is reserved and may change in
* future implementations.
*
* Values:
* - 0 - Windowing mode not selected.
* - 1 - Windowing mode selected.
*/
#define BP_CMP_CR1_WE (6U) //!< Bit position for CMP_CR1_WE.
#define BM_CMP_CR1_WE (0x40U) //!< Bit mask for CMP_CR1_WE.
#define BS_CMP_CR1_WE (1U) //!< Bit field size in bits for CMP_CR1_WE.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_WE field.
#define BR_CMP_CR1_WE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_WE))
#endif
//! @brief Format value for bitfield CMP_CR1_WE.
#define BF_CMP_CR1_WE(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_WE), uint8_t) & BM_CMP_CR1_WE)
#ifndef __LANGUAGE_ASM__
//! @brief Set the WE field to a new value.
#define BW_CMP_CR1_WE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_WE) = (v))
#endif
/*!
* @name Register CMP_CR1, field SE[7] (RW)
*
* At any given time, either SE or WE can be set. If a write to this register
* attempts to set both, then SE is set and WE is cleared. However, avoid writing
* ones to both bit locations because this "11" case is reserved and may change in
* future implementations.
*
* Values:
* - 0 - Sampling mode not selected.
* - 1 - Sampling mode selected.
*/
#define BP_CMP_CR1_SE (7U) //!< Bit position for CMP_CR1_SE.
#define BM_CMP_CR1_SE (0x80U) //!< Bit mask for CMP_CR1_SE.
#define BS_CMP_CR1_SE (1U) //!< Bit field size in bits for CMP_CR1_SE.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_CR1_SE field.
#define BR_CMP_CR1_SE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_SE))
#endif
//! @brief Format value for bitfield CMP_CR1_SE.
#define BF_CMP_CR1_SE(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_CR1_SE), uint8_t) & BM_CMP_CR1_SE)
#ifndef __LANGUAGE_ASM__
//! @brief Set the SE field to a new value.
#define BW_CMP_CR1_SE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_SE) = (v))
#endif
// HW_CMP_FPR - CMP Filter Period Register
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_CMP_FPR - CMP Filter Period Register (RW)
*
* Reset value: 0x00U
*/
typedef union _hw_cmp_fpr
{
uint8_t U;
struct <API key>
{
uint8_t FILT_PER : 8; //!< [7:0] Filter Sample Period
} B;
} hw_cmp_fpr_t;
#endif
/*!
* @name Constants and macros for entire CMP_FPR register
*/
#define HW_CMP_FPR_ADDR(x) (REGS_CMP_BASE(x) + 0x2U)
#ifndef __LANGUAGE_ASM__
#define HW_CMP_FPR(x) (*(__IO hw_cmp_fpr_t *) HW_CMP_FPR_ADDR(x))
#define HW_CMP_FPR_RD(x) (HW_CMP_FPR(x).U)
#define HW_CMP_FPR_WR(x, v) (HW_CMP_FPR(x).U = (v))
#define HW_CMP_FPR_SET(x, v) (HW_CMP_FPR_WR(x, HW_CMP_FPR_RD(x) | (v)))
#define HW_CMP_FPR_CLR(x, v) (HW_CMP_FPR_WR(x, HW_CMP_FPR_RD(x) & ~(v)))
#define HW_CMP_FPR_TOG(x, v) (HW_CMP_FPR_WR(x, HW_CMP_FPR_RD(x) ^ (v)))
#endif
/*
* Constants & macros for individual CMP_FPR bitfields
*/
/*!
* @name Register CMP_FPR, field FILT_PER[7:0] (RW)
*
* When CR1[SE] is equal to zero, this field specifies the sampling period, in
* bus clock cycles, of the comparator output filter. Setting FILT_PER to 0x0
* disables the filter. Filter programming and latency details appear in the
* Functional Description. This field has no effect when CR1[SE] is equal to one. In that
* case, the external SAMPLE signal is used to determine the sampling period.
*/
#define BP_CMP_FPR_FILT_PER (0U) //!< Bit position for CMP_FPR_FILT_PER.
#define BM_CMP_FPR_FILT_PER (0xFFU) //!< Bit mask for CMP_FPR_FILT_PER.
#define BS_CMP_FPR_FILT_PER (8U) //!< Bit field size in bits for CMP_FPR_FILT_PER.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_FPR_FILT_PER field.
#define BR_CMP_FPR_FILT_PER(x) (HW_CMP_FPR(x).B.FILT_PER)
#endif
//! @brief Format value for bitfield CMP_FPR_FILT_PER.
#define BF_CMP_FPR_FILT_PER(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_FPR_FILT_PER), uint8_t) & BM_CMP_FPR_FILT_PER)
#ifndef __LANGUAGE_ASM__
//! @brief Set the FILT_PER field to a new value.
#define BW_CMP_FPR_FILT_PER(x, v) (HW_CMP_FPR_WR(x, (HW_CMP_FPR_RD(x) & ~BM_CMP_FPR_FILT_PER) | BF_CMP_FPR_FILT_PER(v)))
#endif
// HW_CMP_SCR - CMP Status and Control Register
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_CMP_SCR - CMP Status and Control Register (RW)
*
* Reset value: 0x00U
*/
typedef union _hw_cmp_scr
{
uint8_t U;
struct <API key>
{
uint8_t COUT : 1; //!< [0] Analog Comparator Output
uint8_t CFF : 1; //!< [1] Analog Comparator Flag Falling
uint8_t CFR : 1; //!< [2] Analog Comparator Flag Rising
uint8_t IEF : 1; //!< [3] Comparator Interrupt Enable Falling
uint8_t IER : 1; //!< [4] Comparator Interrupt Enable Rising
uint8_t RESERVED0 : 1;
uint8_t DMAEN : 1; //!< [6] DMA Enable Control
uint8_t RESERVED1 : 1;
} B;
} hw_cmp_scr_t;
#endif
/*!
* @name Constants and macros for entire CMP_SCR register
*/
#define HW_CMP_SCR_ADDR(x) (REGS_CMP_BASE(x) + 0x3U)
#ifndef __LANGUAGE_ASM__
#define HW_CMP_SCR(x) (*(__IO hw_cmp_scr_t *) HW_CMP_SCR_ADDR(x))
#define HW_CMP_SCR_RD(x) (HW_CMP_SCR(x).U)
#define HW_CMP_SCR_WR(x, v) (HW_CMP_SCR(x).U = (v))
#define HW_CMP_SCR_SET(x, v) (HW_CMP_SCR_WR(x, HW_CMP_SCR_RD(x) | (v)))
#define HW_CMP_SCR_CLR(x, v) (HW_CMP_SCR_WR(x, HW_CMP_SCR_RD(x) & ~(v)))
#define HW_CMP_SCR_TOG(x, v) (HW_CMP_SCR_WR(x, HW_CMP_SCR_RD(x) ^ (v)))
#endif
/*
* Constants & macros for individual CMP_SCR bitfields
*/
/*!
* @name Register CMP_SCR, field COUT[0] (RO)
*
* Reading the COUT bit will return the current value of the analog comparator
* output. The register bit is reset to zero and will read as CR1[INV] when the
* Analog Comparator module is disabled (CR1[EN] = 0). Writes to this bit are
* ignored.
*/
#define BP_CMP_SCR_COUT (0U) //!< Bit position for CMP_SCR_COUT.
#define BM_CMP_SCR_COUT (0x01U) //!< Bit mask for CMP_SCR_COUT.
#define BS_CMP_SCR_COUT (1U) //!< Bit field size in bits for CMP_SCR_COUT.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_SCR_COUT field.
#define BR_CMP_SCR_COUT(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_COUT))
#endif
/*!
* @name Register CMP_SCR, field CFF[1] (W1C)
*
* During normal operation, the CFF bit is set when a falling edge on COUT has
* been detected. The CFF bit is cleared by writing a logic one to the bit. During
* Stop modes, CFF is level senstive.
*
* Values:
* - 0 - Falling edge on COUT has not been detected.
* - 1 - Falling edge on COUT has occurred.
*/
#define BP_CMP_SCR_CFF (1U) //!< Bit position for CMP_SCR_CFF.
#define BM_CMP_SCR_CFF (0x02U) //!< Bit mask for CMP_SCR_CFF.
#define BS_CMP_SCR_CFF (1U) //!< Bit field size in bits for CMP_SCR_CFF.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_SCR_CFF field.
#define BR_CMP_SCR_CFF(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFF))
#endif
//! @brief Format value for bitfield CMP_SCR_CFF.
#define BF_CMP_SCR_CFF(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_SCR_CFF), uint8_t) & BM_CMP_SCR_CFF)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CFF field to a new value.
#define BW_CMP_SCR_CFF(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFF) = (v))
#endif
/*!
* @name Register CMP_SCR, field CFR[2] (W1C)
*
* During normal operation, the CFR bit is set when a rising edge on COUT has
* been detected. The CFR bit is cleared by writing a logic one to the bit. During
* Stop modes, CFR is level sensitive.
*
* Values:
* - 0 - Rising edge on COUT has not been detected.
* - 1 - Rising edge on COUT has occurred.
*/
#define BP_CMP_SCR_CFR (2U) //!< Bit position for CMP_SCR_CFR.
#define BM_CMP_SCR_CFR (0x04U) //!< Bit mask for CMP_SCR_CFR.
#define BS_CMP_SCR_CFR (1U) //!< Bit field size in bits for CMP_SCR_CFR.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_SCR_CFR field.
#define BR_CMP_SCR_CFR(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFR))
#endif
//! @brief Format value for bitfield CMP_SCR_CFR.
#define BF_CMP_SCR_CFR(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_SCR_CFR), uint8_t) & BM_CMP_SCR_CFR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CFR field to a new value.
#define BW_CMP_SCR_CFR(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFR) = (v))
#endif
/*!
* @name Register CMP_SCR, field IEF[3] (RW)
*
* The IEF bit enables the CFF interrupt from the CMP. When this bit is set, an
* interrupt will be asserted when the CFF bit is set.
*
* Values:
* - 0 - Interrupt disabled.
* - 1 - Interrupt enabled.
*/
#define BP_CMP_SCR_IEF (3U) //!< Bit position for CMP_SCR_IEF.
#define BM_CMP_SCR_IEF (0x08U) //!< Bit mask for CMP_SCR_IEF.
#define BS_CMP_SCR_IEF (1U) //!< Bit field size in bits for CMP_SCR_IEF.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_SCR_IEF field.
#define BR_CMP_SCR_IEF(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IEF))
#endif
//! @brief Format value for bitfield CMP_SCR_IEF.
#define BF_CMP_SCR_IEF(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_SCR_IEF), uint8_t) & BM_CMP_SCR_IEF)
#ifndef __LANGUAGE_ASM__
//! @brief Set the IEF field to a new value.
#define BW_CMP_SCR_IEF(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IEF) = (v))
#endif
/*!
* @name Register CMP_SCR, field IER[4] (RW)
*
* The IER bit enables the CFR interrupt from the CMP. When this bit is set, an
* interrupt will be asserted when the CFR bit is set.
*
* Values:
* - 0 - Interrupt disabled.
* - 1 - Interrupt enabled.
*/
#define BP_CMP_SCR_IER (4U) //!< Bit position for CMP_SCR_IER.
#define BM_CMP_SCR_IER (0x10U) //!< Bit mask for CMP_SCR_IER.
#define BS_CMP_SCR_IER (1U) //!< Bit field size in bits for CMP_SCR_IER.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_SCR_IER field.
#define BR_CMP_SCR_IER(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IER))
#endif
//! @brief Format value for bitfield CMP_SCR_IER.
#define BF_CMP_SCR_IER(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_SCR_IER), uint8_t) & BM_CMP_SCR_IER)
#ifndef __LANGUAGE_ASM__
//! @brief Set the IER field to a new value.
#define BW_CMP_SCR_IER(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IER) = (v))
#endif
/*!
* @name Register CMP_SCR, field DMAEN[6] (RW)
*
* The DMAEN bit enables the DMA transfer triggered from the CMP module. When
* this bit is set, a DMA request is asserted when the CFR or CFF bit is set.
*
* Values:
* - 0 - DMA disabled.
* - 1 - DMA enabled.
*/
#define BP_CMP_SCR_DMAEN (6U) //!< Bit position for CMP_SCR_DMAEN.
#define BM_CMP_SCR_DMAEN (0x40U) //!< Bit mask for CMP_SCR_DMAEN.
#define BS_CMP_SCR_DMAEN (1U) //!< Bit field size in bits for CMP_SCR_DMAEN.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_SCR_DMAEN field.
#define BR_CMP_SCR_DMAEN(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_DMAEN))
#endif
//! @brief Format value for bitfield CMP_SCR_DMAEN.
#define BF_CMP_SCR_DMAEN(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_SCR_DMAEN), uint8_t) & BM_CMP_SCR_DMAEN)
#ifndef __LANGUAGE_ASM__
//! @brief Set the DMAEN field to a new value.
#define BW_CMP_SCR_DMAEN(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_DMAEN) = (v))
#endif
// HW_CMP_DACCR - DAC Control Register
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_CMP_DACCR - DAC Control Register (RW)
*
* Reset value: 0x00U
*/
typedef union _hw_cmp_daccr
{
uint8_t U;
struct <API key>
{
uint8_t VOSEL : 6; //!< [5:0] DAC Output Voltage Select
uint8_t VRSEL : 1; //!< [6] Supply Voltage Reference Source Select
uint8_t DACEN : 1; //!< [7] DAC Enable
} B;
} hw_cmp_daccr_t;
#endif
/*!
* @name Constants and macros for entire CMP_DACCR register
*/
#define HW_CMP_DACCR_ADDR(x) (REGS_CMP_BASE(x) + 0x4U)
#ifndef __LANGUAGE_ASM__
#define HW_CMP_DACCR(x) (*(__IO hw_cmp_daccr_t *) HW_CMP_DACCR_ADDR(x))
#define HW_CMP_DACCR_RD(x) (HW_CMP_DACCR(x).U)
#define HW_CMP_DACCR_WR(x, v) (HW_CMP_DACCR(x).U = (v))
#define HW_CMP_DACCR_SET(x, v) (HW_CMP_DACCR_WR(x, HW_CMP_DACCR_RD(x) | (v)))
#define HW_CMP_DACCR_CLR(x, v) (HW_CMP_DACCR_WR(x, HW_CMP_DACCR_RD(x) & ~(v)))
#define HW_CMP_DACCR_TOG(x, v) (HW_CMP_DACCR_WR(x, HW_CMP_DACCR_RD(x) ^ (v)))
#endif
/*
* Constants & macros for individual CMP_DACCR bitfields
*/
/*!
* @name Register CMP_DACCR, field VOSEL[5:0] (RW)
*
* This bit selects an output voltage from one of 64 distinct levels. DACO =
* (Vin/64) * (VOSEL[5:0] + 1), so the DACO range is from Vin/64 to Vin.
*/
#define BP_CMP_DACCR_VOSEL (0U) //!< Bit position for CMP_DACCR_VOSEL.
#define BM_CMP_DACCR_VOSEL (0x3FU) //!< Bit mask for CMP_DACCR_VOSEL.
#define BS_CMP_DACCR_VOSEL (6U) //!< Bit field size in bits for CMP_DACCR_VOSEL.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_DACCR_VOSEL field.
#define BR_CMP_DACCR_VOSEL(x) (HW_CMP_DACCR(x).B.VOSEL)
#endif
//! @brief Format value for bitfield CMP_DACCR_VOSEL.
#define BF_CMP_DACCR_VOSEL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_DACCR_VOSEL), uint8_t) & BM_CMP_DACCR_VOSEL)
#ifndef __LANGUAGE_ASM__
//! @brief Set the VOSEL field to a new value.
#define BW_CMP_DACCR_VOSEL(x, v) (HW_CMP_DACCR_WR(x, (HW_CMP_DACCR_RD(x) & ~BM_CMP_DACCR_VOSEL) | BF_CMP_DACCR_VOSEL(v)))
#endif
/*!
* @name Register CMP_DACCR, field VRSEL[6] (RW)
*
* Values:
* - 0 - Vin1 is selected as resistor ladder network supply reference Vin.
* - 1 - Vin2 is selected as resistor ladder network supply reference Vin.
*/
#define BP_CMP_DACCR_VRSEL (6U) //!< Bit position for CMP_DACCR_VRSEL.
#define BM_CMP_DACCR_VRSEL (0x40U) //!< Bit mask for CMP_DACCR_VRSEL.
#define BS_CMP_DACCR_VRSEL (1U) //!< Bit field size in bits for CMP_DACCR_VRSEL.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_DACCR_VRSEL field.
#define BR_CMP_DACCR_VRSEL(x) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_VRSEL))
#endif
//! @brief Format value for bitfield CMP_DACCR_VRSEL.
#define BF_CMP_DACCR_VRSEL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_DACCR_VRSEL), uint8_t) & BM_CMP_DACCR_VRSEL)
#ifndef __LANGUAGE_ASM__
//! @brief Set the VRSEL field to a new value.
#define BW_CMP_DACCR_VRSEL(x, v) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_VRSEL) = (v))
#endif
/*!
* @name Register CMP_DACCR, field DACEN[7] (RW)
*
* This bit is used to enable the DAC. When the DAC is disabled, it is powered
* down to conserve power.
*
* Values:
* - 0 - DAC is disabled.
* - 1 - DAC is enabled.
*/
#define BP_CMP_DACCR_DACEN (7U) //!< Bit position for CMP_DACCR_DACEN.
#define BM_CMP_DACCR_DACEN (0x80U) //!< Bit mask for CMP_DACCR_DACEN.
#define BS_CMP_DACCR_DACEN (1U) //!< Bit field size in bits for CMP_DACCR_DACEN.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_DACCR_DACEN field.
#define BR_CMP_DACCR_DACEN(x) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_DACEN))
#endif
//! @brief Format value for bitfield CMP_DACCR_DACEN.
#define BF_CMP_DACCR_DACEN(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_DACCR_DACEN), uint8_t) & BM_CMP_DACCR_DACEN)
#ifndef __LANGUAGE_ASM__
//! @brief Set the DACEN field to a new value.
#define BW_CMP_DACCR_DACEN(x, v) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_DACEN) = (v))
#endif
// HW_CMP_MUXCR - MUX Control Register
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_CMP_MUXCR - MUX Control Register (RW)
*
* Reset value: 0x00U
*/
typedef union _hw_cmp_muxcr
{
uint8_t U;
struct <API key>
{
uint8_t MSEL : 3; //!< [2:0] Minus Input MUX Control
uint8_t PSEL : 3; //!< [5:3] Plus Input MUX Control
uint8_t RESERVED0 : 2;
} B;
} hw_cmp_muxcr_t;
#endif
/*!
* @name Constants and macros for entire CMP_MUXCR register
*/
#define HW_CMP_MUXCR_ADDR(x) (REGS_CMP_BASE(x) + 0x5U)
#ifndef __LANGUAGE_ASM__
#define HW_CMP_MUXCR(x) (*(__IO hw_cmp_muxcr_t *) HW_CMP_MUXCR_ADDR(x))
#define HW_CMP_MUXCR_RD(x) (HW_CMP_MUXCR(x).U)
#define HW_CMP_MUXCR_WR(x, v) (HW_CMP_MUXCR(x).U = (v))
#define HW_CMP_MUXCR_SET(x, v) (HW_CMP_MUXCR_WR(x, HW_CMP_MUXCR_RD(x) | (v)))
#define HW_CMP_MUXCR_CLR(x, v) (HW_CMP_MUXCR_WR(x, HW_CMP_MUXCR_RD(x) & ~(v)))
#define HW_CMP_MUXCR_TOG(x, v) (HW_CMP_MUXCR_WR(x, HW_CMP_MUXCR_RD(x) ^ (v)))
#endif
/*
* Constants & macros for individual CMP_MUXCR bitfields
*/
/*!
* @name Register CMP_MUXCR, field MSEL[2:0] (RW)
*
* Determines which input is selected for the minus input of the comparator. For
* INx inputs, refer to CMP, DAC and ANMUX Blocks Diagram. When an inappropriate
* operation selects the same input for both MUXes, the comparator automatically
* shuts down to prevent itself from becoming a noise generator.
*
* Values:
* - 000 - IN0
* - 001 - IN1
* - 010 - IN2
* - 011 - IN3
* - 100 - IN4
* - 101 - IN5
* - 110 - IN6
* - 111 - IN7
*/
#define BP_CMP_MUXCR_MSEL (0U) //!< Bit position for CMP_MUXCR_MSEL.
#define BM_CMP_MUXCR_MSEL (0x07U) //!< Bit mask for CMP_MUXCR_MSEL.
#define BS_CMP_MUXCR_MSEL (3U) //!< Bit field size in bits for CMP_MUXCR_MSEL.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_MUXCR_MSEL field.
#define BR_CMP_MUXCR_MSEL(x) (HW_CMP_MUXCR(x).B.MSEL)
#endif
//! @brief Format value for bitfield CMP_MUXCR_MSEL.
#define BF_CMP_MUXCR_MSEL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_MUXCR_MSEL), uint8_t) & BM_CMP_MUXCR_MSEL)
#ifndef __LANGUAGE_ASM__
//! @brief Set the MSEL field to a new value.
#define BW_CMP_MUXCR_MSEL(x, v) (HW_CMP_MUXCR_WR(x, (HW_CMP_MUXCR_RD(x) & ~BM_CMP_MUXCR_MSEL) | BF_CMP_MUXCR_MSEL(v)))
#endif
/*!
* @name Register CMP_MUXCR, field PSEL[5:3] (RW)
*
* Determines which input is selected for the plus input of the comparator. For
* INx inputs, refer to CMP, DAC and ANMUX Blocks Diagram. When an inappropriate
* operation selects the same input for both MUXes, the comparator automatically
* shuts down to prevent itself from becoming a noise generator.
*
* Values:
* - 000 - IN0
* - 001 - IN1
* - 010 - IN2
* - 011 - IN3
* - 100 - IN4
* - 101 - IN5
* - 110 - IN6
* - 111 - IN7
*/
#define BP_CMP_MUXCR_PSEL (3U) //!< Bit position for CMP_MUXCR_PSEL.
#define BM_CMP_MUXCR_PSEL (0x38U) //!< Bit mask for CMP_MUXCR_PSEL.
#define BS_CMP_MUXCR_PSEL (3U) //!< Bit field size in bits for CMP_MUXCR_PSEL.
#ifndef __LANGUAGE_ASM__
//! @brief Read current value of the CMP_MUXCR_PSEL field.
#define BR_CMP_MUXCR_PSEL(x) (HW_CMP_MUXCR(x).B.PSEL)
#endif
//! @brief Format value for bitfield CMP_MUXCR_PSEL.
#define BF_CMP_MUXCR_PSEL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CMP_MUXCR_PSEL), uint8_t) & BM_CMP_MUXCR_PSEL)
#ifndef __LANGUAGE_ASM__
//! @brief Set the PSEL field to a new value.
#define BW_CMP_MUXCR_PSEL(x, v) (HW_CMP_MUXCR_WR(x, (HW_CMP_MUXCR_RD(x) & ~BM_CMP_MUXCR_PSEL) | BF_CMP_MUXCR_PSEL(v)))
#endif
// hw_cmp_t - module struct
/*!
* @brief All CMP module registers.
*/
#ifndef __LANGUAGE_ASM__
#pragma pack(1)
typedef struct _hw_cmp
{
__IO hw_cmp_cr0_t CR0; //!< [0x0] CMP Control Register 0
__IO hw_cmp_cr1_t CR1; //!< [0x1] CMP Control Register 1
__IO hw_cmp_fpr_t FPR; //!< [0x2] CMP Filter Period Register
__IO hw_cmp_scr_t SCR; //!< [0x3] CMP Status and Control Register
__IO hw_cmp_daccr_t DACCR; //!< [0x4] DAC Control Register
__IO hw_cmp_muxcr_t MUXCR; //!< [0x5] MUX Control Register
} hw_cmp_t;
#pragma pack()
//! @brief Macro to access all CMP registers.
//! @param x CMP instance number.
//! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct,
//! use the '&' operator, like <code>&HW_CMP(0)</code>.
#define HW_CMP(x) (*(hw_cmp_t *) REGS_CMP_BASE(x))
#endif
#endif // <API key>
// v22/130726/0.9
// EOF
|
/* $Xorg: XrmI.h,v 1.4 2001/02/09 02:03:39 xorgcvs Exp $ */
/*
* Macros to abstract out reading the file, and getting its size.
*
* You may need to redefine these for various other operating systems.
*/
#include <X11/Xos.h>
#include <sys/stat.h>
#define GetSizeOfFile(fd,size) \
{ \
struct stat status_buffer; \
if ( (fstat((fd), &status_buffer)) == -1 ) \
size = -1; \
else \
size = status_buffer.st_size; \
}
|
package org.elasticsearch.xpack.watcher.notification.email;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.SecureSetting;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.xpack.core.watcher.crypto.CryptoService;
import org.elasticsearch.xpack.watcher.notification.NotificationService;
import javax.mail.MessagingException;
import java.util.Arrays;
import java.util.List;
/**
* A component to store email credentials and handle sending email notifications.
*/
public class EmailService extends NotificationService<Account> {
private static final Setting<String> <API key> =
Setting.simpleString("xpack.notification.email.default_account", Property.Dynamic, Property.NodeScope);
private static final Setting.AffixSetting<String> SETTING_PROFILE =
Setting.affixKeySetting("xpack.notification.email.account.", "profile",
(key) -> Setting.simpleString(key, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Settings> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "email_defaults",
(key) -> Setting.groupSetting(key + ".", Property.Dynamic, Property.NodeScope));
// settings that can be configured as smtp properties
private static final Setting.AffixSetting<Boolean> SETTING_SMTP_AUTH =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.auth",
(key) -> Setting.boolSetting(key, false, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Boolean> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.starttls.enable",
(key) -> Setting.boolSetting(key, false, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Boolean> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.starttls.required",
(key) -> Setting.boolSetting(key, false, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<String> SETTING_SMTP_HOST =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.host",
(key) -> Setting.simpleString(key, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Integer> SETTING_SMTP_PORT =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.port",
(key) -> Setting.intSetting(key, 587, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<String> SETTING_SMTP_USER =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.user",
(key) -> Setting.simpleString(key, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<String> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.password",
(key) -> Setting.simpleString(key, Property.Dynamic, Property.NodeScope, Property.Filtered));
private static final Setting.AffixSetting<SecureString> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.secure_password",
(key) -> SecureSetting.secureString(key, null));
private static final Setting.AffixSetting<TimeValue> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.timeout",
(key) -> Setting.timeSetting(key, TimeValue.timeValueMinutes(2), Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<TimeValue> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.connection_timeout",
(key) -> Setting.timeSetting(key, TimeValue.timeValueMinutes(2), Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<TimeValue> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.write_timeout",
(key) -> Setting.timeSetting(key, TimeValue.timeValueMinutes(2), Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<String> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.local_address",
(key) -> Setting.simpleString(key, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<String> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.ssl.trust",
(key) -> Setting.simpleString(key, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Integer> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.local_port",
(key) -> Setting.intSetting(key, 25, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Boolean> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.send_partial",
(key) -> Setting.boolSetting(key, false, Property.Dynamic, Property.NodeScope));
private static final Setting.AffixSetting<Boolean> <API key> =
Setting.affixKeySetting("xpack.notification.email.account.", "smtp.wait_on_quit",
(key) -> Setting.boolSetting(key, true, Property.Dynamic, Property.NodeScope));
private final CryptoService cryptoService;
public EmailService(Settings settings, @Nullable CryptoService cryptoService, ClusterSettings clusterSettings) {
super(settings, "email", clusterSettings, EmailService.getSettings());
this.cryptoService = cryptoService;
// ensure logging of setting changes
clusterSettings.<API key>(<API key>, (s) -> {});
clusterSettings.<API key>(SETTING_PROFILE, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(SETTING_SMTP_AUTH, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(SETTING_SMTP_HOST, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(SETTING_SMTP_PORT, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(SETTING_SMTP_USER, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
clusterSettings.<API key>(<API key>, (s, o) -> {}, (s, o) -> {});
// do an initial load
reload(settings);
}
@Override
protected Account createAccount(String name, Settings accountSettings) {
Account.Config config = new Account.Config(name, accountSettings);
return new Account(config, cryptoService, logger);
}
public EmailSent send(Email email, Authentication auth, Profile profile, String accountName) throws MessagingException {
Account account = getAccount(accountName);
if (account == null) {
throw new <API key>("failed to send email with subject [" + email.subject() + "] via account [" + accountName
+ "]. account does not exist");
}
return send(email, auth, profile, account);
}
private EmailSent send(Email email, Authentication auth, Profile profile, Account account) throws MessagingException {
assert account != null;
try {
email = account.send(email, auth, profile);
} catch (MessagingException me) {
throw new MessagingException("failed to send email with subject [" + email.subject() + "] via account [" + account.name() +
"]", me);
}
return new EmailSent(account.name(), email);
}
public static class EmailSent {
private final String account;
private final Email email;
public EmailSent(String account, Email email) {
this.account = account;
this.email = email;
}
public String account() {
return account;
}
public Email email() {
return email;
}
}
public static List<Setting<?>> getSettings() {
return Arrays.asList(<API key>, SETTING_PROFILE, <API key>, SETTING_SMTP_AUTH, SETTING_SMTP_HOST,
<API key>, SETTING_SMTP_PORT, <API key>, SETTING_SMTP_USER, <API key>,
<API key>, <API key>, <API key>, <API key>,
<API key>, <API key>, <API key>, <API key>,
<API key>);
}
}
|
// file at the top-level directory of this distribution and at
// option. This file may not be copied, modified, or distributed
// except according to those terms.
Synchronous channels/ports
This channel implementation differs significantly from the asynchronous
implementations found next to it (oneshot/stream/share). This is an
implementation of a synchronous, bounded buffer channel.
Each channel is created with some amount of backing buffer, and sends will
*block* until buffer space becomes available. A buffer size of 0 is valid,
which means that every successful send is paired with a successful recv.
This flavor of channels defines a new `send_opt` method for channels which
is the method by which a message is sent but the task does not panic if it
cannot be delivered.
Another major difference is that send() will *always* return back the data
if it couldn't be sent. This is because it is deterministically known when
the data is received and when it is not received.
Implementation-wise, it can all be summed up with "use a mutex plus some
logic". The mutex used here is an OS native mutex, meaning that no user code
is run inside of the mutex (to prevent context switching). This
implementation shares almost all code for the buffered and unbuffered cases
of a synchronous channel. There are a few branches for the unbuffered case,
but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
Only field outside of the mutex. Just done for kicks, but mainly because
the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T: Send> Send for Packet<T> { }
unsafe impl<T: Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: usize, // capacity of this channel
A curious flag used to indicate whether a sender failed or succeeded in
blocking. This is used to transmit information back to the task that it
must dequeue its message from the buffer because it was not received.
This is only relevant in the 0-buffer case. This obviously cannot be
safely constructed, but it's guaranteed to always have a valid pointer
value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
Simple queue for threading tasks together. Nodes are stack-allocated, so
this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: usize,
size: usize,
}
#[derive(Debug)]
pub enum Failure {
Empty,
Disconnected,
}
Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T> Packet<T> {
pub fn new(cap: usize) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: (0..cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if !guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 && !waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap != 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
// select implementation
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
// Buffer, a simple ring buffer backed by Vec<T>
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> usize { self.size }
fn cap(&self) -> usize { self.buf.len() }
}
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
}
|
(function () {
var pigKeywordsU = pigKeywordsL = pigTypesU = pigTypesL = pigBuiltinsU = pigBuiltinsL = [];
var mimeMode = CodeMirror.mimeModes['text/x-pig'];
Object.keys(mimeMode.keywords).forEach( function(w) {
pigKeywordsU.push(w.toUpperCase());
pigKeywordsL.push(w.toLowerCase());
});
Object.keys(mimeMode.types).forEach( function(w) {
pigTypesU.push(w.toUpperCase());
pigTypesL.push(w.toLowerCase());
});
Object.keys(mimeMode.builtins).forEach( function(w) {
pigBuiltinsU.push(w.toUpperCase());
pigBuiltinsL.push(w.toLowerCase());
});
function forEach(arr, f) {
for (var i = 0, e = arr.length; i < e; ++i) {
f(arr[i]);
}
}
function arrayContains(arr, item) {
if (!Array.prototype.indexOf) {
var i = arr.length;
while (i
if (arr[i] === item) {
return true;
}
}
return false;
}
return arr.indexOf(item) != -1;
}
function scriptHint(editor, keywords, getToken) {
// Find the token at the cursor
var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
// If it's not a 'word-style' token, ignore the token.
if (!/^[\w$_]*$/.test(token.string)) {
token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
type: token.string == ":" ? "pig-type" : null};
}
if (!context) var context = [];
context.push(tprop);
completionList = getCompletions(token, context);
completionList = completionList.sort();
return {list: completionList,
from: {line: cur.line, ch: token.start},
to: {line: cur.line, ch: token.end}};
}
function toTitleCase(str) {
return str.replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}
function getCompletions(token, context) {
var found = [], start = token.string;
function maybeAdd(str) {
if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
}
function gatherCompletions(obj) {
if(obj == ":") {
forEach(pigTypesL, maybeAdd);
}
else {
forEach(pigBuiltinsU, maybeAdd);
forEach(pigBuiltinsL, maybeAdd);
forEach(pigTypesU, maybeAdd);
forEach(pigTypesL, maybeAdd);
forEach(pigKeywordsU, maybeAdd);
forEach(pigKeywordsL, maybeAdd);
}
}
if (context) {
// If this is a property, see if it belongs to some object we can
// find in the current environment.
var obj = context.pop(), base;
if (obj.type == "pig-word")
base = obj.string;
else if(obj.type == "pig-type")
base = ":" + obj.string;
while (base != null && context.length)
base = base[context.pop().string];
if (base != null) gatherCompletions(base);
}
return found;
}
CodeMirror.registerHelper("hint", "pig", function(cm, options) {
return scriptHint(cm, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
});
})();
|
import {removeElement} from '#core/dom';
import {Layout_Enum, applyFillContent} from '#core/dom/layout';
import {Services} from '#service';
import {userAssert} from '#utils/log';
import {TAG as KEY_TAG} from './amp-embedly-key';
import {getIframe} from '../../../src/3p-frame';
import {listenFor} from '../../../src/iframe-helper';
/**
* Component tag identifier.
* @const {string}
*/
export const TAG = 'amp-embedly-card';
/**
* Attribute name used to set api key with name
* expected by embedly.
* @const {string}
*/
const <TwitterConsumerkey> = 'data-card-key';
/**
* Implementation of the amp-embedly-card component.
* See {@link ../amp-embedly-card.md} for the spec.
*/
export class AmpEmbedlyCard extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?HTMLIFrameElement} */
this.iframe_ = null;
/** @private {?string} */
this.apiKey_ = null;
}
/** @override */
buildCallback() {
userAssert(
this.element.getAttribute('data-url'),
'The data-url attribute is required for <%s> %s',
TAG,
this.element
);
const <API key> = document.querySelector(KEY_TAG);
if (<API key>) {
this.apiKey_ = <API key>.getAttribute('value');
}
}
/** @override */
layoutCallback() {
// Add optional paid api key attribute if provided
// to remove embedly branding.
if (this.apiKey_) {
this.element.setAttribute(<TwitterConsumerkey>, this.apiKey_);
}
const iframe = getIframe(this.win, this.element, 'embedly');
iframe.title = this.element.title || 'Embedly card';
const opt_is3P = true;
listenFor(
iframe,
'embed-size',
(data) => {
this.forceChangeHeight(data['height']);
},
opt_is3P
);
applyFillContent(iframe);
this.getVsync().mutate(() => {
this.element.appendChild(iframe);
});
this.iframe_ = iframe;
return this.loadPromise(iframe);
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
}
return true;
}
/** @override */
isLayoutSupported(layout) {
return layout == Layout_Enum.RESPONSIVE;
}
/**
* @param {boolean=} opt_onLayout
* @override
*/
preconnectCallback(opt_onLayout) {
Services.preconnectFor(this.win).url(
this.getAmpDoc(),
'https://cdn.embedly.com',
opt_onLayout
);
}
}
|
package com.google.api.ads.dfp.jaxws.v201408;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LiveStreamEvent", propOrder = {
"id",
"name",
"description",
"status",
"creationDateTime",
"<API key>",
"startDateTime",
"endDateTime",
"<API key>",
"contentUrls",
"adTags",
"liveStreamEventCode"
})
public class LiveStreamEvent {
protected Long id;
protected String name;
protected String description;
@XmlSchemaType(name = "string")
protected <API key> status;
protected DateTime creationDateTime;
protected DateTime <API key>;
protected DateTime startDateTime;
protected DateTime endDateTime;
protected Long <API key>;
protected List<String> contentUrls;
protected List<String> adTags;
protected String liveStreamEventCode;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link <API key> }
*
*/
public <API key> getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link <API key> }
*
*/
public void setStatus(<API key> value) {
this.status = value;
}
/**
* Gets the value of the creationDateTime property.
*
* @return
* possible object is
* {@link DateTime }
*
*/
public DateTime getCreationDateTime() {
return creationDateTime;
}
/**
* Sets the value of the creationDateTime property.
*
* @param value
* allowed object is
* {@link DateTime }
*
*/
public void setCreationDateTime(DateTime value) {
this.creationDateTime = value;
}
/**
* Gets the value of the <API key> property.
*
* @return
* possible object is
* {@link DateTime }
*
*/
public DateTime <API key>() {
return <API key>;
}
/**
* Sets the value of the <API key> property.
*
* @param value
* allowed object is
* {@link DateTime }
*
*/
public void <API key>(DateTime value) {
this.<API key> = value;
}
/**
* Gets the value of the startDateTime property.
*
* @return
* possible object is
* {@link DateTime }
*
*/
public DateTime getStartDateTime() {
return startDateTime;
}
/**
* Sets the value of the startDateTime property.
*
* @param value
* allowed object is
* {@link DateTime }
*
*/
public void setStartDateTime(DateTime value) {
this.startDateTime = value;
}
/**
* Gets the value of the endDateTime property.
*
* @return
* possible object is
* {@link DateTime }
*
*/
public DateTime getEndDateTime() {
return endDateTime;
}
/**
* Sets the value of the endDateTime property.
*
* @param value
* allowed object is
* {@link DateTime }
*
*/
public void setEndDateTime(DateTime value) {
this.endDateTime = value;
}
/**
* Gets the value of the <API key> property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long <API key>() {
return <API key>;
}
/**
* Sets the value of the <API key> property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void <API key>(Long value) {
this.<API key> = value;
}
/**
* Gets the value of the contentUrls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the contentUrls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContentUrls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getContentUrls() {
if (contentUrls == null) {
contentUrls = new ArrayList<String>();
}
return this.contentUrls;
}
/**
* Gets the value of the adTags property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adTags property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdTags().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAdTags() {
if (adTags == null) {
adTags = new ArrayList<String>();
}
return this.adTags;
}
/**
* Gets the value of the liveStreamEventCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String <API key>() {
return liveStreamEventCode;
}
/**
* Sets the value of the liveStreamEventCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void <API key>(String value) {
this.liveStreamEventCode = value;
}
}
|
// @strict: true
// Both of the following types trigger the recursion limiter in <API key>
type T1<B extends { [K in keyof B]: Extract<B[Exclude<keyof B, K>], { val: string }>["val"] }> = B;
type T2<B extends { [K in keyof B]: B[Exclude<keyof B, K>]["val"] }> = B;
// Repros from #22950
type AProp<T extends { a: string }> = T
declare function myBug<
T extends { [K in keyof T]: T[K] extends AProp<infer U> ? U : never }
>(arg: T): T
const out = myBug({obj1: {a: "test"}})
type Value<V extends string = string> = Record<"val", V>;
declare function value<V extends string>(val: V): Value<V>;
declare function ensureNoDuplicates<
T extends {
[K in keyof T]: Extract<T[K], Value>["val"] extends Extract<T[Exclude<keyof T, K>], Value>["val"]
? never
: any
}
>(vals: T): void;
const noError = ensureNoDuplicates({main: value("test"), alternate: value("test2")});
const shouldBeNoError = ensureNoDuplicates({main: value("test")});
const shouldBeError = ensureNoDuplicates({main: value("dup"), alternate: value("dup")});
// Repro from #26448
type Cond<T> = T extends number ? number : never;
declare function function1<T extends {[K in keyof T]: Cond<T[K]>}>(): T[keyof T]["foo"];
|
#!/usr/bin/env jruby
require 'jrubyfx'
# Example showing a tree_view and also how complicated you can tailor
# behavior of a tree_view. In this example we allow you to drag and drop
# tree_items around. There are three things you can see in d&d here:
# 1. drag onto other tree item will put it as a child in that tree item
# 2. drag and drop to rearrange items
# 3. drag and drop into another window...it should paste the contents there
# This example also allows you to edit your tree and change the text of
# existing contents. Just double click the item to edit it and hit escape
# to cancel or return to save the new name.
class DraggableTreeCell < Java::javafx::scene::control::TreeCell
include JRubyFX::DSL
SELECTION_PERCENT = 0.25
class << self
attr_accessor :drag_item, :drop_type
end
def initialize()
super
set_on_drag_over do |event|
if !child_of_target? && !over_self?
if drop_into_range? y_percentage(event)
set_effect inner_shadow(offset_x: 1.0)
self.class.drop_type = :drop_into
else
set_effect nil
self.class.drop_type = :rearrange
end
event.<API key> :move
end
end
<API key> do |event|
drag_item = tree_item
if drag_item
content = clipboard_content { put_string drag_item.value }
tree_view.start_drag_and_drop(TransferMode::MOVE).set_content content
self.class.drag_item = drag_item
end
event.consume
end
set_on_drag_dropped do |event|
if drag_item && tree_item
drop_into if drop_type == :drop_into
rearrange(event) if drop_type == :rearrange
self.class.drag_item = nil
event.drop_completed = true
end
event.consume
end
set_on_drag_exited do |event|
set_effect nil
end
end
def y_percentage(event)
y = event.scene_y - local_to_scene(0, 0).y
y == 0 ? 0 : y / height
end
def child_of_target?(parent = tree_item)
return true if drag_item == parent
return false if !parent || !parent.parent
child_of_target?(parent.parent)
end
def drop_into
if !child_of_target? && !over_self?
drag_item.parent.children.remove(drag_item)
tree_item.children.add(drag_item)
tree_item.expanded = true
end
end
def drop_into_range?(percent)
percent >= SELECTION_PERCENT && percent <= (1-SELECTION_PERCENT)
end
def over_self?
drag_item.parent == tree_item
end
def updateItem(item, empty)
super(item, empty);
if empty
set_text nil
set_graphic nil
else
if editing?
@text_field.text = get_string if @text_field
set_text nil
set_graphic @text_field
else
set_text get_string
set_graphic tree_item.graphic
end
end
end
def drag_item
self.class.drag_item
end
def drop_type
self.class.drop_type
end
def rearrange(event)
parent = tree_item.parent
unless parent # root of tree view
parent = tree_item
where = 0
end
drag_item.parent.children.remove(drag_item)
saved_items = parent.children.to_a
unless where # where already deduced from root being view_item
where = saved_items.find_index { |e| e == tree_item }
where += 1 if y_percentage(event) > SELECTION_PERCENT
end
if (where >= saved_items.size)
parent.children.add(drag_item)
else
parent.children.set(where, drag_item)
where.upto(saved_items.size - 2) do |i|
parent.children.set(i+1, saved_items[i])
end
parent.children.add(saved_items[saved_items.size - 1])
end
end
# These methods are part of the code to make the tree editable
def startEdit
super
create_text_field unless @text_field
set_text nil
set_graphic @text_field
@text_field.select_all
end
def cancelEdit
super
set_text get_item
set_graphic tree_item.graphic
end
def get_string
get_item ? get_item.to_s : ''
end
def create_text_field
@text_field = TextField.new(get_string)
@text_field.set_on_key_released do |event|
if event.code == KeyCode::ENTER
commitEdit(@text_field.text)
elsif event.code == KeyCode::ESCAPE
cancelEdit
end
end
end
end
class SimpleTreeView < JRubyFX::Application
def start(stage)
with(stage, width: 300, height: 300, title: 'Simple Tree View') do
layout_scene(:blue) do
stack_pane(padding: insets(30)) do
tree_view(editable: true, cell_factory: proc { DraggableTreeCell.new}) do
tree_item("Root") do
5.times {|i| tree_item "File
end
end
end
end
show
end
end
end
SimpleTreeView.launch
|
package org.zstack.sdk;
import org.zstack.sdk.ImageInventory;
public class <API key> {
public ImageInventory inventory;
public void setInventory(ImageInventory inventory) {
this.inventory = inventory;
}
public ImageInventory getInventory() {
return this.inventory;
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TrTranslation.cdy</title>
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
#CSConsole {
background-color: #FAFAFA;
border-top: 1px solid #333333;
bottom: 0px;
height: 200px;
overflow-y: scroll;
position: fixed;
width: 100%;
}
</style>
<script type="text/javascript" src="../build/js/Cindy.js"></script>
<script id="csdraw" type="text/x-cindyscript">
draw(P1,P1i,arrow->true,color->(1,1,1));
draw(O,X,arrow->true,color->(0,0,1));
draw(Oi,Xi,arrow->true,color->(0,0,1));
</script>
<script type="text/javascript">
CindyJS({
scripts: "cs*",
defaultAppearance: { fontFamily: "sans-serif", lineSize: 1, pointSize: 5.0 },
angleUnit: "°",
geometry: [
{ name: "P1", type: "Free", pos: [ 4.0, -4.0, -0.6666666666666666 ], color: [ 0.0, 0.0, 0.0 ], labeled: true, size: 3.0 },
{ name: "P1i", type: "Free", pos: [ 0.0, -4.0, -1.3333333333333333 ], color: [ 0.5019608, 0.5019608, 0.5019608 ], labeled: true, size: 3.0, printname: "P1'" },
{ name: "Tr0", type: "TrTranslation", color: [ 0.0, 0.0, 1.0 ], args: [ "P1", "P1i" ] },
{ name: "O", type: "Free", pos: [ 4.0, 3.3333333333333335, 0.6666666666666666 ], color: [ 1.0, 1.0, 1.0 ], labeled: true },
{ name: "C0", type: "CircleByRadius", color: [ 1.0, 1.0, 0.0 ], radius: 2.999999999999999, args: [ "O" ], printname: "$C_{0}$" },
{ name: "X", type: "PointOnCircle", pos: [ 4.0, { r: 2.2077737946188507, i: -1.<API key> }, { r: 0.4444531955041505, i: 1.<API key> } ], color: [ 0.0, 0.0, 1.0 ], args: [ "C0" ], labeled: true, size: 3.0 },
{ name: "Oi", type: "Transform", pos: [ 4.0, { r: 0.6666666666666673, i: -3.996802888650567E-17 }, { r: 0.3333333333333333, i: 2.<API key> } ], color: [ 1.0, 1.0, 1.0 ], args: [ "Tr0", "O" ], labeled: true, printname: "O'" },
{ name: "Xi", type: "Transform", pos: [ 4.0, { r: 0.5246443927888744, i: -1.<API key> }, { r: 0.2666698170233487, i: 2.095953600789266E-17 } ], color: [ 0.0, 0.0, 1.0 ], args: [ "Tr0", "X" ], labeled: true, size: 3.0, printname: "X'" },
{ name: "C2", type: "Transform", color: [ 1.0, 1.0, 0.0 ], args: [ "Tr0", "C0" ], printname: "$C_{2}$" } ],
ports: [
{ id: "CSCanvas", width: 680, height: 350, transform: [ { visibleRect: [ -9.06, 9.34, 18.14, -4.66 ] } ], background: "rgb(168,176,192)" } ],
cinderella: { build: 1798, version: [ 2, 9, 1798 ] } });
</script>
</head>
<body>
<div id="CSCanvas"></div>
</body>
</html>
|
create table SALES_PRODUCT (
ID varchar(36) not null,
CREATE_TS timestamp,
CREATED_BY varchar(50),
VERSION integer,
UPDATE_TS timestamp,
UPDATED_BY varchar(50),
DELETE_TS timestamp,
DELETED_BY varchar(50),
NAME varchar(50) not null,
PRICE decimal(19, 2) not null,
primary key (ID)
);
|
<!DOCTYPE html>
<html lang="en">
<!-- head -->
<head>
<include file="Public/public_head" title="-" keywords="{$Think.config.WEB_KEYWORDS}" description="{$Think.config.WEB_DESCRIPTION}" />
</head>
<!-- head -->
<body>
<include file="Public/public_nav" />
<div class="b-h-70"></div>
<div id="b-content" class="container">
<div class="row">
<div class="col-xs-12 col-md-12 col-lg-8 b-chat">
<!-- bjyadmin -->
<script src='http://git.oschina.net/shuaibai123/thinkphp-bjyadmin/widget_preview'></script>
<style>
.pro_name a{color: #4183c4;}
.osc_git_title{background-color: #d8e5f1;}
.osc_git_box{background-color: #fafafa;}
.osc_git_box{border-color: #ddd;}
.osc_git_info{color: #666;}
.osc_git_main a{color: #4183c4;}
</style>
<!-- bjyadmin -->
<!-- bjyblog -->
<script src='http://git.oschina.net/shuaibai123/thinkbjy/widget_preview'></script>
<style>
.pro_name a{color: #4183c4;}
.osc_git_title{background-color: #d8e5f1;}
.osc_git_box{background-color: #fafafa;}
.osc_git_box{border-color: #ddd;}
.osc_git_info{color: #666;}
.osc_git_main a{color: #4183c4;}
</style>
<!-- bjyblog -->
<!-- sublime -->
<script src='http://git.oschina.net/shuaibai123/<API key>/widget_preview'></script>
<style>
.pro_name a{color: #4183c4;}
.osc_git_title{background-color: #d8e5f1;}
.osc_git_box{background-color: #fafafa;}
.osc_git_box{border-color: #ddd;}
.osc_git_info{color: #666;}
.osc_git_main a{color: #4183c4;}
</style>
<!-- sublime -->
<script src='http://git.oschina.net/shuaibai123/resources/widget_preview'></script>
<style>
.pro_name a{color: #4183c4;}
.osc_git_title{background-color: #d8e5f1;}
.osc_git_box{background-color: #fafafa;}
.osc_git_box{border-color: #ddd;}
.osc_git_info{color: #666;}
.osc_git_main a{color: #4183c4;}
</style>
<!-- github -->
<div class="github-widget" data-repo="baijunyao/thinkphp-bjyadmin"></div>
<div class="github-widget" data-repo="baijunyao/thinkphp-bjyblog"></div>
</div>
<include file="Public/public_right" />
</div>
<div class="row">
<include file="Public/public_foot" />
</div>
</div>
<include file="Public/public_login" />
<script src="__PUBLIC__/static/js/jquery.githubRepoWidget.min.js"></script>
<!-- osc -->
<script type="text/javascript">
$(function(){
$('.osc_git_box a,.github-widget a').attr('target','_blank');
})
</script>
</body>
</html>
|
#pragma once
#include <string>
#include "db/<API key>.h"
#include "rocksdb/types.h"
#include "util/coding.h"
#include "util/string_util.h"
namespace ROCKSDB_NAMESPACE {
struct <API key> {
// value of this property is a fixed uint32 number.
static const std::string kVersion;
// value of this property is a fixed uint64 number.
static const std::string kGlobalSeqno;
};
// PropertiesCollector used to add properties specific to tables
// generated by SstFileWriter
class <API key> : public IntTblPropCollector {
public:
explicit <API key>(int32_t version,
SequenceNumber global_seqno)
: version_(version), global_seqno_(global_seqno) {}
virtual Status InternalAdd(const Slice& /*key*/, const Slice& /*value*/,
uint64_t /*file_size*/) override {
// Intentionally left blank. Have no interest in collecting stats for
// individual key/value pairs.
return Status::OK();
}
virtual void BlockAdd(uint64_t /* block_raw_bytes */,
uint64_t /* <API key> */,
uint64_t /* <API key> */) override {
// Intentionally left blank. No interest in collecting stats for
// blocks.
return;
}
virtual Status Finish(<API key>* properties) override {
// File version
std::string version_val;
PutFixed32(&version_val, static_cast<uint32_t>(version_));
properties->insert({<API key>::kVersion, version_val});
// Global Sequence number
std::string seqno_val;
PutFixed64(&seqno_val, static_cast<uint64_t>(global_seqno_));
properties->insert({<API key>::kGlobalSeqno, seqno_val});
return Status::OK();
}
virtual const char* Name() const override {
return "<API key>";
}
virtual <API key> <API key>() const override {
return {{<API key>::kVersion, ToString(version_)}};
}
private:
int32_t version_;
SequenceNumber global_seqno_;
};
class <API key>
: public <API key> {
public:
explicit <API key>(int32_t version,
SequenceNumber global_seqno)
: version_(version), global_seqno_(global_seqno) {}
virtual IntTblPropCollector* <API key>(
uint32_t /*column_family_id*/, int /* level_at_creation */) override {
return new <API key>(version_, global_seqno_);
}
virtual const char* Name() const override {
return "<API key>";
}
private:
int32_t version_;
SequenceNumber global_seqno_;
};
} // namespace ROCKSDB_NAMESPACE
|
package cvc3;
import java.util.*;
import java.io.*;
/** Wrapper for a c++ object as a java Object.
see README for details on garbage collection,
i.e. interplay of delete, finalize, and EmbeddedManager to destruct
the embedded c++ object. */
public abstract class Embedded {
// load jni c++ library
static {
System.loadLibrary("cvc3jni");
/*
// for debugging: stop here by waiting for a key press,
// and attach c++ debugger
System.out.println("Loadded cvc3jni");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
} catch (IOException ioe) {
}
*/
}
Attributes
// embedded object
protected Object d_embedded;
// embedded object manager
private final EmbeddedManager d_embeddedManager;
Constructor
// initialize with embedded object and EmbeddedManager
// if EmbeddedManager is null then delete must be called before
// Embedded is garbage collected
protected Embedded(Object Embedded, EmbeddedManager embeddedManager) {
//System.out.println("Create: Embedded");
assert(Embedded != null);
d_embedded = Embedded;
d_embeddedManager = embeddedManager;
}
// access to embedded c++ object
public synchronized Object embedded() {
return d_embedded;
}
// access to EmbeddedManager (might be null if none used)
public EmbeddedManager embeddedManager() {
return d_embeddedManager;
}
// check if already destructed
// (or queued for destruction in embeddedManager)
public synchronized boolean isDeleted() {
return (d_embedded == null);
}
// delete embedded object or enqueue it for deletion
public synchronized void delete() throws Cvc3Exception {
if (isDeleted()) return;
// no embedded manager, so should be in main thread:
// destruct right away
if (d_embeddedManager == null) {
EmbeddedManager.jniDelete(d_embedded);
}
// could be in finalizer, so queue in embeddedManager;
// unless the embeddedManager is already deleted,
// then its (and this') ValidityChecker has been delete.
// assuming this is an Expr or a Theorem it's embedded object
// has then already been deleted as well.
else {
synchronized(d_embeddedManager) {
if (!d_embeddedManager.isDeleted()) {
d_embeddedManager.register(this);
}
}
}
d_embedded = null;
}
// ensure that delete is called if finalization occurs
public void finalize() throws Throwable {
try {
// no embeddedManager, so deleted should have been called
if (d_embeddedManager == null) {
if (d_embedded != null) {
assert(false);
// System.out.println("Embedded.Finalizer: should never be called");
throw new Error("Embedded.Finalizer: should never be called");
}
}
else if (!d_embeddedManager.isDeleted()) {
delete();
}
} finally {
super.finalize();
}
}
}
|
package com.sun.java.swing.plaf.windows;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.lang.ref.*;
import java.util.*;
import javax.swing.plaf.basic.*;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import static com.sun.java.swing.plaf.windows.TMSchema.*;
import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
/**
* Windows rendition of the component.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is appropriate
* for short term storage or RMI between applications running the same
* version of Swing. A future release of Swing will provide support for
* long term persistence.
*/
public class WindowsScrollBarUI extends BasicScrollBarUI {
private Grid thumbGrid;
private Grid highlightGrid;
private Dimension horizontalThumbSize;
private Dimension verticalThumbSize;
/**
* Creates a UI for a JScrollBar.
*
* @param c the text field
* @return the UI
*/
public static ComponentUI createUI(JComponent c) {
return new WindowsScrollBarUI();
}
protected void installDefaults() {
super.installDefaults();
XPStyle xp = XPStyle.getXP();
if (xp != null) {
scrollbar.setBorder(null);
horizontalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNHORZ);
verticalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNVERT);
} else {
horizontalThumbSize = null;
verticalThumbSize = null;
}
}
private static Dimension getSize(Component component, XPStyle xp, Part part) {
Skin skin = xp.getSkin(component, part);
return new Dimension(skin.getWidth(), skin.getHeight());
}
@Override
protected Dimension getMinimumThumbSize() {
if ((horizontalThumbSize == null) || (verticalThumbSize == null)) {
return super.getMinimumThumbSize();
}
return JScrollBar.HORIZONTAL == scrollbar.getOrientation()
? horizontalThumbSize
: verticalThumbSize;
}
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
thumbGrid = highlightGrid = null;
}
protected void <API key>() {
super.<API key>();
Color color = UIManager.getColor("ScrollBar.trackForeground");
if (color != null && trackColor != null) {
thumbGrid = Grid.getGrid(color, trackColor);
}
color = UIManager.getColor("ScrollBar.<API key>");
if (color != null && trackHighlightColor != null) {
highlightGrid = Grid.getGrid(color, trackHighlightColor);
}
}
protected JButton <API key>(int orientation) {
return new WindowsArrowButton(orientation,
UIManager.getColor("ScrollBar.thumb"),
UIManager.getColor("ScrollBar.thumbShadow"),
UIManager.getColor("ScrollBar.thumbDarkShadow"),
UIManager.getColor("ScrollBar.thumbHighlight"));
}
protected JButton <API key>(int orientation) {
return new WindowsArrowButton(orientation,
UIManager.getColor("ScrollBar.thumb"),
UIManager.getColor("ScrollBar.thumbShadow"),
UIManager.getColor("ScrollBar.thumbDarkShadow"),
UIManager.getColor("ScrollBar.thumbHighlight"));
}
/**
* {@inheritDoc}
* @since 1.6
*/
@Override
protected ArrowButtonListener <API key>(){
// we need to repaint the entire scrollbar because state change for each
// button causes a state change for the thumb and other button on Vista
if(XPStyle.isVista()) {
return new ArrowButtonListener() {
public void mouseEntered(MouseEvent evt) {
repaint();
super.mouseEntered(evt);
}
public void mouseExited(MouseEvent evt) {
repaint();
super.mouseExited(evt);
}
private void repaint() {
scrollbar.repaint();
}
};
} else {
return super.<API key>();
}
}
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds){
boolean v = (scrollbar.getOrientation() == JScrollBar.VERTICAL);
XPStyle xp = XPStyle.getXP();
if (xp != null) {
JScrollBar sb = (JScrollBar)c;
State state = State.NORMAL;
// Pending: Implement rollover (hot) and pressed
if (!sb.isEnabled()) {
state = State.DISABLED;
}
Part part = v ? Part.SBP_LOWERTRACKVERT : Part.SBP_LOWERTRACKHORZ;
xp.getSkin(sb, part).paintSkin(g, trackBounds, state);
} else if (thumbGrid == null) {
super.paintTrack(g, c, trackBounds);
}
else {
thumbGrid.paint(g, trackBounds.x, trackBounds.y, trackBounds.width,
trackBounds.height);
if (trackHighlight == DECREASE_HIGHLIGHT) {
<API key>(g);
}
else if (trackHighlight == INCREASE_HIGHLIGHT) {
<API key>(g);
}
}
}
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
boolean v = (scrollbar.getOrientation() == JScrollBar.VERTICAL);
XPStyle xp = XPStyle.getXP();
if (xp != null) {
JScrollBar sb = (JScrollBar)c;
State state = State.NORMAL;
if (!sb.isEnabled()) {
state = State.DISABLED;
} else if (isDragging) {
state = State.PRESSED;
} else if (isThumbRollover()) {
state = State.HOT;
} else if (XPStyle.isVista()) {
if ((incrButton != null && incrButton.getModel().isRollover()) ||
(decrButton != null && decrButton.getModel().isRollover())) {
state = State.HOVER;
}
}
// Paint thumb
Part thumbPart = v ? Part.SBP_THUMBBTNVERT : Part.SBP_THUMBBTNHORZ;
xp.getSkin(sb, thumbPart).paintSkin(g, thumbBounds, state);
// Paint gripper
Part gripperPart = v ? Part.SBP_GRIPPERVERT : Part.SBP_GRIPPERHORZ;
Skin skin = xp.getSkin(sb, gripperPart);
Insets gripperInsets = xp.getMargin(c, thumbPart, null, Prop.CONTENTMARGINS);
if (gripperInsets == null ||
(v && (thumbBounds.height - gripperInsets.top -
gripperInsets.bottom >= skin.getHeight())) ||
(!v && (thumbBounds.width - gripperInsets.left -
gripperInsets.right >= skin.getWidth()))) {
skin.paintSkin(g,
thumbBounds.x + (thumbBounds.width - skin.getWidth()) / 2,
thumbBounds.y + (thumbBounds.height - skin.getHeight()) / 2,
skin.getWidth(), skin.getHeight(), state);
}
} else {
super.paintThumb(g, c, thumbBounds);
}
}
protected void <API key>(Graphics g) {
if (highlightGrid == null) {
super.<API key>(g);
}
else {
Insets insets = scrollbar.getInsets();
Rectangle thumbR = getThumbBounds();
int x, y, w, h;
if (scrollbar.getOrientation() == JScrollBar.VERTICAL) {
x = insets.left;
y = decrButton.getY() + decrButton.getHeight();
w = scrollbar.getWidth() - (insets.left + insets.right);
h = thumbR.y - y;
}
else {
x = decrButton.getX() + decrButton.getHeight();
y = insets.top;
w = thumbR.x - x;
h = scrollbar.getHeight() - (insets.top + insets.bottom);
}
highlightGrid.paint(g, x, y, w, h);
}
}
protected void <API key>(Graphics g) {
if (highlightGrid == null) {
super.<API key>(g);
}
else {
Insets insets = scrollbar.getInsets();
Rectangle thumbR = getThumbBounds();
int x, y, w, h;
if (scrollbar.getOrientation() == JScrollBar.VERTICAL) {
x = insets.left;
y = thumbR.y + thumbR.height;
w = scrollbar.getWidth() - (insets.left + insets.right);
h = incrButton.getY() - y;
}
else {
x = thumbR.x + thumbR.width;
y = insets.top;
w = incrButton.getX() - x;
h = scrollbar.getHeight() - (insets.top + insets.bottom);
}
highlightGrid.paint(g, x, y, w, h);
}
}
/**
* {@inheritDoc}
* @since 1.6
*/
@Override
protected void setThumbRollover(boolean active) {
boolean old = isThumbRollover();
super.setThumbRollover(active);
// we need to repaint the entire scrollbar because state change for thumb
// causes state change for incr and decr buttons on Vista
if(XPStyle.isVista() && active != old) {
scrollbar.repaint();
}
}
/**
* WindowsArrowButton is used for the buttons to position the
* document up/down. It differs from BasicArrowButton in that the
* preferred size is always a square.
*/
private class WindowsArrowButton extends BasicArrowButton {
public WindowsArrowButton(int direction, Color background, Color shadow,
Color darkShadow, Color highlight) {
super(direction, background, shadow, darkShadow, highlight);
}
public WindowsArrowButton(int direction) {
super(direction);
}
public void paint(Graphics g) {
XPStyle xp = XPStyle.getXP();
if (xp != null) {
ButtonModel model = getModel();
Skin skin = xp.getSkin(this, Part.SBP_ARROWBTN);
State state = null;
boolean jointRollover = XPStyle.isVista() && (isThumbRollover() ||
(this == incrButton && decrButton.getModel().isRollover()) ||
(this == decrButton && incrButton.getModel().isRollover()));
// normal, rollover, pressed, disabled
if (model.isArmed() && model.isPressed()) {
switch (direction) {
case NORTH: state = State.UPPRESSED; break;
case SOUTH: state = State.DOWNPRESSED; break;
case WEST: state = State.LEFTPRESSED; break;
case EAST: state = State.RIGHTPRESSED; break;
}
} else if (!model.isEnabled()) {
switch (direction) {
case NORTH: state = State.UPDISABLED; break;
case SOUTH: state = State.DOWNDISABLED; break;
case WEST: state = State.LEFTDISABLED; break;
case EAST: state = State.RIGHTDISABLED; break;
}
} else if (model.isRollover() || model.isPressed()) {
switch (direction) {
case NORTH: state = State.UPHOT; break;
case SOUTH: state = State.DOWNHOT; break;
case WEST: state = State.LEFTHOT; break;
case EAST: state = State.RIGHTHOT; break;
}
} else if (jointRollover) {
switch (direction) {
case NORTH: state = State.UPHOVER; break;
case SOUTH: state = State.DOWNHOVER; break;
case WEST: state = State.LEFTHOVER; break;
case EAST: state = State.RIGHTHOVER; break;
}
} else {
switch (direction) {
case NORTH: state = State.UPNORMAL; break;
case SOUTH: state = State.DOWNNORMAL; break;
case WEST: state = State.LEFTNORMAL; break;
case EAST: state = State.RIGHTNORMAL; break;
}
}
skin.paintSkin(g, 0, 0, getWidth(), getHeight(), state);
} else {
super.paint(g);
}
}
public Dimension getPreferredSize() {
int size = 16;
if (scrollbar != null) {
switch (scrollbar.getOrientation()) {
case JScrollBar.VERTICAL:
size = scrollbar.getWidth();
break;
case JScrollBar.HORIZONTAL:
size = scrollbar.getHeight();
break;
}
size = Math.max(size, 5);
}
return new Dimension(size, size);
}
}
/**
* This should be pulled out into its own class if more classes need to
* use it.
* <p>
* Grid is used to draw the track for windows scrollbars. Grids
* are cached in a HashMap, with the key being the rgb components
* of the foreground/background colors. Further the Grid is held through
* a WeakRef so that it can be freed when no longer needed. As the
* Grid is rather expensive to draw, it is drawn in a BufferedImage.
*/
private static class Grid {
private static final int BUFFER_SIZE = 64;
private static HashMap<String, WeakReference<Grid>> map;
private BufferedImage image;
static {
map = new HashMap<String, WeakReference<Grid>>();
}
public static Grid getGrid(Color fg, Color bg) {
String key = fg.getRGB() + " " + bg.getRGB();
WeakReference<Grid> ref = map.get(key);
Grid grid = (ref == null) ? null : ref.get();
if (grid == null) {
grid = new Grid(fg, bg);
map.put(key, new WeakReference<Grid>(grid));
}
return grid;
}
public Grid(Color fg, Color bg) {
int cmap[] = { fg.getRGB(), bg.getRGB() };
IndexColorModel icm = new IndexColorModel(8, 2, cmap, 0, false, -1,
DataBuffer.TYPE_BYTE);
image = new BufferedImage(BUFFER_SIZE, BUFFER_SIZE,
BufferedImage.TYPE_BYTE_INDEXED, icm);
Graphics g = image.getGraphics();
try {
g.setClip(0, 0, BUFFER_SIZE, BUFFER_SIZE);
paintGrid(g, fg, bg);
}
finally {
g.dispose();
}
}
/**
* Paints the grid into the specified Graphics at the specified
* location.
*/
public void paint(Graphics g, int x, int y, int w, int h) {
Rectangle clipRect = g.getClipBounds();
int minX = Math.max(x, clipRect.x);
int minY = Math.max(y, clipRect.y);
int maxX = Math.min(clipRect.x + clipRect.width, x + w);
int maxY = Math.min(clipRect.y + clipRect.height, y + h);
if (maxX <= minX || maxY <= minY) {
return;
}
int xOffset = (minX - x) % 2;
for (int xCounter = minX; xCounter < maxX;
xCounter += BUFFER_SIZE) {
int yOffset = (minY - y) % 2;
int width = Math.min(BUFFER_SIZE - xOffset,
maxX - xCounter);
for (int yCounter = minY; yCounter < maxY;
yCounter += BUFFER_SIZE) {
int height = Math.min(BUFFER_SIZE - yOffset,
maxY - yCounter);
g.drawImage(image, xCounter, yCounter,
xCounter + width, yCounter + height,
xOffset, yOffset,
xOffset + width, yOffset + height, null);
if (yOffset != 0) {
yCounter -= yOffset;
yOffset = 0;
}
}
if (xOffset != 0) {
xCounter -= xOffset;
xOffset = 0;
}
}
}
/**
* Actually renders the grid into the Graphics <code>g</code>.
*/
private void paintGrid(Graphics g, Color fg, Color bg) {
Rectangle clipRect = g.getClipBounds();
g.setColor(bg);
g.fillRect(clipRect.x, clipRect.y, clipRect.width,
clipRect.height);
g.setColor(fg);
g.translate(clipRect.x, clipRect.y);
int width = clipRect.width;
int height = clipRect.height;
int xCounter = clipRect.x % 2;
for (int end = width - height; xCounter < end; xCounter += 2) {
g.drawLine(xCounter, 0, xCounter + height, height);
}
for (int end = width; xCounter < end; xCounter += 2) {
g.drawLine(xCounter, 0, width, width - xCounter);
}
int yCounter = ((clipRect.x % 2) == 0) ? 2 : 1;
for (int end = height - width; yCounter < end; yCounter += 2) {
g.drawLine(0, yCounter, width, yCounter + width);
}
for (int end = height; yCounter < end; yCounter += 2) {
g.drawLine(0, yCounter, height - yCounter, height);
}
g.translate(-clipRect.x, -clipRect.y);
}
}
}
|
namespace Microsoft.CodeAnalysis.Host
{
internal class <API key> : <API key>
{
public static readonly <API key> Instance = new <API key>();
private <API key>()
{
}
public IPersistentStorage GetStorage(Solution solution)
=> <API key>.Instance;
public IPersistentStorage GetStorage(Solution solution, bool checkBranchId)
=> <API key>.Instance;
<API key> <API key>.GetStorage(Solution solution)
=> <API key>.Instance;
<API key> <API key>.GetStorage(Solution solution, bool checkBranchId)
=> <API key>.Instance;
}
}
|
package sun.security.smartcardio;
import java.security.*;
import javax.smartcardio.*;
/**
* Provider object for PC/SC.
*
* @since 1.6
* @author Andreas Sterbenz
*/
public final class SunPCSC extends Provider {
private static final long serialVersionUID = <API key>;
public SunPCSC() {
super("SunPCSC", 1.6d, "Sun PC/SC provider");
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
put("TerminalFactory.PC/SC", "sun.security.smartcardio.SunPCSC$Factory");
return null;
}
});
}
public static final class Factory extends TerminalFactorySpi {
public Factory(Object obj) throws PCSCException {
if (obj != null) {
throw new <API key>
("SunPCSC factory does not use parameters");
}
// make sure PCSC is available and that we can obtain a context
PCSC.checkAvailable();
PCSCTerminals.initContext();
}
/**
* Returns the available readers.
* This must be a new object for each call.
*/
protected CardTerminals engineTerminals() {
return new PCSCTerminals();
}
}
}
|
package com.fincatto.documentofiscal.nfe400.utils.qrcode20;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.<API key>;
import org.apache.commons.lang3.StringUtils;
import com.fincatto.documentofiscal.DFAmbiente;
import com.fincatto.documentofiscal.nfe.NFeConfig;
import com.fincatto.documentofiscal.nfe400.classes.nota.NFNota;
public abstract class NFGeraQRCode20 {
public static final String VERSAO_QRCODE = "2";
protected final NFNota nota;
protected final NFeConfig config;
public NFGeraQRCode20(final NFNota nota, final NFeConfig config) {
this.nota = nota;
this.config = config;
}
public abstract String getQRCode() throws <API key>;
public String getUrlQRCode(){
String url = this.config.getAmbiente().equals(DFAmbiente.PRODUCAO) ? this.nota.getInfo().getIdentificacao().getUf().getQrCodeProducao() : this.nota.getInfo().getIdentificacao().getUf().<API key>();
if (StringUtils.isBlank(url)) {
throw new <API key>("URL para consulta do QRCode nao informada para uf " + this.nota.getInfo().getIdentificacao().getUf() + "!");
}
if (StringUtils.isBlank(this.config.<API key>())) {
throw new <API key>("CSC nao informado nas configuracoes!");
}
if ((this.config.<API key>() == null) || (this.config.<API key>() == 0)) {
throw new <API key>("IdCSC nao informado nas configuracoes!");
}
return url;
}
public static String createHash(final String campos, final String csc) throws <API key> {
return sha1(campos + csc);
}
public static String toHex(final String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes(Charset.forName("UTF-8"))));
}
public static String sha1(final String input) throws <API key> {
final StringBuilder sb = new StringBuilder();
for (final byte element : MessageDigest.getInstance("SHA1").digest(input.getBytes(Charset.forName("UTF-8")))) {
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1));
}
return sb.toString().toUpperCase();
}
public String <API key>(){
return this.config.getAmbiente().equals(DFAmbiente.PRODUCAO) ? this.nota.getInfo().getIdentificacao().getUf().<API key>() : this.nota.getInfo().getIdentificacao().getUf().<API key>();
}
}
|
'use strict';
var util = require('../util/util'),
RequestTiming = require('../requestTiming'),
Stats = require('fast-stats').Stats,
winston = require('winston');
var domains = {};
exports.processPage = function(pageData) {
var log = winston.loggers.get('sitespeed.io');
var harData = [];
if (pageData.browsertime && pageData.browsertime.har) {
Array.prototype.push.apply(harData, pageData.browsertime.har);
}
if (pageData.webpagetest && pageData.webpagetest.har) {
Array.prototype.push.apply(harData, pageData.webpagetest.har);
}
// Workaround to avoid issues when bt doesn't generate a har due to useProxy being set to false
harData = harData.filter(function(har) {
return !!har;
});
var pageURL = util.getURLFromPageData(pageData);
harData.forEach(function(har) {
har.log.entries.forEach(function(entry) {
var domain = domains[util.getHostname(entry.request.url)];
var total;
if (domain) {
if (entry.timings) {
total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl +
entry.timings
.send + entry.timings.wait + entry.timings.receive;
domain.blocked.add(entry.timings.blocked, entry.request.url, pageURL);
domain.dns.add(entry.timings.dns, entry.request.url, pageURL);
domain.connect.add(entry.timings.connect, entry.request.url, pageURL);
domain.ssl.add(entry.timings.ssl, entry.request.url, pageURL);
domain.send.add(entry.timings.send, entry.request.url, pageURL);
domain.wait.add(entry.timings.wait, entry.request.url, pageURL);
domain.receive.add(entry.timings.receive, entry.request.url, pageURL);
domain.total.add(total, entry.request.url, pageURL);
domain.accumulatedTime += total;
} else {
log.log('info', 'Missing timings in the HAR');
}
} else {
if (entry.timings) {
total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl +
entry.timings
.send + entry.timings.wait + entry.timings.receive;
domains[util.getHostname(entry.request.url)] = {
domain: util.getHostname(entry.request.url),
blocked: new RequestTiming(entry.timings.blocked, entry.request.url, pageURL),
dns: new RequestTiming(entry.timings.dns, entry.request.url, pageURL),
connect: new RequestTiming(entry.timings.connect, entry.request.url, pageURL),
ssl: new RequestTiming(entry.timings.ssl, entry.request.url, pageURL),
send: new RequestTiming(entry.timings.send, entry.request.url, pageURL),
wait: new RequestTiming(entry.timings.wait, entry.request.url, pageURL),
receive: new RequestTiming(entry.timings.receive, entry.request.url, pageURL),
total: new RequestTiming(total, entry.request.url, pageURL),
accumulatedTime: total
};
} else {
log.log('info', 'Missing timings in the HAR');
}
}
});
});
// we have HAR files with one page tested multiple times,
// make sure we only get data from the first run
// and we kind of add items & size for requests missing
// but only for the first one
var pageref = '';
// add request & size, just do it for the first run
if (harData.length > 0) {
harData[0].log.entries.forEach(function(entry) {
if (pageref === '' || entry.pageref === pageref) {
pageref = entry.pageref;
var domain = domains[util.getHostname(entry.request.url)];
if (domain.count) {
domain.count++;
} else {
domain.count = 1;
}
if (domain.size) {
domain.size.total += entry.response.content.size;
domain.size[util.getContentType(entry.response.content.mimeType)] +=
entry.response.content.size;
} else {
domain.size = {
total: entry.response.content.size,
css: 0,
doc: 0,
js: 0,
image: 0,
font: 0,
flash: 0,
unknown: 0
};
domain.size[util.getContentType(entry.response.content.mimeType)] = entry.response.content.size;
}
} else {
// all other har files
var daDomain = domains[util.getHostname(entry.request.url)];
if (!daDomain.count) {
daDomain.count = 1;
}
if (!daDomain.size) {
// this is not perfect, we will miss request in other HAR..s
daDomain.size = {
total: entry.response.content.size,
css: 0,
doc: 0,
js: 0,
image: 0,
font: 0,
flash: 0,
unknown: 0
};
daDomain.size[util.getContentType(entry.response.content.mimeType)] = entry.response.content.size;
}
}
});
}
};
exports.generateResults = function() {
var values = Object.keys(domains).map(function(key) {
return domains[key];
});
return {
id: 'domains',
list: values
};
};
exports.clear = function() {
domains = {};
};
|
<section id="advice">
<h2 class="page-header"><a href="#advice">A Word of Advice</a></h2>
<p class="lead">
Before you go to see your new awesome theme, here are few tips on how to familiarize yourself with it:
</p>
<ul>
<li><b>AdminLTE is based on <a href="http://getbootstrap.com/" target="_blank">Bootstrap 3</a>.</b> If you are unfamiliar with Bootstrap, visit their website and read through the documentation. All of Bootstrap components have been modified to fit the style of AdminLTE and provide a consistent look throughout the template. This way, we guarantee you will get the best of AdminLTE.</li>
<li><b>Go through the pages that are bundled with the theme.</b> Most of the template example pages contain quick tips on how to create or use a component which can be really helpful when you need to create something on the fly.</li>
<li><b>Documentation.</b> We are trying our best to make your experience with AdminLTE be smooth. One way to achieve that is to provide documentation and support. If you think that something is missing from the documentation, please do not hesitate to create an issue to tell us about it.</li>
<li><b>Built with <a href="http://lesscss.org/" target="_blank">LESS</a>.</b> This theme uses the LESS compiler to make it easier to customize and use. LESS is easy to learn if you know CSS or SASS. It is not necessary to learn LESS but it will benefit you a lot in the future.</li>
<li><b>Hosted on <a href="https://github.com/almasaeed2010/AdminLTE/" target="_blank">GitHub</a>.</b> Visit our GitHub repository to view issues, make requests, or contribute to the project.</li>
</ul>
<p>
<b>Note:</b> LESS files are better commented than the compiled CSS file.
</p>
</section>
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Directions Draggable</title>
<link href="default.css" rel="stylesheet">
<script type="text/javascript" src="https:
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay;
var directionsService;
var map;
var australia;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
directionsService = new google.maps.DirectionsService();
australia = new google.maps.LatLng(-25.274398, 133.775136);
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: australia
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
<API key>(directionsDisplay.getDirections());
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Sydney, NSW',
destination: 'Sydney, NSW',
waypoints:[{location: 'Bourke, NSW'}, {location: 'Broken Hill, NSW'}],
travelMode: google.maps.<API key>.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function <API key>(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
document.getElementById('total').innerHTML = total + ' km';
}
google.load('maps', '3.0', {
callback: initialize,
other_params: 'sensor=false'
});
</script>
</head>
<body>
<div id="map_canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>
|
#include "Tiano.h"
#include EFI_GUID_DEFINITION (EfiShell)
EFI_GUID gEfiShellFileGuid = EFI_SHELL_FILE_GUID;
EFI_GUID <API key> = <API key>;
EFI_GUID_STRING (&gEfiShellFileGuid, "EfiShell", "Efi Shell FFS file name GUID")
EFI_GUID_STRING (&<API key>, "EfiMiniShell", "Efi Mini-Shell FFS file name GUID")
|
<reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters: true
/function g(a, b) { b; }
/g(1, 2);
verify.not.codeFixAvailable("Remove unused declaration for: 'a'");
|
package org.jetbrains.idea.svn;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.conflict.ConflictAction;
import org.jetbrains.idea.svn.conflict.ConflictOperation;
import org.jetbrains.idea.svn.conflict.ConflictVersion;
import org.jetbrains.idea.svn.conflict.<API key>;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.function.BiConsumer;
import static com.intellij.testFramework.EdtTestUtil.runInEdtAndWait;
import static org.junit.Assert.*;
public class <API key> extends SvnTestCase {
private VirtualFile myTheirs;
private SvnClientRunnerImpl mySvnClientRunner;
@Override
@Before
public void before() throws Exception {
myWcRootName = "wcRootConflictData";
myTraceClient = true;
super.before();
<API key>(VcsConfiguration.<API key>.ADD);
myTheirs = myTempDirFixture.findOrCreateDir("theirs");
mySvnClientRunner = new SvnClientRunnerImpl(myRunner);
mySvnClientRunner.checkout(myRepoUrl, myTheirs);
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_ADD, false, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
assertNull(beforeDescription.<API key>());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isNone());
});
}
private String createConflict(@NotNull TreeConflictData.Data data, boolean createSubtree) throws Exception {
if (createSubtree) {
mySvnClientRunner.testSvnVersion(myWorkingCopyDir);
createSubTree();
}
runInEdtAndWait(() -> new ConflictCreator(vcs, myTheirs, myWorkingCopyDir, data, mySvnClientRunner).create());
return data.getConflictFile();
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isNone());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToFile.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
//Assert.assertEquals(NodeKind.FILE, leftVersion.getKind());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
// not a conflict in Subversion 1.7.7. "mine" file becomes added
/*@Test
public void <API key>() throws Exception {
final String conflictFile = createConflict(TreeConflictData.DirToDir.<API key>);
<API key>.getInstance(myProject).markEverythingDirty();
ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
changeListManager.ensureUpToDate(false);
VirtualFile vf = LocalFileSystem.getInstance().<API key>(new File(myWorkingCopyDir.getPath(), conflictFile));
Assert.assertNotNull(vf);
final Change change = changeListManager.getChange(vf);
Assert.assertTrue(change instanceof ConflictedSvnChange);
<API key> beforeDescription = ((ConflictedSvnChange)change).<API key>();
Assert.assertNotNull(beforeDescription);
final <API key> afterDescription = ((ConflictedSvnChange)change).getAfterDescription();
Assert.assertNull(afterDescription);
Assert.assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
Assert.assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
Assert.assertNotNull(leftVersion);
Assert.assertEquals(NodeKind.DIR, leftVersion.getKind());
final ConflictVersion version = beforeDescription.<API key>();
Assert.assertNotNull(version);
Assert.assertEquals(NodeKind.NONE, version.getKind());
}*/
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.DirToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.DirToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isNone());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.DirToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.DirToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.DirToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
//Assert.assertEquals(NodeKind.DIR, leftVersion.getKind());
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void <API key>() throws Exception {
assertConflict(TreeConflictData.FileToDir.<API key>, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.<API key>();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.<API key>();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
|
package org.jboss.resteasy.api.validation;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="<API key>")
@XmlAccessorType(XmlAccessType.FIELD)
public class <API key> implements Serializable
{
private static final long serialVersionUID = -<API key>;
private ConstraintType.Type constraintType;
private String path;
private String message;
private String value;
public <API key>(ConstraintType.Type constraintType, String path, String message, String value)
{
this.constraintType = constraintType;
this.path = path;
this.message = message;
this.value = value;
}
public <API key>()
{
}
/**
* @return type of constraint
*/
public ConstraintType.Type getConstraintType()
{
return constraintType;
}
/**
* @return description of element violating constraint
*/
public String getPath()
{
return path;
}
/**
* @return description of constraint violation
*/
public String getMessage()
{
return message;
}
/**
* @return object in violation of constraint
*/
public String getValue()
{
return value;
}
/**
* @return String representation of violation
*/
public String toString()
{
return "[" + type() + "]\r[" + path + "]\r[" + message + "]\r[" + value + "]\r";
}
/**
* @return String form of violation type
*/
public String type()
{
return constraintType.toString();
}
}
|
package org.jetbrains.kotlin.idea.stubindex;
import com.intellij.openapi.project.Project;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.psi.stubs.StubIndexKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.psi.KtNamedFunction;
import java.util.Collection;
/**
* Stores package top level function (both extension and non-extension) full qualified names.
*/
public class <API key> extends <API key><KtNamedFunction> {
private static final StubIndexKey<String, KtNamedFunction> KEY = KotlinIndexUtil.createIndexKey(<API key>.class);
private static final <API key> INSTANCE = new <API key>();
@NotNull
public static <API key> getInstance() {
return INSTANCE;
}
private <API key>() {
super(KtNamedFunction.class);
}
@NotNull
@Override
public StubIndexKey<String, KtNamedFunction> getKey() {
return KEY;
}
@NotNull
@Override
public Collection<KtNamedFunction> get(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) {
return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction.class);
}
// temporary hack, see comments in <API key> (<API key>.kt)
@NotNull
public Collection<KtNamedFunction> getNoScopeWrap(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) {
return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction.class);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.