text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>SSD1306 OLED display driver: lcd/lcd_pcd8544.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">SSD1306 OLED display driver
 <span id="projectnumber">1.8.2</span>
</div>
<div id="projectbrief">This library is developed to control SSD1306/SSD1331/SSD1351/IL9163/PCD8554 RGB i2c/spi LED displays</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_7539740a674fe554df3e16c8629ce56f.html">lcd</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">lcd_pcd8544.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include "<a class="el" href="io_8h_source.html">ssd1306_hal/io.h</a>"</code><br />
</div>
<p><a href="lcd__pcd8544_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr><td colspan="2"><div class="groupHeader"></div></td></tr>
<tr class="memitem:ga82a5ff26eaac6065f9fdf8e182e0c1a0"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="group___l_c_d___i_n_t_e_r_f_a_c_e___a_p_i.html#ga82a5ff26eaac6065f9fdf8e182e0c1a0">pcd8544_84x48_init</a> (void)</td></tr>
<tr class="memdesc:ga82a5ff26eaac6065f9fdf8e182e0c1a0"><td class="mdescLeft"> </td><td class="mdescRight">Inits 84x48 LED display (based on PCD8544 controller). <a href="group___l_c_d___i_n_t_e_r_f_a_c_e___a_p_i.html#ga82a5ff26eaac6065f9fdf8e182e0c1a0">More...</a><br /></td></tr>
<tr class="separator:ga82a5ff26eaac6065f9fdf8e182e0c1a0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga6e5fe50f6c6bae1adb75b0008880035d"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="group___l_c_d___i_n_t_e_r_f_a_c_e___a_p_i.html#ga6e5fe50f6c6bae1adb75b0008880035d">pcd8544_84x48_spi_init</a> (int8_t rstPin, int8_t cesPin, int8_t dcPin)</td></tr>
<tr class="separator:ga6e5fe50f6c6bae1adb75b0008880035d"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>support for LED 84x48 display (PCD8544) </p>
<p class="definition">Definition in file <a class="el" href="lcd__pcd8544_8h_source.html">lcd_pcd8544.h</a>.</p>
</div></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
</body>
</html>
| {'content_hash': '42c02af69b752c530d61fad0a4fa6f6a', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 346, 'avg_line_length': 50.520833333333336, 'alnum_prop': 0.6934020618556701, 'repo_name': 'lexus2k/ssd1306', 'id': 'c520a8b5ffc08ac1a9e1ce689c850450a1df15dc', 'size': '4850', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/lcd__pcd8544_8h.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '3577'}, {'name': 'C', 'bytes': '675386'}, {'name': 'C++', 'bytes': '181684'}, {'name': 'CMake', 'bytes': '390'}, {'name': 'Makefile', 'bytes': '5178'}, {'name': 'Python', 'bytes': '31917'}, {'name': 'Shell', 'bytes': '6136'}]} |
SYNONYM
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'b7dc9809a9b26e36d082b78f20748520', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.7218045112781954, 'repo_name': 'mdoering/backbone', 'id': 'cac5dc8ffb47b7b391c9fd46a583240acfb341f9', 'size': '185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Iodanthus/Iodanthus pinnatifidus/ Syn. Hesperis pinnatifidus/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Thu Apr 28 18:37:32 UTC 2016 -->
<title>Cassandra.AsyncClient.remove_counter_call (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Cassandra.AsyncClient.remove_counter_call (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Cassandra.AsyncClient.remove_counter_call.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.set_cql_version_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_counter_call.html" target="_top">Frames</a></li>
<li><a href="Cassandra.AsyncClient.remove_counter_call.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_classes_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Nested</a> | </li>
<li><a href="#fields_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.thrift</div>
<h2 title="Class Cassandra.AsyncClient.remove_counter_call" class="title">Class Cassandra.AsyncClient.remove_counter_call</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.thrift.async.TAsyncMethodCall</li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.thrift.Cassandra.AsyncClient.remove_counter_call</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.html" title="class in org.apache.cassandra.thrift">Cassandra.AsyncClient</a></dd>
</dl>
<hr>
<br>
<pre>public static class <span class="strong">Cassandra.AsyncClient.remove_counter_call</span>
extends org.apache.thrift.async.TAsyncMethodCall</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class org.apache.thrift.async.TAsyncMethodCall</h3>
<code>org.apache.thrift.async.TAsyncMethodCall.State</code></li>
</ul>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.thrift.async.TAsyncMethodCall</h3>
<code>client, transport</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_counter_call.html#Cassandra.AsyncClient.remove_counter_call(java.nio.ByteBuffer, org.apache.cassandra.thrift.ColumnPath, org.apache.cassandra.thrift.ConsistencyLevel, org.apache.thrift.async.AsyncMethodCallback, org.apache.thrift.async.TAsyncClient, org.apache.thrift.protocol.TProtocolFactory, org.apache.thrift.transport.TNonblockingTransport)">Cassandra.AsyncClient.remove_counter_call</a></strong>(java.nio.ByteBuffer key,
<a href="../../../../org/apache/cassandra/thrift/ColumnPath.html" title="class in org.apache.cassandra.thrift">ColumnPath</a> path,
<a href="../../../../org/apache/cassandra/thrift/ConsistencyLevel.html" title="enum in org.apache.cassandra.thrift">ConsistencyLevel</a> consistency_level,
org.apache.thrift.async.AsyncMethodCallback resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.TNonblockingTransport transport)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_counter_call.html#getResult()">getResult</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_counter_call.html#write_args(org.apache.thrift.protocol.TProtocol)">write_args</a></strong>(org.apache.thrift.protocol.TProtocol prot)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.thrift.async.TAsyncMethodCall</h3>
<code>getClient, getFrameBuffer, getSequenceId, getStartTime, getState, getTimeoutTimestamp, hasTimeout, isFinished, onError, prepareMethodCall, transition</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Cassandra.AsyncClient.remove_counter_call(java.nio.ByteBuffer, org.apache.cassandra.thrift.ColumnPath, org.apache.cassandra.thrift.ConsistencyLevel, org.apache.thrift.async.AsyncMethodCallback, org.apache.thrift.async.TAsyncClient, org.apache.thrift.protocol.TProtocolFactory, org.apache.thrift.transport.TNonblockingTransport)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Cassandra.AsyncClient.remove_counter_call</h4>
<pre>public Cassandra.AsyncClient.remove_counter_call(java.nio.ByteBuffer key,
<a href="../../../../org/apache/cassandra/thrift/ColumnPath.html" title="class in org.apache.cassandra.thrift">ColumnPath</a> path,
<a href="../../../../org/apache/cassandra/thrift/ConsistencyLevel.html" title="enum in org.apache.cassandra.thrift">ConsistencyLevel</a> consistency_level,
org.apache.thrift.async.AsyncMethodCallback resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.TNonblockingTransport transport)
throws org.apache.thrift.TException</pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>org.apache.thrift.TException</code></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="write_args(org.apache.thrift.protocol.TProtocol)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>write_args</h4>
<pre>public void write_args(org.apache.thrift.protocol.TProtocol prot)
throws org.apache.thrift.TException</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>write_args</code> in class <code>org.apache.thrift.async.TAsyncMethodCall</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>org.apache.thrift.TException</code></dd></dl>
</li>
</ul>
<a name="getResult()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getResult</h4>
<pre>public void getResult()
throws <a href="../../../../org/apache/cassandra/thrift/InvalidRequestException.html" title="class in org.apache.cassandra.thrift">InvalidRequestException</a>,
<a href="../../../../org/apache/cassandra/thrift/UnavailableException.html" title="class in org.apache.cassandra.thrift">UnavailableException</a>,
<a href="../../../../org/apache/cassandra/thrift/TimedOutException.html" title="class in org.apache.cassandra.thrift">TimedOutException</a>,
org.apache.thrift.TException</pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../org/apache/cassandra/thrift/InvalidRequestException.html" title="class in org.apache.cassandra.thrift">InvalidRequestException</a></code></dd>
<dd><code><a href="../../../../org/apache/cassandra/thrift/UnavailableException.html" title="class in org.apache.cassandra.thrift">UnavailableException</a></code></dd>
<dd><code><a href="../../../../org/apache/cassandra/thrift/TimedOutException.html" title="class in org.apache.cassandra.thrift">TimedOutException</a></code></dd>
<dd><code>org.apache.thrift.TException</code></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Cassandra.AsyncClient.remove_counter_call.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.set_cql_version_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_counter_call.html" target="_top">Frames</a></li>
<li><a href="Cassandra.AsyncClient.remove_counter_call.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_classes_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Nested</a> | </li>
<li><a href="#fields_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| {'content_hash': '8beaf5fa2d5d4d1a27dc9fa10af2b47a', 'timestamp': '', 'source': 'github', 'line_count': 346, 'max_line_length': 542, 'avg_line_length': 44.77745664739884, 'alnum_prop': 0.6582972955528303, 'repo_name': 'elisska/cloudera-cassandra', 'id': '12669ba65818440faf3e73919b216b100da37980', 'size': '15493', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DATASTAX_CASSANDRA-2.2.6/javadoc/org/apache/cassandra/thrift/Cassandra.AsyncClient.remove_counter_call.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '75145'}, {'name': 'CSS', 'bytes': '4112'}, {'name': 'HTML', 'bytes': '331372'}, {'name': 'PowerShell', 'bytes': '77673'}, {'name': 'Python', 'bytes': '979128'}, {'name': 'Shell', 'bytes': '143685'}, {'name': 'Thrift', 'bytes': '80564'}]} |
struct Sentence {
char **szSentence; // array of strings representing individual words
int iLength; // length of szSentence (number of array elements)
int iReturnValue; // return value of sentence reads from API
};
struct Block {
struct Sentence **stSentence;
int iLength;
};
// endianness variable...global
int iLittleEndian;
// API specific functions
int apiConnect(char *, int);
void apiDisconnect(int);
int login(int, char *, char *);
void writeLen(int, int);
int readLen(int);
void writeWord(int, char *);
char *readWord(int);
// API helper functions to make things a little bit easier
void initializeSentence(struct Sentence *);
void clearSentence(struct Sentence *);
void writeSentence(int, struct Sentence *);
struct Sentence readSentence(int);
void printSentence(struct Sentence *);
void addWordToSentence(struct Sentence *, char *);
void addPartWordToSentence(struct Sentence *, char *);
void initializeBlock(struct Block *);
void clearBlock(struct Block *);
struct Block readBlock(int);
void addSentenceToBlock(struct Block *, struct Sentence *);
void printBlock(struct Block *);
// MD5 helper functions
char *md5DigestToHexString(md5_byte_t *);
char *md5ToBinary(char *);
char hexStringToChar(char *);
// Endian tests
int isLittleEndian(void);
| {'content_hash': '00d840184bcff281d5f5dee2b5454941', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 80, 'avg_line_length': 29.4, 'alnum_prop': 0.7248677248677249, 'repo_name': 'Devronium/ConceptApplicationServer', 'id': '20374dd0d1e356563a5c3e7371f0b300107221d4', 'size': '1419', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/standard.net.routeros/src/mikrotik-api.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '156546'}, {'name': 'Batchfile', 'bytes': '5629'}, {'name': 'C', 'bytes': '23814868'}, {'name': 'C++', 'bytes': '9045245'}, {'name': 'CSS', 'bytes': '689616'}, {'name': 'HTML', 'bytes': '27027035'}, {'name': 'JavaScript', 'bytes': '3907862'}, {'name': 'M4', 'bytes': '126426'}, {'name': 'Makefile', 'bytes': '6102928'}, {'name': 'PHP', 'bytes': '11766'}, {'name': 'Roff', 'bytes': '10803'}, {'name': 'SCSS', 'bytes': '2187'}, {'name': 'Shell', 'bytes': '7230107'}, {'name': 'Smarty', 'bytes': '83738'}, {'name': 'XSLT', 'bytes': '16139'}]} |
In it's current form, this is a VN engine with some development tools
that were made to allow a number of people who wanted to build a game
to do just that!
Hell's Angel was planned to be a game where you somehow find a devil girl
in your care. The idea was that neither of you knew where she came from,
but if she was going to live with you, she was going to have to live
under your rules.
This repo is currently dormant, but if there is interest to make
something with it, maybe I'll just have to continue to build the tools to
do so..!
[](https://travis-ci.org/d-evelopers/HellsAngel)
## Prerequisates ##
You will first need [Node.js](https://nodejs.org/en/) insatlled on
your system to develop or use Hell's Angel.
...and if you wish to contribute changes, you will also need
[Git](https://git-scm.com/) installed.
## Installing ##
First thing you'll need to do is get the codebase from
[GitHub](https://github.com/d-evelopers/HellsAngel).
You can either download a ZIP containing the code from the above
linked page, or by running the following command in the folder you
want to download the code to:
```sh
git clone https://github.com/d-evelopers/HellsAngel.git
```
And then, when you are in the folder, run the command:
```sh
npm install
```
This will download all of the things needed to run and develop Hell's
Angel.
After that, you have two choices, you can either run the program
normally like so:
```sh
npm start
```
Or, you can run it in debug mode like:
```sh
npm run dev
```
In addition to starting the game, this will:
- Show the menubar of the application (Allowing access to the Blink
devtools)
- ...and drop the console to a REPL
In the REPL, you can type `reactionEditor()` to open the respective
window, or `help()` to get a list of the things you can use. (There is
Tab completion so you can explore..!)
## Troubleshooting ##
This section is for common questions about getting things up and
running. If I get asked a question that isn't in this section
enough--I'll add it..!
### Halp! `git pull` broke something! ###
Usually, this is because of a dependency change and can usually be
fixed with `npm update`.
If that does not solve it, copy any files you have added that you want
to keep, run `git clean -df` and then `npm install`.
If that doesn't do it either... Post a
[bug](https://github.com/d-evelopers/HellsAngel/issues), and I'll see
what I can do for you!
| {'content_hash': '971857de3ccbf1abfc9ef6c63e3187f6', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 127, 'avg_line_length': 33.13333333333333, 'alnum_prop': 0.7420523138832998, 'repo_name': 'd-evelopers/HellsAngel', 'id': '1168f426d70e8559827f331e7de2ba95037cd974', 'size': '2502', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4494'}, {'name': 'HTML', 'bytes': '3718'}, {'name': 'JavaScript', 'bytes': '26242'}]} |
import numpy as np
import pytest
import pandas as pd
import pandas.util.testing as tm
@pytest.mark.filterwarnings("ignore:Sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:Series.to_sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
class TestPivotTable:
def setup_method(self, method):
rs = np.random.RandomState(0)
self.dense = pd.DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "three", "two", "two", "one", "three"],
"C": rs.randn(8),
"D": rs.randn(8),
"E": [np.nan, np.nan, 1, 2, np.nan, 1, np.nan, np.nan],
}
)
self.sparse = self.dense.to_sparse()
def test_pivot_table(self):
res_sparse = pd.pivot_table(self.sparse, index="A", columns="B", values="C")
res_dense = pd.pivot_table(self.dense, index="A", columns="B", values="C")
tm.assert_frame_equal(res_sparse, res_dense)
res_sparse = pd.pivot_table(self.sparse, index="A", columns="B", values="E")
res_dense = pd.pivot_table(self.dense, index="A", columns="B", values="E")
tm.assert_frame_equal(res_sparse, res_dense)
res_sparse = pd.pivot_table(
self.sparse, index="A", columns="B", values="E", aggfunc="mean"
)
res_dense = pd.pivot_table(
self.dense, index="A", columns="B", values="E", aggfunc="mean"
)
tm.assert_frame_equal(res_sparse, res_dense)
def test_pivot_table_with_nans(self):
res_sparse = pd.pivot_table(
self.sparse, index="A", columns="B", values="E", aggfunc="sum"
)
res_dense = pd.pivot_table(
self.dense, index="A", columns="B", values="E", aggfunc="sum"
)
tm.assert_frame_equal(res_sparse, res_dense)
def test_pivot_table_multi(self):
res_sparse = pd.pivot_table(
self.sparse, index="A", columns="B", values=["D", "E"]
)
res_dense = pd.pivot_table(
self.dense, index="A", columns="B", values=["D", "E"]
)
res_dense = res_dense.apply(lambda x: x.astype("Sparse[float64]"))
tm.assert_frame_equal(res_sparse, res_dense)
| {'content_hash': 'd0e9147e0191d0b2e4f6715970054a8a', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 84, 'avg_line_length': 39.152542372881356, 'alnum_prop': 0.5636363636363636, 'repo_name': 'kushalbhola/MyStuff', 'id': '880c1c55f9f79f02ffa3214094981d734be7a89c', 'size': '2310', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Practice/PythonApplication/env/Lib/site-packages/pandas/tests/sparse/test_pivot.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1330'}, {'name': 'C#', 'bytes': '332967'}, {'name': 'CSS', 'bytes': '1451'}, {'name': 'HTML', 'bytes': '7539'}, {'name': 'Java', 'bytes': '14860'}, {'name': 'JavaScript', 'bytes': '9843'}, {'name': 'Jupyter Notebook', 'bytes': '374013'}, {'name': 'PowerShell', 'bytes': '1448'}, {'name': 'Python', 'bytes': '6511820'}, {'name': 'Tcl', 'bytes': '24289'}, {'name': 'TypeScript', 'bytes': '15697'}]} |
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<p style= 'color:red'>Hello world!!!! This is HTML5 Boilerplate.</p><p
style = 'color:green'> This is also my first commit
change to this file! Huurayyy!</p>
<p><a href="https://www.youtube.com/">Fancy some youtube?</a
</p>
<br>This is a line break </br>
<h1>Biggest</h1>
<h2>Bigger</h2>
<h3>Big</h3>
<h4>Small</h4>
<h5>Smaller</h5>
<h6>Smallest</h6>
<ul>
<li>Milk</li>
<li>Eggs</li>
<li>Bacon</li>
<li>Cereal</li>
<li>Pancake Mix</li>
</ul>
<ol>
<li>Most Important</li>
<li>Important</li>
<li>Not as important</li>
</ol>
<ul>
<li><a href="http://www.crunchyroll.com">Crunchyroll</a></li>
<li><a href="http://www.njit.edu">NJIT</a></li>
<li><a href="http://www.google.com">Google</a></li>
</ul>
<img
src="http://planetagracza.pl/wp-content/uploads/2015/06/Zelda-TriForce-Heroes.jpg"/>
<table style="width:50%">
<tr>
<td>Last Name</td>
<td>First Name</td>
<td>Age</td>
<td>Location</td>
</tr>
<tr>
<td>Javier</td>
<td>Elvis</td>
<td>21</td>
<td>New Jersey, USA</td>
</tr>
<tr>
<td>Gonzalez</td>
<td>Jennifer</td>
<td>20</td>
<td>Ontario, Cannada</td>
</tr>
<table><tr><td><img src=
"http://www.legendra.com/media/artworks/3ds/the_legend_of_zelda__triforce_heroes/the_legend_of_zelda__triforce_heroes_art_25.jpg"/> </td></tr></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/{{JQUERY_VERSION}}/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-{{JQUERY_VERSION}}.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
| {'content_hash': '13b0cceacdb2d31031c43ac0bd5cf25a', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 187, 'avg_line_length': 33.806451612903224, 'alnum_prop': 0.5903307888040712, 'repo_name': 'elj4/IS117FINAL', 'id': '2bf84fca6bc97c21f36ea089c0797580096c2936', 'size': '3144', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '11364'}, {'name': 'HTML', 'bytes': '7520'}, {'name': 'JavaScript', 'bytes': '12259'}]} |
import type OneBlinkAPIClient from '../oneblink-api-client'
import chalk from 'chalk'
import inquirer from 'inquirer'
import ora from 'ora'
function confirm(
logger: typeof console,
force: boolean,
env: string,
): Promise<boolean> {
if (force) {
return Promise.resolve(true)
}
const promptQuestions = [
{
type: 'confirm',
name: 'confirmation',
message: chalk.yellow(
`Are you sure you want to teardown environment "${env}": [Y]`,
),
},
]
return inquirer
.prompt(promptQuestions)
.then((results) => results.confirmation)
}
async function teardown(
oneBlinkAPIClient: OneBlinkAPIClient,
apiId: string,
env: string,
): Promise<void> {
const spinner = ora(`Tearing down environment "${env}"...`).start()
try {
await oneBlinkAPIClient.deleteRequest(`/apis/${apiId}/environments/${env}`)
spinner.succeed(`Environment "${env}" has been torn down!`)
} catch (error) {
spinner.fail(`Tearing down environment "${env}" failed!`)
throw error
}
}
export { confirm, teardown }
| {'content_hash': 'cc0eed639e6fec881fc6875aa36d5b0b', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 79, 'avg_line_length': 24.204545454545453, 'alnum_prop': 0.6582159624413145, 'repo_name': 'blinkmobile/cli', 'id': 'a6795e0618f6d376731613d59af9d6296534845f', 'size': '1065', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/api/teardown.ts', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '198745'}]} |
import express from 'express';
import AuthHandler from '../security/authHandler';
import DrinkService from '../service/drinkService';
import ToppingService from '../service/toppingService';
import TableService from '../service/tableService';
import PizzaService from '../service/pizzaService';
import UserService from '../service/userService';
import LoginService from '../service/loginService';
import OrderService from '../service/orderService';
import ClientService from '../service/clientService';
import passport from 'passport';
const router = express.Router();
function getRouter() {
// Facebook authentication
router.get('/auth/facebook', passport.authenticate('facebook', { scope: 'email' }));
router.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), LoginService.handleFacebook);
// Admin authentication
router.post('/api/auth/login', LoginService.login);
router.post('/api/users', UserService.create);
// Clients
router.get('/api/clients', AuthHandler.authorizeRequest, ClientService.find);
// Drinks
router.get('/api/drinks', AuthHandler.authorizeRequest, DrinkService.find);
router.post('/api/drinks', AuthHandler.authorizeRequest, DrinkService.create);
router.put('/api/drinks/:id', AuthHandler.authorizeRequest, DrinkService.update);
router.delete('/api/drinks/:id', AuthHandler.authorizeRequest, DrinkService.remove);
// Toppings
router.get('/api/toppings', AuthHandler.authorizeRequest, ToppingService.find);
router.post('/api/toppings', AuthHandler.authorizeRequest, ToppingService.create);
router.put('/api/toppings/:id', AuthHandler.authorizeRequest, ToppingService.update);
router.delete('/api/toppings/:id', AuthHandler.authorizeRequest, ToppingService.remove);
// Pizzas
router.get('/api/pizzas', AuthHandler.authorizeRequest, PizzaService.find);
router.post('/api/pizzas', AuthHandler.authorizeRequest, PizzaService.create);
router.put('/api/pizzas/:id', AuthHandler.authorizeRequest, PizzaService.update);
router.delete('/api/pizzas/:id', AuthHandler.authorizeRequest, PizzaService.remove);
// Tables
router.get('/api/tables', AuthHandler.authorizeRequest, TableService.find);
// Orders
router.get('/api/orders/:id', AuthHandler.authorizeRequest, OrderService.findOrder);
router.get('/api/orders', AuthHandler.authorizeRequest, OrderService.findAll);
router.post('/api/orders', AuthHandler.authorizeRequest, OrderService.openOrder);
router.post('/api/orders/:id/pizzas', AuthHandler.authorizeRequest, OrderService.orderPizza);
router.post('/api/orders/:id/drinks', AuthHandler.authorizeRequest, OrderService.orderDrink);
router.delete('/api/orders/:id', AuthHandler.authorizeRequest, OrderService.endOrder);
return router;
}
export default getRouter; | {'content_hash': '7c06fa9120979df09e2fad0a5ccf8e17', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 132, 'avg_line_length': 47.68333333333333, 'alnum_prop': 0.7490387976232087, 'repo_name': 'auromota/easy-pizza-api', 'id': '605d4bc7b6821036d115f13c2d52eeb4744d6395', 'size': '2861', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/route/router.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1298'}, {'name': 'HTML', 'bytes': '36024'}, {'name': 'JavaScript', 'bytes': '59628'}]} |
package com.zuoxiaolong.blog.api.controller;
import com.zuoxiaolong.blog.common.authorization.CheckLogin;
import com.zuoxiaolong.blog.common.orm.DigitalPage;
import com.zuoxiaolong.blog.common.utils.ObjectUtils;
import com.zuoxiaolong.blog.common.utils.StringUtils;
import com.zuoxiaolong.blog.model.dto.MessageBoxDto;
import com.zuoxiaolong.blog.model.persistent.MessageBox;
import com.zuoxiaolong.blog.model.persistent.WebUser;
import com.zuoxiaolong.blog.service.MessageBoxService;
import com.zuoxiaolong.blog.service.WebUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author iCodingStar
* @date 2016/6/25 13:20
* @since 1.0.0
*/
@Controller
@RequestMapping("/MessageBox")
public class MessageBoxController extends AbstractApiController {
@Autowired
private MessageBoxService messageBoxService;
@Autowired
private WebUserService webUserService;
/***
* 查看信息箱消息内容
*
* @param id
* @return
*/
@RequestMapping(value = "/Content", method = RequestMethod.GET)
@CheckLogin
public MessageBoxDto getMessageContent(@RequestParam("id") Integer id) {
return messageBoxService.getMessageContentById(id);
}
/***
* 分页参看消息列表
*
* @param currentPageNumber
* @param pageSize
* @param type
* @param status
* @return
*/
@RequestMapping(value = "/List", method = RequestMethod.GET)
@CheckLogin
public DigitalPage getMessageList(@RequestParam(required = false) Integer currentPageNumber,
@RequestParam(required = false) Integer pageSize,
@RequestParam(required = false) Integer type,
@RequestParam(required = false) Integer status) {
return messageBoxService.getMessagesByPage(currentPageNumber, pageSize, type, getWebUserId(), status);
}
/***
* 发送短消息
*
* @param username
* @param messageBox
* @return
*/
@RequestMapping(value = "/Send", method = {RequestMethod.POST, RequestMethod.GET})
@CheckLogin
public Integer sendMessage(String username, MessageBox messageBox) {
messageBox.setSender(getWebUserId());
return messageBoxService.insertMessage(username, messageBox);
}
/***
* 修改短消息状态
* 0:已读
* 1:未读
* 2:已删除
*
* @param messageBox
* @return
*/
@RequestMapping(value = "/Update", method = {RequestMethod.POST, RequestMethod.GET})
public Integer updateMessageStatus(MessageBox messageBox) {
return messageBoxService.updateMessageStatus(messageBox);
}
}
| {'content_hash': 'f0fb57a99e43fda254147c6bd6410663', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 110, 'avg_line_length': 31.838709677419356, 'alnum_prop': 0.6933468422830125, 'repo_name': 'scott17090025902/everyone-java-blog', 'id': 'feb2625b7ac82dfcb3c544a0552185ed06a37131', 'size': '3653', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'blog-api/src/main/java/com/zuoxiaolong/blog/api/controller/MessageBoxController.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '195832'}, {'name': 'HTML', 'bytes': '94289'}, {'name': 'Java', 'bytes': '375045'}, {'name': 'JavaScript', 'bytes': '28298'}]} |
#pragma once
#include <pcl/recognition/quantizable_modality.h>
#include <pcl/recognition/distance_map.h>
#include <pcl/pcl_base.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/recognition/point_types.h>
namespace pcl
{
// --------------------------------------------------------------------------
template <typename PointInT>
class ColorModality
: public QuantizableModality, public PCLBase<PointInT>
{
protected:
using PCLBase<PointInT>::input_;
struct Candidate
{
float distance;
unsigned char bin_index;
size_t x;
size_t y;
bool
operator< (const Candidate & rhs)
{
return (distance > rhs.distance);
}
};
public:
using PointCloudIn = pcl::PointCloud<PointInT>;
ColorModality ();
virtual ~ColorModality ();
inline QuantizedMap &
getQuantizedMap ()
{
return (filtered_quantized_colors_);
}
inline QuantizedMap &
getSpreadedQuantizedMap ()
{
return (spreaded_filtered_quantized_colors_);
}
void
extractFeatures (const MaskMap & mask, size_t nr_features, size_t modalityIndex,
std::vector<QuantizedMultiModFeature> & features) const;
/** \brief Provide a pointer to the input dataset (overwrites the PCLBase::setInputCloud method)
* \param cloud the const boost shared pointer to a PointCloud message
*/
virtual void
setInputCloud (const typename PointCloudIn::ConstPtr & cloud)
{
input_ = cloud;
}
virtual void
processInputData ();
protected:
void
quantizeColors ();
void
filterQuantizedColors ();
static inline int
quantizeColorOnRGBExtrema (const float r,
const float g,
const float b);
void
computeDistanceMap (const MaskMap & input, DistanceMap & output) const;
private:
float feature_distance_threshold_;
pcl::QuantizedMap quantized_colors_;
pcl::QuantizedMap filtered_quantized_colors_;
pcl::QuantizedMap spreaded_filtered_quantized_colors_;
};
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
pcl::ColorModality<PointInT>::ColorModality ()
: feature_distance_threshold_ (1.0f), quantized_colors_ (), filtered_quantized_colors_ (), spreaded_filtered_quantized_colors_ ()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
pcl::ColorModality<PointInT>::~ColorModality ()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
void
pcl::ColorModality<PointInT>::processInputData ()
{
// quantize gradients
quantizeColors ();
// filter quantized gradients to get only dominants one + thresholding
filterQuantizedColors ();
// spread filtered quantized gradients
//spreadFilteredQunatizedColorGradients ();
const int spreading_size = 8;
pcl::QuantizedMap::spreadQuantizedMap (filtered_quantized_colors_,
spreaded_filtered_quantized_colors_, spreading_size);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
void pcl::ColorModality<PointInT>::extractFeatures (const MaskMap & mask,
const size_t nr_features,
const size_t modality_index,
std::vector<QuantizedMultiModFeature> & features) const
{
const size_t width = mask.getWidth ();
const size_t height = mask.getHeight ();
MaskMap mask_maps[8];
for (size_t map_index = 0; map_index < 8; ++map_index)
mask_maps[map_index].resize (width, height);
unsigned char map[255];
memset(map, 0, 255);
map[0x1<<0] = 0;
map[0x1<<1] = 1;
map[0x1<<2] = 2;
map[0x1<<3] = 3;
map[0x1<<4] = 4;
map[0x1<<5] = 5;
map[0x1<<6] = 6;
map[0x1<<7] = 7;
QuantizedMap distance_map_indices (width, height);
//memset (distance_map_indices.data, 0, sizeof (distance_map_indices.data[0])*width*height);
for (size_t row_index = 0; row_index < height; ++row_index)
{
for (size_t col_index = 0; col_index < width; ++col_index)
{
if (mask (col_index, row_index) != 0)
{
//const unsigned char quantized_value = quantized_surface_normals_ (row_index, col_index);
const unsigned char quantized_value = filtered_quantized_colors_ (col_index, row_index);
if (quantized_value == 0)
continue;
const int dist_map_index = map[quantized_value];
distance_map_indices (col_index, row_index) = dist_map_index;
//distance_maps[dist_map_index].at<unsigned char>(row_index, col_index) = 255;
mask_maps[dist_map_index] (col_index, row_index) = 255;
}
}
}
DistanceMap distance_maps[8];
for (int map_index = 0; map_index < 8; ++map_index)
computeDistanceMap (mask_maps[map_index], distance_maps[map_index]);
std::list<Candidate> list1;
std::list<Candidate> list2;
float weights[8] = {0,0,0,0,0,0,0,0};
const size_t off = 4;
for (size_t row_index = off; row_index < height-off; ++row_index)
{
for (size_t col_index = off; col_index < width-off; ++col_index)
{
if (mask (col_index, row_index) != 0)
{
//const unsigned char quantized_value = quantized_surface_normals_ (row_index, col_index);
const unsigned char quantized_value = filtered_quantized_colors_ (col_index, row_index);
//const float nx = surface_normals_ (col_index, row_index).normal_x;
//const float ny = surface_normals_ (col_index, row_index).normal_y;
//const float nz = surface_normals_ (col_index, row_index).normal_z;
if (quantized_value != 0)
{
const int distance_map_index = map[quantized_value];
//const float distance = distance_maps[distance_map_index].at<float> (row_index, col_index);
const float distance = distance_maps[distance_map_index] (col_index, row_index);
if (distance >= feature_distance_threshold_)
{
Candidate candidate;
candidate.distance = distance;
candidate.x = col_index;
candidate.y = row_index;
candidate.bin_index = distance_map_index;
list1.push_back (candidate);
++weights[distance_map_index];
}
}
}
}
}
for (typename std::list<Candidate>::iterator iter = list1.begin (); iter != list1.end (); ++iter)
iter->distance *= 1.0f / weights[iter->bin_index];
list1.sort ();
if (list1.size () <= nr_features)
{
features.reserve (list1.size ());
for (typename std::list<Candidate>::iterator iter = list1.begin (); iter != list1.end (); ++iter)
{
QuantizedMultiModFeature feature;
feature.x = static_cast<int> (iter->x);
feature.y = static_cast<int> (iter->y);
feature.modality_index = modality_index;
feature.quantized_value = filtered_quantized_colors_ (iter->x, iter->y);
features.push_back (feature);
}
return;
}
int distance = static_cast<int> (list1.size () / nr_features + 1); // ??? @todo:!:!:!:!:!:!
while (list2.size () != nr_features)
{
const int sqr_distance = distance*distance;
for (typename std::list<Candidate>::iterator iter1 = list1.begin (); iter1 != list1.end (); ++iter1)
{
bool candidate_accepted = true;
for (typename std::list<Candidate>::iterator iter2 = list2.begin (); iter2 != list2.end (); ++iter2)
{
const int dx = static_cast<int> (iter1->x) - static_cast<int> (iter2->x);
const int dy = static_cast<int> (iter1->y) - static_cast<int> (iter2->y);
const int tmp_distance = dx*dx + dy*dy;
if (tmp_distance < sqr_distance)
{
candidate_accepted = false;
break;
}
}
if (candidate_accepted)
list2.push_back (*iter1);
if (list2.size () == nr_features) break;
}
--distance;
}
for (typename std::list<Candidate>::iterator iter2 = list2.begin (); iter2 != list2.end (); ++iter2)
{
QuantizedMultiModFeature feature;
feature.x = static_cast<int> (iter2->x);
feature.y = static_cast<int> (iter2->y);
feature.modality_index = modality_index;
feature.quantized_value = filtered_quantized_colors_ (iter2->x, iter2->y);
features.push_back (feature);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
void
pcl::ColorModality<PointInT>::quantizeColors ()
{
const size_t width = input_->width;
const size_t height = input_->height;
quantized_colors_.resize (width, height);
for (size_t row_index = 0; row_index < height; ++row_index)
{
for (size_t col_index = 0; col_index < width; ++col_index)
{
const float r = static_cast<float> ((*input_) (col_index, row_index).r);
const float g = static_cast<float> ((*input_) (col_index, row_index).g);
const float b = static_cast<float> ((*input_) (col_index, row_index).b);
quantized_colors_ (col_index, row_index) = quantizeColorOnRGBExtrema (r, g, b);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
void
pcl::ColorModality<PointInT>::filterQuantizedColors ()
{
const size_t width = input_->width;
const size_t height = input_->height;
filtered_quantized_colors_.resize (width, height);
// filter data
for (size_t row_index = 1; row_index < height-1; ++row_index)
{
for (size_t col_index = 1; col_index < width-1; ++col_index)
{
unsigned char histogram[8] = {0,0,0,0,0,0,0,0};
{
const unsigned char * data_ptr = quantized_colors_.getData () + (row_index-1)*width+col_index-1;
assert (0 <= data_ptr[0] && data_ptr[0] < 9 &&
0 <= data_ptr[1] && data_ptr[1] < 9 &&
0 <= data_ptr[2] && data_ptr[2] < 9);
++histogram[data_ptr[0]];
++histogram[data_ptr[1]];
++histogram[data_ptr[2]];
}
{
const unsigned char * data_ptr = quantized_colors_.getData () + row_index*width+col_index-1;
assert (0 <= data_ptr[0] && data_ptr[0] < 9 &&
0 <= data_ptr[1] && data_ptr[1] < 9 &&
0 <= data_ptr[2] && data_ptr[2] < 9);
++histogram[data_ptr[0]];
++histogram[data_ptr[1]];
++histogram[data_ptr[2]];
}
{
const unsigned char * data_ptr = quantized_colors_.getData () + (row_index+1)*width+col_index-1;
assert (0 <= data_ptr[0] && data_ptr[0] < 9 &&
0 <= data_ptr[1] && data_ptr[1] < 9 &&
0 <= data_ptr[2] && data_ptr[2] < 9);
++histogram[data_ptr[0]];
++histogram[data_ptr[1]];
++histogram[data_ptr[2]];
}
unsigned char max_hist_value = 0;
int max_hist_index = -1;
// for (int i = 0; i < 8; ++i)
// {
// if (max_hist_value < histogram[i+1])
// {
// max_hist_index = i;
// max_hist_value = histogram[i+1]
// }
// }
// Unrolled for performance optimization:
if (max_hist_value < histogram[0]) {max_hist_index = 0; max_hist_value = histogram[0];}
if (max_hist_value < histogram[1]) {max_hist_index = 1; max_hist_value = histogram[1];}
if (max_hist_value < histogram[2]) {max_hist_index = 2; max_hist_value = histogram[2];}
if (max_hist_value < histogram[3]) {max_hist_index = 3; max_hist_value = histogram[3];}
if (max_hist_value < histogram[4]) {max_hist_index = 4; max_hist_value = histogram[4];}
if (max_hist_value < histogram[5]) {max_hist_index = 5; max_hist_value = histogram[5];}
if (max_hist_value < histogram[6]) {max_hist_index = 6; max_hist_value = histogram[6];}
if (max_hist_value < histogram[7]) {max_hist_index = 7; max_hist_value = histogram[7];}
//if (max_hist_index != -1 && max_hist_value >= 5)
filtered_quantized_colors_ (col_index, row_index) = 0x1 << max_hist_index;
//else
// filtered_quantized_color_gradients_ (col_index, row_index) = 0;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT>
int
pcl::ColorModality<PointInT>::quantizeColorOnRGBExtrema (const float r,
const float g,
const float b)
{
const float r_inv = 255.0f-r;
const float g_inv = 255.0f-g;
const float b_inv = 255.0f-b;
const float dist_0 = (r*r + g*g + b*b)*2.0f;
const float dist_1 = r*r + g*g + b_inv*b_inv;
const float dist_2 = r*r + g_inv*g_inv+ b*b;
const float dist_3 = r*r + g_inv*g_inv + b_inv*b_inv;
const float dist_4 = r_inv*r_inv + g*g + b*b;
const float dist_5 = r_inv*r_inv + g*g + b_inv*b_inv;
const float dist_6 = r_inv*r_inv + g_inv*g_inv+ b*b;
const float dist_7 = (r_inv*r_inv + g_inv*g_inv + b_inv*b_inv)*1.5f;
const float min_dist = std::min (std::min (std::min (dist_0, dist_1), std::min (dist_2, dist_3)), std::min (std::min (dist_4, dist_5), std::min (dist_6, dist_7)));
if (min_dist == dist_0)
{
return 0;
}
if (min_dist == dist_1)
{
return 1;
}
if (min_dist == dist_2)
{
return 2;
}
if (min_dist == dist_3)
{
return 3;
}
if (min_dist == dist_4)
{
return 4;
}
if (min_dist == dist_5)
{
return 5;
}
if (min_dist == dist_6)
{
return 6;
}
return 7;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ColorModality<PointInT>::computeDistanceMap (const MaskMap & input,
DistanceMap & output) const
{
const size_t width = input.getWidth ();
const size_t height = input.getHeight ();
output.resize (width, height);
// compute distance map
//float *distance_map = new float[input_->points.size ()];
const unsigned char * mask_map = input.getData ();
float * distance_map = output.getData ();
for (size_t index = 0; index < width*height; ++index)
{
if (mask_map[index] == 0)
distance_map[index] = 0.0f;
else
distance_map[index] = static_cast<float> (width + height);
}
// first pass
float * previous_row = distance_map;
float * current_row = previous_row + width;
for (size_t ri = 1; ri < height; ++ri)
{
for (size_t ci = 1; ci < width; ++ci)
{
const float up_left = previous_row [ci - 1] + 1.4f; //distance_map[(ri-1)*input_->width + ci-1] + 1.4f;
const float up = previous_row [ci] + 1.0f; //distance_map[(ri-1)*input_->width + ci] + 1.0f;
const float up_right = previous_row [ci + 1] + 1.4f; //distance_map[(ri-1)*input_->width + ci+1] + 1.4f;
const float left = current_row [ci - 1] + 1.0f; //distance_map[ri*input_->width + ci-1] + 1.0f;
const float center = current_row [ci]; //distance_map[ri*input_->width + ci];
const float min_value = std::min (std::min (up_left, up), std::min (left, up_right));
if (min_value < center)
current_row[ci] = min_value; //distance_map[ri * input_->width + ci] = min_value;
}
previous_row = current_row;
current_row += width;
}
// second pass
float * next_row = distance_map + width * (height - 1);
current_row = next_row - width;
for (int ri = static_cast<int> (height)-2; ri >= 0; --ri)
{
for (int ci = static_cast<int> (width)-2; ci >= 0; --ci)
{
const float lower_left = next_row [ci - 1] + 1.4f; //distance_map[(ri+1)*input_->width + ci-1] + 1.4f;
const float lower = next_row [ci] + 1.0f; //distance_map[(ri+1)*input_->width + ci] + 1.0f;
const float lower_right = next_row [ci + 1] + 1.4f; //distance_map[(ri+1)*input_->width + ci+1] + 1.4f;
const float right = current_row [ci + 1] + 1.0f; //distance_map[ri*input_->width + ci+1] + 1.0f;
const float center = current_row [ci]; //distance_map[ri*input_->width + ci];
const float min_value = std::min (std::min (lower_left, lower), std::min (right, lower_right));
if (min_value < center)
current_row[ci] = min_value; //distance_map[ri*input_->width + ci] = min_value;
}
next_row = current_row;
current_row -= width;
}
}
| {'content_hash': 'a7a5b86938dac6b96f4dcb2a6e415f0f', 'timestamp': '', 'source': 'github', 'line_count': 513, 'max_line_length': 165, 'avg_line_length': 32.85575048732944, 'alnum_prop': 0.550815781667161, 'repo_name': 'drmateo/pcl', 'id': '975e2d46b848bfe60bdd0fad49a2b28a87da3328', 'size': '18586', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'recognition/include/pcl/recognition/color_modality.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '172874'}, {'name': 'C++', 'bytes': '19619498'}, {'name': 'CMake', 'bytes': '440645'}, {'name': 'Cuda', 'bytes': '923615'}, {'name': 'GLSL', 'bytes': '2653'}, {'name': 'Matlab', 'bytes': '3407'}, {'name': 'Objective-C', 'bytes': '5638'}, {'name': 'Objective-C++', 'bytes': '7489'}, {'name': 'Python', 'bytes': '29169'}, {'name': 'Shell', 'bytes': '9857'}]} |
#ifndef _DCCP_H
#define _DCCP_H
#include <linux/dccp.h>
#include <net/snmp.h>
#include <net/sock.h>
#include <net/tcp.h>
#include "ackvec.h"
/*
* DCCP - specific warning and debugging macros.
*/
#define DCCP_WARN(fmt, a...) LIMIT_NETDEBUG(KERN_WARNING "%s: " fmt, \
__FUNCTION__, ##a)
#define DCCP_CRIT(fmt, a...) printk(KERN_CRIT fmt " at %s:%d/%s()\n", ##a, \
__FILE__, __LINE__, __FUNCTION__)
#define DCCP_BUG(a...) do { DCCP_CRIT("BUG: " a); dump_stack(); } while(0)
#define DCCP_BUG_ON(cond) do { if (unlikely((cond) != 0)) \
DCCP_BUG("\"%s\" holds (exception!)", \
__stringify(cond)); \
} while (0)
#ifdef MODULE
#define DCCP_PRINTK(enable, fmt, args...) do { if (enable) \
printk(fmt, ##args); \
} while(0)
#else
#define DCCP_PRINTK(enable, fmt, args...) printk(fmt, ##args)
#endif
#define DCCP_PR_DEBUG(enable, fmt, a...) DCCP_PRINTK(enable, KERN_DEBUG \
"%s: " fmt, __FUNCTION__, ##a)
#ifdef CONFIG_IP_DCCP_DEBUG
extern int dccp_debug;
#define dccp_pr_debug(format, a...) DCCP_PR_DEBUG(dccp_debug, format, ##a)
#define dccp_pr_debug_cat(format, a...) DCCP_PRINTK(dccp_debug, format, ##a)
#else
#define dccp_pr_debug(format, a...)
#define dccp_pr_debug_cat(format, a...)
#endif
extern struct inet_hashinfo dccp_hashinfo;
extern atomic_t dccp_orphan_count;
extern void dccp_time_wait(struct sock *sk, int state, int timeo);
/*
* Set safe upper bounds for header and option length. Since Data Offset is 8
* bits (RFC 4340, sec. 5.1), the total header length can never be more than
* 4 * 255 = 1020 bytes. The largest possible header length is 28 bytes (X=1):
* - DCCP-Response with ACK Subheader and 4 bytes of Service code OR
* - DCCP-Reset with ACK Subheader and 4 bytes of Reset Code fields
* Hence a safe upper bound for the maximum option length is 1020-28 = 992
*/
#define MAX_DCCP_SPECIFIC_HEADER (255 * sizeof(int))
#define DCCP_MAX_PACKET_HDR 28
#define DCCP_MAX_OPT_LEN (MAX_DCCP_SPECIFIC_HEADER - DCCP_MAX_PACKET_HDR)
#define MAX_DCCP_HEADER (MAX_DCCP_SPECIFIC_HEADER + MAX_HEADER)
#define DCCP_TIMEWAIT_LEN (60 * HZ) /* how long to wait to destroy TIME-WAIT
* state, about 60 seconds */
/* RFC 1122, 4.2.3.1 initial RTO value */
#define DCCP_TIMEOUT_INIT ((unsigned)(3 * HZ))
/* Maximal interval between probes for local resources. */
#define DCCP_RESOURCE_PROBE_INTERVAL ((unsigned)(HZ / 2U))
#define DCCP_RTO_MAX ((unsigned)(120 * HZ)) /* FIXME: using TCP value */
/* sysctl variables for DCCP */
extern int sysctl_dccp_request_retries;
extern int sysctl_dccp_retries1;
extern int sysctl_dccp_retries2;
extern int sysctl_dccp_feat_sequence_window;
extern int sysctl_dccp_feat_rx_ccid;
extern int sysctl_dccp_feat_tx_ccid;
extern int sysctl_dccp_feat_ack_ratio;
extern int sysctl_dccp_feat_send_ack_vector;
extern int sysctl_dccp_feat_send_ndp_count;
extern int sysctl_dccp_tx_qlen;
/* is seq1 < seq2 ? */
static inline int before48(const u64 seq1, const u64 seq2)
{
return (s64)((seq1 << 16) - (seq2 << 16)) < 0;
}
/* is seq1 > seq2 ? */
static inline int after48(const u64 seq1, const u64 seq2)
{
return (s64)((seq2 << 16) - (seq1 << 16)) < 0;
}
/* is seq2 <= seq1 <= seq3 ? */
static inline int between48(const u64 seq1, const u64 seq2, const u64 seq3)
{
return (seq3 << 16) - (seq2 << 16) >= (seq1 << 16) - (seq2 << 16);
}
static inline u64 max48(const u64 seq1, const u64 seq2)
{
return after48(seq1, seq2) ? seq1 : seq2;
}
/* is seq1 next seqno after seq2 */
static inline int follows48(const u64 seq1, const u64 seq2)
{
int diff = (seq1 & 0xFFFF) - (seq2 & 0xFFFF);
return diff==1;
}
enum {
DCCP_MIB_NUM = 0,
DCCP_MIB_ACTIVEOPENS, /* ActiveOpens */
DCCP_MIB_ESTABRESETS, /* EstabResets */
DCCP_MIB_CURRESTAB, /* CurrEstab */
DCCP_MIB_OUTSEGS, /* OutSegs */
DCCP_MIB_OUTRSTS,
DCCP_MIB_ABORTONTIMEOUT,
DCCP_MIB_TIMEOUTS,
DCCP_MIB_ABORTFAILED,
DCCP_MIB_PASSIVEOPENS,
DCCP_MIB_ATTEMPTFAILS,
DCCP_MIB_OUTDATAGRAMS,
DCCP_MIB_INERRS,
DCCP_MIB_OPTMANDATORYERROR,
DCCP_MIB_INVALIDOPT,
__DCCP_MIB_MAX
};
#define DCCP_MIB_MAX __DCCP_MIB_MAX
struct dccp_mib {
unsigned long mibs[DCCP_MIB_MAX];
} __SNMP_MIB_ALIGN__;
DECLARE_SNMP_STAT(struct dccp_mib, dccp_statistics);
#define DCCP_INC_STATS(field) SNMP_INC_STATS(dccp_statistics, field)
#define DCCP_INC_STATS_BH(field) SNMP_INC_STATS_BH(dccp_statistics, field)
#define DCCP_INC_STATS_USER(field) SNMP_INC_STATS_USER(dccp_statistics, field)
#define DCCP_DEC_STATS(field) SNMP_DEC_STATS(dccp_statistics, field)
#define DCCP_ADD_STATS_BH(field, val) \
SNMP_ADD_STATS_BH(dccp_statistics, field, val)
#define DCCP_ADD_STATS_USER(field, val) \
SNMP_ADD_STATS_USER(dccp_statistics, field, val)
/*
* Checksumming routines
*/
static inline int dccp_csum_coverage(const struct sk_buff *skb)
{
const struct dccp_hdr* dh = dccp_hdr(skb);
if (dh->dccph_cscov == 0)
return skb->len;
return (dh->dccph_doff + dh->dccph_cscov - 1) * sizeof(u32);
}
static inline void dccp_csum_outgoing(struct sk_buff *skb)
{
int cov = dccp_csum_coverage(skb);
if (cov >= skb->len)
dccp_hdr(skb)->dccph_cscov = 0;
skb->csum = skb_checksum(skb, 0, (cov > skb->len)? skb->len : cov, 0);
}
extern void dccp_v4_send_check(struct sock *sk, int len, struct sk_buff *skb);
extern int dccp_retransmit_skb(struct sock *sk, struct sk_buff *skb);
extern void dccp_send_ack(struct sock *sk);
extern void dccp_send_delayed_ack(struct sock *sk);
extern void dccp_reqsk_send_ack(struct sk_buff *sk, struct request_sock *rsk);
extern void dccp_send_sync(struct sock *sk, const u64 seq,
const enum dccp_pkt_type pkt_type);
extern void dccp_write_xmit(struct sock *sk, int block);
extern void dccp_write_space(struct sock *sk);
extern void dccp_init_xmit_timers(struct sock *sk);
static inline void dccp_clear_xmit_timers(struct sock *sk)
{
inet_csk_clear_xmit_timers(sk);
}
extern unsigned int dccp_sync_mss(struct sock *sk, u32 pmtu);
extern const char *dccp_packet_name(const int type);
extern const char *dccp_state_name(const int state);
extern void dccp_set_state(struct sock *sk, const int state);
extern void dccp_done(struct sock *sk);
extern void dccp_reqsk_init(struct request_sock *req, struct sk_buff *skb);
extern int dccp_v4_conn_request(struct sock *sk, struct sk_buff *skb);
extern struct sock *dccp_create_openreq_child(struct sock *sk,
const struct request_sock *req,
const struct sk_buff *skb);
extern int dccp_v4_do_rcv(struct sock *sk, struct sk_buff *skb);
extern struct sock *dccp_v4_request_recv_sock(struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst);
extern struct sock *dccp_check_req(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct request_sock **prev);
extern int dccp_child_process(struct sock *parent, struct sock *child,
struct sk_buff *skb);
extern int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
struct dccp_hdr *dh, unsigned len);
extern int dccp_rcv_established(struct sock *sk, struct sk_buff *skb,
const struct dccp_hdr *dh, const unsigned len);
extern int dccp_init_sock(struct sock *sk, const __u8 ctl_sock_initialized);
extern int dccp_destroy_sock(struct sock *sk);
extern void dccp_close(struct sock *sk, long timeout);
extern struct sk_buff *dccp_make_response(struct sock *sk,
struct dst_entry *dst,
struct request_sock *req);
extern int dccp_connect(struct sock *sk);
extern int dccp_disconnect(struct sock *sk, int flags);
extern void dccp_hash(struct sock *sk);
extern void dccp_unhash(struct sock *sk);
extern int dccp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen);
extern int dccp_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, int optlen);
#ifdef CONFIG_COMPAT
extern int compat_dccp_getsockopt(struct sock *sk,
int level, int optname,
char __user *optval, int __user *optlen);
extern int compat_dccp_setsockopt(struct sock *sk,
int level, int optname,
char __user *optval, int optlen);
#endif
extern int dccp_ioctl(struct sock *sk, int cmd, unsigned long arg);
extern int dccp_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t size);
extern int dccp_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int nonblock,
int flags, int *addr_len);
extern void dccp_shutdown(struct sock *sk, int how);
extern int inet_dccp_listen(struct socket *sock, int backlog);
extern unsigned int dccp_poll(struct file *file, struct socket *sock,
poll_table *wait);
extern int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len);
extern int dccp_send_reset(struct sock *sk, enum dccp_reset_codes code);
extern void dccp_send_close(struct sock *sk, const int active);
extern int dccp_invalid_packet(struct sk_buff *skb);
static inline int dccp_bad_service_code(const struct sock *sk,
const __be32 service)
{
const struct dccp_sock *dp = dccp_sk(sk);
if (dp->dccps_service == service)
return 0;
return !dccp_list_has_service(dp->dccps_service_list, service);
}
struct dccp_skb_cb {
__u8 dccpd_type:4;
__u8 dccpd_ccval:4;
__u8 dccpd_reset_code;
__u16 dccpd_opt_len;
__u64 dccpd_seq;
__u64 dccpd_ack_seq;
};
#define DCCP_SKB_CB(__skb) ((struct dccp_skb_cb *)&((__skb)->cb[0]))
static inline int dccp_non_data_packet(const struct sk_buff *skb)
{
const __u8 type = DCCP_SKB_CB(skb)->dccpd_type;
return type == DCCP_PKT_ACK ||
type == DCCP_PKT_CLOSE ||
type == DCCP_PKT_CLOSEREQ ||
type == DCCP_PKT_RESET ||
type == DCCP_PKT_SYNC ||
type == DCCP_PKT_SYNCACK;
}
static inline int dccp_packet_without_ack(const struct sk_buff *skb)
{
const __u8 type = DCCP_SKB_CB(skb)->dccpd_type;
return type == DCCP_PKT_DATA || type == DCCP_PKT_REQUEST;
}
#define DCCP_MAX_SEQNO ((((u64)1) << 48) - 1)
#define DCCP_PKT_WITHOUT_ACK_SEQ (DCCP_MAX_SEQNO << 2)
static inline void dccp_set_seqno(u64 *seqno, u64 value)
{
if (value > DCCP_MAX_SEQNO)
value -= DCCP_MAX_SEQNO + 1;
*seqno = value;
}
static inline u64 dccp_delta_seqno(u64 seqno1, u64 seqno2)
{
return ((seqno2 << 16) - (seqno1 << 16)) >> 16;
}
static inline void dccp_inc_seqno(u64 *seqno)
{
if (++*seqno > DCCP_MAX_SEQNO)
*seqno = 0;
}
static inline void dccp_hdr_set_seq(struct dccp_hdr *dh, const u64 gss)
{
struct dccp_hdr_ext *dhx = (struct dccp_hdr_ext *)((void *)dh +
sizeof(*dh));
dh->dccph_seq2 = 0;
dh->dccph_seq = htons((gss >> 32) & 0xfffff);
dhx->dccph_seq_low = htonl(gss & 0xffffffff);
}
static inline void dccp_hdr_set_ack(struct dccp_hdr_ack_bits *dhack,
const u64 gsr)
{
dhack->dccph_reserved1 = 0;
dhack->dccph_ack_nr_high = htons(gsr >> 32);
dhack->dccph_ack_nr_low = htonl(gsr & 0xffffffff);
}
static inline void dccp_update_gsr(struct sock *sk, u64 seq)
{
struct dccp_sock *dp = dccp_sk(sk);
const struct dccp_minisock *dmsk = dccp_msk(sk);
dp->dccps_gsr = seq;
dccp_set_seqno(&dp->dccps_swl,
dp->dccps_gsr + 1 - (dmsk->dccpms_sequence_window / 4));
dccp_set_seqno(&dp->dccps_swh,
dp->dccps_gsr + (3 * dmsk->dccpms_sequence_window) / 4);
}
static inline void dccp_update_gss(struct sock *sk, u64 seq)
{
struct dccp_sock *dp = dccp_sk(sk);
dp->dccps_awh = dp->dccps_gss = seq;
dccp_set_seqno(&dp->dccps_awl,
(dp->dccps_gss -
dccp_msk(sk)->dccpms_sequence_window + 1));
}
static inline int dccp_ack_pending(const struct sock *sk)
{
const struct dccp_sock *dp = dccp_sk(sk);
return dp->dccps_timestamp_echo != 0 ||
#ifdef CONFIG_IP_DCCP_ACKVEC
(dccp_msk(sk)->dccpms_send_ack_vector &&
dccp_ackvec_pending(dp->dccps_hc_rx_ackvec)) ||
#endif
inet_csk_ack_scheduled(sk);
}
extern int dccp_insert_options(struct sock *sk, struct sk_buff *skb);
extern int dccp_insert_option_elapsed_time(struct sock *sk,
struct sk_buff *skb,
u32 elapsed_time);
extern int dccp_insert_option_timestamp(struct sock *sk,
struct sk_buff *skb);
extern int dccp_insert_option(struct sock *sk, struct sk_buff *skb,
unsigned char option,
const void *value, unsigned char len);
extern void dccp_timestamp(const struct sock *sk, struct timeval *tv);
static inline suseconds_t timeval_usecs(const struct timeval *tv)
{
return tv->tv_sec * USEC_PER_SEC + tv->tv_usec;
}
static inline suseconds_t timeval_delta(const struct timeval *large,
const struct timeval *small)
{
time_t secs = large->tv_sec - small->tv_sec;
suseconds_t usecs = large->tv_usec - small->tv_usec;
if (usecs < 0) {
secs--;
usecs += USEC_PER_SEC;
}
return secs * USEC_PER_SEC + usecs;
}
static inline void timeval_add_usecs(struct timeval *tv,
const suseconds_t usecs)
{
tv->tv_usec += usecs;
while (tv->tv_usec >= USEC_PER_SEC) {
tv->tv_sec++;
tv->tv_usec -= USEC_PER_SEC;
}
}
static inline void timeval_sub_usecs(struct timeval *tv,
const suseconds_t usecs)
{
tv->tv_usec -= usecs;
while (tv->tv_usec < 0) {
tv->tv_sec--;
tv->tv_usec += USEC_PER_SEC;
}
DCCP_BUG_ON(tv->tv_sec < 0);
}
#ifdef CONFIG_SYSCTL
extern int dccp_sysctl_init(void);
extern void dccp_sysctl_exit(void);
#else
static inline int dccp_sysctl_init(void)
{
return 0;
}
static inline void dccp_sysctl_exit(void)
{
}
#endif
#endif /* _DCCP_H */
| {'content_hash': '41425a1685aa8f0ccd2f47fe843037de', 'timestamp': '', 'source': 'github', 'line_count': 442, 'max_line_length': 80, 'avg_line_length': 30.619909502262445, 'alnum_prop': 0.6718634550022167, 'repo_name': 'impedimentToProgress/UCI-BlueChip', 'id': 'e33a9edb40363ef7c964de7de3eb55c0c81d7846', 'size': '13933', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'snapgear_linux/linux-2.6.21.1/net/dccp/dccp.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AGS Script', 'bytes': '25338'}, {'name': 'ASP', 'bytes': '4526'}, {'name': 'Ada', 'bytes': '1075367'}, {'name': 'Assembly', 'bytes': '2137017'}, {'name': 'Awk', 'bytes': '133306'}, {'name': 'Bison', 'bytes': '399484'}, {'name': 'BlitzBasic', 'bytes': '101509'}, {'name': 'C', 'bytes': '288543995'}, {'name': 'C++', 'bytes': '7495614'}, {'name': 'CSS', 'bytes': '2128'}, {'name': 'Clojure', 'bytes': '3747'}, {'name': 'Common Lisp', 'bytes': '239683'}, {'name': 'Elixir', 'bytes': '790'}, {'name': 'Emacs Lisp', 'bytes': '45827'}, {'name': 'Erlang', 'bytes': '171340'}, {'name': 'GAP', 'bytes': '3002'}, {'name': 'Groff', 'bytes': '4517911'}, {'name': 'Groovy', 'bytes': '26513'}, {'name': 'HTML', 'bytes': '8141161'}, {'name': 'Java', 'bytes': '481441'}, {'name': 'JavaScript', 'bytes': '339345'}, {'name': 'Logos', 'bytes': '16160'}, {'name': 'M', 'bytes': '2443'}, {'name': 'Makefile', 'bytes': '1309237'}, {'name': 'Max', 'bytes': '3812'}, {'name': 'Nemerle', 'bytes': '966202'}, {'name': 'Objective-C', 'bytes': '376270'}, {'name': 'OpenEdge ABL', 'bytes': '69290'}, {'name': 'PHP', 'bytes': '11533'}, {'name': 'PLSQL', 'bytes': '8464'}, {'name': 'Pascal', 'bytes': '54420'}, {'name': 'Perl', 'bytes': '6498220'}, {'name': 'Perl6', 'bytes': '4155'}, {'name': 'Prolog', 'bytes': '62574'}, {'name': 'Python', 'bytes': '24287'}, {'name': 'QMake', 'bytes': '8619'}, {'name': 'R', 'bytes': '25999'}, {'name': 'Ruby', 'bytes': '31311'}, {'name': 'SAS', 'bytes': '15573'}, {'name': 'Scala', 'bytes': '1506'}, {'name': 'Scilab', 'bytes': '23534'}, {'name': 'Shell', 'bytes': '6951414'}, {'name': 'Smalltalk', 'bytes': '2661'}, {'name': 'Stata', 'bytes': '7930'}, {'name': 'Tcl', 'bytes': '1518344'}, {'name': 'TeX', 'bytes': '1574651'}, {'name': 'UnrealScript', 'bytes': '20822'}, {'name': 'VHDL', 'bytes': '37384578'}, {'name': 'Verilog', 'bytes': '376626'}, {'name': 'Visual Basic', 'bytes': '180'}, {'name': 'XS', 'bytes': '24500'}, {'name': 'XSLT', 'bytes': '5872'}]} |
#include "Mshtml.h"
#include "../resource.h"
#define OLE_CTRL_ID_RANGE_FIRST 1000
#define OLE_CTRL_ID_RANGE_LAST 50000
IMPLEMENT_DYNAMIC(CWebControl, CWebBrowser)
CWebControl::CWebControl(void)
{
pDocHostUIHandlerImpl = new CDocHostUIHandler();
}
CWebControl::~CWebControl(void)
{
delete pDocHostUIHandlerImpl;
ReleaseStates();
}
void CWebControl::ReleaseStates()
{
while (mWebStates.GetCount() > 0)
{
CWebControlState* pState = mWebStates.GetHead();
mWebStates.RemoveHead();
delete pState;
}
}
BEGIN_MESSAGE_MAP(CWebControl, CWebBrowser)
END_MESSAGE_MAP()
BEGIN_EVENTSINK_MAP(CWebControl, CWebBrowser)
ON_EVENT_RANGE(CWebControl, OLE_CTRL_ID_RANGE_FIRST, OLE_CTRL_ID_RANGE_LAST,
259, DocumentComplete,
VTS_I4 VTS_DISPATCH VTS_PVARIANT)
ON_EVENT_RANGE(CWebControl, OLE_CTRL_ID_RANGE_FIRST, OLE_CTRL_ID_RANGE_LAST,
250, BeforeNavigate2,
VTS_I4 VTS_DISPATCH VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PBOOL)
END_EVENTSINK_MAP()
BOOL CWebControl::DocumentComplete(UINT CtlID, LPDISPATCH pDisp, VARIANT* URL)
{
USES_CONVERSION;
csCurrentURL = W2T((LPCWSTR)URL->pbVal);
CWebControlState* pFoundState = FindStateByURL(csCurrentURL);
if (pFoundState)
pDocHostUIHandlerImpl->SetGetPropertyCallback(pFoundState->GetGetPropertyCallback(),
pFoundState->GetCallbackData());
CustomizeWebBrowser();
UpdateStateHandlers();
return TRUE;
}
BOOL CWebControl::BeforeNavigate2(UINT CtlID, LPDISPATCH pDisp, VARIANT* URL, VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData, VARIANT* Headers, BOOL* Cancel)
{
USES_CONVERSION;
csCurrentURL = W2T((LPCWSTR)URL->pbVal);
CWebControlState* pFoundState = FindStateByURL(csCurrentURL);
if (pFoundState)
pDocHostUIHandlerImpl->SetGetPropertyCallback(pFoundState->GetGetPropertyCallback(),
pFoundState->GetCallbackData());
return TRUE;
}
void CWebControl::CustomizeWebBrowser()
{
IUnknown* pUnknown = GetControlUnknown();
if (!pUnknown)
return;
IWebBrowser2 *pBrowser = NULL;
HRESULT hr = pUnknown->QueryInterface(IID_IWebBrowser2, (void**)&pBrowser);
if (!SUCCEEDED(hr))
{
pUnknown->Release();
return;
}
IDispatch* pDocumentDispatch = NULL;
pBrowser->get_Document(&pDocumentDispatch);
if (!pDocumentDispatch)
{
pUnknown->Release();
pBrowser->Release();
return;
}
IHTMLDocument2* pHTMLDocument = NULL;
hr = pDocumentDispatch->QueryInterface(IID_IHTMLDocument2,(void**)&pHTMLDocument);
if (!SUCCEEDED(hr))
{
pUnknown->Release();
pBrowser->Release();
pDocumentDispatch->Release();
return;
}
ICustomDoc* pCustomDoc = NULL;
hr = pHTMLDocument->QueryInterface(IID_ICustomDoc, (void**)&pCustomDoc);
if (!SUCCEEDED(hr))
{
pUnknown->Release();
pBrowser->Release();
pDocumentDispatch->Release();
pHTMLDocument->Release();
return;
}
pCustomDoc->SetUIHandler(pDocHostUIHandlerImpl);
pUnknown->Release();
pBrowser->Release();
pDocumentDispatch->Release();
pHTMLDocument->Release();
pCustomDoc->Release();
}
void CWebControl::FreeCustomizationData()
{
}
void CWebControl::UpdateStateHandlers()
{
CWebControlState* pFoundState = FindStateByURL(csCurrentURL);
if (!pFoundState)
return;
IUnknown* pUnknown = GetControlUnknown();
if (!pUnknown)
return;
IWebBrowser2 *pBrowser = NULL;
HRESULT hr = pUnknown->QueryInterface(IID_IWebBrowser2, (void**)&pBrowser);
if (!SUCCEEDED(hr))
{
pUnknown->Release();
return;
}
IDispatch* pDocumentDispatch = NULL;
pBrowser->get_Document(&pDocumentDispatch);
if (!pDocumentDispatch)
{
pUnknown->Release();
pBrowser->Release();
return;
}
IHTMLDocument2* pHTMLDocument = NULL;
hr = pDocumentDispatch->QueryInterface(IID_IHTMLDocument2,(void**)&pHTMLDocument);
if (!SUCCEEDED(hr))
{
pUnknown->Release();
pBrowser->Release();
pDocumentDispatch->Release();
return;
}
IHTMLElementCollection* pElementCollection = NULL;
pHTMLDocument->get_all(&pElementCollection);
if (!SUCCEEDED(hr))
{
pUnknown->Release();
pBrowser->Release();
pDocumentDispatch->Release();
pHTMLDocument->Release();
return;
}
USES_CONVERSION;
long iElementLength;
pElementCollection->get_length(&iElementLength);
for (long i=0;i<iElementLength;i++)
{
IDispatch* pElementDispatch = NULL;
pElementCollection->item(COleVariant(i), COleVariant(i), &pElementDispatch);
if (!pElementDispatch)
continue;
IHTMLElement* pHTMLElement = NULL;
hr = pElementDispatch->QueryInterface(IID_IHTMLElement,(void**)&pHTMLElement);
if (!SUCCEEDED(hr))
{
pElementDispatch->Release();
continue;
}
CString csAtributeName = "name";
BSTR bstrAttribName = csAtributeName.AllocSysString();
COleVariant varT;
pHTMLElement->getAttribute(bstrAttribName, 0, &varT);
BSTR bstrValue = varT.bstrVal;
CString csValue = W2T(bstrValue);
pFoundState->CreateEnumerator();
while (CInvokeShell* pShell = pFoundState->GetNextInvokeShell())
if (pShell->GetName() == csValue)
{
VARIANT varT;
varT.vt = VT_DISPATCH;
varT.pdispVal = pShell;
HRESULT res = pHTMLElement->put_onclick(varT);
break;
}
pElementDispatch->Release();
pHTMLElement->Release();
}
//pUnknown->Release();
//pBrowser->Release();
//pDocumentDispatch->Release();
//pHTMLDocument->Release();
//pElementCollection->Release();
}
CWebControlState* CWebControl::AddState(CString& csName, CString& csFile)
{
CWebControlState* pState = new CWebControlState(csName, csFile);
mWebStates.AddTail(pState);
return pState;
}
void CWebControl::ShowState(CString& csName)
{
for(POSITION pos = mWebStates.GetHeadPosition();pos;)
{
CWebControlState* pState = mWebStates.GetNext(pos);
if (pState->GetStateName() == csName)
{
USES_CONVERSION;
VARIANT varURL;
varURL.vt = VT_BSTR;
varURL.pbVal = (BYTE*)T2W(pState->GetFileName().GetBuffer());
Navigate2(&varURL, NULL, NULL, NULL, NULL);
return;
}
}
}
void CWebControl::Refresh()
{
CWebBrowser::Refresh();
UpdateStateHandlers();
}
void CWebControl::UpdateState()
{
USES_CONVERSION;
VARIANT varURL;
varURL.vt = VT_BSTR;
varURL.pbVal = (BYTE*)T2W(csCurrentURL.GetBuffer());
Navigate2(&varURL, NULL, NULL, NULL, NULL);
}
CWebControlState* CWebControl::FindStateByURL(CString& URL)
{
CString tmURL(URL);
tmURL.MakeUpper();
for(POSITION pos = mWebStates.GetHeadPosition();pos;)
{
CWebControlState* pState = mWebStates.GetNext(pos);
CString csStateName = pState->GetStateName();
csStateName.MakeUpper();
if (tmURL.Find(csStateName) != -1)
return pState;
}
return NULL;
} | {'content_hash': 'f5df6a3f2d3f6cdabb53559bf8eaa543', 'timestamp': '', 'source': 'github', 'line_count': 303, 'max_line_length': 170, 'avg_line_length': 22.6006600660066, 'alnum_prop': 0.6921728971962616, 'repo_name': 'egorpushkin/neurolab', 'id': 'b0e62471319281d3fa7434839f240eb201c057c0', 'size': '6896', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/Tools/DataCreator/WebControl/WebControl.cpp', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '112'}, {'name': 'C', 'bytes': '1787692'}, {'name': 'C++', 'bytes': '9312245'}, {'name': 'CSS', 'bytes': '44465'}, {'name': 'Clarion', 'bytes': '5268'}, {'name': 'HTML', 'bytes': '408820'}, {'name': 'JavaScript', 'bytes': '5476'}, {'name': 'Makefile', 'bytes': '39256'}, {'name': 'Objective-C', 'bytes': '97952'}, {'name': 'TeX', 'bytes': '3128'}]} |
struct acpi_rdsp {
uchar signature[8];
uchar checksum;
uchar oem_id[6];
uchar revision;
uint32 rsdt_addr_phys;
uint32 length;
uint64 xsdt_addr_phys;
uchar xchecksum;
uchar reserved[3];
} __attribute__((__packed__));
// 5.2.6
struct acpi_desc_header {
uchar signature[4];
uint32 length;
uchar revision;
uchar checksum;
uchar oem_id[6];
uchar oem_tableid[8];
uint32 oem_revision;
uchar creator_id[4];
uint32 creator_revision;
} __attribute__((__packed__));
// 5.2.7
struct acpi_rsdt {
struct acpi_desc_header header;
uint32 entry[0];
} __attribute__((__packed__));
#define TYPE_LAPIC 0
#define TYPE_IOAPIC 1
#define TYPE_INT_SRC_OVERRIDE 2
#define TYPE_NMI_INT_SRC 3
#define TYPE_LAPIC_NMI 4
// 5.2.12 Multiple APIC Description Table
#define SIG_MADT "APIC"
struct acpi_madt {
struct acpi_desc_header header;
uint32 lapic_addr_phys;
uint32 flags;
uchar table[0];
} __attribute__((__packed__));
// 5.2.12.2
#define APIC_LAPIC_ENABLED 1
struct madt_lapic {
uchar type;
uchar length;
uchar acpi_id;
uchar apic_id;
uint32 flags;
} __attribute__((__packed__));
// 5.2.12.3
struct madt_ioapic {
uchar type;
uchar length;
uchar id;
uchar reserved;
uint32 addr;
uint32 interrupt_base;
} __attribute__((__packed__));
#endif
| {'content_hash': 'b6c69799bc927d339200ffab1266cee0', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 41, 'avg_line_length': 19.014705882352942, 'alnum_prop': 0.665893271461717, 'repo_name': 'maxymania/open-xv6', 'id': 'afde3b530355d8c8c6500585e43221e21ea59c60', 'size': '1436', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/gnrc/acpi.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '14176'}, {'name': 'C', 'bytes': '231026'}, {'name': 'C++', 'bytes': '22819'}, {'name': 'Emacs Lisp', 'bytes': '86'}, {'name': 'Makefile', 'bytes': '8484'}, {'name': 'Objective-C', 'bytes': '74'}]} |
package com.tshevchenko.client.ui;
import com.tshevchenko.client.ui.IDataModelInfo;
import com.google.gwt.view.client.ProvidesKey;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* The GeneralInfo class to generalize a data row in a DataGrid
*
* @author Taras Shevchenko, [email protected]
*
*/
public class GeneralInfo implements IDataModelInfo {
public static final ProvidesKey<IDataModelInfo> KEY_PROVIDER =
new ProvidesKey<IDataModelInfo>() {
public Object getKey(IDataModelInfo item) {
return item == null ? null : item.getId();
}
};
private static Long nextId = 0L;
protected Long id;
protected List<String> colNames = new ArrayList<String>();
protected HashMap<String, String> colTitles = new HashMap<String, String>();
protected HashMap<String, String> dataMap = new HashMap<String, String>();
public GeneralInfo() {
this.id = nextId;
nextId++;
}
@Override
public List<String> getNames(){
return colNames;
}
@Override
public String getValue(String colName){
return dataMap.get(colName);
}
@Override
public String getTitle(String colName){
return colTitles.get(colName);
}
@Override
public void setValue(String colName, String value){
dataMap.put(colName, value);
}
@Override
public Long getId() {
return this.id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
return id.intValue();
}
}
| {'content_hash': 'aff97fdbb4f74e3ba56ae8950e62f8b1', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 80, 'avg_line_length': 24.70149253731343, 'alnum_prop': 0.6344410876132931, 'repo_name': 'TarasShev/GWTClientServerExample', 'id': '6b6b6c7762122804d2cac3d2b8200a9c94af480a', 'size': '1655', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SimpleTask/src/main/java/com/tshevchenko/client/ui/GeneralInfo.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '54237'}, {'name': 'HTML', 'bytes': '13943'}, {'name': 'Java', 'bytes': '66934'}, {'name': 'Shell', 'bytes': '31'}]} |
import zmq
IP = "192.168.1.137"
print("Connecting to server... ")
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://{}:5555".format(IP))
for i in range(10):
# Send a message to server
message = "Helo {} ".format(i)
socket.send(message.encode())
#Get the reply
message = socket.recv()
print(message)
socket.send(b"end")
print("Client closed")
| {'content_hash': '45c71b53ee4281037a11eb1e77fb0b0c', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 42, 'avg_line_length': 20.0, 'alnum_prop': 0.6475, 'repo_name': 'carlgonz/zmq_examples', 'id': '25cf17c9bd61996f1f118b4c5e4652f86c718856', 'size': '400', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'basic/client.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '11260'}, {'name': 'Shell', 'bytes': '52'}]} |
require 'pundit'
require 'rails/generators'
class Natural::ResourceGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :model_name, type: :string, default: ''
def generate_dependencies
@model_name = name if @model_name.blank?
invoke 'pundit:policy', [@model_name.singularize]
invoke 'controller', [name.pluralize]
c_sentinel = '< ApplicationController'
# Add resource reference to generated controller
in_root do
gsub_file "app/controllers/#{name.pluralize}_controller.rb", /(#{Regexp.escape(c_sentinel)})/mi do |match|
"#{match}\n resource :#{@model_name.pluralize.downcase}\n\n def resource_params\n params.require(:#{@model_name.singularize}).permit()\n end\n"
end
end
# Add note to generated Pundit policy
in_root do
gsub_file "app/policies/#{@model_name.singularize}_policy.rb", /(def resolve\n\s+scope\n\s+end)/mi do |match|
'# See ApplicationPolicy.rb to see how a scope is defined and used'
end
end
end
end
| {'content_hash': 'a4b96e2e4d72aba24b3ccda33deda5b4', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 157, 'avg_line_length': 36.793103448275865, 'alnum_prop': 0.6785379568884724, 'repo_name': 'Haar/natural_resource', 'id': '7a988bfca7f9d7646f4df0bc5a66904cf54d1be8', 'size': '1067', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/generators/natural/resource/resource_generator.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '686'}, {'name': 'HTML', 'bytes': '4703'}, {'name': 'JavaScript', 'bytes': '596'}, {'name': 'Ruby', 'bytes': '39183'}]} |
@interface SampleManager (SampleManagerPrivate)
- (NSMutableDictionary *)sampleExecutorHandlerWithResult:(HYResult *)result;
@end
@implementation SampleManager
@synthesize standby = _standby;
- (NSString *) name
{
return SampleManagerNotification;
}
- (NSString *) brief
{
return @"Sample manager";
}
+ (SampleManager *)defaultManager
{
static dispatch_once_t once;
static SampleManager *sharedInstance;
dispatch_once(&once, ^{ sharedInstance = [[self alloc] init];});
return sharedInstance;
}
- (BOOL)standbyWithWorkerName:(NSString *)workerName
{
if( (self.standby == YES) || (workerName.length <= 0) ) {
return NO;
}
// regist executor with handling method
[self registExecuter: [[SampleExecutor alloc] init] withWorkerName:workerName action:@selector(sampleExecutorHandlerWithResult:)];
_standby = YES;
return YES;
}
- (void)requestServerApi:(NSString *)serverApiUrlString httpMethod:(NSString *)httpMethod parameterDict:(NSDictionary *)parameterDict completion:(void (^)(NSMutableDictionary *))completion
{
// check parameter
if( (serverApiUrlString.length == 0) || (([httpMethod isEqualToString:@"GET"] == NO) && ([httpMethod isEqualToString:@"POST"] == NO)) ) {
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
}
// make query
HYQuery *query;
if( (query = [self queryForExecutorName:SampleExecutorName]) == nil ) {
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
}
// set url string of server api with its key.
[query setParameter:serverApiUrlString forKey:SampleExecutorParameterKeyUrlString];
// set operation of executor by checking http method parameter.
// parameter value "GET" to 'SampleExecutorOperationGet'.
if( [httpMethod isEqualToString:@"GET"] == YES ) {
[query setParameter:@(SampleExecutorOperationGet) forKey:SampleExecutorParameterKeyOperation];
// we checked parameter 'httpMethod' above and in this case, 'httpMethod' have value @"POST"
// so, set to 'SampleExecutorOperationPost'.
} else {
[query setParameter:@(SampleExecutorOperationPost) forKey:SampleExecutorParameterKeyOperation];
}
// set parameter dictionary with its key, and it'll used query string of http GET method or post parameter of http POST method.
[query setParameter:parameterDict forKey:SampleExecutorParameterKeyRequestDict];
// set completion handler for task after http communiation.
[query setParameter:completion forKey:SampleManagerNotifyParameterKeyCompletionBlock];
// now, query object prepared, push it to hydra.
[[Hydra defaultHydra] pushQuery:query];
}
- (void)requestServerApi:(NSString *)serverApiUrlString parameterDict:(NSDictionary *)parameterDict downloadFileTo:(NSString *)filePath completion:(void (^)(NSMutableDictionary *))completion
{
// check parameter
if( (serverApiUrlString.length == 0) || (filePath.length == 0) ) {
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
}
// make query
HYQuery *query;
if( (query = [self queryForExecutorName:SampleExecutorName]) == nil ) {
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
}
// set url string of server api with its key.
[query setParameter:serverApiUrlString forKey:SampleExecutorParameterKeyUrlString];
// set operation of executor. in this case, set 'SampleExecutorOperationDownloadFile' for download file.
[query setParameter:@(SampleExecutorOperationDownloadFile) forKey:SampleExecutorParameterKeyOperation];
// set parameter dictinary with its key, and it'll used query string of http GET method.
[query setParameter:parameterDict forKey:SampleExecutorParameterKeyRequestDict];
// set file path string with its key. it'll be file path of downloaded file.
[query setParameter:filePath forKey:SampleExecutorParameterKeyFilePath];
// set completion handler for task after http communiation.
[query setParameter:completion forKey:SampleManagerNotifyParameterKeyCompletionBlock];
// now, query object prepared, push it to hydra.
[[Hydra defaultHydra] pushQuery:query];
}
- (void)requestServerApi:(NSString *)serverApiUrlString parameterDict:(NSDictionary *)parameterDict formDataFieldName:(NSString *)formDataFieldName fileName:(NSString *)fileName contentType:(NSString *)contentType uploadFileFrom:(NSString *)filePath completion:(void (^)(NSMutableDictionary *))completion
{
// check parameter
if( (serverApiUrlString.length == 0) || (formDataFieldName.length == 0) || (fileName.length == 0) || (contentType.length == 0) || (filePath.length == 0) ) {
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
}
// make query and push to hydra
HYQuery *query;
if( (query = [self queryForExecutorName:SampleExecutorName]) == nil ) {
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
}
// set url string of server api with its key.
[query setParameter:serverApiUrlString forKey:SampleExecutorParameterKeyUrlString];
// set operation of executor. in this case, set 'SampleExecutorOperationUploadFile' for upload file.
[query setParameter:@(SampleExecutorOperationUploadFile) forKey:SampleExecutorParameterKeyOperation];
// set parameter dictinary with its key, and it'll used post parameter of http POST method.
[query setParameter:parameterDict forKey:SampleExecutorParameterKeyRequestDict];
[query setParameter:formDataFieldName forKey:SampleExecutorParameterKeyFormDataFieldName];
[query setParameter:fileName forKey:SampleExecutorParameterKeyFileName];
[query setParameter:contentType forKey:SampleExecutorParameterKeyContentType];
// set file path string with its key. path of file content data will be upload.
[query setParameter:filePath forKey:SampleExecutorParameterKeyFilePath];
// set completion handler for task after http communiation.
[query setParameter:completion forKey:SampleManagerNotifyParameterKeyCompletionBlock];
// now, query object prepared, push it to hydra.
[[Hydra defaultHydra] pushQuery:query];
}
- (NSMutableDictionary *)sampleExecutorHandlerWithResult:(HYResult *)result
{
// get complete handler.
void (^completionBlock)(NSMutableDictionary *) = [result parameterForKey:SampleManagerNotifyParameterKeyCompletionBlock];
// prepare dictionary object, and it'll have values for notification feedback.
NSMutableDictionary *paramDict = [NSMutableDictionary new];
if( paramDict == nil ) {
if( completionBlock != nil ) {
completionBlock(nil);
}
return nil;
}
// check parameters and set to dicationary object for feedback if need.
// here check server api string,
NSString *serverApiString = [result parameterForKey:SampleExecutorParameterKeyUrlString];
if( serverApiString == nil ) {
if( completionBlock != nil ) {
completionBlock(nil);
}
return nil;
}
paramDict[SampleManagerNotifyParameterKeyServerApiUrlString] = serverApiString;
// and request parameters,
NSMutableDictionary *requestDict = [result parameterForKey:SampleExecutorParameterKeyRequestDict];
if( requestDict != nil ) {
paramDict[SampleManagerNotifyParameterKeyRequestDict] = requestDict;
}
// and received result parameters,
NSMutableDictionary * resultDict = [result parameterForKey:SampleExecutorParameterKeyResultDict];
if( resultDict != nil ) {
paramDict[SampleManagerNotifyParameterKeyResultDict] = resultDict;
}
// and failed flag.
if( [[result parameterForKey:SampleExecutorParameterKeyFailedFlag] boolValue] == YES ) {
paramDict[SampleManagerNotifyParameterKeyFailedFlag] = @"Y";
}
// if completion block specified, then call it.
if( completionBlock != nil ) {
completionBlock(paramDict);
}
// if 'paramDict' is empty, then we don't have to notification, so return 'nil'.
if( paramDict.count == 0 ) {
return nil;
}
// 'paramDict' will be 'userInfo' of notification, 'SampleManagerNotification'.
return paramDict;
}
@end
| {'content_hash': '2bf41dd38f3bcef98de419fec63bcf8b', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 304, 'avg_line_length': 37.49787234042553, 'alnum_prop': 0.6875851112119836, 'repo_name': 'P9SOFT/HJAsyncHttpDeliverer', 'id': 'c65a16dd4372a5bde22a75e198df9a004c4f2600', 'size': '9057', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Samples/HttpCommunication/HttpCommunication/SampleManager.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '49400'}, {'name': 'Ruby', 'bytes': '614'}]} |
package de.javagl.jgltf.model.io;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.function.Consumer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.deser.NullValueProvider;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
/**
* A SettableBeanProperty that passes all calls to a delegate, and
* passes error information to a consumer of {@link JsonError}s
* (for example, when calling a setter caused an exception).
* This is used for error reporting in the Jackson bean deserializers.
*/
class ErrorReportingSettableBeanProperty extends SettableBeanProperty
{
/**
* Serial UID
*/
private static final long serialVersionUID = 7398743799397469737L;
/**
* The delegate
*/
private final SettableBeanProperty delegate;
/**
* The consumer for {@link JsonError}s
*/
private final Consumer<? super JsonError> jsonErrorConsumer;
/**
* Creates a new instance with the given delegate and error consumer
*
* @param delegate The delegate
* @param jsonErrorConsumer The consumer for {@link JsonError}s. If
* this is <code>null</code>, then errors will be ignored.
*/
ErrorReportingSettableBeanProperty(
SettableBeanProperty delegate,
Consumer<? super JsonError> jsonErrorConsumer)
{
super(delegate);
this.delegate = delegate;
this.jsonErrorConsumer = jsonErrorConsumer;
}
@Override
public SettableBeanProperty
withValueDeserializer(JsonDeserializer<?> deser)
{
return new ErrorReportingSettableBeanProperty(
delegate.withValueDeserializer(deser), jsonErrorConsumer);
}
@Override
public SettableBeanProperty withName(PropertyName newName)
{
return new ErrorReportingSettableBeanProperty(
delegate.withName(newName), jsonErrorConsumer);
}
@Override
public Object setAndReturn(Object instance, Object value)
throws IOException
{
return delegate.setAndReturn(instance, value);
}
@Override
public void set(Object instance, Object value) throws IOException
{
delegate.set(instance, value);
}
@Override
public AnnotatedMember getMember()
{
return delegate.getMember();
}
@Override
public <A extends Annotation> A getAnnotation(Class<A> acls)
{
return delegate.getAnnotation(acls);
}
@Override
public Object deserializeSetAndReturn(JsonParser p,
DeserializationContext ctxt, Object instance) throws IOException
{
return delegate.deserializeSetAndReturn(p, ctxt, instance);
}
@Override
public void deserializeAndSet(JsonParser p, DeserializationContext ctxt,
Object instance) throws IOException
{
try
{
delegate.deserializeAndSet(p, ctxt, instance);
}
catch (Exception e)
{
if (jsonErrorConsumer != null)
{
jsonErrorConsumer.accept(new JsonError(
e.getMessage(), p.getParsingContext(), e));
}
}
}
@Override
public SettableBeanProperty withNullProvider(NullValueProvider nva)
{
return new ErrorReportingSettableBeanProperty(
delegate.withNullProvider(nva), jsonErrorConsumer);
}
}
| {'content_hash': '5f065fecafe0bfdf5090dcb041851600', 'timestamp': '', 'source': 'github', 'line_count': 126, 'max_line_length': 76, 'avg_line_length': 30.349206349206348, 'alnum_prop': 0.6563807531380753, 'repo_name': 'javagl/JglTF', 'id': '73c2a373b7027141844fc5f4fb3a4cb609e4149a', 'size': '5026', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jgltf-model/src/main/java/de/javagl/jgltf/model/io/ErrorReportingSettableBeanProperty.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'GLSL', 'bytes': '18055'}, {'name': 'Java', 'bytes': '2594158'}]} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.models;
import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.network.fluent.models.NetworkManagerConnectionInner;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** List of network manager connections. */
@Fluent
public final class NetworkManagerConnectionListResult {
/*
* List of network manager connections.
*/
@JsonProperty(value = "value")
private List<NetworkManagerConnectionInner> value;
/*
* Gets the URL to get the next page of results.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/** Creates an instance of NetworkManagerConnectionListResult class. */
public NetworkManagerConnectionListResult() {
}
/**
* Get the value property: List of network manager connections.
*
* @return the value value.
*/
public List<NetworkManagerConnectionInner> value() {
return this.value;
}
/**
* Set the value property: List of network manager connections.
*
* @param value the value value to set.
* @return the NetworkManagerConnectionListResult object itself.
*/
public NetworkManagerConnectionListResult withValue(List<NetworkManagerConnectionInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: Gets the URL to get the next page of results.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: Gets the URL to get the next page of results.
*
* @param nextLink the nextLink value to set.
* @return the NetworkManagerConnectionListResult object itself.
*/
public NetworkManagerConnectionListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
| {'content_hash': 'b2a800a3e548d7d0c981168b30f00eb1', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 100, 'avg_line_length': 28.88888888888889, 'alnum_prop': 0.6679487179487179, 'repo_name': 'Azure/azure-sdk-for-java', 'id': '5a235a3c9fc1a8d694f12cbe3950ed75ebef6355', 'size': '2340', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkManagerConnectionListResult.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '8762'}, {'name': 'Bicep', 'bytes': '15055'}, {'name': 'CSS', 'bytes': '7676'}, {'name': 'Dockerfile', 'bytes': '2028'}, {'name': 'Groovy', 'bytes': '3237482'}, {'name': 'HTML', 'bytes': '42090'}, {'name': 'Java', 'bytes': '432409546'}, {'name': 'JavaScript', 'bytes': '36557'}, {'name': 'Jupyter Notebook', 'bytes': '95868'}, {'name': 'PowerShell', 'bytes': '737517'}, {'name': 'Python', 'bytes': '240542'}, {'name': 'Scala', 'bytes': '1143898'}, {'name': 'Shell', 'bytes': '18488'}, {'name': 'XSLT', 'bytes': '755'}]} |
require 'spec_helper'
# by default we will test with ubuntu 14.04
RSpec.configure do |config|
config.platform = 'ubuntu'
config.version = '14.04'
end
describe 'dse with default settings' do
cached(:chef_run) { ChefSpec::ServerRunner.converge('dse::default') }
it 'creates the cassandra data directory /data/cassandra' do
expect(chef_run).to create_directory('/data/cassandra').with(
user: 'cassandra',
group: 'cassandra',
mode: '775',
recursive: true
)
end
it 'creates the cassandra commit log directory /var/lib/cassandra/commitlog' do
expect(chef_run).to create_directory('/var/lib/cassandra/commitlog').with(
user: 'cassandra',
group: 'cassandra',
mode: '755',
recursive: true
)
end
it 'includes the apt recipe' do
expect(chef_run).to include_recipe('apt')
end
it 'adds the apt repository to the sources.list' do
expect(chef_run).to add_apt_repository('datastax').with(
uri: 'http://user:[email protected]/enterprise',
distribution: 'stable',
key: 'http://user:[email protected]/debian/repo_key'
)
end
# it 'checks the current version and stops the service if it is upgrading'
it 'installs the dse-full package' do
expect(chef_run).to install_package('dse-full')
expect(chef_run).to install_package('dse-libcassandra')
expect(chef_run).to install_package('dse-libhadoop')
expect(chef_run).to install_package('dse-libhadoop-native')
expect(chef_run).to install_package('dse')
expect(chef_run).to install_package('dse-libhive')
expect(chef_run).to install_package('dse-hive')
expect(chef_run).to install_package('dse-liblog4j')
expect(chef_run).to install_package('dse-libmahout')
expect(chef_run).to install_package('dse-libpig')
expect(chef_run).to install_package('dse-libtomcat')
expect(chef_run).to install_package('dse-libsolr')
expect(chef_run).to install_package('dse-libspark') # default 4.0.1 doesn't support spark
expect(chef_run).to install_package('dse-libsqoop')
expect(chef_run).to install_package('dse-pig')
expect(chef_run).to install_package('dse-demos')
end
it 'does not include the dse::datastax-agent recipe' do
expect(chef_run).to_not include_recipe('dse::datastax-agent')
end
it 'does not include the dse::ssl recipe' do
expect(chef_run).to_not include_recipe('dse::ssl')
end
it 'creates the template /etc/default/dse' do
expect(chef_run).to create_template('/etc/default/dse').with(
source: 'dse/dse_4.7.2-1.erb',
owner: 'cassandra',
group: 'cassandra'
)
template = chef_run.template('/etc/default/dse')
expect(template).to notify('service[dse]').to(:restart)
end
it 'creates the template /etc/dse/cassandra/log4j-server.properties' do
expect(chef_run).to create_template('/etc/dse/cassandra/log4j-server.properties').with(
source: 'log4j-server.properties.erb',
owner: 'cassandra',
group: 'cassandra'
)
template = chef_run.template('/etc/dse/cassandra/log4j-server.properties')
expect(template).to notify('service[dse]').to(:restart)
end
it 'creates the template /etc/dse/dse.yaml' do
expect(chef_run).to create_template('/etc/dse/dse.yaml').with(
source: 'dse_yaml/dse_4.7.2-1.yaml.erb',
owner: 'cassandra',
group: 'cassandra'
)
template = chef_run.template('/etc/dse/dse.yaml')
expect(template).to notify('service[dse]').to(:restart)
end
it 'creates the template /etc/dse/cassandra/cassandra.yaml' do
expect(chef_run).to create_template('/etc/dse/cassandra/cassandra.yaml').with(
source: 'cassandra_yaml/cassandra_4.7.2-1.yaml.erb',
owner: 'cassandra',
group: 'cassandra'
)
template = chef_run.template('/etc/dse/cassandra/cassandra.yaml')
expect(template).to notify('service[dse]').to(:restart)
end
it 'creates the template /etc/dse/cassandra/cassandra-env.sh' do
expect(chef_run).to create_template('/etc/dse/cassandra/cassandra-env.sh').with(
source: 'cassandra-env.sh.erb',
owner: 'cassandra',
group: 'cassandra'
)
template = chef_run.template('/etc/dse/cassandra/cassandra-env.sh')
expect(template).to notify('service[dse]').to(:restart)
end
it 'starts the dse service' do
expect(chef_run).to start_service('dse')
end
end
describe 'dse with node[\'datastax-agent\'][\'enabled\'] true' do
cached(:chef_run) do
ChefSpec::ServerRunner.new do |node|
node.set['datastax-agent']['enabled'] = true
end.converge('dse')
end
it 'installs the sysstat package' do
expect(chef_run).to install_package('sysstat')
end
it 'installs the datastax-agent package' do
expect(chef_run).to install_package('datastax-agent')
end
it 'creates the template /var/lib/datastax-agent/conf/address.yaml' do
expect(chef_run).to create_template('/var/lib/datastax-agent/conf/address.yaml')
end
it 'starts the datastax-agent on the host' do
expect(chef_run).to start_service('datastax-agent')
end
end
describe 'dse with node[\'cassandra\'][\'dse\'][\'internode_encryption\'] set to "all"' do
cached(:chef_run) do
ChefSpec::ServerRunner.new do |node|
node.set['cassandra']['dse']['internode_encryption'] = 'all'
end.converge('dse')
end
it 'includes the dse::ssl recipe' do
expect(chef_run).to include_recipe('dse::ssl')
end
it 'creates the directory /etc/cassandra where ssl keys are stored' do
expect(chef_run).to create_directory('/etc/cassandra').with(
user: 'cassandra',
group: 'cassandra',
mode: '0700'
)
end
it 'generates a cassandra cert' do
expect(chef_run).to run_bash('generate cassandra cert').with(
user: 'cassandra'
)
end
it 'generates a keystore password' do
expect(chef_run).to run_bash('generate keystore password').with(
user: 'cassandra'
)
end
it 'exports the public key' do
expect(chef_run).to run_bash('export public key').with(
user: 'cassandra'
)
end
it 'imports the public keys' do
expect(chef_run).to run_bash('import public keys').with(
user: 'cassandra'
)
end
end
| {'content_hash': '2dbe83d631cc7f1c430783659faf0404', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 93, 'avg_line_length': 32.539267015706805, 'alnum_prop': 0.674175382139984, 'repo_name': 'mbrukman/dse-cookbook', 'id': 'c3bf610a126a4dbf45918cdd9b7d7cc920ae5bc5', 'size': '6215', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/default_spec.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '701550'}, {'name': 'Ruby', 'bytes': '37019'}]} |
package org.picocontainer.defaults;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.Parameter;
import org.picocontainer.PicoVisitor;
import org.picocontainer.testmodel.Touchable;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
/**
* @author Jörg Schaible
*/
public class MethodCallingVisitorTest extends MockObjectTestCase {
private Method add;
private Method touch;
protected void setUp() throws Exception {
super.setUp();
add = List.class.getMethod("add", new Class[]{Object.class});
touch = Touchable.class.getMethod("touch", (Class[])null);
}
public void testVisitorWillTraverseAndCall() throws Exception {
MutablePicoContainer parent = new DefaultPicoContainer();
MutablePicoContainer child = new DefaultPicoContainer();
parent.addChildContainer(child);
parent.registerComponentImplementation(List.class, LinkedList.class, new Parameter[0]);
child.registerComponentImplementation(List.class, LinkedList.class, new Parameter[0]);
List parentList = (List)parent.getComponentInstanceOfType(List.class);
List childList = (List)child.getComponentInstanceOfType(List.class);
assertEquals(0, parentList.size());
assertEquals(0, childList.size());
PicoVisitor visitor = new MethodCallingVisitor(add, List.class, new Object[]{Boolean.TRUE});
visitor.traverse(parent);
assertEquals(1, parentList.size());
assertEquals(1, childList.size());
}
public void testVisitsInInstantiationOrder() throws Exception {
Mock mockTouchable1 = mock(Touchable.class);
Mock mockTouchable2 = mock(Touchable.class);
MutablePicoContainer parent = new DefaultPicoContainer();
MutablePicoContainer child = new DefaultPicoContainer();
parent.addChildContainer(child);
parent.registerComponentInstance(mockTouchable1.proxy());
child.registerComponentInstance(mockTouchable2.proxy());
mockTouchable1.expects(once()).method("touch").id("1");
mockTouchable2.expects(once()).method("touch").after(mockTouchable1, "1");
PicoVisitor visitor = new MethodCallingVisitor(touch, Touchable.class, null);
visitor.traverse(parent);
}
public void testVisitsInReverseInstantiationOrder() throws Exception {
Mock mockTouchable1 = mock(Touchable.class);
Mock mockTouchable2 = mock(Touchable.class);
MutablePicoContainer parent = new DefaultPicoContainer();
MutablePicoContainer child = new DefaultPicoContainer();
parent.addChildContainer(child);
parent.registerComponentInstance(mockTouchable1.proxy());
child.registerComponentInstance(mockTouchable2.proxy());
mockTouchable2.expects(once()).method("touch").id("1");
mockTouchable1.expects(once()).method("touch").after(mockTouchable2, "1");
PicoVisitor visitor = new MethodCallingVisitor(touch, Touchable.class, null, false);
visitor.traverse(parent);
}
}
| {'content_hash': 'cdb91a4a3e39d86afcf73eccc04445b2', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 100, 'avg_line_length': 37.98795180722892, 'alnum_prop': 0.7155090390104663, 'repo_name': 'picocontainer/PicoContainer1', 'id': 'fb08744bd8007baffa6f5f0c802b112138a716a7', 'size': '3706', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'container/src/test/org/picocontainer/defaults/MethodCallingVisitorTest.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '3233'}, {'name': 'HTML', 'bytes': '7018'}, {'name': 'Java', 'bytes': '1034023'}]} |
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; }
*:focus { outline: 0; }
body { line-height: 1em; color: black; background: #fff; }
ol, ul { list-style: none; }
/* tables still need 'cellspacing="0"' in the markup */
table { border-collapse: separate; border-spacing: 0; vertical-align: middle; }
caption, th, td { text-align: left; font-weight: normal; vertical-align: middle; }
q, blockquote { quotes: "" ""; }
q:before, q:after, blockquote:before, blockquote:after { content: ""; }
img a { border: none; }
body { line-height: 1.5; font-family: Helvetica Neue, Arial, Helvetica, sans-serif; color: #333333; font-size: 75%; }
h1 { font-weight: normal; color: #222222; font-size: 3em; line-height: 1; margin-bottom: 0.5em; }
h1 img { margin: 0; }
h2 { font-weight: normal; color: #222222; font-size: 2em; margin-bottom: 0.75em; }
h3 { font-weight: normal; color: #222222; font-size: 1.5em; line-height: 1; margin-bottom: 1em; }
h4 { font-weight: normal; color: #222222; font-size: 1.2em; line-height: 1.25; margin-bottom: 1.25em; }
h5 { font-weight: normal; color: #222222; font-size: 1em; font-weight: bold; margin-bottom: 1.5em; }
h6 { font-weight: normal; color: #222222; font-size: 1em; font-weight: bold; }
h2 img, h3 img, h4 img, h5 img, h6 img { margin: 0; }
p { margin: 0 0 1.5em; }
p img.left { display: inline; float: left; margin: 1.5em 1.5em 1.5em 0; padding: 0; }
p img.right { display: inline; float: right; margin: 1.5em 0 1.5em 1.5em; padding: 0; }
a { text-decoration: underline; color: #000099; }
a:visited { color: #000066; }
a:focus { color: black; }
a:hover { color: black; }
a:active { color: #cc0099; }
blockquote { margin: 1.5em; color: #666; font-style: italic; }
strong { font-weight: bold; }
em { font-style: italic; }
dfn { font-style: italic; font-weight: bold; }
sup, sub { line-height: 0; }
abbr, acronym { border-bottom: 1px dotted #666; }
address { margin: 0 0 1.5em; font-style: italic; }
del { color: #666; }
pre { margin: 1.5em 0; white-space: pre; }
pre, code, tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; }
li ul, li ol { margin: 0 1.5em; }
ul { margin: 0 1.5em 1.5em 1.5em; list-style-type: disc; }
ol { margin: 0 1.5em 1.5em 1.5em; list-style-type: decimal; }
dl { margin: 0 0 1.5em 0; }
dl dt { font-weight: bold; }
dd { margin-left: 1.5em; }
table { margin-bottom: 1.4em; width: 100%; }
th { font-weight: bold; }
thead th { background: #c3d9ff; }
th, td, caption { padding: 4px 10px 4px 5px; }
tr.even td { background: #e5ecf9; }
tfoot { font-style: italic; }
caption { background: #eee; }
.quiet { color: #666666; }
.loud { color: #111111; }
.clear { clear: both; }
.nowrap { white-space: nowrap; }
.clearfix { overflow: hidden; display: inline-block; }
.clearfix { display: block; }
.small { font-size: .8em; margin-bottom: 1.875em; line-height: 1.875em; }
.large { font-size: 1.2em; line-height: 2.5em; margin-bottom: 1.25em; }
.first { margin-left: 0; padding-left: 0; }
.last { margin-right: 0; padding-right: 0; }
.top { margin-top: 0; padding-top: 0; }
.bottom { margin-bottom: 0; padding-bottom: 0; }
.container { width: 950px; margin: 0 auto; overflow: hidden; display: inline-block; }
.container { display: block; }
.column, div.span-1, div.span-2, div.span-3, div.span-4, div.span-5, div.span-6, div.span-7, div.span-8, div.span-9, div.span-10, div.span-11, div.span-12, div.span-13, div.span-14, div.span-15, div.span-16, div.span-17, div.span-18, div.span-19, div.span-20, div.span-21, div.span-22, div.span-23, div.span-24 { display: inline; float: left; margin-right: 10px; }
* html .column, * html div.span-1, * html div.span-2, * html div.span-3, * html div.span-4, * html div.span-5, * html div.span-6, * html div.span-7, * html div.span-8, * html div.span-9, * html div.span-10, * html div.span-11, * html div.span-12, * html div.span-13, * html div.span-14, * html div.span-15, * html div.span-16, * html div.span-17, * html div.span-18, * html div.span-19, * html div.span-20, * html div.span-21, * html div.span-22, * html div.span-23, * html div.span-24 { overflow-x: hidden; }
.last, div.last { margin-right: 0; }
.span-1 { width: 30px; }
.span-2 { width: 70px; }
.span-3 { width: 110px; }
.span-4 { width: 150px; }
.span-5 { width: 190px; }
.span-6 { width: 230px; }
.span-7 { width: 270px; }
.span-8 { width: 310px; }
.span-9 { width: 350px; }
.span-10 { width: 390px; }
.span-11 { width: 430px; }
.span-12 { width: 470px; }
.span-13 { width: 510px; }
.span-14 { width: 550px; }
.span-15 { width: 590px; }
.span-16 { width: 630px; }
.span-17 { width: 670px; }
.span-18 { width: 710px; }
.span-19 { width: 750px; }
.span-20 { width: 790px; }
.span-21 { width: 830px; }
.span-22 { width: 870px; }
.span-23 { width: 910px; }
.span-24, div.span-24 { width: 950px; margin: 0; }
input.span-1, textarea.span-1, select.span-1 { width: 30px !important; }
input.span-2, textarea.span-2, select.span-2 { width: 70px !important; }
input.span-3, textarea.span-3, select.span-3 { width: 110px !important; }
input.span-4, textarea.span-4, select.span-4 { width: 150px !important; }
input.span-5, textarea.span-5, select.span-5 { width: 190px !important; }
input.span-6, textarea.span-6, select.span-6 { width: 230px !important; }
input.span-7, textarea.span-7, select.span-7 { width: 270px !important; }
input.span-8, textarea.span-8, select.span-8 { width: 310px !important; }
input.span-9, textarea.span-9, select.span-9 { width: 350px !important; }
input.span-10, textarea.span-10, select.span-10 { width: 390px !important; }
input.span-11, textarea.span-11, select.span-11 { width: 430px !important; }
input.span-12, textarea.span-12, select.span-12 { width: 470px !important; }
input.span-13, textarea.span-13, select.span-13 { width: 510px !important; }
input.span-14, textarea.span-14, select.span-14 { width: 550px !important; }
input.span-15, textarea.span-15, select.span-15 { width: 590px !important; }
input.span-16, textarea.span-16, select.span-16 { width: 630px !important; }
input.span-17, textarea.span-17, select.span-17 { width: 670px !important; }
input.span-18, textarea.span-18, select.span-18 { width: 710px !important; }
input.span-19, textarea.span-19, select.span-19 { width: 750px !important; }
input.span-20, textarea.span-20, select.span-20 { width: 790px !important; }
input.span-21, textarea.span-21, select.span-21 { width: 830px !important; }
input.span-22, textarea.span-22, select.span-22 { width: 870px !important; }
input.span-23, textarea.span-23, select.span-23 { width: 910px !important; }
input.span-24, textarea.span-24, select.span-24 { width: 950px !important; }
.append-1 { padding-right: 40px; }
.append-2 { padding-right: 80px; }
.append-3 { padding-right: 120px; }
.append-4 { padding-right: 160px; }
.append-5 { padding-right: 200px; }
.append-6 { padding-right: 240px; }
.append-7 { padding-right: 280px; }
.append-8 { padding-right: 320px; }
.append-9 { padding-right: 360px; }
.append-10 { padding-right: 400px; }
.append-11 { padding-right: 440px; }
.append-12 { padding-right: 480px; }
.append-13 { padding-right: 520px; }
.append-14 { padding-right: 560px; }
.append-15 { padding-right: 600px; }
.append-16 { padding-right: 640px; }
.append-17 { padding-right: 680px; }
.append-18 { padding-right: 720px; }
.append-19 { padding-right: 760px; }
.append-20 { padding-right: 800px; }
.append-21 { padding-right: 840px; }
.append-22 { padding-right: 880px; }
.append-23 { padding-right: 920px; }
.prepend-1 { padding-left: 40px; }
.prepend-2 { padding-left: 80px; }
.prepend-3 { padding-left: 120px; }
.prepend-4 { padding-left: 160px; }
.prepend-5 { padding-left: 200px; }
.prepend-6 { padding-left: 240px; }
.prepend-7 { padding-left: 280px; }
.prepend-8 { padding-left: 320px; }
.prepend-9 { padding-left: 360px; }
.prepend-10 { padding-left: 400px; }
.prepend-11 { padding-left: 440px; }
.prepend-12 { padding-left: 480px; }
.prepend-13 { padding-left: 520px; }
.prepend-14 { padding-left: 560px; }
.prepend-15 { padding-left: 600px; }
.prepend-16 { padding-left: 640px; }
.prepend-17 { padding-left: 680px; }
.prepend-18 { padding-left: 720px; }
.prepend-19 { padding-left: 760px; }
.prepend-20 { padding-left: 800px; }
.prepend-21 { padding-left: 840px; }
.prepend-22 { padding-left: 880px; }
.prepend-23 { padding-left: 920px; }
.pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 { display: inline; float: left; position: relative; }
.pull-1 { margin-left: -40px; }
.pull-2 { margin-left: -80px; }
.pull-3 { margin-left: -120px; }
.pull-4 { margin-left: -160px; }
.pull-5 { margin-left: -200px; }
.pull-6 { margin-left: -240px; }
.pull-7 { margin-left: -280px; }
.pull-8 { margin-left: -320px; }
.pull-9 { margin-left: -360px; }
.pull-10 { margin-left: -400px; }
.pull-11 { margin-left: -440px; }
.pull-12 { margin-left: -480px; }
.pull-13 { margin-left: -520px; }
.pull-14 { margin-left: -560px; }
.pull-15 { margin-left: -600px; }
.pull-16 { margin-left: -640px; }
.pull-17 { margin-left: -680px; }
.pull-18 { margin-left: -720px; }
.pull-19 { margin-left: -760px; }
.pull-20 { margin-left: -800px; }
.pull-21 { margin-left: -840px; }
.pull-22 { margin-left: -880px; }
.pull-23 { margin-left: -920px; }
.pull-24 { margin-left: -960px; }
.push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 { display: inline; float: right; position: relative; }
.push-1 { margin: 0 -40px 1.5em 40px; }
.push-2 { margin: 0 -80px 1.5em 80px; }
.push-3 { margin: 0 -120px 1.5em 120px; }
.push-4 { margin: 0 -160px 1.5em 160px; }
.push-5 { margin: 0 -200px 1.5em 200px; }
.push-6 { margin: 0 -240px 1.5em 240px; }
.push-7 { margin: 0 -280px 1.5em 280px; }
.push-8 { margin: 0 -320px 1.5em 320px; }
.push-9 { margin: 0 -360px 1.5em 360px; }
.push-10 { margin: 0 -400px 1.5em 400px; }
.push-11 { margin: 0 -440px 1.5em 440px; }
.push-12 { margin: 0 -480px 1.5em 480px; }
.push-13 { margin: 0 -520px 1.5em 520px; }
.push-14 { margin: 0 -560px 1.5em 560px; }
.push-15 { margin: 0 -600px 1.5em 600px; }
.push-16 { margin: 0 -640px 1.5em 640px; }
.push-17 { margin: 0 -680px 1.5em 680px; }
.push-18 { margin: 0 -720px 1.5em 720px; }
.push-19 { margin: 0 -760px 1.5em 760px; }
.push-20 { margin: 0 -800px 1.5em 800px; }
.push-21 { margin: 0 -840px 1.5em 840px; }
.push-22 { margin: 0 -880px 1.5em 880px; }
.push-23 { margin: 0 -920px 1.5em 920px; }
.push-24 { margin: 0 -960px 1.5em 960px; }
.showgrid { background: url('/images/grid.png'); }
.error { padding: .8em; margin-bottom: 1em; border: 2px solid #dddddd; background: #fbe3e4; color: #8a1f11; border-color: #fbc2c4; }
.error a { color: #8a1f11; }
.notice { padding: .8em; margin-bottom: 1em; border: 2px solid #dddddd; background: #fff6bf; color: #514721; border-color: #ffd324; }
.notice a { color: #514721; }
.success { padding: .8em; margin-bottom: 1em; border: 2px solid #dddddd; background: #e6efc2; color: #264409; border-color: #c6d880; }
.success a { color: #264409; }
.hide { display: none; }
.highlight { background: yellow; }
.added { background: #006600; color: white; }
.removed { background: #990000; color: white; }
label { font-weight: bold; }
fieldset { padding: 1.4em; margin: 0 0 1.5em 0; }
legend { font-weight: bold; font-size: 1.2em; }
input.text, input.title, input[type=text] { margin: 0.5em 0; background-color: #fff; padding: 5px; }
input.title { font-size: 1.5em; }
input[type=checkbox], input.checkbox, input[type=radio], input.radio { position: relative; top: 0.25em; }
textarea { margin: 0.5em 0; padding: 5px; }
select { margin: 0.5em 0; }
fieldset { border: 1px solid #cccccc; }
input.text, input.title, textarea, select { border: 1px solid #bbbbbb; }
input.text:focus, input.title:focus, textarea:focus, select:focus { border: 1px solid #666666; }
input.text, input.title { width: 300px; }
textarea { width: 390px; height: 250px; }
.box { padding: 1.5em; margin-bottom: 1.5em; background: #E5ECF9; }
div.border { padding-right: 4px; margin-right: 5px; border-right: 1px solid #eeeeee; }
div.colborder { padding-right: 24px; margin-right: 25px; border-right: 1px solid #eeeeee; }
hr { background: #dddddd; color: #dddddd; clear: both; float: none; width: 100%; height: .1em; margin: 0 0 1.45em; border: none; }
hr.space { background: #dddddd; color: #dddddd; clear: both; float: none; width: 100%; height: .1em; margin: 0 0 1.45em; border: none; background: #fff; color: #fff; }
body { margin-top: 10px; background: #fff url(/images/body-back.png) top left repeat-x; }
body div.left { float: left; width: 49%; }
body div.right { float: right; width: 49%; text-align: right; }
#wrapper { background: transparent url(/images/wrapper-back.png) top center no-repeat; padding: 25px 20px 20px; position: relative; }
body.two-col #wrapper { background-image: url(/images/wrapper-back-2.png); }
#sidebar { display: inline; float: left; margin-right: 10px; width: 150px; padding-right: 24px; margin-right: 25px; border-right: 1px solid #eeeeee; }
* html #sidebar { overflow-x: hidden; }
#sidebar h3 { margin-bottom: .5em; }
body.one-col #content { display: inline; float: left; margin-right: 0; width: 950px; }
* html body.one-col #content { overflow-x: hidden; }
body.two-col #content { display: inline; float: left; margin-right: 0; width: 750px; }
* html body.two-col #content { overflow-x: hidden; }
#header { position: relative; color: #2e6ab1; clear: both; }
#header a { color: #2e6ab1; }
#header a:hover { color: #e5f2f8; }
#footer { display: inline; float: left; margin-right: 0; width: 950px; margin-top: 20px; padding-top: 0.5em; clear: both; background: #F0F8F8 none repeat scroll 0; color: #009999; line-height: 24px; font-family: Arial,Helvetica,sans-serif; }
* html #footer { overflow-x: hidden; }
#footer a { cursor: pointer!important; text-decoration: none; padding-left: 10px; color: #006C94; font-size: 12px; }
h1 { font-size: 2.5em; }
.navigation-list { margin: 0 0 1.5em -15px; }
.navigation-list li { list-style-type: none; margin-left: 0px; }
.navigation-list li { margin: 0; }
.navigation-list li a { cursor: pointer!important; text-decoration: none; color: #333; display: block; line-height: 2.5em; padding-left: 20px; }
.navigation-list li a:hover { width: 170px; background: url(/images/menu-hover.png) right center no-repeat; }
.navigation-list li.current { width: 200px; }
.navigation-list li.current a { background: url(/images/menu-current.png) right center no-repeat; }
.navigation-list li.current a:hover { width: 180px; }
.breadcrumbs { margin-bottom: 1em; }
.breadcrumbs ul { list-style-type: none; margin: 0px; padding: 0px; display: inline; overflow: auto; margin: 0; padding: 0; }
.breadcrumbs ul li { margin: 0px; padding: 0px; display: inline; }
.breadcrumbs ul li { line-height: 20px; color: #666; }
.breadcrumbs ul li a, .breadcrumbs ul li span { text-decoration: none; padding: 5px 7px; color: #666; }
.breadcrumbs ul li span { color: #333; }
div#login-bar { display: inline; }
ul#language-bar { list-style-type: none; margin: 0px; padding: 0px; display: inline; }
ul#language-bar li { margin: 0px; padding: 0px; display: inline; }
ul#language-bar strong { font-weight: normal; }
ul#nav-bar { line-height: 50px; float: right; clear: both; font-size: 1.2em; list-style: none; margin: 0; padding: 0; }
ul#nav-bar li { float: left; margin-left: 1em; }
ul#nav-bar li.cart-indicator a { display: block; padding-right: 40px; background: transparent url(/images/cart-empty_x32.png) center right no-repeat; }
ul#nav-bar li.cart-indicator a.full { background-image: url(/images/cart-full_x32.png); }
.pagination { padding-top: 10px; text-align: right; }
.pagination a.page, .pagination span.page { padding: 0px 5px; margin: 0 3px; }
.pagination a.page { text-decoration: none; border: 1px solid #9aafe5; color: #2e6ab1; }
.pagination a.page:hover, .pagination a.page:active { border: 1px solid #2b66a5; color: #000; }
.pagination a.next_page { font-weight: bold; }
.pagination span.disabled_page { border: 1px solid #929292; color: #929292; }
.pagination span.current_page { font-weight: bold; border: 1px solid; border-color: #162f54; background-color: #2e6ab1; color: #FFF; }
.product-listing { margin: 2em 0 0 0; padding: 0; }
.product-listing li { list-style-type: none; margin-left: 0px; }
.product-listing li { height: 180px; width: 140px; text-align: center; float: left; margin: 1em; padding: 10px; border: 1px solid #ddd; position: relative; -moz-border-radius: 3px; -webkit-border-radius: 3px; }
.product-listing li a { display: block; text-decoration: none; color: #111; }
.product-listing li a.info { position: absolute; bottom: 0px; right: 0em; padding: 5px; width: 150px; min-height: 60px; background: #fff url(/images/shadow_top.png) 0px -35px repeat-x; border-top: 1px solid #fff; }
.product-listing li a.info span { display: block; }
.product-listing li.last { margin-right: 0; }
.product-listing li:hover { border-color: #1b1b1b; }
.product-listing li:hover a.info { background: #1b1b1b url(/images/bottom_shine.png) bottom left repeat-x; color: #fff; }
ul#product-thumbnails { margin: 0; padding: 0; list-style: none; }
ul#product-thumbnails li { float: left; margin-right: 5px; padding: 3px; border: 1px solid #fff; }
ul#product-thumbnails li:hover { border-color: #ccc; }
ul#product-thumbnails li.selected { border-color: #999; }
#product-variants { margin-bottom: 1em; }
#product-variants ul { margin: 0; padding: 0; }
#product-variants ul li { list-style-type: none; margin-left: 0px; }
#product-images { display: inline; float: left; margin-right: 10px; width: 270px; }
* html #product-images { overflow-x: hidden; }
#product-description { display: inline; float: left; margin-right: 10px; width: 150px; }
* html #product-description { overflow-x: hidden; }
#product-properties { display: inline; float: left; margin-right: 0; width: 150px; }
* html #product-properties { overflow-x: hidden; }
#cart-form { display: inline; float: left; margin-right: 0; width: 270px; }
* html #cart-form { overflow-x: hidden; }
#cart-form button.large { margin-bottom: 0px; }
#product-detail li { list-style-type: none; margin-left: 0px; }
#product-detail li { text-align: left; margin: 1em; border: none; }
#product-detail li a { color: #006699; font-family: Trebuchet MS, Arial, Helvetica, sans-serif; font-size: 14px; line-height: 24px; text-decoration: none; }
#product-detail li a:hover { background: #F4F4F4 no-repeat scroll 0 0; color: #006699; padding-right: 5px; }
.prices { font-weight: bold; }
#product-details .prices { font-size: 1.25em; }
.price.selling { color: #2e6ab1; }
#product-details .price.selling { font-size: 1.5em; }
.price.diff { font-style: italic; font-weight: normal; color: #666666; }
#subtotal { float: right; }
#signup #new-customer, #login #existing-customer { display: inline; float: left; margin-right: 10px; width: 470px; }
* html #signup #new-customer, * html #login #existing-customer { overflow-x: hidden; }
#signup #new-customer h2, #login #existing-customer h2 { margin-bottom: .25em; }
#signup #new-customer p, #login #existing-customer p { margin-bottom: 10px; }
#signup #new-customer p input.title, #login #existing-customer p input.title { padding: 3px; margin: 0px; }
.formError, .errorExplanation { font-size: 1.3em; margin-bottom: 1em; padding: 0.8em; -moz-border-radius: 5px; -webkit-border-radius: 5px; background: #F4B4B4 url(/images/shadow_top.png) repeat-x scroll 0pt -50px; border: 1px solid #000; color: #000; }
.formError p, .errorExplanation p { margin: 0px; }
.formError ul, .errorExplanation ul { margin-bottom: 0px; }
.formError h2, .errorExplanation h2 { font-weight: bold; font-size: 1.0em; margin: 0px; }
.fieldWithErrors { clear: none; }
div#checkout div#registration div.error, div#checkout div#shipping_method div.error { width: 815px; -moz-border-radius: 5px; -webkit-border-radius: 5px; }
div#checkout div#billing input, div#checkout div#shipping input, div#checkout div#payment input, div#checkout div#registration_input input { border: 1px solid #BBB; }
div#checkout div.inner { display: none; padding: 10px 2px; }
div#checkout h2 { margin-bottom: 0.25em; }
div#checkout select.error, div#checkout input.error { padding: 0px; background: #FFF; border: 1px solid #EAE8E3; }
div#checkout p { clear: both; margin-bottom: 15px; }
div#checkout p label { float: left; width: 150px; position: relative; top: 5px; }
div#checkout p span.req { color: red; margin-left: 2px; position: relative; top: -3px; }
div#checkout p input, div#checkout p select { margin-left: 150px; width: 200px; margin: 0px; }
div#checkout p label.error { color: red; clear: both; margin: 0px 0px 5px 150px; top: 0px; font-size: 11px; border: none; padding: 0px; background: #FFF; }
div#checkout label.radio { display: inline; }
div#checkout div#methods p, div#checkout div#registration_choice p { margin-bottom: 7px; }
div#checkout div#methods p input, div#checkout div#methods p label, div#checkout div#registration_choice p input, div#checkout div#registration_choice p label { display: inline; float: none; }
div#checkout div#methods p label, div#checkout div#registration_choice p label { margin: 0px 0px 0px 5px; top: -1px; width: 300px; }
div#checkout div#methods p input, div#checkout div#registration_choice p input { width: 15px; }
div#checkout #registration { background: transparent url(/images/steps/1.png) top right no-repeat; }
div#checkout #registration.completed, div#checkout #registration.disabled { background-image: none; }
div#checkout #registration.completed h2, div#checkout #registration.disabled h2 { background: transparent url(/images/steps/1_small.png) top left no-repeat; }
div#checkout #registration div#registration_choice { float: left; block: none; margin-bottom: 1em; }
div#checkout #registration div#registration_input { float: left; margin-left: 100px; }
div#checkout #registration div#guest_user, div#checkout #registration div#existing_user { display: none; }
div#checkout #registration div#already_logged_in { display: none; }
div#checkout #billing { background: transparent url(/images/steps/2.png) top right no-repeat; }
div#checkout #billing.completed, div#checkout #billing.disabled { background-image: none; }
div#checkout #billing.completed h2, div#checkout #billing.disabled h2 { background: transparent url(/images/steps/2_small.png) top left no-repeat; }
div#checkout #shipping { background: transparent url(/images/steps/3.png) top right no-repeat; }
div#checkout #shipping label#use_billing { top: -3px; }
div#checkout #shipping input#checkout_same_address { border: none; width: 12px; }
div#checkout #shipping.completed, div#checkout #shipping.disabled { background-image: none; }
div#checkout #shipping.completed h2, div#checkout #shipping.disabled h2 { background: transparent url(/images/steps/3_small.png) top left no-repeat; padding-left: 32px; }
div#checkout #shipping_method { background: transparent url(/images/steps/4.png) top right no-repeat; }
div#checkout #shipping_method div.inner { padding-top: 0px; }
div#checkout #shipping_method.completed, div#checkout #shipping_method.disabled { background-image: none; }
div#checkout #shipping_method.completed h2, div#checkout #shipping_method.disabled h2 { background: transparent url(/images/steps/4_small.png) top left no-repeat; }
div#checkout #shipping_method div.error { display: none; }
div#checkout #payment { background: transparent url(/images/steps/5.png) top right no-repeat; }
div#checkout #payment.completed, div#checkout #payment.disabled { background-image: none; }
div#checkout #payment.completed h2, div#checkout #payment.disabled h2 { background: transparent url(/images/steps/5_small.png) top left no-repeat; }
div#checkout #payment p select { width: 75px; }
div#checkout #confirmation { background: transparent url(/images/steps/6.png) top right no-repeat; }
div#checkout #confirmation.completed, div#checkout #confirmation.disabled { background-image: none; }
div#checkout #confirmation.completed h2, div#checkout #confirmation.disabled h2 { background: transparent url(/images/steps/6_small.png) top left no-repeat; }
div#checkout #confirmation table.order-summary .price, div#checkout #confirmation table.order-summary .qty { width: 165px; }
div#checkout #confirmation table.order-summary .total_display { width: 300px; }
div#checkout #confirmation table.order-summary .total_display span { display: block; text-align: right; padding-right: 150px; }
div#checkout #confirmation div#bdisplay, div#checkout #confirmation div#sdisplay { float: left; width: 300px; clear: right; }
div#checkout .checkout.disabled h2, div#checkout .checkout.completed h2 { padding-left: 32px; color: #AFAFAF; font-size: 1.4em; padding-bottom: 10px; border-bottom: 1px solid #ddd; }
div#checkout .checkout.disabled:last-child h2, div#checkout .checkout.completed:last-child h2 { border-bottom: none; }
div#checkout .checkout.completed h2 { color: #111; border-color: #999; }
div#checkout input#continue_billing, div#checkout input#continue_shipping { cursor: pointer; width: 100px; display: block; clear: both; margin-top: 10px; }
div#checkout p input#continue_registration, div#checkout p input#continue_shipping_method, div#checkout p input#continue_payment, div#checkout #confirm_order .inner input { cursor: pointer; width: 100px; }
.form-buttons { clear: both; }
.clear { clear: both; }
button, a.button, input.button { background: #efefef url(/images/buttons/bg-button.png) center left repeat-x !important; border-style: solid; border-width: 1px !important; border-color: #ddd #999 #999 #ddd !important; -moz-border-radius: .3em; -webkit-border-radius: .3em; -moz-outline-radius: .3em; color: #111; display: inline-block; font-family: Helvetica Neue, Helvetica, Arial, Sans-serif; font-size: 1.1em !important; font-size-adjust: none; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; line-height: 1.2em; margin: 0; overflow: visible; padding: 10px 17px; text-decoration: none; text-transform: lowercase; width: auto; height: auto; cursor: pointer; }
button.primary, a.button.primary, input.button.primary { font-weight: bold; color: #000; }
button:hover, a.button:hover, input.button:hover { background-image: url(/images/buttons/bg-button-hover.png) !important; }
button.large, a.button.large, input.button.large { font-size: 1.4em !important; line-height: 1.4em; -moz-border-radius: 5px; -webkit-border-radius: 5px; }
button.small, a.button.small, input.button.small { font-size: .9em; line-height: 1.4em; padding: 5px 10px; -moz-border-radius: 4px; -webkit-border-radius: 4px; }
button.small img, a.button.small img, input.button.small img { margin: 0 3px 0 0 !important; }
button.update img, button.checkout img, a.button.update img, input.button.update img, a.button.checkout img, input.button.checkout img { margin-right: 7px; }
button img, a.button img, input.button img { vertical-align: middle; }
input.title { width: auto; }
p a.button img, p button img { margin: 0 5px 0 0; }
p.follow-all { font-size: 1.3em; text-align: center; display: block; }
p img { float: left; margin-right: 5px; vertical-align: middle; }
a.button:focus { outline: none; }
button::-moz-focus-inner { padding: 0; border: none; }
table { border-collapse: collapse; }
table th { background: transparent; padding: 10px; border-bottom: 1px solid #ddd; }
table#cart tr td { border-bottom: 1px solid #ddd; padding: 1em 0; }
table#cart tr#none td { border-bottom: none; }
table#cart h4 { margin-bottom: 0em; }
.flash { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.flash.notice, .flash.errors { font-size: 1.3em; margin-bottom: 1em; padding: 0.8em; }
.flash.notice { background: #cdf url(/images/shadow_top.png) 0 -50px repeat-x; color: #569; border: 1px solid #9ac; }
.flash.errors { color: #000; background: #F4B4B4 url(/images/shadow_top.png) 0 -50px repeat-x; border: 1px solid #000; }
| {'content_hash': '87339feb3dba5729d90bceaf4eff241e', 'timestamp': '', 'source': 'github', 'line_count': 646, 'max_line_length': 698, 'avg_line_length': 44.473684210526315, 'alnum_prop': 0.6954403063000348, 'repo_name': 'Ideas2IT/augur', 'id': '99383269dcd0d932282067f09f72845dc7c5d4bb', 'size': '28730', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/extensions/site/public/stylesheets/compiled/screen.css', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '65391'}, {'name': 'Ruby', 'bytes': '31465'}]} |
import got from "got";
import cheerio from "cheerio";
import randomUseragent from "random-useragent";
export default class IMDBScraperModel {
_posterSelector: string;
_imdbPath: string;
constructor() {
this._posterSelector = "div.ipc-poster > div.ipc-media__img > img";
this._imdbPath = "https://www.imdb.com/title/";
}
getPosterURL(imdbID) {
const url = this._buildImdbPath(imdbID);
const options = {
retry: 0,
headers: {
"user-agent": randomUseragent.getRandom((ua) => {
return (
parseFloat(ua.browserVersion) >= 20 &&
ua.browserName === "Firefox"
);
}),
accept: "text/html",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
pragma: "no-cache",
},
};
return got.get(url, options).then((resp) => {
const $ = cheerio.load(resp.body);
const imageURL = $(this._posterSelector).attr("src");
return {
imageURL,
url,
};
});
}
_buildImdbPath(imdbID) {
return this._imdbPath + imdbID;
}
}
| {'content_hash': 'c633f1a8a795a1692e3a8dee64770eb2', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 75, 'avg_line_length': 30.186046511627907, 'alnum_prop': 0.47919876733436056, 'repo_name': 'destinmoulton/idiot-box', 'id': 'd50daad0b53a62850dc00ee414a01354f4477272', 'size': '1298', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/server/models/IMDBScraperModel.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '231278'}, {'name': 'SCSS', 'bytes': '18720'}, {'name': 'TypeScript', 'bytes': '89693'}]} |
class KestrelQueueMonitor < Scout::Plugin
OPTIONS=<<-EOS
host:
label: Host
notes: Kestrel host
default: localhost
port:
label: Port
notes: Kestrel admin HTTP port
default: 2223
queue:
label: Queue
notes: Name of Kestrel queue
EOS
needs 'open-uri'
needs 'json'
def build_report
report :items => gauge_stat(:items), :open_transacitons => gauge_stat(:open_transactions),
:mem_items => gauge_stat(:mem_items), :age => gauge_stat(:age_msec).to_f / 1000,
:waiters => gauge_stat(:waiters)
counter(:item_rate, counter_stat(:total_items), :per => :second)
end
def counter_stat(stat)
stats['counters']["q/#{option(:queue)}/#{stat.to_s}"]
end
def gauge_stat(stat)
stats['gauges']["q/#{option(:queue)}/#{stat.to_s}"]
end
def stats
@stats ||= JSON.parse(open("http://#{option(:host)}:#{option(:port)}/admin/stats").read)
end
end
| {'content_hash': '440ccd1c17f1242c56240e8e93e84777', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 94, 'avg_line_length': 24.894736842105264, 'alnum_prop': 0.6078224101479915, 'repo_name': 'speric/scout-plugins', 'id': '2d5dc0e43ab7941189694ea177268a274e6f13da', 'size': '1000', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kestrel_queue/kestrel_queue.rb', 'mode': '33188', 'license': 'mit', 'language': []} |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module RenderGraph
( RenderNode(..)
, type (|>)(..)
, Cull, CullOp(..), cull
, GLIO, glIO
, MultiplePasses, multiplePasses
, BlendMode, blendMode
, BindTexture, bindTexture
, SetUniform, RenderGraph.setUniform
, DepthFunc, depthFunc
, AlphaFunc, alphaFunc
, Viewport, viewport
, MonoidalMap(..)
, GLSLType(..)
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Data.Bits
import Data.Coerce
import Data.Foldable (toList)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Map (Map)
import qualified Data.Map as Map
import GLObjects
import Graphics.GL.Compatibility45
import Linear
-- | The class of types that act as rendering nodes - generally operations that
-- manipulate OpenGL state.
class RenderNode a m where
draw :: a -> m ()
instance Monad m => RenderNode () m where
draw = return
-- Composing render graphs (functor composition)
infixr 6 |>
newtype (g |> f) a = Compose { getCompose :: g (f a) }
deriving (Functor)
instance Monoid (g (f a)) => Monoid ((g |> f) a) where
mempty = Compose mempty
mappend (Compose a) (Compose b) = Compose (a `mappend` b)
instance (RenderNode (g (f a)) m, Monad m) => RenderNode ((g |> f) a) m where
draw (Compose f) = draw f
-- Monoidal maps
newtype MonoidalMap k a = MonoidalMap { getMonoidalMap :: Map k a }
instance Functor (MonoidalMap k) where
fmap f (MonoidalMap a) = MonoidalMap (fmap f a)
instance (Monoid a, Ord k) =>
Monoid (MonoidalMap k a) where
mempty = MonoidalMap Map.empty
mappend (MonoidalMap a) (MonoidalMap b) =
MonoidalMap (Map.unionWith mappend a b)
mconcat =
coerce . Map.unionsWith mappend . (coerce :: [MonoidalMap k a] -> [Map k a])
-- glCullFace
data CullOp = CullNothing | CullFace GLuint
deriving (Eq, Ord)
newtype Cull a = Cull (MonoidalMap CullOp a)
deriving (Functor, Monoid)
cull :: CullOp -> a -> Cull a
cull op a = Cull (MonoidalMap (Map.singleton op a))
instance (MonadIO m, RenderNode a m) =>
RenderNode (Cull a) m where
draw (Cull items) = do
Map.foldrWithKey
(\cullop children k -> do
case cullop of
CullNothing -> glDisable GL_CULL_FACE
CullFace f -> do
glEnable GL_CULL_FACE
glCullFace f
draw children
k)
(return ())
(getMonoidalMap items)
-- Do arbitrary IO. GL state transitions could be violated here!
newtype GLIO a = GLIO { runGLIO :: (IO (), a) }
deriving (Monoid)
instance (MonadIO m, RenderNode a m) => RenderNode (GLIO a) m where
draw (GLIO (io, child)) = do
liftIO io
draw child
glIO :: IO () -> a -> GLIO a
glIO io a = GLIO (io, a)
-- Multi-pass rendering
newtype MultiplePasses a = MultiplePasses (MonoidalIntMap a)
deriving (Functor, Monoid)
instance (Applicative m, RenderNode a m) =>
RenderNode (MultiplePasses a) m where
draw (MultiplePasses (MonoidalIntMap passes)) =
IM.foldr (\a k -> draw a *> k) (pure ()) passes
multiplePasses :: Foldable f => f a -> MultiplePasses a
multiplePasses =
MultiplePasses . MonoidalIntMap . IM.fromDistinctAscList . zip [0 ..] . toList
-- Set blend mode
newtype BlendMode a = BlendMode (MonoidalMap (GLuint, GLuint) a)
deriving (Functor, Monoid)
blendMode :: (GLuint, GLuint) -> a -> BlendMode a
blendMode srcDst = BlendMode . MonoidalMap . Map.singleton srcDst
instance (MonadIO m, RenderNode a m) =>
RenderNode (BlendMode a) m where
draw (BlendMode m) =
Map.foldrWithKey
(\(srcBlend, destBlend) child next -> do
glBlendFunc srcBlend destBlend
draw child
next)
(return ())
(getMonoidalMap m)
-- Texture units
newtype BindTexture a = BindTexture (MonoidalIntMap a)
deriving (Functor, Monoid)
bindTexture :: GLuint -> a -> BindTexture a
bindTexture t = BindTexture . MonoidalIntMap . IM.singleton (fromIntegral t)
instance (MonadIO m, RenderNode a m) =>
RenderNode (BindTexture a) m where
draw (BindTexture t) =
IM.foldrWithKey
(\texture0 m next -> do
glActiveTexture GL_TEXTURE0
glBindTexture GL_TEXTURE_2D (fromIntegral texture0)
draw m
next)
(return ())
(getMonoidalIntMap t)
-- Monoidal IntMaps
newtype MonoidalIntMap a = MonoidalIntMap { getMonoidalIntMap :: IntMap a }
deriving (Functor)
instance Monoid a => Monoid (MonoidalIntMap a) where
mempty = MonoidalIntMap IM.empty
mappend (MonoidalIntMap a) (MonoidalIntMap b) = MonoidalIntMap (IM.unionWith mappend a b)
mconcat = coerce . IM.unionsWith mappend . (coerce :: [MonoidalIntMap a] -> [IntMap a])
-- Set uniform parameters
newtype SetUniform uniformType a = SetUniform (MonoidalMap (String, uniformType) a)
deriving (Functor, Monoid)
setUniform :: String -> uniformType -> a -> SetUniform uniformType a
setUniform k !v = SetUniform . MonoidalMap . Map.singleton (k, v)
class GLSLType a where
setter :: UniformSetter a
instance GLSLType Bool where
setter = bool
instance GLSLType (M33 Float) where
setter = m33
instance (RenderNode a (ReaderT (x, Program) IO), GLSLType k) =>
RenderNode (SetUniform k a) (ReaderT (x, Program) IO) where
draw (SetUniform m) =
Map.foldrWithKey
(\(name, v) children next -> do
ReaderT $ \(_, program) -> GLObjects.setUniform setter program name v
draw children
next)
(return ())
(getMonoidalMap m)
-- Setting depth functions
newtype DepthFunc a = DepthFunc (MonoidalMap GLuint a)
deriving (Functor, Monoid)
depthFunc :: GLuint -> a -> DepthFunc a
depthFunc d = DepthFunc . MonoidalMap . Map.singleton d
instance (RenderNode a m, MonadIO m) =>
RenderNode (DepthFunc a) m where
draw (DepthFunc m) =
Map.foldrWithKey
(\d child next -> do
glDepthFunc d
draw child
next)
(return ())
(getMonoidalMap m)
-- Alpha testing
newtype AlphaFunc a = AlphaFunc (MonoidalMap (Maybe (GLenum, GLclampf)) a)
deriving (Functor, Monoid)
alphaFunc :: Maybe (GLuint, GLclampf) -> a -> AlphaFunc a
alphaFunc d = AlphaFunc . MonoidalMap . Map.singleton d
instance (RenderNode a m, MonadIO m) =>
RenderNode (AlphaFunc a) m where
draw (AlphaFunc m) =
Map.foldrWithKey
(\d child next -> do
case d of
Just (func, ref) -> do
glEnable GL_ALPHA_TEST
glAlphaFunc func ref
Nothing -> glDisable GL_ALPHA_TEST
draw child
next)
(return ())
(getMonoidalMap m)
-- View from a camera, generally the top-most node in rendering.
data Viewport a = Viewport
{ viewViewport :: (GLint, GLint, GLint, GLint)
, viewChild :: a
} deriving (Functor)
instance (RenderNode a m, MonadIO m) => RenderNode (Viewport a) m where
draw (Viewport (x, y, w, h) child) = do
liftIO $ do
glViewport x y w h
glClearColor 0 0 0 0
glClear (GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT)
draw child
viewport :: (GLint, GLint, GLint, GLint) -> a -> Viewport a
viewport = Viewport
| {'content_hash': 'b378fa2c9c44daa2fe3c54e343abe627', 'timestamp': '', 'source': 'github', 'line_count': 277, 'max_line_length': 91, 'avg_line_length': 26.787003610108304, 'alnum_prop': 0.6644204851752021, 'repo_name': 'ocharles/hs-quake-3', 'id': '53e5962059804d1fe5c8722edf2764261ece4110', 'size': '7420', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'RenderGraph.hs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'GLSL', 'bytes': '917'}, {'name': 'Haskell', 'bytes': '85818'}, {'name': 'Nix', 'bytes': '1618'}]} |
Small wrapper module for using the great Python PySerial module (<http://pyserial.sourceforge.net/>) from Julia with the help of PyCall (<https://github.com/stevengj/PyCall.jl>).
## Usage
Example usage:
using PySerial
# construct a serial port object
# positional and keyword arguments can be used just like in the python module
ser = Serial("/dev/ttyUSB0", baudrate=19200)
# read all the waiting characters and output them on the terminal
w = inWaiting(ser)
if w > 0
s = read(ser,w)
print(s)
end
# close the serial port
close(ser)
Also have a look at the minimal terminal example in the examples/ folder.
| {'content_hash': '2e6ca95d74144f64d30562116e74adb0', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 178, 'avg_line_length': 29.47826086956522, 'alnum_prop': 0.6814159292035398, 'repo_name': 'hcgraf/PySerial.jl', 'id': 'fd10dfcd62ebf23251fbac2d8d711e4946073070', 'size': '690', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Julia', 'bytes': '1652'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<artifactId>spring-boot-sample-jetty</artifactId>
<name>Spring Boot Jetty Sample</name>
<description>Spring Boot Jetty Sample</description>
<url>http://projects.spring.io/spring-boot/</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>http://www.spring.io</url>
</organization>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
| {'content_hash': '3da4d4111986d57b2434d4dc175579a2', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 204, 'avg_line_length': 33.875, 'alnum_prop': 0.7177121771217713, 'repo_name': 'akmaharshi/jenkins', 'id': '80e82ff9716c7c3d8dda129b0e6b78fea5d6f164', 'size': '1626', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-boot-samples/spring-boot-sample-jetty/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1948'}, {'name': 'CSS', 'bytes': '5769'}, {'name': 'Dockerfile', 'bytes': '1959'}, {'name': 'Fluent', 'bytes': '18'}, {'name': 'FreeMarker', 'bytes': '2120'}, {'name': 'Groovy', 'bytes': '51722'}, {'name': 'HTML', 'bytes': '74129'}, {'name': 'Java', 'bytes': '9773682'}, {'name': 'JavaScript', 'bytes': '37789'}, {'name': 'Ruby', 'bytes': '1307'}, {'name': 'Shell', 'bytes': '13278'}, {'name': 'Smarty', 'bytes': '3276'}, {'name': 'Vim Snippet', 'bytes': '278'}, {'name': 'XSLT', 'bytes': '34105'}]} |
from __future__ import absolute_import, division, print_function, unicode_literals
from six.moves import zip, map
import six
import dtool
import utool as ut
import vtool as vt
import pyflann
import numpy as np
from ibeis.control.controller_inject import register_preprocs, register_subprops
(print, rrr, profile) = ut.inject2(__name__, '[new_annots]')
derived_attribute = register_preprocs['annot']
register_subprop = register_subprops['annot']
# dtool.Config.register_func = derived_attribute
class VocabConfig(dtool.Config):
_param_info_list = [
ut.ParamInfo('algorithm', 'minibatch', 'alg'),
ut.ParamInfo('random_seed', 42, 'seed'),
ut.ParamInfo('num_words', 1000, 'seed'),
ut.ParamInfo('version', 1),
]
class InvertedIndexConfig(dtool.Config):
_param_info_list = [
ut.ParamInfo('nAssign', 1),
]
class SMKConfig(dtool.Config):
_param_info_list = [
ut.ParamInfo('smk_alpha', 3),
ut.ParamInfo('smk_thresh', 0),
]
@ut.reloadable_class
class SMKCacheable(object):
""" helper for depcache-less cachine """
def get_fpath(self, cachedir, cfgstr=None):
_args2_fpath = ut.util_cache._args2_fpath
#prefix = self.get_prefix()
prefix = self.__class__.__name__
cfgstr = self.get_hashid()
#ext = self.ext
ext = '.cPkl'
fpath = _args2_fpath(cachedir, prefix, cfgstr, ext)
return fpath
def ensure(self, cachedir):
fpath = self.get_fpath(cachedir)
if ut.checkpath(fpath):
self.load(fpath)
else:
self.build()
self.save(fpath)
def save(self, fpath):
state = ut.dict_subset(self.__dict__, self.__columns__)
ut.save_data(fpath, state)
def load(self, fpath):
state = ut.load_data(fpath)
self.__dict__.update(**state)
@ut.reloadable_class
class VisualVocab(ut.NiceRepr):
"""
Class that maintains a list of visual words (cluster centers)
Also maintains a nearest neighbor index structure for finding words.
This class is build using the depcache
"""
def __init__(self, words=None):
self.wx_to_word = words
self.wordflann = None
self.flann_params = vt.get_flann_params(random_seed=42)
# TODO: grab the depcache rowid
def __len__(self):
return len(self.wx_to_word)
def __getstate__(self):
# TODO: Figure out how to make these play nice with the depcache
state = self.__dict__.copy()
if 'wx2_word' in state:
state['wx_to_word'] = state.pop('wx2_word')
del state['wordflann']
# Make a special wordflann pickle
# THIS WILL NOT WORK ON WINDOWS
import tempfile
assert not ut.WIN32, 'Need to fix this on WIN32. Cannot write to temp file'
temp = tempfile.NamedTemporaryFile(delete=True)
try:
self.wordflann.save_index(temp.name)
wordindex_bytes = temp.read()
#print('wordindex_bytes = %r' % (len(wordindex_bytes),))
state['wordindex_bytes'] = wordindex_bytes
except Exception:
raise
finally:
temp.close()
return state
def __setstate__(self, state):
wordindex_bytes = state.pop('wordindex_bytes')
self.__dict__.update(state)
self.wordflann = pyflann.FLANN()
import tempfile
assert not ut.WIN32, 'Need to fix this on WIN32. Cannot write to temp file'
temp = tempfile.NamedTemporaryFile(delete=True)
try:
temp.write(wordindex_bytes)
temp.file.flush()
self.wordflann.load_index(temp.name, self.wx_to_word)
except Exception:
raise
finally:
temp.close()
def reindex(self, verbose=True):
num_vecs = len(self.wx_to_word)
if self.wordflann is None:
self.wordflann = pyflann.FLANN()
if verbose:
print('[nnindex] ...building kdtree over %d points (this may take a sec).' % num_vecs)
tt = ut.tic(msg='Building vocab index')
if num_vecs == 0:
print('WARNING: CANNOT BUILD FLANN INDEX OVER 0 POINTS. THIS MAY BE A SIGN OF A DEEPER ISSUE')
else:
self.wordflann.build_index(self.wx_to_word, **self.flann_params)
if verbose:
ut.toc(tt)
def nn_index(self, idx_to_vec, nAssign):
"""
>>> idx_to_vec = depc.d.get_feat_vecs(aid_list)[0]
>>> self = vocab
>>> nAssign = 1
"""
# Assign each vector to the nearest visual words
assert nAssign > 0, 'cannot assign to 0 neighbors'
try:
idx_to_vec = idx_to_vec.astype(self.wordflann._FLANN__curindex_data.dtype)
_idx_to_wx, _idx_to_wdist = self.wordflann.nn_index(idx_to_vec, nAssign)
except pyflann.FLANNException as ex:
ut.printex(ex, 'probably misread the cached flann_fpath=%r' % (getattr(self.wordflann, 'flann_fpath', None),))
import utool
utool.embed()
raise
else:
_idx_to_wx = vt.atleast_nd(_idx_to_wx, 2)
_idx_to_wdist = vt.atleast_nd(_idx_to_wdist, 2)
return _idx_to_wx, _idx_to_wdist
def assign_to_words(self, idx_to_vec, nAssign, massign_alpha=1.2,
massign_sigma=80.0, massign_equal_weights=False):
"""
Assigns descriptor-vectors to nearest word.
Args:
wordflann (FLANN): nearest neighbor index over words
words (ndarray): vocabulary words
idx_to_vec (ndarray): descriptors to assign
nAssign (int): number of words to assign each descriptor to
massign_alpha (float): multiple-assignment ratio threshold
massign_sigma (float): multiple-assignment gaussian variance
massign_equal_weights (bool): assign equal weight to all multiassigned words
Returns:
tuple: inverted index, multi-assigned weights, and forward index
formated as::
* wx_to_idxs - word index -> vector indexes
* wx_to_maws - word index -> multi-assignment weights
* idf2_wxs - vector index -> assigned word indexes
Example:
>>> # SLOW_DOCTEST
>>> idx_to_vec = depc.d.get_feat_vecs(aid_list)[0][0::300]
>>> idx_to_vec = np.vstack((idx_to_vec, self.wx_to_word[0]))
>>> nAssign = 2
>>> massign_equal_weights = False
>>> massign_alpha = 1.2
>>> massign_sigma = 80.0
>>> nAssign = 2
>>> idx_to_wxs, idx_to_maws = self.assign_to_words(idx_to_vec, nAssign)
>>> print('idx_to_maws = %s' % (ut.repr2(idx_to_wxs, precision=2),))
>>> print('idx_to_wxs = %s' % (ut.repr2(idx_to_maws, precision=2),))
"""
if ut.VERBOSE:
print('[smk_index.assign] +--- Start Assign vecs to words.')
print('[smk_index.assign] * nAssign=%r' % nAssign)
if not ut.QUIET:
print('[smk_index.assign] assign_to_words_. len(idx_to_vec) = %r' % len(idx_to_vec))
_idx_to_wx, _idx_to_wdist = self.nn_index(idx_to_vec, nAssign)
if nAssign > 1:
idx_to_wxs, idx_to_maws = self._compute_multiassign_weights(
_idx_to_wx, _idx_to_wdist, massign_alpha, massign_sigma, massign_equal_weights)
else:
idx_to_wxs = _idx_to_wx.tolist()
idx_to_maws = [[1.0]] * len(idx_to_wxs)
return idx_to_wxs, idx_to_maws
def invert_assignment(self, idx_to_wxs, idx_to_maws):
"""
Inverts assignment of vectors to words into words to vectors.
Example:
>>> idx_to_idx = np.arange(len(idx_to_wxs))
>>> other_idx_to_prop = (idx_to_idx,)
>>> wx_to_idxs, wx_to_maws = self.invert_assignment(idx_to_wxs, idx_to_maws)
"""
# Invert mapping -- Group by word indexes
idx_to_nAssign = [len(wxs) for wxs in idx_to_wxs]
jagged_idxs = [[idx] * num for idx, num in enumerate(idx_to_nAssign)]
wx_keys, groupxs = vt.jagged_group(idx_to_wxs)
idxs_list = vt.apply_jagged_grouping(jagged_idxs, groupxs)
wx_to_idxs = dict(zip(wx_keys, idxs_list))
maws_list = vt.apply_jagged_grouping(idx_to_maws, groupxs)
wx_to_maws = dict(zip(wx_keys, maws_list))
if ut.VERBOSE:
print('[smk_index.assign] L___ End Assign vecs to words.')
return (wx_to_idxs, wx_to_maws)
@staticmethod
def _compute_multiassign_weights(_idx_to_wx, _idx_to_wdist, massign_alpha=1.2,
massign_sigma=80.0,
massign_equal_weights=False):
"""
Multi Assignment Weight Filtering from Improving Bag of Features
Args:
massign_equal_weights (): Turns off soft weighting. Gives all assigned
vectors weight 1
Returns:
tuple : (idx_to_wxs, idx_to_maws)
References:
(Improving Bag of Features)
http://lear.inrialpes.fr/pubs/2010/JDS10a/jegou_improvingbof_preprint.pdf
(Lost in Quantization)
http://www.robots.ox.ac.uk/~vgg/publications/papers/philbin08.ps.gz
(A Context Dissimilarity Measure for Accurate and Efficient Image Search)
https://lear.inrialpes.fr/pubs/2007/JHS07/jegou_cdm.pdf
Example:
>>> massign_alpha = 1.2
>>> massign_sigma = 80.0
>>> massign_equal_weights = False
Notes:
sigma values from \cite{philbin_lost08}
(70 ** 2) ~= 5000, (80 ** 2) ~= 6250, (86 ** 2) ~= 7500,
"""
if not ut.QUIET:
print('[smk_index.assign] compute_multiassign_weights_')
if _idx_to_wx.shape[1] <= 1:
idx_to_wxs = _idx_to_wx.tolist()
idx_to_maws = [[1.0]] * len(idx_to_wxs)
else:
# Valid word assignments are beyond fraction of distance to the nearest word
massign_thresh = _idx_to_wdist.T[0:1].T.copy()
# HACK: If the nearest word has distance 0 then this threshold is too hard
# so we should use the distance to the second nearest word.
EXACT_MATCH_HACK = True
if EXACT_MATCH_HACK:
flag_too_close = (massign_thresh == 0)
massign_thresh[flag_too_close] = _idx_to_wdist.T[1:2].T[flag_too_close]
# Compute the threshold fraction
epsilon = .001
np.add(epsilon, massign_thresh, out=massign_thresh)
np.multiply(massign_alpha, massign_thresh, out=massign_thresh)
# Mark assignments as invalid if they are too far away from the nearest assignment
invalid = np.greater_equal(_idx_to_wdist, massign_thresh)
if ut.VERBOSE:
nInvalid = (invalid.size - invalid.sum(), invalid.size)
print('[maw] + massign_alpha = %r' % (massign_alpha,))
print('[maw] + massign_sigma = %r' % (massign_sigma,))
print('[maw] + massign_equal_weights = %r' % (massign_equal_weights,))
print('[maw] * Marked %d/%d assignments as invalid' % nInvalid)
if massign_equal_weights:
# Performance hack from jegou paper: just give everyone equal weight
masked_wxs = np.ma.masked_array(_idx_to_wx, mask=invalid)
idx_to_wxs = list(map(ut.filter_Nones, masked_wxs.tolist()))
#ut.embed()
if ut.DEBUG2:
assert all([isinstance(wxs, list) for wxs in idx_to_wxs])
idx_to_maws = [np.ones(len(wxs), dtype=np.float32) for wxs in idx_to_wxs]
else:
# More natural weighting scheme
# Weighting as in Lost in Quantization
gauss_numer = np.negative(_idx_to_wdist.astype(np.float64))
gauss_denom = 2 * (massign_sigma ** 2)
gauss_exp = np.divide(gauss_numer, gauss_denom)
unnorm_maw = np.exp(gauss_exp)
# Mask invalid multiassignment weights
masked_unorm_maw = np.ma.masked_array(unnorm_maw, mask=invalid)
# Normalize multiassignment weights from 0 to 1
masked_norm = masked_unorm_maw.sum(axis=1)[:, np.newaxis]
masked_maw = np.divide(masked_unorm_maw, masked_norm)
masked_wxs = np.ma.masked_array(_idx_to_wx, mask=invalid)
# Remove masked weights and word indexes
idx_to_wxs = list(map(ut.filter_Nones, masked_wxs.tolist()))
idx_to_maws = list(map(ut.filter_Nones, masked_maw.tolist()))
#with ut.EmbedOnException():
if ut.DEBUG2:
checksum = [sum(maws) for maws in idx_to_maws]
for x in np.where([not ut.almost_eq(val, 1) for val in checksum])[0]:
print(checksum[x])
print(_idx_to_wx[x])
print(masked_wxs[x])
print(masked_maw[x])
print(massign_thresh[x])
print(_idx_to_wdist[x])
#all([ut.almost_eq(x, 1) for x in checksum])
assert all([ut.almost_eq(val, 1) for val in checksum]), 'weights did not break evenly'
return idx_to_wxs, idx_to_maws
def __nice__(self):
return 'nW=%r' % (ut.safelen(self.wx_to_word))
@ut.reloadable_class
class ForwardIndex(ut.NiceRepr, SMKCacheable):
"""
A Forward Index of Stacked Features
A stack of features from multiple annotations.
Contains a method to create an inverted index given a vocabulary.
"""
__columns__ = ['ax_to_aid', 'ax_to_nFeat', 'idx_to_fx', 'idx_to_ax',
'idx_to_vec']
def __init__(fstack, ibs=None, aid_list=None, config=None, name=None):
# Basic Info
fstack.ibs = ibs
fstack.config = config
fstack.name = name
#-- Stack 1 --
fstack.ax_to_aid = aid_list
fstack.ax_to_nFeat = None
#-- Stack 2 --
fstack.idx_to_fx = None
fstack.idx_to_ax = None
fstack.idx_to_vec = None
# --- Misc ---
fstack.num_feat = None
def build(fstack):
ibs = fstack.ibs
config = fstack.config
ax_to_vecs = ibs.depc.d.get_feat_vecs(fstack.ax_to_aid, config=config)
#-- Stack 1 --
fstack.ax_to_nFeat = [len(vecs) for vecs in ax_to_vecs]
#-- Stack 2 --
fstack.idx_to_fx = np.array(ut.flatten([list(range(num)) for num in fstack.ax_to_nFeat]))
fstack.idx_to_ax = np.array(ut.flatten([[ax] * num for ax, num in enumerate(fstack.ax_to_nFeat)]))
fstack.idx_to_vec = np.vstack(ax_to_vecs)
# --- Misc ---
fstack.num_feat = sum(fstack.ax_to_nFeat)
def __nice__(fstack):
name = '' if fstack.name is None else fstack.name + ' '
if fstack.num_feat is None:
return '%snA=%r NotInitialized' % (name, ut.safelen(fstack.ax_to_aid))
else:
return '%snA=%r nF=%r' % (name, ut.safelen(fstack.ax_to_aid), fstack.num_feat)
def get_cfgstr(self):
depc = self.ibs.depc
annot_cfgstr = self.ibs.get_annot_hashid_visual_uuid(self.aid_list, prefix='')
#cfgstr = depc.chained_cfgstr('annotations', 'featweight', self.config)
config_cfgstr = depc.chained_cfgstr('annotations', 'feat', self.config)
cfgstr = '_'.join([annot_cfgstr, config_cfgstr])
return cfgstr
def get_hashid(self):
return ut.hashstr27(self.get_cfgstr())
@property
def aid_list(fstack):
return fstack.ax_to_aid
def assert_self(fstack):
assert len(fstack.idx_to_fx) == len(fstack.idx_to_ax)
assert len(fstack.idx_to_fx) == len(fstack.idx_to_vec)
assert len(fstack.ax_to_aid) == len(fstack.ax_to_nFeat)
assert fstack.idx_to_ax.max() < len(fstack.ax_to_aid)
@ut.reloadable_class
class InvertedIndex(ut.NiceRepr, SMKCacheable):
"""
Maintains an inverted index of chip descriptors that are multi-assigned to
a set of vocabulary words.
This stack represents the database.
It prorcesses the important information like
* vocab - this is the quantizer
Each word is has an inverted index to a list of:
(annotation index, feature index, multi-assignment weight)
Example:
>>> # ENABLE_LATER
>>> from ibeis.new_annots import * # NOQA
>>> ibs, aid_list, inva = testdata_inva('testdb1', num_words=1000)
>>> print(inva)
"""
__columns__ = ['wx_to_idxs', 'wx_to_maws', 'wx_to_num', 'wx_list',
'num_list', 'perword_stats']
def __init__(inva, fstack=None, vocab=None, config={}):
inva.fstack = fstack
inva.vocab = vocab
inva.config = InvertedIndexConfig(**config)
# Corresponding arrays
inva.wx_to_idxs = None
inva.wx_to_maws = None
inva.wx_to_num = None
#
inva.wx_list = None
# Extra stuff
inva.num_list = None
inva.perword_stats = None
inva._word_patches = {}
def build(inva):
nAssign = inva.config.get('nAssign', 1)
fstack = inva.fstack
vocab = inva.vocab
idx_to_wxs, idx_to_maws = vocab.assign_to_words(fstack.idx_to_vec, nAssign)
wx_to_idxs, wx_to_maws = vocab.invert_assignment(idx_to_wxs, idx_to_maws)
# Corresponding arrays
inva.wx_to_idxs = wx_to_idxs
inva.wx_to_maws = wx_to_maws
inva.wx_to_num = ut.map_dict_vals(len, inva.wx_to_idxs)
#
inva.wx_list = sorted(inva.wx_to_num.keys())
# Extra stuff
inva.num_list = ut.take(inva.wx_to_num, inva.wx_list)
inva.perword_stats = ut.get_stats(inva.num_list)
inva._word_patches = {}
@classmethod
def invert(cls, fstack, vocab, nAssign=1):
inva = cls(fstack, vocab, config={'nAssign': nAssign})
inva.build()
return inva
def get_hashid(inva):
cfgstr = inva.config.get_cfgstr() + '_' + inva.fstack.get_cfgstr()
hashid = ut.hashstr27(cfgstr)
return hashid
def wx_to_fxs(inva, wx):
return inva.fstack.idx_to_fx.take(inva.wx_to_idxs[wx], axis=0)
def wx_to_axs(inva, wx):
return inva.fstack.idx_to_ax.take(inva.wx_to_idxs[wx], axis=0)
def __nice__(inva):
fstack = inva.fstack
name = '' if fstack.name is None else fstack.name + ' '
if inva.wx_to_idxs is None:
return '%sNotInitialized' % (name,)
else:
return '%snW=%r mean=%.2f' % (name, ut.safelen(inva.wx_to_idxs), inva.perword_stats['mean'])
def get_patches(inva, wx, verbose=True):
"""
Loads the patches assigned to a particular word in this stack
"""
ax_list = inva.wx_to_axs(wx)
fx_list = inva.wx_to_fxs(wx)
config = inva.fstack.config
ibs = inva.fstack.ibs
# Group annotations with more than one assignment to this word, so we
# only have to load a chip at most once
unique_axs, groupxs = vt.group_indices(ax_list)
fxs_groups = vt.apply_grouping(fx_list, groupxs)
unique_aids = ut.take(inva.fstack.ax_to_aid, unique_axs)
all_kpts_list = ibs.depc.d.get_feat_kpts(unique_aids, config=config)
sub_kpts_list = vt.ziptake(all_kpts_list, fxs_groups, axis=0)
chip_list = ibs.depc_annot.d.get_chips_img(unique_aids)
# convert to approprate colorspace
#if colorspace is not None:
# chip_list = vt.convert_image_list_colorspace(chip_list, colorspace)
# ut.print_object_size(chip_list, 'chip_list')
patch_size = 64
_prog = ut.ProgPartial(enabled=verbose, lbl='warping patches', bs=True)
grouped_patches_list = [
vt.get_warped_patches(chip, kpts, patch_size=patch_size)[0]
#vt.get_warped_patches(chip, kpts, patch_size=patch_size, use_cpp=True)[0]
for chip, kpts in _prog(zip(chip_list, sub_kpts_list),
nTotal=len(unique_aids))
]
# Make it correspond with original fx_list and ax_list
word_patches = vt.invert_apply_grouping(grouped_patches_list, groupxs)
return word_patches
def get_word_patch(inva, wx):
if wx not in inva._word_patches:
assigned_patches = inva.get_patches(wx, verbose=False)
#print('assigned_patches = %r' % (len(assigned_patches),))
average_patch = np.mean(assigned_patches, axis=0)
average_patch = average_patch.astype(np.float)
inva._word_patches[wx] = average_patch
return inva._word_patches[wx]
def compute_idf(inva):
"""
Use idf (inverse document frequency) to weight each word.
References:
https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Inverse_document_frequency_2
Example:
>>> # ENABLE_LATER
>>> from ibeis.new_annots import * # NOQA
>>> ibs, aid_list, inva = testdata_inva(num_words=256)
>>> wx_to_idf = inva.compute_word_idf()
>>> idf_list = np.array(wx_to_idf.values())
>>> assert np.all(idf_list >= 0)
>>> prob_list = (1 / np.exp(idf_list))
>>> assert np.all(prob_list >= 0)
>>> assert np.all(prob_list <= 1)
"""
num_docs_total = len(inva.fstack.ax_to_aid)
# idf denominator (the num of docs containing a word for each word)
# The max(maws) to denote the probab that this word indexes an annot
wx_to_num_docs = np.array([
sum([maws.max() for maws in vt.apply_grouping(
inva.wx_to_maws[wx],
vt.group_indices(inva.wx_to_axs(wx))[1])])
for wx in inva.wx_list
])
# Typically for IDF, 1 is added to the denom to prevent divide by 0
# We add epsilon to numer and denom to ensure recep is a probability
idf_list = np.log(np.divide(num_docs_total + 1, wx_to_num_docs + 1))
wx_to_idf = dict(zip(inva.wx_list, idf_list))
return wx_to_idf
def get_vecs(inva, wx):
"""
Get raw vectors assigned to a word
"""
vecs = inva.fstack.idx_to_vec.take(inva.wx_to_idxs[wx], axis=0)
return vecs
def compute_rvecs(inva, wx, asint=False):
"""
Driver function for non-aggregated residual vectors to a specific word.
Notes:
rvec = phi(x)
phi(x) = x - q(x)
This function returns `[phi(x) for x in X_c]`
Where c is a word `wx`
IE: all residual vectors for the descriptors assigned to word c
Returns:
tuple : (rvecs_list, flags_list)
Example:
>>> # ENABLE_LATER
>>> from ibeis.new_annots import * # NOQA
>>> ibs, aid_list, inva = testdata_inva(num_words=256)
>>> wx = 1
>>> asint = False
>>> rvecs_list, error_flags = inva.compute_rvecs(1)
"""
# Pick out corresonding lists of residuals and words
vecs = inva.get_vecs(wx)
word = inva.vocab.wx_to_word[wx]
return compute_rvec(vecs, word)
def get_grouped_rvecs(inva, wx):
"""
# Get all residual vectors assigned to a word grouped by annotation
"""
rvecs_list, error_flags = inva.compute_rvecs(wx)
ax_list = inva.wx_to_axs(wx)
maw_list = inva.wx_to_maws[wx]
# group residual vectors by annotation
unique_ax, groupxs = vt.group_indices(ax_list)
# (weighted aggregation with multi-assign-weights)
grouped_maws = vt.apply_grouping(maw_list, groupxs)
grouped_rvecs = vt.apply_grouping(rvecs_list, groupxs)
grouped_errors = vt.apply_grouping(error_flags, groupxs)
# Remove vectors with errors
#inner_flags = vt.apply_grouping(~error_flags, groupxs)
#grouped_rvecs2_ = vt.zipcompress(grouped_rvecs, inner_flags, axis=0)
#grouped_maws2_ = vt.zipcompress(grouped_maws, inner_flags)
grouped_rvecs2_ = grouped_rvecs
grouped_maws2_ = grouped_maws
grouped_errors2_ = grouped_errors
outer_flags = [len(rvecs) > 0 for rvecs in grouped_rvecs2_]
grouped_rvecs3_ = ut.compress(grouped_rvecs2_, outer_flags)
grouped_maws3_ = ut.compress(grouped_maws2_, outer_flags)
grouped_errors3_ = ut.compress(grouped_errors2_, outer_flags)
unique_ax3_ = ut.compress(unique_ax, outer_flags)
return unique_ax3_, grouped_rvecs3_, grouped_maws3_, grouped_errors3_
def compute_agg_rvecs(inva, wx):
"""
Sums and normalizes all rvecs that belong to the same word and the same
annotation id
Returns:
ax_to_aggvec: A mapping from an annotation to its aggregated vector
for this word.
Notes:
aggvec = Phi
Phi(X_c) = psi(sum([phi(x) for x in X_c]))
psi is the identify function currently.
Phi is esentially a VLAD vector for a specific word.
Returns Phi vectors wrt each annotation.
Example:
>>> # ENABLE_LATER
>>> from ibeis.new_annots import * # NOQA
>>> ibs, aid_list, inva = testdata_inva(num_words=256)
>>> wx = 1
>>> asint = False
>>> ax_to_aggvec = inva.compute_agg_rvecs(1)
"""
tup = inva.get_grouped_rvecs(wx)
unique_ax3_, grouped_rvecs3_, grouped_maws3_, grouped_errors3_ = tup
# FIXME: decide how to handle errors
ax_to_aggvec = {
ax: aggregate_rvecs(rvecs, maws, errors)
for ax, rvecs, maws, errors in
zip(unique_ax3_, grouped_rvecs3_, grouped_maws3_, grouped_errors3_)
}
return ax_to_aggvec
def group_annots(inva):
"""
Group by annotations first and then by words
inva = smk.qinva
>>> from ibeis.new_annots import * # NOQA
>>> ibs, smk, qreq_ = testdata_smk()
>>> inva = smk.qinva
"""
fstack = inva.fstack
ax_to_X = [IndexedAnnot(ax, inva) for ax in range(len(fstack.ax_to_aid))]
for wx in inva.wx_list:
idxs = inva.wx_to_idxs[wx]
maws = inva.wx_to_maws[wx]
axs = fstack.idx_to_ax.take(idxs, axis=0)
unique_axs, groupxs = vt.group_indices(axs)
grouped_maws = vt.apply_grouping(maws, groupxs)
grouped_idxs = vt.apply_grouping(idxs, groupxs)
# precompute here
ax_to_aggvec = inva.compute_agg_rvecs(wx)
for ax, idxs_, maws_ in zip(unique_axs, grouped_idxs,
grouped_maws):
X = ax_to_X[ax]
X.wx_to_idxs_[wx] = idxs_
X.wx_to_maws_[wx] = maws_
X.wx_to_aggvec[wx] = ax_to_aggvec[ax]
X_list = ax_to_X
return X_list
def assert_self(inva):
assert sorted(inva.wx_to_idxs.keys()) == sorted(inva.wx_to_maws.keys())
assert sorted(inva.wx_list) == sorted(inva.wx_to_maws.keys())
inva.fstack.assert_self()
@ut.reloadable_class
class IndexedAnnot(ut.NiceRepr):
def __init__(X, ax, inva):
X.ax = ax
X.inva = inva
# only idxs that belong to ax
X.wx_to_idxs_ = {}
X.wx_to_maws_ = {}
X.wx_to_aggvec = {}
def __nice__(X):
return 'aid=%r, nW=%r' % (X.aid, len(X.wx_to_idxs_),)
@property
def aid(X):
return X.inva.fstack.ax_to_aid[X.ax]
def idxs(X, wx):
return X.wx_to_idxs_[wx]
def maws(X, wx):
return X.wx_to_maws_[wx]
def fxs(X, wx):
fxs = X.inva.fstack.idx_to_fx.take(X.idxs(wx), axis=0)
return fxs
def Phi(X, wx):
return X.wx_to_aggvec[wx]
def phis(X, wx):
vocab = X.inva.vocab
idxs = X.idxs(wx)
vecs = X.inva.fstack.idx_to_vec.take(idxs, axis=0)
word = vocab.wx_to_word[wx]
rvecs, flags = compute_rvec(vecs, word)
return rvecs
@property
def words(X):
return list(X.wx_to_aggvec)
def assert_self(X):
assert len(X.wx_to_idxs_) == len(X.wx_to_aggvec)
for wx in X.wx_to_idxs_.keys():
axs = X.inva.fstack.idx_to_ax.take(X.idxs(wx), axis=0)
assert np.all(axs == X.ax)
agg_rvec = aggregate_rvecs(X.phis(wx), X.maws(wx))
assert np.all(agg_rvec == X.Phi(wx))
@ut.reloadable_class
class SMKRequest(ut.NiceRepr):
"""
qreq_-like object
"""
def __init__(qreq_, ibs=None, qaids=None, daids=None, config=None):
"""
Example:
>>> from ibeis.new_annots import * # NOQA
>>> import ibeis
>>> ibs, aid_list = ibeis.testdata_aids(defaultdb='PZ_MTEST')
>>> qaids = aid_list[0:2]
>>> daids = aid_list[2:]
>>> config = {'nAssign': 2}
>>> qreq_ = SMKRequest(ibs, qaids, daids, config)
>>> cm_list = qreq_.execute()
"""
qreq_.ibs = ibs
qreq_.qaids = qaids
qreq_.daids = daids
qreq_.config = config
qreq_.vocab = None
qreq_.dinva = None
qreq_.qinva = None
qreq_.smk = None
def get_pipe_hashid(qreq_):
return ut.hashstr27(str(qreq_.qparams))
def ensure_data(qreq_):
ibs = qreq_.ibs
config = qreq_.config
qreq_.vocab = ibs.depc.get('vocab', [qreq_.daids], 'words',
config=qreq_.config)[0]
cachedir = ut.ensuredir((ibs.cachedir, 'smk'))
qfstack = ForwardIndex(ibs, qreq_.qaids, config, name='query')
dfstack = ForwardIndex(ibs, qreq_.daids, config, name='data')
qinva = InvertedIndex(qfstack, qreq_.vocab, config=config)
dinva = InvertedIndex(dfstack, qreq_.vocab, config=config)
qreq_.ensure_nids()
qfstack.ensure(cachedir)
dfstack.ensure(cachedir)
qinva.ensure(cachedir)
dinva.ensure(cachedir)
qreq_.smk = SMK(qinva, dinva, qreq_.config)
# Hack to work with existing hs code
from ibeis.algo import Config
qreq_.qparams = dtool.base.StackedConfig([
Config.SpatialVerifyConfig(),
qreq_.smk.config
])
def execute(qreq_, qaids=None, prog_hook=None):
assert qaids is None
smk = qreq_.smk
cm_list = smk.execute(qreq_)
return cm_list
# Hacked in functions
def ensure_nids(qreq_):
# Hacked over from hotspotter, seriously hacky
ibs = qreq_.ibs
qreq_.unique_aids = np.union1d(qreq_.qaids, qreq_.daids)
qreq_.unique_nids = ibs.get_annot_nids(qreq_.unique_aids)
qreq_.aid_to_idx = ut.make_index_lookup(qreq_.unique_aids)
@ut.accepts_numpy
def get_qreq_annot_nids(qreq_, aids):
# Hack uses own internal state to grab name rowids
# instead of using ibeis.
idxs = ut.take(qreq_.aid_to_idx, aids)
nids = ut.take(qreq_.unique_nids, idxs)
return nids
def get_qreq_qannot_kpts(qreq_, qaids):
return qreq_.ibs.get_annot_kpts(qaids, config2_=qreq_.smk.qinva.fstack.config)
def get_qreq_dannot_kpts(qreq_, daids):
return qreq_.ibs.get_annot_kpts(daids, config2_=qreq_.smk.dinva.fstack.config)
@property
def extern_query_config2(qreq_):
return qreq_.qparams
@property
def extern_data_config2(qreq_):
return qreq_.qparams
@ut.reloadable_class
class SMK(ut.NiceRepr):
"""
Harness class that controls the execution of the SMK algorithm
K(X, Y) = gamma(X) * gamma(Y) * sum([Mc(Xc, Yc) for c in words])
"""
def __init__(smk, qinva, dinva, config):
smk.qinva = qinva
smk.dinva = dinva
smk.config = SMKConfig(**config)
# Choose which version to use
if True:
smk.match_score = smk.match_score_agg
else:
smk.match_score = smk.match_score_sep
@property
@ut.memoize
def wx_to_idf(smk):
wx_to_idf = smk.dinva.compute_idf()
return wx_to_idf
def weighted_match_score(smk, X, Y, c):
"""
Just computes the total score of all feature matches
"""
u = smk.match_score(X, Y, c)
score = smk.selectivity(u).sum()
score *= smk.wx_to_idf[c]
return score
def weighted_matches(smk, X, Y, c):
"""
Explicitly computes the feature matches that will be scored
"""
u = smk.match_score(X, Y, c)
score = smk.selectivity(u).sum()
score *= smk.wx_to_idf[c]
word_fm = list(ut.product(X.fxs(c), Y.fxs(c)))
if score.size != len(word_fm):
# Spread word score according to contriubtion (maw) weight
contribution = X.maws(c)[:, None].dot(Y.maws(c)[:, None].T)
contrib_weight = (contribution / contribution.sum())
word_fs = (contrib_weight * score).ravel()
else:
# Scores were computed separately, so dont spread
word_fs = score.ravel()
isvalid = word_fs > 0
word_fs = word_fs.compress(isvalid)
word_fm = ut.compress(word_fm, isvalid)
return word_fm, word_fs
def match_score_agg(smk, X, Y, c):
u = X.Phi(c).dot(Y.Phi(c).T)
return u
def match_score_sep(smk, X, Y, c):
u = X.phis(c).dot(Y.phis(c).T)
return u
def selectivity(smk, u):
alpha = smk.config['smk_alpha']
thresh = smk.config['smk_thresh']
score = np.sign(u) * np.power(np.abs(u), alpha)
score *= np.greater(u, thresh)
return score
def gamma(smk, X):
r"""
Computes gamma (self consistency criterion)
It is a scalar which ensures K(X, X) = 1
Returns:
float: sccw self-consistency-criterion weight
Math:
gamma(X) = (sum_{c in C} w_c M(X_c, X_c))^{-.5}
>>> from ibeis.new_annots import * # NOQA
>>> ibs, smk, qreq_= testdata_smk()
>>> X = smk.qinva.group_annots()[0]
>>> print('X.gamma = %r' % (smk.gamma(X),))
"""
rawscores = [smk.weighted_match_score(X, X, c) for c in X.words]
idf_list = np.array(ut.take(smk.wx_to_idf, X.words))
scores = np.array(rawscores) * idf_list
score = scores.sum()
sccw = np.reciprocal(np.sqrt(score))
return sccw
def execute(smk, qreq_):
"""
>>> from ibeis.new_annots import * # NOQA
>>> ibs, smk, qreq_ = testdata_smk()
"""
assert smk.qinva.vocab is smk.dinva.vocab
X_list = smk.qinva.group_annots()
Y_list = smk.dinva.group_annots()
cm_list = [
smk.smk_chipmatch(X, Y_list, qreq_)
for X in ut.ProgIter(X_list, lbl='smk query', bs=False)
]
return cm_list
def smk_chipmatch(smk, X, Y_list, qreq_):
"""
CommandLine:
python -m ibeis.new_annots smk_chipmatch --show
Example:
>>> # FUTURE_ENABLE
>>> from ibeis.new_annots import * # NOQA
>>> ibs, smk, qreq_ = testdata_smk()
>>> X = smk.qinva.group_annots()[0]
>>> Y_list = smk.dinva.group_annots()
>>> Y = Y_list[0]
>>> cm = smk.smk_chipmatch(X, Y_list, qreq_)
>>> ut.qt4ensure()
>>> cm.ishow_analysis(qreq_)
>>> ut.show_if_requested()
"""
from ibeis.algo.hots import chip_match
from ibeis.algo.hots import pipeline
qaid = X.aid
daid_list = []
fm_list = []
fsv_list = []
fsv_col_lbls = ['smk']
gammaX = smk.gamma(X)
for Y in ut.ProgIter(Y_list, lbl='smk match qaid=%r' % (qaid,)):
gammaY = smk.gamma(Y)
gammaXY = gammaX * gammaY
fm = []
fs = []
# Words in common define matches
common_words = ut.isect(X.words, Y.words)
for c in common_words:
word_fm, word_fs = smk.weighted_matches(X, Y, c)
word_fs *= gammaXY
fm.extend(word_fm)
fs.extend(word_fs)
#if len(fm) > 0:
daid = Y.aid
fsv = np.array(fs)[:, None]
daid_list.append(daid)
fm = np.array(fm)
fm_list.append(fm)
fsv_list.append(fsv)
#progiter = iter(ut.ProgIter([0], lbl='smk sver qaid=%r' % (qaid,)))
#six.next(progiter)
# Build initial matches
cm = chip_match.ChipMatch(qaid=qaid, daid_list=daid_list,
fm_list=fm_list, fsv_list=fsv_list,
fsv_col_lbls=fsv_col_lbls)
cm.arraycast_self()
# Score matches and take a shortlist
cm.score_maxcsum(qreq_)
nNameShortList = qreq_.qparams.nNameShortlistSVER
nAnnotPerName = qreq_.qparams.nAnnotPerNameSVER
top_aids = cm.get_name_shortlist_aids(nNameShortList, nAnnotPerName)
cm = cm.shortlist_subset(top_aids)
# Spatially verify chip matches
cm = pipeline.sver_single_chipmatch(qreq_, cm, verbose=True)
# Rescore
cm.score_maxcsum(qreq_)
#list(progiter)
return cm
def render_vocab_word(ibs, inva, wx, fnum=None):
"""
Creates a visualization of a visual word. This includes the average patch,
the SIFT-like representation of the centroid, and some of the patches that
were assigned to it.
CommandLine:
python -m ibeis.new_annots render_vocab_word --show
Example:
>>> from ibeis.new_annots import * # NOQA
>>> ibs, aid_list, inva = testdata_inva('PZ_MTEST', num_words=10000)
>>> sortx = ut.argsort(inva.num_list)[::-1]
>>> wx_list = ut.take(inva.wx_list, sortx)
>>> wx = wx_list[0]
>>> ut.quit_if_noshow()
>>> import plottool as pt
>>> ut.qt4ensure()
>>> fnum = 2
>>> fnum = pt.ensure_fnum(fnum)
>>> # Interactive visualization of many words
>>> for wx in ut.InteractiveIter(wx_list):
>>> word_img = render_vocab_word(ibs, inva, wx, fnum)
>>> pt.imshow(word_img, fnum=fnum, title='Word %r/%r' % (wx, len(inva.vocab)))
>>> pt.update()
>>> ut.show_if_requested()
"""
import plottool as pt
# Create the contributing patch image
word_patches = inva.get_patches(wx)
stacked_patches = vt.stack_square_images(word_patches)
# Create the average word image
word = inva.vocab.wx_to_word[wx]
average_patch = np.mean(word_patches, axis=0)
#vecs = inva.get_vecs(wx)
#assert np.allclose(word, vecs.mean(axis=0))
with_sift = True
if with_sift:
patch_img = pt.render_sift_on_patch(average_patch, word)
else:
patch_img = average_patch
# Stack them together
solidbar = np.zeros((patch_img.shape[0], int(patch_img.shape[1] * .1), 3), dtype=patch_img.dtype)
border_color = (100, 10, 10) # bgr, darkblue
if ut.is_float(solidbar):
solidbar[:, :, :] = (np.array(border_color) / 255)[None, None]
else:
solidbar[:, :, :] = np.array(border_color)[None, None]
# word_img = vt.stack_image_list([patch_img, solidbar, stacked_patches], vert=False, modifysize=True)
patch_img2 = vt.inverted_sift_patch(word)
patch_img = vt.rectify_to_uint8(patch_img)
patch_img2 = vt.rectify_to_uint8(patch_img2)
solidbar = vt.rectify_to_uint8(solidbar)
stacked_patches = vt.rectify_to_uint8(stacked_patches)
patch_img2, patch_img = vt.make_channels_comparable(patch_img2, patch_img)
word_img = vt.stack_image_list([patch_img, solidbar, patch_img2, solidbar, stacked_patches], vert=False, modifysize=True)
return word_img
def render_vocab(inva):
"""
Renders the average patch of each word.
This is a quick visualization of the entire vocabulary.
CommandLine:
python -m ibeis.new_annots render_vocab --show
Example:
>>> from ibeis.new_annots import * # NOQA
>>> ibs, aid_list, inva = testdata_inva('PZ_MTEST', num_words=10000)
>>> render_vocab(inva)
>>> ut.show_if_requested()
"""
sortx = ut.argsort(inva.num_list)[::-1]
# Get words with the most assignments
wx_list = ut.take(inva.wx_list, sortx)
wx_list = ut.strided_sample(wx_list, 64)
word_patch_list = []
for wx in ut.ProgIter(wx_list, bs=True, lbl='building patches'):
word = inva.vocab.wx_to_word[wx]
if False:
word_patch = inva.get_word_patch(wx)
else:
word_patch = vt.inverted_sift_patch(word, 64)
import plottool as pt
word_patch = pt.render_sift_on_patch(word_patch, word)
word_patch_list.append(word_patch)
#for wx, p in zip(wx_list, word_patch_list):
# inva._word_patches[wx] = p
all_words = vt.stack_square_images(word_patch_list)
import plottool as pt
pt.qt4ensure()
pt.imshow(all_words)
def compute_rvec(vecs, word, asint=False):
"""
Compute residual vectors phi(x_c)
Subtract each vector from its quantized word to get the resiudal, then
normalize residuals to unit length.
"""
rvecs = np.subtract(word.astype(np.float), vecs.astype(np.float))
# If a vec is a word then the residual is 0 and it cant be L2 noramlized.
is_zero = np.all(rvecs == 0, axis=1)
vt.normalize_rows(rvecs, out=rvecs)
# reset these values back to zero
if np.any(is_zero):
rvecs[is_zero, :] = 0
if asint:
rvecs = np.clip(np.round(rvecs * 255.0), -127, 127).astype(np.int8)
# Determine if any errors occurred
# FIXME: zero will drive the score of a match to 0 even though if they
# are both 0, then it is an exact match and should be scored as a 1.
error_flags = np.any(np.isnan(rvecs), axis=1)
return rvecs, error_flags
def aggregate_rvecs(rvecs, maws, errors, asint=False):
r"""
Compute aggregated residual vectors Phi(X_c)
"""
if rvecs.shape[0] == 0:
rvecs_agg = np.empty((0, rvecs.shape[1]), dtype=np.float)
if rvecs.shape[0] == 1:
rvecs_agg = rvecs
else:
# Prealloc sum output (do not assign the result of sum)
arr_float = np.empty((1, rvecs.shape[1]), dtype=np.float)
out = arr_float[0]
# Take weighted average of multi-assigned vectors
total_weight = maws.sum()
weighted_sum = (maws[:, np.newaxis] * rvecs.astype(np.float)).sum(axis=0, out=out)
np.divide(weighted_sum, total_weight, out=out)
vt.normalize_rows(arr_float, out=arr_float)
if asint:
rvecs_agg = np.clip(np.round(arr_float * 255.0), -127, 127).astype(np.int8)
else:
rvecs_agg = arr_float
return rvecs_agg
@derived_attribute(
tablename='vocab', parents=['feat*'],
colnames=['words'], coltypes=[VisualVocab],
configclass=VocabConfig, chunksize=1, fname='visual_vocab',
vectorized=False,
)
def compute_vocab(depc, fid_list, config):
r"""
Depcache method for computing a new visual vocab
CommandLine:
python -m ibeis.core_annots --exec-compute_neighbor_index --show
python -m ibeis.control.IBEISControl --test-show_depc_annot_table_input --show --tablename=neighbor_index
python -m ibeis.new_annots --exec-compute_vocab:0
# FIXME make util_tests register
python -m ibeis.new_annots compute_vocab:0
Ignore:
ibs.depc['vocab'].print_table()
Example:
>>> # DISABLE_DOCTEST
>>> from ibeis.new_annots import * # NOQA
>>> # Test depcache access
>>> import ibeis
>>> ibs, aid_list = ibeis.testdata_aids('testdb1')
>>> depc = ibs.depc_annot
>>> input_tuple = [aid_list]
>>> rowid_kw = {}
>>> tablename = 'vocab'
>>> vocabid_list = depc.get_rowids(tablename, input_tuple, **rowid_kw)
>>> vocab = depc.get(tablename, input_tuple, 'words')[0]
>>> assert vocab.wordflann is not None
>>> assert vocab.wordflann._FLANN__curindex_data is not None
>>> assert vocab.wordflann._FLANN__curindex_data is vocab.wx_to_word
Example:
>>> # DISABLE_DOCTEST
>>> from ibeis.new_annots import * # NOQA
>>> import ibeis
>>> ibs, aid_list = ibeis.testdata_aids('testdb1')
>>> depc = ibs.depc_annot
>>> fid_list = depc.get_rowids('feat', aid_list)
>>> config = VocabConfig()
>>> vocab, train_vecs = ut.exec_func_src(compute_vocab, key_list=['vocab', 'train_vecs'])
>>> idx_to_vec = depc.d.get_feat_vecs(aid_list)[0]
>>> self = vocab
>>> ut.quit_if_noshow()
>>> data = train_vecs
>>> centroids = vocab.wx_to_word
>>> import plottool as pt
>>> vt.plot_centroids(data, centroids, num_pca_dims=2)
>>> ut.show_if_requested()
>>> #config = ibs.depc_annot['vocab'].configclass()
"""
print('[IBEIS] COMPUTE_VOCAB:')
vecs_list = depc.get_native('feat', fid_list, 'vecs')
train_vecs = np.vstack(vecs_list)
num_words = config['num_words']
max_iters = 100
print('[smk_index] Train Vocab(nWords=%d) using %d annots and %d descriptors' %
(num_words, len(fid_list), len(train_vecs)))
flann_params = vt.get_flann_params(random_seed=42)
kwds = dict(
max_iters=max_iters,
flann_params=flann_params
)
if config['algorithm'] == 'kdtree':
words = vt.akmeans(train_vecs, num_words, **kwds)
elif config['algorithm'] == 'minibatch':
print('Using minibatch kmeans')
import sklearn.cluster
rng = np.random.RandomState(config['random_seed'])
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
clusterer = sklearn.cluster.MiniBatchKMeans(
num_words, random_state=rng, verbose=5)
clusterer.fit(train_vecs)
words = clusterer.cluster_centers_
if False:
flann_params['checks'] = 64
flann_params['trees'] = 4
num_words = 128
centroids = vt.initialize_centroids(num_words, train_vecs, 'akmeans++')
words, hist = vt.akmeans_iterations(train_vecs, centroids, max_iters=1000, monitor=True,
flann_params=flann_params)
# words, hist = vt.akmeans_iterations(train_vecs, centroids, max_iters=max_iters, monitor=True,
# flann_params=flann_params)
import plottool as pt
ut.qt4ensure()
pt.multi_plot(hist['epoch_num'], [hist['loss']], fnum=2, pnum=(1, 2, 1), label_list=['loss'])
pt.multi_plot(hist['epoch_num'], [hist['ave_unchanged']], fnum=2, pnum=(1, 2, 2), label_list=['unchanged'])
vocab = VisualVocab(words)
vocab.reindex()
return (vocab,)
@ut.memoize
def testdata_vocab(defaultdb='testdb1', **kwargs):
"""
>>> from ibeis.new_annots import * # NOQA
"""
import ibeis
ibs, aid_list = ibeis.testdata_aids(defaultdb=defaultdb)
config = VocabConfig(**kwargs)
vocab = ibs.depc_annot.get('vocab', [aid_list], 'words', config=config)[0]
return ibs, aid_list, vocab
def testdata_inva(*args, **kwargs):
ibs, aid_list, vocab = testdata_vocab(*args, **kwargs)
fstack = ForwardIndex(ibs, aid_list)
inva = InvertedIndex(fstack, vocab, nAssign=3)
return ibs, aid_list, inva
def testdata_smk(*args, **kwargs):
"""
>>> from ibeis.new_annots import * # NOQA
>>> kwargs = {}
"""
import ibeis
import sklearn
import sklearn.cross_validation
# import sklearn.model_selection
ibs, aid_list = ibeis.testdata_aids(defaultdb='PZ_MTEST')
nid_list = np.array(ibs.annots(aid_list).nids)
rng = ut.ensure_rng(0)
xvalkw = dict(n_folds=4, shuffle=False, random_state=rng)
skf = sklearn.cross_validation.StratifiedKFold(nid_list, **xvalkw)
train_idx, test_idx = six.next(iter(skf))
daids = ut.take(aid_list, train_idx)
qaids = ut.take(aid_list, test_idx)
config = {
'num_words': 1000,
}
config.update(**kwargs)
qreq_ = SMKRequest(ibs, qaids, daids, config)
qreq_.ensure_data()
smk = qreq_.smk
#qreq_ = ibs.new_query_request(qaids, daids, cfgdict={'pipeline_root': 'smk', 'proot': 'smk'})
#qreq_ = ibs.new_query_request(qaids, daids, cfgdict={})
return ibs, smk, qreq_
if __name__ == '__main__':
r"""
CommandLine:
python -m ibeis.new_annots
python -m ibeis.new_annots --allexamples
"""
import multiprocessing
multiprocessing.freeze_support() # for win32
import utool as ut # NOQA
ut.doctest_funcs()
| {'content_hash': '8f832b12285b07b6e203eb56337f83f4', 'timestamp': '', 'source': 'github', 'line_count': 1334, 'max_line_length': 125, 'avg_line_length': 36.92128935532234, 'alnum_prop': 0.5713763628611455, 'repo_name': 'SU-ECE-17-7/ibeis', 'id': 'af73ba39a5ba5c058ddfcc9ab90a6dfe07ebc6e1', 'size': '49277', 'binary': False, 'copies': '1', 'ref': 'refs/heads/next', 'path': 'ibeis/new_annots.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CMake', 'bytes': '331'}, {'name': 'CSS', 'bytes': '26792'}, {'name': 'HTML', 'bytes': '33762203'}, {'name': 'Inno Setup', 'bytes': '1585'}, {'name': 'JavaScript', 'bytes': '227454'}, {'name': 'Jupyter Notebook', 'bytes': '66346367'}, {'name': 'Python', 'bytes': '6112508'}, {'name': 'Shell', 'bytes': '58211'}]} |
#include <errno.h>
#include <sstream>
#include "gcanvas/GPoint.h"
#include "GCanvas.hpp"
#include "GCanvas2dContext.h"
#ifdef ANDROID
#include "platform/Android/GFontCache.h"
#include "platform/Android/GCanvas2DContextAndroid.h"
#include "support/CharacterSet.h"
#endif
namespace gcanvas {
GCanvas::GCanvas(std::string canvasId, const GCanvasConfig &config, GCanvasHooks *hooks) :
mContextId(canvasId),
mConfig(config)
{
mHooks = hooks;
LOG_D("Create Canvas");
}
void GCanvas::CreateContext() {
mCanvasContext = new GCanvasContext(0, 0, mConfig, mHooks);
mCanvasContext->mContextId = this->mContextId;
}
void GCanvas::Clear() {
LOG_D("Canvas::DoContextLost start.");
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
LOG_D("Canvas::DoContextLost end.");
}
GCanvas::~GCanvas() {
// LOG_D("Canvas clear");
if (mCanvasContext != NULL) {
delete mCanvasContext;
mCanvasContext = NULL;
}
// Clear();
}
/**
* View大小变化回调(GCanvas创建时会主动调一次)
*/
void GCanvas::OnSurfaceChanged(int x, int y, int width, int height) {
GLint maxRenderbufferSize;
glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &maxRenderbufferSize);
// if ((maxRenderbufferSize <= width) || (maxRenderbufferSize <= height)) {
// LOG_E("GL_MAX_RENDERBUFFER_SIZE error maxRenderbufferSize is %d width is %d height is %d ",maxRenderbufferSize,width,height);
// LOG_EXCEPTION(mHooks, mContextId, "surfacesize_exceed_max",
// "<function:%s, maxSize:%d, width:%d, height:%d>", __FUNCTION__,
// maxRenderbufferSize, width, height);
// return;
// }
if (width == 0 || height == 0) {
return;
}
if (mCanvasContext->mWidth != width || mCanvasContext->mHeight != height) {
mCanvasContext->mX = x;
mCanvasContext->mY = y;
mCanvasContext->mWidth = width;
mCanvasContext->mHeight = height;
mCanvasContext->InitializeGLEnvironment();
}
mCanvasContext->SetContextLost(false);
}
bool GCanvas::IsGCanvasReady()
{
return mCanvasContext->mIsContextReady;
}
void GCanvas::drawFrame() {
mCanvasContext->SendVertexBufferToGPU();
}
}
| {'content_hash': '609c0203f95479ad29674dc5326928fc', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 136, 'avg_line_length': 25.813953488372093, 'alnum_prop': 0.6495495495495496, 'repo_name': 'jwxbond/GCanvas', 'id': '135c146ddf605ce55ed88f67b3664c5151009cfd', 'size': '2547', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/GCanvas.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2673420'}, {'name': 'C++', 'bytes': '1343130'}, {'name': 'CMake', 'bytes': '8322'}, {'name': 'CSS', 'bytes': '13047'}, {'name': 'GLSL', 'bytes': '21523'}, {'name': 'HTML', 'bytes': '7850'}, {'name': 'Java', 'bytes': '2081913'}, {'name': 'JavaScript', 'bytes': '3252726'}, {'name': 'Objective-C', 'bytes': '142977'}, {'name': 'Objective-C++', 'bytes': '38857'}, {'name': 'Ruby', 'bytes': '4070'}, {'name': 'Shell', 'bytes': '683'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>area-method: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / area-method - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
area-method
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-14 21:30:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-14 21:30:01 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/area-method"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/AreaMethod"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: geometry"
"keyword: Chou Gao Zhang area method"
"keyword: decision procedure"
"keyword: automatic theorem proving"
"date: 2004-2010"
]
authors: [
"Julien Narboux"
]
bug-reports: "https://github.com/coq-contribs/area-method/issues"
dev-repo: "git+https://github.com/coq-contribs/area-method.git"
synopsis: "The Chou, Gao and Zhang area method"
description: """
This contribution is the implementation of the Chou, Gao and Zhang's area method decision procedure for euclidean plane geometry.
This development contains a partial formalization of the book "Machine Proofs in Geometry, Automated Production of Readable Proofs for Geometry Theorems" by Chou, Gao and Zhang.
The examples shown automatically (there are more than 100 examples) includes the Ceva, Desargues, Menelaus, Pascal, Centroïd, Pappus, Gauss line, Euler line, Napoleon theorems.
Changelog
2.1 : remove some not needed assumptions in some elimination lemmas (2010)
2.0 : extension implementation to Euclidean geometry (2009-2010)
1.0 : first implementation for affine geometry (2004)"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/area-method/archive/v8.10.0.tar.gz"
checksum: "md5=82e7179a07bdf2a921fc7e8fa1079de4"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-area-method.8.10.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-area-method -> coq < 8.11~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-area-method.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '53c55a019bc3a19dc977bd0454229f31', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 187, 'avg_line_length': 42.90502793296089, 'alnum_prop': 0.5665364583333333, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'ab177b0ae5786b3f298c0144f8d7d5baf6bc0cd5', 'size': '7706', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.08.1-2.0.5/released/8.13.1/area-method/8.10.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
namespace test.sacs
{
public class HistDataWithCondition1 : Test.Framework.TestCase
{
public HistDataWithCondition1()
: base("sacs_histDataWithCondition_tc1", "histDataWithCondition"
, "histDataWithCondition", "test query expression for historical data", "test hist_data_w_condition"
, null)
{
AddPreItem(new test.sacs.HistDataWConditionInit());
AddPostItem(new test.sacs.HistDataWConditionDeinit());
}
public override Test.Framework.TestResult Run()
{
Test.Framework.TestResult result;
string expResult = "Writing data succeeded.";
DDS.ReturnCode ddsReturnCode;
mod.tst data = new mod.tst();
data.long_1 = 1;
data.long_2 = 2;
data.long_3 = 3;
mod.tstDataWriter writer;
mod.tstDataReader reader;
DDS.DataReaderQos drQos;
DDS.ISubscriber subscriber;
DDS.ITopic topic;
DDS.ResourceLimitsQosPolicy resource;
DDS.Duration maxWait;
DDS.Time maxSourceTime;
DDS.Time minSourceTime;
DDS.IDomainParticipant participant;
DDS.Time tHolder = new DDS.Time();
mod.tst[] dataList;
DDS.SampleInfo[] infoList;
ddsReturnCode = DDS.ReturnCode.Ok;
result = new Test.Framework.TestResult(expResult, string.Empty, Test.Framework.TestVerdict.Pass,
Test.Framework.TestVerdict.Fail);
drQos = (DDS.DataReaderQos)this.ResolveObject("datareaderQos");
subscriber = (DDS.ISubscriber)this.ResolveObject("subscriber");
topic = (DDS.ITopic)this.ResolveObject("topic");
participant = (DDS.IDomainParticipant)this.ResolveObject("participant");
ddsReturnCode = DDS.ReturnCode.Ok;
result = new Test.Framework.TestResult(expResult, string.Empty, Test.Framework.TestVerdict.Pass,
Test.Framework.TestVerdict.Fail);
writer = (mod.tstDataWriter)this.ResolveObject("datawriter");
for (int i = 0; (i < 10) && (ddsReturnCode == DDS.ReturnCode.Ok); i++)
{
data.long_1 = i;
data.long_2 = data.long_1 + 1;
data.long_3 = data.long_1 + 2;
System.Console.Out.WriteLine("Write: " + data.long_1 + ", " + data.long_2 + ", "
+ data.long_3);
ddsReturnCode = writer.Write(data, DDS.InstanceHandle.Nil);
}
if (ddsReturnCode != DDS.ReturnCode.Ok)
{
result.Result = "Writing data failed.";
return result;
}
drQos = (DDS.DataReaderQos)this.ResolveObject("datareaderQos");
subscriber = (DDS.ISubscriber)this.ResolveObject("subscriber");
topic = (DDS.ITopic)this.ResolveObject("topic");
participant = (DDS.IDomainParticipant)this.ResolveObject("participant");
reader = (mod.tstDataReader)subscriber.CreateDataReader(topic, drQos);//, null, 0);
if (reader == null)
{
result.Result = "creating datareader failed.";
return result;
}
resource = new DDS.ResourceLimitsQosPolicy();
resource.MaxInstances = -1;
resource.MaxSamples = -1;
resource.MaxSamplesPerInstance = -1;
maxWait = new DDS.Duration(10, 0);
minSourceTime = new DDS.Time(0, 0);
participant.GetCurrentTime(out tHolder);
maxSourceTime = tHolder;
ddsReturnCode = reader.WaitForHistoricalDataWithCondition(
"long_1 < 5 AND long_2 < 5", null, minSourceTime, maxSourceTime, resource, maxWait);
if (ddsReturnCode != DDS.ReturnCode.Ok)
{
result.Result = "wait_for_historical_data_w_condition failed";
subscriber.DeleteDataReader(reader);
return result;
}
dataList = null;
infoList = null;
ddsReturnCode = reader.Take(ref dataList, ref infoList, 10, DDS.SampleStateKind.Any, DDS.ViewStateKind.Any,
DDS.InstanceStateKind.Any);
if (ddsReturnCode != DDS.ReturnCode.Ok)
{
result.Result = "datareader.take failed " + ddsReturnCode + " (" + dataList
.Length + " samples taken)";
this.testFramework.TestMessage(Test.Framework.TestMessage.Note, "waitForHistoricalDataWithCondition not implemented yet.");
result.ExpectedVerdict = Test.Framework.TestVerdict.Fail; subscriber.DeleteDataReader(reader);
return result;
}
for (int i = 0; i < dataList.Length; i++)
{
System.Console.Out.WriteLine("Read sample [" + dataList[i].long_1 + ", " +
dataList[i].long_2 + ", " + dataList[i].long_3 + "]");
}
if (dataList.Length != 4)
{
result.Result = "Unexpected number of samples received.";
this.testFramework.TestMessage(Test.Framework.TestMessage.Note, "waitForHistoricalDataWithCondition not implemented yet.");
result.ExpectedVerdict = Test.Framework.TestVerdict.Fail;
subscriber.DeleteDataReader(reader);
return result;
}
reader.ReturnLoan(ref dataList, ref infoList);
ddsReturnCode = reader.WaitForHistoricalDataWithCondition(
"long_1 < 5 AND long_2 > 5", null, minSourceTime, maxSourceTime, resource, maxWait);
if (ddsReturnCode != DDS.ReturnCode.PreconditionNotMet)
{
result.Result = "wait_for_historical_data_w_condition did not return precondition not met,";
subscriber.DeleteDataReader(reader);
return result;
}
ddsReturnCode = reader.WaitForHistoricalDataWithCondition(
"long_1 < 5 AND long_2 < 5", null, minSourceTime, maxSourceTime, resource, maxWait);
if (ddsReturnCode != DDS.ReturnCode.Ok)
{
result.Result = "wait_for_historical_data_w_condition did not succeed(2)";
subscriber.DeleteDataReader(reader);
return result;
}
subscriber.DeleteDataReader(reader);
result.Result = expResult;
result.Verdict = Test.Framework.TestVerdict.Pass;
return result;
}
}
}
| {'content_hash': 'd25cf9977955e098b4ee4266f1b97a3b', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 139, 'avg_line_length': 47.92805755395683, 'alnum_prop': 0.57069948964275, 'repo_name': 'osrf/opensplice', 'id': 'b3abe54cd5c875f9e509eda2e8bc4449b26c5c03', 'size': '6662', 'binary': False, 'copies': '2', 'ref': 'refs/heads/osrf-6.9.0', 'path': 'testsuite/dbt/api/dcps/sacs/histDataWithCondition/code/test/sacs/HistDataWithCondition1.cs', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '16400'}, {'name': 'Batchfile', 'bytes': '192174'}, {'name': 'C', 'bytes': '19618578'}, {'name': 'C#', 'bytes': '2428591'}, {'name': 'C++', 'bytes': '8036199'}, {'name': 'CMake', 'bytes': '35186'}, {'name': 'CSS', 'bytes': '41427'}, {'name': 'HTML', 'bytes': '457045'}, {'name': 'Java', 'bytes': '5184488'}, {'name': 'JavaScript', 'bytes': '540355'}, {'name': 'LLVM', 'bytes': '13059'}, {'name': 'Lex', 'bytes': '51476'}, {'name': 'Makefile', 'bytes': '513684'}, {'name': 'Objective-C', 'bytes': '38424'}, {'name': 'Perl', 'bytes': '164028'}, {'name': 'Python', 'bytes': '915683'}, {'name': 'Shell', 'bytes': '363583'}, {'name': 'TeX', 'bytes': '8134'}, {'name': 'Visual Basic', 'bytes': '290'}, {'name': 'Yacc', 'bytes': '202848'}]} |
<?php
namespace OC\Preview;
use Imagick;
if (extension_loaded('imagick')) {
$checkImagick = new Imagick();
if(count($checkImagick->queryFormats('SVG')) === 1) {
class SVG extends Provider {
public function getMimeType() {
return '/image\/svg\+xml/';
}
public function getThumbnail($path,$maxX,$maxY,$scalingup,$fileview) {
try{
$svg = new Imagick();
$svg->setBackgroundColor(new \ImagickPixel('transparent'));
$content = stream_get_contents($fileview->fopen($path, 'r'));
if(substr($content, 0, 5) !== '<?xml') {
$content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
}
$svg->readImageBlob($content);
$svg->setImageFormat('png32');
} catch (\Exception $e) {
\OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR);
return false;
}
//new image object
$image = new \OC_Image();
$image->loadFromData($svg);
//check if image object is valid
return $image->valid() ? $image : false;
}
}
\OC\Preview::registerProvider('OC\Preview\SVG');
}
}
| {'content_hash': '882184236f45c4c0cfcd40cd1f948cf3', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 85, 'avg_line_length': 22.5625, 'alnum_prop': 0.6001846722068329, 'repo_name': 'ACOKing/ArcherSys', 'id': '82ef3cdebf649c5b35cf95c741e1855f42949c00', 'size': '1263', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'owncloud-serv/lib/private/preview/svg.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '67515'}, {'name': 'C', 'bytes': '3774'}, {'name': 'C#', 'bytes': '22990'}, {'name': 'CSS', 'bytes': '3962087'}, {'name': 'JavaScript', 'bytes': '10147893'}, {'name': 'Makefile', 'bytes': '1502'}, {'name': 'PHP', 'bytes': '36479079'}, {'name': 'Perl', 'bytes': '31322'}, {'name': 'Python', 'bytes': '65317'}, {'name': 'Shell', 'bytes': '97302'}]} |
/*
* Dalvik-specific side of debugger support. (The JDWP code is intended to
* be relatively generic.)
*/
#ifndef ART_RUNTIME_DEBUGGER_H_
#define ART_RUNTIME_DEBUGGER_H_
#include <pthread.h>
#include <set>
#include <string>
#include <vector>
#include "gc_root.h"
#include "jdwp/jdwp.h"
#include "jni.h"
#include "jvalue.h"
#include "thread.h"
#include "thread_state.h"
namespace art {
namespace mirror {
class Class;
class Object;
class Throwable;
} // namespace mirror
class ArtField;
class ArtMethod;
class ObjectRegistry;
class ScopedObjectAccess;
class ScopedObjectAccessUnchecked;
class StackVisitor;
class Thread;
/*
* Invoke-during-breakpoint support.
*/
struct DebugInvokeReq {
DebugInvokeReq(uint32_t invoke_request_id, JDWP::ObjectId invoke_thread_id,
mirror::Object* invoke_receiver, mirror::Class* invoke_class,
ArtMethod* invoke_method, uint32_t invoke_options,
uint64_t args[], uint32_t args_count)
: request_id(invoke_request_id), thread_id(invoke_thread_id), receiver(invoke_receiver),
klass(invoke_class), method(invoke_method), arg_count(args_count), arg_values(args),
options(invoke_options), reply(JDWP::expandBufAlloc()) {
}
~DebugInvokeReq() {
JDWP::expandBufFree(reply);
}
// Request
const uint32_t request_id;
const JDWP::ObjectId thread_id;
GcRoot<mirror::Object> receiver; // not used for ClassType.InvokeMethod.
GcRoot<mirror::Class> klass;
ArtMethod* const method;
const uint32_t arg_count;
std::unique_ptr<uint64_t[]> arg_values; // will be null if arg_count_ == 0. We take ownership
// of this array so we must delete it upon destruction.
const uint32_t options;
// Reply
JDWP::ExpandBuf* const reply;
void VisitRoots(RootVisitor* visitor, const RootInfo& root_info)
SHARED_REQUIRES(Locks::mutator_lock_);
private:
DISALLOW_COPY_AND_ASSIGN(DebugInvokeReq);
};
// Thread local data-structure that holds fields for controlling single-stepping.
class SingleStepControl {
public:
SingleStepControl(JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth,
int stack_depth, ArtMethod* method)
: step_size_(step_size), step_depth_(step_depth),
stack_depth_(stack_depth), method_(method) {
}
JDWP::JdwpStepSize GetStepSize() const {
return step_size_;
}
JDWP::JdwpStepDepth GetStepDepth() const {
return step_depth_;
}
int GetStackDepth() const {
return stack_depth_;
}
ArtMethod* GetMethod() const {
return method_;
}
const std::set<uint32_t>& GetDexPcs() const {
return dex_pcs_;
}
void AddDexPc(uint32_t dex_pc);
bool ContainsDexPc(uint32_t dex_pc) const;
private:
// See JdwpStepSize and JdwpStepDepth for details.
const JDWP::JdwpStepSize step_size_;
const JDWP::JdwpStepDepth step_depth_;
// The stack depth when this single-step was initiated. This is used to support SD_OVER and SD_OUT
// single-step depth.
const int stack_depth_;
// The location this single-step was initiated from.
// A single-step is initiated in a suspended thread. We save here the current method and the
// set of DEX pcs associated to the source line number where the suspension occurred.
// This is used to support SD_INTO and SD_OVER single-step depths so we detect when a single-step
// causes the execution of an instruction in a different method or at a different line number.
ArtMethod* method_;
std::set<uint32_t> dex_pcs_;
DISALLOW_COPY_AND_ASSIGN(SingleStepControl);
};
// TODO rename to InstrumentationRequest.
class DeoptimizationRequest {
public:
enum Kind {
kNothing, // no action.
kRegisterForEvent, // start listening for instrumentation event.
kUnregisterForEvent, // stop listening for instrumentation event.
kFullDeoptimization, // deoptimize everything.
kFullUndeoptimization, // undeoptimize everything.
kSelectiveDeoptimization, // deoptimize one method.
kSelectiveUndeoptimization // undeoptimize one method.
};
DeoptimizationRequest() : kind_(kNothing), instrumentation_event_(0), method_(nullptr) {}
DeoptimizationRequest(const DeoptimizationRequest& other)
SHARED_REQUIRES(Locks::mutator_lock_)
: kind_(other.kind_), instrumentation_event_(other.instrumentation_event_) {
// Create a new JNI global reference for the method.
SetMethod(other.Method());
}
ArtMethod* Method() const SHARED_REQUIRES(Locks::mutator_lock_);
void SetMethod(ArtMethod* m) SHARED_REQUIRES(Locks::mutator_lock_);
// Name 'Kind()' would collide with the above enum name.
Kind GetKind() const {
return kind_;
}
void SetKind(Kind kind) {
kind_ = kind;
}
uint32_t InstrumentationEvent() const {
return instrumentation_event_;
}
void SetInstrumentationEvent(uint32_t instrumentation_event) {
instrumentation_event_ = instrumentation_event;
}
private:
Kind kind_;
// TODO we could use a union to hold the instrumentation_event and the method since they
// respectively have sense only for kRegisterForEvent/kUnregisterForEvent and
// kSelectiveDeoptimization/kSelectiveUndeoptimization.
// Event to start or stop listening to. Only for kRegisterForEvent and kUnregisterForEvent.
uint32_t instrumentation_event_;
// Method for selective deoptimization.
jmethodID method_;
};
std::ostream& operator<<(std::ostream& os, const DeoptimizationRequest::Kind& rhs);
class Dbg {
public:
static void SetJdwpAllowed(bool allowed);
static void StartJdwp();
static void StopJdwp();
// Invoked by the GC in case we need to keep DDMS informed.
static void GcDidFinish() REQUIRES(!Locks::mutator_lock_);
// Return the DebugInvokeReq for the current thread.
static DebugInvokeReq* GetInvokeReq();
static Thread* GetDebugThread();
static void ClearWaitForEventThread();
/*
* Enable/disable breakpoints and step modes. Used to provide a heads-up
* when the debugger attaches.
*/
static void Connected();
static void GoActive()
REQUIRES(!Locks::breakpoint_lock_, !Locks::deoptimization_lock_, !Locks::mutator_lock_);
static void Disconnected() REQUIRES(!Locks::deoptimization_lock_, !Locks::mutator_lock_);
static void Dispose() {
gDisposed = true;
}
// Returns true if we're actually debugging with a real debugger, false if it's
// just DDMS (or nothing at all).
static bool IsDebuggerActive() {
return gDebuggerActive;
}
// Configures JDWP with parsed command-line options.
static void ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options);
// Returns true if we had -Xrunjdwp or -agentlib:jdwp= on the command line.
static bool IsJdwpConfigured();
// Returns true if a method has any breakpoints.
static bool MethodHasAnyBreakpoints(ArtMethod* method)
SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Locks::breakpoint_lock_);
static bool IsDisposed() {
return gDisposed;
}
/*
* Time, in milliseconds, since the last debugger activity. Does not
* include DDMS activity. Returns -1 if there has been no activity.
* Returns 0 if we're in the middle of handling a debugger request.
*/
static int64_t LastDebuggerActivity();
static void UndoDebuggerSuspensions()
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
/*
* Class, Object, Array
*/
static std::string GetClassName(JDWP::RefTypeId id)
SHARED_REQUIRES(Locks::mutator_lock_);
static std::string GetClassName(mirror::Class* klass)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static void GetClassList(std::vector<JDWP::RefTypeId>* classes)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
uint32_t* pStatus, std::string* pDescriptor)
SHARED_REQUIRES(Locks::mutator_lock_);
static void FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetSignature(JDWP::RefTypeId ref_type_id, std::string* signature)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetSourceFile(JDWP::RefTypeId ref_type_id, std::string* source_file)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag)
SHARED_REQUIRES(Locks::mutator_lock_);
static size_t GetTagWidth(JDWP::JdwpTag tag);
static JDWP::JdwpError GetArrayLength(JDWP::ObjectId array_id, int32_t* length)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError OutputArray(JDWP::ObjectId array_id, int offset, int count,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
JDWP::Request* request)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError CreateString(const std::string& str, JDWP::ObjectId* new_string_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
JDWP::ObjectId* new_array_id)
SHARED_REQUIRES(Locks::mutator_lock_);
//
// Event filtering.
//
static bool MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool MatchLocation(const JDWP::JdwpLocation& expected_location,
const JDWP::EventLocation& event_location)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
ArtField* event_field)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance)
SHARED_REQUIRES(Locks::mutator_lock_);
//
// Monitors.
//
static JDWP::JdwpError GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetOwnedMonitors(JDWP::ObjectId thread_id,
std::vector<JDWP::ObjectId>* monitors,
std::vector<uint32_t>* stack_depths)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetContendedMonitor(JDWP::ObjectId thread_id,
JDWP::ObjectId* contended_monitor)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
//
// Heap.
//
static JDWP::JdwpError GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
std::vector<uint64_t>* counts)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
std::vector<JDWP::ObjectId>* instances)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
std::vector<JDWP::ObjectId>* referring_objects)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError DisableCollection(JDWP::ObjectId object_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError EnableCollection(JDWP::ObjectId object_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError IsCollected(JDWP::ObjectId object_id, bool* is_collected)
SHARED_REQUIRES(Locks::mutator_lock_);
static void DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
SHARED_REQUIRES(Locks::mutator_lock_);
//
// Methods and fields.
//
static std::string GetMethodName(JDWP::MethodId method_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError OutputDeclaredFields(JDWP::RefTypeId ref_type_id, bool with_generic,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError OutputDeclaredMethods(JDWP::RefTypeId ref_type_id, bool with_generic,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError OutputDeclaredInterfaces(JDWP::RefTypeId ref_type_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static void OutputLineTable(JDWP::RefTypeId ref_type_id, JDWP::MethodId method_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static void OutputVariableTable(JDWP::RefTypeId ref_type_id, JDWP::MethodId id, bool with_generic,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static void OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static void OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetBytecodes(JDWP::RefTypeId class_id, JDWP::MethodId method_id,
std::vector<uint8_t>* bytecodes)
SHARED_REQUIRES(Locks::mutator_lock_);
static std::string GetFieldName(JDWP::FieldId field_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpTag GetFieldBasicTag(JDWP::FieldId field_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpTag GetStaticFieldBasicTag(JDWP::FieldId field_id)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
uint64_t value, int width)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError StringToUtf8(JDWP::ObjectId string_id, std::string* str)
SHARED_REQUIRES(Locks::mutator_lock_);
static void OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
/*
* Thread, ThreadGroup, Frame
*/
static JDWP::JdwpError GetThreadName(JDWP::ObjectId thread_id, std::string* name)
SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Locks::thread_list_lock_);
static JDWP::JdwpError GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Locks::thread_list_lock_);
static JDWP::JdwpError GetThreadGroupName(JDWP::ObjectId thread_group_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetThreadGroupParent(JDWP::ObjectId thread_group_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
JDWP::ExpandBuf* pReply)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::ObjectId GetSystemThreadGroupId()
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpThreadStatus ToJdwpThreadStatus(ThreadState state);
static JDWP::JdwpError GetThreadStatus(JDWP::ObjectId thread_id,
JDWP::JdwpThreadStatus* pThreadStatus,
JDWP::JdwpSuspendStatus* pSuspendStatus)
REQUIRES(!Locks::thread_list_lock_);
static JDWP::JdwpError GetThreadDebugSuspendCount(JDWP::ObjectId thread_id,
JDWP::ExpandBuf* pReply)
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
// static void WaitForSuspend(JDWP::ObjectId thread_id);
// Fills 'thread_ids' with the threads in the given thread group. If thread_group_id == 0,
// returns all threads.
static void GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result)
REQUIRES(!Locks::thread_list_lock_);
static JDWP::JdwpError GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
size_t frame_count, JDWP::ExpandBuf* buf)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::ObjectId GetThreadSelfId() SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::ObjectId GetThreadId(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_);
static void SuspendVM()
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
static void ResumeVM()
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
static JDWP::JdwpError SuspendThread(JDWP::ObjectId thread_id, bool request_suspension = true)
REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_,
!Locks::thread_suspend_count_lock_);
static void ResumeThread(JDWP::ObjectId thread_id)
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_)
SHARED_REQUIRES(Locks::mutator_lock_);
static void SuspendSelf();
static JDWP::JdwpError GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
JDWP::ObjectId* result)
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError SetLocalValues(JDWP::Request* request)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError Interrupt(JDWP::ObjectId thread_id)
REQUIRES(!Locks::thread_list_lock_);
/*
* Debugger notification
*/
enum EventFlag {
kBreakpoint = 0x01,
kSingleStep = 0x02,
kMethodEntry = 0x04,
kMethodExit = 0x08,
};
static void PostFieldAccessEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
ArtField* f)
SHARED_REQUIRES(Locks::mutator_lock_);
static void PostFieldModificationEvent(ArtMethod* m, int dex_pc,
mirror::Object* this_object, ArtField* f,
const JValue* field_value)
SHARED_REQUIRES(Locks::mutator_lock_);
static void PostException(mirror::Throwable* exception)
SHARED_REQUIRES(Locks::mutator_lock_);
static void PostThreadStart(Thread* t)
SHARED_REQUIRES(Locks::mutator_lock_);
static void PostThreadDeath(Thread* t)
SHARED_REQUIRES(Locks::mutator_lock_);
static void PostClassPrepare(mirror::Class* c)
SHARED_REQUIRES(Locks::mutator_lock_);
static void UpdateDebugger(Thread* thread, mirror::Object* this_object,
ArtMethod* method, uint32_t new_dex_pc,
int event_flags, const JValue* return_value)
REQUIRES(!Locks::breakpoint_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
// Indicates whether we need deoptimization for debugging.
static bool RequiresDeoptimization();
// Records deoptimization request in the queue.
static void RequestDeoptimization(const DeoptimizationRequest& req)
REQUIRES(!Locks::deoptimization_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
// Manage deoptimization after updating JDWP events list. Suspends all threads, processes each
// request and finally resumes all threads.
static void ManageDeoptimization()
REQUIRES(!Locks::deoptimization_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
// Breakpoints.
static void WatchLocation(const JDWP::JdwpLocation* pLoc, DeoptimizationRequest* req)
REQUIRES(!Locks::breakpoint_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static void UnwatchLocation(const JDWP::JdwpLocation* pLoc, DeoptimizationRequest* req)
REQUIRES(!Locks::breakpoint_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
/*
* Forced interpreter checkers for single-step and continue support.
*/
// Indicates whether we need to force the use of interpreter to invoke a method.
// This allows to single-step or continue into the called method.
static bool IsForcedInterpreterNeededForCalling(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_) {
if (!IsDebuggerActive()) {
return false;
}
return IsForcedInterpreterNeededForCallingImpl(thread, m);
}
// Indicates whether we need to force the use of interpreter entrypoint when calling a
// method through the resolution trampoline. This allows to single-step or continue into
// the called method.
static bool IsForcedInterpreterNeededForResolution(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_) {
if (!IsDebuggerActive()) {
return false;
}
return IsForcedInterpreterNeededForResolutionImpl(thread, m);
}
// Indicates whether we need to force the use of instrumentation entrypoint when calling
// a method through the resolution trampoline. This allows to deoptimize the stack for
// debugging when we returned from the called method.
static bool IsForcedInstrumentationNeededForResolution(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_) {
if (!IsDebuggerActive()) {
return false;
}
return IsForcedInstrumentationNeededForResolutionImpl(thread, m);
}
// Indicates whether we need to force the use of interpreter when returning from the
// interpreter into the runtime. This allows to deoptimize the stack and continue
// execution with interpreter for debugging.
static bool IsForcedInterpreterNeededForUpcall(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_) {
if (!IsDebuggerActive() && !thread->HasDebuggerShadowFrames()) {
return false;
}
return IsForcedInterpreterNeededForUpcallImpl(thread, m);
}
// Indicates whether we need to force the use of interpreter when handling an
// exception. This allows to deoptimize the stack and continue execution with
// the interpreter.
// Note: the interpreter will start by handling the exception when executing
// the deoptimized frames.
static bool IsForcedInterpreterNeededForException(Thread* thread)
SHARED_REQUIRES(Locks::mutator_lock_) {
if (!IsDebuggerActive() && !thread->HasDebuggerShadowFrames()) {
return false;
}
return IsForcedInterpreterNeededForExceptionImpl(thread);
}
// Single-stepping.
static JDWP::JdwpError ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize size,
JDWP::JdwpStepDepth depth)
SHARED_REQUIRES(Locks::mutator_lock_);
static void UnconfigureStep(JDWP::ObjectId thread_id)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
/*
* Invoke support
*/
// Called by the JDWP thread to prepare invocation in the event thread (suspended on an event).
// If the information sent by the debugger is incorrect, it will send a reply with the
// appropriate error code. Otherwise, it will attach a DebugInvokeReq object to the event thread
// and resume it (and possibly other threads depending on the invoke options).
// Unlike other commands, the JDWP thread will not send the reply to the debugger (see
// JdwpState::ProcessRequest). The reply will be sent by the event thread itself after method
// invocation completes (see FinishInvokeMethod). This is required to allow the JDWP thread to
// process incoming commands from the debugger while the invocation is still in progress in the
// event thread, especially if it gets suspended by a debug event occurring in another thread.
static JDWP::JdwpError PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
JDWP::MethodId method_id, uint32_t arg_count,
uint64_t arg_values[], JDWP::JdwpTag* arg_types,
uint32_t options)
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_)
SHARED_REQUIRES(Locks::mutator_lock_);
// Called by the event thread to execute a method prepared by the JDWP thread in the given
// DebugInvokeReq object. Once the invocation completes, the event thread attaches a reply
// to that DebugInvokeReq object so it can be sent to the debugger only when the event thread
// is ready to suspend (see FinishInvokeMethod).
static void ExecuteMethod(DebugInvokeReq* pReq);
// Called by the event thread to send the reply of the invoke (created in ExecuteMethod)
// before suspending itself. This is to ensure the thread is ready to suspend before the
// debugger receives the reply.
static void FinishInvokeMethod(DebugInvokeReq* pReq);
/*
* DDM support.
*/
static void DdmSendThreadNotification(Thread* t, uint32_t type)
SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmSetThreadNotification(bool enable)
REQUIRES(!Locks::thread_list_lock_);
static bool DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen);
static void DdmConnected() SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmDisconnected() SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes)
SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmSendChunk(uint32_t type, size_t len, const uint8_t* buf)
SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count)
SHARED_REQUIRES(Locks::mutator_lock_);
// Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
static void VisitRoots(RootVisitor* visitor)
SHARED_REQUIRES(Locks::mutator_lock_);
/*
* Allocation tracking support.
*/
static void SetAllocTrackingEnabled(bool enabled) REQUIRES(!Locks::alloc_tracker_lock_);
static jbyteArray GetRecentAllocations()
REQUIRES(!Locks::alloc_tracker_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static void DumpRecentAllocations() REQUIRES(!Locks::alloc_tracker_lock_);
enum HpifWhen {
HPIF_WHEN_NEVER = 0,
HPIF_WHEN_NOW = 1,
HPIF_WHEN_NEXT_GC = 2,
HPIF_WHEN_EVERY_GC = 3
};
static int DdmHandleHpifChunk(HpifWhen when)
SHARED_REQUIRES(Locks::mutator_lock_);
enum HpsgWhen {
HPSG_WHEN_NEVER = 0,
HPSG_WHEN_EVERY_GC = 1,
};
enum HpsgWhat {
HPSG_WHAT_MERGED_OBJECTS = 0,
HPSG_WHAT_DISTINCT_OBJECTS = 1,
};
static bool DdmHandleHpsgNhsgChunk(HpsgWhen when, HpsgWhat what, bool native);
static void DdmSendHeapInfo(HpifWhen reason)
SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmSendHeapSegments(bool native)
SHARED_REQUIRES(Locks::mutator_lock_);
static ObjectRegistry* GetObjectRegistry() {
return gRegistry;
}
static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::FieldId ToFieldId(const ArtField* f)
SHARED_REQUIRES(Locks::mutator_lock_);
static void SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc)
SHARED_REQUIRES(Locks::mutator_lock_)
REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
static JDWP::JdwpState* GetJdwpState();
static uint32_t GetInstrumentationEvents() SHARED_REQUIRES(Locks::mutator_lock_) {
return instrumentation_events_;
}
private:
static void ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq)
SHARED_REQUIRES(Locks::mutator_lock_);
static void BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id,
JDWP::JdwpTag result_tag, uint64_t result_value,
JDWP::ObjectId exception)
SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError GetLocalValue(const StackVisitor& visitor,
ScopedObjectAccessUnchecked& soa, int slot,
JDWP::JdwpTag tag, uint8_t* buf, size_t width)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static JDWP::JdwpError SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
JDWP::JdwpTag tag, uint64_t value, size_t width)
REQUIRES(!Locks::thread_list_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static void DdmBroadcast(bool connect) SHARED_REQUIRES(Locks::mutator_lock_);
static void PostThreadStartOrStop(Thread*, uint32_t)
SHARED_REQUIRES(Locks::mutator_lock_);
static void PostLocationEvent(ArtMethod* method, int pcOffset,
mirror::Object* thisPtr, int eventFlags,
const JValue* return_value)
SHARED_REQUIRES(Locks::mutator_lock_);
static void ProcessDeoptimizationRequest(const DeoptimizationRequest& request)
REQUIRES(Locks::mutator_lock_, Roles::uninterruptible_);
static void RequestDeoptimizationLocked(const DeoptimizationRequest& req)
REQUIRES(Locks::deoptimization_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
static bool IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m)
SHARED_REQUIRES(Locks::mutator_lock_);
static bool IsForcedInterpreterNeededForExceptionImpl(Thread* thread)
SHARED_REQUIRES(Locks::mutator_lock_);
// Indicates whether the debugger is making requests.
static bool gDebuggerActive;
// Indicates whether we should drop the JDWP connection because the runtime stops or the
// debugger called VirtualMachine.Dispose.
static bool gDisposed;
// The registry mapping objects to JDWP ids.
static ObjectRegistry* gRegistry;
// Deoptimization requests to be processed each time the event list is updated. This is used when
// registering and unregistering events so we do not deoptimize while holding the event list
// lock.
// TODO rename to instrumentation_requests.
static std::vector<DeoptimizationRequest> deoptimization_requests_ GUARDED_BY(Locks::deoptimization_lock_);
// Count the number of events requiring full deoptimization. When the counter is > 0, everything
// is deoptimized, otherwise everything is undeoptimized.
// Note: we fully deoptimize on the first event only (when the counter is set to 1). We fully
// undeoptimize when the last event is unregistered (when the counter is set to 0).
static size_t full_deoptimization_event_count_ GUARDED_BY(Locks::deoptimization_lock_);
static size_t* GetReferenceCounterForEvent(uint32_t instrumentation_event);
// Instrumentation event reference counters.
// TODO we could use an array instead of having all these dedicated counters. Instrumentation
// events are bits of a mask so we could convert them to array index.
static size_t dex_pc_change_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
static size_t method_enter_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
static size_t method_exit_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
static size_t field_read_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
static size_t field_write_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
static size_t exception_catch_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
static uint32_t instrumentation_events_ GUARDED_BY(Locks::mutator_lock_);
DISALLOW_COPY_AND_ASSIGN(Dbg);
};
#define CHUNK_TYPE(_name) \
static_cast<uint32_t>((_name)[0] << 24 | (_name)[1] << 16 | (_name)[2] << 8 | (_name)[3])
} // namespace art
#endif // ART_RUNTIME_DEBUGGER_H_
| {'content_hash': '06002bc460fe6d8f3eae31c5b1f84e87', 'timestamp': '', 'source': 'github', 'line_count': 784, 'max_line_length': 109, 'avg_line_length': 44.172193877551024, 'alnum_prop': 0.6938292281481909, 'repo_name': 'android-art-intel/Nougat', 'id': 'e908304977e723278ef0deb206224862ce5a9b4e', 'size': '35250', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'art-extension/runtime/debugger.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '5001041'}, {'name': 'C', 'bytes': '289114'}, {'name': 'C++', 'bytes': '18340188'}, {'name': 'CSS', 'bytes': '892'}, {'name': 'HTML', 'bytes': '6648'}, {'name': 'Java', 'bytes': '8319441'}, {'name': 'JavaScript', 'bytes': '451'}, {'name': 'Makefile', 'bytes': '246269'}, {'name': 'PHP', 'bytes': '24634'}, {'name': 'Perl', 'bytes': '115844'}, {'name': 'Python', 'bytes': '230897'}, {'name': 'Shell', 'bytes': '1287151'}, {'name': 'Smali', 'bytes': '444462'}]} |
<?xml version="1.0"?>
<!--
Copyright 2005-2014 The Kuali Foundation
Licensed under the Educational Community License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.opensource.org/licenses/ecl2.php
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>rice-krms</artifactId>
<groupId>org.kuali.rice</groupId>
<version>2.5.0-M5-SNAPSHOT</version>
</parent>
<artifactId>rice-krms-api</artifactId>
<name>Rice KRMS API</name>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rice-core-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<svc.co.name>ComparisonOperatorService</svc.co.name>
<svc.co.wsdl>${wsdl.dir}/${svc.co.name}.wsdl</svc.co.wsdl>
<svc.rr.name>RuleRepositoryService</svc.rr.name>
<svc.rr.wsdl>${wsdl.dir}/${svc.rr.name}.wsdl</svc.rr.wsdl>
<svc.fr.name>FunctionRepositoryService</svc.fr.name>
<svc.fr.wsdl>${wsdl.dir}/${svc.fr.name}.wsdl</svc.fr.wsdl>
<svc.rm.name>RuleManagementService</svc.rm.name>
<svc.rm.wsdl>${wsdl.dir}/${svc.rm.name}.wsdl</svc.rm.wsdl>
<svc.tr.name>TermRepositoryService</svc.tr.name>
<svc.tr.wsdl>${wsdl.dir}/${svc.tr.name}.wsdl</svc.tr.wsdl>
<svc.ktr.name>KrmsTypeRepositoryService</svc.ktr.name>
<svc.ktr.wsdl>${wsdl.dir}/${svc.ktr.name}.wsdl</svc.ktr.wsdl>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-java2ws-plugin</artifactId>
<executions>
<!--<execution>
<id>comparisonOperatorService-wsdl</id>
<phase>${rice.java2ws.phase}</phase>
<configuration>
<className>org.kuali.rice.krms.api.engine.expression.ComparisonOperatorService</className>
<outputFile>${svc.co.wsdl}</outputFile>
<serviceName>${svc.co.name}</serviceName>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>-->
<execution>
<id>krmsTypeRepositoryService-wsdl</id>
<phase>${rice.java2ws.phase}</phase>
<configuration>
<className>org.kuali.rice.krms.api.repository.type.KrmsTypeRepositoryService</className>
<outputFile>${svc.ktr.wsdl}</outputFile>
<serviceName>KrmsTypeRepositoryService</serviceName>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>
<execution>
<id>ruleRepositoryService-wsdl</id>
<phase>${rice.java2ws.phase}</phase>
<configuration>
<className>org.kuali.rice.krms.api.repository.RuleRepositoryService</className>
<outputFile>${svc.rr.wsdl}</outputFile>
<serviceName>RuleRepositoryService</serviceName>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>
<execution>
<id>functionRepositoryService-wsdl</id>
<phase>${rice.java2ws.phase}</phase>
<configuration>
<className>org.kuali.rice.krms.api.repository.function.FunctionRepositoryService</className>
<outputFile>${svc.fr.wsdl}</outputFile>
<serviceName>FunctionRepositoryService</serviceName>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>
<execution>
<id>ruleManagementService-wsdl</id>
<phase>${rice.java2ws.phase}</phase>
<configuration>
<className>org.kuali.rice.krms.api.repository.RuleManagementService</className>
<outputFile>${svc.rm.wsdl}</outputFile>
<serviceName>RuleManagementService</serviceName>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>
<execution>
<id>termRepositoryService-wsdl</id>
<phase>${rice.java2ws.phase}</phase>
<configuration>
<className>org.kuali.rice.krms.api.repository.term.TermRepositoryService</className>
<outputFile>${svc.tr.wsdl}</outputFile>
<serviceName>TermRepositoryService</serviceName>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>attach-wsdls</id>
<goals>
<goal>attach-artifact</goal>
</goals>
<configuration>
<artifacts>
<artifact>
<file>${svc.rr.wsdl}</file>
<classifier>${svc.rr.name}</classifier>
<type>wsdl</type>
</artifact>
<artifact>
<file>${svc.fr.wsdl}</file>
<classifier>${svc.fr.name}</classifier>
<type>wsdl</type>
</artifact>
<artifact>
<file>${svc.ktr.wsdl}</file>
<classifier>${svc.ktr.name}</classifier>
<type>wsdl</type>
</artifact>
<artifact>
<file>${svc.rm.wsdl}</file>
<classifier>${svc.rm.name}</classifier>
<type>wsdl</type>
</artifact>
<artifact>
<file>${svc.tr.wsdl}</file>
<classifier>${svc.tr.name}</classifier>
<type>wsdl</type>
</artifact>
</artifacts>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.cxf</groupId>
<artifactId>
cxf-java2ws-plugin
</artifactId>
<versionRange>
[2.7.0,)
</versionRange>
<goals>
<goal>java2ws</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
| {'content_hash': '1dea49fcb0b458ff615fae533eaa4dd1', 'timestamp': '', 'source': 'github', 'line_count': 219, 'max_line_length': 204, 'avg_line_length': 36.945205479452056, 'alnum_prop': 0.5630947966876777, 'repo_name': 'ewestfal/rice-svn2git-test', 'id': '4ccf4f05b6b624ef8896b7b7c3562b1cd69b4a25', 'size': '8091', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rice-middleware/krms/api/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '793243'}, {'name': 'Groovy', 'bytes': '2170621'}, {'name': 'Java', 'bytes': '34445604'}, {'name': 'JavaScript', 'bytes': '2635300'}, {'name': 'PHP', 'bytes': '15766'}, {'name': 'Shell', 'bytes': '10444'}, {'name': 'XSLT', 'bytes': '107686'}]} |
namespace YouCompleteMe {
Range::Range( const CXSourceRange &range ) {
start_ = Location( clang_getRangeStart( range ) );
end_ = Location( clang_getRangeEnd( range ) );
}
} // namespace YouCompleteMe
| {'content_hash': 'aba608942ff0f0741d00df18857f1cf1', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 52, 'avg_line_length': 23.0, 'alnum_prop': 0.7004830917874396, 'repo_name': 'NcLang/vimrc', 'id': '59d738e427ea7416859a4f34a9c9406aba83987f', 'size': '944', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'sources_non_forked/YouCompleteMe/third_party/ycmd/cpp/ycm/ClangCompleter/Range.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '568'}, {'name': 'CSS', 'bytes': '6320'}, {'name': 'CoffeeScript', 'bytes': '1402'}, {'name': 'Erlang', 'bytes': '3232'}, {'name': 'GCC Machine Description', 'bytes': '525'}, {'name': 'Go', 'bytes': '2239'}, {'name': 'HTML', 'bytes': '134'}, {'name': 'JavaScript', 'bytes': '1064'}, {'name': 'Makefile', 'bytes': '8657'}, {'name': 'Perl', 'bytes': '2705'}, {'name': 'Python', 'bytes': '704814'}, {'name': 'Ruby', 'bytes': '33390'}, {'name': 'Shell', 'bytes': '9370'}, {'name': 'TeX', 'bytes': '6193'}, {'name': 'VimL', 'bytes': '3170590'}, {'name': 'XSLT', 'bytes': '4217'}]} |
<section class="content-header">
<h1>Customers <small>Listing</small></h1>
<ol class="breadcrumb">
<li><a ui-sref="app.landing"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Customers Listing</li>
</ol>
</section>
<section class="content">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Customers List</h3>
<div class="box-tools pull-right">
<a ui-sref="app.customersadd" class="btn btn-block btn-success btn-xs"><i class="fa fa-plus"></i> Add New</a>
</div>
</div>
<div class="box-body">
<table datatable="" width="100%" class="table table-striped table-bordered" ng-if="vm.displayTable" dt-options="vm.dtOptions" dt-columns="vm.dtColumns"></table>
</div>
</div>
</section>
| {'content_hash': '60f7b33c78134b519cddba0f18f2f3ba', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 166, 'avg_line_length': 37.80952380952381, 'alnum_prop': 0.628463476070529, 'repo_name': 'thytran142/freelance-web-app', 'id': '8561a835110e586b5c760c00d976d2dac65e008e', 'size': '794', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'angular/app/components/customers/customers.component.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '553'}, {'name': 'CSS', 'bytes': '7181'}, {'name': 'HTML', 'bytes': '463132'}, {'name': 'JavaScript', 'bytes': '118043'}, {'name': 'PHP', 'bytes': '152712'}]} |
<head>
<link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax:{
inlineMath:[['$','$'],["\\(","\\)"]],
displayMath: [ ['$$', '$$'] ],
processEscapes:true,
}});
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax:{skipTags:['script','noscript','style','textarea','pre','code']},menuSettings:{zoom:"Hover"}});
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Queue(function(){var all=MathJax.Hub.getAllJax(),i;for(i=0;i<all.length;i+=1){all[i].SourceElement().parentNode.className+='has-jax';}});
</script>
<script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML&locale=zh-hans"></script>
<title>
{% if page.title == "Home" %}
{{ site.title }} · {{ site.tagline }}
{% else %}
{{ page.title }} · {{ site.title }}
{% endif %}
</title>
<!-- CSS -->
<link rel="stylesheet" href="{{ site.baseurl }}/public/css/poole.css">
<link rel="stylesheet" href="{{ site.baseurl }}/public/css/syntax.css">
<link rel="stylesheet" href="{{ site.baseurl }}/public/css/lanyon.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">
<!-- Icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ site.baseurl }}/public/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="{{ site.baseurl }}/public/favicon.ico">
<!-- RSS -->
<link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>
| {'content_hash': '868906b1f98d838d8af430009d122ec5', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 153, 'avg_line_length': 42.86666666666667, 'alnum_prop': 0.6324520476931053, 'repo_name': 'atubo/atubo.github.io', 'id': '08c116b3af7763fc0ff0b0082af7295a9ce0d9bb', 'size': '1929', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_includes/head.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23179'}, {'name': 'HTML', 'bytes': '6549'}]} |
<?xml version="1.0" encoding="utf-8"?>
<account-authenticator
xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="com.jhouseke.onemessageaway.acc"
android:icon="@drawable/ic_launcher"
android:smallIcon="@drawable/ic_launcher"
android:label="@string/app_name"/> | {'content_hash': '1bd8644c45ce8322405f062c322c22d5', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 62, 'avg_line_length': 44.0, 'alnum_prop': 0.7272727272727273, 'repo_name': 'jhouseke/one-message-away', 'id': 'abdf32a9e7bb1dc27b7280752ff632ce7110cd49', 'size': '308', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/xml/authenticator.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '26885'}, {'name': 'Java', 'bytes': '1444186'}, {'name': 'Makefile', 'bytes': '792745'}]} |
angular.module( 'ngBoilerplate.about', [
'ui.router',
'placeholders',
'ui.bootstrap'
])
.config(["$stateProvider", function config( $stateProvider ) {
$stateProvider.state( 'about', {
url: '/about',
views: {
"main": {
controller: 'AboutCtrl',
templateUrl: 'about/about.tpl.html'
}
},
data:{ pageTitle: 'What is It?' }
});
}])
.controller( 'AboutCtrl', function AboutCtrl( $scope ) {
// This is simple a demo for UI Boostrap.
$scope.dropdownDemoItems = [
"The first choice!",
"And another choice for you.",
"but wait! A third!"
];
})
;
| {'content_hash': 'f9c47195eb31a595c770875599cc099f', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 62, 'avg_line_length': 21.03448275862069, 'alnum_prop': 0.5868852459016394, 'repo_name': 'i5on9i/angluarjstemplate', 'id': 'cbea691b671026a4531ce0b60c43da3b775051bd', 'size': '610', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'easydownload/src/app/about/about.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2701'}, {'name': 'CoffeeScript', 'bytes': '2118'}, {'name': 'HTML', 'bytes': '20814'}, {'name': 'JavaScript', 'bytes': '27320'}, {'name': 'Smarty', 'bytes': '798'}]} |
<p align="center"><img src ="http://www.devin.com.br/wp-content/uploads/2010/07/mysql_logo.png" /></p>
# MySQL-Stataments
Stataments para MySQL no SA-MP.
>:heavy_exclamation_mark: Após uma perda de dados, a parte do código que se destinava a leitura foi perdida, portanto este agora apenas escreve dados, não lê.
##Funções
```pawn
// Prepared statements
Statement:stmt_prepare(ConnectionHandle, query[])
bool:stmt_execute(&Statement:statement, callback = "", auto_free_result = true)
stmt_bind_value(&Statement:statement, param, DataType:type, ...)
stmt_close(&Statement:statement)
```
##### stmt_prepare
>* Prepara um statement. Coloque pontos de interrogação como espaços reservados para valores a serem inseridos.
>* **Parametros:**
> * `ConnectionHandle`: ID da conexão com o banco de dados.
> * `query[]`: Query a ser preparada.
>* **Retorno:**
> * - ID do Statament criado.
>* **Notas:**
> * Não coloque aspas em torno dos pontos de interrogação.
***
##### stmt_bind_value
>* Definir um valor ao ponto de interrogação.
>* **Parametros:**
> * `&Statement:statement`: Statament em que o valor será designado.
> * `param`: Numero do parametro a alterar.
> * `DataType:type`: Tipo de dado a ser inserido.
> * `...`: Dado a inserir.
>* **Retorno:**
> * - Verdadeiro caso obtenha sucesso, falso caso contrário.
>* **Notas:**
> * Primeiro ponto de interrogação é param 0, segundo é 1, etc.
***
##### stmt_close
>* Fecha um Statament.
>* **Parametros:**
> * `&Statement:statement`: Statament que será fechado.
>* **Retorno:**
> * - Verdadeiro caso obtenha sucesso, falso caso contrário.
***
##### bool:stmt_execute
>* Executa o statement. Caso a callback seja valida irá chama-la
>* **Parametros:**
> * `&Statement:statement`: Statament que será executado.
> * `callback[]`: Callback que irar ser chamada após a query ser realizada.
>* **Retorno:**
> * - Verdadeiro caso obtenha sucesso, falso caso contrário.
***
###Inserindo dados
```pawn
// Prepara o statement
new Statement:stmt = stmt_prepare(Conection, "INSERT INTO mytable VALUES(?, ?, ?)");
// Seta os valores nas interrogações (Primeiro é 0, segundo é 1, etc...)
stmt_bind_value(stmt, 0, TYPE_FLOAT , 123.456);
stmt_bind_value(stmt, 1, TYPE_INT , 1234567);
stmt_bind_value(stmt, 2, TYPE_STRING, "there's no need to \"escape\" anything!");
// Executa o statement
stmt_execute(stmt);
// Agora fecha-o
stmt_close(stmt);
```
###Créditos
* Slice criação original do SQLitei.
* Dayvison transcrição de parte do código para MySQL.
| {'content_hash': '2938a0f106bf910cc16bb2e96317e68d', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 160, 'avg_line_length': 31.949367088607595, 'alnum_prop': 0.6893819334389857, 'repo_name': 'Dayvison/MySQL-Stataments', 'id': 'cad0cadb8b9d21f4679aa81fe3b21f5d3da887fd', 'size': '2561', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'SourcePawn', 'bytes': '7934'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '42afa1a0ac88b4f47a4c7c848877cefa', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'ec08bcd3a04fdc4a63eac708dd7a26b8a6f187a5', 'size': '193', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Croptilon/Croptilon hookerianum/ Syn. Isopappus hookerianus/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?php
/**
* @see Zym_View_Filter_Interface
*/
require_once 'Zym/View/Filter/Interface.php';
/**
* Converts asp tags to full <?php
*
* @author Geoffrey Tran
* @license http://www.zym-project.com/license New BSD License
* @package Zym_View
* @subpackage Filter
* @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/)
*/
class Zym_View_Filter_AspTags implements Zym_View_Filter_Interface
{
/**
* Filter
*
* @param string $buffer
* @return string
*/
public function filter($buffer)
{
// Don't parse if short_tags is enabled
if (ini_get('asp_tags')) {
return $buffer;
}
$pattern = array(
'/<\%(?:=)?(?:\s)*(.*?)(?:;?\s*)\%>/xisS', // <%= handling
);
$out = preg_replace_callback($pattern, array($this, '_callBack'), $buffer);
return $out;
}
/**
* Preg callback
*
* @param array $match
* @return string
*/
protected function _callBack(array $match)
{
// Split up into readable vars
list($full, $body) = $match;
// Parse <%=
if ($this->_isEcho($full)) {
return "<?php echo $body; ?>";
}
return "<?php $body; ?>";
}
/**
* Check if a string is an echo tag
*
* <%= %> style
*
* @param string $string
* @return boolean
*/
protected function _isEcho($string)
{
return (substr($string, 0, 3) === '<%=');
}
} | {'content_hash': 'fe890ef0f44bb74aeaf9799975327061', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 83, 'avg_line_length': 20.78082191780822, 'alnum_prop': 0.5036255767963085, 'repo_name': 'robinsk/zym', 'id': 'e1baaaa3513822e7a9534e73e0ad3e2aa5966806', 'size': '1877', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'library/Zym/View/Filter/AspTags.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '617'}, {'name': 'PHP', 'bytes': '1404140'}]} |
<?php
namespace League\Flysystem;
use League\Flysystem\Util\MimeType;
use LogicException;
class Util
{
/**
* Get normalized pathinfo.
*
* @param string $path
*
* @return array pathinfo
*/
public static function pathinfo($path)
{
$pathinfo = pathinfo($path) + compact('path');
$pathinfo['dirname'] = array_key_exists('dirname', $pathinfo)
? static::normalizeDirname($pathinfo['dirname']) : '';
return $pathinfo;
}
/**
* Normalize a dirname return value.
*
* @param string $dirname
*
* @return string normalized dirname
*/
public static function normalizeDirname($dirname)
{
return $dirname === '.' ? '' : $dirname;
}
/**
* Get a normalized dirname from a path.
*
* @param string $path
*
* @return string dirname
*/
public static function dirname($path)
{
return static::normalizeDirname(dirname($path));
}
/**
* Map result arrays.
*
* @param array $object
* @param array $map
*
* @return array mapped result
*/
public static function map(array $object, array $map)
{
$result = [];
foreach ($map as $from => $to) {
if ( ! isset($object[$from])) {
continue;
}
$result[$to] = $object[$from];
}
return $result;
}
/**
* Normalize path.
*
* @param string $path
*
* @throws LogicException
*
* @return string
*/
public static function normalizePath($path)
{
// Remove any kind of funky unicode whitespace
$normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
$normalized = static::normalizeRelativePath($normalized);
if (preg_match('#(^|/)\.{2}(/|$)#', $normalized)) {
throw new LogicException(
'Path is outside of the defined root, path: [' . $path . '], resolved: [' . $normalized . ']'
);
}
$normalized = preg_replace('#\\\{2,}#', '\\', trim($normalized, '\\'));
$normalized = preg_replace('#/{2,}#', '/', trim($normalized, '/'));
return $normalized;
}
/**
* Normalize relative directories in a path.
*
* @param string $path
*
* @return string
*/
public static function normalizeRelativePath($path)
{
// Path remove self referring paths ("/./").
$path = preg_replace('#/\.(?=/)|^\./|(/|^)\./?$#', '', $path);
// Regex for resolving relative paths
$regex = '#/*[^/\.]+/\.\.(/|$)#Uu';
while (preg_match($regex, $path)) {
$path = preg_replace($regex, '', $path);
}
return $path;
}
/**
* Normalize prefix.
*
* @param string $prefix
* @param string $separator
*
* @return string normalized path
*/
public static function normalizePrefix($prefix, $separator)
{
return rtrim($prefix, $separator) . $separator;
}
/**
* Get content size.
*
* @param string $contents
*
* @return int content size
*/
public static function contentSize($contents)
{
return defined('MB_OVERLOAD_STRING') ? mb_strlen($contents, '8bit') : strlen($contents);
}
/**
* Guess MIME Type based on the path of the file and it's content.
*
* @param string $path
* @param string|resource $content
*
* @return string|null MIME Type or NULL if no extension detected
*/
public static function guessMimeType($path, $content)
{
$mimeType = MimeType::detectByContent($content);
if ( ! (empty($mimeType) || in_array($mimeType, ['application/x-empty', 'text/plain', 'text/x-asm']))) {
return $mimeType;
}
return MimeType::detectByFilename($path);
}
/**
* Emulate directories.
*
* @param array $listing
*
* @return array listing with emulated directories
*/
public static function emulateDirectories(array $listing)
{
$directories = [];
$listedDirectories = [];
foreach ($listing as $object) {
list($directories, $listedDirectories) = static::emulateObjectDirectories(
$object,
$directories,
$listedDirectories
);
}
$directories = array_diff(array_unique($directories), array_unique($listedDirectories));
foreach ($directories as $directory) {
$listing[] = static::pathinfo($directory) + ['type' => 'dir'];
}
return $listing;
}
/**
* Ensure a Config instance.
*
* @param null|array|Config $config
*
* @return Config config instance
*
* @throw LogicException
*/
public static function ensureConfig($config)
{
if ($config === null) {
return new Config();
}
if ($config instanceof Config) {
return $config;
}
if (is_array($config)) {
return new Config($config);
}
throw new LogicException('A config should either be an array or a Flysystem\Config object.');
}
/**
* Rewind a stream.
*
* @param resource $resource
*/
public static function rewindStream($resource)
{
if (ftell($resource) !== 0 && static::isSeekableStream($resource)) {
rewind($resource);
}
}
public static function isSeekableStream($resource)
{
$metadata = stream_get_meta_data($resource);
return $metadata['seekable'];
}
/**
* Get the size of a stream.
*
* @param resource $resource
*
* @return int stream size
*/
public static function getStreamSize($resource)
{
$stat = fstat($resource);
return $stat['size'];
}
/**
* Emulate the directories of a single object.
*
* @param array $object
* @param array $directories
* @param array $listedDirectories
*
* @return array
*/
protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories)
{
if ($object['type'] === 'dir') {
$listedDirectories[] = $object['path'];
}
if (empty($object['dirname'])) {
return [$directories, $listedDirectories];
}
$parent = $object['dirname'];
while ( ! empty($parent) && ! in_array($parent, $directories)) {
$directories[] = $parent;
$parent = static::dirname($parent);
}
if (isset($object['type']) && $object['type'] === 'dir') {
$listedDirectories[] = $object['path'];
return [$directories, $listedDirectories];
}
return [$directories, $listedDirectories];
}
}
| {'content_hash': '623a3b13010bfc4e72e9b0bf042f10d0', 'timestamp': '', 'source': 'github', 'line_count': 288, 'max_line_length': 115, 'avg_line_length': 24.149305555555557, 'alnum_prop': 0.5276779295470885, 'repo_name': 'pqnhat89/notepad-editor', 'id': '3c23a59f94f3deccb13584bf3f125ea272d306df', 'size': '6955', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/league/flysystem/src/Util.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1106'}, {'name': 'CSS', 'bytes': '773550'}, {'name': 'HTML', 'bytes': '37195'}, {'name': 'JavaScript', 'bytes': '620404'}, {'name': 'PHP', 'bytes': '93641'}, {'name': 'Vue', 'bytes': '561'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '1040f54eb7e737a0b23501df625a5b93', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '036268d85d28f5cc6e3d1fd88a5fdb7d0e440c13', 'size': '173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Koeleria/Koeleria sordida/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package cromwell.engine.backend.jes.authentication
import cromwell.engine.WorkflowDescriptor
import cromwell.engine.backend.jes._
import cromwell.engine.io.gcs.GoogleCloudStorage
import cromwell.util.google.GoogleCredentialFactory
import spray.json.JsObject
/**
* Trait for JesConnection
*/
trait JesConnection {
def jesCromwellInterface: JesInterface
/**
* This method should try its best to provide a GCS connection setup with the user's credentials.
* In the case where it's not able to provide such a method, a default one can be provided instead.
*/
def jesUserConnection(workflow: WorkflowDescriptor): GoogleCloudStorage
}
object ProductionJesConnection {
import ProductionJesConfiguration._
// Only one instance of jesCromwellInterface is needed. It uses whichever authScheme has been set in the configuration.
lazy val jesCromwellInterface: JesInterface = {
val cromwellCredentials = GoogleCredentialFactory.fromCromwellAuthScheme
// .get to fail now, as we can't run on Jes without a Cromwell authenticated GCS interface
val gcsInterface = GoogleCloudStorage.cromwellAuthenticated.get
val genomicsInterface = GenomicsFactory(googleConf.appName, jesConf.endpointUrl, cromwellCredentials)
JesInterface(gcsInterface, genomicsInterface)
}
}
/**
* Trait for JesAuthentication
*/
trait JesAuthentication { self: JesConnection =>
def authenticateAsCromwell[A](f: JesInterface => A) = f(jesCromwellInterface)
/**
* Important note: Will default back to cromwell authentication if the configuration for user authentication has not been set or if the refreshToken has been supplied.
*/
def authenticateAsUser[A](workflow: WorkflowDescriptor)(f: GoogleCloudStorage => A) = f(jesUserConnection(workflow))
/**
* Generates a json containing auth information based on the parameters provided.
* @return a string representation of the json
*/
def generateAuthJson(authInformation: Option[JesAuthInformation]*) = {
authInformation.flatten map { _.toMap } match {
case Nil => None
case jsons =>
val authsValues = jsons.reduce(_ ++ _) mapValues JsObject.apply
Option(JsObject("auths" -> JsObject(authsValues)).prettyPrint)
}
}
}
trait ProductionJesAuthentication extends JesAuthentication with JesConnection {
override lazy val jesCromwellInterface = ProductionJesConnection.jesCromwellInterface
/* We re-use the same workflow-level interface for all calls here.
* We can .get safely because at WorkflowDescriptor instantiation time we make sure gcsInterface is defined if running on JES.
* TODO: remove the Option[...] through inheritance or implicits ?
*/
override def jesUserConnection(workflow: WorkflowDescriptor) = workflow.gcsInterface.get
}
| {'content_hash': '346937fc1930253b4ee2586f4bbe2dbc', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 169, 'avg_line_length': 39.68571428571428, 'alnum_prop': 0.7688984881209503, 'repo_name': 'dgtester/cromwell', 'id': '59c58d58d457b25101050c68ad3581ac4ae2a99c', 'size': '2778', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/main/scala/cromwell/engine/backend/jes/authentication/JesAuthentication.scala', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '6688'}, {'name': 'Java', 'bytes': '2582'}, {'name': 'Scala', 'bytes': '889007'}, {'name': 'Shell', 'bytes': '333'}]} |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['BoxCox'] , ['MovingMedian'] , ['Seasonal_WeekOfYear'] , ['LSTM'] ); | {'content_hash': 'c05cd865cbc2ad6d6768c8ac0e4ba54f', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 90, 'avg_line_length': 40.75, 'alnum_prop': 0.7177914110429447, 'repo_name': 'antoinecarme/pyaf', 'id': '03df8ff2e1a9d1968a40cf731260e0851afd298b', 'size': '163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/model_control/detailed/transf_BoxCox/model_control_one_enabled_BoxCox_MovingMedian_Seasonal_WeekOfYear_LSTM.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Makefile', 'bytes': '6773299'}, {'name': 'Procfile', 'bytes': '24'}, {'name': 'Python', 'bytes': '54209093'}, {'name': 'R', 'bytes': '807'}, {'name': 'Shell', 'bytes': '3619'}]} |
`blahb` is a python3 library for object-based image analysis that takes a pixel-centric approach to common spatial analysis tasks on a regular grid.
- (0) Motivation
- [1. Getting Started](1_intro.md)
- [2. Set Operations](2_setops.md)
- [3. Associated Data](3_data.md)
###### What `blahb` does:
* Represents N-dimensional indexes into an image and associated pixel data
* Makes use of `numpy` and `numba` for efficiency and compatibility
* Provides performant set operations, connected component labeling with arbitrary Neighborhoods, and some common fixed-grid spatial operations such a buffering.
###### What `blahb` doesn't do:
* Geographic transformations.
* Represent continuous coordinates
* Anything that isn't rectilinear pixels on a regular grid.
* Real-time image processing
###### When should you use `blahb`?
* If you have a sparse N-dimensional image, perhaps with associated data, on which you want to perform spatial image processing techniques.
* You already use `numba` and accelerate your code with `nopython=True`.
* Your images consist of chunks of a larger global grid.
* You do not know how large your domain will be at the beginning of your analysis.
###### How is this different than typical numpy/scipy image processing?
In typical `numpy` image processing we work with boolean images, a fixed
grid of `True` or `False`
```python
>>>img = np.array([[0,0,0,1,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,1,0,0,0],
[0,0,0,0,1]], dtype=bool)
```
This is an *implicit* representation of spatial data because we are representing points using a the convention that (0, 0) is the top-left-most pixel and the positions of our `True` values of interest can be computed by their offset relative to start pixel. When we do computations, such as [connected-component labeling](https://en.wikipedia.org/wiki/Connected-component_labeling), we operate in this *implicit* realm.
An alternative, the approach that `blahb` takes, is to represent our `True` pixels *explicitly* by the coordinates that they take. This is easy enough to do in `numpy`:
```python
>>>y, x = np.where(img)
>>>a = set(zip(*(y, x)))
>>>a
{(0, 3), (3, 1), (4, 4)}
```
In other words, the location of `True` values is the set {(0, 3), (3, 1), (4, 4)}
Why is this nicer? Conceptually, it is simpler to think about positive space, about pixels that we *have*. However, there are limited existing tools for performing computations on this representation. This is a gap that `blahb` aims to fill.
*As an added bonus, we have injected a measure of optimism into our workflow by dropping all of the negative baggage of the implicit representation.*
Consider another image:
```python
>>>img2 = np.array([[0,0,0,0],
[0,1,0,0],
[0,0,0,0],
[0,0,0,1],
[0,0,0,0]], dtype=bool)
```
but instead of (0, 0), the top pixel now represents (2, 3). `True` pixels in this new image are represented by the set `b`:
```python
>>>y2, x2 = np.where(img2)
>>>y_offset, x_offset = 2, 3
>>>b = set(zip(*(y2 + y_offset, x2 + x_offset)))
>>>b
{(3, 4), (5, 6)}
```
When we use the *explicit* form, we can perform operations like "*find the union of `True` pixels in both images*" quite easily:
```python
>>>c = a | b
>>>c
{(0, 3), (3, 1), (3, 4), (4, 4), (5, 6)}
```
For the *implicit* spatial representation, this is more involved:
```python
>>>result_shape = img2.shape[0] + y_offset, img2.shape[1] + x_offset
>>>big_img = np.zeros(result_shape, dtype=bool)
>>>big_img[:img.shape[0], :img.shape[1]] = img
>>>big_img[y_offset:y_offset + img2.shape[0],
x_offset:x_offset + img2.shape[1]] |= img2
>>>set(zip(*np.where(big_img))) # We get the same result
{(0, 3), (3, 1), (3, 4), (4, 4), (5, 6)}
```
Not only is there more code to write, there is more code to reason about; the potential for errors increases as we move into higher dimensions.
The aim of `blahb` is to provide:
- A `numba.jitclass` similar to the above set-of-coordinate tuples that scales well to real image sizes (i.e. tens of millions of pixels) with an arbitrary number of dimensions (such as an image stack).
- Operators like the above `|` for efficiently manipulating comparing and combining these sets.
- Effortless integration with both `numpy` and `numba.njit` nopython functions when you want to write your own extensions.
---
- (0) Motivation
- [1. Getting Started](1_intro.md)
- [2. Set Operations](2_setops.md)
- [3. Associated Data](3_data.md) | {'content_hash': '398c69b1ff0521f784ea2cec1843f743', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 419, 'avg_line_length': 47.83157894736842, 'alnum_prop': 0.6813380281690141, 'repo_name': 'mvsaha/blahb', 'id': '54a7fca306a35c8c4d4815ecfdcbf8d681489707', 'size': '4544', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/index.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '286601'}]} |
package de.hu_berlin.german.korpling.annis.kickstarter;
import annis.administration.CorpusAdministration;
import java.awt.Frame;
import java.io.File;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.slf4j.LoggerFactory;
/**
*
* @author thomas
*/
public class InitDialog extends javax.swing.JDialog
{
private static final org.slf4j.Logger log = LoggerFactory.getLogger(
InitDialog.class);
private CorpusAdministration corpusAdministration;
private SwingWorker<String, Void> initWorker;
private Frame parentFrame;
private class InitDialogWorker extends SwingWorker<String, Void>
implements Serializable
{
private InitDialog parent;
private List<Map<String, Object>> corpora;
public InitDialogWorker(InitDialog parent, List<Map<String, Object>> corpora)
{
this.parent = parent;
this.corpora = corpora;
}
@Override
protected String doInBackground() throws Exception
{
try
{
corpusAdministration.initializeDatabase("localhost", "5432",
"anniskickstart",
"anniskickstart", "annisKickstartPassword", "postgres",
txtAdminUsername.getText(), new String(txtAdminPassword.getPassword()),
false);
return "";
}
catch (Exception ex)
{
parent.setVisible(false);
ExceptionDialog dlg = new ExceptionDialog(parent, ex);
dlg.setVisible(true);
}
return "ERROR";
}
@Override
protected void done()
{
pbInit.setIndeterminate(false);
btOk.setEnabled(true);
btCancel.setEnabled(true);
try
{
if ("".equals(this.get()))
{
pbInit.setValue(100);
if (corpora != null && corpora.size() > 0)
{
setVisible(false);
// migrate corpora
ImportDialog importDlg = new ImportDialog(parentFrame, true,
corpusAdministration, corpora);
importDlg.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "Database initialized.", "INFO",
JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
}
}
else
{
pbInit.setValue(0);
}
}
catch (InterruptedException ex)
{
log.error(null, ex);
}
catch (ExecutionException ex)
{
log.error(null, ex);
}
}
}
/**
* Creates new form InitDialog
*/
public InitDialog(java.awt.Frame parent, boolean modal,
final CorpusAdministration corpusAdministration)
{
super(parent, modal);
this.parentFrame = parent;
initComponents();
getRootPane().setDefaultButton(btOk);
this.corpusAdministration = corpusAdministration;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
fileChooser = new javax.swing.JFileChooser();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
btOk = new javax.swing.JButton();
btCancel = new javax.swing.JButton();
txtAdminUsername = new javax.swing.JTextField();
txtAdminPassword = new javax.swing.JPasswordField();
pbInit = new javax.swing.JProgressBar();
cbMigrate = new javax.swing.JCheckBox();
fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Init - ANNIS Kickstarter");
setLocationByPlatform(true);
jLabel1.setText("Postgres-Admin username:");
jLabel2.setText("Postgres-Admin password:");
btOk.setMnemonic('o');
btOk.setText("Ok");
btOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btOkActionPerformed(evt);
}
});
btCancel.setMnemonic('c');
btCancel.setText("Cancel");
btCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btCancelActionPerformed(evt);
}
});
txtAdminUsername.setText("postgres");
cbMigrate.setSelected(true);
cbMigrate.setText("migrate already imported corpora (will take same time as re-import)");
cbMigrate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbMigrateActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pbInit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtAdminUsername))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(txtAdminPassword))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btOk, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(cbMigrate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtAdminUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtAdminPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cbMigrate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 4, Short.MAX_VALUE)
.addComponent(pbInit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btOk)
.addComponent(btCancel))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btCancelActionPerformed
{//GEN-HEADEREND:event_btCancelActionPerformed
setVisible(false);
}//GEN-LAST:event_btCancelActionPerformed
private void checkCorpusSourcePathExists(Map<String, Object> corpus)
{
if (!corpus.containsKey("source_path"))
{
// show dialog to the user
int result = JOptionPane.showConfirmDialog(this,
"No source directory given for "
+ "corpus \"" + corpus.get("name")
+ "\". Do you want to manually select a directory?",
"Cannot find \"" + corpus.get("name") + "\"",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
{
// show directory chooser
int fileChooseResult = fileChooser.showDialog(this, "Select");
if (fileChooseResult == JFileChooser.APPROVE_OPTION)
{
corpus.put("source_path", fileChooser.getSelectedFile().
getAbsolutePath());
}
}
}
}
private void btOkActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btOkActionPerformed
{//GEN-HEADEREND:event_btOkActionPerformed
pbInit.setIndeterminate(true);
btOk.setEnabled(false);
btCancel.setEnabled(false);
// collect all necessary information for migration
List<Map<String, Object>> existingCorpora = new LinkedList<Map<String, Object>>();
if (cbMigrate.isSelected())
{
// catch all existing corpora
try
{
existingCorpora = corpusAdministration.listCorpusStats();
}
catch(Exception ex)
{
log.warn("Could not get existing corpus list for migration, migrating "
+ "the corpora will be disabled.", ex);
JOptionPane.showMessageDialog(parentFrame,
"Could not get existing corpus list for migration, migrating "
+ "the corpora will be disabled.");
}
// check if any of these corpora needs more information from the user
for (Map<String, Object> corpus : existingCorpora)
{
checkCorpusSourcePathExists(corpus);
}
}
initWorker = new InitDialogWorker(this, existingCorpora);
// do the actual work
initWorker.execute();
}//GEN-LAST:event_btOkActionPerformed
private void cbMigrateActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbMigrateActionPerformed
{//GEN-HEADEREND:event_cbMigrateActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbMigrateActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btCancel;
private javax.swing.JButton btOk;
private javax.swing.JCheckBox cbMigrate;
private javax.swing.JFileChooser fileChooser;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JProgressBar pbInit;
private javax.swing.JPasswordField txtAdminPassword;
private javax.swing.JTextField txtAdminUsername;
// End of variables declaration//GEN-END:variables
}
| {'content_hash': '24aeeb68a6e04c66d71bdd30cec65e8e', 'timestamp': '', 'source': 'github', 'line_count': 317, 'max_line_length': 170, 'avg_line_length': 36.94637223974763, 'alnum_prop': 0.650785519125683, 'repo_name': 'thomaskrause/ANNIS', 'id': '349c6dd49a04c2530d1001919dc72192cab52819', 'size': '12337', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'annis-kickstarter/src/main/java/de/hu_berlin/german/korpling/annis/kickstarter/InitDialog.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '1491'}, {'name': 'CSS', 'bytes': '64790'}, {'name': 'Java', 'bytes': '2121465'}, {'name': 'JavaScript', 'bytes': '292049'}, {'name': 'PHP', 'bytes': '771685'}, {'name': 'Python', 'bytes': '920'}, {'name': 'Shell', 'bytes': '6468'}]} |
<?php
/*
* --------------------------------------------------------------------
* LOAD COMPOSER
* --------------------------------------------------------------------
*
*/
if (file_exists('./itau/vendor/autoload.php'))
{
include_once './itau/vendor/autoload.php';
}
if( ! ini_get('date.timezone') )
{
date_default_timezone_set('GMT');
}
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2016, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* NOTE: If you change these, also change the error_reporting() code below
*/
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
switch (ENVIRONMENT)
{
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>='))
{
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
else
{
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
/*
*---------------------------------------------------------------
* SYSTEM DIRECTORY NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" directory.
* Set the path if it is not in the same directory as this file.
*/
$system_path = 'system';
/*
*---------------------------------------------------------------
* APPLICATION DIRECTORY NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "application"
* directory than the default one you can set its name here. The directory
* can also be renamed or relocated anywhere on your server. If you do,
* use an absolute (full) server path.
* For more info please see the user guide:
*
* https://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*/
$application_folder = 'application';
/*
*---------------------------------------------------------------
* VIEW DIRECTORY NAME
*---------------------------------------------------------------
*
* If you want to move the view directory out of the application
* directory, set the path to it here. The directory can be renamed
* and relocated anywhere on your server. If blank, it will default
* to the standard location inside your application directory.
* If you do move this, use an absolute (full) server path.
*
* NO TRAILING SLASH!
*/
$view_folder = '';
/*
* --------------------------------------------------------------------
* DEFAULT CONTROLLER
* --------------------------------------------------------------------
*
* Normally you will set your default controller in the routes.php file.
* You can, however, force a custom routing by hard-coding a
* specific controller class/function here. For most applications, you
* WILL NOT set your routing here, but it's an option for those
* special instances where you might want to override the standard
* routing in a specific front controller that shares a common CI installation.
*
* IMPORTANT: If you set the routing here, NO OTHER controller will be
* callable. In essence, this preference limits your application to ONE
* specific controller. Leave the function name blank if you need
* to call functions dynamically via the URI.
*
* Un-comment the $routing array below to use this feature
*/
// The directory name, relative to the "controllers" directory. Leave blank
// if your controller is not in a sub-directory within the "controllers" one
// $routing['directory'] = '';
// The controller class file name. Example: mycontroller
// $routing['controller'] = '';
// The controller function you wish to be called.
// $routing['function'] = '';
/*
* -------------------------------------------------------------------
* CUSTOM CONFIG VALUES
* -------------------------------------------------------------------
*
* The $assign_to_config array below will be passed dynamically to the
* config class when initialized. This allows you to set custom config
* items or override any default config values found in the config.php file.
* This can be handy as it permits you to share one application between
* multiple front controller files, with each file containing different
* config values.
*
* Un-comment the $assign_to_config array below to use this feature
*/
// $assign_to_config['name_of_config_item'] = 'value of config item';
// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------
/*
* ---------------------------------------------------------------
* Resolve the system path for increased reliability
* ---------------------------------------------------------------
*/
// Set the current directory correctly for CLI requests
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (($_temp = realpath($system_path)) !== FALSE)
{
$system_path = $_temp.DIRECTORY_SEPARATOR;
}
else
{
// Ensure there's a trailing slash
$system_path = strtr(
rtrim($system_path, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
).DIRECTORY_SEPARATOR;
}
// Is the system path correct?
if ( ! is_dir($system_path))
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
exit(3); // EXIT_CONFIG
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// Path to the system directory
define('BASEPATH', $system_path);
// Path to the front controller (this file) directory
define('FCPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
// Name of the "system" directory
define('SYSDIR', basename(BASEPATH));
// The path to the "application" directory
if (is_dir($application_folder))
{
if (($_temp = realpath($application_folder)) !== FALSE)
{
$application_folder = $_temp;
}
else
{
$application_folder = strtr(
rtrim($application_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
}
elseif (is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR))
{
$application_folder = BASEPATH.strtr(
trim($application_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
else
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
define('APPPATH', $application_folder.DIRECTORY_SEPARATOR);
// The path to the "views" directory
if ( ! isset($view_folder[0]) && is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.'views';
}
elseif (is_dir($view_folder))
{
if (($_temp = realpath($view_folder)) !== FALSE)
{
$view_folder = $_temp;
}
else
{
$view_folder = strtr(
rtrim($view_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
}
elseif (is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.strtr(
trim($view_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
else
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
define('VIEWPATH', $view_folder.DIRECTORY_SEPARATOR);
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*/
require_once BASEPATH.'core/CodeIgniter.php';
| {'content_hash': 'e04a202d3d299ed6e6d5e082f2729f8a', 'timestamp': '', 'source': 'github', 'line_count': 333, 'max_line_length': 158, 'avg_line_length': 31.834834834834833, 'alnum_prop': 0.5875860767852089, 'repo_name': 'rcardoso1986/Sysimob', 'id': '7b3167f06552be6e80460e3b636db77d3cac9b8a', 'size': '10601', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '401'}, {'name': 'CSS', 'bytes': '69354'}, {'name': 'HTML', 'bytes': '8235618'}, {'name': 'JavaScript', 'bytes': '319932'}, {'name': 'PHP', 'bytes': '3272790'}, {'name': 'Ruby', 'bytes': '2499'}]} |
/**
* Created with JetBrains PhpStorm.
* User: kevin
* Date: 11/3/13
* Time: 7:13 PM
* To change this template use File | Settings | File Templates.
*/
var acl = acl||{};
acl.user = acl.user||{};
acl.user.resource = acl.user.resource||{};
acl.user.resource.search = {
init: function(){
user.search.onResultsRendered(this.decorateUserSearchResult);
},
decorateUserSearchResult: function(resultTable){
resultTable.find('tr').each(function(){
var id = $(this).find('.user-id').text();
var name = $(this).find('.user-name').text();
var link = '<a href="'+basePath+'/acl/user-resource/edit/'+id+'">'+name+'</a>';
$(this).find('.user-name').html(link);
});
}
};
$(function() {
acl.user.resource.search.init();
});
| {'content_hash': '3722c1eefc6c008386af279f70d1c8d0', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 91, 'avg_line_length': 27.896551724137932, 'alnum_prop': 0.5797280593325093, 'repo_name': 'kkucera/rentalmgr', 'id': '10f1851a280a797d307f3a45e3e442d8f2ca9086', 'size': '809', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/js/acl/acl.user.resource.search.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '15982'}, {'name': 'CSS', 'bytes': '152410'}, {'name': 'JavaScript', 'bytes': '2117950'}, {'name': 'PHP', 'bytes': '398630'}, {'name': 'Perl', 'bytes': '711'}, {'name': 'Shell', 'bytes': '7411'}]} |
import {createCustomEvent} from '../../../src/event-helper';
import {dev, user} from '../../../src/log';
import {dict, hasOwn} from '../../../src/utils/object';
import {
escapeCssSelectorIdent,
scopedQuerySelector,
waitForBodyPromise,
waitForChild,
} from '../../../src/dom';
import {installServiceInEmbedScope} from '../../../src/service';
import {toArray} from '../../../src/types';
/**
* CSS class used to deactivate animations.
* @const {string}
*/
export const ANIMATIONS_DISABLED_CLASS = 'i-amphtml-gwd-animation-disabled';
/**
* CSS class name used to identify GWD page wrapper elements.
* @const {string}
*/
export const GWD_PAGE_WRAPPER_CLASS = 'gwd-page-wrapper';
/**
* GWD playback control CSS classes.
* @enum {string}
*/
export const PlaybackCssClass = {
PAUSE: 'gwd-pause-animation',
PLAY: 'gwd-play-animation',
};
/**
* The attribute used to store the name of an element's currently-active label
* animation.
* @const {string}
*/
export const CURRENT_LABEL_ANIMATION_ATTR = 'data-gwd-label-animation';
/**
* The attribute used to store the event name on a GWD event element.
* @const {string}
*/
const EVENT_NAME_ATTR = 'data-event-name';
/**
* Event dispatched when a GWD event `animationend` is captured.
* @const {string}
*/
export const GWD_TIMELINE_EVENT = 'gwd.timelineEvent';
/**
* Standard and vendor-prefixed versions of the `animationend` event for which
* listeners are added.
* @const {!Array<string>}
*/
const VENDOR_ANIMATIONEND_EVENTS = ['animationend', 'webkitAnimationEnd'];
/**
* When executing gotoAndPause, the amount of time to wait (in milliseconds)
* before triggering pause.
* @const {number}
*/
const GOTO_AND_PAUSE_DELAY = 40;
/**
* Property name used to store pending goto counters on an element.
* @const {string}
* Exported for test only.
*/
export const GOTO_COUNTER_PROP = '__AMP_GWD_GOTO_COUNTERS__';
/**
* The GWD runtime service ID (arbitrary string).
* @const {string}
*/
export const GWD_SERVICE_NAME = 'gwd';
/**
* Uppercase identifier for log statements (arbitrary string).
* @const {string}
*/
const LOG_ID = 'GWD';
/**
* @param {!Element} receiver
* @param {string} counterName
* @return {number} The current GWD goto counter value for the given receiver
* element and goto event counter name.
* @private
*/
function getCounter(receiver, counterName) {
if (receiver[GOTO_COUNTER_PROP] &&
hasOwn(receiver[GOTO_COUNTER_PROP], counterName)) {
return receiver[GOTO_COUNTER_PROP][counterName];
}
return 0;
}
/**
* @param {!Element} receiver
* @param {string} counterName
* @param {number} counterValue
* @private
*/
function setCounter(receiver, counterName, counterValue) {
// Ensure a goto counters map with an empty counter is initialized for the
// given element and goto event name.
if (!receiver[GOTO_COUNTER_PROP]) {
receiver[GOTO_COUNTER_PROP] = {};
}
if (!hasOwn(receiver[GOTO_COUNTER_PROP], counterName)) {
receiver[GOTO_COUNTER_PROP][counterName] = 0;
}
receiver[GOTO_COUNTER_PROP][counterName] = counterValue;
}
/**
* AMP GWD animation runtime service.
* @implements {../../../src/service.Disposable}
* @implements {../../../src/service.EmbeddableService}
*/
export class AmpGwdRuntimeService {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc An AMP document
* with GWD content in which to install the animation runtime controller.
* @param {!Window=} opt_win If in a FIE, the FIE window in which to install
* the service.
*/
constructor(ampdoc, opt_win) {
/** @const @private {!../../../src/service/ampdoc-impl.AmpDoc} */
this.ampdoc_ = ampdoc;
/**
* The window containing the GWD ad document. This will differ from the
* provided AmpDoc's window when in FIE.
* @const @private {!Window}
*/
this.win_ = opt_win || ampdoc.win;
/**
* The GWD ad document root. This will differ from the top-level AmpDoc's
* root when in FIE.
* @const @private {!Document}
*/
this.doc_ = this.win_.document;
/** @const @private {!Function} */
this.boundOnAnimationEndEvent_ = this.onAnimationEndEvent_.bind(this);
// Initialize once the body and DOM is ready.
const docReadyPromise =
opt_win ? waitForBodyPromise(this.doc_) : ampdoc.whenBodyAvailable();
docReadyPromise.then(() => {
// If the page deck is not yet in the DOM, wait until it is. The page deck
// must be present in the body before the runtime can be initialized, as
// it must activate animations on the first page. It's not clear whether
// in production this is a realistic scenario (though this occurs in
// tests), but this also avoids performing initialization on the top-level
// document on which the service is first (unnecessarily) installed when
// in a FIE.
const body = dev().assertElement(this.doc_.body);
waitForChild(
body,
() => !!body.querySelector(
`.${escapeCssSelectorIdent(GWD_PAGE_WRAPPER_CLASS)}`),
this.initialize_.bind(this));
});
}
/** @override */
adoptEmbedWindow(embedWin) {
installServiceInEmbedScope(
embedWin,
GWD_SERVICE_NAME,
new AmpGwdRuntimeService(this.ampdoc_, embedWin));
}
/**
* Initializes the runtime. Attaches `animationend` event listeners for
* handling timeline events, and activates animations on the first page.
* @private
*/
initialize_() {
// TODO(#7846): The GWD animation runtime should start out disabled, but
// leaving it enabled for now as the main runtime is not yet integrated to
// enable it. When it does so, uncomment the below code (also see
// associated test).
/*
// Initially disable all animations (AMP runtime will enable when ready).
this.setEnabled(false);
*/
// Begin listening for timeline events (GWD event element `animationend`).
this.listenForAnimationEnd_();
// Permit animations to play on the first GWD page.
this.setCurrentPage(0);
}
/**
* Enables or disables all animations in this document. When disabled, all
* animations are turned off with a CSS `animation: none` override. Actions
* like play or gotoAndPlay may be invoked while in the disabled state, though
* they will have no immediate effect; playback changes will be reflected when
* animations are re-enabled.
* @param {boolean} enable True to enable, false to disable.
*/
setEnabled(enable) {
this.doc_.body.classList.toggle(ANIMATIONS_DISABLED_CLASS, !enable);
}
/**
* Handles a page switch by resetting animations and goto counters on the
* currently-active page and starting animations on the new page.
* @param {number} index The index of the newly-active page (a slide in the
* pagedeck amp-carousel).
*/
setCurrentPage(index) {
const gwdPages = this.doc_.body.querySelectorAll(
`.${escapeCssSelectorIdent(GWD_PAGE_WRAPPER_CLASS)}`);
if (gwdPages.length == 0) {
user().warn(LOG_ID,
'Could not set current page. No pages were found in the document.');
return;
}
// Deactivate the outgoing current page, if there is one.
// TODO(sklobovskaya): Decide if it's worth just storing the index.
const activePageSelector =
`.${escapeCssSelectorIdent(GWD_PAGE_WRAPPER_CLASS)}.${
escapeCssSelectorIdent(PlaybackCssClass.PLAY)
}`;
const currentPageEl =
scopedQuerySelector(this.doc_.body, activePageSelector);
if (currentPageEl) {
this.deactivatePage_(currentPageEl);
}
// Activate animations on the new current page.
const newPageEl = gwdPages[index];
if (newPageEl) {
this.activatePage_(newPageEl);
} else {
user().error(LOG_ID, 'Could not find page with index ' + index + '.');
}
}
/**
* Sets a page as the current active page by enabling animations on it.
* Animations are prevented from running on inactive pages.
* @param {!Element} pageEl
* @private
*/
activatePage_(pageEl) {
pageEl.classList.add(PlaybackCssClass.PLAY);
}
/**
* Sets a page inactive by disabling all animations and resetting all
* animation state (such as goto counters) on all elements within the page.
* @param {!Element} pageEl
* @private
*/
deactivatePage_(pageEl) {
// Cancel and disable all animations on the page.
pageEl.classList.remove(PlaybackCssClass.PLAY);
// Reset other animation state on the page and all descendants.
[pageEl]
.concat(toArray(pageEl.querySelectorAll('*')))
.forEach(el => this.resetAnimatedElement_(el));
}
/**
* Resets all transient GWD animation state on an animated element associated
* with a page (either a descendant of the page or the page element itself).
* The page elements themselves have an additional class which controls
* whether any animations may play on the page (PlaybackCssClass.PLAY); this
* class is toggled separately in activatePage_ and deactivatePage_.
* @param {!Element} element A descendant of a page or a page element.
* @private
*/
resetAnimatedElement_(element) {
// Reset animation-play-state for animations which have been paused.
element.classList.remove(PlaybackCssClass.PAUSE);
// Cancel any active label animations in the page. The main non-label
// animations will be automatically cancelled when the play class is
// removed above, but because goto animations are activated with a special
// class, the class must be removed manually.
if (element.hasAttribute(CURRENT_LABEL_ANIMATION_ATTR)) {
const activeGotoAnimation =
element.getAttribute(CURRENT_LABEL_ANIMATION_ATTR);
element.classList.remove(activeGotoAnimation);
element.removeAttribute(CURRENT_LABEL_ANIMATION_ATTR);
}
// Clear all gotoAndPlayNTimes counters.
delete element[GOTO_COUNTER_PROP];
}
/**
* The play action.
* @param {string} id Receiver id.
*/
play(id) {
const receiver = this.getReceiver(id);
if (!receiver) {
return;
}
receiver.classList.remove(PlaybackCssClass.PAUSE);
}
/**
* The pause action.
* @param {string} id Receiver id.
*/
pause(id) {
const receiver = this.getReceiver(id);
if (!receiver) {
return;
}
receiver.classList.add(PlaybackCssClass.PAUSE);
}
/**
* The togglePlay action.
* @param {string} id Receiver id.
*/
togglePlay(id) {
const receiver = this.getReceiver(id);
if (!receiver) {
return;
}
receiver.classList.toggle(PlaybackCssClass.PAUSE);
}
/**
* The gotoAndPlay action.
* @param {string} id Receiver id.
* @param {string} label The name of the label animation to go to.
*/
gotoAndPlay(id, label) {
const receiver = this.getReceiver(id);
if (!receiver) {
return;
}
this.playLabelAnimation_(receiver, label);
}
/**
* The gotoAndPause action. A gotoAndPause is a gotoAndPlay followed by an
* (almost) immediate pause.
* @param {string} id Receiver id.
* @param {string} label The name of the label animation to go to.
*/
gotoAndPause(id, label) {
const receiver = this.getReceiver(id);
if (!receiver) {
return;
}
// Switch to the label animation.
this.playLabelAnimation_(receiver, label);
// Pause playback. The pause must be triggered after a delay as a workaround
// for a Safari bug that prevents pausing animations from working.
this.win_.setTimeout(() => {
this.pause(id);
}, GOTO_AND_PAUSE_DELAY);
}
/**
* The gotoAndPlayNTimes action.
* @param {string} id Receiver id.
* @param {string} label The name of the label animation to go to.
* @param {number} maxCount The number of times this timeline event should
* trigger gotoAndPlay.
* @param {string} eventName The source timeline event name, used to enforce
* that gotoAndPlay is triggered a maximum of N times for this event.
*/
gotoAndPlayNTimes(id, label, maxCount, eventName) {
if (maxCount <= 0) {
user().error(LOG_ID, `Invalid maxCount parameter: ${maxCount}`);
return;
}
if (!eventName) {
user().error(LOG_ID, 'Event name required but not specified.');
return;
}
const receiver = this.getReceiver(id);
if (!receiver) {
return;
}
// Invoke gotoAndPlay up to the requested number of times.
const counterName = `${eventName}_${label}`;
const currentCount = getCounter(receiver, counterName);
if (currentCount < maxCount) {
this.playLabelAnimation_(receiver, label);
setCounter(receiver, counterName, currentCount + 1);
}
}
/**
* Returns the element identified by a receiver id if it exists in the
* invocation origin document and has a classList. If not found, returns null.
* @param {string} id The receiver id.
* @return {?Element}
*/
getReceiver(id) {
if (id == 'document.body') {
return this.doc_.body;
}
// Try to locate the receiver by id in the DOM.
// TODO(sklobovskaya): When support for groups is added, this lookup will
// need to use GwdIds.
const receiver = this.doc_.getElementById(id);
// Check that a valid element was found.
if (receiver && receiver.classList) {
return receiver;
} else {
user().error(LOG_ID, `Could not get receiver with id ${id}.`);
return null;
}
}
/**
* Switches an element's current animation to a label animation.
* This is a core gotoAndPlay routine used in all goto* actions.
* @param {!Element} receiver
* @param {string} label
* @private
*/
playLabelAnimation_(receiver, label) {
// Unpause playback.
receiver.classList.remove(PlaybackCssClass.PAUSE);
// If another goto animation is currently active on this element, stop it.
const currentLabel =
receiver.getAttribute(CURRENT_LABEL_ANIMATION_ATTR);
if (currentLabel) {
receiver.classList.remove(currentLabel);
receiver.removeAttribute(CURRENT_LABEL_ANIMATION_ATTR);
}
// A forced reflow is needed if removing and readding the same class so
// the animation is restarted.
if (currentLabel == label) {
reflow(receiver);
}
// Add the label animation class and record this label as this element's
// current animation.
receiver.classList.add(label);
receiver.setAttribute(CURRENT_LABEL_ANIMATION_ATTR, label);
}
/**
* Handles GWD event `animationend` events, which signal that a timeline event
* marker has been reached. If the event originated from a GWD event element,
* extracts its event name and dispatches a custom event.
* @param {!Event} event An `animationend` event.
* @private
*/
onAnimationEndEvent_(event) {
const userEventName = event.target.getAttribute(EVENT_NAME_ATTR);
if (!userEventName) {
// No GWD event name could be extracted, usually just because the event is
// from some other animation. Just ignore it.
return;
}
const detail = dict({
'eventName': userEventName,
'sourceEvent': event,
});
const timelineEvent =
createCustomEvent(this.win_, GWD_TIMELINE_EVENT, detail);
this.doc_.dispatchEvent(timelineEvent);
}
/**
* @private
*/
listenForAnimationEnd_() {
for (let i = 0; i < VENDOR_ANIMATIONEND_EVENTS.length; i++) {
this.doc_.body.addEventListener(
VENDOR_ANIMATIONEND_EVENTS[i], this.boundOnAnimationEndEvent_, true);
}
}
/**
* @private
*/
unlistenForAnimationEnd_() {
for (let i = 0; i < VENDOR_ANIMATIONEND_EVENTS.length; i++) {
this.doc_.body.removeEventListener(
VENDOR_ANIMATIONEND_EVENTS[i], this.boundOnAnimationEndEvent_, true);
}
}
/** @override */
dispose() {
this.unlistenForAnimationEnd_();
}
}
/**
* Utility function which triggers layout on the element. This is necessary
* to invoke when reapplying the same label animation class so the animation
* restarts.
* @param {!Element} element
*/
function reflow(element) {
// exporting global to trick Closure into thinking this function has side
// effects.
const globalRef = '__AMP_GWD_TEMP';
// Reading `offsetWidth` is what actually causes reflow.
self[globalRef] = element./*OK*/offsetWidth;
delete self[globalRef];
}
| {'content_hash': 'ea854aed3700fb59c2af26c0badbc449', 'timestamp': '', 'source': 'github', 'line_count': 546, 'max_line_length': 80, 'avg_line_length': 30.155677655677657, 'alnum_prop': 0.6655936835712116, 'repo_name': 'koshka/amphtml', 'id': '76218e23de30486a4e11861e3d3e4e27bcd4e10c', 'size': '17092', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'extensions/amp-gwd-animation/0.1/amp-gwd-animation-impl.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '372049'}, {'name': 'Go', 'bytes': '7459'}, {'name': 'HTML', 'bytes': '1484567'}, {'name': 'Java', 'bytes': '37149'}, {'name': 'JavaScript', 'bytes': '13017432'}, {'name': 'Python', 'bytes': '72953'}, {'name': 'Shell', 'bytes': '15122'}, {'name': 'Yacc', 'bytes': '22627'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta content="text/html; charset=iso-8859-1" http-equiv="content-type">
<title>Stochastic depression analysis</title>
<link rel="stylesheet" type="text/css" href="Help.css">
</head>
<body>
<h1>Stochastic depression analysis</h1>
<p>This tool can be used to map topographic depressions in a digital
elevation model (DEM), taking into account the uncertainty in
depression shape resulting from DEM error. The tool uses a stochastic
simulation approach (i.e. Monte Carlo method) to map depressions. It
is a re-implementation of the algorithm described by Lindsay and
Creed (2006), originally appearing in the Terrain Analysis System
(TAS) software. Whitebox's stochastic depression analysis tool
contains several improvements compared to the earlier TAS algorithm.
</p>
<p>The Whitebox algorithm differs in the way that each realization, and
in particular the error fields, are created. It uses a
<a href="TurningBands.html">turning bands</a> technique to create
error fields. The turning bands method is used to ensure that the
error fields have the desired spatial characteristics (e.g.
autocorrelation and range) and <a href="HistogramMatching.html">
Histogram Matching</a> is used to ensure they have the
appropriate statistical distribution.</p>
<p>By using histogram matching, the modelled DEM error can follow any
desirable statistical distribution. For example, it is commonly the
case that error within a DEM is more peaked than would be described
by a Guassian (normal) distribution. The user specifies the shape of
the error distribution by inputing a histogram. This is simply a
text file with two columns, the first is error value (in the same
units as the z-units of the DEM) and the second is the frequency of
occurrence (for additional information see
<a href="HistogramMatching.html"><b><i>Histogram Matching</i></b></a>).
This can be generated in a spreadsheet for theoretical
distributions (e.g. if the only error information that is available
is an RMSE value derived from the DEM's metadata, then it is
reasonable to assume a Gaussian distribution and to create the
appropriate histogram using the Gaussian probability function in a
spreadsheet). The preferred method for generating the input error
histogram, however, is to use ground control points (GCPs). If
several GCPs are available, it is possible to derive an empirical
error distribution form the data, again using a spreadsheet to plot
the frequency distribution.</p>
<p>The added benefit of having GCPs is that it these same data can also
be used calculate the range, which is a measure of the correlation
length within the error fields. This value must be specified, in
the same units as the DEM x-y units. If GCPs are available, the range
can be derived from the variogram. In this way, it is possible to
ensure that each DEM realization in the simulation has the appropriate
spatial and statistical error properties.</p>
<p>The tool effectively creates a user specified number of DEM
realizations, i.e. multiple equiprobable models of the topography
given the known error characteristics. Each realization is created
by adding a unique error field to the original DEM. The topographic
depressions within the DEM realization are then mapped by differencing
a depression-filled version of the realization from the non-depression
filled realization. Depressions are filled using the highly efficient
<a href="FillDepressions.html">Wang and Liu (2006) depression filling</a>
algorithm. The use of this algorithm does limit the application of
this tool to DEMs that fit in memory. With each iteration, grid cells
that are affected by the depression filling process are flagged and
entered into a cumulative grid. In this way, the probability of a
grid cell belonging to a depression feature (<i>p<sub>dep</sub></i>),
given the uncertainty in the DEM, can be mapped. The simulation will
continue until the user-specified number of iterations has been
reached. This stochastic analysis has been found to provide
accurate maps of depressions (or wetlands, in some landscapes) even
with moderate resolution DEM data. The accuracy of the results will
depend, however, on the specific DEM data and the landscape
characteristics.</p>
<h2 class="SeeAlso">See Also:</h2>
<ul>
<li><a href="FillDepressions.html">Fill Depressions</a></li>
<li><a href="TurningBands.html">Turning Bands Simulation</a></li>
<li><a href="HistogramMatching.html">Histogram Matching</a></li>
</ul>
<h2 class="SeeAlso">Credits:</h2>
<ul>
<li>John Lindsay and Beau Ahrens (2012) email: [email protected]</li>
</ul>
<h2 class="SeeAlso">Scripting:</h2>
<p>The following is an example of a Python script that uses this tool:</p>
<p style="background-color: rgb(240,240,240)">
<code>
wd = pluginHost.getWorkingDirectory() <br>
inputFile = wd + "input.dep" <br>
outputFile = wd + "output.dep" <br>
histogramFile = wd + "histo.txt" <br>
range = "265.0" <br>
numIterations = "100" <br>
numBands = "1000" <br>
args = [inputFile, outputFile, histogramFile, range, numIterations, numBands] <br>
pluginHost.runPlugin("StochasticDepressionAnalysis", args, False) <br>
</code>
</p>
<p>This is a Groovy script also using this tool:</p>
<p style="background-color: rgb(240,240,240)">
<code>
def wd = pluginHost.getWorkingDirectory() <br>
def inputFile = wd + "input.dep" <br>
def outputFile = wd + "output.dep" <br>
def histogramFile = wd + "histo.txt" <br>
def range = "265.0" <br>
def numIterations = "100" <br>
def numBands = "1000" <br>
String[] args = [inputFile, outputFile, histogramFile, range, numIterations, numBands] <br>
pluginHost.runPlugin("StochasticDepressionAnalysis", args, false) <br>
</code>
</p>
<h2 class="SeeAlso">References:</h2>
<ul>
<li>Carr, JR. 2002. Data visualization in the geosciences. Prentice
Hall, 267 pp.</li>
<li>Lindsay JB, Creed IF. 2006. Distinguishing between
artefact and real depressions in digital elevation data.
Computers and Geosciences, 32(8): 1192-1204.
doi: 10.1016/j.cageo.2005.11.002.</li>
</ul>
</body>
</html>
| {'content_hash': '34a6c28425f94a29254d75809d730362', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 111, 'avg_line_length': 58.42748091603053, 'alnum_prop': 0.6204598902534623, 'repo_name': 'jblindsay/jblindsay.github.io', 'id': 'f17e4294fcd924c45d01207f1f75d6d07410be33', 'size': '7654', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ghrg/Whitebox/WhiteboxGAT-linux/resources/Help/StochasticDepressionAnalysis.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '52'}, {'name': 'CSS', 'bytes': '1086446'}, {'name': 'Groovy', 'bytes': '2186907'}, {'name': 'HTML', 'bytes': '11454480'}, {'name': 'Java', 'bytes': '5373007'}, {'name': 'JavaScript', 'bytes': '1745824'}, {'name': 'Python', 'bytes': '82583'}, {'name': 'SCSS', 'bytes': '173472'}, {'name': 'TeX', 'bytes': '15589'}]} |
import { StyleSheet } from 'react-native';
import { dimensions, fontSizes, colors, fontWeights, scalingUtils } from '../../styles';
const styles = StyleSheet.create({
container: {
margin: dimensions.halfIndent,
},
accountContainer: {
width: dimensions.length,
height: dimensions.length,
borderRadius: dimensions.borderRadius,
alignItems: 'center',
justifyContent: 'center',
},
value: {
fontSize: fontSizes.big,
color: colors.white,
fontWeight: fontWeights.heavy,
},
toLargeText: {
color: colors.white,
fontWeight: fontWeights.semiBold,
fontSize: fontSizes.verySmall,
textAlign: 'center',
paddingBottom: 10,
},
valueContainer: {
padding: dimensions.halfIndent,
},
subtitle: {
fontSize: fontSizes.verySmall,
color: colors.white,
fontWeight: fontWeights.bold,
},
addButtonSubtitle: {
fontSize: fontSizes.verySmall - 2,
color: colors.greyDarker,
fontWeight: fontWeights.bold,
},
subtitleContainer: {
position: 'absolute',
bottom: scalingUtils.verticalScale(10),
},
image: {
width: dimensions.length,
height: dimensions.length,
},
});
export default styles;
| {'content_hash': '83e2c316e3b9acc7a2ed1012f7efe90a', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 88, 'avg_line_length': 22.528301886792452, 'alnum_prop': 0.6733668341708543, 'repo_name': 'JSSolutions/Perfi', 'id': 'a5bb2a9954bcca9e730f1908fe7dc136b1599cf8', 'size': '1194', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/components/AccountItem/styles.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '270023'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '0aba0b4309ce8eec7b8a604c694ee683', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'a852ae81ce494ed96d81fdb9bab827ae91a98648', 'size': '193', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Centaurea/Centaurea solstitialis/ Syn. Calcitrapa pyracantha/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>math-classes: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.12.0 / math-classes - 1.0.4</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
math-classes
<small>
1.0.4
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-14 03:58:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-14 03:58:21 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.12.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/math-classes/"
doc: "https://github.com/math-classes/"
authors: [
"Eelis van der Weegen"
"Bas Spitters"
"Robbert Krebbers"
]
license: "Public Domain"
build: [
[ "./configure.sh" ]
[ make "-j%{jobs}%" ]
]
install: [ make "install" ]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [
"logpath:MathClasses"
]
synopsis: "A library of abstract interfaces for mathematical structures in Coq"
url {
src:
"https://github.com/math-classes/math-classes/archive/9853988446ab19ee0618181f8da1d7dbdebcc45f.zip"
checksum: "md5=b2293d8e429ab1174160f68c1cba12d2"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-math-classes.1.0.4 coq.8.12.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.12.0).
The following dependencies couldn't be met:
- coq-math-classes -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-math-classes.1.0.4</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '72e1ee170871cdb38b4a1be574f20b66', 'timestamp': '', 'source': 'github', 'line_count': 166, 'max_line_length': 159, 'avg_line_length': 38.68674698795181, 'alnum_prop': 0.5261600747430707, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '7990c46ee74b89eb860e9aa2d7060c8168b5d396', 'size': '6447', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.07.1-2.0.6/released/8.12.0/math-classes/1.0.4.html', 'mode': '33188', 'license': 'mit', 'language': []} |
#include "./gray.hpp"
#include "./black.hpp"
#include "./white.hpp"
| {'content_hash': '0156b1d9ddd372e188ce1a2d3c876f2a', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 22, 'avg_line_length': 12.833333333333334, 'alnum_prop': 0.5714285714285714, 'repo_name': 'dmilos/color', 'id': '0161ae46c3ad7dc86c431567bd24ba3f4fe62dbd', 'size': '146', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/color/gray/get/get.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '202084'}, {'name': 'C++', 'bytes': '5689078'}, {'name': 'CMake', 'bytes': '3786'}, {'name': 'Python', 'bytes': '11674'}, {'name': 'Shell', 'bytes': '153373'}]} |
from webpage import Webpage
import html
# Constants
# Functions
# Classes
class WebpageToSelectWifi(object):
def __init__(self, action_to_rescan = None, action_to_skip_step = None):
self.__wifis = []
self.__connected_services = []
self.__action_to_rescan = action_to_rescan
self.__action_to_skip_step = action_to_skip_step
def append_wifi_with_name(self,
name,
action_when_selected,
action_params = []):
link = html.link_with_name(name,
action = action_when_selected,
params = action_params)
self.__wifis.append(link)
def append_connected_service_with_name(self, name):
self.__connected_services.append(name)
def render(self):
body = ''
if self.__wifis:
body += html.paragraph_with_text('Select WIFI:')
body += html.ordered_list_with_elements(self.__wifis)
if self.__action_to_rescan:
body += html.form_with_text('Re-scan',
action = self.__action_to_rescan)
if self.__connected_services:
body += html.paragraph_with_text(
'Already connected to: %s' %
', '.join(self.__connected_services))
if self.__action_to_skip_step:
body += html.form_with_text('Skip',
action = self.__action_to_skip_step)
return Webpage(body = body).render()
| {'content_hash': 'cfc554fea655aeb47b2beea6d800c761', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 76, 'avg_line_length': 32.53061224489796, 'alnum_prop': 0.5119196988707654, 'repo_name': 'comodoo/comodoo-pos-wizard', 'id': '299501ca7718861f12314ef88dc3f8bd9e69d377', 'size': '1605', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'webpage_to_select_wifi.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '16601'}]} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon</groupId>
<artifactId>carbon-utils</artifactId>
<version>4.3.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>statistics-feature</artifactId>
<version>4.3.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - System Statistics Feature Aggregator Module</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.system.statistics.feature</module>
<module>org.wso2.carbon.system.statistics.server.feature</module>
<module>org.wso2.carbon.system.statistics.ui.feature</module>
</modules>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.statistics</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.statistics.ui</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.statistics.stub</artifactId>
</dependency>
</dependencies>
<!-- <properties>
<wso2carbon.version.statistics>${wso2carbon.version}</wso2carbon.version.statistics>
</properties>-->
</project>
| {'content_hash': 'fbfdb4a508bb409bb1e87becc33a244e', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 105, 'avg_line_length': 36.46875, 'alnum_prop': 0.6465295629820051, 'repo_name': 'maheshika/carbon-utils', 'id': '367358664bc0a8cdcba6fab94b4146093717234d', 'size': '2334', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'features/system-statistics/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '65818'}, {'name': 'Java', 'bytes': '2543190'}, {'name': 'JavaScript', 'bytes': '962576'}, {'name': 'PHP', 'bytes': '15326'}, {'name': 'XSLT', 'bytes': '335028'}]} |
const int main_minimum_lambda = 120;
int main(int argc, char** argv) {
// Generate a keyset.
TFheGateBootstrappingParameterSet* params =
new_default_gate_bootstrapping_parameters(main_minimum_lambda);
// Generate a "random" key.
// Note: In real applications, a cryptographically secure seed needs to be
// used.
uint32_t seed[] = {314, 1592, 657};
tfhe_random_generator_setSeed(seed, 3);
TFheGateBootstrappingSecretKeySet* key =
new_random_gate_bootstrapping_secret_keyset(params);
const TFheGateBootstrappingCloudKeySet* cloud_key = &key->cloud;
Helper helper_a;
helper_a.a = -1;
helper_a.b = 0xffffffff;
helper_a.c = -4;
Helper helper_b;
helper_b.a = 1;
helper_b.b = 0x7fffffff;
helper_b.c = 32;
Helper helper_c;
helper_c.a = -64;
helper_c.b = 128;
helper_c.c = -256;
Tfhe<Helper> fhe_helper_a(params);
fhe_helper_a.SetEncrypted(helper_a, key);
Tfhe<Helper> fhe_helper_b(params);
fhe_helper_b.SetEncrypted(helper_b, key);
Tfhe<Helper> fhe_helper_c(params);
fhe_helper_c.SetEncrypted(helper_c, key);
std::cout << "Round trip check : helper_a: " << std::endl;
Helper round_trip_a = fhe_helper_a.Decrypt(key);
std::cout << " a: " << static_cast<int>(round_trip_a.a) << std::endl;
std::cout << " b: " << static_cast<unsigned int>(round_trip_a.b)
<< std::endl;
std::cout << " c: " << static_cast<int>(round_trip_a.c) << std::endl;
std::cout << "Round trip check : helper_b: " << std::endl;
Helper round_trip_b = fhe_helper_b.Decrypt(key);
std::cout << " a: " << static_cast<int>(round_trip_b.a) << std::endl;
std::cout << " b: " << static_cast<unsigned int>(round_trip_b.b)
<< std::endl;
std::cout << " c: " << static_cast<int>(round_trip_b.c) << std::endl;
std::cout << "Round trip check : helper_c: " << std::endl;
Helper round_trip_c = fhe_helper_c.Decrypt(key);
std::cout << " a: " << static_cast<int>(round_trip_c.a) << std::endl;
std::cout << " b: " << static_cast<unsigned int>(round_trip_c.b)
<< std::endl;
std::cout << " c: " << static_cast<int>(round_trip_c.c) << std::endl;
std::cout << "Starting computation." << std::endl;
Tfhe<ReturnStruct> fhe_result(params);
XLS_CHECK_OK(ConstructReturnStructWithInout(
fhe_result, fhe_helper_a, fhe_helper_b, fhe_helper_c, cloud_key));
ReturnStruct result = fhe_result.Decrypt(key);
std::cout << "Done. Function return: " << std::endl;
std::cout << " - a: " << static_cast<int>(result.a) << std::endl;
std::cout << " - b.a: " << static_cast<int>(result.b.a) << std::endl;
std::cout << " - b.b: " << static_cast<unsigned int>(result.b.b) << std::endl;
std::cout << " - b.c: " << static_cast<int>(result.b.c) << std::endl;
std::cout << " - c: " << static_cast<int>(result.c) << std::endl << std::endl;
std::cout << "helper_a return-by-reference: " << std::endl;
Helper output_a = fhe_helper_a.Decrypt(key);
std::cout << " a: " << static_cast<int>(output_a.a) << std::endl;
std::cout << " b: " << static_cast<unsigned int>(output_a.b) << std::endl;
std::cout << " c: " << static_cast<int>(output_a.c) << std::endl
<< std::endl;
std::cout << "helper_b return-by-reference: " << std::endl;
Helper output_b = fhe_helper_b.Decrypt(key);
std::cout << " a: " << static_cast<int>(output_b.a) << std::endl;
std::cout << " b: " << static_cast<unsigned int>(output_b.b) << std::endl;
std::cout << " c: " << static_cast<int>(output_b.c) << std::endl
<< std::endl;
std::cout << "helper_c (should be unchanged!): " << std::endl;
Helper output_c = fhe_helper_c.Decrypt(key);
std::cout << " a: " << static_cast<int>(output_c.a) << std::endl;
std::cout << " b: " << static_cast<unsigned int>(output_c.b) << std::endl;
std::cout << " c: " << static_cast<int>(output_c.c) << std::endl
<< std::endl;
return 0;
}
| {'content_hash': '6c32487bb35bba862c1103b4bdc16898', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 80, 'avg_line_length': 41.45744680851064, 'alnum_prop': 0.5991788555298948, 'repo_name': 'google/fully-homomorphic-encryption', 'id': 'f3ac913170115f841d050f728ad7e3b90b0b469f', 'size': '5178', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'transpiler/examples/structs/return_struct_with_inout_tfhe_testbench.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '25113'}, {'name': 'C++', 'bytes': '832683'}, {'name': 'Dockerfile', 'bytes': '1100'}, {'name': 'Starlark', 'bytes': '179030'}]} |
title: axk19
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: k19
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {'content_hash': '93ea988925a215720a729d47071d0c73', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 61, 'avg_line_length': 22.333333333333332, 'alnum_prop': 0.6656716417910448, 'repo_name': 'pblack/kaldi-hugo-cms-template', 'id': '89f9e327fc5f35626bbdd76673aff7ed9f765948', 'size': '339', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'site/content/pages2/axk19.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '94394'}, {'name': 'HTML', 'bytes': '18889'}, {'name': 'JavaScript', 'bytes': '10014'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<Definitions>
<Application id="Application" name="Application">
<Schemas>
<Schema id="schemaName" name="schemaName">
<attribute name="w" type="java.lang.String"></attribute>
</Schema>
</Schemas>
<Operators>
<Aggregate id="aggregate1" name="Aggregate1" parallel="1">
<window name="time_sort">
<length>0</length>
<groupbyExpression></groupbyExpression>
<orderbyExpression>s</orderbyExpression>
</window>
<groupbyExpression>sdfs</groupbyExpression>
<orderBy>sdfsdf</orderBy>
<filterBeforeAggregate>eer</filterBeforeAggregate>
<filterAfterAggregate>dd</filterAfterAggregate>
<limit>2</limit>
<outputExpression>sdfsdf</outputExpression>
</Aggregate>
<Join id="join1" name="Join1" parallel="1">
<leftWindow name="length_slide">
<length>0</length>
</leftWindow>
<rightWindow name="time_slide">
<length>0</length>
</rightWindow>
<leftStreamName>stream2</leftStreamName>
<rightStreamName>stream1</rightStreamName>
<joinType>INNER_JOIN</joinType>
<joinExpression>dfsd</joinExpression>
<filterAfterJoinExpression>dsfsd</filterAfterJoinExpression>
<outputExpression>sdfsdf</outputExpression>
</Join>
<Filter id="filter1" name="Filter1" parallel="1">
<filterExpression></filterExpression>
<outputExpression>gfg</outputExpression>
</Filter>
<Functor id="functor1" name="Functor1" parallel="1">
<filterExpression>gggg</filterExpression>
<outputExpression>fgdgdf</outputExpression>
</Functor>
<RandomSource id="randominput1" name="Random Input1"
parallel="2">
<timeUnit>MILLISECONDS</timeUnit>
<period>4</period>
<eventNumPerPeriod>3</eventNumPerPeriod>
<isSchedule>true</isSchedule>
<totalNumber>6</totalNumber>
<delayTime>5</delayTime>
<deserializer class="SimpleSerDe">
<serde.simpleserde.separator>~</serde.simpleserde.separator>
</deserializer>
</RandomSource>
<KafkaReader id="kafkainput1" name="Kafka Input1"
parallel="1">
<groupId>3</groupId>
<topic>rwer</topic>
<zookeepers>dfdf</zookeepers>
<zkSessionTimeout>234</zkSessionTimeout>
<zkSyncTime>234234</zkSyncTime>
<messageSerializerClass>werwer</messageSerializerClass>
<deserializer class="SimpleSerDe">
<serde.simpleserde.separator>!</serde.simpleserde.separator>
</deserializer>
</KafkaReader>
<KafkaWriter id="kafkaoutput1" name="Kafka Output1"
parallel="1">
<topic>23423</topic>
<zookeepers>ssss</zookeepers>
<zkSessionTimeout>43</zkSessionTimeout>
<zkSyncTime>234234</zkSyncTime>
<messageSerializerClass>2342</messageSerializerClass>
<serializer class="NullSerializer"></serializer>
</KafkaWriter>
<Sort id="sort2" name="Sort2" parallel="1">
<window name="group_time_batch">
<length>0</length>
<groupbyExpression>gdfgdfgd</groupbyExpression>
<orderbyExpression></orderbyExpression>
</window>
<orderBy></orderBy>
<limit>0</limit>
<outputExpression></outputExpression>
</Sort>
</Operators>
<Transitions>
<Transition id="transition2" name="stream2" from="functor1"
to="join1">
<schemaName>schemaName</schemaName>
<distributedType>SHUFFLE</distributedType>
<distributedFields></distributedFields>
</Transition>
<Transition id="transition3" name="stream1" from="aggregate1"
to="join1">
<schemaName>schemaName</schemaName>
<distributedType>FIELDS</distributedType>
<distributedFields>fddf</distributedFields>
</Transition>
<Transition id="transition4" name="stream1" from="aggregate1"
to="filter1">
<schemaName>schemaName</schemaName>
<distributedType>SHUFFLE</distributedType>
<distributedFields></distributedFields>
</Transition>
<Transition id="transition6" name="stream6" from="kafkainput1"
to="kafkaoutput1">
<schemaName></schemaName>
<distributedType>SHUFFLE</distributedType>
<distributedFields></distributedFields>
</Transition>
<Transition id="transition7" name="stream7" from="tcpinput1"
to="tcpoutput1">
<schemaName></schemaName>
<distributedType>SHUFFLE</distributedType>
<distributedFields></distributedFields>
</Transition>
</Transitions>
</Application>
<Diagram id="Diagram_Application">
<STREAMShape STREAMElement="aggregate1" id="STREAMShape_aggregate1">
<bounds height="50" width="100" x="600" y="300"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="join1" id="STREAMShape_join1">
<bounds height="50" width="100" x="351" y="300"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="filter1" id="STREAMShape_filter1">
<bounds height="50" width="100" x="570" y="90"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="functor1" id="STREAMShape_functor1">
<bounds height="50" width="100" x="280" y="120"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="randominput1" id="STREAMShape_randominput1">
<bounds height="50" width="100" x="190" y="60"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="kafkainput1" id="STREAMShape_kafkainput1">
<bounds height="50" width="100" x="810" y="40"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="kafkaoutput1" id="STREAMShape_kafkaoutput1">
<bounds height="50" width="100" x="850" y="180"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="sort2" id="STREAMShape_sort2">
<bounds height="50" width="100" x="150" y="300"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="tcpinput1" id="STREAMShape_tcpinput1">
<bounds height="50" width="100" x="711" y="148"></bounds>
</STREAMShape>
<STREAMShape STREAMElement="tcpoutput1" id="STREAMShape_tcpoutput1">
<bounds height="50" width="100" x="860" y="290"></bounds>
</STREAMShape>
<STREAMEdge STREAMElement="transition2" id="STREAMEdge_transition2"></STREAMEdge>
<STREAMEdge STREAMElement="transition3" id="STREAMEdge_transition3"></STREAMEdge>
<STREAMEdge STREAMElement="transition4" id="STREAMEdge_transition4"></STREAMEdge>
<STREAMEdge STREAMElement="transition6" id="STREAMEdge_transition6"></STREAMEdge>
<STREAMEdge STREAMElement="transition7" id="STREAMEdge_transition7"></STREAMEdge>
</Diagram>
</Definitions>
| {'content_hash': 'b85a0030e5dbd3848760644d37dbf68e', 'timestamp': '', 'source': 'github', 'line_count': 159, 'max_line_length': 89, 'avg_line_length': 49.515723270440255, 'alnum_prop': 0.563063635208942, 'repo_name': 'jack6215/StreamCQL', 'id': 'e8a26bcb8b46db73c3e4cb9a8e4ee00d84c6263d', 'size': '7873', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cql/src/test/resources/executor/plans/MyProcess.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '24721'}, {'name': 'Batchfile', 'bytes': '2104'}, {'name': 'Java', 'bytes': '4145463'}, {'name': 'Shell', 'bytes': '695'}]} |
using System;
using System.Configuration;
namespace CacheSharp.Console
{
public class FileLoadConfiguration : ILoadConfiguration
{
public int ParallelInstances
{
get { return Convert.ToInt32(ConfigurationManager.AppSettings["ParallelInstances"]); }
}
public int IterationsPerInstance
{
get { return Convert.ToInt32(ConfigurationManager.AppSettings["IterationsPerInstance"]); }
}
public string CacheProvider
{
get { return ConfigurationManager.AppSettings["CacheProvider"]; }
}
public int CharactersPerMessage
{
get { return Convert.ToInt32(ConfigurationManager.AppSettings["CharactersPerMessage"]); }
}
}
} | {'content_hash': 'cc19f9bf57ae47fecf09c36c82f2407c', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 102, 'avg_line_length': 28.357142857142858, 'alnum_prop': 0.6221662468513854, 'repo_name': 'paulfryer/CacheSharp', 'id': 'a3e512b76b58815fc2e8c786124f4ac4641904b9', 'size': '796', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'CacheSharp.Console/FileLoadConfiguration.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '119'}, {'name': 'C#', 'bytes': '62614'}, {'name': 'HTML', 'bytes': '1299'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '65f3fa1e5c91d75a9f9e6a24790da4f5', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'c38f11c71b56c9ae5ecc5d76f4867422113e1622', 'size': '173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Liliales/Liliaceae/Streptopus/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
var map;
var directionsDisplay;
var directionsService;
function initMap() {
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: restLatlng.lat, lng: restLatlng.lng},
});
directionsDisplay.setMap(map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: pos,
destination: restLatlng,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
document.getElementById('mode').addEventListener('change', function() {
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: pos,
destination: restLatlng,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
},function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
initMap();
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
//WORKING GOOGLE MAP
// var userLatlng = {lat: {{ rest_info['coordinates']['latitude'] }},
// lng: {{ rest_info['coordinates']['longitude'] }}};
// var map;
// function initMap() {
// map = new google.maps.Map(document.getElementById('map'), {
// center: {lat: userLatlng.lat, lng: userLatlng.lng},
// zoom: 12
// // zoomControl: true,
// });
// var marker = new google.maps.Marker({
// position: userLatlng,
// icon: 'https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_local_restaurant_48px-32.png',
// map: map
// });
// var contentString = '<div><h3>{{ rest_info['name'] }}</h3></div>' +
// '<div><p>{{ rest_info['location']['address1'] }}</p>' +
// '<p>{{ rest_info['location']['city'] }}, {{ rest_info['location']['state'] }}</p></div>'
// + '<a>Direction</a>';
// var infowindow = new google.maps.InfoWindow({
// content: contentString
// });
// marker.addListener('click', function() {
// infowindow.open(map, marker);
// });
// }
| {'content_hash': '4ae118f5dcbaecfd8632052fbad48523', 'timestamp': '', 'source': 'github', 'line_count': 142, 'max_line_length': 118, 'avg_line_length': 25.591549295774648, 'alnum_prop': 0.5742982938910292, 'repo_name': 'shioramen/HB_PROJECT', 'id': '73ba07c5ec4cb9bb60e3c7c31a4e76dac90a42a8', 'size': '3635', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'static/js/map.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5515'}, {'name': 'HTML', 'bytes': '41405'}, {'name': 'JavaScript', 'bytes': '8600'}, {'name': 'Python', 'bytes': '31211'}]} |
require 'test/unit'
require 'rexml/document'
require '_loadpath'
require 'openwsman'
require '_client'
class WsmanTest < Test::Unit::TestCase
def test_client
# Openwsman::debug = 1
client = Client.open
assert client
options = Openwsman::ClientOptions.new
assert options
options.set_dump_request
uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem"
# uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_HostedService"
# uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_CommMechanismForManager"
# uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ManagedElement"
result = client.get( options, uri )
assert result
puts result
end
end
| {'content_hash': '97b50b1f46d60f31f4bd952ddfc12893', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 90, 'avg_line_length': 29.68, 'alnum_prop': 0.706199460916442, 'repo_name': 'steakknife/openwsman', 'id': 'dd45b224bdd2438a484b876fc4d166e977a22942', 'size': '804', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'bindings/ruby/tests/cim_get_class.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
public class TrainPassengersLimitFactory
{
public static TrainPassengersLimit Get(TrainPassengersLimitType type)
{
switch (type)
{
case TrainPassengersLimitType.PerStation:
return new PerStationTrainPassengersLimit();
case TrainPassengersLimitType.PerTrain:
return new PerTrainTrainPassengersLimit();
default:
return null;
}
}
}
| {'content_hash': '366213775fba6c33b6ec1e9b856770ad', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 70, 'avg_line_length': 23.533333333333335, 'alnum_prop': 0.7875354107648725, 'repo_name': 'alvarogzp/nextation', 'id': '789f73b7af0f6616ab160f73e0fea87f3dcf2e5a', 'size': '353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Assets/Scripts/Train/Passengers/Limit/TrainPassengersLimitFactory.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '179337'}, {'name': 'JavaScript', 'bytes': '1437'}, {'name': 'Shell', 'bytes': '3196'}]} |
package ch.petikoch.examples.rxjava.threading;
import rx.Observable;
import rx.Single;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class OneLaneMcDrive2 {
private static final Clock clock = new Clock(Time.EIGTH_AM);
public static void main(String[] args) throws InterruptedException {
Observable<String> customers = Observable.just("Fred", "John", "Maria", "Ben", "Ken", "Greg", "Peter", "Henry").repeat();
Observable<Long> arrivals = Observable.interval(0, 10, TimeUnit.SECONDS);
Observable<CustomerWithArrivalTime> customerArriveStream =
Observable.zip(
customers,
arrivals,
(customer, eventNumber) -> new CustomerWithArrivalTime(customer + eventNumber, clock.getTime()))
.doOnNext(customer -> sysout(customer.name + " arrived"));
PublishSubject<CustomerWithArrivalTime> finishedOrderStream = PublishSubject.create();
AtomicBoolean readyForNext = new AtomicBoolean(true);
customerArriveStream.subscribe(customerWithArrivalTime -> {
while (!readyForNext.compareAndSet(true, false)) {
waitMilliSeconds(1);
}
Single<String> mac = Single.<String>create(singleSubscriber -> {
sysout("Starting with mac for " + customerWithArrivalTime);
waitSeconds(8);
sysout("Mac ready for " + customerWithArrivalTime);
singleSubscriber.onSuccess("mac");
}).subscribeOn(Schedulers.io());
Single<String> fries = Single.<String>create(singleSubscriber -> {
sysout("Starting with fries for " + customerWithArrivalTime);
waitSeconds(4);
sysout("Fries ready for " + customerWithArrivalTime);
singleSubscriber.onSuccess("fries");
}).subscribeOn(Schedulers.io());
Single<String> coke = Single.<String>create(singleSubscriber -> {
sysout("Starting with coke for " + customerWithArrivalTime);
waitSeconds(1);
sysout("Coke ready for " + customerWithArrivalTime);
singleSubscriber.onSuccess("coke");
}).subscribeOn(Schedulers.io());
Single.zip(mac, fries, coke, (s, s2, s3) -> {
readyForNext.set(true);
return customerWithArrivalTime;
}).toObservable().first().subscribe(finishedOrderStream);
});
finishedOrderStream.subscribe(customerWithArrivalTime -> {
int timeDifference = clock.getTime().difference(customerWithArrivalTime.arrivalTime);
sysout(customerWithArrivalTime.name + " order finished after " + timeDifference + " minutes");
sysout(customerWithArrivalTime.name + " says good bye and leaves.");
});
waitSeconds(60);
}
private static void sysout(String text) {
System.out.println(clock.getTime() + " [" + Thread.currentThread().getName() + "] " + text);
}
private static void waitSeconds(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void waitMilliSeconds(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class CustomerWithArrivalTime {
String name;
Time arrivalTime;
CustomerWithArrivalTime(String name, Time arrivalTime) {
this.name = name;
this.arrivalTime = arrivalTime;
}
@Override
public String toString() {
return name + " (arrived at " + arrivalTime + ")";
}
}
static class Clock {
private final AtomicInteger internalTimeInMinutes = new AtomicInteger();
Clock(Time initialTime) {
internalTimeInMinutes.set(initialTime.internalTimeInMinutes);
Observable.interval(1, TimeUnit.SECONDS).subscribe(aLong -> {
internalTimeInMinutes.incrementAndGet();
System.out.println(getTime());
});
}
public boolean isBefore(Time time) {
return internalTimeInMinutes.get() < time.internalTimeInMinutes;
}
public Time getTime() {
return new Time(internalTimeInMinutes.get());
}
}
static class Time {
static final Time EIGTH_AM = new Time(8 * 60);
static final Time EIGTH_TWO_AM = new Time(8 * 60 + 2);
static final Time NINE_AM = new Time(9 * 60);
static final Time FIVE_PM = new Time(17 * 60);
private final int internalTimeInMinutes;
Time(int internalTimeInMinutes) {
this.internalTimeInMinutes = internalTimeInMinutes;
}
private static String leftPadded2DigitsString(int number, int maxNumber) {
if (number < 10) {
return "0" + number;
} else if (number >= 10 && number <= maxNumber) {
return Integer.toString(number);
} else {
throw new IllegalStateException("Unhandled: " + number);
}
}
int difference(Time laterOther) {
int result = laterOther.internalTimeInMinutes - internalTimeInMinutes;
if (result < 0) {
result = result * -1;
}
return result;
}
@Override
public String toString() {
return leftPadded2DigitsString(internalTimeInMinutes / 60, 23) + ":" + leftPadded2DigitsString(internalTimeInMinutes % 60, 59);
}
}
}
| {'content_hash': '39dd0582abdd1ed54df7166f9287af18', 'timestamp': '', 'source': 'github', 'line_count': 167, 'max_line_length': 139, 'avg_line_length': 35.52095808383233, 'alnum_prop': 0.5962575859743763, 'repo_name': 'Petikoch/rxjava_examples', 'id': 'f09d2b65d312ee2b0f49de45eae32f1059095a95', 'size': '6521', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/ch/petikoch/examples/rxjava/threading/OneLaneMcDrive2.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '47584'}]} |
package com.smartystreets.spring;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ZipCodeResponse {
@JsonProperty("input_index")
private int inputIndex;
@JsonProperty("input_id")
private String inputId;
@JsonProperty("city_states")
private List<CityState> cityStates;
@JsonProperty("zipcodes")
private List<ZipCode> zipCodes;
private String status;
private String reason;
public List<CityState> getCityStates() {
return cityStates;
}
public void setCityStates(List<CityState> cityStates) {
this.cityStates = cityStates;
}
public String getInputId() {
return inputId;
}
public void setInputId(String inputId) {
this.inputId = inputId;
}
public int getInputIndex() {
return inputIndex;
}
public void setInputIndex(int inputIndex) {
this.inputIndex = inputIndex;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<ZipCode> getZipCodes() {
return zipCodes;
}
public void setZipCodes(List<ZipCode> zipCodes) {
this.zipCodes = zipCodes;
}
}
| {'content_hash': '257c45f5764924e5a601f349d9c94d58', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 63, 'avg_line_length': 19.376470588235293, 'alnum_prop': 0.6666666666666666, 'repo_name': 'rnbWarden/smartystreets-spring', 'id': '44129c089aa84516418b3360c71f3d3e23da585b', 'size': '2788', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/smartystreets/spring/ZipCodeResponse.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '71206'}]} |
namespace RapidVulkan
{
namespace Debug
{
inline const char* TryToString(const VkSurfaceTransformFlagBitsKHR& value)
{
switch(value)
{
case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
return "VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR";
case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
return "VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR";
case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
return "VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR";
case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
return "VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR";
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
return "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR";
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
return "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR";
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
return "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR";
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
return "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR";
case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
return "VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR";
default:
return nullptr;
}
};
inline const char* ToString(const VkSurfaceTransformFlagBitsKHR& value)
{
auto result = TryToString(value);
return (result != nullptr ? result : "*Unknown*");
};
}
}
#endif
| {'content_hash': '64b1c4831f64fd642b75efa14567f210', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 78, 'avg_line_length': 37.8, 'alnum_prop': 0.6871693121693122, 'repo_name': 'Unarmed1000/RapidVulkan', 'id': '66aa451e157757e8affb8ec152d032067264146f', 'size': '3791', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/RapidVulkan/Debug/Strings/VkSurfaceTransformFlagBitsKHR.hpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C++', 'bytes': '1097694'}, {'name': 'CMake', 'bytes': '3581'}]} |
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DecimalFormatting.java,v 1.2.4.1 2005/09/12 10:14:32 pvedula Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.compiler;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.GETSTATIC;
import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.generic.PUSH;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;
import com.sun.org.apache.xml.internal.utils.XML11Char;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
*/
final class DecimalFormatting extends TopLevelElement {
private static final String DFS_CLASS = "java.text.DecimalFormatSymbols";
private static final String DFS_SIG = "Ljava/text/DecimalFormatSymbols;";
private QName _name = null;
/**
* No type check needed for the <xsl:decimal-formatting/> element
*/
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
return Type.Void;
}
/**
* Parse the name of the <xsl:decimal-formatting/> element
*/
public void parseContents(Parser parser) {
// Get the name of these decimal formatting symbols
final String name = getAttribute("name");
if (name.length() > 0) {
if (!XML11Char.isXML11ValidQName(name)){
ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_QNAME_ERR, name, this);
parser.reportError(Constants.ERROR, err);
}
}
_name = parser.getQNameIgnoreDefaultNs(name);
if (_name == null) {
_name = parser.getQNameIgnoreDefaultNs(EMPTYSTRING);
}
// Check if a set of symbols has already been registered under this name
SymbolTable stable = parser.getSymbolTable();
if (stable.getDecimalFormatting(_name) != null) {
reportWarning(this, parser, ErrorMsg.SYMBOLS_REDEF_ERR,
_name.toString());
}
else {
stable.addDecimalFormatting(_name, this);
}
}
/**
* This method is called when the constructor is compiled in
* Stylesheet.compileConstructor() and not as the syntax tree is traversed.
*/
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
ConstantPoolGen cpg = classGen.getConstantPool();
InstructionList il = methodGen.getInstructionList();
// DecimalFormatSymbols.<init>(Locale);
// xsl:decimal-format - except for the NaN and infinity attributes.
final int init = cpg.addMethodref(DFS_CLASS, "<init>",
"("+LOCALE_SIG+")V");
// Push the format name on the stack for call to addDecimalFormat()
il.append(classGen.loadTranslet());
il.append(new PUSH(cpg, _name.toString()));
// Manufacture a DecimalFormatSymbols on the stack
// for call to addDecimalFormat()
// Use the US Locale as the default, as most of its settings
// are equivalent to the default settings required of
il.append(new NEW(cpg.addClass(DFS_CLASS)));
il.append(DUP);
il.append(new GETSTATIC(cpg.addFieldref(LOCALE_CLASS, "US",
LOCALE_SIG)));
il.append(new INVOKESPECIAL(init));
String tmp = getAttribute("NaN");
if ((tmp == null) || (tmp.equals(EMPTYSTRING))) {
int nan = cpg.addMethodref(DFS_CLASS,
"setNaN", "(Ljava/lang/String;)V");
il.append(DUP);
il.append(new PUSH(cpg, "NaN"));
il.append(new INVOKEVIRTUAL(nan));
}
tmp = getAttribute("infinity");
if ((tmp == null) || (tmp.equals(EMPTYSTRING))) {
int inf = cpg.addMethodref(DFS_CLASS,
"setInfinity",
"(Ljava/lang/String;)V");
il.append(DUP);
il.append(new PUSH(cpg, "Infinity"));
il.append(new INVOKEVIRTUAL(inf));
}
final int nAttributes = _attributes.getLength();
for (int i = 0; i < nAttributes; i++) {
final String name = _attributes.getQName(i);
final String value = _attributes.getValue(i);
boolean valid = true;
int method = 0;
if (name.equals("decimal-separator")) {
// DecimalFormatSymbols.setDecimalSeparator();
method = cpg.addMethodref(DFS_CLASS,
"setDecimalSeparator", "(C)V");
}
else if (name.equals("grouping-separator")) {
method = cpg.addMethodref(DFS_CLASS,
"setGroupingSeparator", "(C)V");
}
else if (name.equals("minus-sign")) {
method = cpg.addMethodref(DFS_CLASS,
"setMinusSign", "(C)V");
}
else if (name.equals("percent")) {
method = cpg.addMethodref(DFS_CLASS,
"setPercent", "(C)V");
}
else if (name.equals("per-mille")) {
method = cpg.addMethodref(DFS_CLASS,
"setPerMill", "(C)V");
}
else if (name.equals("zero-digit")) {
method = cpg.addMethodref(DFS_CLASS,
"setZeroDigit", "(C)V");
}
else if (name.equals("digit")) {
method = cpg.addMethodref(DFS_CLASS,
"setDigit", "(C)V");
}
else if (name.equals("pattern-separator")) {
method = cpg.addMethodref(DFS_CLASS,
"setPatternSeparator", "(C)V");
}
else if (name.equals("NaN")) {
method = cpg.addMethodref(DFS_CLASS,
"setNaN", "(Ljava/lang/String;)V");
il.append(DUP);
il.append(new PUSH(cpg, value));
il.append(new INVOKEVIRTUAL(method));
valid = false;
}
else if (name.equals("infinity")) {
method = cpg.addMethodref(DFS_CLASS,
"setInfinity",
"(Ljava/lang/String;)V");
il.append(DUP);
il.append(new PUSH(cpg, value));
il.append(new INVOKEVIRTUAL(method));
valid = false;
}
else {
valid = false;
}
if (valid) {
il.append(DUP);
il.append(new PUSH(cpg, value.charAt(0)));
il.append(new INVOKEVIRTUAL(method));
}
}
final int put = cpg.addMethodref(TRANSLET_CLASS,
"addDecimalFormat",
"("+STRING_SIG+DFS_SIG+")V");
il.append(new INVOKEVIRTUAL(put));
}
/**
* Creates the default, nameless, DecimalFormat object in
* AbstractTranslet's format_symbols hashtable.
* This should be called for every stylesheet, and the entry
* may be overridden by later nameless xsl:decimal-format instructions.
*/
public static void translateDefaultDFS(ClassGenerator classGen,
MethodGenerator methodGen) {
ConstantPoolGen cpg = classGen.getConstantPool();
InstructionList il = methodGen.getInstructionList();
final int init = cpg.addMethodref(DFS_CLASS, "<init>",
"("+LOCALE_SIG+")V");
// Push the format name, which is empty, on the stack
// for call to addDecimalFormat()
il.append(classGen.loadTranslet());
il.append(new PUSH(cpg, EMPTYSTRING));
// Manufacture a DecimalFormatSymbols on the stack for
// call to addDecimalFormat(). Use the US Locale as the
// default, as most of its settings are equivalent to
// the default settings required of xsl:decimal-format -
// except for the NaN and infinity attributes.
il.append(new NEW(cpg.addClass(DFS_CLASS)));
il.append(DUP);
il.append(new GETSTATIC(cpg.addFieldref(LOCALE_CLASS, "US",
LOCALE_SIG)));
il.append(new INVOKESPECIAL(init));
int nan = cpg.addMethodref(DFS_CLASS,
"setNaN", "(Ljava/lang/String;)V");
il.append(DUP);
il.append(new PUSH(cpg, "NaN"));
il.append(new INVOKEVIRTUAL(nan));
int inf = cpg.addMethodref(DFS_CLASS,
"setInfinity",
"(Ljava/lang/String;)V");
il.append(DUP);
il.append(new PUSH(cpg, "Infinity"));
il.append(new INVOKEVIRTUAL(inf));
final int put = cpg.addMethodref(TRANSLET_CLASS,
"addDecimalFormat",
"("+STRING_SIG+DFS_SIG+")V");
il.append(new INVOKEVIRTUAL(put));
}
}
| {'content_hash': '7a4a1abc43e51f2c2bff07f6cdacb69b', 'timestamp': '', 'source': 'github', 'line_count': 258, 'max_line_length': 84, 'avg_line_length': 40.84496124031008, 'alnum_prop': 0.5541848548111596, 'repo_name': 'rokn/Count_Words_2015', 'id': '8c89eaef400e6942ef300c3afa3d80e7028aee62', 'size': '10538', 'binary': False, 'copies': '38', 'ref': 'refs/heads/master', 'path': 'testing/openjdk2/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/DecimalFormatting.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '61802'}, {'name': 'Ruby', 'bytes': '18888605'}]} |
<?php
namespace Oro\Bundle\DataGridBundle\Extension\Formatter\Property;
use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface;
/**
* Interface PropertyInterface
* @package Oro\Bundle\DataGridBundle\Extension\Formatter\Property
*
* Every property should be stateless
*/
interface PropertyInterface
{
const TYPE_DATE = 'date';
const TYPE_DATETIME = 'datetime';
const TYPE_DECIMAL = 'decimal';
const TYPE_INTEGER = 'integer';
const TYPE_PERCENT = 'percent';
const TYPE_SELECT = 'select';
const TYPE_STRING = 'string';
const TYPE_HTML = 'html';
const TYPE_BOOLEAN = 'boolean';
const METADATA_NAME_KEY = 'name';
const METADATA_TYPE_KEY = 'type';
const TYPE_KEY = 'type';
const NAME_KEY = 'name';
const DATA_NAME_KEY = 'data_name';
const TRANSLATABLE_KEY = 'translatable';
const FRONTEND_TYPE_KEY = 'frontend_type';
/**
* Initialize property for each cell
*
* @param PropertyConfiguration $params
*
* @return $this
*/
public function init(PropertyConfiguration $params);
/**
* Get field value from data
*
* @param ResultRecordInterface $record
*
* @return mixed
*/
public function getValue(ResultRecordInterface $record);
/**
* Returns field metadata
*
* @return array
*/
public function getMetadata();
}
| {'content_hash': '1fda3670665c095430684ea02d065894', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 66, 'avg_line_length': 24.620689655172413, 'alnum_prop': 0.6316526610644257, 'repo_name': 'minhnguyen-balance/oro_platform', 'id': '844295b5450396c64fe68e11324c758b4638bc36', 'size': '1428', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/oro/platform/src/Oro/Bundle/DataGridBundle/Extension/Formatter/Property/PropertyInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '659640'}, {'name': 'JavaScript', 'bytes': '4359711'}, {'name': 'PHP', 'bytes': '213427'}, {'name': 'Perl', 'bytes': '26'}]} |
package com.asakusafw.dag.runtime.adapter;
import java.io.IOException;
/**
* An abstract super interface of generic operations.
* @param <T> the operation input type
* @since 0.4.0
*/
@FunctionalInterface
public interface Operation<T> {
/**
* Processes this operation.
* @param input the input
* @throws IOException if I/O error was occurred while processing
* @throws InterruptedException if interrupted while processing
*/
void process(T input) throws IOException, InterruptedException;
}
| {'content_hash': '43e71f2b99a92f8dd5517e871a19f54b', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 69, 'avg_line_length': 25.333333333333332, 'alnum_prop': 0.7161654135338346, 'repo_name': 'ashigeru/asakusafw-compiler', 'id': 'f77c6747137a9db9ac881dd090f33c43c238d528', 'size': '1144', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dag/runtime/runtime/src/main/java/com/asakusafw/dag/runtime/adapter/Operation.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '40879'}, {'name': 'Groovy', 'bytes': '67219'}, {'name': 'Java', 'bytes': '6494509'}, {'name': 'Shell', 'bytes': '1081'}]} |
package tinker.sample.android.reporter;
import android.content.Context;
import android.content.Intent;
import com.tencent.tinker.lib.reporter.DefaultPatchReporter;
import com.tencent.tinker.loader.shareutil.SharePatchInfo;
import java.io.File;
import java.util.List;
/**
* optional, you can just use DefaultPatchReporter
* Created by zhangshaowen on 16/4/8.
*/
public class SamplePatchReporter extends DefaultPatchReporter {
private final static String TAG = "Tinker.SamplePatchReporter";
public SamplePatchReporter(Context context) {
super(context);
}
@Override
public void onPatchServiceStart(Intent intent) {
super.onPatchServiceStart(intent);
SampleTinkerReport.onApplyPatchServiceStart();
}
@Override
public void onPatchDexOptFail(File patchFile, List<File> dexFiles, Throwable t) {
super.onPatchDexOptFail(patchFile, dexFiles, t);
SampleTinkerReport.onApplyDexOptFail(t);
}
@Override
public void onPatchException(File patchFile, Throwable e) {
super.onPatchException(patchFile, e);
SampleTinkerReport.onApplyCrash(e);
}
@Override
public void onPatchInfoCorrupted(File patchFile, String oldVersion, String newVersion) {
super.onPatchInfoCorrupted(patchFile, oldVersion, newVersion);
SampleTinkerReport.onApplyInfoCorrupted();
}
@Override
public void onPatchPackageCheckFail(File patchFile, int errorCode) {
super.onPatchPackageCheckFail(patchFile, errorCode);
SampleTinkerReport.onApplyPackageCheckFail(errorCode);
}
@Override
public void onPatchResult(File patchFile, boolean success, long cost) {
super.onPatchResult(patchFile, success, cost);
SampleTinkerReport.onApplied(cost, success);
}
@Override
public void onPatchTypeExtractFail(File patchFile, File extractTo, String filename, int fileType) {
super.onPatchTypeExtractFail(patchFile, extractTo, filename, fileType);
SampleTinkerReport.onApplyExtractFail(fileType);
}
@Override
public void onPatchVersionCheckFail(File patchFile, SharePatchInfo oldPatchInfo, String patchFileVersion) {
super.onPatchVersionCheckFail(patchFile, oldPatchInfo, patchFileVersion);
SampleTinkerReport.onApplyVersionCheckFail();
}
}
| {'content_hash': 'e4eebb7f4060284b2e2b1fc5c45384cf', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 111, 'avg_line_length': 32.87323943661972, 'alnum_prop': 0.739502999143102, 'repo_name': 'weiwenqiang/GitHub', 'id': '9099bb4ce3241eed612cadfca0c3d99740f48da5', 'size': '3052', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Update/tinker-master/tinker-sample-android/app/src/main/java/tinker/sample/android/reporter/SamplePatchReporter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '87'}, {'name': 'C', 'bytes': '42062'}, {'name': 'C++', 'bytes': '12137'}, {'name': 'CMake', 'bytes': '202'}, {'name': 'CSS', 'bytes': '75087'}, {'name': 'Clojure', 'bytes': '12036'}, {'name': 'FreeMarker', 'bytes': '21704'}, {'name': 'Groovy', 'bytes': '55083'}, {'name': 'HTML', 'bytes': '61549'}, {'name': 'Java', 'bytes': '42222825'}, {'name': 'JavaScript', 'bytes': '216823'}, {'name': 'Kotlin', 'bytes': '24319'}, {'name': 'Makefile', 'bytes': '19490'}, {'name': 'Perl', 'bytes': '280'}, {'name': 'Prolog', 'bytes': '1030'}, {'name': 'Python', 'bytes': '13032'}, {'name': 'Scala', 'bytes': '310450'}, {'name': 'Shell', 'bytes': '27802'}]} |
<?php
class update_model extends CI_Model{
// Function To Fetch All Record
function show_users(){
$query = $this->db->get('users');
$query_result = $query->result();
return $query_result;
}
// Function To Fetch Selected Record
function show_user_id($data){
$this->db->select('*');
$this->db->from('users');
$this->db->where('user_id', $data);
$query = $this->db->get();
$result = $query->result();
return $result;
}
// Update Query For Selected User
function update_user_id1($id,$data){
echo $id;
$this->db->where('user_id', $id);
$this->db->update('users', $data);
}
}
?>
| {'content_hash': '582bf80ef1d2ec3509f91f1b9ae3f198', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 36, 'avg_line_length': 22.115384615384617, 'alnum_prop': 0.648695652173913, 'repo_name': 'bfcarter/CodeIgniter-2', 'id': '8d6431fd5a4e45c2a41f3e08aaf800cdf2fefdcc', 'size': '575', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/models/update_model.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '240'}, {'name': 'CSS', 'bytes': '159607'}, {'name': 'HTML', 'bytes': '5401297'}, {'name': 'JavaScript', 'bytes': '84909'}, {'name': 'PHP', 'bytes': '2002882'}]} |
install the **stats** app
```pycon
pip install -e git+https://github.com/buildingenergy/seed_demo_app.git#egg=seed_demo_app
```
add `stats` to your Django setting's `INSTALLED_APPS`:
```py
INSTALLED_APPS += ('stats',)
```
add `stats` to your url routes:
```py
url(r'stats/', include('stats.urls', app_name='stats')),
```
go to `/stats/` in your browser...
that's it!

| {'content_hash': 'f109eee10af4332ddeba8e26061df177', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 88, 'avg_line_length': 15.615384615384615, 'alnum_prop': 0.6527093596059114, 'repo_name': 'buildingenergy/buildingenergy-platform', 'id': '613705291d15bb740992d4023966c5c4be3eab31', 'size': '436', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'samples/demo_app/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '41308'}, {'name': 'JavaScript', 'bytes': '410448'}, {'name': 'Python', 'bytes': '2737347'}, {'name': 'Shell', 'bytes': '12179'}]} |
#include <aws/s3-crt/model/GetObjectResult.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::S3Crt::Model;
using namespace Aws::Utils::Stream;
using namespace Aws::Utils;
using namespace Aws;
GetObjectResult::GetObjectResult() :
m_deleteMarker(false),
m_contentLength(0),
m_missingMeta(0),
m_serverSideEncryption(ServerSideEncryption::NOT_SET),
m_bucketKeyEnabled(false),
m_storageClass(StorageClass::NOT_SET),
m_requestCharged(RequestCharged::NOT_SET),
m_replicationStatus(ReplicationStatus::NOT_SET),
m_partsCount(0),
m_tagCount(0),
m_objectLockMode(ObjectLockMode::NOT_SET),
m_objectLockLegalHoldStatus(ObjectLockLegalHoldStatus::NOT_SET)
{
}
GetObjectResult::GetObjectResult(GetObjectResult&& toMove) :
m_body(std::move(toMove.m_body)),
m_deleteMarker(toMove.m_deleteMarker),
m_acceptRanges(std::move(toMove.m_acceptRanges)),
m_expiration(std::move(toMove.m_expiration)),
m_restore(std::move(toMove.m_restore)),
m_lastModified(std::move(toMove.m_lastModified)),
m_contentLength(toMove.m_contentLength),
m_eTag(std::move(toMove.m_eTag)),
m_checksumCRC32(std::move(toMove.m_checksumCRC32)),
m_checksumCRC32C(std::move(toMove.m_checksumCRC32C)),
m_checksumSHA1(std::move(toMove.m_checksumSHA1)),
m_checksumSHA256(std::move(toMove.m_checksumSHA256)),
m_missingMeta(toMove.m_missingMeta),
m_versionId(std::move(toMove.m_versionId)),
m_cacheControl(std::move(toMove.m_cacheControl)),
m_contentDisposition(std::move(toMove.m_contentDisposition)),
m_contentEncoding(std::move(toMove.m_contentEncoding)),
m_contentLanguage(std::move(toMove.m_contentLanguage)),
m_contentRange(std::move(toMove.m_contentRange)),
m_contentType(std::move(toMove.m_contentType)),
m_expires(std::move(toMove.m_expires)),
m_websiteRedirectLocation(std::move(toMove.m_websiteRedirectLocation)),
m_serverSideEncryption(toMove.m_serverSideEncryption),
m_metadata(std::move(toMove.m_metadata)),
m_sSECustomerAlgorithm(std::move(toMove.m_sSECustomerAlgorithm)),
m_sSECustomerKeyMD5(std::move(toMove.m_sSECustomerKeyMD5)),
m_sSEKMSKeyId(std::move(toMove.m_sSEKMSKeyId)),
m_bucketKeyEnabled(toMove.m_bucketKeyEnabled),
m_storageClass(toMove.m_storageClass),
m_requestCharged(toMove.m_requestCharged),
m_replicationStatus(toMove.m_replicationStatus),
m_partsCount(toMove.m_partsCount),
m_tagCount(toMove.m_tagCount),
m_objectLockMode(toMove.m_objectLockMode),
m_objectLockRetainUntilDate(std::move(toMove.m_objectLockRetainUntilDate)),
m_objectLockLegalHoldStatus(toMove.m_objectLockLegalHoldStatus),
m_id2(std::move(toMove.m_id2)),
m_requestId(std::move(toMove.m_requestId))
{
}
GetObjectResult& GetObjectResult::operator=(GetObjectResult&& toMove)
{
if(this == &toMove)
{
return *this;
}
m_body = std::move(toMove.m_body);
m_deleteMarker = toMove.m_deleteMarker;
m_acceptRanges = std::move(toMove.m_acceptRanges);
m_expiration = std::move(toMove.m_expiration);
m_restore = std::move(toMove.m_restore);
m_lastModified = std::move(toMove.m_lastModified);
m_contentLength = toMove.m_contentLength;
m_eTag = std::move(toMove.m_eTag);
m_checksumCRC32 = std::move(toMove.m_checksumCRC32);
m_checksumCRC32C = std::move(toMove.m_checksumCRC32C);
m_checksumSHA1 = std::move(toMove.m_checksumSHA1);
m_checksumSHA256 = std::move(toMove.m_checksumSHA256);
m_missingMeta = toMove.m_missingMeta;
m_versionId = std::move(toMove.m_versionId);
m_cacheControl = std::move(toMove.m_cacheControl);
m_contentDisposition = std::move(toMove.m_contentDisposition);
m_contentEncoding = std::move(toMove.m_contentEncoding);
m_contentLanguage = std::move(toMove.m_contentLanguage);
m_contentRange = std::move(toMove.m_contentRange);
m_contentType = std::move(toMove.m_contentType);
m_expires = std::move(toMove.m_expires);
m_websiteRedirectLocation = std::move(toMove.m_websiteRedirectLocation);
m_serverSideEncryption = toMove.m_serverSideEncryption;
m_metadata = std::move(toMove.m_metadata);
m_sSECustomerAlgorithm = std::move(toMove.m_sSECustomerAlgorithm);
m_sSECustomerKeyMD5 = std::move(toMove.m_sSECustomerKeyMD5);
m_sSEKMSKeyId = std::move(toMove.m_sSEKMSKeyId);
m_bucketKeyEnabled = toMove.m_bucketKeyEnabled;
m_storageClass = toMove.m_storageClass;
m_requestCharged = toMove.m_requestCharged;
m_replicationStatus = toMove.m_replicationStatus;
m_partsCount = toMove.m_partsCount;
m_tagCount = toMove.m_tagCount;
m_objectLockMode = toMove.m_objectLockMode;
m_objectLockRetainUntilDate = std::move(toMove.m_objectLockRetainUntilDate);
m_objectLockLegalHoldStatus = toMove.m_objectLockLegalHoldStatus;
m_id2 = std::move(toMove.m_id2);
m_requestId = std::move(toMove.m_requestId);
return *this;
}
GetObjectResult::GetObjectResult(Aws::AmazonWebServiceResult<ResponseStream>&& result) :
m_deleteMarker(false),
m_contentLength(0),
m_missingMeta(0),
m_serverSideEncryption(ServerSideEncryption::NOT_SET),
m_bucketKeyEnabled(false),
m_storageClass(StorageClass::NOT_SET),
m_requestCharged(RequestCharged::NOT_SET),
m_replicationStatus(ReplicationStatus::NOT_SET),
m_partsCount(0),
m_tagCount(0),
m_objectLockMode(ObjectLockMode::NOT_SET),
m_objectLockLegalHoldStatus(ObjectLockLegalHoldStatus::NOT_SET)
{
*this = std::move(result);
}
GetObjectResult& GetObjectResult::operator =(Aws::AmazonWebServiceResult<ResponseStream>&& result)
{
m_body = result.TakeOwnershipOfPayload();
const auto& headers = result.GetHeaderValueCollection();
const auto& deleteMarkerIter = headers.find("x-amz-delete-marker");
if(deleteMarkerIter != headers.end())
{
m_deleteMarker = StringUtils::ConvertToBool(deleteMarkerIter->second.c_str());
}
const auto& acceptRangesIter = headers.find("accept-ranges");
if(acceptRangesIter != headers.end())
{
m_acceptRanges = acceptRangesIter->second;
}
const auto& expirationIter = headers.find("x-amz-expiration");
if(expirationIter != headers.end())
{
m_expiration = expirationIter->second;
}
const auto& restoreIter = headers.find("x-amz-restore");
if(restoreIter != headers.end())
{
m_restore = restoreIter->second;
}
const auto& lastModifiedIter = headers.find("last-modified");
if(lastModifiedIter != headers.end())
{
m_lastModified = DateTime(lastModifiedIter->second, DateFormat::RFC822);
}
const auto& contentLengthIter = headers.find("content-length");
if(contentLengthIter != headers.end())
{
m_contentLength = StringUtils::ConvertToInt64(contentLengthIter->second.c_str());
}
const auto& eTagIter = headers.find("etag");
if(eTagIter != headers.end())
{
m_eTag = eTagIter->second;
}
const auto& checksumCRC32Iter = headers.find("x-amz-checksum-crc32");
if(checksumCRC32Iter != headers.end())
{
m_checksumCRC32 = checksumCRC32Iter->second;
}
const auto& checksumCRC32CIter = headers.find("x-amz-checksum-crc32c");
if(checksumCRC32CIter != headers.end())
{
m_checksumCRC32C = checksumCRC32CIter->second;
}
const auto& checksumSHA1Iter = headers.find("x-amz-checksum-sha1");
if(checksumSHA1Iter != headers.end())
{
m_checksumSHA1 = checksumSHA1Iter->second;
}
const auto& checksumSHA256Iter = headers.find("x-amz-checksum-sha256");
if(checksumSHA256Iter != headers.end())
{
m_checksumSHA256 = checksumSHA256Iter->second;
}
const auto& missingMetaIter = headers.find("x-amz-missing-meta");
if(missingMetaIter != headers.end())
{
m_missingMeta = StringUtils::ConvertToInt32(missingMetaIter->second.c_str());
}
const auto& versionIdIter = headers.find("x-amz-version-id");
if(versionIdIter != headers.end())
{
m_versionId = versionIdIter->second;
}
const auto& cacheControlIter = headers.find("cache-control");
if(cacheControlIter != headers.end())
{
m_cacheControl = cacheControlIter->second;
}
const auto& contentDispositionIter = headers.find("content-disposition");
if(contentDispositionIter != headers.end())
{
m_contentDisposition = contentDispositionIter->second;
}
const auto& contentEncodingIter = headers.find("content-encoding");
if(contentEncodingIter != headers.end())
{
m_contentEncoding = contentEncodingIter->second;
}
const auto& contentLanguageIter = headers.find("content-language");
if(contentLanguageIter != headers.end())
{
m_contentLanguage = contentLanguageIter->second;
}
const auto& contentRangeIter = headers.find("content-range");
if(contentRangeIter != headers.end())
{
m_contentRange = contentRangeIter->second;
}
const auto& contentTypeIter = headers.find("content-type");
if(contentTypeIter != headers.end())
{
m_contentType = contentTypeIter->second;
}
const auto& expiresIter = headers.find("expires");
if(expiresIter != headers.end())
{
m_expires = DateTime(expiresIter->second, DateFormat::RFC822);
}
const auto& websiteRedirectLocationIter = headers.find("x-amz-website-redirect-location");
if(websiteRedirectLocationIter != headers.end())
{
m_websiteRedirectLocation = websiteRedirectLocationIter->second;
}
const auto& serverSideEncryptionIter = headers.find("x-amz-server-side-encryption");
if(serverSideEncryptionIter != headers.end())
{
m_serverSideEncryption = ServerSideEncryptionMapper::GetServerSideEncryptionForName(serverSideEncryptionIter->second);
}
std::size_t prefixSize = sizeof("x-amz-meta-") - 1; //subtract the NULL terminator out
for(const auto& item : headers)
{
std::size_t foundPrefix = item.first.find("x-amz-meta-");
if(foundPrefix != std::string::npos)
{
m_metadata[item.first.substr(prefixSize)] = item.second;
}
}
const auto& sSECustomerAlgorithmIter = headers.find("x-amz-server-side-encryption-customer-algorithm");
if(sSECustomerAlgorithmIter != headers.end())
{
m_sSECustomerAlgorithm = sSECustomerAlgorithmIter->second;
}
const auto& sSECustomerKeyMD5Iter = headers.find("x-amz-server-side-encryption-customer-key-md5");
if(sSECustomerKeyMD5Iter != headers.end())
{
m_sSECustomerKeyMD5 = sSECustomerKeyMD5Iter->second;
}
const auto& sSEKMSKeyIdIter = headers.find("x-amz-server-side-encryption-aws-kms-key-id");
if(sSEKMSKeyIdIter != headers.end())
{
m_sSEKMSKeyId = sSEKMSKeyIdIter->second;
}
const auto& bucketKeyEnabledIter = headers.find("x-amz-server-side-encryption-bucket-key-enabled");
if(bucketKeyEnabledIter != headers.end())
{
m_bucketKeyEnabled = StringUtils::ConvertToBool(bucketKeyEnabledIter->second.c_str());
}
const auto& storageClassIter = headers.find("x-amz-storage-class");
if(storageClassIter != headers.end())
{
m_storageClass = StorageClassMapper::GetStorageClassForName(storageClassIter->second);
}
const auto& requestChargedIter = headers.find("x-amz-request-charged");
if(requestChargedIter != headers.end())
{
m_requestCharged = RequestChargedMapper::GetRequestChargedForName(requestChargedIter->second);
}
const auto& replicationStatusIter = headers.find("x-amz-replication-status");
if(replicationStatusIter != headers.end())
{
m_replicationStatus = ReplicationStatusMapper::GetReplicationStatusForName(replicationStatusIter->second);
}
const auto& partsCountIter = headers.find("x-amz-mp-parts-count");
if(partsCountIter != headers.end())
{
m_partsCount = StringUtils::ConvertToInt32(partsCountIter->second.c_str());
}
const auto& tagCountIter = headers.find("x-amz-tagging-count");
if(tagCountIter != headers.end())
{
m_tagCount = StringUtils::ConvertToInt32(tagCountIter->second.c_str());
}
const auto& objectLockModeIter = headers.find("x-amz-object-lock-mode");
if(objectLockModeIter != headers.end())
{
m_objectLockMode = ObjectLockModeMapper::GetObjectLockModeForName(objectLockModeIter->second);
}
const auto& objectLockRetainUntilDateIter = headers.find("x-amz-object-lock-retain-until-date");
if(objectLockRetainUntilDateIter != headers.end())
{
m_objectLockRetainUntilDate = DateTime(objectLockRetainUntilDateIter->second, DateFormat::ISO_8601);
}
const auto& objectLockLegalHoldStatusIter = headers.find("x-amz-object-lock-legal-hold");
if(objectLockLegalHoldStatusIter != headers.end())
{
m_objectLockLegalHoldStatus = ObjectLockLegalHoldStatusMapper::GetObjectLockLegalHoldStatusForName(objectLockLegalHoldStatusIter->second);
}
const auto& id2Iter = headers.find("x-amz-id-2");
if(id2Iter != headers.end())
{
m_id2 = id2Iter->second;
}
const auto& requestIdIter = headers.find("x-amz-request-id");
if(requestIdIter != headers.end())
{
m_requestId = requestIdIter->second;
}
return *this;
}
| {'content_hash': '87a4d8e8b1be8db519976517c634391a', 'timestamp': '', 'source': 'github', 'line_count': 373, 'max_line_length': 142, 'avg_line_length': 34.9946380697051, 'alnum_prop': 0.7245843867310197, 'repo_name': 'cedral/aws-sdk-cpp', 'id': '935dfc06c35e3e3465260cdcd5dfd97e9e4cd172', 'size': '13172', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-s3-crt/source/model/GetObjectResult.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '294220'}, {'name': 'C++', 'bytes': '428637022'}, {'name': 'CMake', 'bytes': '862025'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '7904'}, {'name': 'Java', 'bytes': '352201'}, {'name': 'Python', 'bytes': '106761'}, {'name': 'Shell', 'bytes': '10891'}]} |
if(!dojo._hasResource["dojox.data.tests.stores.QueryReadStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.data.tests.stores.QueryReadStore"] = true;
dojo.provide("dojox.data.tests.stores.QueryReadStore");
dojo.require("dojox.data.QueryReadStore");
dojo.require("dojo.data.api.Read");
//dojo.require("dojox.testing.DocTest");
dojox.data.tests.stores.QueryReadStore.getStore = function(){
return new dojox.data.QueryReadStore({
url: dojo.moduleUrl("dojox.data.tests", "stores/QueryReadStore.php").toString()
});
};
tests.register("dojox.data.tests.stores.QueryReadStore",
[
/*
function testDocTests(t) {
// summary:
// Run all the doc comments.
var doctest = new dojox.testing.DocTest();
doctest.run("dojox.data.QueryReadStore");
t.assertTrue(doctest.errors.length==0);
},
*/
function testReadApi_getValue(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
// The good cases.
t.assertEqual("Alabama", store.getValue(item, "name"));
t.assertEqual("<img src='images/Alabama.jpg'/>Alabama", store.getValue(item, "label"));
t.assertEqual("AL", store.getValue(item, "abbreviation"));
// Test the defaultValue cases (the third paramter).
t.assertEqual("default value", store.getValue(item, "NAME", "default value"));
// TODO Test for null somehow ...
// Read api says: Returns null if and only if null was explicitly set as the attribute value.
// According to Read-API getValue() an exception is thrown when
// the item is not an item or when the attribute is not a string.
t.assertError(Error, store, "getValue", ["not an item", "NOT THERE"]);
t.assertError(Error, store, "getValue", [item, {}]);
d.callback(true);
}
store.fetch({query:{q:"Alabama"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_getValues(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
// The good cases.
t.assertEqual(["Alabama"], store.getValues(item, "name"));
t.assertEqual(["<img src='images/Alabama.jpg'/>Alabama"], store.getValues(item, "label"));
t.assertEqual(["AL"], store.getValues(item, "abbreviation"));
// TODO Test for null somehow ...
// Read api says: Returns null if and only if null was explicitly set as the attribute value.
// Test for not-existing attributes without defaultValues and invalid items.
// TODO
t.assertEqual([], store.getValues(item, "NOT THERE"));
var errThrown = false;
try{
//Should throw an exception.
var values = store.getValues("not an item", "NOT THERE");
}catch (e){
errThrown = true;
}
t.assertTrue(errThrown);
d.callback(true);
}
store.fetch({query:{q:"Alabama"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_getAttributes(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
// The good case(s).
t.assertEqual(['id', 'name', 'label', 'abbreviation', 'capital'], store.getAttributes(item));
t.assertError(Error, store, "getAttributes", [{}]);
d.callback(true);
}
store.fetch({query:{q:"Alabama"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_getLabel(t){
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
// The good cases.
t.assertEqual(["<img src='images/Alabama.jpg'/>Alabama"], store.getLabel(item));
d.callback(true);
}
store.fetch({query:{q:"Alabama"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_hasAttribute(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
// The positive cases.
t.assertEqual(true, store.hasAttribute(item, "name"));
t.assertEqual(true, store.hasAttribute(item, "label"));
t.assertEqual(true, store.hasAttribute(item, "abbreviation"));
// Make sure attribute case doesnt matter.
t.assertEqual(false, store.hasAttribute(item, "NAME"));
t.assertEqual(false, store.hasAttribute(item, "Name"));
t.assertEqual(false, store.hasAttribute(item, "Label"));
// Pass in an invalid item.
t.assertEqual(false, store.hasAttribute({}, "abbreviation"));
// pass in something that looks like the item with the attribute.
t.assertEqual(false, store.hasAttribute({name:"yo"}, "name"));
d.callback(true);
}
store.fetch({query:{q:"Alaska"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_containsValue(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
t.assertTrue(store.containsValue(item, "name", "Alaska"));
d.callback(true);
}
store.fetch({query:{q:"Alaska"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_isItem(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
// The good case.
t.assertEqual(true, store.isItem(items[0]));
// Try a pure object.
t.assertEqual(false, store.isItem({}));
// Try to look like an item.
t.assertEqual(false, store.isItem({name:"Alaska", label:"Alaska", abbreviation:"AK"}));
d.callback(true);
}
store.fetch({query:{q:"Alaska"}, onComplete: onComplete});
return d; //Object
},
function testReadApi_isItemLoaded(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
var item = items[0];
// The good case(s).
t.assertTrue(store.isItemLoaded(item));
d.callback(true);
}
store.fetch({query:{q:"Alabama"}, onComplete: onComplete});
return d; //Object
},
//function testReadApi_loadItem(t){
// // summary:
// // description:
// t.assertTrue(false);
//},
function testReadApi_fetch_all(t){
// summary:
// Simple test of fetching all items.
// description:
// Simple test of fetching all items.
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request) {
t.assertEqual(12, items.length);
d.callback(true);
}
function onError(error, request) {
d.errback(error);
}
store.fetch({query:{q:"m"}, onComplete: onComplete, onError: onError});
return d; //Object
},
function testReadApi_fetch_onBegin(t){
// summary:
// Simple test of fetching items, checking that onBegin size is all items matched, and page is just the items asked for.
// description:
// Simple test of fetching items, checking that onBegin size is all items matched, and page is just the items asked for.
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
var passed = false;
function onBegin(size, request){
t.assertEqual(12, size);
passed = true;
}
function onComplete(items, request) {
t.assertEqual(5, items.length);
if(passed){
d.callback(true);
}else{
d.errback(new Error("Store did not return proper number of rows, regardless of page size"));
}
}
function onError(error, request) {
d.errback(error);
}
store.fetch({query:{q:"m"}, start: 0, count: 5, onBegin: onBegin, onComplete: onComplete, onError: onError});
return d; //Object
},
function testReadApi_fetch_onBegin_ServersidePaging(t){
// summary:
// Simple test of fetching items, checking that onBegin size is all items matched, and page is just the items asked for.
// description:
// Simple test of fetching items, checking that onBegin size is all items matched, and page is just the items asked for.
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
var passed = false;
function onBegin(size, request){
t.assertEqual(12, size);
passed = true;
}
function onComplete(items, request) {
t.assertEqual(5, items.length);
if(passed){
d.callback(true);
}else{
d.errback(new Error("Store did not return proper number of rows, regardless of page size"));
}
}
function onError(error, request) {
d.errback(error);
}
store.fetch({query:{q:"m"}, start: 5, count: 5, onBegin: onBegin, onComplete: onComplete, onError: onError});
return d; //Object
},
function testReadApi_fetch_onBegin_ClientsidePaging(t){
// summary:
// Simple test of fetching items, checking that onBegin size is all items matched, and page is just the items asked for.
// description:
// Simple test of fetching items, checking that onBegin size is all items matched, and page is just the items asked for.
var store = dojox.data.tests.stores.QueryReadStore.getStore();
store.doClientPaging = true;
var d = new doh.Deferred();
var passed = false;
function onBegin(size, request){
t.assertEqual(12, size);
passed = true;
}
function onComplete(items, request) {
t.assertEqual(5, items.length);
if(passed){
d.callback(true);
}else{
d.errback(new Error("Store did not return proper number of rows, regardless of page size"));
}
}
function onError(error, request) {
d.errback(error);
}
store.fetch({query:{q:"m"}, start: 0, count: 5, onBegin: onBegin, onComplete: onComplete, onError: onError});
return d; //Object
},
function testReadApi_fetch_one(t){
// summary:
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var d = new doh.Deferred();
function onComplete(items, request){
t.assertEqual(1, items.length);
d.callback(true);
}
function onError(error, request) {
d.errback(error);
}
store.fetch({query:{q:"Alaska"}, onComplete: onComplete, onError: onError});
return d; //Object
},
function testReadApi_fetch_client_paging(t){
// summary:
// Lets test that paging on the same request does not trigger
// server requests.
// description:
var store = dojox.data.tests.stores.QueryReadStore.getStore();
store.doClientPaging = true;
var lastRequestHash = null;
var firstItems = [];
var d = new doh.Deferred();
function onComplete(items, request) {
t.assertEqual(5, items.length);
lastRequestHash = store.lastRequestHash;
firstItems = items;
// Do the next request AFTER the previous one, so we are sure its sequential.
// We need to be sure so we can compare to the data from the first request.
function onComplete1(items, request) {
t.assertEqual(5, items.length);
t.assertEqual(lastRequestHash, store.lastRequestHash);
t.assertEqual(firstItems[1], items[0]);
d.callback(true);
}
req.start = 1;
req.onComplete = onComplete1;
store.fetch(req);
}
function onError(error, request) {
d.errback(error);
}
var req = {query:{q:"m"}, start:0, count:5,
onComplete: onComplete, onError: onError};
store.fetch(req);
return d; //Object
},
function testReadApi_fetch_server_paging(t) {
// Verify that the paging on the server side does work.
// This is the test for http://trac.dojotoolkit.org/ticket/4761
//
// How? We request 10 items from the server, start=0, count=10.
// The second request requests 5 items: start=5, count=5 and those
// 5 items should have the same values as the last 5 of the first
// request.
// This tests if the server side paging does work.
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var lastRequestHash = null;
var d = new doh.Deferred();
function onComplete(items, request) {
t.assertEqual(10, items.length);
lastRequestHash = store.lastRequestHash;
firstItems = items;
// Do the next request AFTER the previous one, so we are sure its sequential.
// We need to be sure so we can compare to the data from the first request.
function onComplete1(items, request) {
t.assertEqual(5, items.length);
// Compare the hash of the last request, they must be different,
// since another server request was issued.
t.assertTrue(lastRequestHash!=store.lastRequestHash);
t.assertEqual(store.getValue(firstItems[5], "name"), store.getValue(items[0], "name"));
t.assertEqual(store.getValue(firstItems[6], "name"), store.getValue(items[1], "name"));
t.assertEqual(store.getValue(firstItems[7], "name"), store.getValue(items[2], "name"));
t.assertEqual(store.getValue(firstItems[8], "name"), store.getValue(items[3], "name"));
t.assertEqual(store.getValue(firstItems[9], "name"), store.getValue(items[4], "name"));
d.callback(true);
}
// Init a new store, or it will use the old data, since the query has not changed.
store.doClientPaging = false;
store.fetch({start:5, count:5, onComplete: onComplete1, onError: onError});
}
function onError(error, request) {
d.errback(error);
}
store.fetch({query:{}, start:0, count:10, onComplete: onComplete, onError: onError});
return d; //Object
},
function testReadApi_getFeatures(t) {
var store = dojox.data.tests.stores.QueryReadStore.getStore();
var features = store.getFeatures();
t.assertTrue(features["dojo.data.api.Read"]);
t.assertTrue(features["dojo.data.api.Identity"]);
var count = 0;
for (i in features){
count++;
}
t.assertEqual(2, count);
},
function testReadAPI_functionConformance(t){
// summary:
// Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.
// description:
// Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.
var testStore = dojox.data.tests.stores.QueryReadStore.getStore();
var readApi = new dojo.data.api.Read();
var passed = true;
for(i in readApi){
var member = readApi[i];
//Check that all the 'Read' defined functions exist on the test store.
if(typeof member === "function"){
var testStoreMember = testStore[i];
if(!(typeof testStoreMember === "function")){
console.log("Problem with function: [" + i + "]");
passed = false;
break;
}
}
}
t.assertTrue(passed);
}
]
);
}
| {'content_hash': '413e99f484d4a71e579f538b36718f88', 'timestamp': '', 'source': 'github', 'line_count': 442, 'max_line_length': 150, 'avg_line_length': 35.13574660633484, 'alnum_prop': 0.6446877012234385, 'repo_name': 'feklee/rotogame', 'id': '981f1a25a449c612e3eafbac7842fb713590d5e9', 'size': '15530', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/dojo-release-1.3.0-src/release/dojo/dojox/data/tests/stores/QueryReadStore.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ActionScript', 'bytes': '42638'}, {'name': 'Batchfile', 'bytes': '864'}, {'name': 'CSS', 'bytes': '565560'}, {'name': 'HTML', 'bytes': '5871151'}, {'name': 'Java', 'bytes': '135293'}, {'name': 'JavaScript', 'bytes': '9667358'}, {'name': 'PHP', 'bytes': '776671'}, {'name': 'PostScript', 'bytes': '687211'}, {'name': 'Python', 'bytes': '34768'}, {'name': 'Shell', 'bytes': '10872'}, {'name': 'XSLT', 'bytes': '62061'}]} |
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
/**
* Exception thrown when a {@code BeanFactory} is asked for a bean instance for which it
* cannot find a definition. This may point to a non-existing bean, a non-unique bean,
* or a manually registered singleton instance without an associated bean definition.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Stephane Nicoll
* @see BeanFactory#getBean(String)
* @see BeanFactory#getBean(Class)
* @see NoUniqueBeanDefinitionException
*/
@SuppressWarnings("serial")
public class NoSuchBeanDefinitionException extends BeansException {
private String beanName;
private ResolvableType resolvableType;
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param name the name of the missing bean
*/
public NoSuchBeanDefinitionException(String name) {
super("No bean named '" + name + "' available");
this.beanName = name;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param name the name of the missing bean
* @param message detailed message describing the problem
*/
public NoSuchBeanDefinitionException(String name, String message) {
super("No bean named '" + name + "' available: " + message);
this.beanName = name;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type required type of the missing bean
*/
public NoSuchBeanDefinitionException(Class<?> type) {
this(ResolvableType.forClass(type));
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type required type of the missing bean
* @param message detailed message describing the problem
*/
public NoSuchBeanDefinitionException(Class<?> type, String message) {
this(ResolvableType.forClass(type), message);
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type full type declaration of the missing bean
* @since 4.3.4
*/
public NoSuchBeanDefinitionException(ResolvableType type) {
super("No qualifying bean of type '" + type + "' available");
this.resolvableType = type;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type full type declaration of the missing bean
* @param message detailed message describing the problem
* @since 4.3.4
*/
public NoSuchBeanDefinitionException(ResolvableType type, String message) {
super("No qualifying bean of type '" + type + "' available: " + message);
this.resolvableType = type;
}
/**
* Return the name of the missing bean, if it was a lookup <em>by name</em> that failed.
*/
public String getBeanName() {
return this.beanName;
}
/**
* Return the required type of the missing bean, if it was a lookup <em>by type</em>
* that failed.
*/
public Class<?> getBeanType() {
return (this.resolvableType != null ? this.resolvableType.getRawClass() : null);
}
/**
* Return the required {@link ResolvableType} of the missing bean, if it was a lookup
* <em>by type</em> that failed.
* @since 4.3.4
*/
public ResolvableType getResolvableType() {
return this.resolvableType;
}
/**
* Return the number of beans found when only one matching bean was expected.
* For a regular NoSuchBeanDefinitionException, this will always be 0.
* @see NoUniqueBeanDefinitionException
*/
public int getNumberOfBeansFound() {
return 0;
}
}
| {'content_hash': '099c66ac8bf51213d2f6ccee3a9a9c59', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 89, 'avg_line_length': 28.747899159663866, 'alnum_prop': 0.7214264834843613, 'repo_name': 'boggad/jdk9-sample', 'id': '413282f7e8e4cfd9753d81dbf3bdfd608f102554', 'size': '4041', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sample-catalog/spring-jdk9/src/spring.beans/org/springframework/beans/factory/NoSuchBeanDefinitionException.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AspectJ', 'bytes': '32336'}, {'name': 'HTML', 'bytes': '124863'}, {'name': 'Java', 'bytes': '30303872'}, {'name': 'Makefile', 'bytes': '1069'}, {'name': 'Standard ML', 'bytes': '119878'}, {'name': 'XSLT', 'bytes': '16226'}]} |
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
</style>
<style name="BaseTextView">
</style>
<style name="TitleTextView" parent="BaseTextView">
<item name="android:textColor">@color/title_textView</item>
<item name="android:textSize">@dimen/title_textView</item>
</style>
<style name="WordTextView" parent="BaseTextView">
<item name="android:textColor">@color/word_textView</item>
<item name="android:textSize">@dimen/word_textView</item>
</style>
<style name="HintTextView" parent="WordTextView">
<item name="android:textColor">@color/hint_textView</item>
</style>
<style name="BaseMenuTextView" parent="BaseTextView">
</style>
<style name="menu_edit" parent="BaseMenuTextView">
<item name="android:textColor">@color/theme_color_edit_button_list</item>
<item name="android:textSize">@dimen/menu_edit_textVew</item>
</style>
<style name="menu_list_item_text" parent="BaseMenuTextView">
<item name="android:textColor">@color/theme_color_white</item>
<item name="android:textSize">@dimen/menu_list_item_text_size</item>
</style>
<style name="BaseListView"/>
<style name="DrawerListView" parent="BaseMenuTextView">
<item name="android:divider">@color/theme_color_text_list</item>
<item name="android:dividerHeight">@dimen/menu_list_item_divider_height</item>
</style>
</resources>
| {'content_hash': '7a9ce4a6d2be08d8b333ea7425ca9ec6', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 86, 'avg_line_length': 37.75609756097561, 'alnum_prop': 0.6550387596899225, 'repo_name': 'LionelCursor/GreenDict', 'id': '36b6975b1154aaae334d57f097dd76b367e62fac', 'size': '1548', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/values/styles.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '230660'}]} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Cat. Lich. Univers. 4: 138 (1926)
#### Original name
Lecidea redepta Stirt.
### Remarks
null | {'content_hash': 'b11fa1b84a4f6573c61286d61e4c5d5e', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 33, 'avg_line_length': 12.0, 'alnum_prop': 0.6858974358974359, 'repo_name': 'mdoering/backbone', 'id': '1f23faeaf9cd1e8b1b4fe879992ef52a532f2099', 'size': '212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Bacidia/Bacidia redepta/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
/**
* Created by cmeyers on 10/21/16.
*/
/**
* Models a SCM Provider (e.g. Git, Github, GitHub Enterprise) used in 'Create Pipeline' flow.
* Extend this class and implement methods to provide an implementation.
*/
export default class ScmProvider {
/**
* Return a React element (button) that when selected will start the "creation flow"
* Call props.onSelect to initiate the creation flow.
*/
getDefaultOption() {
throw new Error('must implement getDefaultOption');
}
/**
* Return a FlowManager subclass which will return the initial step to begin.
*/
getFlowManager() {
throw new Error('must implement getFlowManager');
}
/**
* Called when the related creation flow is about to exit.
* Similar to React's componentWillUnmount, perform cleanup of event listeners, timers, etc.
*/
destroyFlowManager() {
throw new Error('must implement destroyFlowManager');
}
}
| {'content_hash': '4628fb1eaaf5fc1b193f16c502c73e61', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 96, 'avg_line_length': 30.28125, 'alnum_prop': 0.6635706914344686, 'repo_name': 'jenkinsci/blueocean-plugin', 'id': '606dea7275ea8c79c1ef62d66904082c6daf45ef', 'size': '969', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'blueocean-dashboard/src/main/js/creation/ScmProvider.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1464'}, {'name': 'Dockerfile', 'bytes': '1808'}, {'name': 'EJS', 'bytes': '3816'}, {'name': 'Groovy', 'bytes': '18426'}, {'name': 'HTML', 'bytes': '11925'}, {'name': 'Java', 'bytes': '2571450'}, {'name': 'JavaScript', 'bytes': '2502482'}, {'name': 'Less', 'bytes': '210023'}, {'name': 'Scala', 'bytes': '527'}, {'name': 'Shell', 'bytes': '25109'}, {'name': 'TypeScript', 'bytes': '106651'}]} |
namespace g{namespace Uno{struct ObjectDisposedException;}}
namespace g{
namespace Uno{
// public sealed class ObjectDisposedException :287
// {
::g::Uno::Exception_type* ObjectDisposedException_typeof();
void ObjectDisposedException__ctor_3_fn(ObjectDisposedException* __this, uString* objectName);
void ObjectDisposedException__New4_fn(uString* objectName, ObjectDisposedException** __retval);
struct ObjectDisposedException : ::g::Uno::Exception
{
void ctor_3(uString* objectName);
static ObjectDisposedException* New4(uString* objectName);
};
// }
}} // ::g::Uno
| {'content_hash': '0532ff6a85b463b5486bc09063a1a16a', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 95, 'avg_line_length': 30.473684210526315, 'alnum_prop': 0.7616580310880829, 'repo_name': 'blyk/BlackCode-Fuse', 'id': 'f90e3c03047497bbd6443743a35562c2b35d703a', 'size': '796', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'Welcome/.build/Simulator/Android/include/Uno.ObjectDisposedException.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '31111'}, {'name': 'C', 'bytes': '22885804'}, {'name': 'C++', 'bytes': '197750292'}, {'name': 'Java', 'bytes': '951083'}, {'name': 'JavaScript', 'bytes': '578555'}, {'name': 'Logos', 'bytes': '48297'}, {'name': 'Makefile', 'bytes': '6592573'}, {'name': 'Shell', 'bytes': '19985'}]} |
package com.spectralogic.ds3autogen.python.generators.response;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class GetObjectResponseGenerator_Test {
private final static GetObjectResponseGenerator generator = new GetObjectResponseGenerator();
@Test
public void toParseResponsePayloadTest() {
final String expected = "stream = self.request.stream\n" +
" try:\n" +
" bytes_read = response.read(self.buffer_size)\n" +
" while bytes_read:\n" +
" stream.write(bytes_read)\n" +
" bytes_read = response.read(self.buffer_size)\n" +
" finally:\n" +
" stream.close()\n" +
" response.close()\n";
final String result = generator.toParseResponsePayload(null);
assertThat(result, is(expected));
}
@Test
public void toInitResponseTest() {
final String expected = "def __init__(self, response, request, buffer_size=None):\n" +
" self.buffer_size = buffer_size\n" +
" super(self.__class__, self).__init__(response, request)\n";
final String result = generator.toInitResponse();
assertThat(result, is(expected));
}
}
| {'content_hash': '05e22332e9ef12d7d7642f017e042c20', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 97, 'avg_line_length': 37.31578947368421, 'alnum_prop': 0.5627644569816643, 'repo_name': 'RachelTucker/ds3_autogen', 'id': 'c549ea10c9bbb04a89f71273e032bf339272854b', 'size': '2175', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ds3-autogen-python/src/test/java/com.spectralogic.ds3autogen.python/generators/response/GetObjectResponseGenerator_Test.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Fluent', 'bytes': '14817'}, {'name': 'FreeMarker', 'bytes': '213341'}, {'name': 'Java', 'bytes': '2709069'}, {'name': 'Kotlin', 'bytes': '192576'}]} |
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.val.ebtm.myiconnapp"
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="6"
android:versionName="Notario fix 1">
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.val.ebtm.view.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.val.ebtm.view.AjustesActivity"
android:label="Ajustes">
</activity>
<activity
android:name="com.val.ebtm.view.ShowPodcastsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_show_podcasts"
android:screenOrientation="portrait">
</activity>
<receiver
android:name="com.val.ebtm.reciver.AlarmaReciver"
android:enabled="true"
android:exported="true">
</receiver>
<service
android:name="com.val.ebtm.service.CheckNuevoPodcastDisponibleService"
android:enabled="true"
android:exported="true">
</service>
<receiver
android:name="com.val.ebtm.reciver.RestartAlarmaReciver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
| {'content_hash': '727837ab3631eb4b6f1285a2343b26cc', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 82, 'avg_line_length': 39.472972972972975, 'alnum_prop': 0.6425881547415269, 'repo_name': 'EstefaniaGilVaquero/ciceAndroid', 'id': '553383085c1fa93db2d89efd3cce5d93599677b0', 'size': '2921', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ElBoxeoTieneMusica/ElBoxeoTieneMusicaApp/app/src/main/AndroidManifest.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1333'}, {'name': 'Java', 'bytes': '819548'}]} |
namespace epseudo3d
{
Task::Task(wxFrame* parent)
: m_root(NULL)
, m_parent(parent)
{
InitLayout();
}
Task::~Task()
{
ee::SymbolMgr::Instance()->Clear();
delete m_root;
}
void Task::Load(const char* filename)
{
epseudo3d::StageCanvas3D* canvas = static_cast<epseudo3d::StageCanvas3D*>(m_stage->GetCanvas());
canvas->LoadScene(filename);
}
void Task::Store(const char* filename) const
{
epseudo3d::StageCanvas3D* canvas = static_cast<epseudo3d::StageCanvas3D*>(m_stage->GetCanvas());
canvas->StoreScene(filename);
}
bool Task::IsDirty() const
{
return false;
}
const ee::EditPanel* Task::GetEditPanel() const
{
return m_stage;
}
// void Task::InitLayout()
// {
// wxSplitterWindow* right_splitter = new wxSplitterWindow(m_parent);
// wxSplitterWindow* left_splitter = new wxSplitterWindow(right_splitter);
//
// m_library = new LibraryPanel(left_splitter);
// m_stage = new StagePanel(left_splitter, m_parent, m_library);
// m_library->SetCanvas(m_stage->getCanvas());
//
// left_splitter->SetSashGravity(0.2f);
// left_splitter->SplitVertically(m_library, m_stage);
//
// ToolbarPanel* toolbar = new ToolbarPanel(right_splitter, static_cast<StagePanel*>(m_stage));
// right_splitter->SetSashGravity(0.85f);
// right_splitter->SplitVertically(left_splitter, toolbar);
//
// m_root = right_splitter;
// }
void Task::InitLayout()
{
m_stage = new ee::EditPanel(m_parent, m_parent);
// m_stage->SetCanvas(std::make_shared<epseudo3d::StageCanvas3D>(m_stage));
// m_stage->setEditOP(std::make_shared<e3d::ControlCameraOP>(m_stage));
m_stage->SetCanvas(std::make_shared<epseudo3d::StageCanvas2D>(m_stage, m_stage->GetStageImpl()));
m_stage->SetEditOP(std::make_shared<epseudo3d::Proj2DEditOP>(m_stage, m_stage->GetStageImpl()));
}
} | {'content_hash': 'd5d317838cfcdc756e04b194ec1ef711', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 98, 'avg_line_length': 25.565217391304348, 'alnum_prop': 0.7069160997732427, 'repo_name': 'xzrunner/easyeditor', 'id': 'e46f6ec38fee563d9a8c25fc75cc5921f2ea0ba2', 'size': '1863', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'easypseudo3d/src/easypseudo3d/Task.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '118661'}, {'name': 'C++', 'bytes': '5152354'}, {'name': 'GLSL', 'bytes': '10503'}, {'name': 'Lua', 'bytes': '127544'}, {'name': 'Makefile', 'bytes': '210'}]} |
I.user = (function ($) {
function syncProjects(url) {
$('#syncing').show();
$("a[data-sync-projects]").hide();
$.ajax(url, {dataType: 'script', method: 'POST'});
}
return {
syncProjects: syncProjects
};
}(jQuery));
jQuery(function($) {
$("body").on("click", "a[data-sync-projects]", function(evt) {
evt.preventDefault();
evt.stopPropagation();
I.user.syncProjects(this.href);
});
});
| {'content_hash': '09b5abf31a7a38010bd05a47b22f8ceb', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 64, 'avg_line_length': 22.42105263157895, 'alnum_prop': 0.5821596244131455, 'repo_name': 'inch-ci/inch_ci-web', 'id': '5f09ab18aa454b617f5109f78ab4460ad709705b', 'size': '426', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/assets/javascripts/application/users.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13220'}, {'name': 'HTML', 'bytes': '81162'}, {'name': 'JavaScript', 'bytes': '31643'}, {'name': 'Ruby', 'bytes': '239705'}]} |
/**
* Classes used for formatting in Context with MsgPhrase.
*
* @author The eFaps Team
* @version $Id: $
*/
package org.efaps.esjp.common.format;
| {'content_hash': 'eee6f6961b88aa3b1cb42577445f4511', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 57, 'avg_line_length': 17.11111111111111, 'alnum_prop': 0.6753246753246753, 'repo_name': 'eFaps/eFaps-Kernel-Install', 'id': '76485d9a2db014ea4bb53938c5cffd180467e1c4', 'size': '915', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/efaps/ESJP/org/efaps/esjp/common/format/package-info.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1478988'}, {'name': 'JavaScript', 'bytes': '39333'}]} |
TaskBerserk is a [TaskWarrior][tw] client for iOS. App uses [Inthe.am][intheam] RESTful API for syncing with TaskWarrior.
Feel free to create issues, especially enhancement.
# Current state
Currently app is in early development stage. Current [development][develop-branch] version v0.1.0 contains next improvements:
- Basic functionality
- [x] Add tasks
- [x] Remove tasks
- [ ] Edit tasks
- [x] Change task's names
- [ ] Change task's project
- [ ] Change task's tags
- [ ] Change task's priority
- [ ] Basic gestures
- [ ] Done taskg
- [ ] Delete task
- [x] Fetching task via Intheam
- [x] Local storage(CoreData)
- [ ] Additional functionality
- [x] View all projects
- [ ] View all tags
- [ ] View project's tasks
- [ ] View tag's tasks
# Roadmap
* v0.1.0 Basic functionality + fetching via Intheam
* v0.2.0 Syncing via Intheam
* v0.3.0 Better compatibility support(depends on tasks, sub projects) + gestures
* v0.4.0 Filters + searching
* v0.5.0 UI
* v0.6.0 Calendar + notifications
* v0.7.0 Reports/charts
# Installation
For now the only way to install app is to download and build it from a [release page][releases] or clone from current [development branch][develop-branch]. You should also add an AppKey.plist file to project with your Inthe.am API key:
```xml
<dict>
<key>Intheam</key>
<string>Your API Key</string>
</dict>
```
# Changes
###### v0.0.5:
Prototype with support of syncing task via [Inthe.am][intheam] API. App parses JSON into tasks and projects.
# Licence
TaskBerserk is released under MIT license. For details, see [LICENSE][license].
[intheam]: https://inthe.am/about
[tw]: http://taskwarrior.org/
[releases]: https://github.com/Rag0n/TaskBerserk/releases
[license]: LICENSE.md
[version-0.0.5]: https://github.com/Rag0n/TaskBerserk/releases/tag/v0.0.5
[develop-branch]: https://github.com/Rag0n/TaskBerserk/tree/develop
| {'content_hash': '5b459abe1e900f274aacd4cb7480f4f1', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 235, 'avg_line_length': 31.639344262295083, 'alnum_prop': 0.6994818652849741, 'repo_name': 'Rag0n/TaskBerserk', 'id': '188e129112733234cf116fae8f512b756440aa7d', 'size': '1945', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': []} |
#pragma once
#include <mutex>
class SipStack;
namespace doubango_rt
{
namespace BackEnd
{
ref class rtSipCallback;
interface class rtISipCallback;
ref class rtDDebugCallback;
interface class rtIDDebugCallback;
enum class rt_tdav_codec_id_t;
public ref class rtDnsResult sealed
{
internal:
rtDnsResult(uint16 port, Platform::String^ address):_port(port), _address(address){}
public:
property uint16 Port{ uint16 get() { return _port; }; }
property Platform::String^ Address{ Platform::String^ get() { return _address; }; }
private:
uint16 _port;
Platform::String^ _address;
};
public ref class rtSipStack sealed
{
public:
virtual ~rtSipStack();
internal:
rtSipStack(rtISipCallback^ callback, Platform::String^ realmUri, Platform::String^ impiString, Platform::String^ impuUri);
const SipStack* getWrappedStack() { return m_pSipStack; }
public:
bool start();
bool setDebugCallback(rtIDDebugCallback^ pCallback);
bool setDisplayName(Platform::String^ display_name);
bool setRealm(Platform::String^ realm_uri);
bool setIMPI(Platform::String^ impi);
bool setIMPU(Platform::String^ impu_uri);
bool setPassword(Platform::String^ password);
bool setAMF(Platform::String^ amf);
bool setOperatorId(Platform::String^ opid);
bool setProxyCSCF(Platform::String^ fqdn, unsigned short port, Platform::String^ transport, Platform::String^ ipversion);
bool setLocalIP(Platform::String^ ip, Platform::String^ transport);
bool setLocalIP(Platform::String^ ip);
bool setLocalPort(unsigned short port, Platform::String^ transport);
bool setLocalPort(unsigned short port);
bool setEarlyIMS(bool enabled);
bool addHeader(Platform::String^ name, Platform::String^ value);
bool removeHeader(Platform::String^ name);
bool addDnsServer(Platform::String^ ip);
bool setDnsDiscovery(bool enabled);
bool setAoR(Platform::String^ ip, int port);
bool setSigCompParams(unsigned dms, unsigned sms, unsigned cpb, bool enablePresDict);
bool addSigCompCompartment(Platform::String^ compId);
bool removeSigCompCompartment(Platform::String^ compId);
bool setSTUNServer(Platform::String^ ip, unsigned short port);
bool setSTUNCred(Platform::String^ login, Platform::String^ password);
bool setTLSSecAgree(bool enabled);
bool setSSLCertificates(Platform::String^ privKey, Platform::String^ pubKey, Platform::String^ caKey, bool verify);
bool setSSLCertificates(Platform::String^ privKey, Platform::String^ pubKey, Platform::String^ caKey);
bool setIPSecSecAgree(bool enabled);
bool setIPSecParameters(Platform::String^ algo, Platform::String^ ealgo, Platform::String^ mode, Platform::String^ proto);
Platform::String^ dnsENUM(Platform::String^ service, Platform::String^ e164num, Platform::String^ domain);
#if COM_VISIBLE
rtDnsResult^ dnsNaptrSrv(Platform::String^ domain, Platform::String^ service);
rtDnsResult^ dnsSrv(Platform::String^ service);
Platform::String^ getLocalIP(Platform::String^ protocol);
uint16 getLocalPort(Platform::String^ protocol);
#else
Platform::String^ dnsNaptrSrv(Platform::String^ domain, Platform::String^ service, Platform::IntPtr port);
Platform::String^ dnsSrv(Platform::String^ service, Platform::IntPtr port);
Platform::String^ getLocalIPnPort(Platform::String^ protocol, Platform::IntPtr port);
#endif
Platform::String^ getPreferredIdentity();
bool isValid();
bool stop();
static bool initialize();
static bool deInitialize();
static void setCodecs(enum class rt_tdav_codec_id_t codecs);
static bool setCodecPriority(enum class rt_tdav_codec_id_t codec_id, int priority);
static bool isCodecSupported(enum class rt_tdav_codec_id_t codec_id);
private:
SipStack* m_pSipStack;
rtSipCallback^ m_pSipCallback;
rtDDebugCallback^ m_pDebugCallback;
std::recursive_mutex mLock;
};
}
} | {'content_hash': '686e51138e58857ea3163f99b34aea8a', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 125, 'avg_line_length': 38.50961538461539, 'alnum_prop': 0.7213483146067415, 'repo_name': 'PeterXu/perfume', 'id': '43a9e0afc3cd4036aae25f3213eeba9a5220a843', 'size': '4726', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rtcall/doubango/bindings/winrt/doubango_rt/include/rt_SipStack.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '4130'}, {'name': 'Awk', 'bytes': '708'}, {'name': 'C', 'bytes': '18053480'}, {'name': 'C#', 'bytes': '362421'}, {'name': 'C++', 'bytes': '6331389'}, {'name': 'CSS', 'bytes': '266360'}, {'name': 'D', 'bytes': '5123'}, {'name': 'Java', 'bytes': '901985'}, {'name': 'JavaScript', 'bytes': '3921875'}, {'name': 'Lua', 'bytes': '5827'}, {'name': 'Objective-C', 'bytes': '81566'}, {'name': 'Perl', 'bytes': '127228'}, {'name': 'Python', 'bytes': '133095'}, {'name': 'Ragel in Ruby Host', 'bytes': '608499'}, {'name': 'Shell', 'bytes': '62166'}]} |
package gh.test.gh2013.payload
import gh2013.payloads.{MemberEventPayload, PullRequestEventPayload}
import net.liftweb.json._
import org.scalatest.{Matchers, FlatSpec}
class MemberEventPayloadTest extends FlatSpec with Matchers
{
"A valid MemberEvent payload" must "be correctly parsed" in {
val json = parse(
"""
| {
|
| "action":"added",
| "member":{
| "url":"https://api.github.com/users/apphb",
| "repos_url":"https://api.github.com/users/apphb/repos",
| "followers_url":"https://api.github.com/users/apphb/followers",
| "id":631394,
| "starred_url":"https://api.github.com/users/apphb/starred{/owner}{/repo}",
| "login":"apphb",
| "type":"User",
| "received_events_url":"https://api.github.com/users/apphb/received_events",
| "gists_url":"https://api.github.com/users/apphb/gists{/gist_id}",
| "subscriptions_url":"https://api.github.com/users/apphb/subscriptions",
| "events_url":"https://api.github.com/users/apphb/events{/privacy}",
| "following_url":"https://api.github.com/users/apphb/following",
| "avatar_url":"https://secure.gravatar.com/avatar/03ac88c837ebf7761b39f2afbbae7cdf?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png",
| "gravatar_id":"03ac88c837ebf7761b39f2afbbae7cdf",
| "organizations_url":"https://api.github.com/users/apphb/orgs"
| }
|
|}
""".stripMargin)
MemberEventPayload(json) shouldBe 'defined
}
}
| {'content_hash': '64ae50e84aa4bed1edb1a20db490b287', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 194, 'avg_line_length': 46.526315789473685, 'alnum_prop': 0.5684389140271493, 'repo_name': 'mgoeminne/github_etl', 'id': 'f1fb91e83cb815f221a5229c420fb89f813e9b8a', 'size': '1768', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/scala/gh/test/gh2013/payload/MemberEventPayloadTest.scala', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Scala', 'bytes': '950348'}]} |
layout: post
title: Issac Newton
date: 2020-02-08 23:37:05
summary:
categories: drawing
---

| {'content_hash': 'b40fcc1f5123a7fa50d2b2f3ec7cfa93', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 51, 'avg_line_length': 23.285714285714285, 'alnum_prop': 0.6380368098159509, 'repo_name': 'gregist/gregist.github.io', 'id': '644fd4590144604e2f2c5cff2183401709225a7a', 'size': '167', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2020-02-08-Issac-Newton.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '25750'}, {'name': 'HTML', 'bytes': '25271'}, {'name': 'JavaScript', 'bytes': '1409'}, {'name': 'Python', 'bytes': '1873'}, {'name': 'Ruby', 'bytes': '6612'}]} |
require "helper"
describe NormalisedBraintree::Response::FailedValidation do
it_behaves_like "a response"
let(:errors) do
[
double(code: '1', message: 'Hi 1'),
double(code: '2', message: 'Hi 2'),
]
end
let(:response) { NormalisedBraintree::Response::FailedValidation.new(errors) }
it "#success? is false" do
expect(response.success?).to be_false
end
it "#code is pulled from the first error" do
expect(response.code).to eq('1')
end
it "#message is pulled from the first error" do
expect(response.message).to eq('Hi 1')
end
it "#status is hardcoded" do
expect(response.status).to eq('failed_validation')
end
end
| {'content_hash': '01dca2e958d9d43194375324534660bc', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 80, 'avg_line_length': 23.344827586206897, 'alnum_prop': 0.6661742983751846, 'repo_name': 'everydayhero/braintree_transaction_gateway', 'id': 'e1d282e7694c08868d7b25e08d49979904f4a47b', 'size': '677', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/normalised_braintree/response/failed_validation_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '28173'}]} |
- v1 released [\#28](https://github.com/nofluxjs/noflux-react/pull/28) ([malash](https://github.com/malash))
- Remove deprecated API [\#26](https://github.com/nofluxjs/noflux-react/pull/26) ([malash](https://github.com/malash))
- Rewrite connect with ES6 class [\#25](https://github.com/nofluxjs/noflux-react/pull/25) ([malash](https://github.com/malash))
- Use constructor for init in connect component [\#24](https://github.com/nofluxjs/noflux-react/pull/24) ([malash](https://github.com/malash))
## [v0.8.1](https://github.com/nofluxjs/noflux-react/tree/v0.8.1) (2018-04-12)
- Support React new lifecycle methods [\#24](https://github.com/nofluxjs/noflux-react/pull/24) ([malash](https://github.com/malash))
## [v0.8.0](https://github.com/nofluxjs/noflux-react/tree/v0.8.0) (2017-12-27)
- Upgrade @noflux/[email protected]
## [v0.7.0](https://github.com/nofluxjs/noflux-react/tree/v0.7.0) (2017-12-25)
- Reduce component type check [\#23](https://github.com/nofluxjs/noflux-react/pull/23) ([malash](https://github.com/malash))
- Update dependencies [\#22](https://github.com/nofluxjs/noflux-react/pull/22) ([malash](https://github.com/malash))
- Upgrade enzyme@3 [\#21](https://github.com/nofluxjs/noflux-react/pull/21) ([malash](https://github.com/malash))
## [v0.6.1](https://github.com/nofluxjs/noflux-react/tree/v0.6.1) (2017-10-10)
- Add `index.d.ts` file. [\#20](https://github.com/nofluxjs/noflux-react/pull/20) ([malash](https://github.com/malash))
- Batch forceUpdate [\#19](https://github.com/nofluxjs/noflux-react/pull/19) ([malash](https://github.com/malash))
- Update dependencies [\#18](https://github.com/nofluxjs/noflux-react/pull/18) ([malash](https://github.com/malash))
## [v0.6.0](https://github.com/nofluxjs/noflux-react/tree/v0.6.0) (2017-09-06)
- Fix memory leak on server-side rendering [\#15](https://github.com/nofluxjs/noflux-react/issues/15) by adding canUseDOM for preventing memory leak from server-side rendering [\#17](https://github.com/nofluxjs/noflux-react/pull/17) ([malash](https://github.com/malash))
- External package in es/cjs build & add rollup-plugin-filesize [\#14](https://github.com/nofluxjs/noflux-react/pull/14) ([malash](https://github.com/malash))
## [v0.5.2](https://github.com/nofluxjs/noflux-react/tree/v0.5.2) (2017-08-18)
- Replace `NODE_ENV` in noflux-state.umd.js [\#13](https://github.com/nofluxjs/noflux-react/pull/13) ([malash](https://github.com/malash))
## [v0.5.0](https://github.com/nofluxjs/noflux-react/tree/v0.5.0) (2017-08-10)
- Use rollup for bundle build [\#12](https://github.com/nofluxjs/noflux-react/pull/12) ([malash](https://github.com/malash))
## [v0.4.4](https://github.com/nofluxjs/noflux-react/tree/v0.4.4) (2017-07-13)
- Upgrade @noflux/[email protected]
## [v0.4.3](https://github.com/nofluxjs/noflux-react/tree/v0.4.3) (2017-06-10)
- Support Node.js 8 & NPM 5 [\#10](https://github.com/nofluxjs/noflux-react/pull/10) ([malash](https://github.com/malash))
## [v0.4.2](https://github.com/nofluxjs/noflux-react/tree/v0.4.2) (2017-06-01)
- Fix bug `state.set` on `componentDidMount` does not call forceUpdate [\#11](https://github.com/nofluxjs/noflux-react/pull/11) ([malash](https://github.com/malash))
## [v0.4.1](https://github.com/nofluxjs/noflux-react/tree/v0.4.1) (2017-05-16)
- Fix `@connect` validate throw error
## [v0.4.0](https://github.com/nofluxjs/noflux-react/tree/v0.4.0) (2017-05-15)
- Refact partial connect for a better paradigm [\#9](https://github.com/nofluxjs/noflux-react/pull/9) ([malash](https://github.com/malash))
## [v0.3.0](https://github.com/nofluxjs/noflux-react/tree/v0.3.0) (2017-05-07)
- Add `state.load` API [\#8](https://github.com/nofluxjs/noflux-react/pull/8) ([malash](https://github.com/malash))
## [v0.2.0](https://github.com/nofluxjs/noflux-react/tree/v0.2.0) (2017-04-23)
- New connect without rxjs [\#7](https://github.com/nofluxjs/noflux-react/pull/7) ([sartrey](https://github.com/sartrey))
- Remove semver for less code size [\#6](https://github.com/nofluxjs/noflux-react/pull/6) ([malash](https://github.com/malash))
## [v0.1.0](https://github.com/nofluxjs/noflux-react/tree/v0.1.0) (2017-04-12)
- Refactor [\#5](https://github.com/nofluxjs/noflux-react/pull/5) ([malash](https://github.com/malash))
- Less code in pure.js [\#2](https://github.com/nofluxjs/noflux-react/pull/2) ([malash](https://github.com/malash))
- Start noflux@next project [\#1](https://github.com/nofluxjs/noflux-react/pull/1) ([malash](https://github.com/malash))
| {'content_hash': '1f769ad2e23a9cd258114ed9a711a3a7', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 270, 'avg_line_length': 66.83582089552239, 'alnum_prop': 0.7047789191603394, 'repo_name': 'nofluxjs/noflux-react', 'id': 'd3019e655b16e13405f1803e8cb6ccde65c931f7', 'size': '4572', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CHANGELOG.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '18634'}, {'name': 'TypeScript', 'bytes': '1707'}]} |
module Nemiro.Collections {
/**
* Represents key and value item.
*/
export class KeyValueItem {
/**
* Gets or sets key.
*/
public Key: string;
/**
* Gets or sets value.
*/
public Value: string;
constructor(key?: string, value?: string) {
this.Key = key || null;
this.Value = value || null;
}
}
} | {'content_hash': '26dd3d5bd0cf05943f56a669a244afbc', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 47, 'avg_line_length': 14.26923076923077, 'alnum_prop': 0.522911051212938, 'repo_name': 'adminstock/ssa', 'id': 'd99cc50ae8035b4bbd3d0728f8c40133b37ae475', 'size': '981', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'FrontEndScripts/libs/Nemiro/Collections/KeyValueItem.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '171604'}, {'name': 'HTML', 'bytes': '920'}, {'name': 'JavaScript', 'bytes': '5503541'}, {'name': 'Nginx', 'bytes': '3092'}, {'name': 'PHP', 'bytes': '575748'}, {'name': 'Shell', 'bytes': '1670'}, {'name': 'TypeScript', 'bytes': '311134'}]} |
[](http://multiversi.zolmeister.com)
### Web: http://multiversi.zolmeister.com
### iOS app: http://multiversi.es @bradzeis
A 3-player Reversi (Othello) inspired board game. Jump over pieces and take over control points to win.
[](http://multiversi.zolmeister.com)
###### License: MIT
| {'content_hash': 'a6b987a7f30902e15320c4c47b7edbf2', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 140, 'avg_line_length': 54.888888888888886, 'alnum_prop': 0.7591093117408907, 'repo_name': 'Zolmeister/multiversi', 'id': '4a4a8f39955d68b40d8bbc4168462cd3989493e5', 'size': '508', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6873'}, {'name': 'JavaScript', 'bytes': '84093'}]} |
namespace Elixr.Api.ApiModels
{
public class SeedInfo
{
public int Id { get; set; }
public string Code { get; set; }
public long PerformedAtMS { get; set; }
}
} | {'content_hash': '2609986bc2edda009067def877d16bc8', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 47, 'avg_line_length': 22.666666666666668, 'alnum_prop': 0.553921568627451, 'repo_name': 'adjentz/Elixr', 'id': 'c72296383628e9fc4f8e633cfdd47b359cb0e3d5', 'size': '204', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Elixr.Api/ApiModels/SeedInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '62'}, {'name': 'C#', 'bytes': '235913'}, {'name': 'CSS', 'bytes': '26194'}, {'name': 'HTML', 'bytes': '263751'}, {'name': 'JavaScript', 'bytes': '50577'}, {'name': 'TypeScript', 'bytes': '230141'}]} |
{-# LANGUAGE GADTs, TypeFamilies, TypeOperators, FlexibleContexts, FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell, PatternGuards, ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances, StandaloneDeriving #-}
module Language.Floha.Base
( (:.)(..)
, Nil(..)
, BitRepr(..)
, FE(..)
, (-->)
, LiftFE
, Tuple(..)
, Reset(..)
, Clock(..)
, Actor(..)
, actor
, actorN
, ActorBody
, auto
, autoN
, initial
, __
, rules
, rulesND
, constant
, report
, simulate
, Logic(..)
, AddSub(..)
, net
, feFalse
, feTrue
, feUnit
, deriveBitRepr
, generateCode
, Language(..)
) where
import Control.Monad
import Control.Monad.State
import Data.Bits
import Data.Int
import qualified Data.Map as Map
import Data.Maybe
import Data.List(intercalate, nub, isPrefixOf)
import qualified Data.Set as Set
import Data.Word
import Text.Printf
import qualified Language.Haskell.TH as TH
import Debug.Trace
-------------------------------------------------------------------------------
-- HList.
infixr 5 :.
data a :. b = a :. b
data Nil = Nil
-------------------------------------------------------------------------------
-- Constraints on types for Floha.
-- Basically, the bit size of value of type should be computable at the compilation time.
data Z = Z
data S n = S n
type family Plus a b
type instance Plus Z b = b
type instance Plus (S a) b = S (Plus a b)
type Twice a = Plus a a
type family Max a b
type instance Max Z (S b) = S b
type instance Max (S a) Z = S a
type instance Max (S a) (S b) = S (Max a b)
newtype NatI = NatI { fromNatI :: Integer}
deriving (Eq, Ord, Num)
instance Show NatI where
show = show . fromNatI
class Nat a where
-- |Get the value of that type.
realizeNat :: a
-- |Lower value from types.
natValue :: a -> NatI
instance Nat Z where
realizeNat = Z
natValue ~Z = 0
instance Nat n => Nat (S n) where
realizeNat = S realizeNat
natValue ~(S n) = 1 + natValue n
newtype BitVectConst = BitVectConst { fromBitVectConst :: Integer }
deriving (Eq, Ord, Show, Num, Bits)
class Nat (BitSize a) => BitRepr a where
-- |Type representation for the size.
type BitSize a
typeBitSize :: a -> BitSize a
typeBitSize _ = realizeNat
-- |Get the bit size of the type.
bitReprSize :: a -> NatI
bitReprSize a = natValue (typeBitSize a)
-- |Safe value. In most cases @decode 0@ suffice, but
-- for "one of N" encoding this is not the case.
-- "One if N" always has one bit set.
safeValue :: a
-- |Encode the value as bit vector.
encode :: a -> BitVectConst
-- |Decode the value from bit vector.
decode :: BitVectConst -> a
-------------------------------------------------------------------------------
-- HList.
-- |Kind of variable.
data VarK = Var | Ready | Valid
deriving (Eq, Ord, Show)
-- |How we identify variables.
data VarID = VarID (Maybe String) [Int] VarK
deriving (Eq, Ord, Show)
-- |Compile-time constant size bit vectors are a necessity.
data BitVect size = BitVect
deriving (Eq, Ord, Show)
-- |Floha expression structure.
data FE a where
FELow :: SizedLFE -> FE a
-- |Untyped and sized expressions for generating Verilog or VHDL code.
-- Every expression is accompanied by its size.
data LowFE =
-- regular constant.
LFEConst BitVectConst
-- variable - input, output, register, temp...
| LFEVar VarID
-- wildarg. Can be pattern and value.
| LFEWild
-- Various binary operations.
| LFEBin LFWBinOp SizedLFE SizedLFE
-- Concatenation of expressions, basically curly brackets from Verilog.
| LFECat [SizedLFE]
-- LFESub value high low: take subvector (low..high) from value. Tuple splits use this. Indices are inclusive.
-- The size should be high-low+1.
| LFESub SizedLFE Int Int
-- Change size from one to another. Change to smaller size basically is the same as LFESub v (size-1) 0.
| LFEChangeSize ChangeFiller SizedLFE
-- The register assignment. Arguments are name of the clock, default value (after reset) and the computed value.
| LFERegister String BitVectConst SizedLFE
deriving (Eq, Ord, Show)
-- |Binary operations for LowFE. Note that there is no distinction between bitwise and logical operations.
-- This is so because they are identical for Verilog and can be made so for VHDL.
data LFWBinOp = Plus | Minus | And | Or | Xor | Equal | Compare CompareOp
deriving (Eq, Ord, Show)
-- |Whether comparison is signed?
data Signed = Unsigned | Signed
deriving (Eq, Ord, Show)
-- |The comparison operator.
data CompareOperator = LT | LE | GT | GE
deriving (Eq, Ord, Show)
-- |Compare operations.
data CompareOp = CompareOp CompareOperator Signed
deriving (Eq, Ord, Show)
-- |What we are doing when changing size of expression.
-- This is relevant only for extending the size.
data ChangeFiller = FillZero | FillSign
deriving (Eq, Ord, Show)
-- |Sized low FE is a pair of LowFE value and it's size.
type SizedLFE = (NatI, LowFE)
-- |Class to describe basic arithmetic operations.
class AddSub a where
(.+), (.-) :: a -> a -> a
-- |How FE supports them.
instance AddSub a => AddSub (FE a) where
FELow a@(size,_) .+ FELow b = FELow $ (size, LFEBin Plus a b)
FELow a@(size,_) .- FELow b = FELow $ (size, LFEBin Minus a b)
-- |Class to describe bitwise operations like .&. and .|. from Data.Bits.Bits.
-- It is also suitable for logical connectives.
class Logic a where
(.&), (.|) ,(.^) :: a -> a -> a
-- |Support for BitWise for FE's.
instance Logic a => Logic (FE a) where
FELow a@(size,_) .& FELow b = FELow (size, LFEBin And a b)
FELow a@(size,_) .| FELow b = FELow (size, LFEBin Or a b)
FELow a@(size,_) .^ FELow b = FELow (size, LFEBin Xor a b)
-- |Lift HList to the HList of Floha expressions.
type family LiftFE ts
type instance LiftFE Nil = Nil
type instance LiftFE (t :. ts) = FE t :. LiftFE ts
-- |Make a HList of Strings from a HList.
type family StringList ts
type instance StringList Nil = Nil
type instance StringList (n :. ns) = String :. StringList ns
-- |Tuple support.
class Tuple tup where
-- |Transformation at type level - from (FE a, FE b) to FE (a,b)
type FETuple tup
-- |The code for transformation.
tuple :: tup -> FETuple tup
-- |Reset signal properties.
class Reset r where
-- |Name of reset signal.
resetName :: r -> String
-- |Reset active polarity, True for positive (1).
resetActiveHigh :: r -> Bool
-- |Is reset synchronous?
resetSynchronous :: r -> Bool
class (Reset (ClockReset c), Show c) => Clock c where
-- |The type of clock reset signal.
type ClockReset c
-- |The clock name.
clockName :: c -> String
-- |Whether clock edge is positive (front).
clockPosEdge :: c -> Bool
-- |Reset type for this clock.
clockReset :: c -> ClockReset c
-- |Clock frequency.
clockFrequency :: c -> Rational
data ClockInfo = ClockInfo {
ciClockName :: String
, ciResetName :: String
, ciClockPosEdge :: Bool
, ciResetSync :: Bool
, ciResetActiveHigh :: Bool
}
deriving (Eq, Ord, Show)
clockInfo :: Clock c => c -> ClockInfo
clockInfo c = ClockInfo {
ciClockName = clockName c
, ciResetName = resetName r
, ciClockPosEdge = clockPosEdge c
, ciResetSync = resetSynchronous r
, ciResetActiveHigh = resetActiveHigh r
}
where
r = clockReset c
-- |Default reset type for default clock.
data DefaultReset = DefaultReset
deriving (Eq, Ord, Show)
instance Reset DefaultReset where
resetName = show
resetActiveHigh = const False
resetSynchronous = const False
data DefaultClock = DefaultClock
deriving (Eq, Ord, Show)
instance Clock DefaultClock where
type ClockReset DefaultClock = DefaultReset
clockName = show
clockPosEdge = const True
clockReset = const DefaultReset
clockFrequency = const 1
data ClockHolder where
ClockHolder :: Clock c => c -> ClockHolder
data RulesType = Deterministic | NonDeterministic
deriving (Eq, Ord, Show)
data Rules = Rules RulesType [SizedLFE] [SizedLFE] [([SizedLFE], [SizedLFE])]
deriving (Eq, Ord, Show)
-- |Instance of an actor. Name of instance, clocked inputs and outputs and the internal representation of an actor.
data Instance = Instance String [(ClockInfo, SizedLFE)] [(ClockInfo, SizedLFE)] LLActor
deriving (Eq, Ord, Show)
-- |FIFO annotation. What channel FIFO is added to and the size.
data FIFO = FIFO SizedLFE Int
deriving (Eq, Ord, Show)
type ClockedSizedLFE = (ClockInfo, SizedLFE)
-- |Low level representation of Floha actor.
data LLActor =
-- state machine variant of actor.
-- includes: name, inputs, outputs, assignments for the variables, matching rules (at least one) and clock information.
LLActor String [SizedLFE] [SizedLFE] (Map.Map VarID SizedLFE) [Rules] ClockInfo
-- network variant of actor.
-- includes: name, inputs and outputs with associated clock information, instances of actors and FIFO annotations
-- for channels.
| LLNet String [ClockedSizedLFE] [ClockedSizedLFE] [Instance] [FIFO]
deriving (Eq, Ord, Show)
-- |Floha actor.
data Actor ins outs where
Actor :: LLActor -> Actor ins outs
deriving instance Show (Actor ins outs)
-------------------------------------------------------------------------------
-- Main combinators.
actor :: (FEList (LiftFE ins), FEList (LiftFE outs)) => String -> ActorBody (LiftFE ins) (LiftFE outs) -> Actor ins outs
actor name body = _mkActor name Nothing body
actorN :: (FEList (LiftFE ins), FEList (LiftFE outs)) => String -> StringList (LiftFE ins) -> ActorBody (LiftFE ins) (LiftFE outs) -> Actor ins outs
actorN name names body = _mkActor name (Just names) body
net :: String -> Actor ins outs
net name = error "net is not yet ready."
-- |Deterministic version of rules - it does not take into account readyness of the outputs.
rules :: (Match matchE, Change changeE) => (matchE, changeE) -> [(matchE, changeE)] -> ActorBodyM ()
rules (headerMatch, headerResults) matchChanges = do
let r = Rules Deterministic (matchExpressions headerMatch) (changeExpressions headerResults)
(map (\(m,c) -> (matchExpressions m, changeExpressions c)) matchChanges)
modify $ \abs -> abs { absRules = r : absRules abs }
-- |Non-deterministic rules - rule considered firing if patterns matches and valid and outputs are ready.
rulesND :: (Match matchE, Change changeE) => (matchE, changeE) -> [(matchE, changeE)] -> ActorBodyM ()
rulesND (headerMatch, headerResults) matchChanges = do
let r = Rules NonDeterministic (matchExpressions headerMatch) (changeExpressions headerResults)
(map (\(m,c) -> (matchExpressions m, changeExpressions c)) matchChanges)
modify $ \abs -> abs { absRules = r : absRules abs }
-- | @-->@ is just an operator version of tuple constructor.
infix 9 -->
(-->) :: a -> b -> (a,b)
a --> b = (a,b)
auto :: BitRepr a => ActorBodyM (FE a)
auto = inventVar Nothing
autoN :: BitRepr a => String -> ActorBodyM (FE a)
autoN = inventVar . Just
__ :: BitRepr a => FE a
__ = r
where
r = FELow (size, LFEWild)
toA :: BitRepr a => FE a -> a
toA _ = error "toA in __ is forced!"
size = fromIntegral $ fromNatI $ bitReprSize $ toA r
-- |Create a constant FE.
constant :: BitRepr a => a -> FE a
constant a = FELow (fromIntegral $ fromNatI $ bitReprSize a, LFEConst $ encode a)
-- |Initial assignment for variable.
initial :: BitRepr a => FE a -> a -> ActorBodyM ()
initial (FELow (_,LFEVar vid)) a = do
_setInitial vid (bitReprSize a, LFEConst (encode a))
internalUnsafeCast :: (BitRepr a, BitRepr b) => FE a -> FE b
internalUnsafeCast (FELow e) = r
where
r = FELow (feBitSize r, LFEChangeSize FillZero e)
-- |Display the value, if condition is met.
report :: (BitRepr a, Show a) => FE Bool -> FE a -> ActorBodyM ()
report condition value = do
error "report !!!"
frequency :: Clock c => ActorBodyM Rational
frequency = do
ClockHolder c <- liftM absClock get
return $ clockFrequency c
-------------------------------------------------------------------------------
-- Implementation.
data ABState = ABS {
-- |Generating unique indices.
absUnique :: Int
-- |Initial values for the variables.
, absInitials :: Map.Map VarID SizedLFE
-- |Register signals as inputs.
, absInputs :: [SizedLFE]
-- |And also register signals as outputs.
, absOutputs :: [SizedLFE]
-- |Rules.
, absRules :: [Rules]
-- |Clock specification.
, absClock :: ClockHolder
}
type ActorBodyM a = State ABState a
type ActorBody ins outs = ins -> ActorBodyM outs
-- |Handy function to get the size of FE.
feBitSize :: BitRepr a => FE a -> NatI
feBitSize e = bitReprSize $ toA e
where
toA :: BitRepr a => FE a -> a
toA _ = error "toA in feBitSize called!"
-- |Handy function to get the safe value for FE.
feSafeValue :: BitRepr a => FE a -> a
feSafeValue e = safeValue
startABState :: ABState
startABState = ABS {
absUnique = 0
, absInitials = Map.empty
, absInputs = []
, absOutputs = []
, absRules = []
, absClock = ClockHolder DefaultClock
}
_unique :: ActorBodyM Int
_unique = modify (\abs -> abs { absUnique = absUnique abs + 1 }) >> liftM absUnique get
_inventVarID :: Maybe String -> ActorBodyM VarID
_inventVarID name = checkName name >> liftM (($ Var) . VarID name . (\n -> [n])) _unique
where
checkName Nothing = return ()
checkName (Just n)
| isPrefixOf "fevar_" n = error $ "invalid variable name "++show n++". choose another prefix (up to underscore)."
| otherwise = return ()
_setInitial :: VarID -> SizedLFE -> ActorBodyM ()
_setInitial v init = modify $ \abs -> abs { absInitials = Map.insert v init $ absInitials abs }
cloneVarID :: VarID -> ActorBodyM VarID
cloneVarID (VarID n ns k) = do
suffix <- _unique
return $ VarID n (ns ++ [suffix]) k
inventVar :: BitRepr a => Maybe String -> ActorBodyM (FE a)
inventVar name = do
v <- _inventVarID name
let (r, initial) = mkR v
_setInitial v initial
return r
where
mkR :: BitRepr a => VarID -> (FE a, SizedLFE)
mkR varID = (r, initial)
where
r = FELow (size, LFEVar varID)
size = feBitSize r
initial = (size, LFEConst $ encode $ feSafeValue r)
class FEList feList where
inventList :: Maybe (StringList feList) -> ActorBodyM feList
_toSizedLFEs :: feList -> [SizedLFE]
instance FEList Nil where
inventList _ = return Nil
_toSizedLFEs = const []
instance (BitRepr a, FEList feList) => FEList (FE a :. feList) where
inventList names = do
fe <- inventVar name
feList <- inventList names'
return $ fe :. feList
where
(name, names') = case names of
Just (n :. ns) -> (Just n, Just ns)
Nothing -> (Nothing, Nothing)
_toSizedLFEs (FELow slfe :. list) = slfe : _toSizedLFEs list
class Match match where
-- |Convert the match into the list of expressions.
matchExpressions :: match -> [SizedLFE]
class Change change where
-- |Convert the change part into the list of expressions.
changeExpressions :: change -> [SizedLFE]
encodeConst :: BitRepr a => a -> SizedLFE
encodeConst a = (bitReprSize a, LFEConst $ encode a)
internal :: String -> a
internal s = error $ "internal error: "++s
lfeTrue, lfeFalse :: SizedLFE
[lfeTrue, lfeFalse] = map encodeConst [True, False]
varLFEReady, varLFEValid :: VarID -> SizedLFE
varLFEReady (VarID n ns k) = (1, LFEVar (VarID n ns Ready))
varLFEValid (VarID n ns k) = (1, LFEVar (VarID n ns Valid))
lfeReady, lfeValid :: SizedLFE -> SizedLFE
(lfeReady, lfeValid) = (recurse varLFEReady, recurse varLFEValid)
where
recurse change (_,e) = case e of
LFEConst _ -> lfeTrue
LFEVar v -> change v
LFEBin op a b -> lfeAnd (recurse change a) (recurse change b)
_ -> error $ "recurse in lfeReady/Valid, expression "++show e
lfeEqual, lfeAnd :: SizedLFE -> SizedLFE -> SizedLFE
lfeEqual a@(s, _) b = (s, LFEBin Equal a b)
lfeAnd a b = (fst a, LFEBin And a b)
instance Match (FE a) where
matchExpressions (FELow sizedLFE) = [sizedLFE]
instance Change (FE a) where
changeExpressions (FELow sizedLFE) = [sizedLFE]
_mkActor :: forall feIns feOuts ins outs . (feIns ~ LiftFE ins, feOuts ~ LiftFE outs, FEList feIns, FEList feOuts) => String -> Maybe (StringList feIns) -> ActorBody feIns feOuts -> Actor ins outs
_mkActor name names body = flip evalState startABState $ do
ins <- inventList names :: ActorBodyM (LiftFE ins)
outs <- body (ins :: LiftFE ins)
rules <- liftM absRules get
ClockHolder c <- liftM absClock get
initials <- liftM absInitials get
let insLFEs = _toSizedLFEs ins
outsLFEs = _toSizedLFEs outs
let anError c e = when c $ error $ name++": "++e
anError (nonUnique insLFEs) $ "input names are not unique."
anError (nonUnique outsLFEs) $ "output names are not unique."
anError (null rules) $ "no rules."
let renameIO (LFEVar v@(VarID (Just n) ns k)) = Map.singleton v (VarID (Just n) (tail ns) k)
renameIO v = Map.empty
let ioRenames = Map.unions $ map renameIO $ map snd $ insLFEs ++ outsLFEs
rules <- forM rules $ renameRulesVars ioRenames
return $ toActor ioRenames ins outs rules c initials
where
renameAny :: Map.Map VarID VarID -> SizedLFE -> SizedLFE
renameAny rmap (sz, e) = (,) sz $ case e of
LFEVar v -> case Map.lookup v rmap of
Just v -> LFEVar v
Nothing -> e
LFEBin op a b -> LFEBin op (renameAny rmap a) (renameAny rmap b)
LFECat es -> LFECat $ map (renameAny rmap) es
LFESub a o1 o2 -> LFESub (renameAny rmap a) o1 o2
LFEChangeSize filler a -> LFEChangeSize filler (renameAny rmap a)
LFERegister x y a -> LFERegister x y (renameAny rmap a)
renameRulesVars :: Map.Map VarID VarID -> Rules -> ActorBodyM Rules
renameRulesVars renames (Rules rulesType headerFrom headerTo matchChanges) = do
matchChanges' <- forM matchChanges $ \(p',e') -> do
let p = map rename p'
e = map rename e'
rs <- liftM Map.unions $ mapM (inventRenames Map.empty) p
return (map (renameAny rs) p, map (renameAny rs) e)
return $ Rules rulesType headerFrom' headerTo' matchChanges'
where
inventRenames map (_,e) = case e of
LFEVar v -> liftM (flip (Map.insert v) map) $ cloneVarID v
LFEBin _ a b -> liftM2 (Map.union) (inventRenames map a) (inventRenames map b)
LFECat es -> liftM Map.unions $ mapM (inventRenames map) es
LFESub a _ _ -> inventRenames map a
LFEChangeSize _ a -> inventRenames map a
LFERegister _ _ a -> inventRenames map a
rename = renameAny renames
headerTo' = map rename headerTo
headerFrom' = map rename headerFrom
nonUnique :: [SizedLFE] -> Bool
nonUnique [] = False
nonUnique vs
| all isNothing mbNames = False
| all isJust mbNames = checkDuplicates (catMaybes mbNames)
| otherwise = error $ "Not all outputs are named in "++name
where
mbNames = map getName vs
getName (_, LFEVar (VarID v _ _)) = v
getName _ = internal $ "output is not a variable in "++name
checkDuplicates (s:ss) = elem s ss || checkDuplicates ss
checkDuplicates [] = False
toActor :: (FEList (LiftFE ins), FEList (LiftFE outs), Clock c) => Map.Map VarID VarID -> LiftFE ins -> LiftFE outs -> [Rules] -> c -> Map.Map VarID SizedLFE -> Actor ins outs
toActor ioRenames ins outs rules c initials = Actor (LLActor name (map (renameAny ioRenames) $ _toSizedLFEs ins) (map checkVar $ map (renameAny ioRenames) $ _toSizedLFEs outs) initials rules (clockInfo c))
checkVar (sz,LFEVar n) = (sz,LFEVar n)
checkVar e = error $ "Actor "++show name++": output is not a variable: "++show e
-------------------------------------------------------------------------------
-- Simulate actors.
-- |Describe input sequences.
data Sequence a = Wait Int | Data [a]
deriving (Eq, Ord, Show)
-- |Transform HList of types into a HList of lists of sequences of types.
type family SeqsList ins
type instance SeqsList Nil = Nil
type instance SeqsList (a :. as) = [Sequence a] :. SeqsList as
-- |Simulate the actor.
simulate :: Actor ins outs -> SeqsList ins -> SeqsList outs
simulate actor seqlist = error "simulate!!!"
-------------------------------------------------------------------------------
-- Code generation.
-- |What language we should generate for.
data Language = VHDL | Verilog
deriving (Eq, Ord, Show)
-- |Code generation monad internal state.
data CGState = CGState {
-- |Unique index generator.
cgsUnique :: Int
-- |Nesting level.
, cgsNest :: Int
-- |Language used throughout generated code.
, cgsLanguage :: Language
-- |Generated lines of code.
, cgsRevLines :: [String]
-- |List of warnings.
, cgsWarnings :: [String]
-- |Current actor being generated (for warnings generation). Includes both original and unique names.
, cgsCurrentActor :: (String, String)
-- |Set of used actor names. We can have idA applied to Bool and Int32 channels, they will be
-- different actors, actually.
, cgsUsedActorNames :: Set.Set String
-- |Maping between actors and their names.
, cgsActorsVisited :: Map.Map LLActor String
-- |assignments. We first accumulate them, then realize. That allows us to have declarations before
-- any assignment will be made.
, cgsAssignments :: [(VarID, SizedLFE)]
}
deriving (Eq, Ord, Show)
startCGState :: Language -> CGState
startCGState lang = CGState {
cgsUnique = 0
, cgsNest = 0
, cgsLanguage = lang
, cgsRevLines = []
, cgsWarnings = []
, cgsCurrentActor = error "no current actor is set."
, cgsUsedActorNames = Set.empty
, cgsActorsVisited = Map.empty
, cgsAssignments = []
}
type CGM a = State CGState a
genLine :: String -> CGM ()
genLine line = modify $
\cgs -> cgs {
cgsRevLines = (if null line then "" else replicate (cgsNest cgs) ' ' ++ line) : cgsRevLines cgs
}
genNL :: CGM ()
genNL = genLine ""
genLanguage :: CGM Language
genLanguage = liftM cgsLanguage get
genWarning :: String -> CGM ()
genWarning warning = do
(actorName, uniqueActorName) <- liftM cgsCurrentActor get
let w = "actor "++show actorName++", unique name "++show uniqueActorName++". warning: "++warning
modify $ \cgs -> cgs { cgsWarnings = w : cgsWarnings cgs }
genNest :: CGM a -> CGM a
genNest act = do
n <- liftM cgsNest get
modify $ \cgs -> cgs { cgsNest = n + 4 }
r <- act
modify $ \cgs -> cgs { cgsNest = n }
return r
genComment :: String -> CGM ()
genComment line = do
l <- genLanguage
genLine $ (++" "++line) $ case l of
VHDL -> "--"
Verilog -> "//"
actorName :: LLActor -> String
actorName (LLActor name _ _ _ _ _) = name
actorName (LLNet name _ _ _ _) = name
underscoredIndices :: String -> [Int] -> VarK -> String
underscoredIndices name ns k = intercalate "_" (name : map show ns ++ kindStr)
where
kindStr = case k of
Var -> []
Ready -> ["ready"]
Valid -> ["valid"]
varIDToStr :: VarID -> String
varIDToStr (VarID s ns k) = underscoredIndices (fromMaybe "generated_var" s) ns k
changeKind :: VarK -> VarID -> VarID
changeKind k (VarID name ns _) = VarID name ns k
genModule :: String -> [ClockedSizedLFE] -> [ClockedSizedLFE] -> [ClockInfo] -> CGM () -> CGM ()
genModule un ins outs clocks compileRules = do
l <- genLanguage
case l of
Verilog -> do
genLine $ "module "++un
let cs = map ((,) "input " . (\c -> (1,VarID (Just c) [] Var))) (clks ++ resets)
let fullInputs = concatMap (signal "input " "output") ins
let fullOutputs = concatMap (signal "output" "input ") outs
genNest $ do
forM_ (zipWith (,) ("(" : repeat ",") (cs++fullInputs ++ fullOutputs)) $ \(comma,(direction,(size, v))) -> do
if size > 0
then genLine $ unwords [comma, direction, vlSize size, varIDToStr v]
else return ()
genLine ");"
genNL
VHDL -> do
genLine "VHDL QQ"
compileRules
assignments <- liftM cgsAssignments get
let decls = accumDecls assignments
genDecls $ Map.toList decls
forM_ assignments $ \(v,e) -> genAssignText v e
case l of
Verilog -> do
genNL
genLine "endmodule"
return ()
where
clks = nub $ map ciClockName clocks
resets = nub $ map ciResetName clocks
signal dirTo dirFrom (_,(size, LFEVar vid)) = [(dirTo, (size, vid)), (dirTo, (1, changeKind Valid vid)), (dirFrom, (1, changeKind Ready vid))]
signal _ _ (_,(_, e)) = internal $ "not a variable: "++show e
vlSize = take 16 . vlSize'
vlSize' 1 = repeat ' '
vlSize' n = printf "[%d:0]" (fromNatI (n-1))++ repeat ' '
exprDecls (sz,LFEConst _) = []
exprDecls (sz, LFEVar v) = [Map.singleton v sz]
exprDecls (sz,e) = internal $ "exprDecls "++show e
assignDecls (v, e@(sz, _)) = Map.singleton v sz : exprDecls e
accumDecls assigns = Map.unionsWith checkInvalidDups $ concatMap assignDecls assigns
checkInvalidDups sz1 sz2
| sz1 /= sz2 = internal $ "checkInvalidDups: "++show (sz1, sz2)
| otherwise = sz1
genDecls :: [(VarID, NatI)] -> CGM ()
genDecls decls = do
forM_ decls $ \(v,sz) -> case sz of
0 -> return ()
1 -> genLine $ unwords ["wire", varText v, ";"]
sz -> genLine $ unwords ["wire [", show (sz-1),": 0 ]", varText v, ";"]
return ()
genCompileRules :: String -> ClockInfo -> [SizedLFE] -> [SizedLFE] -> Map.Map VarID SizedLFE -> [Rules] -> CGM ()
genCompileRules name ci ins outs initials [Rules rulesType hLeft hRight matches] = do
genComment "Rules - single instance."
genCompileMatches rulesType hLeft hRight matches
return ()
genCompileRules name ci ins outs initials manyRules = do
internal $ "multiple rules aren't supported. actor "++name
varText :: VarID -> String
varText (VarID n ns kind) = underscoredIndices (fromMaybe "fevar_auto_gen" n) ns kind
exprText :: Language -> SizedLFE -> String
exprText l (sz,e) = case l of
Verilog -> vlogText
VHDL -> vhdlText
where
bits n x
| n > 0 || x > 0 = bits (max 0 (n-1)) (div x 2) ++ show (mod x 2)
| otherwise = ""
vlogText = case e of
LFEVar v -> varText v
LFEConst c -> concat [show sz,"'", bits sz $ fromBitVectConst c]
e -> internal $ "exprText Verilog: "++show e
vhdlText = case e of
e -> internal $ "exprText VHDL: "++show e
genUnique :: CGM Int
genUnique = do
modify $ \cgs -> cgs { cgsUnique = cgsUnique cgs + 1 }
liftM cgsUnique get
genCloneVar :: VarID -> CGM VarID
genCloneVar (VarID n ns k) = do
i <- genUnique
return $ VarID n (ns++[i]) k
genAssignText :: VarID -> SizedLFE -> CGM ()
genAssignText v e = do
l <- genLanguage
let eText = exprText l e
genLine $ case l of
Verilog -> unwords ["assign", varText v, "=", eText,";"]
VHDL -> "assignment !!!"
return ()
genAssign :: VarID -> SizedLFE -> CGM SizedLFE
genAssign v e = do
modify $ \cgs -> cgs { cgsAssignments = (v,e) : cgsAssignments cgs }
return (fst e, LFEVar v)
genCompileMatches :: RulesType -> [SizedLFE] -> [SizedLFE] -> [([SizedLFE], [SizedLFE])] -> CGM ()
genCompileMatches ruleType from to matchChanges = do
firesReadys <- forM matchChanges $ \(match, change) -> do
let matchValid = foldAnd $ matchsValid match
matched <- matchAssignments [] from match
return (lfeAnd matchValid matched, lfeFalse)
return ()
where
foldAnd [] = lfeTrue
foldAnd [e] = e
foldAnd es = foldAnd (by2 es)
where
by2 [] = []
by2 [e] = [e]
by2 (x:y:es) = lfeAnd x y : by2 es
fromValids = map lfeValid from
toReady = map lfeReady to
matchsValid match = concat $ zipWith matchValid fromValids match
matchValid valid (_,e) = case e of
LFEWild -> [] -- do not care for "valid" signal for wildcards.
_ -> [valid] -- all other patterns require valid signal.
matchAssignments fires [] [] = return (foldAnd fires)
matchAssignments fires (fromE:fromEs) (matchE:matchEs) = do
f <- genMatchAssignments (snd fromE) matchE
matchAssignments (fires ++ f) fromEs matchEs
genMatchAssignments e@(LFEVar v) (n, LFEConst c) = do
v' <- genCloneVar v
genAssign v' (lfeEqual (n, LFEVar v) (n, LFEConst c))
return [(1, LFEVar v')]
genMatchAssignments e@(LFEVar v) (n, LFEVar v') = do
genAssign v' (n, e)
return []
-- |Generate code from actor (either just an actor or network).
generateCode :: Language -> Actor ins outs -> ([String], String)
generateCode lang (Actor actor) = flip evalState (startCGState lang) $ do
genComment $ "GENERATED CODE!!! DO NOT MODIFY!!!"
genComment $ ""
genComment $ "Top level Floha actor: "++actorName actor
genLine ""
genLine ""
gen actor
lines <- liftM cgsRevLines get
warns <- liftM cgsWarnings get
return (reverse warns, unlines $ reverse lines)
where
gen a = do
uniqueName <- findName a
case uniqueName of
Nothing -> return ()
Just un -> do
oldAN <- liftM cgsCurrentActor get
modify $ \cgs -> cgs { cgsCurrentActor = (actorName a, un) }
l <- genLanguage
code un a
modify $ \cgs -> cgs { cgsCurrentActor = oldAN }
code un (LLActor name ins outs initials rules ci) = do
genComment $ "Actor "++name++"."
let clocked = zipWith (,) (repeat ci)
genModule un (clocked ins) (clocked outs) [ci] (genCompileRules name ci ins outs initials rules)
return ()
findName a = do
name <- liftM (Map.lookup a . cgsActorsVisited) get
case name of
Just a -> return Nothing
Nothing -> liftM Just $ inventName $ actorName a
inventName a = do
checkInvent a (inventName' 1 a)
inventName' n a = checkInvent (underscoredIndices a [n] Var) (inventName' (n+1) a)
checkInvent name cont = do
registered <- liftM (Set.member name . cgsUsedActorNames) get
if registered
then cont
else do
modify $ \cgs -> cgs { cgsUsedActorNames = Set.insert name $ cgsUsedActorNames cgs }
return name
-------------------------------------------------------------------------------
-- Instances of various classes for various types.
instance BitRepr Bool where
type BitSize Bool = S Z
safeValue = False
encode = fromInteger . fromIntegral . fromEnum
decode = toEnum . fromIntegral . fromBitVectConst
instance BitRepr Word8 where
type BitSize Word8 = Twice (Twice (Twice (S Z)))
safeValue = 0
encode = fromInteger . fromIntegral
decode = fromIntegral . fromBitVectConst
feFalse :: FE Bool
feFalse = FELow (1, LFEConst 0)
feTrue :: FE Bool
feTrue = FELow (1, LFEConst 1)
instance BitRepr () where
type BitSize () = Z
safeValue = ()
encode = const 0
decode = const ()
feUnit :: FE ()
feUnit = FELow (0, LFEConst 0)
instance Logic Bool where
(.&) = (&&)
(.|) = (||)
a .^ b = (a .& not b) .| (not a .& b)
-------------------------------------------------------------------------------
-- Derivation of BitRepr for algebraic types.
_concatenateSizedBitVectors :: [(NatI, BitVectConst)] -> BitVectConst
_concatenateSizedBitVectors vects = snd $ foldl1 (\(_,acc) (size, x) -> (0,shiftL acc (fromIntegral $ fromNatI size) .|. x)) vects
type family AlgebraicTypeBusSize a
-- |Derive instances of BitRepr for algebraic types.
-- Also derive functions to express construction of algebraic types values as FE's.
deriveBitRepr :: [TH.Name] -> TH.Q [TH.Dec]
deriveBitRepr names = do
defs <- liftM concat $ forM names $ \name -> do
info <- TH.reify name
case info of
TH.TyConI (TH.DataD [] name vars conses derive) -> do
fes <- liftM concat $ forM (zip [0..] conses) $ \(i, cons) -> def i (length conses) (maximum $ map (length . conTypes) conses) name vars cons
return (bitRepr name vars conses ++ fes)
_ -> error $ show name ++ " is not an algebraic type with empty context."
TH.runIO $ mapM (print . TH.ppr) defs
return defs
where
completeTy name vars =
foldl TH.AppT (TH.ConT name) $ map (TH.VarT . fromVarBindr) vars
fromVarBindr (TH.PlainTV v) = v
fromVarBindr (TH.KindedTV _ _) = error "kinded type arguments aren't supported."
conTypes cons = case cons of
TH.NormalC _ stys -> map snd stys
bitReprC v = TH.ClassP ''BitRepr [TH.VarT v]
bitRepr name vars conses =
[ TH.InstanceD
(TH.ClassP ''Nat [TH.ConT ''BitSize `TH.AppT` ty] : map bitReprC (map fromVarBindr vars))
(TH.ConT ''BitRepr `TH.AppT` ty)
[ TH.TySynInstD ''BitSize [ty] sizeT, safeValueV, encodeF, decodeF]
, TH.TySynInstD ''AlgebraicTypeBusSize [ty] (plusT selSize (foldl1 maxT conSizes))]
where
ty = completeTy name vars
nToTy 0 = TH.ConT ''Z
nToTy n = TH.ConT ''S `TH.AppT` nToTy (n-1)
conSizes = map conSize conses
conSize cons = case conTypes cons of
[] -> TH.ConT ''Z
ts -> foldl1 plusT $ map (TH.ConT ''BitSize `TH.AppT`) ts
selSize
| length conses == 1 = nToTy 0
| length conses == 2 = nToTy 1
| length conses > 2 = nToTy (length conses)
plusT a b = TH.ConT ''Plus `TH.AppT` a `TH.AppT` b
maxT a b = TH.ConT ''Max `TH.AppT` a `TH.AppT` b
bitSizeT a = TH.ConT ''BitSize `TH.AppT` a
consSize (TH.NormalC _ []) = []
consSize (TH.NormalC _ (a:as)) = [foldl plusT (bitSizeT $ snd a) (map (bitSizeT . snd) as)]
sizeT = case concatMap consSize conses of
[] -> selSize
s:ss -> plusT selSize (foldl maxT s ss)
safeValueV = TH.FunD 'safeValue [TH.Clause [] (TH.NormalB sv) []]
where
sv = case conses of
TH.NormalC name tys : _ -> foldl TH.AppE (TH.ConE name) (map (const $ TH.VarE 'safeValue) tys)
_ -> error "not a normal constructor for safe value."
x = TH.mkName "x"
encodeF = TH.FunD 'encode [TH.Clause [TH.VarP x] (TH.NormalB $ TH.VarE 'undefined) []]
decodeF = TH.FunD 'decode [TH.Clause [TH.VarP x] (TH.NormalB $ TH.VarE 'undefined) []]
def i n maxTys name vars cons = do
let funN = TH.mkName $ "fe"++TH.nameBase conN
TH.runIO $ putStrLn $ "defining construction for "++show (name, vars, cons)
case (n, maxTys) of
-- special cases for enums, they are easy.
(1,0) -> return [TH.FunD funN [TH.Clause [] (TH.NormalB $ feLow $ constSizedLTE 0 (constLTE 0)) []]]
(2,0) -> return [TH.FunD funN [TH.Clause [] (TH.NormalB $ feLow $ constSizedLTE 1 (constLTE i)) []]]
(n,0) -> return [TH.FunD funN [TH.Clause [] (TH.NormalB $ feLow $ constSizedLTE n (constLTE (shiftL (1 :: Int) i))) []]]
where
feLow e = TH.ConE 'FELow `TH.AppE` e
constLTE c = TH.ConE 'LFEConst `TH.AppE` TH.LitE (TH.IntegerL $ fromIntegral c)
constSizedLTE size e = TH.TupE [TH.LitE $ TH.IntegerL $ fromIntegral size, e]
conN = case cons of
TH.NormalC n _ -> n
_ -> error $ "Only normal constructors are allowed. Problem is "++show (TH.ppr cons)
-------------------------------------------------------------------------------
-- Trivial derivable instance for header tuples, BitRepr, etc.
$(liftM concat $ forM [2..8] $ \n -> let
names = map (TH.mkName . ("a"++) . show) [1..n]
types = map TH.VarT names
tupleP = TH.TupP (map TH.VarP names)
tupleType = tupleT types
fes = map (TH.ConT (''FE) `TH.AppT`) types
matchN = ''Match
changeN = ''Change
matchC t = TH.ConT (''Match) `TH.AppT` t
changeC t = TH.ConT (''Change) `TH.AppT` t
tupleC t = TH.ConT (''Tuple) `TH.AppT` t
bitReprC t = TH.ConT (''BitRepr) `TH.AppT` t
matchPred t = TH.ClassP matchN [t]
changePred t = TH.ClassP changeN [t]
bitReprPred t = TH.ClassP ''BitRepr [t]
tupleT ts = foldl TH.AppT (TH.TupleT (length ts)) ts
tupleFEs = tupleT fes
feTuple = TH.ConT ''FE `TH.AppT` tupleType
matchExpressionsCode = TH.FunD 'matchExpressions
[TH.Clause [tupleP] (TH.NormalB $ foldl1 (\a b -> TH.InfixE (Just a) (TH.VarE '(++)) (Just b)) $ map ((TH.VarE 'matchExpressions `TH.AppE` ) . TH.VarE) names) []]
match = TH.InstanceD (map matchPred fes) (matchC tupleFEs) [matchExpressionsCode]
change = TH.InstanceD (map changePred fes) (changeC tupleFEs) []
tupleNName = TH.mkName $ "tuple"++show n
tupleNTy = TH.SigD tupleNName $ TH.ForallT (map TH.PlainTV names) (map bitReprPred types) $ TH.ArrowT `TH.AppT` tupleFEs `TH.AppT` feTuple
tupleN = TH.FunD tupleNName [TH.Clause [] (TH.NormalB $ TH.VarE 'tuple) []]
x = TH.mkName "x"
tuplePFELow = TH.TupP $ map (\n -> TH.ConP 'FELow [TH.VarP n]) names
tupleF = TH.FunD 'tuple
[TH.Clause [tuplePFELow]
(TH.NormalB $ TH.ConE 'FELow `TH.AppE` TH.TupE [sumSize, cat])
[] ]
where
list = TH.ListE (map TH.VarE names)
sumSize = TH.VarE 'sum `TH.AppE` (TH.VarE 'map `TH.AppE` TH.VarE 'fst `TH.AppE` list)
cat = TH.ConE 'LFECat `TH.AppE` list
tupleD = TH.InstanceD [] (tupleC tupleFEs)
[ TH.TySynInstD ''FETuple [tupleFEs] feTuple
, tupleF
]
safeValueV = TH.FunD 'safeValue [TH.Clause [] (TH.NormalB $ TH.TupE $ map (const $ TH.VarE 'safeValue) names) []]
plusT a b = TH.ConT ''Plus `TH.AppT` a `TH.AppT` b
encodeF = TH.FunD 'encode
[TH.Clause [tupleP]
(TH.NormalB $ TH.VarE '_concatenateSizedBitVectors `TH.AppE`
TH.ListE (map (\v -> TH.TupE [TH.VarE 'bitReprSize `TH.AppE` v, TH.VarE 'encode `TH.AppE` v]) $ map TH.VarE names)) []]
decodeF = TH.FunD 'encode [TH.Clause [TH.VarP x] (TH.NormalB $ TH.VarE r) [rD, ssD]]
where
ssD = TH.ValD (TH.VarP ss) (TH.NormalB $ TH.ListE $ map (\n -> TH.VarE 'bitReprSize `TH.AppE` TH.VarE n) names) []
ss = TH.mkName "ss"
rD = TH.ValD (TH.AsP r tupleP) (TH.NormalB $ TH.VarE 'undefined) []
r = TH.mkName "r"
bitSize t = TH.ConT ''BitSize `TH.AppT` t
bitReprD = TH.InstanceD (TH.ClassP ''Nat [bitSize tupleType]:map bitReprPred types) (bitReprC tupleType)
[ encodeF
, TH.FunD 'decode [TH.Clause [TH.VarP x] (TH.NormalB $ TH.VarE 'undefined) []]
, safeValueV
, TH.TySynInstD ''BitSize [tupleType] $ foldl plusT (bitSize $ head types) (map bitSize $ tail types)
]
in do
let rs = [match, change, tupleD, bitReprD, tupleNTy, tupleN]
when (n == 3) $ TH.runIO $ mapM_ (print . TH.ppr) rs
return rs
)
| {'content_hash': '5ab1fa9b4d6928b85a8989f1e1cfea27', 'timestamp': '', 'source': 'github', 'line_count': 1087, 'max_line_length': 207, 'avg_line_length': 35.04967801287948, 'alnum_prop': 0.6387044279377412, 'repo_name': 'thesz/floha', 'id': 'fa54d73e23cfee1498db18dc792cb2d60b9b9d2b', 'size': '38192', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Language/Floha/Base.hs', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Haskell', 'bytes': '39647'}]} |
package se.gigurra.dcs.remote.dcsclient
import java.util.UUID
import com.twitter.io.Buf
import com.twitter.util.{Duration, Future, Promise}
case class Request(script: String,
timeOut: Duration = Duration.fromSeconds(2),
promise: Promise[Buf] = Promise[Buf],
id: String = UUID.randomUUID().toString) {
def reply: Future[Buf] = promise
}
| {'content_hash': 'a8f745b6a0716e0507be712612b22b45', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 63, 'avg_line_length': 31.615384615384617, 'alnum_prop': 0.6277372262773723, 'repo_name': 'GiGurra/dcs-remote2', 'id': '76be4732e10d245b82ca2a919d1462246996ac59', 'size': '411', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/se/gigurra/dcs/remote/dcsclient/Request.scala', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '300'}, {'name': 'Lua', 'bytes': '29470'}, {'name': 'Scala', 'bytes': '21436'}, {'name': 'Shell', 'bytes': '19395'}]} |
@interface VLTripPagerUnitTests : XCTestCase
@property (strong, nonatomic) NSDictionary *dictionary; // JSON Dict to initialize object
@property (strong, nonatomic) VLService *service;
@end
@implementation VLTripPagerUnitTests
#pragma mark - Class Methods
- (void)createDictionaryWithTrips:(NSArray *)trips
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
if (trips)
{
[mutableDict setObject:trips forKey:@"trips"];
}
self.dictionary = mutableDict;
}
- (NSDictionary *)createInitialPagerDictionary
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
[mutableDict setObject:[NSMutableArray new] forKey:@"trips"];
[mutableDict[@"trips"] addObject:[NSDictionary new]];
[mutableDict setObject:[NSMutableDictionary new] forKey:@"meta"];
[mutableDict[@"meta"] setObject:[NSMutableDictionary new] forKey:@"pagination"];
[mutableDict[@"meta"][@"pagination"] setObject:@1 forKey:@"limit"];
[mutableDict[@"meta"][@"pagination"] setObject:@2 forKey:@"remaining"];
[mutableDict[@"meta"][@"pagination"] setObject:[NSMutableDictionary new] forKey:@"links"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:@"https://initialPriorURL" forKey:@"prior"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:@"https://initialNextURL" forKey:@"next"];
return mutableDict;
}
- (NSDictionary *)createNextPagerDictionary
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
[mutableDict setObject:[NSMutableArray new] forKey:@"trips"];
[mutableDict[@"trips"] addObject:[NSDictionary new]];
[mutableDict setObject:[NSMutableDictionary new] forKey:@"meta"];
[mutableDict[@"meta"] setObject:[NSMutableDictionary new] forKey:@"pagination"];
[mutableDict[@"meta"][@"pagination"] setObject:@1 forKey:@"remaining"];
[mutableDict[@"meta"][@"pagination"] setObject:[NSMutableDictionary new] forKey:@"links"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:@"https://nextPriorURL" forKey:@"prior"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:@"https://nextNextURL" forKey:@"next"];
return mutableDict;
}
// This is the case where there are no next trips
- (NSDictionary *)createEmptyNextPagerDictionary
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
[mutableDict setObject:[NSMutableArray new] forKey:@"trips"];
[mutableDict setObject:[NSMutableDictionary new] forKey:@"meta"];
[mutableDict[@"meta"] setObject:[NSMutableDictionary new] forKey:@"pagination"];
[mutableDict[@"meta"][@"pagination"] setObject:@0 forKey:@"remaining"];
[mutableDict[@"meta"][@"pagination"] setObject:[NSMutableDictionary new] forKey:@"links"];
return mutableDict;
}
- (NSDictionary *)createZeroRemaingTripsPagerDictionaryWithLink
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
[mutableDict setObject:[NSMutableArray new] forKey:@"trips"];
[mutableDict setObject:[NSMutableDictionary new] forKey:@"meta"];
[mutableDict[@"meta"] setObject:[NSMutableDictionary new] forKey:@"pagination"];
[mutableDict[@"meta"][@"pagination"] setObject:@0 forKey:@"remaining"];
[mutableDict[@"meta"][@"pagination"] setObject:[NSMutableDictionary new] forKey:@"links"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:@"https://nextPriorURL" forKey:@"prior"];
return mutableDict;
}
- (NSDictionary *)createNullTripsJSONResponse
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
[mutableDict setObject:[NSNull null] forKey:@"trips"];
return mutableDict;
}
- (NSDictionary *)createTripsJSONResponseForNullKeyValueObjects
{
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
[mutableDict setObject:[NSMutableArray new] forKey:@"trips"];
[mutableDict setObject:[NSMutableDictionary new] forKey:@"meta"];
[mutableDict[@"meta"] setObject:[NSMutableDictionary new] forKey:@"pagination"];
[mutableDict[@"meta"][@"pagination"] setObject:[NSNull null] forKey:@"remaining"];
[mutableDict[@"meta"][@"pagination"] setObject:[NSMutableDictionary new] forKey:@"links"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:[NSNull null] forKey:@"prior"];
[mutableDict[@"meta"][@"pagination"][@"links"] setObject:[NSNull null] forKey:@"next"];
return mutableDict;
}
#pragma mark - XCTestCase Methods
- (void)setUp
{
[super setUp];
if (!_service)
{
_service = [[VLService alloc] init];
[_service useSession:[[VLSession alloc] initWithAccessToken:@"TEST"]];
}
}
- (void)tearDown
{
[super tearDown];
}
#pragma mark - InitWithDictionary Tests
- (void)testInitWithDictWithTrips
{
[self createDictionaryWithTrips:@[]];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:self.dictionary];
XCTAssertNil(tripPager.service , @"Service should be nil");
XCTAssertNotNil(tripPager.trips, @"Trips shoud not be nil");
XCTAssertEqual(tripPager.trips.count, [self.dictionary[@"trips"] count], @"Trips count should equal the number of trips passed in");
}
- (void)testInitWithDictWithoutTrips
{
[self createDictionaryWithTrips:nil];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:self.dictionary];
XCTAssertNil(tripPager.service , @"Service should be nil");
XCTAssertEqual(tripPager.trips.count, 0, @"Trips shoud be zero when we do not pass in a dictionary");
}
#pragma mark - InitWithDictionary:AndService Tests
- (void)testInitWithDictAndServiceWithTrips
{
[self createDictionaryWithTrips:@[]];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:self.dictionary service:self.service];
XCTAssertNotNil(tripPager.service , @"Service should be nil");
XCTAssertNotNil(tripPager.trips, @"Trips shoud not be nil");
XCTAssertEqual(tripPager.trips.count, [self.dictionary[@"trips"] count], @"Trips count should equal the number of trips passed in");
}
- (void)testInitWithDictAndServiceWithoutTrips
{
[self createDictionaryWithTrips:nil];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:self.dictionary service:self.service];
XCTAssertNotNil(tripPager.service , @"Service should be nil");
XCTAssertEqual(tripPager.trips.count, 0, @"Trips shoud be zero when we do not pass in a dictionary");
}
#pragma mark - getNextTrips Tests
- (void)testGetNextTripsOnSuccess
{
id mockConnection = OCMPartialMock(self.service);
NSDictionary *initialResponse = [self createInitialPagerDictionary];
[[[mockConnection expect] andDo:^(NSInvocation *invocation) {
NSDictionary *nextTripsResponse = [self createNextPagerDictionary];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL new] statusCode:200 HTTPVersion:nil headerFields:nil];
void (^successBlock)(NSDictionary *result, NSHTTPURLResponse *response) = nil;
[invocation getArgument:&successBlock atIndex:4];
successBlock(nextTripsResponse, response);
}] startWithHost:[OCMArg any] requestUri:[OCMArg any] onSuccess:[OCMArg any] onFailure:[OCMArg any]];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:initialResponse service:mockConnection];
unsigned long copyRemaining = tripPager.remaining;
NSURL *copyNextURL = tripPager.nextURL;
NSURL *copyPriorURL = tripPager.priorURL;
[tripPager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNil(error, @"Error should be nil");
XCTAssertNotEqualObjects(copyNextURL.absoluteString, tripPager.nextURL.absoluteString, @"nextURL should have been updated to grab the next set of trips.");
XCTAssertNotEqualObjects(copyPriorURL.absoluteString, tripPager.priorURL.absoluteString, @"priorURL should have been updated to grab the next set of trips.");
XCTAssertGreaterThanOrEqual(copyRemaining, tripPager.remaining, @"The remaining property should be decreasing with each pagination.");
XCTAssertNotNil(nextTrips, @"nextTrips should exist.");
XCTAssertLessThanOrEqual(nextTrips.count, tripPager.limit, @"The number of nextTrips returned back should be less than or equal to pager limit.");
XCTAssertGreaterThanOrEqual(nextTrips.count, 0, @"The number of nextTrips should always be at least zero.");
BOOL containsEachTrip = YES;
for (VLTrip *aTrip in nextTrips)
{
if (![tripPager.trips containsObject:aTrip])
{
containsEachTrip = NO;
break;
}
}
XCTAssertTrue(containsEachTrip, @"Each VLTrip returned in nextTrips should be in the VLTripPager's trips array.");
}];
}
// This is when there are zero remaining trips
- (void)testGetEmptyNextTripsOnSuccess
{
id mockConnection = OCMPartialMock(self.service);
NSDictionary *initialResponse = [self createInitialPagerDictionary];
[[[mockConnection expect] andDo:^(NSInvocation *invocation) {
NSDictionary *nextTripsResponse = [self createEmptyNextPagerDictionary];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL new] statusCode:200 HTTPVersion:nil headerFields:nil];
void (^successBlock)(NSDictionary *result, NSHTTPURLResponse *response) = nil;
[invocation getArgument:&successBlock atIndex:4];
successBlock(nextTripsResponse, response);
}] startWithHost:[OCMArg any] requestUri:[OCMArg any] onSuccess:[OCMArg any] onFailure:[OCMArg any]];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:initialResponse service:mockConnection];
[tripPager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNil(error, @"Error should be nil");
XCTAssertNotNil(nextTrips, @"nextTrips should exist.");
XCTAssertEqual(nextTrips.count, 0, @"Since there are no remaining trips nextTrips should be zero.");
XCTAssertEqual(tripPager.remaining, 0, @"There should be zero remaining trips.");
XCTAssertNil(tripPager.nextURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips.");
XCTAssertNil(tripPager.priorURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips.");
}];
}
- (void)testGetNextTripsWithZeroRemainingAndPriorURLOnSuccess
{
id mockConnection = OCMPartialMock(self.service);
NSDictionary *initialResponse = [self createZeroRemaingTripsPagerDictionaryWithLink];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:initialResponse service:mockConnection];
NSURL *copyNextURL = tripPager.nextURL;
NSURL *copyPriorURL = tripPager.priorURL;
[tripPager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNotNil(error, @"Error should not be nil");
XCTAssertEqual(error.code, NSURLErrorUnknown, @"The error codes should equal eachother in order to explain the error.");
XCTAssertNil(nextTrips, @"nextTrips should not exist.");
if (copyPriorURL.absoluteString.length > 0)
{
XCTAssertNotNil(tripPager.priorURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips. However, there shoudld be an error if there is this one exists.");
}
if (copyNextURL.absoluteString.length > 0)
{
XCTAssertNotNil(tripPager.nextURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips. However, there shoudld be an error if there is this one exists.");
}
}];
}
- (void)testGetNextTripsWithZeroRemainingOnSuccess
{
id mockConnection = OCMPartialMock(self.service);
NSDictionary *initialResponse = [self createEmptyNextPagerDictionary];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:initialResponse service:mockConnection];
[tripPager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNil(error, @"Error should be nil");
XCTAssertNotNil(nextTrips, @"nextTrips should exist.");
XCTAssertEqual(nextTrips.count, 0, @"Since there are no remaining trips nextTrips should be zero.");
XCTAssertEqual(tripPager.remaining, 0, @"There should be zero remaining trips.");
XCTAssertNil(tripPager.nextURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips.");
XCTAssertNil(tripPager.priorURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips.");
}];
}
- (void)testGetNextTripsOnFailure
{
id mockConnection = OCMPartialMock(self.service);
NSDictionary *initialResponse = [self createInitialPagerDictionary];
[[[mockConnection expect] andDo:^(NSInvocation *invocation) {
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL new] statusCode:400 HTTPVersion:nil headerFields:nil];
NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
void (^failureBlock)(NSError *error, NSHTTPURLResponse *response) = nil;
[invocation getArgument:&failureBlock atIndex:5];
failureBlock(error, response);
}] startWithHost:[OCMArg any] requestUri:[OCMArg any] onSuccess:[OCMArg any] onFailure:[OCMArg any]];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:initialResponse service:mockConnection];
[tripPager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNotNil(error, @"Error should not be nil");
XCTAssertNil(nextTrips, @"nextTrips should not exist.");
}];
}
- (void)testGetNextTripsWithoutVLService
{
VLTripPager *pager = [[VLTripPager alloc] initWithDictionary:nil service:nil];
[pager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNil(nextTrips);
XCTAssertNotNil(error);
XCTAssertEqual(error.code, NSURLErrorUserAuthenticationRequired);
}];
}
#pragma mark - Null tests
- (void)testForNullTrips
{
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:[self createNullTripsJSONResponse]];
XCTAssertEqual(tripPager.trips.count, 0, @"When we get a null value of trips back, we return an empty array");
}
// This is when there are null key value objects
- (void)testForNullKeyValueObjects
{
id mockConnection = OCMPartialMock(self.service);
NSDictionary *initialResponse = [self createInitialPagerDictionary];
[[[mockConnection expect] andDo:^(NSInvocation *invocation) {
NSDictionary *nextTripsResponse = [self createTripsJSONResponseForNullKeyValueObjects];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL new] statusCode:200 HTTPVersion:nil headerFields:nil];
void (^successBlock)(NSDictionary *result, NSHTTPURLResponse *response) = nil;
[invocation getArgument:&successBlock atIndex:4];
successBlock(nextTripsResponse, response);
}] startWithHost:[OCMArg any] requestUri:[OCMArg any] onSuccess:[OCMArg any] onFailure:[OCMArg any]];
VLTripPager *tripPager = [[VLTripPager alloc] initWithDictionary:initialResponse service:mockConnection];
[tripPager getNextTrips:^(NSArray<VLTrip *> * _Nullable nextTrips, NSError * _Nullable error) {
XCTAssertNil(error, @"Error should be nil");
XCTAssertNotNil(nextTrips, @"nextTrips should exist.");
XCTAssertEqual(nextTrips.count, 0, @"Since there are no remaining trips nextTrips should be zero.");
XCTAssertEqual(tripPager.remaining, 0, @"There should be zero remaining trips.");
XCTAssertNil(tripPager.nextURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips.");
XCTAssertNil(tripPager.priorURL, @"Since there are no remaining trips, then we should expect links dictionary to be empty since there is no new link to get more trips.");
}];
}
@end
| {'content_hash': '5a4a9ba6b57f57b20203d839e2598978', 'timestamp': '', 'source': 'github', 'line_count': 383, 'max_line_length': 249, 'avg_line_length': 44.09660574412533, 'alnum_prop': 0.7057256202261827, 'repo_name': 'vinli/ios-net', 'id': '4f63dd27fd83f52b22387d879e89eaa8541ae7d0', 'size': '17149', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'VinliSDKTests/VLTripPagerUnitTests.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '704646'}, {'name': 'Ruby', 'bytes': '986'}, {'name': 'Shell', 'bytes': '178'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.