branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>joaoabcoelho/lbcat-doxy<file_sep>/doc/html/search/files_c.js var searchData= [ ['object_2ecpp',['Object.cpp',['../Object_8cpp.html',1,'']]], ['object_2eh',['Object.h',['../Object_8h.html',1,'']]], ['object_2epy',['object.py',['../object_8py.html',1,'']]], ['options_2ecpp',['Options.cpp',['../Options_8cpp.html',1,'']]], ['options_2eh',['Options.h',['../Options_8h.html',1,'']]] ]; <file_sep>/doc/html/search/files_b.js var searchData= [ ['ni6008_2ecpp',['NI6008.cpp',['../NI6008_8cpp.html',1,'']]], ['ni6008_2eh',['NI6008.h',['../NI6008_8h.html',1,'']]] ]; <file_sep>/doc/html/search/typedefs_d.js var searchData= [ ['runsvc',['RunSvc',['../Application_8h.html#a59643f52f9391fa83f137814aaae27ef',1,'Application.h']]] ]; <file_sep>/doc/html/search/variables_8.js var searchData= [ ['h1',['h1',['../classPhaserRampExec.html#a8c13c96564df17be4e71685684e67edd',1,'PhaserRampExec']]], ['h2',['h2',['../classPhaserRampExec.html#a538d1b02ed14d13c71f54b2b48e765ba',1,'PhaserRampExec']]], ['h3',['h3',['../classPhaserRampExec.html#ad9ec4185f676732648c4886f28c9c6b7',1,'PhaserRampExec']]], ['h4',['h4',['../classPhaserRampExec.html#aa487df389ad66093dba562f27f558128',1,'PhaserRampExec']]], ['h7',['h7',['../classTestI2C.html#a5810c36ed7c1f23edaf77264084b005f',1,'TestI2C.h7()'],['../classTestSPI.html#aa072fcb2c8a99033ff634a04ac375ac7',1,'TestSPI.h7()'],['../classTestUSB.html#a18ac9c994c85be08fa09d6b3b1cb4446',1,'TestUSB.h7()'],['../classTestSuite.html#a64192d2fc98e5040f3156e460d23d8ac',1,'TestSuite.h7()']]], ['hevent',['hEvent',['../struct__OVERLAPPED.html#aa34d425458cd9ae57e8a8bf5aadc2923',1,'_OVERLAPPED']]], ['highdriveios',['HighDriveIOs',['../structft__program__data.html#a0f53600aee9f86d6286ecd0803f71825',1,'ft_program_data']]], ['hist_5ffile',['hist_file',['../namespacecat.html#a5be1540f4d9418c1650b9bafbe8efa5a',1,'cat']]], ['histo',['histo',['../classPhaserRampExec.html#a0c8d1c3ee09159cba1b1a07ce3fb1d96',1,'PhaserRampExec']]], ['hv1',['hv1',['../classPhaserRampExec.html#ad2a2a82a0be74bc39c84b580e33d9c34',1,'PhaserRampExec']]], ['hv2',['hv2',['../classPhaserRampExec.html#a9762fd546432b5f3dffc4c5323af56ac',1,'PhaserRampExec']]], ['hv3',['hv3',['../classPhaserRampExec.html#ad3127f38a360044f7ad8fed272f916f9',1,'PhaserRampExec']]], ['hv4',['hv4',['../classPhaserRampExec.html#a998b7e5a8d186df60c2d60cba2b43aa0',1,'PhaserRampExec']]] ]; <file_sep>/doc/html/search/enums_4.js var searchData= [ ['lvds_5foutput_5fcurrent_5fselector',['LVDS_OUTPUT_CURRENT_SELECTOR',['../LSDelayChipV1_8h.html#a9dbbe19d91a9e4d61f7291c5aeabce63',1,'LSDelayChipV1.h']]] ]; <file_sep>/doc/html/search/all_11.js var searchData= [ ['quality',['Quality',['../namespaceCATApp.html#a10d106f6dbef9da3b1ba48892278b9c4',1,'CATApp']]], ['quota',['Quota',['../namespaceSystem.html#a71a46d52920ca8e98fc4649949be58a7ace0b09a8b0f5c6a1973163673cd11edb',1,'System']]] ]; <file_sep>/doc/html/search/classes_4.js var searchData= [ ['element',['Element',['../classElement.html',1,'Element'],['../classelement_1_1element.html',1,'element.element']]], ['elementwrap',['ElementWrap',['../structElementWrap.html',1,'']]], ['emulatefe',['EmulateFE',['../classEmulateFE.html',1,'EmulateFE'],['../classEmulateFE_1_1EmulateFE.html',1,'EmulateFE.EmulateFE']]], ['event',['Event',['../classEvent.html',1,'']]], ['eventheader',['EventHeader',['../classEventHeader.html',1,'']]] ]; <file_sep>/doc/html/search/classes_9.js var searchData= [ ['logframe',['LogFrame',['../classLogFrame_1_1LogFrame.html',1,'LogFrame']]], ['lsdelaychipv1',['LSDelayChipV1',['../classLSDelayChipV1.html',1,'']]] ]; <file_sep>/doc/html/search/typedefs_f.js var searchData= [ ['threadhandle',['ThreadHandle',['../namespaceSystem.html#ad0b1bc3494d9fecebf85204f61224ac6',1,'System']]] ]; <file_sep>/doc/html/search/defines_1.js var searchData= [ ['adc_5f0_5fconfreg_5faddr',['ADC_0_CONFREG_ADDR',['../LSDelayChipV1_8h.html#ad1c6f1ce476a54a95469cd130dffa074',1,'LSDelayChipV1.h']]], ['adc_5f1_5fconfreg_5faddr',['ADC_1_CONFREG_ADDR',['../LSDelayChipV1_8h.html#a83aa641dd89900461bdc2ed428f2bce9',1,'LSDelayChipV1.h']]], ['adc_5f2_5fconfreg_5faddr',['ADC_2_CONFREG_ADDR',['../LSDelayChipV1_8h.html#abd577ee5c75174c74fc6886c1eaad80a',1,'LSDelayChipV1.h']]], ['adc_5f3_5fconfreg_5faddr',['ADC_3_CONFREG_ADDR',['../LSDelayChipV1_8h.html#a19e4f86f88864d8c249bd537ef628f92',1,'LSDelayChipV1.h']]] ]; <file_sep>/doc/html/search/namespaces_2.js var searchData= [ ['element',['element',['../namespaceelement.html',1,'']]], ['emulatefe',['EmulateFE',['../namespaceEmulateFE.html',1,'']]] ]; <file_sep>/doc/html/search/files_7.js var searchData= [ ['icecalv3_2ecpp',['ICECALv3.cpp',['../ICECALv3_8cpp.html',1,'']]], ['icecalv3_2eh',['ICECALv3.h',['../ICECALv3_8h.html',1,'']]], ['icphaser_2ecpp',['ICPhaser.cpp',['../ICPhaser_8cpp.html',1,'']]], ['icphaser_2eh',['ICPhaser.h',['../ICPhaser_8h.html',1,'']]], ['images_2epy',['images.py',['../images_8py.html',1,'']]], ['interface_2ecpp',['Interface.cpp',['../Interface_8cpp.html',1,'']]], ['interface_2eh',['Interface.h',['../Interface_8h.html',1,'']]], ['iodata_2ecpp',['IOdata.cpp',['../IOdata_8cpp.html',1,'']]], ['iodata_2eh',['IOdata.h',['../IOdata_8h.html',1,'']]], ['ioobject_2ecpp',['IOobject.cpp',['../IOobject_8cpp.html',1,'']]], ['ioobject_2eh',['IOobject.h',['../IOobject_8h.html',1,'']]] ]; <file_sep>/doc/html/search/typedefs_b.js var searchData= [ ['overlapped',['OVERLAPPED',['../CatCaloProto40MHz_2inc_2WinTypes_8h.html#acc634c5d2ba8f268fe1b5774d7477297',1,'OVERLAPPED():&#160;WinTypes.h'],['../LALUsbMLx64_2include_2WinTypes_8h.html#acc634c5d2ba8f268fe1b5774d7477297',1,'OVERLAPPED():&#160;WinTypes.h'],['../LALUsbx64_2include_2WinTypes_8h.html#acc634c5d2ba8f268fe1b5774d7477297',1,'OVERLAPPED():&#160;WinTypes.h']]] ]; <file_sep>/doc/html/search/files_3.js var searchData= [ ['element_2ecpp',['Element.cpp',['../Element_8cpp.html',1,'']]], ['element_2eh',['Element.h',['../Element_8h.html',1,'']]], ['element_2epy',['element.py',['../element_8py.html',1,'']]], ['emulatefe_2ecpp',['EmulateFE.cpp',['../EmulateFE_8cpp.html',1,'']]], ['emulatefe_2eh',['EmulateFE.h',['../EmulateFE_8h.html',1,'']]], ['emulatefe_2epy',['EmulateFE.py',['../EmulateFE_8py.html',1,'']]], ['event_2ecpp',['Event.cpp',['../Event_8cpp.html',1,'']]], ['event_2eh',['Event.h',['../Event_8h.html',1,'']]], ['eventheader_2ecpp',['EventHeader.cpp',['../EventHeader_8cpp.html',1,'']]], ['eventheader_2eh',['EventHeader.h',['../EventHeader_8h.html',1,'']]], ['eventheaderlinkdef_2eh',['EventHeaderLinkDef.h',['../EventHeaderLinkDef_8h.html',1,'']]], ['eventlinkdef_2eh',['EventLinkDef.h',['../EventLinkDef_8h.html',1,'']]] ]; <file_sep>/doc/html/CatCaloProto40MHz_2src_2Python_8cpp_source.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Cat: /home/eleclhcb/LHCb/lbcat-cmake/CatCaloProto40MHz/src/Python.cpp Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Cat </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_cbd8e9a422cfc6b49055e6fadc099056.html">lbcat-cmake</a></li><li class="navelem"><a class="el" href="dir_a8e6b2bad6357526dc3d11310864e483.html">CatCaloProto40MHz</a></li><li class="navelem"><a class="el" href="dir_cc8fedb7eeba4d36179a43e12977f4cb.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Python.cpp</div> </div> </div><!--header--> <div class="contents"> <a href="CatCaloProto40MHz_2src_2Python_8cpp.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="preprocessor">#include &lt;vector&gt;</span></div><div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="preprocessor">#include &lt;list&gt;</span></div><div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;</div><div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="Processus_8h.html">Processus.h</a>&quot;</span></div><div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;</div><div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="Element_8h.html">Element.h</a>&quot;</span></div><div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="A3PE_8h.html">A3PE.h</a>&quot;</span></div><div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="Proto40MHz__v1_8h.html">Proto40MHz_v1.h</a>&quot;</span></div><div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160;</div><div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160;<span class="preprocessor">#include &quot;Acquisition.h&quot;</span></div><div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="A3PE__BitFlip_8h.html">A3PE_BitFlip.h</a>&quot;</span></div><div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="UsbFTInterface_8h.html">UsbFTInterface.h</a>&quot;</span></div><div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160;</div><div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="RegisterTest_8h.html">RegisterTest.h</a>&quot;</span></div><div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="UsbFTInterfaceTest_8h.html">UsbFTInterfaceTest.h</a>&quot;</span></div><div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160;</div><div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160;<span class="preprocessor">#include &lt;boost/python.hpp&gt;</span></div><div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160;<span class="preprocessor">#include &lt;boost/python/suite/indexing/vector_indexing_suite.hpp&gt;</span></div><div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;</div><div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160;<span class="keyword">using namespace </span><a class="code" href="namespaceboost_1_1python.html">boost::python</a>;</div><div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160;</div><div class="line"><a name="l00022"></a><span class="lineno"><a class="line" href="CatCaloProto40MHz_2src_2Python_8cpp.html#af793744b9236fc3e951260d9965db307"> 22</a></span>&#160;<a class="code" href="CatBcn_2src_2Python_8cpp.html#a527b17e3e2c7c505c5d99fcbaa744eab">BOOST_PYTHON_MODULE</a>(libCatCaloProto40MHz)</div><div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;{</div><div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160; class_&lt;A3PE, bases &lt;Element&gt; &gt;(<span class="stringliteral">&quot;A3PE&quot;</span>)</div><div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160; .def(<span class="stringliteral">&quot;ctrlReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#ae5fc5dac92af2b34a41be388586647be">A3PE::ctrlReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160; .def(<span class="stringliteral">&quot;resetReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#afd34bfbfd92838717c7cdec856b2a0b2">A3PE::resetReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160; .def(<span class="stringliteral">&quot;setupReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a94d96383e441153ed01e82cc12d2f593">A3PE::setupReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160; .def(<span class="stringliteral">&quot;statusReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#af260fc8bce78935b7bad57c987574683">A3PE::statusReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160; .def(<span class="stringliteral">&quot;acqReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aca56dadafd70e670e75569ee03d91651">A3PE::acqReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160; .def(<span class="stringliteral">&quot;latencyReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aca56dadafd70e670e75569ee03d91651">A3PE::acqReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00031"></a><span class="lineno"> 31</span>&#160; .def(<span class="stringliteral">&quot;writeLengthFifoReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a3b75531731fc939206cce076f7ac9f9a">A3PE::writeLengthFifoReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00032"></a><span class="lineno"> 32</span>&#160; .def(<span class="stringliteral">&quot;ctrlAnaMezzReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aa94c6120a73194d69dc5761cf90a4800">A3PE::ctrlAnaMezzReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00033"></a><span class="lineno"> 33</span>&#160; .def(<span class="stringliteral">&quot;clockDivisionReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a10cf30ff852d7580ba94dbee0c48e0d5">A3PE::clockDivisionReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00034"></a><span class="lineno"> 34</span>&#160; .def(<span class="stringliteral">&quot;triggerReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a4bf922f391fee6753fb0d53e133603b7">A3PE::triggerReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00035"></a><span class="lineno"> 35</span>&#160; .def(<span class="stringliteral">&quot;toAXReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a43b0006fafa3aeae353abb2ac30e872c">A3PE::toAXReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00036"></a><span class="lineno"> 36</span>&#160; .def(<span class="stringliteral">&quot;fromAXReg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a0b2fabe7e7941f33de210d9385b7afce">A3PE::fromAXReg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160; .def(<span class="stringliteral">&quot;spare3Reg&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a979a9ac462eb55e611f6de4e94bad18e">A3PE::spare3Reg</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160; .def(<span class="stringliteral">&quot;storageRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#af241373059bad4a3c376ab2ac98a7b29">A3PE::storageRam</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00039"></a><span class="lineno"> 39</span>&#160; .def(<span class="stringliteral">&quot;patternRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a94ef54086baa29f7f6638c13d8906e56">A3PE::patternRam</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00040"></a><span class="lineno"> 40</span>&#160; .def(<span class="stringliteral">&quot;triggerRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aad0f7ac467db22e5608ae6b0957665a1">A3PE::triggerRam</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00041"></a><span class="lineno"> 41</span>&#160; .def(<span class="stringliteral">&quot;toAXRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a16b16ac12705b9dd93d70fa172deb584">A3PE::toAXRam</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00042"></a><span class="lineno"> 42</span>&#160; .def(<span class="stringliteral">&quot;fromAXRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a7c9026a74c1954b2d250be05fbc1c8c5">A3PE::fromAXRam</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00043"></a><span class="lineno"> 43</span>&#160; .def(<span class="stringliteral">&quot;testRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a9327d0bd2efb5baa7c6b7de27bbc5997">A3PE::testRam</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00044"></a><span class="lineno"> 44</span>&#160; .def(<span class="stringliteral">&quot;reset&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a449775588222d544aeeaab190d553652">A3PE::reset</a>)</div><div class="line"><a name="l00045"></a><span class="lineno"> 45</span>&#160; .def(<span class="stringliteral">&quot;resetStorageFifo&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a8e7074703227b118aa9230258f22b44c">A3PE::resetStorageFifo</a>)</div><div class="line"><a name="l00046"></a><span class="lineno"> 46</span>&#160; .def(<span class="stringliteral">&quot;resetTriggerFifo&quot;</span> ,&amp;<a class="code" href="classA3PE.html#ac81388bd2988192cf54034b245f69891">A3PE::resetTriggerFifo</a>)</div><div class="line"><a name="l00047"></a><span class="lineno"> 47</span>&#160; .def(<span class="stringliteral">&quot;resetPatternFifo&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a4e5b677dd2872428abf3d64ef7a769c1">A3PE::resetPatternFifo</a>)</div><div class="line"><a name="l00048"></a><span class="lineno"> 48</span>&#160; .def(<span class="stringliteral">&quot;resetFromAXRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aa10639563d06c0d09f3c0725710ff35d">A3PE::resetFromAXRam</a>)</div><div class="line"><a name="l00049"></a><span class="lineno"> 49</span>&#160; .def(<span class="stringliteral">&quot;resetToAXRam&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a31f72fac5a0f00bcf3a0db99bd5704ee">A3PE::resetToAXRam</a>)</div><div class="line"><a name="l00050"></a><span class="lineno"> 50</span>&#160; .def(<span class="stringliteral">&quot;resetSequenceFromToAX&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a6015ba83a7b828efb1969291ab740eee">A3PE::resetSequenceFromToAX</a>)</div><div class="line"><a name="l00051"></a><span class="lineno"> 51</span>&#160; .def(<span class="stringliteral">&quot;resetUsbPhasers&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a0ad1110ea755ffd0b277284d807a8794">A3PE::resetUsbPhasers</a>)</div><div class="line"><a name="l00052"></a><span class="lineno"> 52</span>&#160; .def(<span class="stringliteral">&quot;resetLatencyCounter&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a44c50d822ac4f5d8f2b8ed75c5b90580">A3PE::resetLatencyCounter</a>)</div><div class="line"><a name="l00053"></a><span class="lineno"> 53</span>&#160; .def(<span class="stringliteral">&quot;resetFE&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a2cfdb2f37d3d786cbe1ff42fef37b276">A3PE::resetFE</a>)</div><div class="line"><a name="l00054"></a><span class="lineno"> 54</span>&#160; .def(<span class="stringliteral">&quot;resetSPI&quot;</span> ,&amp;<a class="code" href="classA3PE.html#ae164123b49f8c4d1d119dbf201f0a839">A3PE::resetSPI</a>)</div><div class="line"><a name="l00055"></a><span class="lineno"> 55</span>&#160; .def(<span class="stringliteral">&quot;setEnableADC&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a0c90134c3440c8b8c8dc796c43893d64">A3PE::setEnableADC</a>)</div><div class="line"><a name="l00056"></a><span class="lineno"> 56</span>&#160; .def(<span class="stringliteral">&quot;enableADC&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a02608198bd28bc61882f27368fd90db1">A3PE::enableADC</a>)</div><div class="line"><a name="l00057"></a><span class="lineno"> 57</span>&#160; .def(<span class="stringliteral">&quot;setWriteStorageFifoUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aa688f9dff8d2892464fcd13fdf3600ad">A3PE::setWriteStorageFifoUsb</a>)</div><div class="line"><a name="l00058"></a><span class="lineno"> 58</span>&#160; .def(<span class="stringliteral">&quot;writeStorageFifoUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#af15048318a126074e28df1c6120d5e0d">A3PE::writeStorageFifoUsb</a>)</div><div class="line"><a name="l00059"></a><span class="lineno"> 59</span>&#160; .def(<span class="stringliteral">&quot;setReadPatternFifoUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a9d3ba9807ea65be0af7f23ffa2372d6b">A3PE::setReadPatternFifoUsb</a>)</div><div class="line"><a name="l00060"></a><span class="lineno"> 60</span>&#160; .def(<span class="stringliteral">&quot;readPatternFifoUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a3bb47f43f9f98d8a0d825aadc04e5ab6">A3PE::readPatternFifoUsb</a>)</div><div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160; .def(<span class="stringliteral">&quot;setReadTriggerFifoUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a1d0dd1db3c493bc31aa56b55e7439e0e">A3PE::setReadTriggerFifoUsb</a>)</div><div class="line"><a name="l00062"></a><span class="lineno"> 62</span>&#160; .def(<span class="stringliteral">&quot;readTriggerFifoUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a083315774486528a8b6c40e240fbf98f">A3PE::readTriggerFifoUsb</a>)</div><div class="line"><a name="l00063"></a><span class="lineno"> 63</span>&#160; .def(<span class="stringliteral">&quot;setReadToAXRamUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a7ad649611d4cc5a7743db54aa3a4f943">A3PE::setReadToAXRamUsb</a>)</div><div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160; .def(<span class="stringliteral">&quot;readToAXRamUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#af3152e461d446f442cfa7b69456ac276">A3PE::readToAXRamUsb</a>)</div><div class="line"><a name="l00065"></a><span class="lineno"> 65</span>&#160; .def(<span class="stringliteral">&quot;setWriteFromAXRamUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aeb276fae7f19c45b4b4a3a5a2b99c337">A3PE::setWriteFromAXRamUsb</a>)</div><div class="line"><a name="l00066"></a><span class="lineno"> 66</span>&#160; .def(<span class="stringliteral">&quot;writeFromAXRamUsb&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a3b4333f547a2a36fc1f38bf4ca9afa89">A3PE::writeFromAXRamUsb</a>)</div><div class="line"><a name="l00067"></a><span class="lineno"> 67</span>&#160; .def(<span class="stringliteral">&quot;setSoftwareTrigger&quot;</span> ,&amp;<a class="code" href="classA3PE.html#aac0ee532f78885a25eebddbad501417f">A3PE::setSoftwareTrigger</a>)</div><div class="line"><a name="l00068"></a><span class="lineno"> 68</span>&#160; .def(<span class="stringliteral">&quot;softwareTrigger&quot;</span> ,&amp;<a class="code" href="classA3PE.html#acb2ccd6b78b39a0a9e360439b3b6f4c7">A3PE::softwareTrigger</a>)</div><div class="line"><a name="l00069"></a><span class="lineno"> 69</span>&#160; .def(<span class="stringliteral">&quot;setClockDivision&quot;</span> ,&amp;<a class="code" href="classA3PE.html#acf354b2c85a7e20f7f037beb278dd79d">A3PE::setClockDivision</a>)</div><div class="line"><a name="l00070"></a><span class="lineno"> 70</span>&#160; .def(<span class="stringliteral">&quot;clockDivision&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a81e32c82ca14f85fd7f26cd9a54f7a38">A3PE::clockDivision</a>)</div><div class="line"><a name="l00071"></a><span class="lineno"> 71</span>&#160; .def(<span class="stringliteral">&quot;setTriggerDelay&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a6a63fc9503e0aa89ee9928fc7222ce0f">A3PE::setTriggerDelay</a>)</div><div class="line"><a name="l00072"></a><span class="lineno"> 72</span>&#160; <span class="comment">// .def(&quot;setSeqPulseDelay&quot; ,&amp;A3PE::setSeqPulseDelay)</span></div><div class="line"><a name="l00073"></a><span class="lineno"> 73</span>&#160; .def(<span class="stringliteral">&quot;triggerDelay&quot;</span> ,&amp;<a class="code" href="classA3PE.html#ac0aabc1457923b7ee7da0a2c91c46451">A3PE::triggerDelay</a>)</div><div class="line"><a name="l00074"></a><span class="lineno"> 74</span>&#160; <span class="comment">// .def(&quot;seqPulseDelay&quot; ,&amp;A3PE::seqPulseDelay)</span></div><div class="line"><a name="l00075"></a><span class="lineno"> 75</span>&#160; .def(<span class="stringliteral">&quot;setTriggerRate&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a1ae8e5a69e17d6b3157779544fa14c75">A3PE::setTriggerRate</a>)</div><div class="line"><a name="l00076"></a><span class="lineno"> 76</span>&#160; .def(<span class="stringliteral">&quot;triggerRate&quot;</span> ,&amp;<a class="code" href="classA3PE.html#ada46375753047d6a74acdec442044f39">A3PE::triggerRate</a>)</div><div class="line"><a name="l00077"></a><span class="lineno"> 77</span>&#160; .def(<span class="stringliteral">&quot;setNTrigger&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a81db44ddfc42b67ed08756b113b8e122">A3PE::setNTrigger</a>)</div><div class="line"><a name="l00078"></a><span class="lineno"> 78</span>&#160; .def(<span class="stringliteral">&quot;nTrigger&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a3398fa3ce59a4b1b946e7b4ab4912580">A3PE::nTrigger</a>)</div><div class="line"><a name="l00079"></a><span class="lineno"> 79</span>&#160; .def(<span class="stringliteral">&quot;setFifoLatency&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a969469569005dfb130aca674de5dacff">A3PE::setFifoLatency</a>)</div><div class="line"><a name="l00080"></a><span class="lineno"> 80</span>&#160; .def(<span class="stringliteral">&quot;fifoLatency&quot;</span> ,&amp;<a class="code" href="classA3PE.html#a7f6959a6a38c16fa6609560827413764">A3PE::fifoLatency</a>)</div><div class="line"><a name="l00081"></a><span class="lineno"> 81</span>&#160; .def(<span class="stringliteral">&quot;setFifoDepth&quot;</span>, &amp;<a class="code" href="classA3PE.html#a4d8f78a1b09b409f288b34d503c71146">A3PE::setFifoDepth</a>)</div><div class="line"><a name="l00082"></a><span class="lineno"> 82</span>&#160; .def(<span class="stringliteral">&quot;fifoDepth&quot;</span>, &amp;<a class="code" href="classA3PE.html#a8bb523e4a7a5dbb6ab3c5549ebf6db86">A3PE::fifoDepth</a>)</div><div class="line"><a name="l00083"></a><span class="lineno"> 83</span>&#160; .def(<span class="stringliteral">&quot;acquisition&quot;</span>, &amp;<a class="code" href="classA3PE.html#a035886b99761cc4f3c342ff0b4e44f59">A3PE::acquisition</a>)</div><div class="line"><a name="l00084"></a><span class="lineno"> 84</span>&#160; .def(<span class="stringliteral">&quot;trigger&quot;</span>, &amp;<a class="code" href="classA3PE.html#a75cd0377eb653ed22c4d258ab359f3d6">A3PE::trigger</a>)</div><div class="line"><a name="l00085"></a><span class="lineno"> 85</span>&#160; .def(<span class="stringliteral">&quot;enableStorage&quot;</span>, &amp;<a class="code" href="classA3PE.html#a2071d7922f140ee6705da954efb685f7">A3PE::enableStorage</a>)</div><div class="line"><a name="l00086"></a><span class="lineno"> 86</span>&#160; .def(<span class="stringliteral">&quot;dataReady&quot;</span>, &amp;<a class="code" href="classA3PE.html#a55df064c578bbc1e80a3b5fc05933f27">A3PE::dataReady</a>)</div><div class="line"><a name="l00087"></a><span class="lineno"> 87</span>&#160; .def(<span class="stringliteral">&quot;dumpStorage&quot;</span>, &amp;<a class="code" href="classA3PE.html#ad7999557f9d561dec67526730a3c97ef">A3PE::dumpStorage</a>)</div><div class="line"><a name="l00088"></a><span class="lineno"> 88</span>&#160; .def(<span class="stringliteral">&quot;dumpPattern&quot;</span>, &amp;<a class="code" href="classA3PE.html#a23da04d3c7e632dfb64e5ed4e21a21f3">A3PE::dumpPattern</a>)</div><div class="line"><a name="l00089"></a><span class="lineno"> 89</span>&#160; .def(<span class="stringliteral">&quot;dumpTrigger&quot;</span>, &amp;<a class="code" href="classA3PE.html#aeab7701d0d1f6fd910e952b631769d42">A3PE::dumpTrigger</a>)</div><div class="line"><a name="l00090"></a><span class="lineno"> 90</span>&#160; .def(<span class="stringliteral">&quot;dumpToAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#ad6b6f1ae4ac23e6d0827eee8cc2c98e4">A3PE::dumpToAX</a>)</div><div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160; .def(<span class="stringliteral">&quot;dumpFromAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#a60a510251ec2b5fd800af2ba88e9fdac">A3PE::dumpFromAX</a>)</div><div class="line"><a name="l00092"></a><span class="lineno"> 92</span>&#160; .def(<span class="stringliteral">&quot;loadStorage&quot;</span>, &amp;<a class="code" href="classA3PE.html#a8bd4a7a5dd8219f93386756c24a0f0b5">A3PE::loadStorage</a>)</div><div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160; .def(<span class="stringliteral">&quot;loadPattern&quot;</span>, &amp;<a class="code" href="classA3PE.html#a522cba0a4d976eec59222504af188fb2">A3PE::loadPattern</a>)</div><div class="line"><a name="l00094"></a><span class="lineno"> 94</span>&#160; .def(<span class="stringliteral">&quot;loadTrigger&quot;</span>, &amp;<a class="code" href="classA3PE.html#a34a9499a0d9065a1b5772880d7e8d5c4">A3PE::loadTrigger</a>)</div><div class="line"><a name="l00095"></a><span class="lineno"> 95</span>&#160; .def(<span class="stringliteral">&quot;loadToAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#a40017b4138705690f8b04e336a7ffcdf">A3PE::loadToAX</a>)</div><div class="line"><a name="l00096"></a><span class="lineno"> 96</span>&#160; .def(<span class="stringliteral">&quot;loadFromAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#a65235f7d42e8f7fb6056f5629545d2aa">A3PE::loadFromAX</a>)</div><div class="line"><a name="l00097"></a><span class="lineno"> 97</span>&#160; .def(<span class="stringliteral">&quot;setInternalAXSequence&quot;</span>, &amp;<a class="code" href="classA3PE.html#ad5f953a38661104a87834cc8a63252fa">A3PE::setInternalAXSequence</a>)</div><div class="line"><a name="l00098"></a><span class="lineno"> 98</span>&#160; .def(<span class="stringliteral">&quot;internalAXSequence&quot;</span>, &amp;<a class="code" href="classA3PE.html#a4b9cf42bdd0a14e48807faa0956c59bd">A3PE::internalAXSequence</a>)</div><div class="line"><a name="l00099"></a><span class="lineno"> 99</span>&#160; .def(<span class="stringliteral">&quot;setLengthAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#a0300aa5c5ed02b82275c1de434196b9a">A3PE::setLengthAX</a>)</div><div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160; .def(<span class="stringliteral">&quot;lengthAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#acb95104d817db2e4f97e250f7e45b43d">A3PE::lengthAX</a>)</div><div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160; .def(<span class="stringliteral">&quot;setLatencyAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#a53882e1272e8146e51837904ea00f33c">A3PE::setLatencyAX</a>)</div><div class="line"><a name="l00102"></a><span class="lineno"> 102</span>&#160; .def(<span class="stringliteral">&quot;latencyAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#ab5970721a8172ae57b3da68040f58199">A3PE::latencyAX</a>)</div><div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160; .def(<span class="stringliteral">&quot;setAddFromAXRam&quot;</span>, &amp;<a class="code" href="classA3PE.html#a834fde5951d2c1bf6b41842520360fce">A3PE::setAddFromAXRam</a>)</div><div class="line"><a name="l00104"></a><span class="lineno"> 104</span>&#160; .def(<span class="stringliteral">&quot;setAddToAXRam&quot;</span>, &amp;<a class="code" href="classA3PE.html#a54fe4da570ea8833fe2c981de1085387">A3PE::setAddToAXRam</a>)</div><div class="line"><a name="l00105"></a><span class="lineno"> 105</span>&#160; .def(<span class="stringliteral">&quot;startSequenceAX&quot;</span>, &amp;<a class="code" href="classA3PE.html#a91ae249ca14676f8b0832487955fcf8c">A3PE::startSequenceAX</a>)</div><div class="line"><a name="l00106"></a><span class="lineno"> 106</span>&#160; .def(<span class="stringliteral">&quot;setPipeline&quot;</span>, &amp;<a class="code" href="classA3PE.html#a5b3840fc8edd14427ac9fb4def3171d3">A3PE::setPipeline</a>)</div><div class="line"><a name="l00107"></a><span class="lineno"> 107</span>&#160; .def(<span class="stringliteral">&quot;pipeline&quot;</span>, &amp;<a class="code" href="classA3PE.html#aeb22b2fcba4d14f234ad2d6dcef7948c">A3PE::pipeline</a>)</div><div class="line"><a name="l00108"></a><span class="lineno"> 108</span>&#160; ;</div><div class="line"><a name="l00109"></a><span class="lineno"> 109</span>&#160;</div><div class="line"><a name="l00110"></a><span class="lineno"> 110</span>&#160; class_&lt;Proto40MHz_v1, bases &lt;Element&gt; &gt;(<span class="stringliteral">&quot;Proto40MHz_v1&quot;</span>)</div><div class="line"><a name="l00111"></a><span class="lineno"> 111</span>&#160; .def(<span class="stringliteral">&quot;usb&quot;</span>,&amp;<a class="code" href="classProto40MHz__v1.html#aee48500fba238c4caf8502db32ebb991">Proto40MHz_v1::usb</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00112"></a><span class="lineno"> 112</span>&#160; .def(<span class="stringliteral">&quot;phaser0&quot;</span>,&amp;<a class="code" href="classProto40MHz__v1.html#a545f205296c492530a50febd54584f73">Proto40MHz_v1::phaser0</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00113"></a><span class="lineno"> 113</span>&#160; .def(<span class="stringliteral">&quot;phaser1&quot;</span>,&amp;<a class="code" href="classProto40MHz__v1.html#a9c4ef3187b86b74b05bdec3c167a405e">Proto40MHz_v1::phaser1</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00114"></a><span class="lineno"> 114</span>&#160; .def(<span class="stringliteral">&quot;phaser2&quot;</span>,&amp;<a class="code" href="classProto40MHz__v1.html#a59defd14376765f7df8f87d594170527">Proto40MHz_v1::phaser2</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00115"></a><span class="lineno"> 115</span>&#160; .def(<span class="stringliteral">&quot;a3pe&quot;</span>, &amp;<a class="code" href="classProto40MHz__v1.html#a263cfc900aafa3ceee1af4b596a824de">Proto40MHz_v1::a3pe</a>,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00116"></a><span class="lineno"> 116</span>&#160; ;</div><div class="line"><a name="l00117"></a><span class="lineno"> 117</span>&#160;</div><div class="line"><a name="l00118"></a><span class="lineno"> 118</span>&#160; class_&lt;Acquisition,bases &lt;Processus&gt; &gt;(<span class="stringliteral">&quot;Acquisition&quot;</span>)</div><div class="line"><a name="l00119"></a><span class="lineno"> 119</span>&#160; .def(<span class="stringliteral">&quot;initialize&quot;</span>,&amp;<a class="code" href="classAcquisition.html#acffc6b70b80811657409f92e489584ba">Acquisition::initialize</a>)</div><div class="line"><a name="l00120"></a><span class="lineno"> 120</span>&#160; .def(<span class="stringliteral">&quot;execute&quot;</span>,&amp;<a class="code" href="classAcquisition.html#ae3b63064bee1b042914b63ae4135cbd8">Acquisition::execute</a>)</div><div class="line"><a name="l00121"></a><span class="lineno"> 121</span>&#160; .def(<span class="stringliteral">&quot;finalize&quot;</span>,&amp;<a class="code" href="classAcquisition.html#ab8ffcd86548280f0403b3ae6338f2499">Acquisition::finalize</a>)</div><div class="line"><a name="l00122"></a><span class="lineno"> 122</span>&#160; .def(<span class="stringliteral">&quot;setDepth&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a303145d497f99da966fcfd95c00cd81e">Acquisition::setDepth</a>)</div><div class="line"><a name="l00123"></a><span class="lineno"> 123</span>&#160; .def(<span class="stringliteral">&quot;depth&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a1ad973e21a067c0de0b6264d0eb5182b">Acquisition::depth</a>)</div><div class="line"><a name="l00124"></a><span class="lineno"> 124</span>&#160; .def(<span class="stringliteral">&quot;setChannels&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a3ee93f665573b4622bd9cba92c0cc04e">Acquisition::setChannels</a>)</div><div class="line"><a name="l00125"></a><span class="lineno"> 125</span>&#160; .def(<span class="stringliteral">&quot;channels&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a3041537afcb4dfe5c6940f0ef6829265">Acquisition::channels</a>)</div><div class="line"><a name="l00126"></a><span class="lineno"> 126</span>&#160; .def(<span class="stringliteral">&quot;setTrigger&quot;</span>,&amp;<a class="code" href="classAcquisition.html#acdb167b43f3babb59a98698aa5c5066f">Acquisition::setTrigger</a>)</div><div class="line"><a name="l00127"></a><span class="lineno"> 127</span>&#160; .def(<span class="stringliteral">&quot;trigger&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a6f680938eb6a42d57dfa7466e8852af9">Acquisition::trigger</a>)</div><div class="line"><a name="l00128"></a><span class="lineno"> 128</span>&#160; .def(<span class="stringliteral">&quot;setStoreTree&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a759193856d26354722e5f647e60e16de">Acquisition::setStoreTree</a>)</div><div class="line"><a name="l00129"></a><span class="lineno"> 129</span>&#160; .def(<span class="stringliteral">&quot;setStoreTrend&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a1ceff272a1ad030dcd20c0dcddc65443">Acquisition::setStoreTrend</a>)</div><div class="line"><a name="l00130"></a><span class="lineno"> 130</span>&#160; .def(<span class="stringliteral">&quot;setStoreSample&quot;</span>,&amp;<a class="code" href="classAcquisition.html#af36a1b660244096b7d274f591f67b695">Acquisition::setStoreSample</a>)</div><div class="line"><a name="l00131"></a><span class="lineno"> 131</span>&#160; .def(<span class="stringliteral">&quot;storeTree&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a8ab7e58ccb3fee54eb6850e5081fae10">Acquisition::storeTree</a>)</div><div class="line"><a name="l00132"></a><span class="lineno"> 132</span>&#160; .def(<span class="stringliteral">&quot;storeTrend&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a5af693448daef6e9e054ab7f1aa50784">Acquisition::storeTrend</a>)</div><div class="line"><a name="l00133"></a><span class="lineno"> 133</span>&#160; .def(<span class="stringliteral">&quot;storeSample&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a9af304e0fb2076cd4f92703708efe83e">Acquisition::storeSample</a>)</div><div class="line"><a name="l00134"></a><span class="lineno"> 134</span>&#160; .def(<span class="stringliteral">&quot;setDeadTime&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a37e05315fc47958c290a7d938c61e067">Acquisition::setDeadTime</a>)</div><div class="line"><a name="l00135"></a><span class="lineno"> 135</span>&#160; .def(<span class="stringliteral">&quot;deadTime&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a8fb2cd60a34993ab0952d719a8517831">Acquisition::deadTime</a>)</div><div class="line"><a name="l00136"></a><span class="lineno"> 136</span>&#160; .def(<span class="stringliteral">&quot;setSample&quot;</span>,&amp;<a class="code" href="classAcquisition.html#ade6fd6483b3e3737fe7dcdffb5065954">Acquisition::setSample</a>)</div><div class="line"><a name="l00137"></a><span class="lineno"> 137</span>&#160; .def(<span class="stringliteral">&quot;sample&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a83181975c0746e5837d53933031e7b62">Acquisition::sample</a>)</div><div class="line"><a name="l00138"></a><span class="lineno"> 138</span>&#160; .def(<span class="stringliteral">&quot;setNBins&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a6ee040a009aa48f848b1e12434135db9">Acquisition::setNBins</a>)</div><div class="line"><a name="l00139"></a><span class="lineno"> 139</span>&#160; .def(<span class="stringliteral">&quot;nBins&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a3a3dad0de9535d5a29c0810a5bdc3ae3">Acquisition::nBins</a>)</div><div class="line"><a name="l00140"></a><span class="lineno"> 140</span>&#160; .def(<span class="stringliteral">&quot;setMinRange&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a8a15ffc6e539a3ae12efe4bea1ca7587">Acquisition::setMinRange</a>)</div><div class="line"><a name="l00141"></a><span class="lineno"> 141</span>&#160; .def(<span class="stringliteral">&quot;minRange&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a44f441710231748d2ca8f691647b2bcd">Acquisition::minRange</a>)</div><div class="line"><a name="l00142"></a><span class="lineno"> 142</span>&#160; .def(<span class="stringliteral">&quot;setMaxRange&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a786da6cff5428020034be23e554e0e1b">Acquisition::setMaxRange</a>)</div><div class="line"><a name="l00143"></a><span class="lineno"> 143</span>&#160; .def(<span class="stringliteral">&quot;maxRange&quot;</span>,&amp;<a class="code" href="classAcquisition.html#a386f3ebc6b1d4956aa7e40b314ddb4eb">Acquisition::maxRange</a>)</div><div class="line"><a name="l00144"></a><span class="lineno"> 144</span>&#160; ;</div><div class="line"><a name="l00145"></a><span class="lineno"> 145</span>&#160;</div><div class="line"><a name="l00146"></a><span class="lineno"> 146</span>&#160; class_&lt;A3PE_BitFlip,bases &lt;Processus&gt; &gt;(<span class="stringliteral">&quot;A3PE_BitFlip&quot;</span>)</div><div class="line"><a name="l00147"></a><span class="lineno"> 147</span>&#160; .def(<span class="stringliteral">&quot;initialize&quot;</span>,&amp;<a class="code" href="classA3PE__BitFlip.html#a88dc6cfe690a518e38ff6d89026e6e0c">A3PE_BitFlip::initialize</a>)</div><div class="line"><a name="l00148"></a><span class="lineno"> 148</span>&#160; .def(<span class="stringliteral">&quot;execute&quot;</span>,&amp;<a class="code" href="classA3PE__BitFlip.html#affa7320fb39001a6e9b5696542fe4584">A3PE_BitFlip::execute</a>)</div><div class="line"><a name="l00149"></a><span class="lineno"> 149</span>&#160; .def(<span class="stringliteral">&quot;finalize&quot;</span>,&amp;<a class="code" href="classA3PE__BitFlip.html#ab40772a001613a0e1932d1e356ccf717">A3PE_BitFlip::finalize</a>)</div><div class="line"><a name="l00150"></a><span class="lineno"> 150</span>&#160; .def(<span class="stringliteral">&quot;setFile&quot;</span>,&amp;<a class="code" href="classA3PE__BitFlip.html#a079d34acd89f699395a9bbf6b4918205">A3PE_BitFlip::setFile</a>)</div><div class="line"><a name="l00151"></a><span class="lineno"> 151</span>&#160; .def(<span class="stringliteral">&quot;file&quot;</span>,&amp;<a class="code" href="classA3PE__BitFlip.html#ace874c555080ce6cb68b6bf320977a5a">A3PE_BitFlip::file</a>)</div><div class="line"><a name="l00152"></a><span class="lineno"> 152</span>&#160; ;</div><div class="line"><a name="l00153"></a><span class="lineno"> 153</span>&#160;</div><div class="line"><a name="l00154"></a><span class="lineno"> 154</span>&#160; enum_&lt;UsbFTInterface::WordSize&gt;(<span class="stringliteral">&quot;WordSize&quot;</span>)</div><div class="line"><a name="l00155"></a><span class="lineno"> 155</span>&#160; .value(<span class="stringliteral">&quot;U8&quot;</span>, <a class="code" href="classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2ea32efe2feb6728578134aa9b85b97d1b9">UsbFTInterface::WS_Byte</a>)</div><div class="line"><a name="l00156"></a><span class="lineno"> 156</span>&#160; .value(<span class="stringliteral">&quot;U16&quot;</span>, <a class="code" href="classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2ea83a39aef091bbcfb420ac32aafe55e0a">UsbFTInterface::WS_Word</a>)</div><div class="line"><a name="l00157"></a><span class="lineno"> 157</span>&#160; .value(<span class="stringliteral">&quot;U32&quot;</span>, <a class="code" href="classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2eae8012559bbaaae91ac6208ed7b3ffe89">UsbFTInterface::WS_DWord</a>)</div><div class="line"><a name="l00158"></a><span class="lineno"> 158</span>&#160; ;</div><div class="line"><a name="l00159"></a><span class="lineno"> 159</span>&#160;</div><div class="line"><a name="l00160"></a><span class="lineno"> 160</span>&#160; <a class="code" href="classStatusCode.html">StatusCode</a> (<a class="code" href="classUsbFTInterface.html">UsbFTInterface</a>::*write_1)(<span class="keywordtype">unsigned</span> <span class="keywordtype">long</span> int, boost::python::list) = (&amp;<a class="code" href="classUsbFTInterface.html#a059296c0d7e5118f975f1dfa2e1f3fbb">UsbFTInterface::write</a>);</div><div class="line"><a name="l00161"></a><span class="lineno"> 161</span>&#160; <a class="code" href="classStatusCode.html">StatusCode</a> (<a class="code" href="classUsbFTInterface.html">UsbFTInterface</a>::*write_2)(<a class="code" href="classIOdata.html">IOdata</a>*) = (&amp;<a class="code" href="classUsbFTInterface.html#a059296c0d7e5118f975f1dfa2e1f3fbb">UsbFTInterface::write</a>);</div><div class="line"><a name="l00162"></a><span class="lineno"> 162</span>&#160; <a class="code" href="classStatusCode.html">StatusCode</a> (<a class="code" href="classUsbFTInterface.html">UsbFTInterface</a>::*read_1)(<span class="keywordtype">unsigned</span> <span class="keywordtype">long</span> int,<span class="keywordtype">unsigned</span> <span class="keywordtype">long</span> int, boost::python::list&amp;) = (&amp;<a class="code" href="classUsbFTInterface.html#ab9daafce1d7878b95ba0655a570922e2">UsbFTInterface::read</a>);</div><div class="line"><a name="l00163"></a><span class="lineno"> 163</span>&#160; <a class="code" href="classStatusCode.html">StatusCode</a> (<a class="code" href="classUsbFTInterface.html">UsbFTInterface</a>::*read_2)(<a class="code" href="classIOdata.html">IOdata</a>*) = (&amp;<a class="code" href="classUsbFTInterface.html#ab9daafce1d7878b95ba0655a570922e2">UsbFTInterface::read</a>);</div><div class="line"><a name="l00164"></a><span class="lineno"> 164</span>&#160;</div><div class="line"><a name="l00165"></a><span class="lineno"> 165</span>&#160; class_&lt;UsbFTInterface, bases &lt;Element&gt; &gt; (<span class="stringliteral">&quot;UsbFTInterface&quot;</span>)</div><div class="line"><a name="l00166"></a><span class="lineno"> 166</span>&#160; .def(<span class="stringliteral">&quot;init&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#a5371fe7b447850599eaec81a0ffa2ba0">UsbFTInterface::init</a>)</div><div class="line"><a name="l00167"></a><span class="lineno"> 167</span>&#160; .def(<span class="stringliteral">&quot;setSerialNum&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#aaabe44c3b717a98e7571de296085c3a4">UsbFTInterface::setSerialNum</a>)</div><div class="line"><a name="l00168"></a><span class="lineno"> 168</span>&#160; .def(<span class="stringliteral">&quot;setDeviceDesc&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#abb106a3d2c48826f96ec2ac10d029132">UsbFTInterface::setDeviceDesc</a>)</div><div class="line"><a name="l00169"></a><span class="lineno"> 169</span>&#160; .def(<span class="stringliteral">&quot;serialNum&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#ab4a2aa9664e903c57ae396faf643e7a3">UsbFTInterface::serialNum</a>)</div><div class="line"><a name="l00170"></a><span class="lineno"> 170</span>&#160; .def(<span class="stringliteral">&quot;deviceDesc&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#af353796fd68a869ea5c8e753aa65dc2c">UsbFTInterface::deviceDesc</a>)</div><div class="line"><a name="l00171"></a><span class="lineno"> 171</span>&#160; .def(<span class="stringliteral">&quot;setWordSize&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#a1666f09d2b8994f8d13d6bc66f43b530">UsbFTInterface::setWordSize</a>)</div><div class="line"><a name="l00172"></a><span class="lineno"> 172</span>&#160; .def(<span class="stringliteral">&quot;wordSize&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#add098ede127a2089e3ac8ea615ed6d46">UsbFTInterface::wordSize</a>)</div><div class="line"><a name="l00173"></a><span class="lineno"> 173</span>&#160; .def(<span class="stringliteral">&quot;close&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#ad555e20eb4b80da1d3cac5a8c6509bb5">UsbFTInterface::close</a>)</div><div class="line"><a name="l00174"></a><span class="lineno"> 174</span>&#160; .def(<span class="stringliteral">&quot;setLatencyTimer&quot;</span>,&amp;<a class="code" href="classUsbFTInterface.html#abe0147f74ac414d0bd2cb4a7a81024b9">UsbFTInterface::setLatencyTimer</a>)</div><div class="line"><a name="l00175"></a><span class="lineno"> 175</span>&#160; .def(<span class="stringliteral">&quot;latencyTimer&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#a4fa70ce4a4cd4f8f01cdeb4835f11276">UsbFTInterface::latencyTimer</a>)</div><div class="line"><a name="l00176"></a><span class="lineno"> 176</span>&#160; .def(<span class="stringliteral">&quot;setTimeOut&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#a62d90f80a81d1decd66f9b9f10cb8dc6">UsbFTInterface::setTimeOut</a>)</div><div class="line"><a name="l00177"></a><span class="lineno"> 177</span>&#160; .def(<span class="stringliteral">&quot;txTimeOut&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#acab2397cb42003a1ed8f69a0c6cae195">UsbFTInterface::txTimeOut</a>)</div><div class="line"><a name="l00178"></a><span class="lineno"> 178</span>&#160; .def(<span class="stringliteral">&quot;rxTimeOut&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#ad95ffb87539ca86882e26fa24b00de97">UsbFTInterface::rxTimeOut</a>)</div><div class="line"><a name="l00179"></a><span class="lineno"> 179</span>&#160; .def(<span class="stringliteral">&quot;setBuffer&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#aaa09fdc28deb45d0a65f5d42c06dd659">UsbFTInterface::setBuffer</a>)</div><div class="line"><a name="l00180"></a><span class="lineno"> 180</span>&#160; .def(<span class="stringliteral">&quot;txBuffer&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#acac73d3fc1587437656bb7fe24e10906">UsbFTInterface::txBuffer</a>)</div><div class="line"><a name="l00181"></a><span class="lineno"> 181</span>&#160; .def(<span class="stringliteral">&quot;rxBuffer&quot;</span> ,&amp;<a class="code" href="classUsbFTInterface.html#a836d1a8d181fd49e11235bb677e3fa7e">UsbFTInterface::rxBuffer</a>)</div><div class="line"><a name="l00182"></a><span class="lineno"> 182</span>&#160; .def(<span class="stringliteral">&quot;write&quot;</span> ,write_1)</div><div class="line"><a name="l00183"></a><span class="lineno"> 183</span>&#160; .def(<span class="stringliteral">&quot;write&quot;</span> ,write_2)</div><div class="line"><a name="l00184"></a><span class="lineno"> 184</span>&#160; .def(<span class="stringliteral">&quot;read&quot;</span> ,read_1)</div><div class="line"><a name="l00185"></a><span class="lineno"> 185</span>&#160; .def(<span class="stringliteral">&quot;read&quot;</span> ,read_2)</div><div class="line"><a name="l00186"></a><span class="lineno"> 186</span>&#160; ;</div><div class="line"><a name="l00187"></a><span class="lineno"> 187</span>&#160;</div><div class="line"><a name="l00188"></a><span class="lineno"> 188</span>&#160; class_&lt;UsbFTInterfaceTest, bases&lt;Processus&gt; &gt; (<span class="stringliteral">&quot;UsbFTInterfaceTest&quot;</span>)</div><div class="line"><a name="l00189"></a><span class="lineno"> 189</span>&#160; .def(<span class="stringliteral">&quot;setAddress&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#ab9c65d9bc48f205d5dc75e7088474529">UsbFTInterfaceTest::setAddress</a>)</div><div class="line"><a name="l00190"></a><span class="lineno"> 190</span>&#160; .def(<span class="stringliteral">&quot;setParam&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#a7aec1fc4c65f7079140b69a627f015a3">UsbFTInterfaceTest::setParam</a>)</div><div class="line"><a name="l00191"></a><span class="lineno"> 191</span>&#160; .def(<span class="stringliteral">&quot;mean&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#a8b88ab4c18cff5e8da014ef6fcf39b90">UsbFTInterfaceTest::mean</a>)</div><div class="line"><a name="l00192"></a><span class="lineno"> 192</span>&#160; .def(<span class="stringliteral">&quot;sigma&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#a582fdf03be84fdd791a50a4129ce8938">UsbFTInterfaceTest::sigma</a>)</div><div class="line"><a name="l00193"></a><span class="lineno"> 193</span>&#160; ;</div><div class="line"><a name="l00194"></a><span class="lineno"> 194</span>&#160;</div><div class="line"><a name="l00195"></a><span class="lineno"> 195</span>&#160; class_&lt;RegisterTest, bases&lt;Processus&gt; &gt; (<span class="stringliteral">&quot;RegisterTest&quot;</span>)</div><div class="line"><a name="l00196"></a><span class="lineno"> 196</span>&#160; .def(<span class="stringliteral">&quot;setAddress&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#ab9c65d9bc48f205d5dc75e7088474529">UsbFTInterfaceTest::setAddress</a>)</div><div class="line"><a name="l00197"></a><span class="lineno"> 197</span>&#160; .def(<span class="stringliteral">&quot;setParam&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#a7aec1fc4c65f7079140b69a627f015a3">UsbFTInterfaceTest::setParam</a>)</div><div class="line"><a name="l00198"></a><span class="lineno"> 198</span>&#160; .def(<span class="stringliteral">&quot;mean&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#a8b88ab4c18cff5e8da014ef6fcf39b90">UsbFTInterfaceTest::mean</a>)</div><div class="line"><a name="l00199"></a><span class="lineno"> 199</span>&#160; .def(<span class="stringliteral">&quot;sigma&quot;</span>, &amp;<a class="code" href="classUsbFTInterfaceTest.html#a582fdf03be84fdd791a50a4129ce8938">UsbFTInterfaceTest::sigma</a>)</div><div class="line"><a name="l00200"></a><span class="lineno"> 200</span>&#160; ;</div><div class="line"><a name="l00201"></a><span class="lineno"> 201</span>&#160;</div><div class="line"><a name="l00202"></a><span class="lineno"> 202</span>&#160;}</div><div class="ttc" id="classA3PE_html_a94d96383e441153ed01e82cc12d2f593"><div class="ttname"><a href="classA3PE.html#a94d96383e441153ed01e82cc12d2f593">A3PE::setupReg</a></div><div class="ttdeci">Register * setupReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00488">A3PE.h:488</a></div></div> <div class="ttc" id="A3PE_8h_html"><div class="ttname"><a href="A3PE_8h.html">A3PE.h</a></div></div> <div class="ttc" id="classUsbFTInterfaceTest_html_a7aec1fc4c65f7079140b69a627f015a3"><div class="ttname"><a href="classUsbFTInterfaceTest.html#a7aec1fc4c65f7079140b69a627f015a3">UsbFTInterfaceTest::setParam</a></div><div class="ttdeci">StatusCode setParam(int size, double mean, double sigma)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterfaceTest_8h_source.html#l00037">UsbFTInterfaceTest.h:37</a></div></div> <div class="ttc" id="classAcquisition_html_a3ee93f665573b4622bd9cba92c0cc04e"><div class="ttname"><a href="classAcquisition.html#a3ee93f665573b4622bd9cba92c0cc04e">Acquisition::setChannels</a></div><div class="ttdeci">StatusCode setChannels(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00214">Acquisition.cpp:214</a></div></div> <div class="ttc" id="classA3PE_html_a60a510251ec2b5fd800af2ba88e9fdac"><div class="ttname"><a href="classA3PE.html#a60a510251ec2b5fd800af2ba88e9fdac">A3PE::dumpFromAX</a></div><div class="ttdeci">void dumpFromAX()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00896">A3PE.cpp:896</a></div></div> <div class="ttc" id="UsbFTInterfaceTest_8h_html"><div class="ttname"><a href="UsbFTInterfaceTest_8h.html">UsbFTInterfaceTest.h</a></div></div> <div class="ttc" id="classA3PE_html_ab5970721a8172ae57b3da68040f58199"><div class="ttname"><a href="classA3PE.html#ab5970721a8172ae57b3da68040f58199">A3PE::latencyAX</a></div><div class="ttdeci">unsigned int latencyAX()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00348">A3PE.cpp:348</a></div></div> <div class="ttc" id="Processus_8h_html"><div class="ttname"><a href="Processus_8h.html">Processus.h</a></div></div> <div class="ttc" id="classAcquisition_html_ab8ffcd86548280f0403b3ae6338f2499"><div class="ttname"><a href="classAcquisition.html#ab8ffcd86548280f0403b3ae6338f2499">Acquisition::finalize</a></div><div class="ttdeci">virtual StatusCode finalize()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00173">Acquisition.cpp:173</a></div></div> <div class="ttc" id="classA3PE_html_aa94c6120a73194d69dc5761cf90a4800"><div class="ttname"><a href="classA3PE.html#aa94c6120a73194d69dc5761cf90a4800">A3PE::ctrlAnaMezzReg</a></div><div class="ttdeci">Register * ctrlAnaMezzReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00512">A3PE.h:512</a></div></div> <div class="ttc" id="classA3PE_html_a81db44ddfc42b67ed08756b113b8e122"><div class="ttname"><a href="classA3PE.html#a81db44ddfc42b67ed08756b113b8e122">A3PE::setNTrigger</a></div><div class="ttdeci">StatusCode setNTrigger(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00549">A3PE.cpp:549</a></div></div> <div class="ttc" id="UsbFTInterface_8h_html"><div class="ttname"><a href="UsbFTInterface_8h.html">UsbFTInterface.h</a></div></div> <div class="ttc" id="classA3PE_html_a083315774486528a8b6c40e240fbf98f"><div class="ttname"><a href="classA3PE.html#a083315774486528a8b6c40e240fbf98f">A3PE::readTriggerFifoUsb</a></div><div class="ttdeci">bool readTriggerFifoUsb()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00258">A3PE.cpp:258</a></div></div> <div class="ttc" id="classA3PE__BitFlip_html_ace874c555080ce6cb68b6bf320977a5a"><div class="ttname"><a href="classA3PE__BitFlip.html#ace874c555080ce6cb68b6bf320977a5a">A3PE_BitFlip::file</a></div><div class="ttdeci">std::string file()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE__BitFlip_8h_source.html#l00035">A3PE_BitFlip.h:35</a></div></div> <div class="ttc" id="classAcquisition_html_a8ab7e58ccb3fee54eb6850e5081fae10"><div class="ttname"><a href="classAcquisition.html#a8ab7e58ccb3fee54eb6850e5081fae10">Acquisition::storeTree</a></div><div class="ttdeci">bool storeTree()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00049">Acquisition.h:49</a></div></div> <div class="ttc" id="classA3PE_html_a1ae8e5a69e17d6b3157779544fa14c75"><div class="ttname"><a href="classA3PE.html#a1ae8e5a69e17d6b3157779544fa14c75">A3PE::setTriggerRate</a></div><div class="ttdeci">StatusCode setTriggerRate(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00520">A3PE.cpp:520</a></div></div> <div class="ttc" id="classAcquisition_html_a8fb2cd60a34993ab0952d719a8517831"><div class="ttname"><a href="classAcquisition.html#a8fb2cd60a34993ab0952d719a8517831">Acquisition::deadTime</a></div><div class="ttdeci">int deadTime()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00067">Acquisition.h:67</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a62d90f80a81d1decd66f9b9f10cb8dc6"><div class="ttname"><a href="classUsbFTInterface.html#a62d90f80a81d1decd66f9b9f10cb8dc6">UsbFTInterface::setTimeOut</a></div><div class="ttdeci">void setTimeOut(int txTimeOut, int rxTimeOut)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00298">UsbFTInterface.h:298</a></div></div> <div class="ttc" id="classA3PE_html_a3bb47f43f9f98d8a0d825aadc04e5ab6"><div class="ttname"><a href="classA3PE.html#a3bb47f43f9f98d8a0d825aadc04e5ab6">A3PE::readPatternFifoUsb</a></div><div class="ttdeci">bool readPatternFifoUsb()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00253">A3PE.cpp:253</a></div></div> <div class="ttc" id="classA3PE_html_a7ad649611d4cc5a7743db54aa3a4f943"><div class="ttname"><a href="classA3PE.html#a7ad649611d4cc5a7743db54aa3a4f943">A3PE::setReadToAXRamUsb</a></div><div class="ttdeci">StatusCode setReadToAXRamUsb(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00201">A3PE.cpp:201</a></div></div> <div class="ttc" id="classA3PE_html_a7c9026a74c1954b2d250be05fbc1c8c5"><div class="ttname"><a href="classA3PE.html#a7c9026a74c1954b2d250be05fbc1c8c5">A3PE::fromAXRam</a></div><div class="ttdeci">RAM * fromAXRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00552">A3PE.h:552</a></div></div> <div class="ttc" id="classA3PE_html_af3152e461d446f442cfa7b69456ac276"><div class="ttname"><a href="classA3PE.html#af3152e461d446f442cfa7b69456ac276">A3PE::readToAXRamUsb</a></div><div class="ttdeci">bool readToAXRamUsb()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00272">A3PE.cpp:272</a></div></div> <div class="ttc" id="classA3PE_html_ada46375753047d6a74acdec442044f39"><div class="ttname"><a href="classA3PE.html#ada46375753047d6a74acdec442044f39">A3PE::triggerRate</a></div><div class="ttdeci">unsigned int triggerRate()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00539">A3PE.cpp:539</a></div></div> <div class="ttc" id="classA3PE_html_aac0ee532f78885a25eebddbad501417f"><div class="ttname"><a href="classA3PE.html#aac0ee532f78885a25eebddbad501417f">A3PE::setSoftwareTrigger</a></div><div class="ttdeci">StatusCode setSoftwareTrigger(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00368">A3PE.cpp:368</a></div></div> <div class="ttc" id="classA3PE_html_a9d3ba9807ea65be0af7f23ffa2372d6b"><div class="ttname"><a href="classA3PE.html#a9d3ba9807ea65be0af7f23ffa2372d6b">A3PE::setReadPatternFifoUsb</a></div><div class="ttdeci">StatusCode setReadPatternFifoUsb(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00124">A3PE.cpp:124</a></div></div> <div class="ttc" id="classA3PE_html_a81e32c82ca14f85fd7f26cd9a54f7a38"><div class="ttname"><a href="classA3PE.html#a81e32c82ca14f85fd7f26cd9a54f7a38">A3PE::clockDivision</a></div><div class="ttdeci">unsigned int clockDivision()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00448">A3PE.cpp:448</a></div></div> <div class="ttc" id="classUsbFTInterfaceTest_html_a8b88ab4c18cff5e8da014ef6fcf39b90"><div class="ttname"><a href="classUsbFTInterfaceTest.html#a8b88ab4c18cff5e8da014ef6fcf39b90">UsbFTInterfaceTest::mean</a></div><div class="ttdeci">double mean()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterfaceTest_8h_source.html#l00044">UsbFTInterfaceTest.h:44</a></div></div> <div class="ttc" id="classA3PE_html_a43b0006fafa3aeae353abb2ac30e872c"><div class="ttname"><a href="classA3PE.html#a43b0006fafa3aeae353abb2ac30e872c">A3PE::toAXReg</a></div><div class="ttdeci">Register * toAXReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00524">A3PE.h:524</a></div></div> <div class="ttc" id="Proto40MHz__v1_8h_html"><div class="ttname"><a href="Proto40MHz__v1_8h.html">Proto40MHz_v1.h</a></div></div> <div class="ttc" id="classA3PE_html_a54fe4da570ea8833fe2c981de1085387"><div class="ttname"><a href="classA3PE.html#a54fe4da570ea8833fe2c981de1085387">A3PE::setAddToAXRam</a></div><div class="ttdeci">StatusCode setAddToAXRam(int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00179">A3PE.cpp:179</a></div></div> <div class="ttc" id="classUsbFTInterface_html_acac73d3fc1587437656bb7fe24e10906"><div class="ttname"><a href="classUsbFTInterface.html#acac73d3fc1587437656bb7fe24e10906">UsbFTInterface::txBuffer</a></div><div class="ttdeci">int txBuffer()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00336">UsbFTInterface.h:336</a></div></div> <div class="ttc" id="classUsbFTInterface_html_aaa09fdc28deb45d0a65f5d42c06dd659"><div class="ttname"><a href="classUsbFTInterface.html#aaa09fdc28deb45d0a65f5d42c06dd659">UsbFTInterface::setBuffer</a></div><div class="ttdeci">void setBuffer(int txBuffer, int rxBuffer)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00326">UsbFTInterface.h:326</a></div></div> <div class="ttc" id="classA3PE_html_a44c50d822ac4f5d8f2b8ed75c5b90580"><div class="ttname"><a href="classA3PE.html#a44c50d822ac4f5d8f2b8ed75c5b90580">A3PE::resetLatencyCounter</a></div><div class="ttdeci">StatusCode resetLatencyCounter()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00037">A3PE.cpp:37</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a057387f452eaac094fb77ba09cf1cf2ea83a39aef091bbcfb420ac32aafe55e0a"><div class="ttname"><a href="classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2ea83a39aef091bbcfb420ac32aafe55e0a">UsbFTInterface::WS_Word</a></div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00049">UsbFTInterface.h:49</a></div></div> <div class="ttc" id="classUsbFTInterfaceTest_html_a582fdf03be84fdd791a50a4129ce8938"><div class="ttname"><a href="classUsbFTInterfaceTest.html#a582fdf03be84fdd791a50a4129ce8938">UsbFTInterfaceTest::sigma</a></div><div class="ttdeci">double sigma()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterfaceTest_8h_source.html#l00048">UsbFTInterfaceTest.h:48</a></div></div> <div class="ttc" id="classAcquisition_html_a3a3dad0de9535d5a29c0810a5bdc3ae3"><div class="ttname"><a href="classAcquisition.html#a3a3dad0de9535d5a29c0810a5bdc3ae3">Acquisition::nBins</a></div><div class="ttdeci">int nBins()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00079">Acquisition.h:79</a></div></div> <div class="ttc" id="classProto40MHz__v1_html_a545f205296c492530a50febd54584f73"><div class="ttname"><a href="classProto40MHz__v1.html#a545f205296c492530a50febd54584f73">Proto40MHz_v1::phaser0</a></div><div class="ttdeci">Phaser * phaser0()</div><div class="ttdef"><b>Definition:</b> <a href="Proto40MHz__v1_8h_source.html#l00062">Proto40MHz_v1.h:62</a></div></div> <div class="ttc" id="classUsbFTInterface_html_ad95ffb87539ca86882e26fa24b00de97"><div class="ttname"><a href="classUsbFTInterface.html#ad95ffb87539ca86882e26fa24b00de97">UsbFTInterface::rxTimeOut</a></div><div class="ttdeci">int rxTimeOut()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00317">UsbFTInterface.h:317</a></div></div> <div class="ttc" id="classA3PE_html_a0ad1110ea755ffd0b277284d807a8794"><div class="ttname"><a href="classA3PE.html#a0ad1110ea755ffd0b277284d807a8794">A3PE::resetUsbPhasers</a></div><div class="ttdeci">StatusCode resetUsbPhasers()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00032">A3PE.cpp:32</a></div></div> <div class="ttc" id="classA3PE_html_a4d8f78a1b09b409f288b34d503c71146"><div class="ttname"><a href="classA3PE.html#a4d8f78a1b09b409f288b34d503c71146">A3PE::setFifoDepth</a></div><div class="ttdeci">StatusCode setFifoDepth(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00612">A3PE.cpp:612</a></div></div> <div class="ttc" id="classA3PE_html_a6015ba83a7b828efb1969291ab740eee"><div class="ttname"><a href="classA3PE.html#a6015ba83a7b828efb1969291ab740eee">A3PE::resetSequenceFromToAX</a></div><div class="ttdeci">StatusCode resetSequenceFromToAX()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00067">A3PE.cpp:67</a></div></div> <div class="ttc" id="classA3PE_html_a40017b4138705690f8b04e336a7ffcdf"><div class="ttname"><a href="classA3PE.html#a40017b4138705690f8b04e336a7ffcdf">A3PE::loadToAX</a></div><div class="ttdeci">void loadToAX(std::string)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00858">A3PE.cpp:858</a></div></div> <div class="ttc" id="classA3PE_html_a94ef54086baa29f7f6638c13d8906e56"><div class="ttname"><a href="classA3PE.html#a94ef54086baa29f7f6638c13d8906e56">A3PE::patternRam</a></div><div class="ttdeci">RAM * patternRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00540">A3PE.h:540</a></div></div> <div class="ttc" id="classAcquisition_html_a786da6cff5428020034be23e554e0e1b"><div class="ttname"><a href="classAcquisition.html#a786da6cff5428020034be23e554e0e1b">Acquisition::setMaxRange</a></div><div class="ttdeci">void setMaxRange(float maxrange)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00087">Acquisition.h:87</a></div></div> <div class="ttc" id="classA3PE_html_a34a9499a0d9065a1b5772880d7e8d5c4"><div class="ttname"><a href="classA3PE.html#a34a9499a0d9065a1b5772880d7e8d5c4">A3PE::loadTrigger</a></div><div class="ttdeci">void loadTrigger(std::string)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00809">A3PE.cpp:809</a></div></div> <div class="ttc" id="classUsbFTInterface_html_ab4a2aa9664e903c57ae396faf643e7a3"><div class="ttname"><a href="classUsbFTInterface.html#ab4a2aa9664e903c57ae396faf643e7a3">UsbFTInterface::serialNum</a></div><div class="ttdeci">std::string serialNum()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00256">UsbFTInterface.h:256</a></div></div> <div class="ttc" id="classUsbFTInterface_html_add098ede127a2089e3ac8ea615ed6d46"><div class="ttname"><a href="classUsbFTInterface.html#add098ede127a2089e3ac8ea615ed6d46">UsbFTInterface::wordSize</a></div><div class="ttdeci">unsigned long wordSize()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00393">UsbFTInterface.h:393</a></div></div> <div class="ttc" id="classAcquisition_html_acdb167b43f3babb59a98698aa5c5066f"><div class="ttname"><a href="classAcquisition.html#acdb167b43f3babb59a98698aa5c5066f">Acquisition::setTrigger</a></div><div class="ttdeci">StatusCode setTrigger(bool trig)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00036">Acquisition.h:36</a></div></div> <div class="ttc" id="classProto40MHz__v1_html_a263cfc900aafa3ceee1af4b596a824de"><div class="ttname"><a href="classProto40MHz__v1.html#a263cfc900aafa3ceee1af4b596a824de">Proto40MHz_v1::a3pe</a></div><div class="ttdeci">A3PE * a3pe()</div><div class="ttdef"><b>Definition:</b> <a href="Proto40MHz__v1_8h_source.html#l00074">Proto40MHz_v1.h:74</a></div></div> <div class="ttc" id="classA3PE_html_af241373059bad4a3c376ab2ac98a7b29"><div class="ttname"><a href="classA3PE.html#af241373059bad4a3c376ab2ac98a7b29">A3PE::storageRam</a></div><div class="ttdeci">RAM * storageRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00536">A3PE.h:536</a></div></div> <div class="ttc" id="classA3PE_html_af15048318a126074e28df1c6120d5e0d"><div class="ttname"><a href="classA3PE.html#af15048318a126074e28df1c6120d5e0d">A3PE::writeStorageFifoUsb</a></div><div class="ttdeci">bool writeStorageFifoUsb()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00248">A3PE.cpp:248</a></div></div> <div class="ttc" id="A3PE__BitFlip_8h_html"><div class="ttname"><a href="A3PE__BitFlip_8h.html">A3PE_BitFlip.h</a></div></div> <div class="ttc" id="classA3PE_html_acb2ccd6b78b39a0a9e360439b3b6f4c7"><div class="ttname"><a href="classA3PE.html#acb2ccd6b78b39a0a9e360439b3b6f4c7">A3PE::softwareTrigger</a></div><div class="ttdeci">bool softwareTrigger()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00379">A3PE.cpp:379</a></div></div> <div class="ttc" id="classA3PE__BitFlip_html_affa7320fb39001a6e9b5696542fe4584"><div class="ttname"><a href="classA3PE__BitFlip.html#affa7320fb39001a6e9b5696542fe4584">A3PE_BitFlip::execute</a></div><div class="ttdeci">virtual StatusCode execute()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE__BitFlip_8cpp_source.html#l00109">A3PE_BitFlip.cpp:109</a></div></div> <div class="ttc" id="classUsbFTInterface_html"><div class="ttname"><a href="classUsbFTInterface.html">UsbFTInterface</a></div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00040">UsbFTInterface.h:40</a></div></div> <div class="ttc" id="classA3PE_html_ad7999557f9d561dec67526730a3c97ef"><div class="ttname"><a href="classA3PE.html#ad7999557f9d561dec67526730a3c97ef">A3PE::dumpStorage</a></div><div class="ttdeci">void dumpStorage()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00641">A3PE.cpp:641</a></div></div> <div class="ttc" id="classA3PE_html_ae164123b49f8c4d1d119dbf201f0a839"><div class="ttname"><a href="classA3PE.html#ae164123b49f8c4d1d119dbf201f0a839">A3PE::resetSPI</a></div><div class="ttdeci">StatusCode resetSPI()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00077">A3PE.cpp:77</a></div></div> <div class="ttc" id="classA3PE_html_a23da04d3c7e632dfb64e5ed4e21a21f3"><div class="ttname"><a href="classA3PE.html#a23da04d3c7e632dfb64e5ed4e21a21f3">A3PE::dumpPattern</a></div><div class="ttdeci">void dumpPattern()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00716">A3PE.cpp:716</a></div></div> <div class="ttc" id="classA3PE_html_a91ae249ca14676f8b0832487955fcf8c"><div class="ttname"><a href="classA3PE.html#a91ae249ca14676f8b0832487955fcf8c">A3PE::startSequenceAX</a></div><div class="ttdeci">StatusCode startSequenceAX()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00949">A3PE.cpp:949</a></div></div> <div class="ttc" id="classA3PE_html_a449775588222d544aeeaab190d553652"><div class="ttname"><a href="classA3PE.html#a449775588222d544aeeaab190d553652">A3PE::reset</a></div><div class="ttdeci">void reset()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00225">A3PE.h:225</a></div></div> <div class="ttc" id="classAcquisition_html_a6f680938eb6a42d57dfa7466e8852af9"><div class="ttname"><a href="classAcquisition.html#a6f680938eb6a42d57dfa7466e8852af9">Acquisition::trigger</a></div><div class="ttdeci">bool trigger()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00041">Acquisition.h:41</a></div></div> <div class="ttc" id="classAcquisition_html_a8a15ffc6e539a3ae12efe4bea1ca7587"><div class="ttname"><a href="classAcquisition.html#a8a15ffc6e539a3ae12efe4bea1ca7587">Acquisition::setMinRange</a></div><div class="ttdeci">void setMinRange(float minrange)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00081">Acquisition.h:81</a></div></div> <div class="ttc" id="classProto40MHz__v1_html_a9c4ef3187b86b74b05bdec3c167a405e"><div class="ttname"><a href="classProto40MHz__v1.html#a9c4ef3187b86b74b05bdec3c167a405e">Proto40MHz_v1::phaser1</a></div><div class="ttdeci">Phaser * phaser1()</div><div class="ttdef"><b>Definition:</b> <a href="Proto40MHz__v1_8h_source.html#l00066">Proto40MHz_v1.h:66</a></div></div> <div class="ttc" id="RegisterTest_8h_html"><div class="ttname"><a href="RegisterTest_8h.html">RegisterTest.h</a></div></div> <div class="ttc" id="classA3PE_html_aad0f7ac467db22e5608ae6b0957665a1"><div class="ttname"><a href="classA3PE.html#aad0f7ac467db22e5608ae6b0957665a1">A3PE::triggerRam</a></div><div class="ttdeci">RAM * triggerRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00544">A3PE.h:544</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a057387f452eaac094fb77ba09cf1cf2ea32efe2feb6728578134aa9b85b97d1b9"><div class="ttname"><a href="classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2ea32efe2feb6728578134aa9b85b97d1b9">UsbFTInterface::WS_Byte</a></div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00048">UsbFTInterface.h:48</a></div></div> <div class="ttc" id="classAcquisition_html_a9af304e0fb2076cd4f92703708efe83e"><div class="ttname"><a href="classAcquisition.html#a9af304e0fb2076cd4f92703708efe83e">Acquisition::storeSample</a></div><div class="ttdeci">bool storeSample()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00061">Acquisition.h:61</a></div></div> <div class="ttc" id="classA3PE_html_aca56dadafd70e670e75569ee03d91651"><div class="ttname"><a href="classA3PE.html#aca56dadafd70e670e75569ee03d91651">A3PE::acqReg</a></div><div class="ttdeci">Register * acqReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00500">A3PE.h:500</a></div></div> <div class="ttc" id="classUsbFTInterface_html_ab9daafce1d7878b95ba0655a570922e2"><div class="ttname"><a href="classUsbFTInterface.html#ab9daafce1d7878b95ba0655a570922e2">UsbFTInterface::read</a></div><div class="ttdeci">StatusCode read(IOdata *)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8cpp_source.html#l00817">UsbFTInterface.cpp:817</a></div></div> <div class="ttc" id="classA3PE_html_a55df064c578bbc1e80a3b5fc05933f27"><div class="ttname"><a href="classA3PE.html#a55df064c578bbc1e80a3b5fc05933f27">A3PE::dataReady</a></div><div class="ttdeci">bool dataReady()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00406">A3PE.cpp:406</a></div></div> <div class="ttc" id="classAcquisition_html_ae3b63064bee1b042914b63ae4135cbd8"><div class="ttname"><a href="classAcquisition.html#ae3b63064bee1b042914b63ae4135cbd8">Acquisition::execute</a></div><div class="ttdeci">virtual StatusCode execute()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00118">Acquisition.cpp:118</a></div></div> <div class="ttc" id="classUsbFTInterface_html_aaabe44c3b717a98e7571de296085c3a4"><div class="ttname"><a href="classUsbFTInterface.html#aaabe44c3b717a98e7571de296085c3a4">UsbFTInterface::setSerialNum</a></div><div class="ttdeci">void setSerialNum(std::string serialNum)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00248">UsbFTInterface.h:248</a></div></div> <div class="ttc" id="CatBcn_2src_2Python_8cpp_html_a527b17e3e2c7c505c5d99fcbaa744eab"><div class="ttname"><a href="CatBcn_2src_2Python_8cpp.html#a527b17e3e2c7c505c5d99fcbaa744eab">BOOST_PYTHON_MODULE</a></div><div class="ttdeci">BOOST_PYTHON_MODULE(libCatBcn)</div><div class="ttdef"><b>Definition:</b> <a href="CatBcn_2src_2Python_8cpp_source.html#l00024">Python.cpp:24</a></div></div> <div class="ttc" id="classProto40MHz__v1_html_aee48500fba238c4caf8502db32ebb991"><div class="ttname"><a href="classProto40MHz__v1.html#aee48500fba238c4caf8502db32ebb991">Proto40MHz_v1::usb</a></div><div class="ttdeci">UsbFTInterface * usb()</div><div class="ttdef"><b>Definition:</b> <a href="Proto40MHz__v1_8h_source.html#l00058">Proto40MHz_v1.h:58</a></div></div> <div class="ttc" id="classAcquisition_html_a5af693448daef6e9e054ab7f1aa50784"><div class="ttname"><a href="classAcquisition.html#a5af693448daef6e9e054ab7f1aa50784">Acquisition::storeTrend</a></div><div class="ttdeci">bool storeTrend()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00055">Acquisition.h:55</a></div></div> <div class="ttc" id="classAcquisition_html_a6ee040a009aa48f848b1e12434135db9"><div class="ttname"><a href="classAcquisition.html#a6ee040a009aa48f848b1e12434135db9">Acquisition::setNBins</a></div><div class="ttdeci">void setNBins(int nbins)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00075">Acquisition.h:75</a></div></div> <div class="ttc" id="classUsbFTInterface_html_af353796fd68a869ea5c8e753aa65dc2c"><div class="ttname"><a href="classUsbFTInterface.html#af353796fd68a869ea5c8e753aa65dc2c">UsbFTInterface::deviceDesc</a></div><div class="ttdeci">std::string deviceDesc()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00272">UsbFTInterface.h:272</a></div></div> <div class="ttc" id="classA3PE_html_ac0aabc1457923b7ee7da0a2c91c46451"><div class="ttname"><a href="classA3PE.html#ac0aabc1457923b7ee7da0a2c91c46451">A3PE::triggerDelay</a></div><div class="ttdeci">unsigned int triggerDelay()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00480">A3PE.cpp:480</a></div></div> <div class="ttc" id="classAcquisition_html_a44f441710231748d2ca8f691647b2bcd"><div class="ttname"><a href="classAcquisition.html#a44f441710231748d2ca8f691647b2bcd">Acquisition::minRange</a></div><div class="ttdeci">float minRange()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00085">Acquisition.h:85</a></div></div> <div class="ttc" id="classA3PE_html_a53882e1272e8146e51837904ea00f33c"><div class="ttname"><a href="classA3PE.html#a53882e1272e8146e51837904ea00f33c">A3PE::setLatencyAX</a></div><div class="ttdeci">StatusCode setLatencyAX(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00327">A3PE.cpp:327</a></div></div> <div class="ttc" id="classUsbFTInterface_html_ad555e20eb4b80da1d3cac5a8c6509bb5"><div class="ttname"><a href="classUsbFTInterface.html#ad555e20eb4b80da1d3cac5a8c6509bb5">UsbFTInterface::close</a></div><div class="ttdeci">void close()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8cpp_source.html#l00802">UsbFTInterface.cpp:802</a></div></div> <div class="ttc" id="classAcquisition_html_a83181975c0746e5837d53933031e7b62"><div class="ttname"><a href="classAcquisition.html#a83181975c0746e5837d53933031e7b62">Acquisition::sample</a></div><div class="ttdeci">int sample()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00073">Acquisition.h:73</a></div></div> <div class="ttc" id="classA3PE_html_a0b2fabe7e7941f33de210d9385b7afce"><div class="ttname"><a href="classA3PE.html#a0b2fabe7e7941f33de210d9385b7afce">A3PE::fromAXReg</a></div><div class="ttdeci">Register * fromAXReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00528">A3PE.h:528</a></div></div> <div class="ttc" id="classA3PE_html_a75cd0377eb653ed22c4d258ab359f3d6"><div class="ttname"><a href="classA3PE.html#a75cd0377eb653ed22c4d258ab359f3d6">A3PE::trigger</a></div><div class="ttdeci">StatusCode trigger()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00363">A3PE.cpp:363</a></div></div> <div class="ttc" id="classA3PE_html_a6a63fc9503e0aa89ee9928fc7222ce0f"><div class="ttname"><a href="classA3PE.html#a6a63fc9503e0aa89ee9928fc7222ce0f">A3PE::setTriggerDelay</a></div><div class="ttdeci">StatusCode setTriggerDelay(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00461">A3PE.cpp:461</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a057387f452eaac094fb77ba09cf1cf2eae8012559bbaaae91ac6208ed7b3ffe89"><div class="ttname"><a href="classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2eae8012559bbaaae91ac6208ed7b3ffe89">UsbFTInterface::WS_DWord</a></div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00050">UsbFTInterface.h:50</a></div></div> <div class="ttc" id="classAcquisition_html_a386f3ebc6b1d4956aa7e40b314ddb4eb"><div class="ttname"><a href="classAcquisition.html#a386f3ebc6b1d4956aa7e40b314ddb4eb">Acquisition::maxRange</a></div><div class="ttdeci">float maxRange()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00091">Acquisition.h:91</a></div></div> <div class="ttc" id="classA3PE_html_a5b3840fc8edd14427ac9fb4def3171d3"><div class="ttname"><a href="classA3PE.html#a5b3840fc8edd14427ac9fb4def3171d3">A3PE::setPipeline</a></div><div class="ttdeci">StatusCode setPipeline(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00290">A3PE.cpp:290</a></div></div> <div class="ttc" id="classA3PE_html_a979a9ac462eb55e611f6de4e94bad18e"><div class="ttname"><a href="classA3PE.html#a979a9ac462eb55e611f6de4e94bad18e">A3PE::spare3Reg</a></div><div class="ttdeci">Register * spare3Reg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00532">A3PE.h:532</a></div></div> <div class="ttc" id="classA3PE_html_a8e7074703227b118aa9230258f22b44c"><div class="ttname"><a href="classA3PE.html#a8e7074703227b118aa9230258f22b44c">A3PE::resetStorageFifo</a></div><div class="ttdeci">StatusCode resetStorageFifo()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00027">A3PE.cpp:27</a></div></div> <div class="ttc" id="classProto40MHz__v1_html_a59defd14376765f7df8f87d594170527"><div class="ttname"><a href="classProto40MHz__v1.html#a59defd14376765f7df8f87d594170527">Proto40MHz_v1::phaser2</a></div><div class="ttdeci">Phaser * phaser2()</div><div class="ttdef"><b>Definition:</b> <a href="Proto40MHz__v1_8h_source.html#l00070">Proto40MHz_v1.h:70</a></div></div> <div class="ttc" id="classIOdata_html"><div class="ttname"><a href="classIOdata.html">IOdata</a></div><div class="ttdef"><b>Definition:</b> <a href="IOdata_8h_source.html#l00017">IOdata.h:17</a></div></div> <div class="ttc" id="classA3PE_html_af260fc8bce78935b7bad57c987574683"><div class="ttname"><a href="classA3PE.html#af260fc8bce78935b7bad57c987574683">A3PE::statusReg</a></div><div class="ttdeci">Register * statusReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00496">A3PE.h:496</a></div></div> <div class="ttc" id="classA3PE_html_a4e5b677dd2872428abf3d64ef7a769c1"><div class="ttname"><a href="classA3PE.html#a4e5b677dd2872428abf3d64ef7a769c1">A3PE::resetPatternFifo</a></div><div class="ttdeci">StatusCode resetPatternFifo()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00047">A3PE.cpp:47</a></div></div> <div class="ttc" id="classA3PE_html_a969469569005dfb130aca674de5dacff"><div class="ttname"><a href="classA3PE.html#a969469569005dfb130aca674de5dacff">A3PE::setFifoLatency</a></div><div class="ttdeci">StatusCode setFifoLatency(unsigned short)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00581">A3PE.cpp:581</a></div></div> <div class="ttc" id="classA3PE_html_a3398fa3ce59a4b1b946e7b4ab4912580"><div class="ttname"><a href="classA3PE.html#a3398fa3ce59a4b1b946e7b4ab4912580">A3PE::nTrigger</a></div><div class="ttdeci">unsigned int nTrigger()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00568">A3PE.cpp:568</a></div></div> <div class="ttc" id="classA3PE_html_a4bf922f391fee6753fb0d53e133603b7"><div class="ttname"><a href="classA3PE.html#a4bf922f391fee6753fb0d53e133603b7">A3PE::triggerReg</a></div><div class="ttdeci">Register * triggerReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00520">A3PE.h:520</a></div></div> <div class="ttc" id="classA3PE_html_a8bd4a7a5dd8219f93386756c24a0f0b5"><div class="ttname"><a href="classA3PE.html#a8bd4a7a5dd8219f93386756c24a0f0b5">A3PE::loadStorage</a></div><div class="ttdeci">void loadStorage(std::string)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00670">A3PE.cpp:670</a></div></div> <div class="ttc" id="classA3PE__BitFlip_html_a88dc6cfe690a518e38ff6d89026e6e0c"><div class="ttname"><a href="classA3PE__BitFlip.html#a88dc6cfe690a518e38ff6d89026e6e0c">A3PE_BitFlip::initialize</a></div><div class="ttdeci">virtual StatusCode initialize()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE__BitFlip_8cpp_source.html#l00049">A3PE_BitFlip.cpp:49</a></div></div> <div class="ttc" id="classAcquisition_html_a3041537afcb4dfe5c6940f0ef6829265"><div class="ttname"><a href="classAcquisition.html#a3041537afcb4dfe5c6940f0ef6829265">Acquisition::channels</a></div><div class="ttdeci">unsigned int channels()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00034">Acquisition.h:34</a></div></div> <div class="ttc" id="classA3PE_html_a834fde5951d2c1bf6b41842520360fce"><div class="ttname"><a href="classA3PE.html#a834fde5951d2c1bf6b41842520360fce">A3PE::setAddFromAXRam</a></div><div class="ttdeci">StatusCode setAddFromAXRam(int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00190">A3PE.cpp:190</a></div></div> <div class="ttc" id="classA3PE_html_a1d0dd1db3c493bc31aa56b55e7439e0e"><div class="ttname"><a href="classA3PE.html#a1d0dd1db3c493bc31aa56b55e7439e0e">A3PE::setReadTriggerFifoUsb</a></div><div class="ttdeci">StatusCode setReadTriggerFifoUsb(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00152">A3PE.cpp:152</a></div></div> <div class="ttc" id="classA3PE_html_a65235f7d42e8f7fb6056f5629545d2aa"><div class="ttname"><a href="classA3PE.html#a65235f7d42e8f7fb6056f5629545d2aa">A3PE::loadFromAX</a></div><div class="ttdeci">void loadFromAX(std::string)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00911">A3PE.cpp:911</a></div></div> <div class="ttc" id="classA3PE_html_acb95104d817db2e4f97e250f7e45b43d"><div class="ttname"><a href="classA3PE.html#acb95104d817db2e4f97e250f7e45b43d">A3PE::lengthAX</a></div><div class="ttdeci">unsigned int lengthAX()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00338">A3PE.cpp:338</a></div></div> <div class="ttc" id="classA3PE_html_a2071d7922f140ee6705da954efb685f7"><div class="ttname"><a href="classA3PE.html#a2071d7922f140ee6705da954efb685f7">A3PE::enableStorage</a></div><div class="ttdeci">StatusCode enableStorage()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00383">A3PE.cpp:383</a></div></div> <div class="ttc" id="classUsbFTInterface_html_abe0147f74ac414d0bd2cb4a7a81024b9"><div class="ttname"><a href="classUsbFTInterface.html#abe0147f74ac414d0bd2cb4a7a81024b9">UsbFTInterface::setLatencyTimer</a></div><div class="ttdeci">void setLatencyTimer(unsigned char latencyTimer)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00280">UsbFTInterface.h:280</a></div></div> <div class="ttc" id="classAcquisition_html_ade6fd6483b3e3737fe7dcdffb5065954"><div class="ttname"><a href="classAcquisition.html#ade6fd6483b3e3737fe7dcdffb5065954">Acquisition::setSample</a></div><div class="ttdeci">void setSample(int nsample)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00069">Acquisition.h:69</a></div></div> <div class="ttc" id="classUsbFTInterface_html_acab2397cb42003a1ed8f69a0c6cae195"><div class="ttname"><a href="classUsbFTInterface.html#acab2397cb42003a1ed8f69a0c6cae195">UsbFTInterface::txTimeOut</a></div><div class="ttdeci">int txTimeOut()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00308">UsbFTInterface.h:308</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a836d1a8d181fd49e11235bb677e3fa7e"><div class="ttname"><a href="classUsbFTInterface.html#a836d1a8d181fd49e11235bb677e3fa7e">UsbFTInterface::rxBuffer</a></div><div class="ttdeci">int rxBuffer()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00344">UsbFTInterface.h:344</a></div></div> <div class="ttc" id="classA3PE_html_a16b16ac12705b9dd93d70fa172deb584"><div class="ttname"><a href="classA3PE.html#a16b16ac12705b9dd93d70fa172deb584">A3PE::toAXRam</a></div><div class="ttdeci">RAM * toAXRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00548">A3PE.h:548</a></div></div> <div class="ttc" id="classA3PE_html_a3b4333f547a2a36fc1f38bf4ca9afa89"><div class="ttname"><a href="classA3PE.html#a3b4333f547a2a36fc1f38bf4ca9afa89">A3PE::writeFromAXRamUsb</a></div><div class="ttdeci">bool writeFromAXRamUsb()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00276">A3PE.cpp:276</a></div></div> <div class="ttc" id="classA3PE_html_ae5fc5dac92af2b34a41be388586647be"><div class="ttname"><a href="classA3PE.html#ae5fc5dac92af2b34a41be388586647be">A3PE::ctrlReg</a></div><div class="ttdeci">Register * ctrlReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00484">A3PE.h:484</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a059296c0d7e5118f975f1dfa2e1f3fbb"><div class="ttname"><a href="classUsbFTInterface.html#a059296c0d7e5118f975f1dfa2e1f3fbb">UsbFTInterface::write</a></div><div class="ttdeci">StatusCode write(IOdata *)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8cpp_source.html#l00871">UsbFTInterface.cpp:871</a></div></div> <div class="ttc" id="classAcquisition_html_a1ad973e21a067c0de0b6264d0eb5182b"><div class="ttname"><a href="classAcquisition.html#a1ad973e21a067c0de0b6264d0eb5182b">Acquisition::depth</a></div><div class="ttdeci">unsigned int depth()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00031">Acquisition.h:31</a></div></div> <div class="ttc" id="classUsbFTInterface_html_abb106a3d2c48826f96ec2ac10d029132"><div class="ttname"><a href="classUsbFTInterface.html#abb106a3d2c48826f96ec2ac10d029132">UsbFTInterface::setDeviceDesc</a></div><div class="ttdeci">void setDeviceDesc(std::string deviceDesc)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00264">UsbFTInterface.h:264</a></div></div> <div class="ttc" id="classAcquisition_html_a759193856d26354722e5f647e60e16de"><div class="ttname"><a href="classAcquisition.html#a759193856d26354722e5f647e60e16de">Acquisition::setStoreTree</a></div><div class="ttdeci">void setStoreTree(bool store_tree)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00045">Acquisition.h:45</a></div></div> <div class="ttc" id="classA3PE_html_aa688f9dff8d2892464fcd13fdf3600ad"><div class="ttname"><a href="classA3PE.html#aa688f9dff8d2892464fcd13fdf3600ad">A3PE::setWriteStorageFifoUsb</a></div><div class="ttdeci">StatusCode setWriteStorageFifoUsb(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00099">A3PE.cpp:99</a></div></div> <div class="ttc" id="classA3PE_html_a9327d0bd2efb5baa7c6b7de27bbc5997"><div class="ttname"><a href="classA3PE.html#a9327d0bd2efb5baa7c6b7de27bbc5997">A3PE::testRam</a></div><div class="ttdeci">RAM * testRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00556">A3PE.h:556</a></div></div> <div class="ttc" id="classA3PE_html_a035886b99761cc4f3c342ff0b4e44f59"><div class="ttname"><a href="classA3PE.html#a035886b99761cc4f3c342ff0b4e44f59">A3PE::acquisition</a></div><div class="ttdeci">StatusCode acquisition()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00417">A3PE.cpp:417</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a1666f09d2b8994f8d13d6bc66f43b530"><div class="ttname"><a href="classUsbFTInterface.html#a1666f09d2b8994f8d13d6bc66f43b530">UsbFTInterface::setWordSize</a></div><div class="ttdeci">void setWordSize(unsigned long wordSize)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00385">UsbFTInterface.h:385</a></div></div> <div class="ttc" id="classStatusCode_html"><div class="ttname"><a href="classStatusCode.html">StatusCode</a></div><div class="ttdef"><b>Definition:</b> <a href="StatusCode_8h_source.html#l00016">StatusCode.h:16</a></div></div> <div class="ttc" id="classA3PE__BitFlip_html_ab40772a001613a0e1932d1e356ccf717"><div class="ttname"><a href="classA3PE__BitFlip.html#ab40772a001613a0e1932d1e356ccf717">A3PE_BitFlip::finalize</a></div><div class="ttdeci">virtual StatusCode finalize()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE__BitFlip_8cpp_source.html#l00161">A3PE_BitFlip.cpp:161</a></div></div> <div class="ttc" id="classA3PE_html_ac81388bd2988192cf54034b245f69891"><div class="ttname"><a href="classA3PE.html#ac81388bd2988192cf54034b245f69891">A3PE::resetTriggerFifo</a></div><div class="ttdeci">StatusCode resetTriggerFifo()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00052">A3PE.cpp:52</a></div></div> <div class="ttc" id="namespaceboost_1_1python_html"><div class="ttname"><a href="namespaceboost_1_1python.html">python</a></div></div> <div class="ttc" id="classA3PE_html_a8bb523e4a7a5dbb6ab3c5549ebf6db86"><div class="ttname"><a href="classA3PE.html#a8bb523e4a7a5dbb6ab3c5549ebf6db86">A3PE::fifoDepth</a></div><div class="ttdeci">unsigned int fifoDepth()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00631">A3PE.cpp:631</a></div></div> <div class="ttc" id="classA3PE_html_a31f72fac5a0f00bcf3a0db99bd5704ee"><div class="ttname"><a href="classA3PE.html#a31f72fac5a0f00bcf3a0db99bd5704ee">A3PE::resetToAXRam</a></div><div class="ttdeci">StatusCode resetToAXRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00057">A3PE.cpp:57</a></div></div> <div class="ttc" id="Element_8h_html"><div class="ttname"><a href="Element_8h.html">Element.h</a></div></div> <div class="ttc" id="classA3PE_html_aeb22b2fcba4d14f234ad2d6dcef7948c"><div class="ttname"><a href="classA3PE.html#aeb22b2fcba4d14f234ad2d6dcef7948c">A3PE::pipeline</a></div><div class="ttdeci">unsigned int pipeline()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00307">A3PE.cpp:307</a></div></div> <div class="ttc" id="classA3PE_html_aa10639563d06c0d09f3c0725710ff35d"><div class="ttname"><a href="classA3PE.html#aa10639563d06c0d09f3c0725710ff35d">A3PE::resetFromAXRam</a></div><div class="ttdeci">StatusCode resetFromAXRam()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00062">A3PE.cpp:62</a></div></div> <div class="ttc" id="classA3PE_html_ad5f953a38661104a87834cc8a63252fa"><div class="ttname"><a href="classA3PE.html#ad5f953a38661104a87834cc8a63252fa">A3PE::setInternalAXSequence</a></div><div class="ttdeci">StatusCode setInternalAXSequence(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00280">A3PE.cpp:280</a></div></div> <div class="ttc" id="classA3PE_html_acf354b2c85a7e20f7f037beb278dd79d"><div class="ttname"><a href="classA3PE.html#acf354b2c85a7e20f7f037beb278dd79d">A3PE::setClockDivision</a></div><div class="ttdeci">StatusCode setClockDivision(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00429">A3PE.cpp:429</a></div></div> <div class="ttc" id="classA3PE_html_a0c90134c3440c8b8c8dc796c43893d64"><div class="ttname"><a href="classA3PE.html#a0c90134c3440c8b8c8dc796c43893d64">A3PE::setEnableADC</a></div><div class="ttdeci">StatusCode setEnableADC(unsigned int, bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00087">A3PE.cpp:87</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a4fa70ce4a4cd4f8f01cdeb4835f11276"><div class="ttname"><a href="classUsbFTInterface.html#a4fa70ce4a4cd4f8f01cdeb4835f11276">UsbFTInterface::latencyTimer</a></div><div class="ttdeci">unsigned char latencyTimer()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8h_source.html#l00289">UsbFTInterface.h:289</a></div></div> <div class="ttc" id="classUsbFTInterface_html_a5371fe7b447850599eaec81a0ffa2ba0"><div class="ttname"><a href="classUsbFTInterface.html#a5371fe7b447850599eaec81a0ffa2ba0">UsbFTInterface::init</a></div><div class="ttdeci">virtual StatusCode init()</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterface_8cpp_source.html#l00047">UsbFTInterface.cpp:47</a></div></div> <div class="ttc" id="classA3PE_html_a4b9cf42bdd0a14e48807faa0956c59bd"><div class="ttname"><a href="classA3PE.html#a4b9cf42bdd0a14e48807faa0956c59bd">A3PE::internalAXSequence</a></div><div class="ttdeci">bool internalAXSequence()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00285">A3PE.cpp:285</a></div></div> <div class="ttc" id="classAcquisition_html_a303145d497f99da966fcfd95c00cd81e"><div class="ttname"><a href="classAcquisition.html#a303145d497f99da966fcfd95c00cd81e">Acquisition::setDepth</a></div><div class="ttdeci">StatusCode setDepth(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00202">Acquisition.cpp:202</a></div></div> <div class="ttc" id="classA3PE_html_a7f6959a6a38c16fa6609560827413764"><div class="ttname"><a href="classA3PE.html#a7f6959a6a38c16fa6609560827413764">A3PE::fifoLatency</a></div><div class="ttdeci">unsigned int fifoLatency()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00599">A3PE.cpp:599</a></div></div> <div class="ttc" id="classAcquisition_html_af36a1b660244096b7d274f591f67b695"><div class="ttname"><a href="classAcquisition.html#af36a1b660244096b7d274f591f67b695">Acquisition::setStoreSample</a></div><div class="ttdeci">void setStoreSample(bool store_sample)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00057">Acquisition.h:57</a></div></div> <div class="ttc" id="classA3PE_html_a3b75531731fc939206cce076f7ac9f9a"><div class="ttname"><a href="classA3PE.html#a3b75531731fc939206cce076f7ac9f9a">A3PE::writeLengthFifoReg</a></div><div class="ttdeci">Register * writeLengthFifoReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00508">A3PE.h:508</a></div></div> <div class="ttc" id="classAcquisition_html_a37e05315fc47958c290a7d938c61e067"><div class="ttname"><a href="classAcquisition.html#a37e05315fc47958c290a7d938c61e067">Acquisition::setDeadTime</a></div><div class="ttdeci">void setDeadTime(int deadtime)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00063">Acquisition.h:63</a></div></div> <div class="ttc" id="classA3PE_html_ad6b6f1ae4ac23e6d0827eee8cc2c98e4"><div class="ttname"><a href="classA3PE.html#ad6b6f1ae4ac23e6d0827eee8cc2c98e4">A3PE::dumpToAX</a></div><div class="ttdeci">void dumpToAX()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00844">A3PE.cpp:844</a></div></div> <div class="ttc" id="classA3PE__BitFlip_html_a079d34acd89f699395a9bbf6b4918205"><div class="ttname"><a href="classA3PE__BitFlip.html#a079d34acd89f699395a9bbf6b4918205">A3PE_BitFlip::setFile</a></div><div class="ttdeci">StatusCode setFile(std::string filename)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE__BitFlip_8h_source.html#l00030">A3PE_BitFlip.h:30</a></div></div> <div class="ttc" id="classA3PE_html_a2cfdb2f37d3d786cbe1ff42fef37b276"><div class="ttname"><a href="classA3PE.html#a2cfdb2f37d3d786cbe1ff42fef37b276">A3PE::resetFE</a></div><div class="ttdeci">StatusCode resetFE()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00072">A3PE.cpp:72</a></div></div> <div class="ttc" id="classA3PE_html_aeab7701d0d1f6fd910e952b631769d42"><div class="ttname"><a href="classA3PE.html#aeab7701d0d1f6fd910e952b631769d42">A3PE::dumpTrigger</a></div><div class="ttdeci">void dumpTrigger()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00791">A3PE.cpp:791</a></div></div> <div class="ttc" id="classAcquisition_html_a1ceff272a1ad030dcd20c0dcddc65443"><div class="ttname"><a href="classAcquisition.html#a1ceff272a1ad030dcd20c0dcddc65443">Acquisition::setStoreTrend</a></div><div class="ttdeci">void setStoreTrend(bool store_hist)</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00051">Acquisition.h:51</a></div></div> <div class="ttc" id="classA3PE_html_a0300aa5c5ed02b82275c1de434196b9a"><div class="ttname"><a href="classA3PE.html#a0300aa5c5ed02b82275c1de434196b9a">A3PE::setLengthAX</a></div><div class="ttdeci">StatusCode setLengthAX(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00316">A3PE.cpp:316</a></div></div> <div class="ttc" id="classAcquisition_html_acffc6b70b80811657409f92e489584ba"><div class="ttname"><a href="classAcquisition.html#acffc6b70b80811657409f92e489584ba">Acquisition::initialize</a></div><div class="ttdeci">virtual StatusCode initialize()</div><div class="ttdef"><b>Definition:</b> <a href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00049">Acquisition.cpp:49</a></div></div> <div class="ttc" id="classA3PE_html_afd34bfbfd92838717c7cdec856b2a0b2"><div class="ttname"><a href="classA3PE.html#afd34bfbfd92838717c7cdec856b2a0b2">A3PE::resetReg</a></div><div class="ttdeci">Register * resetReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00492">A3PE.h:492</a></div></div> <div class="ttc" id="classA3PE_html_aeb276fae7f19c45b4b4a3a5a2b99c337"><div class="ttname"><a href="classA3PE.html#aeb276fae7f19c45b4b4a3a5a2b99c337">A3PE::setWriteFromAXRamUsb</a></div><div class="ttdeci">StatusCode setWriteFromAXRamUsb(bool)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00213">A3PE.cpp:213</a></div></div> <div class="ttc" id="classA3PE_html_a522cba0a4d976eec59222504af188fb2"><div class="ttname"><a href="classA3PE.html#a522cba0a4d976eec59222504af188fb2">A3PE::loadPattern</a></div><div class="ttdeci">void loadPattern(std::string)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00747">A3PE.cpp:747</a></div></div> <div class="ttc" id="classA3PE_html_a10cf30ff852d7580ba94dbee0c48e0d5"><div class="ttname"><a href="classA3PE.html#a10cf30ff852d7580ba94dbee0c48e0d5">A3PE::clockDivisionReg</a></div><div class="ttdeci">Register * clockDivisionReg()</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8h_source.html#l00516">A3PE.h:516</a></div></div> <div class="ttc" id="classA3PE_html_a02608198bd28bc61882f27368fd90db1"><div class="ttname"><a href="classA3PE.html#a02608198bd28bc61882f27368fd90db1">A3PE::enableADC</a></div><div class="ttdeci">bool enableADC(unsigned int)</div><div class="ttdef"><b>Definition:</b> <a href="A3PE_8cpp_source.html#l00265">A3PE.cpp:265</a></div></div> <div class="ttc" id="classUsbFTInterfaceTest_html_ab9c65d9bc48f205d5dc75e7088474529"><div class="ttname"><a href="classUsbFTInterfaceTest.html#ab9c65d9bc48f205d5dc75e7088474529">UsbFTInterfaceTest::setAddress</a></div><div class="ttdeci">StatusCode setAddress(long int address)</div><div class="ttdef"><b>Definition:</b> <a href="UsbFTInterfaceTest_8h_source.html#l00032">UsbFTInterfaceTest.h:32</a></div></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html> <file_sep>/doc/html/search/variables_7.js var searchData= [ ['gapp',['gApp',['../Tools_8cpp.html#aea679c7117e896daafaf36140158c9ee',1,'Tools.cpp']]], ['gui',['gui',['../namespacegui.html#a6de765688c7629408f05477a6ffa24b7',1,'gui']]] ]; <file_sep>/doc/html/search/typedefs_4.js var searchData= [ ['entrypoint',['EntryPoint',['../classDLL.html#a6d72472c2f54dc82cbb6a5bbab70dae6',1,'DLL']]], ['event_5fhandle',['EVENT_HANDLE',['../LALUsbMLx64_2include_2ftd2xx_8h.html#a23f25cdd38503df3e0edbe14d56dc427',1,'EVENT_HANDLE():&#160;ftd2xx.h'],['../LALUsbx64_2include_2ftd2xx_8h.html#a23f25cdd38503df3e0edbe14d56dc427',1,'EVENT_HANDLE():&#160;ftd2xx.h']]], ['ext_5fusb_5ferror',['Ext_USB_Error',['../LALUsbML_8h.html#ac71032bff6ebe08f542aedd5be9e0e55',1,'Ext_USB_Error():&#160;LALUsbML.h'],['../LALUsb_8h.html#ac71032bff6ebe08f542aedd5be9e0e55',1,'Ext_USB_Error():&#160;LALUsb.h']]] ]; <file_sep>/README.md A branch for the doxygen documentation. To generate the documentation the CATPATH variable needs to be properly set. Doxygen page: https://joaoabcoelho.github.io/lbcat-doxy/doc/html/ <file_sep>/doc/html/search/classes_0.js var searchData= [ ['_5f_5flonglong',['__longlong',['../struct____longlong.html',1,'']]], ['_5fevent_5fhandle',['_EVENT_HANDLE',['../struct__EVENT__HANDLE.html',1,'']]], ['_5fft_5fdevice_5flist_5finfo_5fnode',['_ft_device_list_info_node',['../struct__ft__device__list__info__node.html',1,'']]], ['_5fftcomstat',['_FTCOMSTAT',['../struct__FTCOMSTAT.html',1,'']]], ['_5fftdcb',['_FTDCB',['../struct__FTDCB.html',1,'']]], ['_5ffttimeouts',['_FTTIMEOUTS',['../struct__FTTIMEOUTS.html',1,'']]], ['_5fint_5fframe_5finfo',['_int_frame_info',['../struct__int__frame__info.html',1,'']]], ['_5fml_5fframe',['_ml_frame',['../struct__ml__frame.html',1,'']]], ['_5foverlapped',['_OVERLAPPED',['../struct__OVERLAPPED.html',1,'']]], ['_5fsecurity_5fattributes',['_SECURITY_ATTRIBUTES',['../struct__SECURITY__ATTRIBUTES.html',1,'']]] ]; <file_sep>/doc/html/search/files_1.js var searchData= [ ['cat_2epy',['cat.py',['../cat_8py.html',1,'']]], ['catbcn_5fload_2ecpp',['CatBcn_load.cpp',['../CatBcn__load_8cpp.html',1,'']]], ['catcalo_5fload_2ecpp',['CatCalo_load.cpp',['../CatCalo__load_8cpp.html',1,'']]], ['catcaloproto40mhz_5fload_2ecpp',['CatCaloProto40MHz_load.cpp',['../CatCaloProto40MHz__load_8cpp.html',1,'']]], ['catcaloupgrade_5fload_2ecpp',['CatCaloUpgrade_load.cpp',['../CatCaloUpgrade__load_8cpp.html',1,'']]], ['catcore_5fload_2ecpp',['CatCore_load.cpp',['../CatCore__load_8cpp.html',1,'']]], ['catni_5fload_2ecpp',['CatNI_load.cpp',['../CatNI__load_8cpp.html',1,'']]], ['catspecs_5fload_2ecpp',['CatSpecs_load.cpp',['../CatSpecs__load_8cpp.html',1,'']]], ['cfgframe_2epy',['CfgFrame.py',['../CfgFrame_8py.html',1,'']]], ['computer_2ecpp',['Computer.cpp',['../Computer_8cpp.html',1,'']]], ['computer_2eh',['Computer.h',['../Computer_8h.html',1,'']]], ['computer_2epy',['Computer.py',['../Computer_8py.html',1,'']]], ['confframe_2epy',['ConfFrame.py',['../ConfFrame_8py.html',1,'']]], ['croc_2ecpp',['Croc.cpp',['../Croc_8cpp.html',1,'']]], ['croc_2eh',['Croc.h',['../Croc_8h.html',1,'']]], ['croc_2epy',['Croc.py',['../Croc_8py.html',1,'']]], ['cu_5fv1_2ecpp',['CU_v1.cpp',['../CU__v1_8cpp.html',1,'']]], ['cu_5fv1_2eh',['CU_v1.h',['../CU__v1_8h.html',1,'']]], ['currentmeasurement_2ecpp',['CurrentMeasurement.cpp',['../CurrentMeasurement_8cpp.html',1,'']]], ['currentmeasurement_2eh',['CurrentMeasurement.h',['../CurrentMeasurement_8h.html',1,'']]], ['currentmeasurement_2epy',['CurrentMeasurement.py',['../CurrentMeasurement_8py.html',1,'']]] ]; <file_sep>/doc/html/search/classes_13.js var searchData= [ ['wrapper',['wrapper',['../classwrapper_1_1wrapper.html',1,'wrapper']]] ]; <file_sep>/doc/html/search/files_2.js var searchData= [ ['data_2ecpp',['Data.cpp',['../CatCaloEvent_2src_2Data_8cpp.html',1,'(Global Namespace)'],['../CatKernel_2src_2Data_8cpp.html',1,'(Global Namespace)']]], ['data_2eh',['Data.h',['../CatCaloEvent_2inc_2Data_8h.html',1,'(Global Namespace)'],['../CatKernel_2inc_2Data_8h.html',1,'(Global Namespace)']]], ['datalinkdef_2eh',['DataLinkDef.h',['../DataLinkDef_8h.html',1,'']]], ['dcu_2ecpp',['DCU.cpp',['../DCU_8cpp.html',1,'']]], ['dcu_2eh',['DCU.h',['../DCU_8h.html',1,'']]], ['dll_2ecpp',['DLL.cpp',['../DLL_8cpp.html',1,'']]], ['dll_2eh',['DLL.h',['../DLL_8h.html',1,'']]], ['dllmgr_2ecpp',['DLLMgr.cpp',['../DLLMgr_8cpp.html',1,'']]], ['dllmgr_2eh',['DLLMgr.h',['../DLLMgr_8h.html',1,'']]] ]; <file_sep>/doc/html/search/all_18.js var searchData= [ ['xbins',['xbins',['../classHisto2D.html#a8f42529a5fba07c339e547bf504dd418',1,'Histo2D']]], ['xoffchar',['XoffChar',['../struct__FTDCB.html#a30a25a1c40525289b24b29f6593a6c51',1,'_FTDCB']]], ['xofflim',['XoffLim',['../struct__FTDCB.html#af78536d2734d9172b6707df1d3b1326d',1,'_FTDCB']]], ['xonchar',['XonChar',['../struct__FTDCB.html#aee3e405df31d5b168110814d5529b014',1,'_FTDCB']]], ['xonlim',['XonLim',['../struct__FTDCB.html#a44679a1dcfaa0f97bc4d1500538c4b47',1,'_FTDCB']]] ]; <file_sep>/doc/html/search/files_10.js var searchData= [ ['testi2c_2ecpp',['TestI2C.cpp',['../TestI2C_8cpp.html',1,'']]], ['testi2c_2eh',['TestI2C.h',['../TestI2C_8h.html',1,'']]], ['testi2c_2epy',['TestI2C.py',['../TestI2C_8py.html',1,'']]], ['testspi_2ecpp',['TestSPI.cpp',['../TestSPI_8cpp.html',1,'']]], ['testspi_2eh',['TestSPI.h',['../TestSPI_8h.html',1,'']]], ['testspi_2epy',['TestSPI.py',['../TestSPI_8py.html',1,'']]], ['testsuite_2ecpp',['TestSuite.cpp',['../TestSuite_8cpp.html',1,'']]], ['testsuite_2eh',['TestSuite.h',['../TestSuite_8h.html',1,'']]], ['testsuite_2epy',['TestSuite.py',['../TestSuite_8py.html',1,'']]], ['testusb_2ecpp',['TestUSB.cpp',['../TestUSB_8cpp.html',1,'']]], ['testusb_2eh',['TestUSB.h',['../TestUSB_8h.html',1,'']]], ['testusb_2epy',['TestUSB.py',['../TestUSB_8py.html',1,'']]], ['timing_2eh',['Timing.h',['../Timing_8h.html',1,'']]], ['tools_2ecpp',['Tools.cpp',['../Tools_8cpp.html',1,'']]], ['tools_2eh',['Tools.h',['../Tools_8h.html',1,'']]], ['tools_2epy',['tools.py',['../tools_8py.html',1,'']]], ['tree_2epy',['tree.py',['../tree_8py.html',1,'']]], ['tutorial_2emd',['Tutorial.md',['../Tutorial_8md.html',1,'']]] ]; <file_sep>/doc/html/search/namespaces_9.js var searchData= [ ['testi2c',['TestI2C',['../namespaceTestI2C.html',1,'']]], ['testspi',['TestSPI',['../namespaceTestSPI.html',1,'']]], ['testsuite',['TestSuite',['../namespaceTestSuite.html',1,'']]], ['testusb',['TestUSB',['../namespaceTestUSB.html',1,'']]], ['tools',['tools',['../namespacetools.html',1,'']]], ['tree',['tree',['../namespacetree.html',1,'']]] ]; <file_sep>/doc/html/search/functions_17.js var searchData= [ ['ybins',['ybins',['../classHisto2D.html#a0ae225e33eb9837137b10a159ac1d4f2',1,'Histo2D']]] ]; <file_sep>/doc/html/search/all_b.js var searchData= [ ['kernel_2eh',['Kernel.h',['../Kernel_8h.html',1,'']]], ['kerneltime',['kernelTime',['../namespaceSystem.html#a52400aecb0f63c891b51bc958ea064e9',1,'System']]] ]; <file_sep>/doc/html/search/classes_6.js var searchData= [ ['graphframe',['GraphFrame',['../classGraphFrame_1_1GraphFrame.html',1,'GraphFrame']]], ['gui',['Gui',['../classgui_1_1Gui.html',1,'gui']]] ]; <file_sep>/doc/html/search/classes_2.js var searchData= [ ['cfgframe',['CfgFrame',['../classCfgFrame_1_1CfgFrame.html',1,'CfgFrame']]], ['computer',['Computer',['../classComputer_1_1Computer.html',1,'Computer.Computer'],['../classComputer.html',1,'Computer']]], ['confframe',['ConfFrame',['../classConfFrame_1_1ConfFrame.html',1,'ConfFrame']]], ['config',['Config',['../classConfig.html',1,'']]], ['confregdata',['confRegData',['../structconfRegData.html',1,'']]], ['croc',['Croc',['../classCroc_1_1Croc.html',1,'Croc.Croc'],['../classCroc.html',1,'Croc']]], ['cu_5fv1',['CU_v1',['../classCU__v1.html',1,'']]], ['currentmeasurement',['CurrentMeasurement',['../classCurrentMeasurement.html',1,'CurrentMeasurement'],['../classADCMeasurement_1_1CurrentMeasurement.html',1,'ADCMeasurement.CurrentMeasurement'],['../classCurrentMeasurement_1_1CurrentMeasurement.html',1,'CurrentMeasurement.CurrentMeasurement']]] ]; <file_sep>/doc/html/search/enumvalues_12.js var searchData= [ ['times',['Times',['../namespaceSystem.html#a71a46d52920ca8e98fc4649949be58a7a3f922834570db4b74edefd683ee0424b',1,'System']]], ['txstatus',['TXSTATUS',['../LALUsbML_8h.html#a7bb4b3f5a75f92e2825cf776d730210ca9cafa2e2fa7aa5557cad854538cd329d',1,'TXSTATUS():&#160;LALUsbML.h'],['../LALUsb_8h.html#a7bb4b3f5a75f92e2825cf776d730210ca9cafa2e2fa7aa5557cad854538cd329d',1,'TXSTATUS():&#160;LALUsb.h']]] ]; <file_sep>/doc/html/search/enums_9.js var searchData= [ ['wordsize',['WordSize',['../classUsbFTInterface.html#a057387f452eaac094fb77ba09cf1cf2e',1,'UsbFTInterface::WordSize()'],['../classUsbFTMLInterface.html#ae0f25daa336091a5acd548aef3e9b4b4',1,'UsbFTMLInterface::WordSize()'],['../classIOdata.html#a37c53ebf4bf8d866aac8af572962a84c',1,'IOdata::WordSize()']]] ]; <file_sep>/doc/html/search/classes_e.js var searchData= [ ['ram',['RAM',['../classRAM.html',1,'']]], ['register',['Register',['../classRegister.html',1,'']]], ['registertest',['RegisterTest',['../classRegisterTest.html',1,'']]], ['run',['Run',['../classRun.html',1,'']]] ]; <file_sep>/doc/html/search/functions_a.js var searchData= [ ['kerneltime',['kernelTime',['../namespaceSystem.html#a52400aecb0f63c891b51bc958ea064e9',1,'System']]] ]; <file_sep>/doc/html/search/enumvalues_6.js var searchData= [ ['good',['GOOD',['../namespaceCATApp.html#a10d106f6dbef9da3b1ba48892278b9c4a38777cb47f97b9703919e12ca841f9a3',1,'CATApp']]], ['green',['GREEN',['../classMsgSvc.html#af95de99b5b2e7b6754b6d94ec5526d2ca0b06352b93e105a1b59d246e3ab1473f',1,'MsgSvc::GREEN()'],['../classServer__NI6008.html#abee9aec1c5054cd3223d4a1e5e4a7ad9a68bc466d3117463d6348299d532b2d45',1,'Server_NI6008::GREEN()']]] ]; <file_sep>/doc/html/search/classes_8.js var searchData= [ ['icecalv3',['ICECALv3',['../classICECALv3.html',1,'']]], ['icphaser',['ICPhaser',['../classICPhaser.html',1,'']]], ['imageclass',['ImageClass',['../classimages_1_1ImageClass.html',1,'images']]], ['interface',['Interface',['../classInterface.html',1,'']]], ['interfacewrap',['InterfaceWrap',['../structInterfaceWrap.html',1,'']]], ['iodata',['IOdata',['../classIOdata.html',1,'']]], ['ioobject',['IOobject',['../classIOobject.html',1,'']]] ]; <file_sep>/doc/html/search/classes_11.js var searchData= [ ['usage',['Usage',['../classarguments_1_1Usage.html',1,'arguments']]], ['usbftinterface',['UsbFTInterface',['../classUsbFTInterface.html',1,'']]], ['usbftinterfacetest',['UsbFTInterfaceTest',['../classUsbFTInterfaceTest_1_1UsbFTInterfaceTest.html',1,'UsbFTInterfaceTest.UsbFTInterfaceTest'],['../classUsbFTInterfaceTest.html',1,'UsbFTInterfaceTest']]], ['usbftmlinterface',['UsbFTMLInterface',['../classUsbFTMLInterface.html',1,'']]], ['usbi2cbus',['UsbI2cBus',['../classUsbI2cBus.html',1,'']]], ['usbmli2cbus',['UsbMLI2cBus',['../classUsbMLI2cBus.html',1,'']]], ['usbmlspibus',['UsbMLSpiBus',['../classUsbMLSpiBus.html',1,'']]], ['usbspibus',['UsbSpiBus',['../classUsbSpiBus.html',1,'']]] ]; <file_sep>/doc/html/search/defines_b.js var searchData= [ ['resetdev',['RESETDEV',['../LALUsbMLx64_2include_2WinTypes_8h.html#a17b5a1451c6a0498bcac6ade3ba2fe17',1,'RESETDEV():&#160;WinTypes.h'],['../LALUsbx64_2include_2ftd2xx_8h.html#a17b5a1451c6a0498bcac6ade3ba2fe17',1,'RESETDEV():&#160;ftd2xx.h']]] ]; <file_sep>/doc/html/search/enumvalues_14.js var searchData= [ ['verbose',['VERBOSE',['../classMsgSvc.html#ae671eb7301996cd049d2da8a65925926af655256b06494ade5ba830abe5401ec9',1,'MsgSvc::VERBOSE()'],['../classServer__NI6008.html#af1e3e3bac26355a746b5d2e548fe25bea58fcd852dfcff4011a32756eda28852b',1,'Server_NI6008::VERBOSE()']]] ]; <file_sep>/doc/html/search/files_12.js var searchData= [ ['var_2ecpp',['var.cpp',['../var_8cpp.html',1,'']]], ['var_2eh',['var.h',['../var_8h.html',1,'']]], ['version_2epy',['version.py',['../version_8py.html',1,'']]] ]; <file_sep>/doc/html/search/enumvalues_a.js var searchData= [ ['locus_5f0350_5fua',['LOCUS_0350_UA',['../LSDelayChipV1_8h.html#a9dbbe19d91a9e4d61f7291c5aeabce63abcd44318e3bbcab80cb33b8ac0638fa0',1,'LSDelayChipV1.h']]], ['locus_5f1400_5fua',['LOCUS_1400_UA',['../LSDelayChipV1_8h.html#a9dbbe19d91a9e4d61f7291c5aeabce63aaf5de18b5633f00e781bb74b6c3850d3',1,'LSDelayChipV1.h']]], ['locus_5f2300_5fua',['LOCUS_2300_UA',['../LSDelayChipV1_8h.html#a9dbbe19d91a9e4d61f7291c5aeabce63a06d3e527062b8ffd220520be69e0d4e6',1,'LSDelayChipV1.h']]], ['locus_5f3000_5fua',['LOCUS_3000_UA',['../LSDelayChipV1_8h.html#a9dbbe19d91a9e4d61f7291c5aeabce63a259de7b287dcc219dd6cda577c9ebc4c',1,'LSDelayChipV1.h']]] ]; <file_sep>/doc/html/search/classes_7.js var searchData= [ ['hierarchy',['Hierarchy',['../classHierarchy.html',1,'']]], ['histo1d',['Histo1D',['../classHisto1D.html',1,'']]], ['histo2d',['Histo2D',['../classHisto2D.html',1,'']]] ]; <file_sep>/doc/html/search/files_11.js var searchData= [ ['usbftinterface_2ecpp',['UsbFTInterface.cpp',['../UsbFTInterface_8cpp.html',1,'']]], ['usbftinterface_2eh',['UsbFTInterface.h',['../UsbFTInterface_8h.html',1,'']]], ['usbftinterfacetest_2ecpp',['UsbFTInterfaceTest.cpp',['../UsbFTInterfaceTest_8cpp.html',1,'']]], ['usbftinterfacetest_2eh',['UsbFTInterfaceTest.h',['../UsbFTInterfaceTest_8h.html',1,'']]], ['usbftinterfacetest_2epy',['UsbFTInterfaceTest.py',['../UsbFTInterfaceTest_8py.html',1,'']]], ['usbftmlinterface_2ecpp',['UsbFTMLInterface.cpp',['../UsbFTMLInterface_8cpp.html',1,'']]], ['usbftmlinterface_2eh',['UsbFTMLInterface.h',['../UsbFTMLInterface_8h.html',1,'']]], ['usbi2cbus_2ecpp',['UsbI2cBus.cpp',['../UsbI2cBus_8cpp.html',1,'']]], ['usbi2cbus_2eh',['UsbI2cBus.h',['../UsbI2cBus_8h.html',1,'']]], ['usbmli2cbus_2ecpp',['UsbMLI2cBus.cpp',['../UsbMLI2cBus_8cpp.html',1,'']]], ['usbmli2cbus_2eh',['UsbMLI2cBus.h',['../UsbMLI2cBus_8h.html',1,'']]], ['usbmlspibus_2ecpp',['UsbMLSpiBus.cpp',['../UsbMLSpiBus_8cpp.html',1,'']]], ['usbmlspibus_2eh',['UsbMLSpiBus.h',['../UsbMLSpiBus_8h.html',1,'']]], ['usbspibus_2ecpp',['UsbSpiBus.cpp',['../UsbSpiBus_8cpp.html',1,'']]], ['usbspibus_2eh',['UsbSpiBus.h',['../UsbSpiBus_8h.html',1,'']]] ]; <file_sep>/doc/html/search/pages_0.js var searchData= [ ['cat_20tutorial',['CAT Tutorial',['../index.html',1,'']]], ['cat_20tutorial',['CAT Tutorial',['../tutorial.html',1,'']]] ]; <file_sep>/doc/html/search/namespaces_a.js var searchData= [ ['usbftinterfacetest',['UsbFTInterfaceTest',['../namespaceUsbFTInterfaceTest.html',1,'']]] ]; <file_sep>/doc/html/search/defines_2.js var searchData= [ ['bxid_5fresynch_5faddr',['BXID_RESYNCH_ADDR',['../ICECALv3_8h.html#a57a201af9e55ffd847b551bff2dc71ce',1,'ICECALv3.h']]] ]; <file_sep>/doc/html/search/files_13.js var searchData= [ ['win32psapi_2eh',['Win32PsApi.h',['../Win32PsApi_8h.html',1,'']]], ['wintypes_2eh',['WinTypes.h',['../CatCaloProto40MHz_2inc_2WinTypes_8h.html',1,'(Global Namespace)'],['../LALUsbMLx64_2include_2WinTypes_8h.html',1,'(Global Namespace)'],['../LALUsbx64_2include_2WinTypes_8h.html',1,'(Global Namespace)']]], ['wrapper_2epy',['wrapper.py',['../wrapper_8py.html',1,'']]] ]; <file_sep>/doc/html/search/enums_8.js var searchData= [ ['timetype',['TimeType',['../namespaceSystem.html#a15db094516c062b412df2453b4350f1a',1,'System']]], ['txrx_5fstatus',['TXRX_STATUS',['../LALUsbML_8h.html#a7bb4b3f5a75f92e2825cf776d730210c',1,'TXRX_STATUS():&#160;LALUsbML.h'],['../LALUsb_8h.html#a7bb4b3f5a75f92e2825cf776d730210c',1,'TXRX_STATUS():&#160;LALUsb.h']]], ['type',['Type',['../classStatusCode.html#a6f565cbeadc76d14c72f047e5e85eb4b',1,'StatusCode::Type()'],['../classvar.html#ae4f9e2c747c3e72f245b148146b1855e',1,'var::Type()']]] ]; <file_sep>/doc/html/search/files_a.js var searchData= [ ['moduleinfo_2ecpp',['ModuleInfo.cpp',['../ModuleInfo_8cpp.html',1,'']]], ['moduleinfo_2eh',['ModuleInfo.h',['../ModuleInfo_8h.html',1,'']]], ['msgsvc_2ecpp',['MsgSvc.cpp',['../MsgSvc_8cpp.html',1,'']]], ['msgsvc_2eh',['MsgSvc.h',['../MsgSvc_8h.html',1,'']]], ['msoxxxx_2ecpp',['MSOxxxx.cpp',['../MSOxxxx_8cpp.html',1,'']]], ['msoxxxx_2eh',['MSOxxxx.h',['../MSOxxxx_8h.html',1,'']]] ]; <file_sep>/doc/html/search/typedefs_3.js var searchData= [ ['destructorelement',['DestructorElement',['../classDLL.html#a204f0c776712969410a2673db3d98cf5',1,'DLL']]], ['destructorobject',['DestructorObject',['../classDLL.html#a4400d330cd793ae5f883ffa58384f637',1,'DLL']]], ['destructorprocessus',['DestructorProcessus',['../classDLL.html#a203a61b2a683e2751b5f3fe5a7187a7e',1,'DLL']]], ['dword',['DWORD',['../CatCaloProto40MHz_2inc_2WinTypes_8h.html#ad342ac907eb044443153a22f964bf0af',1,'DWORD():&#160;WinTypes.h'],['../LALUsbMLx64_2include_2WinTypes_8h.html#ad342ac907eb044443153a22f964bf0af',1,'DWORD():&#160;WinTypes.h'],['../LALUsbx64_2include_2WinTypes_8h.html#ad342ac907eb044443153a22f964bf0af',1,'DWORD():&#160;WinTypes.h']]] ]; <file_sep>/doc/html/search/searchdata.js var indexSectionsWithContent = { 0: "_abcdefghijklmnopqrstuvwxy~", 1: "_acdefghilmnoprstuvw", 2: "acegilopstuvw", 3: "acdefghiklmnoprstuvw", 4: "_abcdefghiklmnoprstuvwxy~", 5: "_abcdefghilmnoprstuvwx", 6: "abcdefghilmoprstuvw", 7: "_abilmqstw", 8: "abcdefghijlmnopqrstuvwy", 9: "_abcdefilmprstuw", 10: "c", 11: "c" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "namespaces", 3: "files", 4: "functions", 5: "variables", 6: "typedefs", 7: "enums", 8: "enumvalues", 9: "defines", 10: "groups", 11: "pages" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Namespaces", 3: "Files", 4: "Functions", 5: "Variables", 6: "Typedefs", 7: "Enumerations", 8: "Enumerator", 9: "Macros", 10: "Modules", 11: "Pages" }; <file_sep>/doc/html/search/classes_f.js var searchData= [ ['seqpga',['SeqPGA',['../classSeqPGA.html',1,'']]], ['server',['Server',['../classServer.html',1,'']]], ['server_5fni6008',['Server_NI6008',['../classServer__NI6008.html',1,'']]], ['specsbus',['SpecsBus',['../classSpecsBus.html',1,'']]], ['specsglue',['SpecsGlue',['../classSpecsGlue.html',1,'']]], ['specsi2c',['SpecsI2c',['../classSpecsI2c.html',1,'']]], ['specsinterface',['SpecsInterface',['../classSpecsInterface.html',1,'']]], ['specsmaster',['SpecsMaster',['../classSpecsMaster.html',1,'']]], ['specsmezzanine',['SpecsMezzanine',['../classSpecsMezzanine.html',1,'']]], ['specsparallelbus',['SpecsParallelBus',['../classSpecsParallelBus.html',1,'']]], ['specsslave',['SpecsSlave',['../classSpecsSlave.html',1,'']]], ['splashscreen',['SplashScreen',['../classgui_1_1SplashScreen.html',1,'gui']]], ['state',['State',['../classState.html',1,'']]], ['statregdata',['statRegData',['../structstatRegData.html',1,'']]], ['statuscode',['StatusCode',['../classStatusCode.html',1,'']]], ['storagefifo',['StorageFifo',['../classStorageFifo_1_1StorageFifo.html',1,'StorageFifo.StorageFifo'],['../classStorageFifo.html',1,'StorageFifo']]], ['storagefifoacquisition',['StorageFifoAcquisition',['../classStorageFifoAcquisition.html',1,'StorageFifoAcquisition'],['../classStorageFifoAcquisition_1_1StorageFifoAcquisition.html',1,'StorageFifoAcquisition.StorageFifoAcquisition']]] ]; <file_sep>/doc/html/search/classes_1.js var searchData= [ ['a3pe',['A3PE',['../classA3PE.html',1,'']]], ['a3pe_5fbitflip',['A3PE_BitFlip',['../classA3PE__BitFlip.html',1,'A3PE_BitFlip'],['../classA3PE__BitFlip_1_1A3PE__BitFlip.html',1,'A3PE_BitFlip.A3PE_BitFlip']]], ['acquisition',['Acquisition',['../classAcquisition.html',1,'Acquisition'],['../classAcquisition_1_1Acquisition.html',1,'Acquisition.Acquisition']]], ['adcmeasurement',['ADCMeasurement',['../classADCMeasurement.html',1,'']]], ['animatedprogressbar',['AnimatedProgressBar',['../classprogressbar_1_1AnimatedProgressBar.html',1,'progressbar']]], ['appframe',['AppFrame',['../classAppFrame_1_1AppFrame.html',1,'AppFrame']]], ['application',['Application',['../classApplication.html',1,'']]], ['arguments',['arguments',['../classarguments_1_1arguments.html',1,'arguments']]], ['attrib',['Attrib',['../classAttrib.html',1,'']]] ]; <file_sep>/doc/html/search/classes_a.js var searchData= [ ['moduledictwrapper',['ModuleDictWrapper',['../classwrapper_1_1ModuleDictWrapper.html',1,'wrapper']]], ['msgsvc',['MsgSvc',['../classMsgSvc.html',1,'']]], ['msoxxxx',['MSOxxxx',['../classMSOxxxx.html',1,'']]], ['mytreectrl',['MyTreeCtrl',['../classtree_1_1MyTreeCtrl.html',1,'tree']]] ]; <file_sep>/doc/html/search/variables_5.js var searchData= [ ['econdvar',['eCondVar',['../struct__EVENT__HANDLE.html#a22f9905a075b5f0c84fa336b8532e756',1,'_EVENT_HANDLE']]], ['elementcombo',['elementCombo',['../classAppFrame_1_1AppFrame.html#a756e6204d661babaec7a23ee50a745d1',1,'AppFrame::AppFrame']]], ['emutex',['eMutex',['../struct__EVENT__HANDLE.html#ac18c63dbb1acc29ff1104b80fe7b4269',1,'_EVENT_HANDLE']]], ['end',['end',['../classprogressbar_1_1ProgressBar.html#a92053e3baab49364971c15373b6c848f',1,'progressbar::ProgressBar']]], ['endpointsize',['EndpointSize',['../structft__program__data.html#adef6d265cbf1ca51540468b6f39c387a',1,'ft_program_data']]], ['environ',['environ',['../System_8cpp.html#aa006daaf11f1e2e45a6ababaf463212b',1,'System.cpp']]], ['eofchar',['EofChar',['../struct__FTDCB.html#a6f0a84ef54dbc36123a40e05ba94aa4e',1,'_FTDCB']]], ['err',['err',['../classICECALv3.html#ad8989925ee5b3ff322d863ce6aaff0bd',1,'ICECALv3::err()'],['../classMSOxxxx.html#af0af7ac8123ee93917d0e92ec947acaa',1,'MSOxxxx::err()']]], ['err_5fcode',['err_code',['../struct__int__frame__info.html#a43e1a7c19fbc0d16e21dd9cb58f686e2',1,'_int_frame_info']]], ['error_5ftype',['error_type',['../struct__int__frame__info.html#a1bec0ff5f853c91d7c1f942a313b3f04',1,'_int_frame_info']]], ['errorchar',['ErrorChar',['../struct__FTDCB.html#a0b8fa24da4dcdba892abd2c6cdb55707',1,'_FTDCB']]], ['errorcount',['errorCount',['../classPhaserRampExec.html#a3f09b8bf4cd8f5425adf8ae168d39e50',1,'PhaserRampExec']]], ['errordllslow',['errorDllSlow',['../structstatRegData.html#aef4d8d8abc4ce09fe4513a491718cf78',1,'statRegData']]], ['evt',['Evt',['../classData.html#a116d0476675c4eb96ad7f3ddb2b5f6cd',1,'Data']]], ['evtchar',['EvtChar',['../struct__FTDCB.html#a579b4755ad4a7ea9c76ddaf5f548a460',1,'_FTDCB']]] ]; <file_sep>/doc/html/search/files_e.js var searchData= [ ['ram_2ecpp',['RAM.cpp',['../RAM_8cpp.html',1,'']]], ['ram_2eh',['RAM.h',['../RAM_8h.html',1,'']]], ['readme_2emd',['README.md',['../README_8md.html',1,'']]], ['register_2ecpp',['Register.cpp',['../Register_8cpp.html',1,'']]], ['register_2eh',['Register.h',['../Register_8h.html',1,'']]], ['registertest_2ecpp',['RegisterTest.cpp',['../RegisterTest_8cpp.html',1,'']]], ['registertest_2eh',['RegisterTest.h',['../RegisterTest_8h.html',1,'']]], ['run_2ecpp',['Run.cpp',['../Run_8cpp.html',1,'']]], ['run_2eh',['Run.h',['../Run_8h.html',1,'']]], ['runlinkdef_2eh',['RunLinkDef.h',['../RunLinkDef_8h.html',1,'']]] ]; <file_sep>/doc/html/search/files_d.js var searchData= [ ['phaser_2ecpp',['Phaser.cpp',['../Phaser_8cpp.html',1,'']]], ['phaser_2eh',['Phaser.h',['../Phaser_8h.html',1,'']]], ['phaserrampexec_2ecpp',['PhaserRampExec.cpp',['../PhaserRampExec_8cpp.html',1,'']]], ['phaserrampexec_2eh',['PhaserRampExec.h',['../PhaserRampExec_8h.html',1,'']]], ['phaserscan_2eh',['PhaserScan.h',['../PhaserScan_8h.html',1,'']]], ['plot_2ecpp',['Plot.cpp',['../Plot_8cpp.html',1,'']]], ['plot_2eh',['Plot.h',['../Plot_8h.html',1,'']]], ['plotter_2epy',['plotter.py',['../plotter_8py.html',1,'']]], ['proc_2epy',['proc.py',['../proc_8py.html',1,'']]], ['procdatabase_2ecpp',['ProcDataBase.cpp',['../ProcDataBase_8cpp.html',1,'']]], ['procdatabase_2eh',['ProcDataBase.h',['../ProcDataBase_8h.html',1,'']]], ['processus_2ecpp',['Processus.cpp',['../Processus_8cpp.html',1,'']]], ['processus_2eh',['Processus.h',['../Processus_8h.html',1,'']]], ['proctimer_2ecpp',['ProcTimer.cpp',['../ProcTimer_8cpp.html',1,'']]], ['proctimer_2eh',['ProcTimer.h',['../ProcTimer_8h.html',1,'']]], ['progressbar_2epy',['progressbar.py',['../progressbar_8py.html',1,'']]], ['proto40mhz_5fv1_2ecpp',['Proto40MHz_v1.cpp',['../Proto40MHz__v1_8cpp.html',1,'']]], ['proto40mhz_5fv1_2eh',['Proto40MHz_v1.h',['../Proto40MHz__v1_8h.html',1,'']]], ['proto40mhz_5fv1_2epy',['Proto40MHz_v1.py',['../Proto40MHz__v1_8py.html',1,'']]], ['protofeb_5fv1_2epy',['ProtoFEB_v1.py',['../ProtoFEB__v1_8py.html',1,'']]], ['python_2ecpp',['Python.cpp',['../CatBcn_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatCalo_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatCaloProto40MHz_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatCaloUpgrade_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatCore_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatKernel_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatNI_2src_2Python_8cpp.html',1,'(Global Namespace)'],['../CatSpecs_2src_2Python_8cpp.html',1,'(Global Namespace)']]], ['python_5fbase_2ecpp',['Python_Base.cpp',['../Python__Base_8cpp.html',1,'']]], ['python_5fobj_2ecpp',['Python_Obj.cpp',['../Python__Obj_8cpp.html',1,'']]], ['python_5fproc_2ecpp',['Python_Proc.cpp',['../Python__Proc_8cpp.html',1,'']]] ]; <file_sep>/doc/html/search/typedefs_a.js var searchData= [ ['ml_5fframe',['ML_Frame',['../LALUsbML_8h.html#ac256ca94b86e3a080c0fc61f3c546bb1',1,'LALUsbML.h']]] ]; <file_sep>/doc/html/classAcquisition_1_1Acquisition.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Cat: Acquisition.Acquisition 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> <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">Cat </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="classAcquisition.html">Acquisition</a></li><li class="navelem"><a class="el" href="classAcquisition_1_1Acquisition.html">Acquisition</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="classAcquisition_1_1Acquisition-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">Acquisition.Acquisition Class Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for Acquisition.Acquisition:</div> <div class="dyncontent"> <div class="center"> <img src="classAcquisition_1_1Acquisition.png" usemap="#Acquisition.Acquisition_map" alt=""/> <map id="Acquisition.Acquisition_map" name="Acquisition.Acquisition_map"> </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:a2811edf47d59be70aeb9589a5e339893"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#a2811edf47d59be70aeb9589a5e339893">__init__</a> (self, cat, obj, panel, path)</td></tr> <tr class="separator:a2811edf47d59be70aeb9589a5e339893"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac7be703152b5ec0e02bc9c742d59cd50"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#ac7be703152b5ec0e02bc9c742d59cd50">onApply</a> (self, event)</td></tr> <tr class="separator:ac7be703152b5ec0e02bc9c742d59cd50"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa686f47e8d19e10efa43c3330fd7d19b"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#aa686f47e8d19e10efa43c3330fd7d19b">onSoftTrig</a> (self, event)</td></tr> <tr class="separator:aa686f47e8d19e10efa43c3330fd7d19b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9d82c40d0be476e1f4b9a8ec0f6ea29a"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#a9d82c40d0be476e1f4b9a8ec0f6ea29a">onTree</a> (self, event)</td></tr> <tr class="separator:a9d82c40d0be476e1f4b9a8ec0f6ea29a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:adde3ae2fd3eff1e113bd20651c8561a3"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#adde3ae2fd3eff1e113bd20651c8561a3">onTrend</a> (self, event)</td></tr> <tr class="separator:adde3ae2fd3eff1e113bd20651c8561a3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a37caf6d3a03c683c5fbcc079a2d8c7ec"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#a37caf6d3a03c683c5fbcc079a2d8c7ec">onSample</a> (self, event)</td></tr> <tr class="separator:a37caf6d3a03c683c5fbcc079a2d8c7ec"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aec0df3e0eea3f89f5c3057fac481be46"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#aec0df3e0eea3f89f5c3057fac481be46">onDeadtime</a> (self, event)</td></tr> <tr class="separator:aec0df3e0eea3f89f5c3057fac481be46"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:abd482f75a95cdcc9b55c5adb7c046ae3"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#abd482f75a95cdcc9b55c5adb7c046ae3">onDepth</a> (self, event)</td></tr> <tr class="separator:abd482f75a95cdcc9b55c5adb7c046ae3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae0cfd44965bc1dd829cd6d6660cdd0ee"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#ae0cfd44965bc1dd829cd6d6660cdd0ee">onNSample</a> (self, event)</td></tr> <tr class="separator:ae0cfd44965bc1dd829cd6d6660cdd0ee"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a59fd4f2c9690f7745f346281ffe4f658"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#a59fd4f2c9690f7745f346281ffe4f658">onNBins</a> (self, event)</td></tr> <tr class="separator:a59fd4f2c9690f7745f346281ffe4f658"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aeb3c0ebfb598e5b1c03710574826108c"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#aeb3c0ebfb598e5b1c03710574826108c">onMin</a> (self, event)</td></tr> <tr class="separator:aeb3c0ebfb598e5b1c03710574826108c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad744ff797e84b6e5f785c24d44144697"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#ad744ff797e84b6e5f785c24d44144697">onMax</a> (self, event)</td></tr> <tr class="separator:ad744ff797e84b6e5f785c24d44144697"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:abb09e973b83aec6cc4c660992b7dcc9d"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classAcquisition_1_1Acquisition.html#abb09e973b83aec6cc4c660992b7dcc9d">update</a> (self)</td></tr> <tr class="separator:abb09e973b83aec6cc4c660992b7dcc9d"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00008">8</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a id="a2811edf47d59be70aeb9589a5e339893"></a> <h2 class="memtitle"><span class="permalink"><a href="#a2811edf47d59be70aeb9589a5e339893">&#9670;&nbsp;</a></span>__init__()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.__init__ </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>cat</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>obj</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>panel</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>path</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00009">9</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="element_8py_source.html#l00015">element.element.loadxrc()</a>, <a class="el" href="proc_8py_source.html#l00016">proc.proc.loadxrc()</a>, <a class="el" href="Acquisition_8py_source.html#l00026">Acquisition.Acquisition.onApply()</a>, <a class="el" href="Acquisition_8py_source.html#l00064">Acquisition.Acquisition.onDeadtime()</a>, <a class="el" href="Acquisition_8py_source.html#l00066">Acquisition.Acquisition.onDepth()</a>, <a class="el" href="Acquisition_8py_source.html#l00078">Acquisition.Acquisition.onMax()</a>, <a class="el" href="Acquisition_8py_source.html#l00075">Acquisition.Acquisition.onMin()</a>, <a class="el" href="Acquisition_8py_source.html#l00072">Acquisition.Acquisition.onNBins()</a>, <a class="el" href="Acquisition_8py_source.html#l00069">Acquisition.Acquisition.onNSample()</a>, <a class="el" href="Acquisition_8py_source.html#l00061">Acquisition.Acquisition.onSample()</a>, <a class="el" href="Acquisition_8py_source.html#l00046">Acquisition.Acquisition.onSoftTrig()</a>, <a class="el" href="Proto40MHz__v1_8py_source.html#l00182">Proto40MHz_v1.Proto40MHz_v1.onSoftTrig()</a>, <a class="el" href="ProtoFEB__v1_8py_source.html#l00182">ProtoFEB_v1.ProtoFEB_v1.onSoftTrig()</a>, <a class="el" href="Acquisition_8py_source.html#l00055">Acquisition.Acquisition.onTree()</a>, <a class="el" href="Acquisition_8py_source.html#l00058">Acquisition.Acquisition.onTrend()</a>, <a class="el" href="object_8py_source.html#l00010">object.object.panel</a>, <a class="el" href="element_8py_source.html#l00021">element.element.panel</a>, <a class="el" href="proc_8py_source.html#l00022">proc.proc.panel</a>, <a class="el" href="LogFrame_8py_source.html#l00028">LogFrame.LogFrame.panel</a>, <a class="el" href="ConfFrame_8py_source.html#l00032">ConfFrame.ConfFrame.panel</a>, <a class="el" href="GraphFrame_8py_source.html#l00035">GraphFrame.GraphFrame.panel</a>, <a class="el" href="AppFrame_8py_source.html#l00080">AppFrame.AppFrame.panel</a>, <a class="el" href="Croc_8py_source.html#l00010">Croc.Croc.update()</a>, <a class="el" href="A3PE__BitFlip_8py_source.html#l00015">A3PE_BitFlip.A3PE_BitFlip.update()</a>, <a class="el" href="Croc_8h_source.html#l00048">Croc.update()</a>, <a class="el" href="Proto40MHz__v1_8h_source.html#l00056">Proto40MHz_v1.update()</a>, <a class="el" href="Acquisition_8py_source.html#l00081">Acquisition.Acquisition.update()</a>, <a class="el" href="Proto40MHz__v1_8py_source.html#l00091">Proto40MHz_v1.Proto40MHz_v1.update()</a>, <a class="el" href="ProtoFEB__v1_8py_source.html#l00091">ProtoFEB_v1.ProtoFEB_v1.update()</a>, <a class="el" href="Phaser_8h_source.html#l00097">Phaser.update()</a>, <a class="el" href="UsbFTInterface_8h_source.html#l00101">UsbFTInterface.update()</a>, <a class="el" href="MSOxxxx_8h_source.html#l00113">MSOxxxx.update()</a>, <a class="el" href="ICECALv3_8h_source.html#l00127">ICECALv3.update()</a>, <a class="el" href="LSDelayChipV1_8h_source.html#l00154">LSDelayChipV1.update()</a>, and <a class="el" href="A3PE_8h_source.html#l00465">A3PE.update()</a>.</p> <div class="fragment"><div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160; <span class="keyword">def </span><a class="code" href="classwrapper_1_1ModuleDictWrapper.html#a9a7a794150502f51df687831583e13b9">__init__</a>(self, cat, obj, panel, path):</div><div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160; proc.__init__(self,cat,obj,panel,path)</div><div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160; self.loadxrc()</div><div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160; self.panel.Bind(wx.EVT_TOGGLEBUTTON,self.onSoftTrig,id=xrc.XRCID(<span class="stringliteral">&quot;softtrigger&quot;</span>))</div><div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160; self.panel.Bind(wx.EVT_TOGGLEBUTTON,self.onTree,id=xrc.XRCID(<span class="stringliteral">&quot;tree&quot;</span>))</div><div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160; self.panel.Bind(wx.EVT_TOGGLEBUTTON,self.onTrend,id=xrc.XRCID(<span class="stringliteral">&quot;trend&quot;</span>))</div><div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160; self.panel.Bind(wx.EVT_TOGGLEBUTTON,self.onSample,id=xrc.XRCID(<span class="stringliteral">&quot;sample&quot;</span>))</div><div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160; self.panel.Bind(wx.EVT_SPINCTRL,self.onDeadtime,id=xrc.XRCID(<span class="stringliteral">&quot;acquisition_deadtime&quot;</span>))</div><div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160; self.panel.Bind(wx.EVT_BUTTON,self.onApply,id=xrc.XRCID(<span class="stringliteral">&quot;apply&quot;</span>))</div><div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160; self.panel.Bind(wx.EVT_SPINCTRL, self.onDepth, id=xrc.XRCID(<span class="stringliteral">&quot;depth&quot;</span>))</div><div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160; self.panel.Bind(wx.EVT_SPINCTRL, self.onNSample, id=xrc.XRCID(<span class="stringliteral">&quot;nsample&quot;</span>))</div><div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160; self.panel.Bind(wx.EVT_SPINCTRL, self.onNBins, id=xrc.XRCID(<span class="stringliteral">&quot;nbins&quot;</span>))</div><div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160; self.panel.Bind(wx.EVT_TEXT, self.onMin, id=xrc.XRCID(<span class="stringliteral">&quot;min&quot;</span>))</div><div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160; self.panel.Bind(wx.EVT_TEXT, self.onMax, id=xrc.XRCID(<span class="stringliteral">&quot;max&quot;</span>))</div><div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;</div><div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160; self.update()</div><div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160;</div><div class="ttc" id="classwrapper_1_1ModuleDictWrapper_html_a9a7a794150502f51df687831583e13b9"><div class="ttname"><a href="classwrapper_1_1ModuleDictWrapper.html#a9a7a794150502f51df687831583e13b9">wrapper.ModuleDictWrapper.__init__</a></div><div class="ttdeci">def __init__(self, dict)</div><div class="ttdef"><b>Definition:</b> <a href="wrapper_8py_source.html#l00056">wrapper.py:56</a></div></div> </div><!-- fragment --> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a id="ac7be703152b5ec0e02bc9c742d59cd50"></a> <h2 class="memtitle"><span class="permalink"><a href="#ac7be703152b5ec0e02bc9c742d59cd50">&#9670;&nbsp;</a></span>onApply()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onApply </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00026">26</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00214">Acquisition.setChannels()</a>.</p> <p class="reference">Referenced by <a class="el" href="A3PE__BitFlip_8py_source.html#l00009">A3PE_BitFlip.A3PE_BitFlip.__init__()</a>, <a class="el" href="EmulateFE_8py_source.html#l00009">EmulateFE.EmulateFE.__init__()</a>, and <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160; <span class="keyword">def </span>onApply(self,event):</div><div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160; channels=0</div><div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl0&quot;</span>).GetValue()) : channels=channels|0b1</div><div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b11111110</div><div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl1&quot;</span>).GetValue()) : channels=channels|0b10</div><div class="line"><a name="l00031"></a><span class="lineno"> 31</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b11111101</div><div class="line"><a name="l00032"></a><span class="lineno"> 32</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl2&quot;</span>).GetValue()) : channels=channels|0b100</div><div class="line"><a name="l00033"></a><span class="lineno"> 33</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b11111011</div><div class="line"><a name="l00034"></a><span class="lineno"> 34</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl3&quot;</span>).GetValue()) : channels=channels|0b1000</div><div class="line"><a name="l00035"></a><span class="lineno"> 35</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b11110111</div><div class="line"><a name="l00036"></a><span class="lineno"> 36</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl4&quot;</span>).GetValue()) : channels=channels|0b10000</div><div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b11101111</div><div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl5&quot;</span>).GetValue()) : channels=channels|0b100000</div><div class="line"><a name="l00039"></a><span class="lineno"> 39</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b11011111</div><div class="line"><a name="l00040"></a><span class="lineno"> 40</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl6&quot;</span>).GetValue()) : channels=channels|0b1000000</div><div class="line"><a name="l00041"></a><span class="lineno"> 41</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b10111111</div><div class="line"><a name="l00042"></a><span class="lineno"> 42</span>&#160; <span class="keywordflow">if</span> (self.getControl(<span class="stringliteral">&quot;chl7&quot;</span>).GetValue()) : channels=channels|0b10000000</div><div class="line"><a name="l00043"></a><span class="lineno"> 43</span>&#160; <span class="keywordflow">else</span> : channels=channels&amp;0b1111111</div><div class="line"><a name="l00044"></a><span class="lineno"> 44</span>&#160; self.obj.setChannels(channels) </div><div class="line"><a name="l00045"></a><span class="lineno"> 45</span>&#160; </div></div><!-- fragment --> </div> </div> <a id="aec0df3e0eea3f89f5c3057fac481be46"></a> <h2 class="memtitle"><span class="permalink"><a href="#aec0df3e0eea3f89f5c3057fac481be46">&#9670;&nbsp;</a></span>onDeadtime()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onDeadtime </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00064">64</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00063">Acquisition.setDeadTime()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160; <span class="keyword">def </span>onDeadtime(self,event):</div><div class="line"><a name="l00065"></a><span class="lineno"> 65</span>&#160; self.obj.setDeadTime(self.getControl(<span class="stringliteral">&quot;acquisition_deadtime&quot;</span>).GetValue())</div></div><!-- fragment --> </div> </div> <a id="abd482f75a95cdcc9b55c5adb7c046ae3"></a> <h2 class="memtitle"><span class="permalink"><a href="#abd482f75a95cdcc9b55c5adb7c046ae3">&#9670;&nbsp;</a></span>onDepth()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onDepth </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00066">66</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp_source.html#l00202">Acquisition.setDepth()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00066"></a><span class="lineno"> 66</span>&#160; <span class="keyword">def </span>onDepth(self,event):</div><div class="line"><a name="l00067"></a><span class="lineno"> 67</span>&#160; self.obj.setDepth(self.getControl(<span class="stringliteral">&quot;depth&quot;</span>).GetValue()) </div><div class="line"><a name="l00068"></a><span class="lineno"> 68</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="ad744ff797e84b6e5f785c24d44144697"></a> <h2 class="memtitle"><span class="permalink"><a href="#ad744ff797e84b6e5f785c24d44144697">&#9670;&nbsp;</a></span>onMax()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onMax </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00078">78</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00087">Acquisition.setMaxRange()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00078"></a><span class="lineno"> 78</span>&#160; <span class="keyword">def </span>onMax(self,event):</div><div class="line"><a name="l00079"></a><span class="lineno"> 79</span>&#160; self.obj.setMaxRange(float(self.getControl(<span class="stringliteral">&quot;max&quot;</span>).GetValue())) </div><div class="line"><a name="l00080"></a><span class="lineno"> 80</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="aeb3c0ebfb598e5b1c03710574826108c"></a> <h2 class="memtitle"><span class="permalink"><a href="#aeb3c0ebfb598e5b1c03710574826108c">&#9670;&nbsp;</a></span>onMin()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onMin </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00075">75</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00081">Acquisition.setMinRange()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00075"></a><span class="lineno"> 75</span>&#160; <span class="keyword">def </span>onMin(self,event):</div><div class="line"><a name="l00076"></a><span class="lineno"> 76</span>&#160; self.obj.setMinRange(float(self.getControl(<span class="stringliteral">&quot;min&quot;</span>).GetValue())) </div><div class="line"><a name="l00077"></a><span class="lineno"> 77</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="a59fd4f2c9690f7745f346281ffe4f658"></a> <h2 class="memtitle"><span class="permalink"><a href="#a59fd4f2c9690f7745f346281ffe4f658">&#9670;&nbsp;</a></span>onNBins()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onNBins </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00072">72</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00075">Acquisition.setNBins()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00072"></a><span class="lineno"> 72</span>&#160; <span class="keyword">def </span>onNBins(self,event):</div><div class="line"><a name="l00073"></a><span class="lineno"> 73</span>&#160; self.obj.setNBins(self.getControl(<span class="stringliteral">&quot;nbins&quot;</span>).GetValue()) </div><div class="line"><a name="l00074"></a><span class="lineno"> 74</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="<KEY>"></a> <h2 class="memtitle"><span class="permalink"><a href="#ae0cfd44965bc1dd829cd6d6660cdd0ee">&#9670;&nbsp;</a></span>onNSample()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onNSample </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00069">69</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00069">Acquisition.setSample()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00069"></a><span class="lineno"> 69</span>&#160; <span class="keyword">def </span>onNSample(self,event):</div><div class="line"><a name="l00070"></a><span class="lineno"> 70</span>&#160; self.obj.setSample(self.getControl(<span class="stringliteral">&quot;nsample&quot;</span>).GetValue()) </div><div class="line"><a name="l00071"></a><span class="lineno"> 71</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="a37caf6d3a03c683c5fbcc079a2d8c7ec"></a> <h2 class="memtitle"><span class="permalink"><a href="#a37caf6d3a03c683c5fbcc079a2d8c7ec">&#9670;&nbsp;</a></span>onSample()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onSample </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00061">61</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00057">Acquisition.setStoreSample()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160; <span class="keyword">def </span>onSample(self,event):</div><div class="line"><a name="l00062"></a><span class="lineno"> 62</span>&#160; self.obj.setStoreSample(self.getControl(<span class="stringliteral">&quot;sample&quot;</span>).GetValue())</div><div class="line"><a name="l00063"></a><span class="lineno"> 63</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="aa686f47e8d19e10efa43c3330fd7d19b"></a> <h2 class="memtitle"><span class="permalink"><a href="#aa686f47e8d19e10efa43c3330fd7d19b">&#9670;&nbsp;</a></span>onSoftTrig()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onSoftTrig </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00046">46</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00036">Acquisition.setTrigger()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00046"></a><span class="lineno"> 46</span>&#160; <span class="keyword">def </span>onSoftTrig(self,event):</div><div class="line"><a name="l00047"></a><span class="lineno"> 47</span>&#160; self.obj.setTrigger(self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).GetValue())</div><div class="line"><a name="l00048"></a><span class="lineno"> 48</span>&#160; <span class="keywordflow">if</span> self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).GetValue():</div><div class="line"><a name="l00049"></a><span class="lineno"> 49</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetValue(1)</div><div class="line"><a name="l00050"></a><span class="lineno"> 50</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetLabel(<span class="stringliteral">&quot;Soft. Trig.&quot;</span>)</div><div class="line"><a name="l00051"></a><span class="lineno"> 51</span>&#160; <span class="keywordflow">else</span>:</div><div class="line"><a name="l00052"></a><span class="lineno"> 52</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetValue(0)</div><div class="line"><a name="l00053"></a><span class="lineno"> 53</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetLabel(<span class="stringliteral">&quot;Ext. Trig.&quot;</span>)</div><div class="line"><a name="l00054"></a><span class="lineno"> 54</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="a9d82c40d0be476e1f4b9a8ec0f6ea29a"></a> <h2 class="memtitle"><span class="permalink"><a href="#a9d82c40d0be476e1f4b9a8ec0f6ea29a">&#9670;&nbsp;</a></span>onTree()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onTree </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00055">55</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00045">Acquisition.setStoreTree()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00055"></a><span class="lineno"> 55</span>&#160; <span class="keyword">def </span>onTree(self,event):</div><div class="line"><a name="l00056"></a><span class="lineno"> 56</span>&#160; self.obj.setStoreTree(self.getControl(<span class="stringliteral">&quot;tree&quot;</span>).GetValue())</div><div class="line"><a name="l00057"></a><span class="lineno"> 57</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="adde3ae2fd3eff1e113bd20651c8561a3"></a> <h2 class="memtitle"><span class="permalink"><a href="#adde3ae2fd3eff1e113bd20651c8561a3">&#9670;&nbsp;</a></span>onTrend()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.onTrend </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>event</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00058">58</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00051">Acquisition.setStoreTrend()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>.</p> <div class="fragment"><div class="line"><a name="l00058"></a><span class="lineno"> 58</span>&#160; <span class="keyword">def </span>onTrend(self,event):</div><div class="line"><a name="l00059"></a><span class="lineno"> 59</span>&#160; self.obj.setStoreTrend(self.getControl(<span class="stringliteral">&quot;trend&quot;</span>).GetValue())</div><div class="line"><a name="l00060"></a><span class="lineno"> 60</span>&#160;</div></div><!-- fragment --> </div> </div> <a id="abb09e973b83aec6cc4c660992b7dcc9d"></a> <h2 class="memtitle"><span class="permalink"><a href="#abb09e973b83aec6cc4c660992b7dcc9d">&#9670;&nbsp;</a></span>update()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def Acquisition.Acquisition.update </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>self</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="Acquisition_8py_source.html#l00081">81</a> of file <a class="el" href="Acquisition_8py_source.html">Acquisition.py</a>.</p> <p class="reference">References <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00034">Acquisition.channels()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00067">Acquisition.deadTime()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00031">Acquisition.depth()</a>, <a class="el" href="object_8py_source.html#l00014">object.object.getControl()</a>, <a class="el" href="ConfFrame_8py_source.html#l00043">ConfFrame.ConfFrame.getControl()</a>, <a class="el" href="GraphFrame_8py_source.html#l00044">GraphFrame.GraphFrame.getControl()</a>, <a class="el" href="CfgFrame_8py_source.html#l00064">CfgFrame.CfgFrame.getControl()</a>, <a class="el" href="AppFrame_8py_source.html#l00156">AppFrame.AppFrame.getControl()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00091">Acquisition.maxRange()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00085">Acquisition.minRange()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00079">Acquisition.nBins()</a>, <a class="el" href="object_8py_source.html#l00009">object.object.obj</a>, <a class="el" href="CfgFrame_8py_source.html#l00029">CfgFrame.CfgFrame.obj</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00073">Acquisition.sample()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00061">Acquisition.storeSample()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00049">Acquisition.storeTree()</a>, <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00055">Acquisition.storeTrend()</a>, and <a class="el" href="CatCaloProto40MHz_2inc_2proc_2Acquisition_8h_source.html#l00041">Acquisition.trigger()</a>.</p> <p class="reference">Referenced by <a class="el" href="Acquisition_8py_source.html#l00009">Acquisition.Acquisition.__init__()</a>, <a class="el" href="EmulateFE_8py_source.html#l00009">EmulateFE.EmulateFE.__init__()</a>, <a class="el" href="AppFrame_8py_source.html#l00392">AppFrame.AppFrame.deleteHardware()</a>, <a class="el" href="ConfFrame_8py_source.html#l00073">ConfFrame.ConfFrame.onChange()</a>, <a class="el" href="GraphFrame_8py_source.html#l00074">GraphFrame.GraphFrame.onChange()</a>, <a class="el" href="CfgFrame_8py_source.html#l00093">CfgFrame.CfgFrame.onChange()</a>, <a class="el" href="ConfFrame_8py_source.html#l00096">ConfFrame.ConfFrame.onEdit()</a>, <a class="el" href="AppFrame_8py_source.html#l00328">AppFrame.AppFrame.onLoad()</a>, <a class="el" href="ConfFrame_8py_source.html#l00076">ConfFrame.ConfFrame.onReLoad()</a>, <a class="el" href="GraphFrame_8py_source.html#l00081">GraphFrame.GraphFrame.onReLoad()</a>, <a class="el" href="CfgFrame_8py_source.html#l00097">CfgFrame.CfgFrame.onReLoad()</a>, and <a class="el" href="AppFrame_8py_source.html#l00406">AppFrame.AppFrame.onReLoad()</a>.</p> <div class="fragment"><div class="line"><a name="l00081"></a><span class="lineno"> 81</span>&#160; <span class="keyword">def </span>update(self):</div><div class="line"><a name="l00082"></a><span class="lineno"> 82</span>&#160; <span class="keywordflow">if</span> self.obj.trigger():</div><div class="line"><a name="l00083"></a><span class="lineno"> 83</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetValue(1)</div><div class="line"><a name="l00084"></a><span class="lineno"> 84</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetLabel(<span class="stringliteral">&quot;Soft. Trig.&quot;</span>)</div><div class="line"><a name="l00085"></a><span class="lineno"> 85</span>&#160; <span class="keywordflow">else</span>:</div><div class="line"><a name="l00086"></a><span class="lineno"> 86</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetValue(0)</div><div class="line"><a name="l00087"></a><span class="lineno"> 87</span>&#160; self.getControl(<span class="stringliteral">&quot;softtrigger&quot;</span>).SetLabel(<span class="stringliteral">&quot;Ext. Trig.&quot;</span>)</div><div class="line"><a name="l00088"></a><span class="lineno"> 88</span>&#160;</div><div class="line"><a name="l00089"></a><span class="lineno"> 89</span>&#160; channels=self.obj.channels()</div><div class="line"><a name="l00090"></a><span class="lineno"> 90</span>&#160; <span class="keywordflow">if</span> (channels&amp;1) : self.getControl(<span class="stringliteral">&quot;chl0&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl0&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00092"></a><span class="lineno"> 92</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b10) : self.getControl(<span class="stringliteral">&quot;chl1&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl1&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00094"></a><span class="lineno"> 94</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b100) : self.getControl(<span class="stringliteral">&quot;chl2&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00095"></a><span class="lineno"> 95</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl2&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00096"></a><span class="lineno"> 96</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b1000) : self.getControl(<span class="stringliteral">&quot;chl3&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00097"></a><span class="lineno"> 97</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl3&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00098"></a><span class="lineno"> 98</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b10000) : self.getControl(<span class="stringliteral">&quot;chl4&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00099"></a><span class="lineno"> 99</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl4&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b100000) : self.getControl(<span class="stringliteral">&quot;chl5&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl5&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00102"></a><span class="lineno"> 102</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b1000000) : self.getControl(<span class="stringliteral">&quot;chl6&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl6&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00104"></a><span class="lineno"> 104</span>&#160; <span class="keywordflow">if</span> (channels&amp;0b10000000) : self.getControl(<span class="stringliteral">&quot;chl7&quot;</span>).SetValue(<span class="keyword">True</span>)</div><div class="line"><a name="l00105"></a><span class="lineno"> 105</span>&#160; <span class="keywordflow">else</span> : self.getControl(<span class="stringliteral">&quot;chl7&quot;</span>).SetValue(<span class="keyword">False</span>)</div><div class="line"><a name="l00106"></a><span class="lineno"> 106</span>&#160; self.getControl(<span class="stringliteral">&quot;depth&quot;</span>).SetValue(self.obj.depth())</div><div class="line"><a name="l00107"></a><span class="lineno"> 107</span>&#160; self.getControl(<span class="stringliteral">&quot;tree&quot;</span>).SetValue(self.obj.storeTree())</div><div class="line"><a name="l00108"></a><span class="lineno"> 108</span>&#160; self.getControl(<span class="stringliteral">&quot;trend&quot;</span>).SetValue(self.obj.storeTrend())</div><div class="line"><a name="l00109"></a><span class="lineno"> 109</span>&#160; self.getControl(<span class="stringliteral">&quot;sample&quot;</span>).SetValue(self.obj.storeSample())</div><div class="line"><a name="l00110"></a><span class="lineno"> 110</span>&#160; self.getControl(<span class="stringliteral">&quot;acquisition_deadtime&quot;</span>).SetValue(self.obj.deadTime())</div><div class="line"><a name="l00111"></a><span class="lineno"> 111</span>&#160; self.getControl(<span class="stringliteral">&quot;depth&quot;</span>).SetValue(self.obj.depth())</div><div class="line"><a name="l00112"></a><span class="lineno"> 112</span>&#160; self.getControl(<span class="stringliteral">&quot;nsample&quot;</span>).SetValue(self.obj.sample())</div><div class="line"><a name="l00113"></a><span class="lineno"> 113</span>&#160; self.getControl(<span class="stringliteral">&quot;nbins&quot;</span>).SetValue(self.obj.nBins())</div><div class="line"><a name="l00114"></a><span class="lineno"> 114</span>&#160; self.getControl(<span class="stringliteral">&quot;min&quot;</span>).SetValue(str(self.obj.minRange()))</div><div class="line"><a name="l00115"></a><span class="lineno"> 115</span>&#160; self.getControl(<span class="stringliteral">&quot;max&quot;</span>).SetValue(str(self.obj.maxRange()))</div><div class="line"><a name="l00116"></a><span class="lineno"> 116</span>&#160; </div><div class="line"><a name="l00117"></a><span class="lineno"> 117</span>&#160;<span class="comment">#----------------------------------------------------------------------</span></div><div class="line"><a name="l00118"></a><span class="lineno"> 118</span>&#160;</div></div><!-- fragment --> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>/home/eleclhcb/LHCb/lbcat-cmake/CatCaloProto40MHz/python/proc/<a class="el" href="Acquisition_8py_source.html">Acquisition.py</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html> <file_sep>/doc/html/search/files_5.js var searchData= [ ['graphframe_2epy',['GraphFrame.py',['../GraphFrame_8py.html',1,'']]], ['gui_2epy',['gui.py',['../gui_8py.html',1,'']]] ]; <file_sep>/doc/html/search/variables_14.js var searchData= [ ['warningdllfast',['warningDllFast',['../structstatRegData.html#ab2c309fd8e307f289133e11a72d54dc2',1,'statRegData']]], ['width',['width',['../classprogressbar_1_1ProgressBar.html#abde0c8da19e6e6bcde845b1eb3cee279',1,'progressbar::ProgressBar']]], ['wrap',['wrap',['../classCfgFrame_1_1CfgFrame.html#ac0c4e476c6ffc2a0cd485c6c11b4178d',1,'CfgFrame::CfgFrame']]], ['wraps',['wraps',['../classConfFrame_1_1ConfFrame.html#a787b2c045a34b615b110e2cdf98c4c49',1,'ConfFrame::ConfFrame']]], ['wreserved',['wReserved',['../struct__FTDCB.html#a09597c9223026be01c71a1374715fb2f',1,'_FTDCB']]], ['wreserved1',['wReserved1',['../struct__FTDCB.html#a6775b20a593cc63edde243ed9605a028',1,'_FTDCB']]], ['writetotaltimeoutconstant',['WriteTotalTimeoutConstant',['../struct__FTTIMEOUTS.html#ac36dfafaf9522e0b041080242538d196',1,'_FTTIMEOUTS']]], ['writetotaltimeoutmultiplier',['WriteTotalTimeoutMultiplier',['../struct__FTTIMEOUTS.html#a1944986d4b6760a45db8ce1b58fa3688',1,'_FTTIMEOUTS']]] ]; <file_sep>/doc/html/search/namespaces_8.js var searchData= [ ['shell',['shell',['../namespaceshell.html',1,'']]], ['storagefifo',['StorageFifo',['../namespaceStorageFifo.html',1,'']]], ['storagefifoacquisition',['StorageFifoAcquisition',['../namespaceStorageFifoAcquisition.html',1,'']]], ['system',['System',['../namespaceSystem.html',1,'']]] ]; <file_sep>/doc/html/search/enums_2.js var searchData= [ ['bus',['Bus',['../classIOdata.html#a99aa7bed39364c4359ab8a7596bc013c',1,'IOdata']]] ]; <file_sep>/doc/html/CatSpecs_2src_2Python_8cpp.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Cat: /home/eleclhcb/LHCb/lbcat-cmake/CatSpecs/src/Python.cpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Cat </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_cbd8e9a422cfc6b49055e6fadc099056.html">lbcat-cmake</a></li><li class="navelem"><a class="el" href="dir_91b5592058d61a39bf730a71d5ec187c.html">CatSpecs</a></li><li class="navelem"><a class="el" href="dir_ae82234e6f8b2a9d9afd3a92f9ec2522.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">Python.cpp File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &lt;vector&gt;</code><br /> <code>#include &lt;list&gt;</code><br /> <code>#include &quot;<a class="el" href="Element_8h_source.html">Element.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="Interface_8h_source.html">Interface.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="SpecsInterface_8h_source.html">SpecsInterface.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="SpecsParallelBus_8h_source.html">SpecsParallelBus.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="SpecsI2c_8h_source.html">SpecsI2c.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="SpecsBus_8h_source.html">SpecsBus.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="SpecsMaster_8h_source.html">SpecsMaster.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="SpecsSlave_8h_source.html">SpecsSlave.h</a>&quot;</code><br /> <code>#include &lt;boost/python.hpp&gt;</code><br /> <code>#include &lt;boost/python/suite/indexing/vector_indexing_suite.hpp&gt;</code><br /> </div> <p><a href="CatSpecs_2src_2Python_8cpp_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:ac638738161d138927158670707ec9502"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="CatSpecs_2src_2Python_8cpp.html#ac638738161d138927158670707ec9502">BOOST_PYTHON_MODULE</a> (libCatSpecs)</td></tr> <tr class="separator:ac638738161d138927158670707ec9502"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function Documentation</h2> <a id="ac638738161d138927158670707ec9502"></a> <h2 class="memtitle"><span class="permalink"><a href="#ac638738161d138927158670707ec9502">&#9670;&nbsp;</a></span>BOOST_PYTHON_MODULE()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">BOOST_PYTHON_MODULE </td> <td>(</td> <td class="paramtype">libCatSpecs&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="CatSpecs_2src_2Python_8cpp_source.html#l00021">21</a> of file <a class="el" href="CatSpecs_2src_2Python_8cpp_source.html">Python.cpp</a>.</p> <p class="reference">References <a class="el" href="SpecsSlave_8cpp_source.html#l00175">SpecsSlave::addI2c()</a>, <a class="el" href="SpecsInterface_8cpp_source.html#l00033">SpecsInterface::address()</a>, <a class="el" href="SpecsSlave_8cpp_source.html#l00119">SpecsSlave::detect()</a>, <a class="el" href="SpecsMaster_8cpp_source.html#l00062">SpecsMaster::help()</a>, <a class="el" href="SpecsInterface_8h_source.html#l00063">SpecsInterface::help()</a>, <a class="el" href="SpecsSlave_8cpp_source.html#l00069">SpecsSlave::init()</a>, <a class="el" href="SpecsMaster_8cpp_source.html#l00069">SpecsMaster::init()</a>, <a class="el" href="SpecsInterface_8h_source.html#l00069">SpecsInterface::init()</a>, <a class="el" href="SpecsMaster_8h_source.html#l00042">SpecsMaster::masterDevID()</a>, <a class="el" href="SpecsInterface_8cpp_source.html#l00041">SpecsInterface::outputSelect()</a>, <a class="el" href="SpecsMaster_8h_source.html#l00034">SpecsMaster::pciDevID()</a>, <a class="el" href="SpecsMaster_8cpp_source.html#l00130">SpecsMaster::reset()</a>, <a class="el" href="SpecsInterface_8h_source.html#l00081">SpecsInterface::reset()</a>, <a class="el" href="SpecsSlave_8cpp_source.html#l00184">SpecsSlave::resetInternal()</a>, <a class="el" href="SpecsSlave_8cpp_source.html#l00050">SpecsSlave::setAddress()</a>, <a class="el" href="SpecsInterface_8cpp_source.html#l00029">SpecsInterface::setAddress()</a>, <a class="el" href="SpecsMaster_8h_source.html#l00038">SpecsMaster::setMasterDevID()</a>, <a class="el" href="SpecsInterface_8cpp_source.html#l00037">SpecsInterface::setOutputSelect()</a>, <a class="el" href="SpecsMaster_8h_source.html#l00030">SpecsMaster::setPciDevID()</a>, <a class="el" href="SpecsMaster_8cpp_source.html#l00149">SpecsMaster::setSpeed()</a>, <a class="el" href="SpecsInterface_8cpp_source.html#l00057">SpecsInterface::specsMaster()</a>, <a class="el" href="SpecsInterface_8cpp_source.html#l00049">SpecsInterface::specsSlave()</a>, <a class="el" href="SpecsMaster_8h_source.html#l00064">SpecsMaster::speed()</a>, <a class="el" href="SpecsMaster_8h_source.html#l00066">SpecsMaster::update()</a>, and <a class="el" href="SpecsInterface_8h_source.html#l00086">SpecsInterface::update()</a>.</p> <div class="fragment"><div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160;{</div><div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160; class_&lt;SpecsMaster, bases &lt;Element&gt; &gt;(<span class="stringliteral">&quot;SpecsMaster&quot;</span>)</div><div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160; .def(<span class="stringliteral">&quot;setPciDevID&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#a3c55e5652286c35baa41fccd240c8cb5">SpecsMaster::setPciDevID</a>)</div><div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160; .def(<span class="stringliteral">&quot;pciDevID&quot;</span>, &amp;<a class="code" href="classSpecsMaster.html#af4c88071a81c706e2a30ec7786aea707">SpecsMaster::pciDevID</a>)</div><div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160; .def(<span class="stringliteral">&quot;setMasterDevID&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#acb635bc974bb3f4528e769251c3b30a9">SpecsMaster::setMasterDevID</a>)</div><div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160; .def(<span class="stringliteral">&quot;masterDevID&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#a7bbbc2994a3e17bb91a0651eaa241842">SpecsMaster::masterDevID</a>)</div><div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160; .def(<span class="stringliteral">&quot;setSpeed&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#a25c7a250f74f4d1148240f3ab0df160b">SpecsMaster::setSpeed</a>)</div><div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160; .def(<span class="stringliteral">&quot;speed&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#ad50f852711a25ab247b6bc0603db498d">SpecsMaster::speed</a>)</div><div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160; .def(<span class="stringliteral">&quot;help&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#ad96a7533c46f01c0f67f330f6fdbf94a">SpecsMaster::help</a>)</div><div class="line"><a name="l00031"></a><span class="lineno"> 31</span>&#160; .def(<span class="stringliteral">&quot;init&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#a121457b9c5dff70caf24349c51d37cf5">SpecsMaster::init</a>)</div><div class="line"><a name="l00032"></a><span class="lineno"> 32</span>&#160; .def(<span class="stringliteral">&quot;reset&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#a0cbd251edefae5f154ec21b1b944d153">SpecsMaster::reset</a>)</div><div class="line"><a name="l00033"></a><span class="lineno"> 33</span>&#160; .def(<span class="stringliteral">&quot;update&quot;</span>,&amp;<a class="code" href="classSpecsMaster.html#abf060966e8205396e326dbbe6cfcc9e8">SpecsMaster::update</a>)</div><div class="line"><a name="l00034"></a><span class="lineno"> 34</span>&#160; ;</div><div class="line"><a name="l00035"></a><span class="lineno"> 35</span>&#160;</div><div class="line"><a name="l00036"></a><span class="lineno"> 36</span>&#160; class_&lt;SpecsInterface, bases &lt;Interface&gt; &gt;(<span class="stringliteral">&quot;SpecsInterface&quot;</span>)</div><div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160; .def(<span class="stringliteral">&quot;help&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#a24bf2b5e2da6c675ba5de3b226481a73">SpecsInterface::help</a>)</div><div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160; .def(<span class="stringliteral">&quot;init&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#a99ec05cbe0d15892afbec6feaf33c89b">SpecsInterface::init</a>)</div><div class="line"><a name="l00039"></a><span class="lineno"> 39</span>&#160; .def(<span class="stringliteral">&quot;reset&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#ade474eeef32f10c72926c9ba7d23f9a8">SpecsInterface::reset</a>)</div><div class="line"><a name="l00040"></a><span class="lineno"> 40</span>&#160; .def(<span class="stringliteral">&quot;update&quot;</span>,&amp;<a class="code" href="classSpecsInterface.html#af17ca5c8d48bea81f84e503b2994f5da">SpecsInterface::update</a>)</div><div class="line"><a name="l00041"></a><span class="lineno"> 41</span>&#160; .def(<span class="stringliteral">&quot;setAddress&quot;</span>,&amp;<a class="code" href="classSpecsInterface.html#aa92dff67cc80487ee3109b6aee2fa007">SpecsInterface::setAddress</a>)</div><div class="line"><a name="l00042"></a><span class="lineno"> 42</span>&#160; .def(<span class="stringliteral">&quot;address&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#a0fa039a15b842a5ba783ce825b9915d8">SpecsInterface::address</a>)</div><div class="line"><a name="l00043"></a><span class="lineno"> 43</span>&#160; .def(<span class="stringliteral">&quot;setOutputSelect&quot;</span>,&amp;<a class="code" href="classSpecsInterface.html#a1907d360f2bda367cfb1d39e379c6493">SpecsInterface::setOutputSelect</a>)</div><div class="line"><a name="l00044"></a><span class="lineno"> 44</span>&#160; .def(<span class="stringliteral">&quot;outputSelect&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#ab291ed03f4c2f0143e14c26ad5f648dd">SpecsInterface::outputSelect</a>)</div><div class="line"><a name="l00045"></a><span class="lineno"> 45</span>&#160; .def(<span class="stringliteral">&quot;specsMaster&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#a3d497c965fb6ec06b49a54b7901a22b2">SpecsInterface::specsMaster</a>,</div><div class="line"><a name="l00046"></a><span class="lineno"> 46</span>&#160; return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00047"></a><span class="lineno"> 47</span>&#160; .def(<span class="stringliteral">&quot;specsSlave&quot;</span>, &amp;<a class="code" href="classSpecsInterface.html#a13cf39bddfa8ba21d6e6aa78e78f0e4f">SpecsInterface::specsSlave</a></div><div class="line"><a name="l00048"></a><span class="lineno"> 48</span>&#160; ,return_value_policy&lt;reference_existing_object&gt;())</div><div class="line"><a name="l00049"></a><span class="lineno"> 49</span>&#160; ;</div><div class="line"><a name="l00050"></a><span class="lineno"> 50</span>&#160; </div><div class="line"><a name="l00051"></a><span class="lineno"> 51</span>&#160; <span class="comment">// class_&lt;SpecsParallelBus, bases &lt;SpecsInterface&gt; &gt;(&quot;SpecsParallelBus&quot;)</span></div><div class="line"><a name="l00052"></a><span class="lineno"> 52</span>&#160; <span class="comment">// ;</span></div><div class="line"><a name="l00053"></a><span class="lineno"> 53</span>&#160;</div><div class="line"><a name="l00054"></a><span class="lineno"> 54</span>&#160; <span class="comment">// class_&lt;SpecsI2c, bases &lt;SpecsInterface&gt; &gt;(&quot;SpecsI2c&quot;)</span></div><div class="line"><a name="l00055"></a><span class="lineno"> 55</span>&#160; <span class="comment">// ;</span></div><div class="line"><a name="l00056"></a><span class="lineno"> 56</span>&#160;</div><div class="line"><a name="l00057"></a><span class="lineno"> 57</span>&#160; class_&lt;SpecsSlave, bases &lt;SpecsInterface&gt; &gt;(<span class="stringliteral">&quot;SpecsSlave&quot;</span>)</div><div class="line"><a name="l00058"></a><span class="lineno"> 58</span>&#160; .def(<span class="stringliteral">&quot;setAddress&quot;</span>,&amp;<a class="code" href="classSpecsSlave.html#a1e5917c1f323cd7b4aabe4940c6baf12">SpecsSlave::setAddress</a>)</div><div class="line"><a name="l00059"></a><span class="lineno"> 59</span>&#160; .def(<span class="stringliteral">&quot;addI2c&quot;</span>,&amp;<a class="code" href="classSpecsSlave.html#af462b4d6e716ceb4bd454ad835938737">SpecsSlave::addI2c</a>)</div><div class="line"><a name="l00060"></a><span class="lineno"> 60</span>&#160; .def(<span class="stringliteral">&quot;detect&quot;</span>,&amp;<a class="code" href="classSpecsSlave.html#aa1411ca849bda04215518b08535185e2">SpecsSlave::detect</a>)</div><div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160; .def(<span class="stringliteral">&quot;init&quot;</span>,&amp;<a class="code" href="classSpecsSlave.html#ab34b5117373a334027d3a5cf33287bb6">SpecsSlave::init</a>)</div><div class="line"><a name="l00062"></a><span class="lineno"> 62</span>&#160; .def(<span class="stringliteral">&quot;resetInternal&quot;</span>,&amp;<a class="code" href="classSpecsSlave.html#aa4f2493eabe522bb6651abcd67a6a690">SpecsSlave::resetInternal</a>)</div><div class="line"><a name="l00063"></a><span class="lineno"> 63</span>&#160; ; </div><div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160;}</div><div class="ttc" id="classSpecsInterface_html_a3d497c965fb6ec06b49a54b7901a22b2"><div class="ttname"><a href="classSpecsInterface.html#a3d497c965fb6ec06b49a54b7901a22b2">SpecsInterface::specsMaster</a></div><div class="ttdeci">virtual SpecsMaster * specsMaster()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8cpp_source.html#l00057">SpecsInterface.cpp:57</a></div></div> <div class="ttc" id="classSpecsInterface_html_af17ca5c8d48bea81f84e503b2994f5da"><div class="ttname"><a href="classSpecsInterface.html#af17ca5c8d48bea81f84e503b2994f5da">SpecsInterface::update</a></div><div class="ttdeci">virtual void update()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8h_source.html#l00086">SpecsInterface.h:86</a></div></div> <div class="ttc" id="classSpecsMaster_html_a7bbbc2994a3e17bb91a0651eaa241842"><div class="ttname"><a href="classSpecsMaster.html#a7bbbc2994a3e17bb91a0651eaa241842">SpecsMaster::masterDevID</a></div><div class="ttdeci">unsigned char masterDevID()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8h_source.html#l00042">SpecsMaster.h:42</a></div></div> <div class="ttc" id="classSpecsMaster_html_a0cbd251edefae5f154ec21b1b944d153"><div class="ttname"><a href="classSpecsMaster.html#a0cbd251edefae5f154ec21b1b944d153">SpecsMaster::reset</a></div><div class="ttdeci">void reset()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8cpp_source.html#l00130">SpecsMaster.cpp:130</a></div></div> <div class="ttc" id="classSpecsInterface_html_a0fa039a15b842a5ba783ce825b9915d8"><div class="ttname"><a href="classSpecsInterface.html#a0fa039a15b842a5ba783ce825b9915d8">SpecsInterface::address</a></div><div class="ttdeci">unsigned char address()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8cpp_source.html#l00033">SpecsInterface.cpp:33</a></div></div> <div class="ttc" id="classSpecsMaster_html_ad96a7533c46f01c0f67f330f6fdbf94a"><div class="ttname"><a href="classSpecsMaster.html#ad96a7533c46f01c0f67f330f6fdbf94a">SpecsMaster::help</a></div><div class="ttdeci">void help()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8cpp_source.html#l00062">SpecsMaster.cpp:62</a></div></div> <div class="ttc" id="classSpecsSlave_html_aa4f2493eabe522bb6651abcd67a6a690"><div class="ttname"><a href="classSpecsSlave.html#aa4f2493eabe522bb6651abcd67a6a690">SpecsSlave::resetInternal</a></div><div class="ttdeci">void resetInternal()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsSlave_8cpp_source.html#l00184">SpecsSlave.cpp:184</a></div></div> <div class="ttc" id="classSpecsMaster_html_a121457b9c5dff70caf24349c51d37cf5"><div class="ttname"><a href="classSpecsMaster.html#a121457b9c5dff70caf24349c51d37cf5">SpecsMaster::init</a></div><div class="ttdeci">StatusCode init()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8cpp_source.html#l00069">SpecsMaster.cpp:69</a></div></div> <div class="ttc" id="classSpecsMaster_html_a25c7a250f74f4d1148240f3ab0df160b"><div class="ttname"><a href="classSpecsMaster.html#a25c7a250f74f4d1148240f3ab0df160b">SpecsMaster::setSpeed</a></div><div class="ttdeci">void setSpeed(unsigned char)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8cpp_source.html#l00149">SpecsMaster.cpp:149</a></div></div> <div class="ttc" id="classSpecsInterface_html_a99ec05cbe0d15892afbec6feaf33c89b"><div class="ttname"><a href="classSpecsInterface.html#a99ec05cbe0d15892afbec6feaf33c89b">SpecsInterface::init</a></div><div class="ttdeci">virtual StatusCode init()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8h_source.html#l00069">SpecsInterface.h:69</a></div></div> <div class="ttc" id="classSpecsMaster_html_ad50f852711a25ab247b6bc0603db498d"><div class="ttname"><a href="classSpecsMaster.html#ad50f852711a25ab247b6bc0603db498d">SpecsMaster::speed</a></div><div class="ttdeci">unsigned char speed()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8h_source.html#l00064">SpecsMaster.h:64</a></div></div> <div class="ttc" id="classSpecsMaster_html_acb635bc974bb3f4528e769251c3b30a9"><div class="ttname"><a href="classSpecsMaster.html#acb635bc974bb3f4528e769251c3b30a9">SpecsMaster::setMasterDevID</a></div><div class="ttdeci">void setMasterDevID(unsigned char masterDevID)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8h_source.html#l00038">SpecsMaster.h:38</a></div></div> <div class="ttc" id="classSpecsInterface_html_a13cf39bddfa8ba21d6e6aa78e78f0e4f"><div class="ttname"><a href="classSpecsInterface.html#a13cf39bddfa8ba21d6e6aa78e78f0e4f">SpecsInterface::specsSlave</a></div><div class="ttdeci">virtual SpecsSlave * specsSlave()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8cpp_source.html#l00049">SpecsInterface.cpp:49</a></div></div> <div class="ttc" id="classSpecsSlave_html_a1e5917c1f323cd7b4aabe4940c6baf12"><div class="ttname"><a href="classSpecsSlave.html#a1e5917c1f323cd7b4aabe4940c6baf12">SpecsSlave::setAddress</a></div><div class="ttdeci">void setAddress(unsigned char)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsSlave_8cpp_source.html#l00050">SpecsSlave.cpp:50</a></div></div> <div class="ttc" id="classSpecsMaster_html_a3c55e5652286c35baa41fccd240c8cb5"><div class="ttname"><a href="classSpecsMaster.html#a3c55e5652286c35baa41fccd240c8cb5">SpecsMaster::setPciDevID</a></div><div class="ttdeci">void setPciDevID(unsigned char pciDevID)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8h_source.html#l00030">SpecsMaster.h:30</a></div></div> <div class="ttc" id="classSpecsInterface_html_ade474eeef32f10c72926c9ba7d23f9a8"><div class="ttname"><a href="classSpecsInterface.html#ade474eeef32f10c72926c9ba7d23f9a8">SpecsInterface::reset</a></div><div class="ttdeci">virtual void reset()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8h_source.html#l00081">SpecsInterface.h:81</a></div></div> <div class="ttc" id="classSpecsInterface_html_ab291ed03f4c2f0143e14c26ad5f648dd"><div class="ttname"><a href="classSpecsInterface.html#ab291ed03f4c2f0143e14c26ad5f648dd">SpecsInterface::outputSelect</a></div><div class="ttdeci">unsigned char outputSelect()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8cpp_source.html#l00041">SpecsInterface.cpp:41</a></div></div> <div class="ttc" id="classSpecsSlave_html_ab34b5117373a334027d3a5cf33287bb6"><div class="ttname"><a href="classSpecsSlave.html#ab34b5117373a334027d3a5cf33287bb6">SpecsSlave::init</a></div><div class="ttdeci">StatusCode init()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsSlave_8cpp_source.html#l00069">SpecsSlave.cpp:69</a></div></div> <div class="ttc" id="classSpecsInterface_html_a24bf2b5e2da6c675ba5de3b226481a73"><div class="ttname"><a href="classSpecsInterface.html#a24bf2b5e2da6c675ba5de3b226481a73">SpecsInterface::help</a></div><div class="ttdeci">virtual void help()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8h_source.html#l00063">SpecsInterface.h:63</a></div></div> <div class="ttc" id="classSpecsSlave_html_af462b4d6e716ceb4bd454ad835938737"><div class="ttname"><a href="classSpecsSlave.html#af462b4d6e716ceb4bd454ad835938737">SpecsSlave::addI2c</a></div><div class="ttdeci">void addI2c(Hierarchy *)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsSlave_8cpp_source.html#l00175">SpecsSlave.cpp:175</a></div></div> <div class="ttc" id="classSpecsInterface_html_a1907d360f2bda367cfb1d39e379c6493"><div class="ttname"><a href="classSpecsInterface.html#a1907d360f2bda367cfb1d39e379c6493">SpecsInterface::setOutputSelect</a></div><div class="ttdeci">void setOutputSelect(unsigned char)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8cpp_source.html#l00037">SpecsInterface.cpp:37</a></div></div> <div class="ttc" id="classSpecsMaster_html_abf060966e8205396e326dbbe6cfcc9e8"><div class="ttname"><a href="classSpecsMaster.html#abf060966e8205396e326dbbe6cfcc9e8">SpecsMaster::update</a></div><div class="ttdeci">void update()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8h_source.html#l00066">SpecsMaster.h:66</a></div></div> <div class="ttc" id="classSpecsInterface_html_aa92dff67cc80487ee3109b6aee2fa007"><div class="ttname"><a href="classSpecsInterface.html#aa92dff67cc80487ee3109b6aee2fa007">SpecsInterface::setAddress</a></div><div class="ttdeci">void setAddress(unsigned char)</div><div class="ttdef"><b>Definition:</b> <a href="SpecsInterface_8cpp_source.html#l00029">SpecsInterface.cpp:29</a></div></div> <div class="ttc" id="classSpecsMaster_html_af4c88071a81c706e2a30ec7786aea707"><div class="ttname"><a href="classSpecsMaster.html#af4c88071a81c706e2a30ec7786aea707">SpecsMaster::pciDevID</a></div><div class="ttdeci">unsigned char pciDevID()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsMaster_8h_source.html#l00034">SpecsMaster.h:34</a></div></div> <div class="ttc" id="classSpecsSlave_html_aa1411ca849bda04215518b08535185e2"><div class="ttname"><a href="classSpecsSlave.html#aa1411ca849bda04215518b08535185e2">SpecsSlave::detect</a></div><div class="ttdeci">bool detect()</div><div class="ttdef"><b>Definition:</b> <a href="SpecsSlave_8cpp_source.html#l00119">SpecsSlave.cpp:119</a></div></div> </div><!-- fragment --> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html> <file_sep>/doc/html/search/enumvalues_16.js var searchData= [ ['year',['Year',['../namespaceSystem.html#a15db094516c062b412df2453b4350f1aa64832eae7c2445025f46f1edffee0dc9',1,'System']]], ['yellow',['YELLOW',['../classMsgSvc.html#af95de99b5b2e7b6754b6d94ec5526d2cafc5827dd1cc81b88110254bfbdf1add2',1,'MsgSvc::YELLOW()'],['../classServer__NI6008.html#abee9aec1c5054cd3223d4a1e5e4a7ad9a5595845a9cce91475fd2c84dfc0244a1',1,'Server_NI6008::YELLOW()']]] ]; <file_sep>/doc/html/search/files_9.js var searchData= [ ['lalusb_2eh',['LALUsb.h',['../LALUsb_8h.html',1,'']]], ['lalusbml_2eh',['LALUsbML.h',['../LALUsbML_8h.html',1,'']]], ['logframe_2epy',['LogFrame.py',['../LogFrame_8py.html',1,'']]], ['lsdelaychipv1_2ecpp',['LSDelayChipV1.cpp',['../LSDelayChipV1_8cpp.html',1,'']]], ['lsdelaychipv1_2eh',['LSDelayChipV1.h',['../LSDelayChipV1_8h.html',1,'']]] ]; <file_sep>/doc/html/search/files_0.js var searchData= [ ['a3pe_2ecpp',['A3PE.cpp',['../A3PE_8cpp.html',1,'']]], ['a3pe_2eh',['A3PE.h',['../A3PE_8h.html',1,'']]], ['a3pe_5fbitflip_2ecpp',['A3PE_BitFlip.cpp',['../A3PE__BitFlip_8cpp.html',1,'']]], ['a3pe_5fbitflip_2eh',['A3PE_BitFlip.h',['../A3PE__BitFlip_8h.html',1,'']]], ['a3pe_5fbitflip_2epy',['A3PE_BitFlip.py',['../A3PE__BitFlip_8py.html',1,'']]], ['acquisition_2ecpp',['Acquisition.cpp',['../CatCaloProto40MHz_2src_2proc_2Acquisition_8cpp.html',1,'(Global Namespace)'],['../CatCaloUpgrade_2src_2proc_2Acquisition_8cpp.html',1,'(Global Namespace)']]], ['acquisition_2eh',['Acquisition.h',['../CatCaloProto40MHz_2inc_2proc_2Acquisition_8h.html',1,'(Global Namespace)'],['../CatCaloUpgrade_2inc_2proc_2Acquisition_8h.html',1,'(Global Namespace)']]], ['acquisition_2epy',['Acquisition.py',['../Acquisition_8py.html',1,'']]], ['adcmeasurement_2ecpp',['ADCMeasurement.cpp',['../ADCMeasurement_8cpp.html',1,'']]], ['adcmeasurement_2eh',['ADCMeasurement.h',['../ADCMeasurement_8h.html',1,'']]], ['adcmeasurement_2epy',['ADCMeasurement.py',['../ADCMeasurement_8py.html',1,'']]], ['appframe_2epy',['AppFrame.py',['../AppFrame_8py.html',1,'']]], ['application_2ecpp',['Application.cpp',['../Application_8cpp.html',1,'']]], ['application_2eh',['Application.h',['../Application_8h.html',1,'']]], ['arguments_2epy',['arguments.py',['../arguments_8py.html',1,'']]], ['attrib_2ecpp',['Attrib.cpp',['../Attrib_8cpp.html',1,'']]], ['attrib_2eh',['Attrib.h',['../Attrib_8h.html',1,'']]] ]; <file_sep>/doc/html/search/enumvalues_e.js var searchData= [ ['parallel',['PARALLEL',['../classIOdata.html#a99aa7bed39364c4359ab8a7596bc013caf68d3c4cdd5e3c21501655358370b460',1,'IOdata']]], ['passive',['PASSIVE',['../classAttrib.html#a69e171d7cc6417835a5a306d3c764235a2bfb2af57b87031d190a05fe25dd92ed',1,'Attrib']]], ['priorityboost',['PriorityBoost',['../namespaceSystem.html#a71a46d52920ca8e98fc4649949be58a7a09f7fed636a453ce56c03452d1cc3169',1,'System']]], ['processbasics',['ProcessBasics',['../namespaceSystem.html#a71a46d52920ca8e98fc4649949be58a7abf68053aed010d37fad9cb7247259406',1,'System']]], ['processus',['PROCESSUS',['../classAttrib.html#a69e171d7cc6417835a5a306d3c764235a75250e29692496e73effca2c0330977f',1,'Attrib']]] ]; <file_sep>/doc/html/search/enums_3.js var searchData= [ ['infotype',['InfoType',['../namespaceSystem.html#a71a46d52920ca8e98fc4649949be58a7',1,'System']]], ['iomode',['IOMode',['../classUsbFTInterface.html#ace858cb26e5a7e13f69074fae6bf8f4a',1,'UsbFTInterface::IOMode()'],['../classUsbFTMLInterface.html#a181227ebb27454964e5b6d185432498d',1,'UsbFTMLInterface::IOMode()']]] ]; <file_sep>/doc/html/search/typedefs_12.js var searchData= [ ['word',['WORD',['../CatCaloProto40MHz_2inc_2WinTypes_8h.html#a197942eefa7db30960ae396d68339b97',1,'WORD():&#160;WinTypes.h'],['../LALUsbMLx64_2include_2WinTypes_8h.html#a197942eefa7db30960ae396d68339b97',1,'WORD():&#160;WinTypes.h'],['../LALUsbx64_2include_2WinTypes_8h.html#a197942eefa7db30960ae396d68339b97',1,'WORD():&#160;WinTypes.h']]] ]; <file_sep>/doc/html/search/namespaces_5.js var searchData= [ ['logframe',['LogFrame',['../namespaceLogFrame.html',1,'']]] ]; <file_sep>/doc/html/search/classes_3.js var searchData= [ ['data',['Data',['../classData.html',1,'']]], ['dcu',['DCU',['../classDCU.html',1,'']]], ['dll',['DLL',['../classDLL.html',1,'']]], ['dllmgr',['DLLMgr',['../classDLLMgr.html',1,'']]] ]; <file_sep>/doc/html/search/typedefs_2.js var searchData= [ ['char',['CHAR',['../CatCaloProto40MHz_2inc_2WinTypes_8h.html#aebb9e13210d88d43e32e735ada43a425',1,'CHAR():&#160;WinTypes.h'],['../LALUsbMLx64_2include_2WinTypes_8h.html#aafe4eca1b22515c54ee8c3b838003b0b',1,'CHAR():&#160;WinTypes.h'],['../LALUsbx64_2include_2WinTypes_8h.html#aebb9e13210d88d43e32e735ada43a425',1,'CHAR():&#160;WinTypes.h']]], ['commands',['commands',['../Tools_8h.html#a3691191ee3160cd3594dce0138ef60fa',1,'Tools.h']]], ['constructorelement',['ConstructorElement',['../classDLL.html#a104a81e667f9a54504c0faf095f77fc7',1,'DLL']]], ['constructorobject',['ConstructorObject',['../classDLL.html#a67b9601085a9f972b9ac6876cd11398e',1,'DLL']]], ['constructorprocessus',['ConstructorProcessus',['../classDLL.html#afbf4c85f3517962642944b80833a3607',1,'DLL']]] ]; <file_sep>/doc/html/functions_o.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Cat: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Cat </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <!-- 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 class="contents"> <div class="textblock">Here is a list of all class members with links to the classes they belong to:</div> <h3><a id="index_o"></a>- o -</h3><ul> <li>obj : <a class="el" href="classCfgFrame_1_1CfgFrame.html#a5035fd7edabdfbf2919ba8ae47b2cdf0">CfgFrame.CfgFrame</a> , <a class="el" href="classobject_1_1object.html#a82b61e7cd7e18b1f9de10fc832e5b75e">object.object</a> </li> <li>Object() : <a class="el" href="classObject.html#a40860402e64d8008fb42329df7097cdb">Object</a> </li> <li>objectList() : <a class="el" href="classDLL.html#a7d378e5aceb5b06e0fd7df6bc07f9ee5">DLL</a> </li> <li>objpath : <a class="el" href="classCfgFrame_1_1CfgFrame.html#a0a33bcbfbac5e80e5c4d0069ed9d6c91">CfgFrame.CfgFrame</a> </li> <li>objs : <a class="el" href="classAppFrame_1_1AppFrame.html#a925760a1216ddc946794ac24c7512dbd">AppFrame.AppFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#a8d6caf98ca21d47a6e1988ed20f5a688">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#a2f83944a4fed433a745817d7bf39550f">GraphFrame.GraphFrame</a> </li> <li>objtype : <a class="el" href="classCfgFrame_1_1CfgFrame.html#a224427c3ba9e154dbdf952a8150cd254">CfgFrame.CfgFrame</a> </li> <li>Offset : <a class="el" href="struct__OVERLAPPED.html#a60b84fb65a45c8383a5274b38a3f4896">_OVERLAPPED</a> </li> <li>OffsetHigh : <a class="el" href="struct__OVERLAPPED.html#a07370c1d35023959e51450a8e91c5a32">_OVERLAPPED</a> </li> <li>OK : <a class="el" href="classProcessus.html#a36278773bd98f2d5612fea40c7774821af77c64124fa175f28200166fff165ea2">Processus</a> </li> <li>ok : <a class="el" href="classwrapper_1_1wrapper.html#a81f1d31a0ccc51bfdf4d8e18eff6e437">wrapper.wrapper</a> </li> <li>oldSubtract() : <a class="el" href="classFEB__v1.html#a5b277ace76b9e511c055ad94d241dd61">FEB_v1</a> </li> <li>onAbout() : <a class="el" href="classAppFrame_1_1AppFrame.html#afeb5cc9b92feb69befb4705e8f06f3e2">AppFrame.AppFrame</a> </li> <li>onAcquisition() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ad89c2823006ad921bcb9f1587797694e">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a13917550359353e22ea8ee17d856d472">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onAcquisitionReset() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a64caf487900ebef03ab80ae633f8b59e">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a11a6f30c362bd2261ab1ea60a04b36f4">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onApply() : <a class="el" href="classAcquisition_1_1Acquisition.html#ac7be703152b5ec0e02bc9c742d59cd50">Acquisition.Acquisition</a> , <a class="el" href="classADCMeasurement_1_1CurrentMeasurement.html#a1ae6055f5228952c14ea04fe83db0cb4">ADCMeasurement.CurrentMeasurement</a> , <a class="el" href="classCurrentMeasurement_1_1CurrentMeasurement.html#a25af769de641fb09274e8ac719114476">CurrentMeasurement.CurrentMeasurement</a> , <a class="el" href="classStorageFifo_1_1StorageFifo.html#a7fa51672518fefda7102ec998203508f">StorageFifo.StorageFifo</a> , <a class="el" href="classStorageFifoAcquisition_1_1StorageFifoAcquisition.html#a42ea0140c1ae56bcd5a6f4422f49bb13">StorageFifoAcquisition.StorageFifoAcquisition</a> , <a class="el" href="classTestI2C_1_1TestI2C.html#a6737e8674436af268fa39e4d6ebea064">TestI2C.TestI2C</a> , <a class="el" href="classTestSPI_1_1TestSPI.html#afb81e2aa5e79d416c526e5a468a233c7">TestSPI.TestSPI</a> , <a class="el" href="classTestSuite_1_1TestSuite.html#a40cdae2e901d21c94a0153699f518846">TestSuite.TestSuite</a> , <a class="el" href="classTestUSB_1_1TestUSB.html#a84bfb6f16ea97644b1369e853a0da21b">TestUSB.TestUSB</a> , <a class="el" href="classUsbFTInterfaceTest_1_1UsbFTInterfaceTest.html#a8e9351da77d0c0de7215d7dfb77399ad">UsbFTInterfaceTest.UsbFTInterfaceTest</a> </li> <li>onapplyaxlatency() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a9cc766ba7ec88bfd62fcb808e9e6a7c3">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a99efa326b380d20b35277081583d7e1f">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplyaxlength() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a290b605ea5c60d320cb32d8c9cd94bc8">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a3f04a3f93366082ad95de91d1457fdf5">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplyCh() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a396ff2e86b0d9f7211b353aa5970bb19">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a1dcbf839bbd6f33c1b9de47749d98626">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplyclockdiv() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#aebb346c0ab965ffe6fa0296a29574253">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#aa0834fab61762024dcc8c89ba06bd29b">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplydelay() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a608b5e152da694d561a3e6e7d87a1b44">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a2d83c6aa70f086f76cd03957971c35a9">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplyfifodepth() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a294c942e8da1b356e4dfab6c3ac4c4bb">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#affa41d5c50897be4f575bca04c73fd2b">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplyfreq() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a5b5aed6590a3c371680928a7d678583e">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ac654ad0cdb32adcdb9a649ead2473739">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplynumber() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a93922a09cbaefc409b6018fad42e9da2">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#aadcdf53a503962a44439327ee7819de7">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onapplytrig() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a02dd49010273fa59a8964c08aafe94c8">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a5108ef129a2d3cf2415489db2b8ca0ed">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onAutoCheck() : <a class="el" href="classAppFrame_1_1AppFrame.html#a6dbf7445418dc6934ed33664684aad0e">AppFrame.AppFrame</a> </li> <li>onChange() : <a class="el" href="classCfgFrame_1_1CfgFrame.html#afa122f42de17c4e6685cec02376c11af">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#a1f922c19035b3f3a5039ee438c3d4e36">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#a46ef6b8a00bb885e5546bb7e12ef6223">GraphFrame.GraphFrame</a> </li> <li>onClose() : <a class="el" href="classAppFrame_1_1AppFrame.html#aa606dfde54071fb64f9ec980433eebdf">AppFrame.AppFrame</a> , <a class="el" href="classCfgFrame_1_1CfgFrame.html#aab5f2e7597bccc345b1c953cac83275d">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#a15511ec80bb3c5ce4a99aeb78af41c15">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#a6c2fa99d2cdb9a5a943daef19dae4e83">GraphFrame.GraphFrame</a> </li> <li>OnClose() : <a class="el" href="classgui_1_1SplashScreen.html#a2688263042c784a3d7cb7947fabe0edb">gui.SplashScreen</a> </li> <li>onClose() : <a class="el" href="classLogFrame_1_1LogFrame.html#afa3d32e2694b9e5a50279cbaf31cddba">LogFrame.LogFrame</a> </li> <li>onCloseAll() : <a class="el" href="classConfFrame_1_1ConfFrame.html#a6dea964103ba882eafed2c8735ab0a07">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#af96c612fe973abb68cd576b3e4637a31">GraphFrame.GraphFrame</a> </li> <li>onCloseConfirm() : <a class="el" href="classAppFrame_1_1AppFrame.html#a65bdce54a07b810b589c6c0096c0c78d">AppFrame.AppFrame</a> , <a class="el" href="classLogFrame_1_1LogFrame.html#a79ee5eea72f19f0a14aa047123125e1e">LogFrame.LogFrame</a> </li> <li>onCollapse() : <a class="el" href="classAppFrame_1_1AppFrame.html#a7e972158ea6bfcb0ede937b37079b4c7">AppFrame.AppFrame</a> </li> <li>OnCompareItems() : <a class="el" href="classtree_1_1MyTreeCtrl.html#a8073a87006e33820096e0b2ea305af5c">tree.MyTreeCtrl</a> </li> <li>onConfigure() : <a class="el" href="classAppFrame_1_1AppFrame.html#a42b5e1947e8d7ef528d158a15a8b081d">AppFrame.AppFrame</a> </li> <li>onDeadtime() : <a class="el" href="classAcquisition_1_1Acquisition.html#aec0df3e0eea3f89f5c3057fac481be46">Acquisition.Acquisition</a> </li> <li>onDelete() : <a class="el" href="classAppFrame_1_1AppFrame.html#a55868f842496adbc598ea5a8e03a8a03">AppFrame.AppFrame</a> </li> <li>onDepth() : <a class="el" href="classAcquisition_1_1Acquisition.html#abd482f75a95cdcc9b55c5adb7c046ae3">Acquisition.Acquisition</a> </li> <li>onEdit() : <a class="el" href="classAppFrame_1_1AppFrame.html#ae6524f7daa824546661b4824a2ae7606">AppFrame.AppFrame</a> , <a class="el" href="classCfgFrame_1_1CfgFrame.html#acf46c57cf539a9e2ed98333580508835">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#aaec4c61352cd88fbb16f230df55cc4bc">ConfFrame.ConfFrame</a> </li> <li>onenableAll() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a942b2d6f638b5966874437390f11890d">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ad7f0700c99d68f8d6fb83d413f22f6ca">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onEnableStorage() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a504affc7cfd2238410d8856a670415c2">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a014b9b6ed64493754e2c759c01564f21">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onEnter() : <a class="el" href="classAppFrame_1_1AppFrame.html#a6d45e9371b9574920fbbaff0846cb3a6">AppFrame.AppFrame</a> </li> <li>onExit() : <a class="el" href="classAppFrame_1_1AppFrame.html#a27e6061a0b781a7af1c3a813da24a0a3">AppFrame.AppFrame</a> , <a class="el" href="classLogFrame_1_1LogFrame.html#a53ce12d6947a1e35da471e5cb9d6011b">LogFrame.LogFrame</a> </li> <li>onExpand() : <a class="el" href="classAppFrame_1_1AppFrame.html#a3edd90a5c52b1be8d12d3536c800f0c9">AppFrame.AppFrame</a> </li> <li>onFifoRAZ() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#af298324a50fcbaab3114aa2b9cc52b81">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a7abdc74a7edba3a8e7c3b4bc4a616664">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onFifoReset() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ab13eebd15de4b16c9abf12d07dbda156">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#aa63a526f65c5a13a99d56c89bcb4c7f7">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onFifoWrite() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ac3a292f2caf8585e44dd45ce99c6cbf7">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a1ba3f8146393f309ab8c3b88fb9c1c6e">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onFileCheck() : <a class="el" href="classAppFrame_1_1AppFrame.html#ae832c27d48d36bf3c50a709db009c2a1">AppFrame.AppFrame</a> </li> <li>onFromAXPtrRaz() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a028a01486c07973be1c66d5b632cb58a">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a737330f2c73fda78aed98f9ce652ec45">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onFromAXRAZ() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#aee2e5a6ae16a099c14d734eaaa119979">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a4829ef01438ae9be1106a715ba8feffd">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onFromAXWrite() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ac8f631c7bc3944eadb1c8fce58f21a6d">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a9bb0cbe720de19edf05beadcd7de581d">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onGlobalReset() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a3396648f1e18f32dfc0e2f9edb38c723">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a37e3aa3b32821feafcf7f0a3f7edb930">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onHelp() : <a class="el" href="classAppFrame_1_1AppFrame.html#ab6921bc4674e0a2ff0c7d1e96e9b989c">AppFrame.AppFrame</a> </li> <li>onIconize() : <a class="el" href="classCfgFrame_1_1CfgFrame.html#adc334ba0611bcc77be88db2d9956e784">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#ade9e2d205fbe79ecc809d80233323387">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#aae122b48f5b9f830f883192c8dbab6b2">GraphFrame.GraphFrame</a> </li> <li>onIdle() : <a class="el" href="classAppFrame_1_1AppFrame.html#aeaebe92cb0672c1b2f03625d3fbc0c5d">AppFrame.AppFrame</a> , <a class="el" href="classCfgFrame_1_1CfgFrame.html#ad63704259ed900af6c1d0844c07aaea9">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#a82cf80e649080f468ad4d4de1a2d6b9a">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#aa2baa5d8bd7aed70f505e6a815a3b350">GraphFrame.GraphFrame</a> , <a class="el" href="classLogFrame_1_1LogFrame.html#af3d0abc16c93855ab9d760ff7b4c7d3e">LogFrame.LogFrame</a> </li> <li>onInit() : <a class="el" href="classAppFrame_1_1AppFrame.html#a3b9d3eb6615829d42754d51b4d82f300">AppFrame.AppFrame</a> </li> <li>OnInit() : <a class="el" href="classgui_1_1Gui.html#aadde570d41694a77449af20a9c9ecd93">gui.Gui</a> </li> <li>onLatencyReset() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a1558f7e9c28374df38db7229076f621c">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a243c7ced24005de9ce61efac1db46564">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onLoad() : <a class="el" href="classAppFrame_1_1AppFrame.html#a3a44fde65be4ba4bd5a92f4e85a29772">AppFrame.AppFrame</a> </li> <li>onLogCheck() : <a class="el" href="classAppFrame_1_1AppFrame.html#a35ce110eb56fd0867d2690889c6e5a35">AppFrame.AppFrame</a> </li> <li>onMax() : <a class="el" href="classAcquisition_1_1Acquisition.html#ad744ff797e84b6e5f785c24d44144697">Acquisition.Acquisition</a> </li> <li>onMin() : <a class="el" href="classAcquisition_1_1Acquisition.html#aeb3c0ebfb598e5b1c03710574826108c">Acquisition.Acquisition</a> </li> <li>onModeAX() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#af871ec7ec3be7b3612c48d26148eaef6">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ab6385041b979fc82b051649c486a0d13">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onModeCh() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ab8ebf6ec8e0154809593d1d3f16ec818">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#aa3700cfa620c058e18e6da7ca2e270c1">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onNBins() : <a class="el" href="classAcquisition_1_1Acquisition.html#a59fd4f2c9690f7745f346281ffe4f658">Acquisition.Acquisition</a> </li> <li>onNSample() : <a class="el" href="classAcquisition_1_1Acquisition.html#ae0cfd44965bc1dd829cd6d6660cdd0ee">Acquisition.Acquisition</a> </li> <li>onPatternRAZ() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a4ab762dab8eaef531e74cb43c8e3b399">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a7f49aab9779b34272906afef8df9f6d7">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onPatternWrite() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a1e9aa581b003b51a6f9b532d69734202">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a33df4a0a6bcdd022dd1ff67e57b6d1a4">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onPhaser0() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a3c0faa924421f2dc50101373a7d144b9">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a06d63189000c361c5ebaf7258bce3af2">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onPhaser1() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a6ce4bff9a33098821c271c6126d38e87">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a7ca754417fbe0aefab173753713c02d3">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onPhaser2() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#aa6e608163c77fab1034a0d4dd6e07ed3">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a4680b8cb99ce517798f9c0bb7b4c4d0d">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onPipeline() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#aa4039f9fab5ec8b17cda49278e146bb8">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#abee9bc133cd4291b011fc6f9746c945b">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onPlot() : <a class="el" href="classGraphFrame_1_1GraphFrame.html#a2b974345cbf4d2655e6adf1af6f18b16">GraphFrame.GraphFrame</a> </li> <li>onPrint() : <a class="el" href="classGraphFrame_1_1GraphFrame.html#a3a50f27df2c9a224ca79506117392a6f">GraphFrame.GraphFrame</a> </li> <li>onReadFifo() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#af4681815eba15ad08b366382e6724208">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a592ffa0a854e0bb583e6b19910950cc7">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onReadFromAX() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a7c2739aa6bc9aa2b84e5dd61a75f1a8a">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#acd0a2f2aaa8759c090a7d1a5ac57cbd5">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onReadPattern() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a26f7a8b8616e631dd9f193a683dce4fe">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ac3b7f23ff35c3ea4ca38782468b96d1e">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onReadToAX() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ab2d7f48fb96de1a4f7e055d222cd81a7">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ad6c45326229443ae2b784b92eab27c60">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onReadTrigger() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ad09ec450bda96a2afa0416eac0456238">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a3c2db844a47acc8436134752581902f0">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onReLoad() : <a class="el" href="classAppFrame_1_1AppFrame.html#a9ff1f12856ce454896ae7c965eef2ba3">AppFrame.AppFrame</a> , <a class="el" href="classCfgFrame_1_1CfgFrame.html#a3aaf73db16dddc96228e7d0fe3900d3a">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#a3d39db586535191174d87bb5aac11a47">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#a7b18d46fe532780e2cb335195d245a46">GraphFrame.GraphFrame</a> </li> <li>onResetFE() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a9b79ac2b7e3f3d0b3b11da1d0366656b">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ab186e2261ac831a15d991615fc09a85e">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onResetSPI() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a64103f436e81b9e0b08d94b22fd4a088">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a4ac4ca3d899a986193fe0c25b4c5d72f">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onSample() : <a class="el" href="classAcquisition_1_1Acquisition.html#a37caf6d3a03c683c5fbcc079a2d8c7ec">Acquisition.Acquisition</a> </li> <li>onSave() : <a class="el" href="classGraphFrame_1_1GraphFrame.html#ac512e14bd8704cb74de330cc75d4b106">GraphFrame.GraphFrame</a> </li> <li>onSingle() : <a class="el" href="classAppFrame_1_1AppFrame.html#ad84cc70dd583d651f0b8eded860340a8">AppFrame.AppFrame</a> </li> <li>onSoftTrig() : <a class="el" href="classAcquisition_1_1Acquisition.html#aa686f47e8d19e10efa43c3330fd7d19b">Acquisition.Acquisition</a> , <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a20a1ff18e3e5385432b6b16aafcf5cb4">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a69c60670b21c01003a31f0407a5b5b4a">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onStart() : <a class="el" href="classAppFrame_1_1AppFrame.html#a9816dbc13e8b6c54d11532e2bf53eb86">AppFrame.AppFrame</a> </li> <li>onStartSequenceAX() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a9311a8d74fcc534437715e3ce1bb5dfb">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a5ab10f7dde24277b9c9680aaf4cd804b">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onStopOnError() : <a class="el" href="classAppFrame_1_1AppFrame.html#ab6fb8d94be671fbbad0a873282e75830">AppFrame.AppFrame</a> </li> <li>onToAXPtrRaz() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a290d939bc88adbfc9dd6d3044b88aa80">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ae58fe734ecb48ef9b4baa8583598c17f">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onToAXRAZ() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a9a9f8eae643623b9aae3239fc204a9d1">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a594e7f8dc94c4e28ac5d2132238983b6">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onToAXWrite() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a0111c0c34c35554f5775a2ebfd651d2d">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ae6649390f039b699c26021eb1c1e8efb">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onTree() : <a class="el" href="classAcquisition_1_1Acquisition.html#a9d82c40d0be476e1f4b9a8ec0f6ea29a">Acquisition.Acquisition</a> </li> <li>onTrend() : <a class="el" href="classAcquisition_1_1Acquisition.html#adde3ae2fd3eff1e113bd20651c8561a3">Acquisition.Acquisition</a> </li> <li>onTrigger() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ad3639b823f80b8a837d5c6b0240dfa04">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#adf08ce25a443183367172750dac37a08">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onTriggerRAZ() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a6eaf9957a2db9ea41e3cb80625fbd8c9">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#ab38e96accffbc2a3329955acb9a00ebb">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onTriggerWrite() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#a6d03147c7dc0b36d7e7b3405c625ce1c">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#aaadfd193fc5d2893dca1b37ebab68a0f">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onunableAll() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#ad140223c54f34dfd64730ccb0140cd81">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#a694594dcf119e0a6055a54dc108f14e6">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>onUsbPhasersReset() : <a class="el" href="classProto40MHz__v1_1_1Proto40MHz__v1.html#af3de374ffd7881b77c2f8c8001a10077">Proto40MHz_v1.Proto40MHz_v1</a> , <a class="el" href="classProtoFEB__v1_1_1ProtoFEB__v1.html#af5cbe00aedb8c9addca6edae4b6fd33c">ProtoFEB_v1.ProtoFEB_v1</a> </li> <li>open() : <a class="el" href="classMSOxxxx.html#a4acff38c6f55795533c4d6b4cef6106b">MSOxxxx</a> </li> <li>openRootFile() : <a class="el" href="classProcessus.html#aacf6812880c1d1a2bf14a4a39458f443">Processus</a> </li> <li>operator=() : <a class="el" href="classStatusCode.html#af5179c5605558840cefe14e2794265de">StatusCode</a> </li> <li>options() : <a class="el" href="classApplication.html#ada7cc0e8db586985f1435aee0c79f47d">Application</a> </li> <li>Options() : <a class="el" href="classOptions.html#ab72fb640172a6109e34c8a5366563753">Options</a> </li> <li>origin() : <a class="el" href="classHierarchy.html#aee461dc930ce3871636ff87f075b1b83">Hierarchy</a> </li> <li>output : <a class="el" href="classarguments_1_1arguments.html#aa3da800e3d6dbadd4cfa43fea9ad8d78">arguments.arguments</a> </li> <li>outputSelect() : <a class="el" href="classDCU.html#a8ddffa9021a269df7a76fa42df005597">DCU</a> , <a class="el" href="classIOdata.html#aaa410b57a4607857d45ac6a7cd013307">IOdata</a> , <a class="el" href="classSpecsInterface.html#ab291ed03f4c2f0143e14c26ad5f648dd">SpecsInterface</a> </li> <li>overflow() : <a class="el" href="classHisto1D.html#a5d13018047a4ffb15e662f44a0a3f520">Histo1D</a> </li> <li>overviewText : <a class="el" href="classAppFrame_1_1AppFrame.html#a4434bdbbdbfdeacb2eaef8fa719140fc">AppFrame.AppFrame</a> , <a class="el" href="classCfgFrame_1_1CfgFrame.html#ac38a04df70f0af1945810ddecc548cd5">CfgFrame.CfgFrame</a> , <a class="el" href="classConfFrame_1_1ConfFrame.html#a65a5a2c5440955179d5b471875f1046d">ConfFrame.ConfFrame</a> , <a class="el" href="classGraphFrame_1_1GraphFrame.html#a9abea07b31cb5c6c71077bb51ed5906e">GraphFrame.GraphFrame</a> , <a class="el" href="classLogFrame_1_1LogFrame.html#a59c2a62bec07d62ee3db2615338443ae">LogFrame.LogFrame</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html> <file_sep>/doc/html/search/enumvalues_d.js var searchData= [ ['ok',['OK',['../classProcessus.html#a36278773bd98f2d5612fea40c7774821af77c64124fa175f28200166fff165ea2',1,'Processus']]] ]; <file_sep>/doc/html/search/groups_0.js var searchData= [ ['core_20package_20of_20cat',['Core Package of CAT',['../group__CATCore.html',1,'']]] ];
d831dc623bb0b4249f36b54105aa46ded8beec74
[ "JavaScript", "HTML", "Markdown" ]
75
JavaScript
joaoabcoelho/lbcat-doxy
c2083ef9774ffb80acff65f637ced10e5b30d46d
a091138d46d5be519ffef0eb7505872e995828eb
HEAD
<file_sep>"# AngularD3LinearGauge" <file_sep>(function () { 'use strict'; angular.module('myApp.directives') .directive('d3Bars', ['d3', function (d3) { return { restrict: 'EA', scope: { data: "=", label: "@", onClick: "&" }, link: function (scope, iElement, iAttrs) { var svg = d3.select(iElement[0]) .append("svg") .attr("width", "100%"); // on window resize, re-render d3 canvas window.onresize = function () { return scope.$apply(); }; scope.$watch(function () { return angular.element(window)[0].innerWidth; }, function () { return scope.render(scope.data); } ); // watch for data changes and re-render scope.$watch('data', function (newVals, oldVals) { return scope.render(newVals); }, true); // define render function scope.render = function (data) { // remove all previous items before render svg.selectAll("*").remove(); var xStart = 110; var height = 19; var width = 75; var midWidth = width + 50; var percentiles = data.map(function (percentile) { return Math.round(percentile.value / 1000); }); var target = 150; var qOne = percentiles[0]; var qTwo = percentiles[1]; var qThree = percentiles[2]; var rectangleData = [{ "rx": xStart, "ry": xStart, "height": height, "width": width, "color": "#A3C4DC" }, { "rx": xStart + width, "ry": xStart, "height": height, "width": midWidth, "color": "#5391BE" }, { "rx": xStart + width + midWidth, "ry": xStart, "height": height, "width": width, "color": "#216CA6" }]; var lineData = [{ "lx1": xStart + 1, "ly1": xStart + height, "lx2": xStart + 1, "ly2": xStart + height + 6, "color": "gray" }, { "lx1": xStart + width + 1, "ly1": xStart + height, "lx2": xStart + width + 1, "ly2": xStart + height + 6, "color": "gray" }, { "lx1": (xStart + width + 1) + (midWidth / 2), "ly1": xStart + height, "lx2": (xStart + width + 1) + (midWidth / 2), "ly2": xStart + height + 6, "color": "gray" }, { "lx1": xStart + width + 1 + midWidth, "ly1": xStart + height, "lx2": xStart + width + 1 + midWidth, "ly2": xStart + height + 6, "color": "gray" }, { "lx1": xStart + width + midWidth + width - 1, "ly1": xStart + height, "lx2": xStart + width + midWidth + width - 1, "ly2": xStart + height + 6, "color": "gray" }]; svg.attr("width", 750).attr("height", 200); var rectangles = svg.selectAll("rect") .data(rectangleData) .enter() .append("rect"); var lines = svg.selectAll("line") .data(lineData) .enter() .append("line"); var rectangleAttributes = rectangles .attr("x", function (d) { return d.rx; }) .attr("y", function (d) { return d.ry; }) .attr("height", function (d) { return d.height; }) .attr("width", function (d) { return d.width; }) .style("fill", function (d) { return d.color; }); var lineAttributes = lines .attr("x1", function (d) { return d.lx1; }) .attr("y1", function (d) { return d.ly1; }) .attr("x2", function (d) { return d.lx2; }) .attr("y2", function (d) { return d.ly2; }) .style("stroke", function (d) { return d.color; }); var text = svg.selectAll("text") .data(lineData) .enter() .append("text"); var textLabels = text .attr("x", function (d) { return d.lx2; }) .attr("y", function (d) { return d.ly2 + 15; }) .text(function (d, i) { var sal = 0; if (i == 1) { sal = qOne; } else if (i == 2) { sal = qTwo; } else if (i == 3) { sal = qThree; } return sal == 0 ? "" : ("$" + sal + "K"); }) .attr("font-family", "sans-serif") .attr("font-size", "10px") .attr("text-anchor", "middle"); var markerStart = [xStart, xStart + 10, xStart - 7, xStart - 10, xStart + 7, xStart - 10]; var marker = svg.append("polygon") .attr("points", markerStart) .attr("fill", "gray"); var idx = percentiles.indexOf(target); var mEnd = 0; var interval = 0; var diff = 0; if (idx != -1) { mEnd = lineData[idx + 1].lx1; } else if (target < qOne) { interval = width / qOne; diff = target * interval; mEnd = lineData[0].lx1 + diff; } else if (target > qOne && target < qTwo) { interval = (midWidth / 2) / (qTwo - qOne); diff = (target - qOne) * interval; mEnd = lineData[1].lx1 + diff; } else if (target > qTwo && target < qThree) { interval = (midWidth / 2) / (qThree - qTwo); diff = (target - qTwo) * interval; mEnd = lineData[2].lx1 + diff; } else if (target > qThree) { interval = 1; diff = (target - qThree) * interval; mEnd = target > (qThree + width) ? lineData[4].lx1 : lineData[3].lx1 + diff; } var markerEnd = [mEnd, xStart + 10, mEnd - 7, xStart - 10, mEnd + 7, xStart - 10]; marker.transition() .style("fill", "black") .attr("points", markerEnd) .duration(1500) .delay(200); }; } }; }]); } ());<file_sep>(function () { 'use strict'; angular.module('myApp.controllers') .controller('DemoCtrl', ['$scope', function ($scope) { $scope.title = "DemoCtrl"; $scope.d3Data = [{ "percentile": 25, "value": 79996.0 }, { "percentile": 50, "value": 97876.48 }, { "percentile": 75, "value": 120000.0 }]; $scope.d3OnClick = function (item) { alert(item.name); }; }]); } ());
ecd8b15f119fab83b4a76aa7fe1ae04309483241
[ "Markdown", "JavaScript" ]
3
Markdown
Umamaheswaran1990/AngularD3LinearGauge
e6b7d734c564582bb60e93105e69634164ce9215
08a24afd2b6c9db3c68dc608b12302a1360addf2
refs/heads/master
<repo_name>confuser/node-validity-equal-field<file_sep>/README.md # validity-equal-field [![Build Status](https://travis-ci.org/confuser/node-validity-equal-field.png?branch=master)](https://travis-ci.org/confuser/node-validity-equal-field) Validity style validator to ensure a property is equal to another schemata field ## Installation npm install validity-equal-field ## Usage Below is a simple example for usage with schemata: ```js var validity = require('validity') , schemata = require('schemata') , save = require('save') , createValidator = require('validity-equal-field') var schema = schemata( { password: { type: String , validators: { all: [ createValidator('vpassword') ] } } , vpassword: { type: String } }) ``` A custom error message can also be passed ```createValidator('vpassword', 'Passwords do not match')``` ## API ### var validate = createValidator() Create a validate function. ### validate(String:key, String:keyDisplayName, Object:object, Function:cb) This is a validity compatible function, which in turn is used by schemata for schema validation. The callback signature cb(err, errorMessage). err is an Error object if something bad happened and null otherwise. errorMessage is a String if a validation error happened and undefined otherwise. ## Licence Licensed under the [New BSD License](http://opensource.org/licenses/bsd-license.php) <file_sep>/test/validator.test.js var validate = require('../validator') , fixture = require('./fixtures') , should = require('should') describe('Field Equal Validation', function() { it('should not pass back an error when the value matches the field', function () { var validator = validate(fixture.field) validator('bar', 'bar', fixture.equal, function (err, errMessage) { should.not.exist(err) should.not.exist(errMessage) }) }) it('should pass back an error when the value fails to match the field', function () { var validator = validate(fixture.field) validator('bar', 'bar', fixture.notEqual, function (err, errMessage) { should.not.exist(err) should.exist(errMessage) errMessage.should.equal('bar must equal foo') }) }) it('should pass back custom message when the value fails to match the field', function () { var customError = 'This is a custom error message' , validator = validate(fixture.field, customError) validator('bar', 'bar', fixture.notEqual, function (err, errMessage) { should.not.exist(err) should.exist(errMessage) errMessage.should.equal(customError) }) }) }) <file_sep>/test/fixtures.js module.exports = { field: 'foo' , equal: { foo: 'test', bar: 'test' } , notEqual: { foo: 'bar', bar: 'foo' } } <file_sep>/validator.js module.exports = function (field, customMessage) { function validate(key, keyDisplayName, object, cb) { if (object[key] !== object[field]) { var message = customMessage || keyDisplayName + ' must equal ' + field return cb(null, message) } return cb(null, undefined) } return validate }
f444c378659a8239d2c8c0a88da15e2e4a9dd8cd
[ "Markdown", "JavaScript" ]
4
Markdown
confuser/node-validity-equal-field
92104509cf71b9babc4d242142e23b79f8244725
351e35b05b4afd5f41bf3d7b5f09c44f4da742e9
refs/heads/master
<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { User } from '../model/user'; const httpoptions = { headers: new HttpHeaders({'Content-type':'application/json'}) } @Injectable({ providedIn: 'root' }) export class AuthService { constructor(private http:HttpClient,private _router: Router) { } // apiUrl = 'http://192.168.1.103:8080/api'; apiUrl = 'http://localhost:8080/api'; loginUser(email:any,password:any):Observable<User[]>{ return this.http.post<User[]>(this.apiUrl+'/login',{email, password}, httpoptions) } signup(data:any):Observable<User[]>{ return this.http.post<User[]>(this.apiUrl+'/register', data) } logoutUser() { localStorage.removeItem('token') this._router.navigate(['/index']) } getToken() { return localStorage.getItem('token') } loggedIn() { return !!localStorage.getItem('token') } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr'; import { AuthService } from 'src/app/service/auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: any; signupForm: any; login: any; uploadedFiles: any; constructor(private _auth: AuthService,private fb:FormBuilder, private _router:Router,private toastr: ToastrService) { this.loginForm = this.fb.group({ emailField:['',[Validators.email,Validators.required]], password:['',[Validators.minLength(4),Validators.required]] }) this.signupForm = this.fb.group({ firstName:['',[Validators.required]], lastName:['',[Validators.required]], role:['',[Validators.required]], password:['',[Validators.required,Validators.minLength(4)]], email:['',[Validators.required,Validators.email]], phone:['',[Validators.required,Validators.minLength(10),Validators.pattern('[0-9]{10}')]], address:['',[Validators.required]], profile:[null], city:['',[Validators.required]], state:['',[Validators.required]], country:['',[Validators.required]], zip:['',[Validators.required]], }) } ngOnInit(): void { } onSubmitlogin(){ let email = this.loginForm.get('emailField').value; let password = this.loginForm.get('password').value; this._auth.loginUser(email,password).subscribe(res=>{ this.login = res; // console.log(res); // console.log(this.login); if (this.login.match) { localStorage.setItem('token', this.login.accesstoken); this._router.navigate(['/index']); } else { this.toastr.info('User Not found<br>OR<br>email and password invalid','Message'); } }, err => { console.log(err); } ) } fileChange(event:any) { if (event.target.files.length>0) { this.signupForm.get('profile').value = event.target.files[0]; } } onSignupSubmit(){ let formData:any = new FormData(); formData.append('firstName',this.signupForm.get('firstName').value); formData.append('lastName',this.signupForm.get('lastName').value); formData.append('role',this.signupForm.get('role').value); formData.append('password',this.signupForm.get('password').value); formData.append('email',this.signupForm.get('email').value); formData.append('phone',this.signupForm.get('phone').value); formData.append('address',this.signupForm.get('address').value); formData.append('profile',this.signupForm.get('profile').value); formData.append('city',this.signupForm.get('city').value); formData.append('state',this.signupForm.get('state').value); formData.append('country',this.signupForm.get('country').value); formData.append('zip',this.signupForm.get('zip').value); this._auth.signup(formData) .subscribe( res => { this.toastr.success('Registration Successfully','Message'); this.signupForm.reset(); this._router.navigate(['/']); }, err => console.log(err) ) } } <file_sep>import { Routes, RouterModule } from '@angular/router'; import { CartComponent } from '../components/cart/cart.component'; import { CategoryComponent } from '../components/category/category.component'; import { CheckoutComponent } from '../components/checkout/checkout.component'; import { Error404Component } from '../components/error404/error404.component'; import { IndexComponent } from '../components/index/index.component'; import { LoginComponent } from '../components/login/login.component'; import { ProductDetailComponent } from '../components/product-detail/product-detail.component'; import { AuthGuard } from '../guard/auth.guard'; export const UserRouting:Routes=[ { path:'', redirectTo:'index', pathMatch:'full' }, { path:'index', component:IndexComponent }, { path:'login', component:LoginComponent }, { path:'category', component:CategoryComponent }, { path:'checkout', component:CheckoutComponent, canActivate: [AuthGuard] }, { path:'cart', component:CartComponent, canActivate: [AuthGuard] }, { path:'productdetail', component:ProductDetailComponent }, { path:'**', component:Error404Component } ];<file_sep>export class User { firstName:string | undefined; lastName:string | undefined; role:string | undefined; phone:number | undefined; email: string | undefined; password:string | undefined; address:string | undefined; city:string | undefined; state:string | undefined; country:string | undefined; profile:File | undefined; } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { IndexComponent } from './components/index/index.component'; import { LoginComponent } from './components/login/login.component'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { UserRouting } from './router/user-routing'; import { CategoryComponent } from './components/category/category.component'; import { CheckoutComponent } from './components/checkout/checkout.component'; import { CartComponent } from './components/cart/cart.component'; import { ProductDetailComponent } from './components/product-detail/product-detail.component'; import { Error404Component } from './components/error404/error404.component'; import { HttpClientModule } from "@angular/common/http"; import { AuthService } from './service/auth.service'; import { AuthGuard } from './guard/auth.guard'; import { ToastrModule } from 'ngx-toastr'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ declarations: [ AppComponent, IndexComponent, LoginComponent, CategoryComponent, CheckoutComponent, CartComponent, ProductDetailComponent, Error404Component ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule, RouterModule.forRoot(UserRouting), HttpClientModule, BrowserAnimationsModule, ToastrModule.forRoot({ preventDuplicates:true, progressBar:true, enableHtml:true, progressAnimation:"decreasing" }), ], providers: [AuthService,AuthGuard], bootstrap: [AppComponent] }) export class AppModule { }
c1f60c7790ba9e70200e7868fe5fb6aa36d74667
[ "TypeScript" ]
5
TypeScript
DheeruDheeru/angularFrontend
9fec6077765dff5b8859b2e00864dab58e763ddb
d359b6f548dbdc07936e9cd94db9ede8a6cd825e
refs/heads/master
<repo_name>chusizquierdo/formulariosReact<file_sep>/src/App.js import Formulario1 from "./components/Formulario1"; import Formulario2 from "./components/Formulario2"; function App() { return ( <div> {/* <Formulario1 /> */} <Formulario2 /> </div> ); } export default App;
13e12433686fde41eed06c7fc5d0509a757a5451
[ "JavaScript" ]
1
JavaScript
chusizquierdo/formulariosReact
3977c970bf4cd5bcf68d861a8b59c2d76c1b5aaf
fa85836acae435b410a7cceb54d3fbc7e7d58be9
refs/heads/master
<file_sep>Perform a Logistics Regression Analysis to determine features affecting Customers Churn and predict churn.<file_sep>#Churn Assignment library(dplyr) library(caret) install.packages("e1071") library(e1071) #DATA UNDERSTANDING AND PREPARATION #import and understand dataset df = read.csv("C:/Users/<NAME>/Documents/Stat P1/Stat P1/Telco-Customer-Churn.csv") head(df) ls(df) #check for NA and replace withs means if its exist sapply(df, function(x) sum(is.na(x))) df$TotalCharges[is.na(df$TotalCharges)] = mean(df$TotalCharges, na.rm=TRUE) table(is.na(df)) #dataset preparation head(df) str(df) dfx = select(df, -customerID) summary(dfx) dfx$Churn = as.factor(dfx$Churn) unique(df$SeniorCitizen) dfx$SeniorCitizen = as.factor(dfx$SeniorCitizen) str(dfx) unique(Churn) #MODELLING #partition to train and test trainindex = createDataPartition(dfx$Churn, p=0.7, list=FALSE) dfxTrain= dfx[trainindex, ] dfxTest = dfx[-trainindex, ] #train and understand model logmod = glm(Churn~., data=dfxTrain, family ="binomial") summary(logmod) #make predictions on trained model pred = predict(logmod, newdata=dfxTest, type="response" ) dfxTest$predictions = pred View(dfxTest) #EVALUATION dfxTest$predictions = ifelse(pred>0.5, 1, 0) str(dfxTest$predictions) dfxTest$predictions = as.factor(dfxTest$predictions) confusionMatrix(dfxTest$Churn, dfxTest$predictions) #SIGNIFICANCE OF MODEL: #On a C.I of 95% and Accuracy of 80.12%, #1. Based on its p-values, the following factors have; #No effect on Customer Churn: Gender, SeniorCitizen, Partner, Dependents, phoneservice, multiplelines,OnlineSecurity, internetService, MonthlyCharges #"OnlineBackup" "DeviceProtection" "TechSupport", "StreamingTV" "StreamingMovies" #little: MultipleLinesYes, InternetServiceFiber optic, InternetServiceNo, #Somewhat: PaperlessBillingYes #Strong: #Tenure, ContractOneYear, ContractTwoYear, PaymentMethodElectronic check, TotalCharges
e17c4e0d11c5b04cffa5522f2b70ea0a76a899ee
[ "Text", "R" ]
2
Text
Tobsam237/Customer_Churn
1fff97d7e9abbd7618244b79a0b0916579298113
1d6e09b82f3cf2c94cdeb13f487236711e3dc772
refs/heads/master
<file_sep>namespace SOAPClient.Manually { using System.ServiceModel; using System.ServiceModel.Channels; using System.Threading.Tasks; public class CalculatorServiceClient : ClientBase<ICalculatorService> { public CalculatorServiceClient(Binding binding, EndpointAddress address) : base(binding, address) { } public async Task<int> AddAsync(int x, int y) => await Channel.AddAsync(x, y); public async Task<int> SubtractAsync(int x, int y) => await Channel.SubtractAsync(x, y); public async Task<int> MultiplyAsync(int x, int y) => await Channel.MultiplyAsync(x, y); public async Task<int> DivideAsync(int x, int y) => await Channel.DivideAsync(x, y); } } <file_sep>namespace SOAPClient.Manually { using System.ServiceModel; using System.Threading.Tasks; [ServiceContract] public interface ICalculatorService { [OperationContract(Action = "http://tempuri.org/Add", ReplyAction = "*")] Task<int> AddAsync(int intA, int intB); [OperationContract(Action = "http://tempuri.org/Subtract", ReplyAction = "*")] Task<int> SubtractAsync(int intA, int intB); [OperationContract(Action = "http://tempuri.org/Multiply", ReplyAction = "*")] Task<int> MultiplyAsync(int intA, int intB); [OperationContract(Action = "http://tempuri.org/Divide", ReplyAction = "*")] Task<int> DivideAsync(int intA, int intB); } } <file_sep>namespace SOAPClient { using System; using System.Threading.Tasks; using CalculatorClient; class Program { static async Task Main(string[] args) { var x = 14; var y = 7; var client = new CalculatorSoapClient(CalculatorSoapClient.EndpointConfiguration.CalculatorSoap12); Console.WriteLine($"{x} + {y} == {await client.AddAsync(x, y)}"); Console.WriteLine($"{x} - {y} == {await client.SubtractAsync(x, y)}"); Console.WriteLine($"{x} * {y} == {await client.MultiplyAsync(x, y)}"); Console.WriteLine($"{x} / {y} == {await client.DivideAsync(x, y)}"); await client.CloseAsync(); Console.ReadKey(); } } } <file_sep>namespace SOAPClient.Manually { using System; using System.ServiceModel; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { var x = 14; var y = 7; var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress(new Uri("http://www.dneonline.com/calculator.asmx")); var client = new CalculatorServiceClient(binding, endpoint); Console.WriteLine($"{x} + {y} == {await client.AddAsync(x, y)}"); Console.WriteLine($"{x} - {y} == {await client.SubtractAsync(x, y)}"); Console.WriteLine($"{x} * {y} == {await client.MultiplyAsync(x, y)}"); Console.WriteLine($"{x} / {y} == {await client.DivideAsync(x, y)}"); client.Close(); Console.ReadKey(); } } } //http://www.dneonline.com/calculator.asmx
3af2a6dc6092c09ae7f37d3814a9696dbe3432a0
[ "C#" ]
4
C#
mwalczynski-upskill/SOAPConsumerExample
1ca6852e749e0705e07db0addf117a17d2e736b8
5a48518a0e74f8ed05bde357206f7df00a1275aa
refs/heads/master
<repo_name>bridgecrew-perf7/mkdocs-deploy-tencentcos<file_sep>/ac.sh #!/bin/bash set -e function print_info() { echo -e "\e[36mINFO: ${1}\e[m" } if [ -n "${CONFIG_FILE}" ]; then print_info "Setting custom path for mkdocs config yml" export CONFIG_FILE="${GITHUB_WORKSPACE}/${CONFIG_FILE}" else export CONFIG_FILE="${GITHUB_WORKSPACE}/mkdocs.yml" fi REQUIREMENTS="${GITHUB_WORKSPACE}/requirements.txt" if [ -f "${REQUIREMENTS}" ]; then pip install -r "${REQUIREMENTS}" fi mkdocs build --config-file "${CONFIG_FILE}" if [ -z "$SECRET_ID" ]; then print_info '::error::Required SecretId parameter' exit 1 fi if [ -z "$SECRET_KEY" ]; then print_info '::error::Required SecretKey parameter' exit 1 fi if [ -z "$BUCKET" ]; then print_info '::error::Required Bucket parameter' exit 1 fi if [ -z "$REGION" ]; then print_info '::error::Required Region parameter' exit 1 fi coscmd config -a "$SECRET_ID" -s "$SECRET_KEY" -b "$BUCKET" -r "$REGION" -m 30 print_info "Running command: coscmd upload -r ${GITHUB_WORKSPACE}/site/ /" coscmd upload -r "${GITHUB_WORKSPACE}"/site/ / print_info "Commands ran successfully"<file_sep>/Dockerfile FROM python:3.7-slim LABEL maintainer="aschenmaker, <EMAIL>" ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade --no-cache-dir coscmd mkdocs mkdocs-material COPY ac.sh /ac.sh RUN chmod +x /ac.sh ENTRYPOINT ["/ac.sh"]<file_sep>/README.md # GitHub Action to deploy MkDocs site to Tencent Cos ![GitHub Badge](https://github.com/aschenmaker/mkdocs-deploy-tencentcos/actions/workflows/check.yml/badge.svg) 部署Mkdocs到腾讯云COS静态网站 ## Intro 推送触发,GitHub Action进行构建,并自动推送到腾讯云COS。通过设置COS域名,实现静态网站访问。 ## Example 在对应的 mkdocs git仓库中创建`.github/workflows/deploy.yml`, ```yml name: Deploy to tencent osss on: push: branches: - master jobs: build: name: Deploy docs runs-on: ubuntu-latest steps: - name: Checkout main uses: actions/checkout@v2 - name: Deploy to tencent osss uses: aschenmaker/mkdocs-deploy-tencentcos@master env: CONFIG_FILE: mkdocs.yml SECRET_ID: ${{ secrets.SECRET_ID }} SECRET_KEY: ${{ secrets.SECRET_KEY }} BUCKET: ${{ secrets.BUCKET }} REGION: ap-nanjing ``` `SECRET_ID`,`SECRET_KEY`,`BUCKET`需要设置在仓库`Settings`-`Secret`中进行配置 | 参数 | 说明 | 是否必须 | | ----------- | --------------------- | -------- | | CONFIG_FILE | 配置文件位置 | 否 | | SECRET_ID | API密钥,腾讯云中获取 | 是 | | SECRET_KEY | API-key,腾讯云中获取 | 是 | | BUCKET | 存储桶名称 | 是 | | REGION | 存储桶位置 | 是 |
1448b5012ed0d1290b15905c74bd116b52c90104
[ "Markdown", "Dockerfile", "Shell" ]
3
Shell
bridgecrew-perf7/mkdocs-deploy-tencentcos
e3002d0fb49b8c2f161b54c67f0b77f4575da134
991edb5a391cc3be8bf5dafeb815169938f3f9fc
refs/heads/main
<file_sep> Install rapidxml library before using: - go to Resources directory - write on terminal : sudo apt install librapidxml-dev -y For Compile: in Src directory - g++ -Wall -g -std=c++17 -o a.out State.cpp ExampleStates.cpp Machine.cpp RunTest.cpp Event.cpp TerminalEventListener.cpp Xml file writing instractions: <LegalEvents> - The evetn known by the machine <Event description = > Add the event name <Sequence sequence_Name> - Add new sequence <Event description> - list of events needs to invoke the sequence For Example : use machine_state_test.xml file State Machine: InitialMachine - state that ivoked when machine is ready to recieve events from the user WaitingForEvent - invoked when one or more of the sequences recieved its wanted event SequenceEnded - invoked when sequence event is complete prints sequence_name in terminal Ignore - initialize the sequences when no sequence event recieved that matches the wanted sequences and invoked when inknown sequence recieved Each state is decribed in StateInterface.h Special Events: Any - recieves any event End - exits the event listener Bin directory: includes .out files Resources directory: icludes external resources used by the programm Bin directory: includes all .h .hpp .cpp files ╔══╗─╔╗──────╔═══╗ ╚╣╠╝─║║──────║╔═╗║ ─║║╔═╝╠══╦═╗─║║─║╠═╗ ─║║║╔╗║╔╗║╔╗╗║║─║║╔╝ ╔╣╠╣╚╝║╔╗║║║║║╚═╝║║ ╚══╩══╩╝╚╩╝╚╝╚═══╩╝ <file_sep>#include <string> #include "Event.h" Event::Event(const Event& src){ m_eventDescription = src.m_eventDescription; }; void Event::SetValues(std::string& value) { m_eventDescription = value; } Event& Event::operator=(const Event& src) { m_eventDescription = src.m_eventDescription; return *this; }<file_sep>#pragma once #include <list> #include <iostream> #include <vector> #include "StateInterface.h" #include "State.h" class InitialMachine : public StateInterface { public: virtual void Enter(State* state); virtual void Invoke(State* state); virtual void Exit(State* state); static StateInterface& getInstance(); // for singleton implementation virtual ~InitialMachine(){}; InitialMachine(const InitialMachine& src) = delete; InitialMachine& operator=(const InitialMachine& src) = delete; virtual int GetUniqueId(); private: InitialMachine();// private ctor for singleton implementation int m_uniqueId = 1; };//InitialMachine class WaitingForEvent : public StateInterface { public: virtual void Enter(State* state); virtual void Invoke(State* state); virtual void Exit(State* state); static StateInterface& getInstance(); // for singleton implementation virtual ~WaitingForEvent(){}; virtual int GetUniqueId(); private: WaitingForEvent();// private ctor for singleton implementation WaitingForEvent(const WaitingForEvent& src) = delete; WaitingForEvent& operator=(const WaitingForEvent& src) = delete; int m_uniqueId = 2; };//WaitingForEvent class SequenceEnded : public StateInterface { public: virtual void Enter(State* state); virtual void Invoke(State* state); virtual void Exit(State* state); static StateInterface& getInstance(); // for singleton implementation virtual ~SequenceEnded() {}; virtual int GetUniqueId(); private: SequenceEnded();// private ctor for singleton implementation SequenceEnded(const SequenceEnded& src); SequenceEnded& operator=(const SequenceEnded& src) = delete; int m_uniqueId = 3; };//SequenceEnded class Ignore : public StateInterface { public: virtual void Enter(State* state); virtual void Invoke(State* state); virtual void Exit(State* state); static StateInterface& getInstance(); // for singleton implementation virtual ~Ignore() = default; virtual int GetUniqueId(); private: Ignore();// private ctor for singleton implementation Ignore(const Ignore& src); Ignore& operator=(const Ignore& src) = delete; static Ignore* singleton; int m_uniqueId = 4; };//Ignore<file_sep>#pragma once #include <iostream> #include <vector> #include <string> using std::string; class Event { public: explicit Event() = default; Event(const Event& src); Event& operator=(const Event& src); ~Event() noexcept = default; void SetValues(string& value); string m_eventDescription; };//Even <file_sep>#pragma once #include "Machine.h" class EventListenerIntrerface { public: explicit EventListenerIntrerface() = default; EventListenerIntrerface(const EventListenerIntrerface& src) = delete; EventListenerIntrerface& operator = (const EventListenerIntrerface& src) = delete; inline void Start() { m_listen = true; } inline void Stop() { m_listen = false; } virtual void ListenToEvent(Machine& machine) = 0; protected: bool m_listen; };//EventListenerInterface<file_sep>#pragma once #include <map> #include "StateInterface.h" #include "Event.h" using std::vector; using std::map; using std::string; class StateInterface;//forword decleration to prevent circular dependencies class State { public: State() = default; inline StateInterface* getCurrentState() const { return currentState; } ~State() noexcept = default; void Invoke(); void SetState(StateInterface& nextState); StateInterface& ValidateState(Event eventDescription); string GetLastSequence(); void SetEventSequences(map<string, vector<string>> eventSequences); inline vector<int>& GetEventRunner() { return m_eventRunners; } inline vector<string>& GetLegalEvents() { return m_legalEvents; } private: StateInterface* currentState; map<string, vector<string>> m_eventSequences; vector<int> m_eventRunners; vector<string> m_legalEvents; StateInterface* InnerValidateState(const std::vector<std::string>* itMap, size_t itRunner, std::string event); };//State <file_sep>#include <iostream> #include <fstream> #include <vector> #include <list> #include <map> #include <cstring> #include <iterator> #include <filesystem> #include "../Resources/rapidxml/rapidxml.hpp" #include "State.h" #include "Machine.h" #include "ExampleStates.hpp" using std::string; using std::vector; using std::map; using std::cout; using std::endl; using std::ifstream; using std::iterator; using std::istreambuf_iterator; using std::cin; using namespace rapidxml; map<string, vector<string>> Machine::ReadMachineStateFromXML () { xml_document<> doc; xml_node<> * root_node = NULL; map<string, vector<string>> machineStateMap; string fileLocation; bool isFileValid = false; while(!isFileValid) { cout<<"\nPlease Enter Valid .xml file: "; cin>>fileLocation; cout<<endl; if(std::filesystem::exists(fileLocation)) { isFileValid = true; } else { cout<<"\nError: File Location Is Invalid"<<endl; } } cout << "\nParsing Sequences from XML"; ifstream file(fileLocation); vector<char> buffer ((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); buffer.push_back('\0'); doc.parse<0>(&buffer[0]); root_node = doc.first_node("MachineState"); xml_node<>* legalEvent = root_node -> first_node("LegalEvents"); cout<<"\nLegal Events: "<<endl; for(xml_node<> *itr_activity_node = legalEvent->first_node("Event"); itr_activity_node; itr_activity_node = itr_activity_node->next_sibling()) { string activity_description = itr_activity_node->first_attribute("desctiption")->value(); currentState.GetLegalEvents().push_back(activity_description); cout<<"Desctiption = "<<activity_description<<endl; } for(xml_node<> * itrNode = root_node -> first_node("Sequence"); itrNode; itrNode = itrNode->next_sibling()) { vector<string> activity_vector; string state = itrNode->first_attribute("sequence_name")->value(); cout<< "\nSequence = "<< state; cout<<endl; for(xml_node<> *itr_activity_node = itrNode->first_node("Event"); itr_activity_node; itr_activity_node = itr_activity_node->next_sibling()) { string activity_description = itr_activity_node->first_attribute("desctiption")->value(); activity_vector.push_back(activity_description); cout<<"Desctiption = "<<activity_description<<endl; } machineStateMap[state] = activity_vector; currentState.GetEventRunner().push_back(-1); cout<<endl; } return machineStateMap; } void Machine::RegisterEvent(Event eventDescription) { StateInterface* state = &currentState.ValidateState(eventDescription); SetState(*state); currentState.Invoke(); } Machine::Machine() : currentState() { currentState.SetEventSequences(ReadMachineStateFromXML()); SetState(InitialMachine::getInstance()); } void Machine::SetState(StateInterface& nextState) { currentState.SetState(nextState); }<file_sep>#pragma once #include "EventListenerInterface.h" class TerminalEventListener : public EventListenerIntrerface { public: TerminalEventListener() = default; TerminalEventListener(const TerminalEventListener& src) = delete; TerminalEventListener& operator=(TerminalEventListener& src) = delete; ~TerminalEventListener() noexcept = default; virtual void ListenToEvent(Machine& machine); protected: bool m_listen = false; };//TerminalEventListener<file_sep>#pragma once class State;//forword decleration to prevent circular dependencies class StateInterface { public: virtual void Enter(State* light) = 0; virtual void Invoke(State* light) = 0; virtual void Exit(State* light) = 0; virtual int GetUniqueId() = 0; private: int m_uniqueId = 0; };//StateInterface <file_sep>#include <iostream> #include "ExampleStates.hpp" #include "State.h" #include "Utils.hpp" using std::string; using std::cout; using std::endl; static WaitingForEvent* singletonWaitingForEvent = nullptr; static SequenceEnded* singletonSequenceEnded = nullptr; static Ignore* singletonIgnore = nullptr; static InitialMachine* singletonInitialMachine = nullptr; static int uniqeIdGenerator = 0; InitialMachine::InitialMachine() { m_uniqueId = uniqeIdGenerator++; } int InitialMachine::GetUniqueId() { return m_uniqueId; } StateInterface& InitialMachine::getInstance() { static InitialMachine singleton; if(singletonInitialMachine == nullptr) { singletonInitialMachine = new InitialMachine(); } return singleton; } void InitialMachine::Invoke(State* state) { cout<<"\nInitialMachine Is Invoked"<<endl; } void InitialMachine::Enter(State* state) { cout<<"\nMachine Entered InitialMachine State"<<endl; } void InitialMachine::Exit(State* state) { cout<<"\nMachine Exit InitialMachine State"<<endl; } WaitingForEvent::WaitingForEvent() { m_uniqueId = uniqeIdGenerator++; } StateInterface& WaitingForEvent::getInstance() { if(singletonWaitingForEvent == 0) { singletonWaitingForEvent = new WaitingForEvent(); } return *singletonWaitingForEvent; } int WaitingForEvent::GetUniqueId() { return m_uniqueId; } void WaitingForEvent::Invoke(State* state) { cout<<"\nWaitingForEvent Is Invoked"<<endl; } void WaitingForEvent::Enter(State* state) { cout<<"\nMachine Entered WaitingForEvent State"<<endl; } void WaitingForEvent::Exit(State* state) { cout<<"\nMachine Exit WaitingForEvent State"<<endl; } SequenceEnded::SequenceEnded() { m_uniqueId = uniqeIdGenerator++; } StateInterface& SequenceEnded::getInstance() { if(singletonSequenceEnded == 0) { singletonSequenceEnded = new SequenceEnded(); } return *singletonSequenceEnded; } int SequenceEnded::GetUniqueId() { return m_uniqueId; } void SequenceEnded::Invoke(State* state) { cout<<"\nSequnce Ended: "<<state->GetLastSequence()<<endl; } void SequenceEnded::Enter(State* state) { cout<<"\nMachine Entered SequenceEnded State"<<endl; } void SequenceEnded::Exit(State* state) { cout<<"\nMachine Exit SequenceEnded State"<<endl; } StateInterface& Ignore::getInstance() { if(singletonIgnore == 0) { singletonIgnore = new Ignore(); } return *singletonIgnore; } Ignore::Ignore() { m_uniqueId = uniqeIdGenerator++; } int Ignore::GetUniqueId() { return m_uniqueId; } void Ignore::Enter(State* state) { cout<<"\nMachine Entered Ignore State"<<endl; } void Ignore::Exit(State* state) { cout<<"\nMachine Exit Ignore State"<<endl; } void Ignore::Invoke(State* state) { cout<<"State Ignore Is Invoked"<<endl; }<file_sep>#include <iostream> #include <map> #include <iterator> #include <algorithm> #include <utility> #include "State.h" #include "ExampleStates.hpp" using std::string; using std::vector; using std::find; using std::map; void State::SetState(StateInterface& nextState) { if(currentState != nullptr) { currentState->Exit(this); // do stuff before we change state } currentState = &nextState; // change state currentState->Enter(this); // do stuff after we change state } void State::Invoke() { currentState->Invoke(this); } StateInterface& State::ValidateState(Event eventDescription) { string event = eventDescription.m_eventDescription; size_t i = 0; StateInterface* retState = &InitialMachine::getInstance(); for(auto itMap = m_eventSequences.begin(); itMap != m_eventSequences.end(); itMap++) { StateInterface* tempRetState = &Ignore::getInstance(); tempRetState = InnerValidateState(&itMap->second, i, event); if(SequenceEnded::getInstance().GetUniqueId() == tempRetState->GetUniqueId()) { m_eventRunners[i] = -2; retState = tempRetState; } else if(WaitingForEvent::getInstance().GetUniqueId() == tempRetState->GetUniqueId()) { if(retState->GetUniqueId() != SequenceEnded::getInstance().GetUniqueId()) retState = tempRetState; } else { m_eventRunners[i] = -1; if(retState->GetUniqueId() != WaitingForEvent::getInstance().GetUniqueId() && retState->GetUniqueId() != SequenceEnded::getInstance().GetUniqueId()) retState = tempRetState; } i++; } return *retState; } string State::GetLastSequence() { size_t i = 0; for(auto itMap = m_eventSequences.begin(); itMap != m_eventSequences.end(); ++itMap) { if(m_eventRunners[i] == - 2) { m_eventRunners[i] = -1; return itMap->first; } i++; } return "Warning: no Sequence Found Maching"; } StateInterface* State::InnerValidateState(const vector<string>* itMap, size_t itRunner, string event) { m_eventRunners[itRunner] += 1; //if event is not in the legal event vector - ignore if(find(m_legalEvents.begin(), m_legalEvents.end(), event) == m_legalEvents.end()) { return &Ignore::getInstance(); } //if event equals the wanted event in seq if(event.compare((*itMap)[m_eventRunners[itRunner]]) == 0 || (*itMap)[m_eventRunners[itRunner]] == "Any") { if(m_eventRunners[itRunner] == (int)(*itMap).size() - 1) { return &SequenceEnded::getInstance(); } else { return &WaitingForEvent::getInstance(); } } //sequnce should be ignored else { return &Ignore::getInstance(); } } void State::SetEventSequences(map<string, vector<string>> eventSequences) { m_eventSequences = eventSequences; } <file_sep>#pragma once #include <iostream> class Utils { public: Utils() = default; Utils(const Utils& src) = delete; Utils& operator=(const Utils& src) = delete; ~Utils() noexcept = default; template<typename Base, typename T> static inline bool instanceof(const T*) { return std::is_base_of<Base, T>::value; } };//Utils<file_sep>#include <iostream> #include <vector> #include <string> #include "TerminalEventListener.h" #include "Event.h" using std::string; using std::cin; using std::cout; using std::endl; using std::vector; void TerminalEventListener::ListenToEvent(Machine& machine) { string input; string endRun = "End"; m_listen = true; while(m_listen) { static Event event; vector<string> valuesVector; cout<<"\nenter next event: "; cin>>input; if(endRun.compare(input) == 0) { cout<<"End Key Recieved" <<endl; m_listen = false; } else { event.SetValues(input); machine.RegisterEvent(event); } } }<file_sep>#pragma once #include <vector> #include <map> #include <vector> #include "State.h" #include "StateInterface.h" #include "Event.h" using std::map; using std::vector; using std::string; class Machine { public: explicit Machine(); Machine(const Machine& src); Machine& operator=(const Machine& src); void RegisterEvent(Event eventDescription);//TODO maybe return handler_id_type void SetState(StateInterface& nextState); private: map<string, vector<string>> ReadMachineStateFromXML(); State currentState; };//Machine<file_sep>#include <functional> #include <iostream> #include "Machine.h" #include "TerminalEventListener.h" int main() { Machine stateMachine; TerminalEventListener eventListener; eventListener.Start(); eventListener.ListenToEvent(stateMachine); }
559019f54f80a3f0bf83fbd82d5f8424958b4d89
[ "Text", "C++" ]
15
Text
Nashdidan/SequenceDrivenStateMachine
19d819c01eec2d0ea026b43d5b04cea2f2dedbf8
47a9df564151ece29a2ad712b24df6c425b919af
refs/heads/master
<repo_name>TankwartErich/radio<file_sep>/README.md pip3.6 install --upgrade pip pip3.6 install lxml pip3.6 install requests pip3.6 install mysql-connector-python Visual Studio Code -> cmd + p -> '>Python Select Interpreter' <file_sep>/radio.py from lxml import html import requests import mysql.connector from datetime import datetime, timedelta import time import traceback import configparser import argparse class PlaylistEntry: def __init__(self, song, artist, airdate): self.song = song self.artist = artist self.airdate = airdate class DBInfo: def __init__(self, database, cursor): self.database = database self.cursor = cursor def logger(text): date = datetime.now() print("[" + date.strftime("%d.%m.%Y %H:%M") + "] " + text + ".") def parseArguments(): parser = argparse.ArgumentParser() parser.add_argument("--config", help="Set path to config file.") args = parser.parse_args() return args def parseConfiguration(filepath): configParser = configparser.ConfigParser() configParser.read(filepath) return configParser def initOrSetDatabase(user,pwd): initDB = True database = mysql.connector.connect( host="127.0.0.1", port="3306", user=user, passwd=pwd ) dbinfo = DBInfo(database, database.cursor()) dbinfo.cursor.execute("SHOW DATABASES") for x in dbinfo.cursor: if(str(x).find("radio") > 0): initDB = False #print("Database radio found.") if(initDB): print("Initializing database radio.") dbinfo.cursor.execute("CREATE DATABASE radio") dbinfo.cursor.execute("USE radio") dbinfo.cursor.execute("CREATE TABLE artist (ID MEDIUMINT NOT NULL AUTO_INCREMENT, name VARCHAR(250), PRIMARY KEY (ID) );") dbinfo.cursor.execute("CREATE TABLE song (ID MEDIUMINT NOT NULL AUTO_INCREMENT, title VARCHAR(250), PRIMARY KEY (ID) );") dbinfo.cursor.execute("CREATE TABLE playlist (ID MEDIUMINT NOT NULL AUTO_INCREMENT, artist_id MEDIUMINT, song_id MEDIUMINT, airdate DATETIME, PRIMARY KEY (ID) );") print("Database radio initialised.") dbinfo.cursor.execute("use radio") return dbinfo def getPlaylistEntriesFromURL(date): playlist = [] if(date > datetime.now()): return playlist songSearchUrl = 'https://www.rockantenne.de/musik/song-suche?station=rockantenne&date=' + str(date.day) + '.' + str(date.month) + '.' + str(date.year) + '&hour=' + str(date.hour) + '&minutes=' + date.strftime("%M") #Double zero page = requests.get(songSearchUrl) tree = html.fromstring(page.content) songs = tree.xpath('//h2[@class="song_title"]/a/text()') artists = tree.xpath('//p[@class="artist"]/a/text()') times = tree.xpath('//p[@class="artist"]/following::p[1]/text()') if(len(songs) != len(artists)): logger("Missmatch between songs and artist found on page") return playlist entryCount = 0 for time in times: datetimestring = time[-23:] datestring = datetimestring[:10] timestring = datetimestring[-9:] timestring = timestring[:5] datetimestring = datestring + " " + timestring datetime_object = datetime.strptime(datetimestring, '%d.%m.%Y %H:%M') plentry = PlaylistEntry(songs[entryCount].replace("'", ""), artists[entryCount].replace("'", ""), datetime_object) playlist.append(plentry) entryCount = entryCount + 1 logger(str(len(playlist)) + " songs found for " + date.strftime("%d.%m.%Y %H:%M")) return playlist def savePlaylistToDatabase(playlist, dbinfo): timescount = 0 for entry in playlist: selstatement = "SELECT ID FROM playlist WHERE airdate = '" + str(entry.airdate) + "';" dbinfo.cursor.execute(selstatement) dbinfo.cursor.fetchall() artist_id = 0 song_id = 0 if(dbinfo.cursor.rowcount == 0): #Artist selectArtistID = "SELECT ID FROM artist WHERE name = '" + entry.artist + "';" dbinfo.cursor.execute(selectArtistID) artistResList = dbinfo.cursor.fetchall() if(dbinfo.cursor.rowcount == 1): artist_id = str(artistResList[0]) artist_id = artist_id.replace(")", "").replace("(", "").replace(",","") #print("Artist [" + cleanArtist + "] already listed with id [" + artist_id + "]") else: insertArtist = "INSERT INTO artist (name) VALUES ('" + entry.artist + "');" dbinfo.cursor.execute(insertArtist) dbinfo.database.commit() artist_id = dbinfo.cursor.lastrowid #print("Artist [" + cleanArtist + "] inserted with id [" + str(artist_id) + "]") #Song selectSondID = "SELECT ID FROM song WHERE title = '" + entry.song + "';" dbinfo.cursor.execute(selectSondID) songResList = dbinfo.cursor.fetchall() if(dbinfo.cursor.rowcount == 1): song_id = str(songResList[0]) #change to str(songResList[0][0]) and test song_id = song_id.replace(")", "").replace("(", "").replace(",","") #print("Song [" + cleanSong + "] already listed with id [" + song_id + "]") else: insertSong = "INSERT INTO song (title) VALUES ('" + entry.song + "');" dbinfo.cursor.execute(insertSong) dbinfo.database.commit() song_id = dbinfo.cursor.lastrowid #print("Song [" + cleanSong + "] inserted with id [" + str(song_id) + "]") #Playlist insertPlaylist = "INSERT INTO playlist (artist_id, song_id, airdate) VALUES (" + str(artist_id) + ", " + str(song_id) + ", '" + str(entry.airdate) + "');" dbinfo.cursor.execute(insertPlaylist) dbinfo.database.commit() logger(entry.song + " by " + entry.artist + " inserted at " + str(entry.airdate) + " with id " + str(dbinfo.cursor.lastrowid)) timescount = timescount +1 def doEntriesExist(date, dbinfo): startDate = date.replace(minute = 0) endDate = date.replace(minute = 59) selstatement = "SELECT ID FROM playlist WHERE airdate BETWEEN '" + str(startDate) + "' AND '" + str(endDate) + "';" dbinfo.cursor.execute(selstatement) dbinfo.cursor.fetchall() if(dbinfo.cursor.rowcount > 0): return True return False ########### # Start # ########### try: arguments = parseArguments() config = parseConfiguration(arguments.config) print(config['mysql']['user']) print(config['mysql']['password']) print(config['Default']['daysoffuturepast']) daysOfFuturePast = int(config['Default']['daysoffuturepast']) dbinfo = initOrSetDatabase(config['mysql']['user'], config['mysql']['password']) dayCount = 1 while dayCount < daysOfFuturePast+1: subDate = datetime.today() - timedelta(days=dayCount) hours = range(0,24) minutes = [0,30] for hour in hours: subDate = subDate.replace(hour = hour) entriesExist = doEntriesExist(subDate, dbinfo) if entriesExist: logger("Skipped " + subDate.strftime("%d.%m.%Y %H:%M") + " while entries exist") continue for minute in minutes: subDate = subDate.replace(minute = minute) playlist = getPlaylistEntriesFromURL(subDate) if len(playlist) > 0: savePlaylistToDatabase(playlist, dbinfo) #time.sleep(5) #DDOS delay ;) dayCount = dayCount +1 except Exception as e: logger("Unexpected error: " + traceback.format_exc()) <file_sep>/cfg.ini [mysql] user = root password = <PASSWORD> [Default] daysoffuturepast = 2
942414aa28a78ba930656b3d1e6fd86c45a9c131
[ "Markdown", "Python", "INI" ]
3
Markdown
TankwartErich/radio
2c1a7b90c27076477bb1a753f9c0f0d03b776cf0
9a95a1c86c5e8a54e2aa198b06b1bd7e5ae354eb
refs/heads/master
<repo_name>BeardedBry/react-query-practice<file_sep>/src/components/Quote.js import React from "react"; const Quote = ({ quote }) => { return ( <li> <p className="quote">{quote.en}</p> <p className="quoteAuthor">- {quote.author}</p> </li> ); }; export default Quote; <file_sep>/src/App.js import React from "react"; import { ReactQueryDevtools } from "react-query-devtools"; import "./App.css"; import Infinite from "./components/Infinite"; import NormalQuery from "./components/NormalQuery"; import Paginated from "./components/Paginated"; const defaultComp = <NormalQuery />; const componentList = ["Default", "Infinite", "Paginated"]; const None = () => { return <p>None</p>; }; function App() { const [comp, setComp] = React.useState(defaultComp); function chooseComponent(target) { switch (target) { case "Default": setComp(<NormalQuery />); break; case "Infinite": setComp(<Infinite />); break; case "Paginated": setComp(<Paginated />); break; default: setComp(<None />); break; } } return ( <> <div className="App"> <h3>React-Query Learning</h3> {componentList.map((component) => { return ( <button onClick={() => chooseComponent(component)} key={component}> {component} </button> ); })} {comp} </div> <ReactQueryDevtools initialIsOpen={false} /> </> ); } export default App; <file_sep>/src/components/NormalQuery.js import React from "react"; import { useQuery, Query } from "react-query"; import Quote from "./Quote"; const endpoint = "https://programming-quotes-api.herokuapp.com/quotes/page/"; const fetchQuotes = async (key, page) => { const res = await fetch( `https://programming-quotes-api.herokuapp.com/quotes/page/${page}` ); return res.json(); }; const NormalQuery = () => { const { data, status } = useQuery(["quotes", 1], fetchQuotes, { staleTime: 60000, refetchOnWindowFocus: false, onSuccess: () => console.log('fetched quotes'), }); return ( <div className="regularPage"> <h1>Regular Query</h1> <p>Source: {endpoint}</p> {status === "loading" && <span>Loading Data...</span>} {status === "error" || (data?.success === false && <span>Error Fetching Data.</span>)} {status === "success" && ( <ul className="quoteList"> {data.map((quote) => ( <Quote quote={quote} key={quote.id}/> ))} </ul> )} </div> ); }; export default NormalQuery;
de4c6438a761072ef26451abdca2df2e91cfcae9
[ "JavaScript" ]
3
JavaScript
BeardedBry/react-query-practice
75314965d2a4cf27df844af5f0c41803eaaf0821
92b18027c972bb87c64c468b7ae9d3a33e781a8a
refs/heads/master
<repo_name>LaoZhongGu/fastquery<file_sep>/src/main/java/org/fastquery/util/FastQueryJSONObject.java /* * Copyright (c) 2016-2016, fastquery.org and/or its affiliates. All rights reserved. * * 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. * * For more information, please see http://www.fastquery.org/. * */ package org.fastquery.util; import java.util.ArrayList; import java.util.List; import org.fastquery.core.RepositoryException; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * * @author xixifeng (<EMAIL>) */ public class FastQueryJSONObject { private static JSONObject jsonObject; private FastQueryJSONObject(){} static void setJsonObject(JSONObject o){// 只允许对jsonObject赋值一次 if(jsonObject==null) { jsonObject = o; } } /** * 获取基准路径 * @return basedir */ public static String getBasedir(){ return jsonObject.getString("basedir"); } /** * @return velocity配置文件的路径 */ public static String getVelocity(){ return jsonObject.getString("velocity"); } public static boolean getDebug(){ return (boolean)jsonObject.getOrDefault("debug", false); } public static List<String> getQueries(){ List<String> strs = new ArrayList<>(); JSONArray jsonArray = jsonObject.getJSONArray("queries"); if(jsonArray==null){ return strs; } jsonArray.forEach(s -> strs.add(s.toString())); return strs; } static void check(){ // 1). queries属性要么不配置,要么配置正确 List<String> strs = getQueries(); for (String str : strs) { if( "".equals(str)) { continue; } if(str.charAt(0)=='/') { throw new RepositoryException(String.format("fastquery.json-> queries配置错误,\"%s\"的开头不应该有\"/\"", str)); } if(str.charAt(str.length()-1)!='/'){ throw new RepositoryException(String.format("fastquery.json-> queries配置错误,\"%s\"的末尾必须加\"/\"", str)); } } } } <file_sep>/src/main/java/org/fastquery/osgi/act/Activator.java package org.fastquery.osgi.act; import org.fastquery.osgi.impl.FQueryImpl; import org.fastquery.osgi.service.FQuery; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { private ServiceRegistration serviceRegistration; public void start(BundleContext bundleContext) throws Exception { // 对外提供FQuery服务 serviceRegistration = bundleContext.registerService(FQuery.class, new FQueryImpl(), null); } public void stop(BundleContext bundleContext) throws Exception { if(serviceRegistration!=null) { serviceRegistration.unregister(); } bundleContext = null; } } <file_sep>/src/test/java/org/fastquery/test/MethodQueryTest.java /* * Copyright (c) 2016-2016, fastquery.org and/or its affiliates. All rights reserved. * * 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. * * For more information, please see http://www.fastquery.org/. * */ package org.fastquery.test; import org.fastquery.bean.UserInfo; import org.fastquery.core.RepositoryException; import org.fastquery.dao.UserInfoDBService; import org.fastquery.example.StudentDBService; import org.fastquery.service.FQuery; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Collection; /** * * @author xixifeng (<EMAIL>) */ public class MethodQueryTest { @Rule public ExpectedException thrown = ExpectedException.none(); private StudentDBService studentDBService; private UserInfoDBService userInfoDBService; @Before public void before(){ studentDBService = FQuery.getRepository(StudentDBService.class); userInfoDBService = FQuery.getRepository(UserInfoDBService.class); } @Test public void testSave(){ Integer id = 36; String name = "Jsxxv"; Integer age = 23; UserInfo u = new UserInfo(id,name, age); while (userInfoDBService.findById(id)!=null) { // 该主键已经存在,直到该主键不存在时,才会结束循环 id += 1; } u.setId(id); UserInfo u2 = studentDBService.save(u); assertThat(u2.getId(), equalTo(u.getId())); assertThat(u2.getName(), equalTo(u.getName())); assertThat(u2.getAge(), equalTo(u.getAge())); } @Test public void testSave2(){ Integer id = null; String name = "凤侯"; Integer age = 32; UserInfo u = new UserInfo(id,name, age); UserInfo u2 = studentDBService.save("xk-c3p0", "xk", u); System.out.println("id:" + u2.getId()); assertThat(u2.getId(), notNullValue()); assertThat(u2.getName(), equalTo(u.getName())); assertThat(u2.getAge(), equalTo(u.getAge())); } @Test public void save3(){ UserInfo u1 = new UserInfo(1, "equinox", 10); UserInfo u2 = new UserInfo(2, "Eclipse", 3); UserInfo u3 = new UserInfo(3, "ement", 2); int effect = studentDBService.saveArray(true, u1,u2,u3); assertThat(effect, is(0)); } @Test public void save4(){ UserInfo u1 = new UserInfo(1, "equ", 10); UserInfo u2 = new UserInfo(2, "Ecl", 3); UserInfo u3 = new UserInfo(3, "ement", 2); // 断言: 在执行studentDBService.save(false, u1,u2,u3)之后,将会抛出 RepositoryException 异常! thrown.expect(RepositoryException.class); // 断言: 在执行studentDBService.save(false, u1,u2,u3)之后,抛出的异常信息中包含有"Duplicate entry '1' for key 'PRIMARY'"字符串 thrown.expectMessage(containsString("Duplicate entry '1' for key 'PRIMARY'")); int effect = studentDBService.saveArray(false, u1,u2,u3); assertThat(effect, is(0)); } @Test public void save5(){ UserInfo u1 = new UserInfo("equ", 10); UserInfo u2 = new UserInfo("Ecl", 3); UserInfo u3 = new UserInfo("ement", 2); int effect = studentDBService.saveArray(false, u1,u2,u3); assertThat(effect, is(3)); } @Test public void save6(){ UserInfo u1 = new UserInfo("安小惠", 10); UserInfo u2 = new UserInfo("袁承志", 3); UserInfo u3 = new UserInfo("袁崇焕", 2); Collection<UserInfo> userInfos = new ArrayList<>(); userInfos.add(u1); userInfos.add(u2); userInfos.add(u3); int effect = studentDBService.save(false,userInfos); assertThat(effect, is(3)); } @Test(expected = RepositoryException.class) public void executeBatch() { // 参考: http://mxm910821.iteye.com/blog/1701822 studentDBService.executeBatch("update.sql", "sqlout.log"); } @Test public void update3(){ String dataSourceName = "xk-c3p0"; String dbName = "xk"; UserInfo entity = new UserInfo(1,"好哇瓦",3); UserInfo u = studentDBService.update(dataSourceName, dbName, entity); assertThat(u.getId(), equalTo(1)); assertThat(u.getName(), equalTo("好哇瓦")); assertThat(u.getAge(), equalTo(3)); } @Test public void saveOrUpdate() { UserInfo userInfo = new UserInfo(100,"小蜜蜂", 5); UserInfo u1 = studentDBService.saveOrUpdate(userInfo); Integer id1 = u1.getId(); assertThat(id1, notNullValue()); assertThat(u1.getName(), equalTo("小蜜蜂")); assertThat(u1.getAge(), equalTo(5)); UserInfo u2 = studentDBService.saveOrUpdate(u1); Integer id2 = u2.getId(); assertThat(id2, equalTo(id1)); assertThat(u2.getName(), equalTo("小蜜蜂")); assertThat(u2.getAge(), equalTo(5)); } // 使用update时,同时自定义条件的例子 @Test public void update4(){ Integer id = 1; String name = "好哇瓦"; Integer age = 3; UserInfo entity = new UserInfo(id,name,age); // 会解析成:update `UserInfo` set `id`=?, `age`=? where name = ? int effect = studentDBService.update(entity,"name = :name"); // 断言: 影响的行数大于0行 assertThat(effect, greaterThan(0)); // 不想让id字段参与改运算 entity.setId(null); // 会解析成:update `UserInfo` set `age`=? where name = ? effect = studentDBService.update(entity,"name = :name"); assertThat(effect, greaterThan(0)); // 不想让age字段参与改运算 entity.setAge(null); effect = studentDBService.update(entity,"name = :name"); assertThat(effect, is(0)); } @Test public void update5(){ Integer id = 1; String name = "框架测试!"; Integer age = 23; UserInfo ui = FQuery.reset(UserInfo.class); ui.setName(name); ui.setAge(age); ui.setId(id); int i = userInfoDBService.update(ui,"id in (:id,:id)"); assertThat(i, equalTo(1)); UserInfo userInfo = userInfoDBService.findById(ui.getId()); assertThat(userInfo.getId(), equalTo(id)); assertThat(userInfo.getName(), equalTo(name)); assertThat(userInfo.getAge(), equalTo(age)); } @Test public void update6(){ UserInfo ui = FQuery.reset(UserInfo.class); ui.setId(1); int i = userInfoDBService.update(ui,"id = :id"); assertThat(i, lessThan(1)); } }
77beaf73b9648def43417e95cfccd81189baaa9e
[ "Java" ]
3
Java
LaoZhongGu/fastquery
c72f77e4ea068298f31eb8ef9879e2914364d15e
f15153eee1c0ef4fd65495c6e21a96b0d034bee3
refs/heads/master
<repo_name>ajw170/FSU-KevinBacon<file_sep>/Support Files/CPP/primes.h /* primes.h 12/21/2016 <NAME> prototypes of functions PrimeBelow, PrimeAbove, AllPrimesBelow, Sieve plus optimized versions of each all use BitVectors, and the first three all call sieve(), an implementation of the Sieve of Eratosthenes Copyright 2016, <NAME> */ #ifndef _PRIMES_H #define _PRIMES_H #include <iostream> #include <bitvect.h> namespace fsu { size_t PrimeBelow (size_t n, bool ticker = 0); // returns largest prime number <= n // or zero if input is too large size_t PrimeAbove (size_t n, bool ticker = 0); // returns smallest prime number >= n // or zero if input is too large void AllPrimesBelow (size_t n, std::ostream& os = std::cout, bool ticker = 0); // prints all primes less than n void Sieve (fsu::BitVector& b, bool ticker = 0); // The Sieve of Eratosthenes // pre: b is a BitVector // post: for n < b.Size(), // n is prime iff 1 = b.Test(n) /* These opt versions code the sieve process for odd integers only. First handle the special case 2, then only look at odd integers from 3. The BitVector then "codes" primeness of 2i+1 at index i. We already know that 2i is not prime, so no need to waste time and space on these 50% of the positive integers. Need two Lemmas: Lemma 1: If k is odd then k*k + (2n+1)k is even. Proof: Factor k*k + (2n+1)k = k(k+2n+1) = A*B. If A = k is odd then B = k+2n+1 is even. If A = k is even then B = k+2n+1 is odd. Either way, A or B is even so AB is even. Lemma 2: if k is odd then k*k + 2nk is odd. Proof: k = 2i+1 odd => k*k = 4i^2 + 4i + 1 is odd, hence k*k + even is odd. */ size_t PrimeBelowOpt (size_t n, bool ticker); size_t PrimeAboveOpt (size_t n, bool ticker); void AllPrimesBelowOpt (size_t n, std::ostream& os, bool ticker); void SieveOpt (BitVector& b, bool ticker); } // namespace fsu #endif <file_sep>/Support Files/TCPP/topsort.h /* topsort.h 08/30/14 Topological Sort Function Template Call: TopSort(diGraph, outQueue) - performs a topological sort on diGraph, - places the result in outQueue, and - returns 1 if the sort is successful (indicating diGraph is a DAG) - returns 0 if the sort is not successful (outQueue contains a partial sort) IN: 1. diGraph conforms to the API defined in igraph.h 2. outQueue exposes a public operation Push(int) 3. outQueue is initially empty OUT: 1. diGraph is unchanged 2. outQueue contains result of topological sort on diGraph 3. outQueue.Size() == diGraph.vSize() iff diGraph is DAG 4. return (outQueue.Size() == diGraph.vSize() ? 1 : 0) Copyright 2014, <NAME> */ #include <queue.h> #include <stack.h> #include <vector.h> namespace fsu { template <class DigraphType, class ResultType> bool TopSort (const DigraphType& diGraph, ResultType& outQueue) { typedef typename DigraphType::Vertex Vertex; typedef typename DigraphType::AdjIterator AdjIterator; fsu::Queue < Vertex > conQueue; // fsu::Stack < Vertex > conStack; // conQueue stores current source vertices prior to processing // note we could use other structures here to give possibly different topsorts fsu::Vector < Vertex > inDegree(diGraph.VrtxSize(),0); // current in-degree of each vertex // preprocess to get all InDegrees (more efficient than search) inDegree.SetSize(diGraph.VrtxSize(), 0); for (Vertex v = 0; v < diGraph.VrtxSize(); ++v) { for (AdjIterator i = diGraph.Begin(v); i != diGraph.End(v); ++i) { ++inDegree[(size_t)*i]; } } // main algorithm Vertex v, w; for (v = 0; v < diGraph.VrtxSize(); ++v) { if (inDegree[v] == 0) { conQueue.Push(v); } } while (!conQueue.Empty()) { // v = conQueue.Top(); // if conQueue is a Stack v = conQueue.Front(); conQueue.Pop(); outQueue.Push(v); for (AdjIterator i = diGraph.Begin(v); i != diGraph.End(v); ++i) { w = *i; --inDegree[w]; if (inDegree[w] == 0) conQueue.Push(w); } } // end while // report result if (outQueue.Size() != diGraph.VrtxSize()) return 0; return 1; } // TopSort } // fsu <file_sep>/Support Files/TCPP/gset.h /* gset.h 01/01/13 <NAME> generic set algorithms All of these algorithms have a common set of preconditions, as follows: 1. I1, I2 are input iterators and I3 is output iterator. (I3 may be an insert iterator.) 2. The input ranges are specified by pairs of iterators of type I1, I2 respectively 3. The beginning of the output range is specified by an iterator of type I3 4. The input ranges have the same ValueType, which is convertible to the output range ValueType 5. P is a predicate order class defined on the ValueType of the input iterators 6. p is a predicate object of type P 7. Note that p is passed by reference to allow passing predicates with state 7. The two input ranges are sorted using p where present and < otherwise A common postcondition is: the output range is sorted (using p where present or < otherise) Copyright 2009-13, <NAME> */ #ifndef _GSET_H #define _GSET_H namespace fsu { template <class I1, class I2, class I3, class P> void g_set_union(I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, P& p) // range3 = range1 union range2 { while (beg1 != end1 && beg2 != end2) { if (p(*beg1, *beg2)) { *dest = *beg1; ++beg1; } else if (p(*beg2, *beg1)) { *dest = *beg2; ++beg2; } else { *dest = *beg1; ++beg1; ++beg2; } ++dest; } while (beg1 != end1) { *dest++ = *beg1++; } while (beg2 != end2) { *dest++ = *beg2++; } } template <class I1, class I2, class I3> void g_set_union(I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator < { while (beg1 != end1 && beg2 != end2) { if (*beg1 < *beg2) { *dest = *beg1; ++beg1; } else if (*beg2 < *beg1) { *dest = *beg2; ++beg2; } else { *dest = *beg1; ++beg1; ++beg2; } ++dest; } while (beg1 != end1) { *dest++ = *beg1++; } while (beg2 != end2) { *dest++ = *beg2++; } } template <class I1, class I2, class I3, class P> void g_set_merge (I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, P& p) // range3 = range1 merge range2 { while (beg1 != end1 && beg2 != end2) { if (p(*beg2,*beg1)) { *dest++ = *beg2++; } else { *dest++ = *beg1++; } } while (beg1 != end1) { *dest++ = *beg1++; } while (beg2 != end2) { *dest++ = *beg2++; } } template <class I1, class I2, class I3> void g_set_merge (I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator < () { while (beg1 != end1 && beg2 != end2) { if ((*beg2) < (*beg1)) { *dest++ = *beg2++; } else { *dest++ = *beg1++; } } while (beg1 != end1) { *dest++ = *beg1++; } while (beg2 != end2) { *dest++ = *beg2++; } } template <class I1, class I2, class I3, class P> void g_set_intersection(I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, P& p) // range3 = range1 intersection range2 { while (beg1 != end1 && beg2 != end2) { if (p(*beg2,*beg1)) { ++beg2; } else if (p(*beg1, *beg2)) { ++beg1; } else { *dest++ = *beg1; // *beg1 == *beg2 ++beg1; ++beg2; } } } template <class I1, class I2, class I3> void g_set_intersection(I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator <() { while (beg1 != end1 && beg2 != end2) { if ((*beg2) < (*beg1)) { ++beg2; } else if ((*beg1) < (*beg2)) { ++beg1; } else { *dest++ = *beg1; // *beg1 == *beg2 ++beg1; ++beg2; } } } template <class I1, class I2, class I3, class P> void g_set_difference(I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, P& p) // range3 = range1 difference range2 { while (beg1 != end1 && beg2 != end2) { if (p(*beg2,*beg1)) { ++beg2; } else if (p(*beg1, *beg2)) { *dest++ = *beg1++; } else { ++beg1; ++beg2; } } while (beg1 != end1) *dest++ = *beg1++; } template <class I1, class I2, class I3> void g_set_difference(I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator <() { while (beg1 != end1 && beg2 != end2) { if ((*beg2) < (*beg1)) { ++beg2; } else if ((*beg1) < (*beg2)) { *dest++ = *beg1++; } else { ++beg1; ++beg2; } } while (beg1 != end1) *dest++ = *beg1++; } template <class I1, class I2, class P> bool g_subset_of(I1 beg1, I1 end1, I2 beg2, I2 end2, P& p) // returns true iff range 1 is contained in range 2 { while (beg1 != end1 && beg2 != end2) if (p(*beg1, *beg2)) // *beg1 lies below *beg2 in ValueType return 0; // hence *beg1 not in range2 else if (p(*beg2, *beg1)) // *beg1 lies above *beg2 in ValueType ++beg2; // *beg1 may still be in range2 else // *beg1 == *beg2 ++beg1, ++beg2; // *beg1 found in range2 return (beg1 == end1); // true iff all elements of range1 have been found in range2 } template <class I1, class I2> bool g_subset_of (I1 beg1, I1 end1, I2 beg2, I2 end2) // default version uses operator <() { while (beg1 != end1 && beg2 != end2) if ((*beg1) < (*beg2)) // *beg1 lies below *beg2 in ValueType return 0; else if ((*beg2) < (*beg1)) // *beg1 lies above *beg2 in ValueType ++beg2; else // *beg1 == *beg2 ++beg1, ++beg2; if (beg1 == end1) // all elements of range1 have been found in range2 return 1; return 0; } } // namespace fsu #endif <file_sep>/FSU MovieMatch/graph.h /* graph.h <NAME> COP 4530 This is the header file for the graph API. It defines the ALUGraph (Adjacency List Undirected) and the ALDGraph (Adjaceny List Directed). Note that the code is self-documenting. */ #ifndef GRAPH_H #define GRAPH_H #include <list.h> #include <vector.h> #include <cstdlib> namespace fsu { template < typename N > class ALUGraph { public: typedef N Vertex; typedef typename fsu::List<Vertex> SetType; typedef typename SetType::ConstIterator AdjIterator; void SetVrtxSize (N n); size_t VrtxSize () const; void AddEdge (Vertex from, Vertex to); bool HasEdge (Vertex from, Vertex to) const; size_t EdgeSize () const; size_t OutDegree (Vertex v) const; size_t InDegree (Vertex v) const; void Clear (); void Dump (std::ostream & os); void Shuffle (); AdjIterator Begin (Vertex x) const; AdjIterator End (Vertex x) const; ALUGraph (); //constructor explicit ALUGraph (N n); //constructor with no type converting allowed protected: fsu::Vector <SetType> al_; //vector containing the vertices }; //end class ALUGraph //Directed graph - derived from undirected graph template < typename N > class ALDGraph : public ALUGraph <N> { public: typedef N Vertex; typedef typename ALUGraph<N>::SetType SetType; typedef typename ALUGraph<N>::AdjIterator AdjIterator; void AddEdge (Vertex from, Vertex to); size_t EdgeSize () const; size_t InDegree (Vertex v) const; void Reverse (ALDGraph & d) const; ALDGraph (); explicit ALDGraph (N n); }; //end class ALDGraph //-- //Undirected graph implementations //-- template < typename N > void ALUGraph<N>::SetVrtxSize (N n) { al_.SetSize(n); //sets the underlying vector size } template < typename N > size_t ALUGraph<N>::VrtxSize() const { return al_.Size(); //returns number of vertices (size of vector) } template < typename N > void ALUGraph<N>::AddEdge(Vertex from, Vertex to) { al_[from].Insert(to); //adds "to" vertex to the corresponding list al_[to].Insert(from); } template < typename N > bool ALUGraph<N>::HasEdge (Vertex from, Vertex to) const { AdjIterator i = al_[from].Includes(to); if (i == al_[from].End()) return 0; //not found return 1; //found } template < typename N > size_t ALUGraph<N>::EdgeSize() const { size_t esize = 0; for (Vertex v = 0; v < al_.Size(); ++v) esize += al_[v].Size(); return (esize / 2); //since this is undirected } template < typename N > size_t ALUGraph<N>::OutDegree(Vertex v) const { return al_[v].Size(); //return size of list corresponding to vertex } template < typename N > size_t ALUGraph<N>::InDegree(Vertex v) const { return al_[v].Size(); //for undirected graphs, same as OutDegree } template < typename N > void ALUGraph<N>::Clear() { //loop through and clear all subsidiary structures for (Vertex v = 0; v < al_.Size(); ++v) al_[v].Clear(); //clear all lists al_.Clear(); //set vector size = 0 } template < typename N > void ALUGraph<N>::Dump(std::ostream & os) { AdjIterator j; for (Vertex v = 0; v < VrtxSize(); ++v) { os << "[" << v << "]->"; j = this->Begin(v); if (j != this->End(v)) { os << *j; ++j; } for (; j != this->End(v); ++j) { os << ',' << *j; } os << '\n'; } } template < typename N > void ALUGraph<N>::Shuffle() { for (Vertex v = 0; v < VrtxSize(); ++v) al_[v].Shuffle(); } template < typename N > typename ALUGraph<N>::AdjIterator ALUGraph<N>::Begin (Vertex x) const { return al_[x].Begin(); //returns Begin list iterator } template < typename N > typename ALUGraph<N>::AdjIterator ALUGraph<N>::End (Vertex x) const { return al_[x].End(); //returns End list iterator } template < typename N > ALUGraph<N>::ALUGraph() {} //default constructor - nothign to be done here; vector will initialize to size 0 template < typename N > ALUGraph<N>::ALUGraph(N n) { al_.SetSize(n); //sets vector to size n; indicates number of vertices in graph } // -- //Directed graph implementations // -- template < typename N> void ALDGraph<N>::AddEdge(Vertex from, Vertex to) { (this->al_)[from].Insert(to); //this needed since this is templated function } template < typename N > size_t ALDGraph<N>::EdgeSize() const { size_t esize = 0; for (Vertex v = 0; v < (this->al_).Size(); ++v) esize += ALUGraph<N>::al_[v].Size(); return esize; } template < typename N > size_t ALDGraph<N>::InDegree (Vertex v) const { size_t indegree = 0; AdjIterator j; for (Vertex x = 0; x < this->VrtxSize(); ++x) { for (j = this->Begin(x); j != this->End(x); ++j) { if (v == *j) ++indegree; } } return indegree; } template < typename N > void ALDGraph<N>::Reverse (ALDGraph & d) const { //the graph d gets created as a reverse of *this d.Clear(); //clears d - empty graph d.SetVrtxSize(this->VrtxSize()); //sets d to size of *this for (Vertex x = 0; x < this->VrtxSize(); ++x) { for (AdjIterator j = this->Begin(x); j != this->End(x); ++j) //go through list { d.AddEdge(*j, x); //add edge from *j to x } } } template < typename N > ALDGraph<N>::ALDGraph () : ALUGraph<N>() //default constructor {} template < typename N > ALDGraph<N>::ALDGraph(N n) : ALUGraph<N> (n) {} }//end namespace fsu #endif /* GRAPH_H */ <file_sep>/FSU MovieMatch/moviematch.h /* moviematch.h <NAME> COP4530 Final Revision Defines and implements the Kevin Bacon - "Six Degrees of Separation" game. The user will be able to determine any selected actor's Kevin Bacon number! The following technologies are used in the implementation: -Graphs -Graph Search and Survey -Path Computation in Graphs -Associative Arrays [implemented via hash tables] -Generic sort algorithms (specifically, heap sort) -Generic binary search Note that the code is self-documenting. */ #ifndef MOVIEMATCH_H #define MOVIEMATCH_H #include <xstring.h> #include <cstdlib> #include <graph.h> #include <bfsurvey.h> #include <vector.h> #include <hashclasses.h> #include <hashtbl.h> #include <graph_util.h> #include <survey_util.h> #include <list.h> #include <cctype> #include <genalg.h> #include <gheap.h> #include <gbsearch.h> //class for sorting case insensitve strings class CaseInsensitiveLessThan { public: bool operator () (const fsu::String& s1, const fsu::String& s2) { size_t i = 0; for (i = 0; i < s1.Size() && i < s2.Size(); ++i) { if (tolower(s1[i]) < tolower(s2[i])) return 1; if (tolower(s1[i]) > tolower(s2[i])) return 0; } if (s1.Size() < s2.Size()) return 1; return 0; } }; //The main MovieMatch class class MovieMatch { public: //terminology support typedef size_t Vertex; typedef fsu::String Name; typedef fsu::ALUGraph<Vertex> Graph; typedef fsu::BFSurvey<Graph> BFS; typedef hashclass::KISS<Name> Hash; typedef fsu::HashTable<Name,Vertex,Hash> AA; //associative array typedef fsu::Vector<Name> Vector; //vector of strings typedef fsu::List<Vertex> List; //list of vertices MovieMatch (); //default constructor bool Load (const char * filename); bool Init (const char * actor); void Shuffle (); long MovieDistance (const char * actor); void ShowPath (std::ostream & os) const; void ShowStar (Name name, std::ostream & os) const; void Hint (Name name, std::ostream & os, size_t size) const; void Dump (std::ostream & os) const; private: static void Line (std::istream & is, Vector & movie); //helper read function bool isMovie (Vertex v); //takes a vertex and determines if it is a movie Graph g_; //the bipartite graph connecting actors with movies Vector name_; //the vector mapping vertex numbers to names Vector hint_; //the hint vector used AA vrtx_; //the associatve array mappint names to vertex numbers BFS bfs_; //the breadth first survey Name baseActor_; //holds the base actor's name List path_; //holds the path from specified vertex to base }; //end class MovieMatch //default constructor - only initial object is created MovieMatch::MovieMatch() : g_(), name_(), hint_(), vrtx_(), bfs_(g_), baseActor_() {} bool MovieMatch::Load (const char * filename) { std::cout << " Loading database " << filename << " (first read) ..."; //read first line of file fsu::Vector<Name> inFileVector; Vertex dummyVertexNum = 0; //General purpose vertex Vertex vertexNum = 0; //used to insert values bool isThere = 0; //Used to test presence in AA size_t movieCount = 0; size_t actorCount = 0; size_t numBuckets = 100; //used to optimize hash table load std::ifstream inFile(filename, std::ios::in); if (!inFile) return 0; //file failed to open inFile.seekg(0); //ensure pointer is at 0th byte of file //build AA and name Vector while (!(inFile.eof())) { Line(inFile, inFileVector); //reads line with movie and actor information if (inFileVector.Size() > 0) //if it's not a blank line ++movieCount; //increment movie count (each line is a movie) //check to see if vertex is already in graph //loop through vector and attempt to insert names if they don't already exist for (size_t i = 0; i < inFileVector.Size(); ++i) { isThere = vrtx_.Retrieve(inFileVector[i],dummyVertexNum); //checks presence of vertex name if (!isThere) //if vertex doesn't already exist { vrtx_[inFileVector[i]] = vertexNum; //adds name to AA with specified vertex number name_.PushBack(inFileVector[i]); //adds name to vector hint_.PushBack(inFileVector[i]); //similar to name, but will be sorted in Init() ++actorCount; ++vertexNum; //increments vertex number } } //HashTable optimization Note: "actorCount" is number of elements inserted into symbol tables if (actorCount > (2 * numBuckets)) { numBuckets *= 4; //double size of hash table vrtx_.Rehash(numBuckets); } } //final optimization of hash table vrtx_.Rehash(actorCount); //fix actor count to subtract out movie Count actorCount -= movieCount; //add edges to graph based on file inFile.clear(); //clear bad state after EOF inFile.seekg(0); //reposition pointer to beginning of file std::cout << "(second read) ... "; g_.SetVrtxSize(vrtx_.Size()); //sets number of graph vertices in the HashTable while (!(inFile.eof())) { Line(inFile, inFileVector); //read line from file for (size_t i = 1; i < inFileVector.Size(); ++i) { //adds edge from movie in position 0 to actor in position i g_.AddEdge(vrtx_[inFileVector[0]], vrtx_[inFileVector[i]]); } } inFile.close(); std::cout << "done.\n "; std::cout << movieCount << " movies and " << actorCount << " actors read from " << filename << "\n"; return 1; //successful } //Initializes the BFS object with the actor as the start point bool MovieMatch::Init (const char * actor) { CaseInsensitiveLessThan pred_; //declares predicate object fsu::g_heap_sort(hint_.Begin(),hint_.End(), pred_); //sorts the hint array //determine if the actor is in the database Vertex v; bool isHere = vrtx_.Retrieve(actor,v); //if successful, vertex number will be in v if (!isHere) { std::cerr << " ** Init: " << actor << " is not in the database\n"; return 0; //failure } else if (isMovie(v)) { std::cerr << " ** Init: " << actor << " is a movie\n"; return 0; //failure } else { baseActor_ = actor; //sets base actor in MM object bfs_.Reset(); //resets BFS object with up-do-date graph information bfs_.Search(v); //search graph with vertex v as base return 1; } } void MovieMatch::Shuffle() { g_.Shuffle(); bfs_.Reset(); bfs_.Search(vrtx_[baseActor_]); } long MovieMatch::MovieDistance(const char * actor) { //-3, -2, or -1 or actual movie distance Vertex v; bool isHere = vrtx_.Retrieve(actor, v); //if successful, vertex number will be in v if (!isHere) { return -3; //name is not in database } else if (bfs_.Color()[v] != 'b') //if the actor is unreachable from base { return -2; } else if (isMovie(v)) { return -1; } else //the actor is reachable, compute distance and store path { long movieDistance = bfs_.Distance()[v] / 2; //computed directly from bfs_'s distance vector path_.Clear(); //clear any pre-existing path path_.PushBack(v); //push actor vertex onto path_ //note: the base actor's parent will be null_ while (bfs_.Parent()[v] != bfs_.NullVertex()) { path_.PushBack(bfs_.Parent()[v]); v = bfs_.Parent()[v]; } return movieDistance; } } void MovieMatch::ShowPath(std::ostream & os) const { size_t counter = 0; List::ConstIterator i; i = path_.Begin(); os << "\n"; for (i = path_.Begin(); i != path_.End(); ++i) { if ((counter % 2) == 1) os << " | "; else os << " "; os << name_[*i] << "\n"; ++counter; } os << "\n"; } void MovieMatch::ShowStar(Name name, std::ostream & os) const { Graph::AdjIterator i; Vertex v = vrtx_[name]; //determines vertex number of the star name; note: protected in const environment Vector sortedStar; for (i = g_.Begin(v); i != g_.End(v); ++i) { sortedStar.PushBack(name_[*i]); //push names onto list } CaseInsensitiveLessThan pred_; fsu::g_heap_sort(sortedStar.Begin(), sortedStar.End(), pred_); //sorts the vector os << "\n "; os << name << "\n"; for (Vector::ConstIterator i = sortedStar.Begin(); i != sortedStar.End(); ++i) { os << " | " << *i << "\n"; } os << "\n\n"; } void MovieMatch::Hint (Name name, std::ostream & os, size_t size = 6) const { CaseInsensitiveLessThan pred_; size_t truncSize = size; size_t nameSize = name.Size(); if (nameSize < size) truncSize = nameSize; Name trunc; //creates string "trunc" Name trunczz; //creates string "trunczz" char charString[truncSize+1]; //make room for null character for (size_t i = 0; i < truncSize; ++i) { charString[i] = name.Element(i); } charString[truncSize] = '\0'; trunc.Wrap(charString); char charStringZ[truncSize+3]; //make room for zz plus null character for (size_t i = 0; i < (truncSize); ++i) { charStringZ[i] = name.Element(i); } charStringZ[truncSize] = 'z'; charStringZ[truncSize+1] = 'z'; charStringZ[truncSize+2] = '\0'; trunczz.Wrap(charStringZ); Vector::ConstIterator fullHintBegin = hint_.Begin(); Vector::ConstIterator fullHintEnd = hint_.End(); Vector::ConstIterator hintBegin = fsu::g_lower_bound(fullHintBegin, fullHintEnd, trunc, pred_); Vector::ConstIterator hintEnd = fsu::g_upper_bound(fullHintBegin, fullHintEnd, trunczz, pred_); //move hintBegin iterator back by 2, if possible for (size_t count = 0; count < 2; ++count) { if (hintBegin != fullHintBegin) --hintBegin; } //move hintEnd iterator forward by 2, is possible for (size_t count = 0; count < 2; ++count) { if (hintEnd != fullHintEnd) ++hintEnd; } Vector::ConstIterator h; for (h = hintBegin; h != hintEnd; ++h) { std::cout << *h << "\n"; } } void MovieMatch::Dump (std::ostream & os) const { ShowAL(g_,os); WriteData(bfs_,os); vrtx_.Dump(os); for (size_t i = 0; i < name_.Size(); ++i) { os << "name_[" << i << "] = " << name_[i] << '\t'; os << "vrtx_[" << name_[i] << "] = " << vrtx_[name_[i]] << '\n'; } vrtx_.Analysis(std::cout); } void MovieMatch::Line (std::istream& is, fsu::Vector<Name>& movie) { movie.Clear(); fsu::String line; char delim = '/'; line.GetLine(is); char* name_buffer = new char [1+line.Size()]; size_t pos = 0, next = 0; while (pos < line.Size()) { next = line.Position(delim,pos); for (size_t i = pos; i < next; ++i) { name_buffer[i - pos]= line[i]; } name_buffer[next-pos] = '\0'; movie.PushBack(name_buffer); pos = ++next; // skip delimiter } delete [] name_buffer; } bool MovieMatch::isMovie(Vertex v) { fsu::String s(name_[v]); //instantiates string with name corresponding to vertex size_t stringSize = s.Length(); //gets lengh of string //determines if last part of string is a year if (s[stringSize -1] != ')') { return 0; //not a movie } else if ( isdigit(s[stringSize-2]) && isdigit(s[stringSize-3]) && isdigit(s[stringSize-4]) && isdigit(s[stringSize-5]) && (s[stringSize-6] == '(') ) { return 1; //title ends in a year, is a movie } else { return 0; //not a movie } } #endif /* MOVIEMATCH_H */ <file_sep>/Support Files/TCPP/survey_util.h /* survey_util.h <NAME> 09/28/16 Levelorder(BFS) Preorder(DFS) Postorder(DFS) WriteData(BFS) WriteData(DFS) Arguments() - called by fbfs_ug, fbfs_dg, fdfs_ug,fdfs_dg Copyright 2016, <NAME> */ #ifndef _SURVEY_UTIL_H #define _SURVEY_UTIL_H #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <cstring> #include <bfsurvey.h> #include <dfsurvey.h> template < class G > void Levelorder (const fsu::BFSurvey<G>& bfs, std::ostream& os) { // for BFS, dtime is 1-1 map [0,size) -> [0,size) // complicated when search is partial (some undiscovered vertices) size_t size = bfs.VrtxSize(); fsu::Vector <size_t> dorder(size,size); // invert dtime size_t blacks = 0; for (size_t i = 0; i < size; ++i) { if (bfs.Color()[i] == 'b') { ++blacks; dorder[bfs.DTime()[i]] = i; } } // compress if (blacks < size) { size_t skip = 0; for (size_t i = 0; i < size; ++i) { if (dorder[i] == size) // infinity { ++skip; } else { dorder[i - skip] = dorder[i]; } // std::cout << " skip = " << skip << '\n'; } // */ // assert (blacks + skip == size) if (blacks + skip != size) { std::cerr << " ** Levelorder Error: black_count = " << blacks << '\n' << " skip_count = " << skip << '\n' << " vertex_count = " << size << "\n\n"; } } // now all black vertices are discovered // discovery order for black vertices is dorder[0..blacks-1] os << " Vertex discovery order:"; for (size_t i = 0; i < blacks; ++i) { os << ' ' << dorder[i]; } os << '\n'; os << " grouped by distance:"; size_t i = 0; // i = discovery order size_t vertex = dorder[i]; size_t distance = bfs.Distance()[vertex]; os << " [ ( " << vertex; while (i < blacks - 1) { size_t nextvertex = dorder[i+1]; size_t nextdistance = bfs.Distance()[nextvertex]; if (nextdistance == 0) { os << " ) ] [ ( " << nextvertex; } else if (nextdistance == distance) { os << ' ' << nextvertex; } else if (nextdistance < distance) { std::cerr << " ** logic error in distance grouping\n"; return; } else // nextdistance > distance { os << " ) ( " << nextvertex; } distance = nextdistance; ++i; } os << " ) ]\n"; // } template < class G > void Preorder (const fsu::DFSurvey<G>& dfs, std::ostream& os) { // for DFS, dtime is 1-1 map [0,size) -> [0,2*size) size_t size = dfs.VrtxSize(); fsu::Vector <size_t> dorder(2*size,2*size); // invert dtime /* game plan: (1) "invert" dtime by mapping to dorder then 1/2 of the entries will be unhit (still 2|V| = infinity) (2) compress dorder by skipping the infinity entries (3) complicated when search is partial - process only black vertices */ // map size_t blacks = 0; for (size_t i = 0; i < size; ++i) { if (dfs.Color()[i] == 'b') { ++blacks; dorder[dfs.DTime()[i]] = i; } } // compress size_t skip = 0; for (size_t i = 0; i < 2*size; ++i) { if (dorder[i] == 2*size) // infinity { ++skip; } else { dorder[i - skip] = dorder[i]; } // std::cout << " skip = " << skip << '\n'; } // */ // assert (blacks + skip == size) if (blacks + skip != 2*size) { std::cerr << " ** Preorder Error: black_count = " << blacks << '\n' << " skip_count = " << skip << '\n' << " vertex_count*2 = " << 2*size << "\n\n"; } os << " Vertex discovery order:"; for (size_t i = 0; i < blacks; ++i) os << ' ' << dorder[i]; os << '\n'; } template < class G > void Postorder (const fsu::DFSurvey<G>& dfs, std::ostream& os) { // for DFS, ftime is 1-1 map [0,size) -> [0,2*size) size_t size = dfs.VrtxSize(); fsu::Vector <size_t> forder(2*size,2*size); // invert ftime /* game plan: (1) "invert" ftime by mapping to forder then 1/2 of the entries will be unhit (still 2|V| = infinity) (2) compress forder by skipping the infinity entries (3) complicated when search is partial - process only black vertices */ // map size_t blacks = 0; for (size_t i = 0; i < size; ++i) { if (dfs.Color()[i] == 'b') { ++blacks; forder[dfs.FTime()[i]] = i; } } // compress size_t skip = 0; for (size_t i = 0; i < 2*size; ++i) { if (forder[i] == 2*size) // infinity { ++skip; } else { forder[i - skip] = forder[i]; } // std::cout << " skip = " << skip << '\n'; } // */ // assert (blacks + skip == size) if (blacks + skip != 2*size) { std::cerr << " ** Postorder Error: black_count = " << blacks << '\n' << " skip_count = " << skip << '\n' << " vertex_count*2 = " << 2*size << "\n\n"; } os << " Vertex finishing order:"; for (size_t i = 0; i < blacks; ++i) os << ' ' << forder[i]; os << '\n'; } template < class G > void WriteData (const fsu::BFSurvey<G>& bfs, std::ostream& os) { int c1 = 8, c2 = 10, c3 = 11, c4 = 12, c5 = 13; os << '\n'; os << std::setw(c1 + c2 - 2) << "bf survey data" << '\n'; os << std::setw(c1 + c2 - 2) << "==============" << '\n'; os << std::setw(c1) << "vertex" << std::setw(c2) << "distance" << std::setw(c3) << "dtime" << std::setw(c4) << "parent" << std::setw(c5) << "color" << '\n'; os << std::setw(c1) << "------" << std::setw(c2) << "--------" << std::setw(c3) << "-----" << std::setw(c4) << "------" << std::setw(c5) << "-----" << '\n'; for (size_t i = 0; i < bfs.VrtxSize(); ++i) { os << std::setw(c1) << i << std::setw(c2) << bfs.Distance()[i] << std::setw(c3) << bfs.DTime()[i]; if ((bfs.Parent())[i] < bfs.VrtxSize()) os << std::setw(c4) << (bfs.Parent())[i]; else os << std::setw(c4) << "NULL"; os << std::setw(c5) << bfs.Color()[i] << '\n'; } } template < class G > void WriteData (const fsu::DFSurvey<G>& dfs, std::ostream& os) { int c1 = 8, c2 = 10, c3 = 11, c4 = 12, c5 = 13; os << '\n'; os << std::setw(c1 + c2 - 2) << "df survey data" << '\n'; os << std::setw(c1 + c2 - 2) << "==============" << '\n'; os << std::setw(c1) << "vertex" << std::setw(c2) << "dtime" << std::setw(c3) << "ftime" << std::setw(c4) << "parent" << std::setw(c5) << "color" << '\n'; os << std::setw(c1) << "------" << std::setw(c2) << "-----" << std::setw(c3) << "-----" << std::setw(c4) << "------" << std::setw(c5) << "-----" << '\n'; for (size_t i = 0; i < dfs.VrtxSize(); ++i) { os << std::setw(c1) << i << std::setw(c2) << dfs.DTime()[i] << std::setw(c3) << dfs.FTime()[i]; if ((dfs.Parent())[i] < dfs.VrtxSize()) os << std::setw(c4) << (dfs.Parent())[i]; else os << std::setw(c4) << "NULL"; os << std::setw(c5) << dfs.Color()[i] << '\n'; } } void Arguments(std::ostream& os) { os << " Required arguments\n" << " ------------------\n" << " [1]: char* input_filename\n" << " [2]: char 's' = single search, 'f' = full survey\n" << " [3]: unsigned start_vertex [0..vsize)\n" << " [4]: bool '0' = no trace, '1' = trace\n"; } #endif <file_sep>/Support Files/CPP/primes.cpp /* primes.cpp 12/21/16 <NAME> implementations of functions prototyped in primes.h Copyright 2009-16, <NAME> */ #ifndef _PRIMES_CCP #define _PRIMES_CCP #include <primes.h> #include <timer.h> #include <iomanip> #include <timer.cpp> namespace fsu { size_t PrimeBelow (size_t n, bool ticker) // returns largest prime number <= n // This is likely to be more efficient than PrimeAbove(), because // it only needs a bitvector of size n+1 { if (n <= 1) return 0; if (n == 2) return 2; if (n >= n+1) { std::cerr << " ** PrimeBelow: argument too large for implementation. Execution terminating.\n"; exit (EXIT_FAILURE); } fsu::BitVector b(1+n); Sieve(b, ticker); if (n%2 == 0) --n; // make n odd while (n > 2) { if (b.Test(n)) return n; n -= 2; } return 2; } size_t PrimeBelowOpt (size_t n, bool ticker) // odd integer version { if (n <= 1) return 0; if (n == 2) return 2; if (1 == n%2 && n < n+1) // n is odd and not the largest size_t ++n; fsu::BitVector b(n/2); SieveOpt(b, ticker); for (size_t k = n/2; k > 1; ) { --k; if (b.Test(k)) return 2*k+1; } return 2; } size_t PrimeAbove (size_t n, bool ticker) // returns smallest prime number >= n // or zero if input is too large { if (n <= 2) return 2; size_t m = n << 1; // m = 2n if (m <= n) // 2n <= n => overflow { return 0; } fsu::BitVector b(m); Sieve(b, ticker); while (n < m) { if (b.Test(n)) return n; ++n; } return PrimeAbove(m,ticker); } // tested experimental version void AllPrimesBelowOpt (size_t n, std::ostream& os, bool ticker) // writes all primes <= n to os { if (n < n + 1) // n is not the largest size_t ++n; fsu::BitVector b(n/2); SieveOpt(b, ticker); if (n > 2) os << ' ' << 2; for (size_t i = 1; i < n/2; ++i) if (b.Test(i)) os << ' ' << 2*i+1; os << std::endl; } // tested experimental version void SieveOpt(BitVector& b, bool ticker) // pre: b is a BitVector // post: for all odd n < b.Size(), // n is prime iff 1 = b.Test(n) { // set up timer fsu::Timer timer; fsu::Instant time; if (ticker) { timer.EventReset(); } const size_t max = 1+2*b.Size(); size_t sqrt = 2; while (sqrt*sqrt < max) { ++sqrt; } b.Set(); b.Unset(0); // 1 = 2*0+1 is not prime // clear bits at multiples of all odd primes < sqrt(max) sqrt /= 2; for (size_t i = 1, k = 3; i < sqrt; i += 1, k += 2) // k = 2*i+1 { if (b.Test(i)) // k is prime { if (ticker) std::cout << '.' << std::flush; // for (size_t j = k*k; j < max; j+= 2*k) // these are the odd j's - see Lemmas // { // b.Unset(j/2); // } // for (size_t j = k*k, l = j/2; j < max; j+= 2*k, l+= k) // these are the odd j's - see Lemmas for (size_t l = k*k/2; l < max/2; l+= k) // j = 2l+1 are the odd j's - see Lemmas { b.Unset(l); } } } if (ticker) { time = timer.EventTime(); std::cout << '\n'; std::cout << " Sieve time: "; time.Write_seconds(std::cout,2); std::cout << " sec\n"; } } // end Sieve() // */ // tested version 2 - ignores all even bits void AllPrimesBelow (size_t n, std::ostream& os, bool ticker) // writes all primes <= n to os { if (n < n + 1) // n is not the largest size_t ++n; fsu::BitVector b(n); Sieve(b, ticker); if (n >= 2) os << ' ' << 2; for (size_t i = 3; i < n; i += 2) if (b.Test(i)) os << ' ' << i; os << std::endl; } void Sieve(BitVector& b, bool ticker) // pre: b is a BitVector // post: for all odd n < b.Size(), // n is prime iff 1 = b.Test(n) { // set up timer fsu::Timer timer; fsu::Instant time; if (ticker) { timer.EventReset(); } const size_t max = b.Size(); size_t sqrt = 2; while (sqrt*sqrt < max) { ++sqrt; } // initialize b b.Set(); // b.Unset(0); // 0 is not prime // b.Unset(1); // 1 is not prime // clear bits at multiples of all odd primes < sqrt(max) for (size_t i = 3; i < sqrt; i += 2) { if (b.Test(i)) // i is prime { if (ticker) std::cout << '.' << std::flush; // for (size_t j = i+i; j < max; j+= i) // clear all multiples of i for (size_t j = i*i; j < max; j+= i) // clear all multiples of i { b.Unset(j); } } } if (ticker) { time = timer.EventTime(); std::cout << '\n'; std::cout << " Sieve time: "; time.Write_seconds(std::cout,2); std::cout << " sec\n"; } } // end Sieve() // */ /* void DumpValue(const fsu::BitVector& b, std::ostream& os = std::cout) { os << " "; for (size_t i = 0; i < b.Size(); ++i) os << b.Test(i); os << '\n'; } void DumpIndex(const fsu::BitVector& b, std::ostream& os = std::cout) { os << " "; for (size_t i = 0; i < b.Size(); ++i) os << (2*i + 1)%10; os << '\n'; } */ } // namespace fsu #endif <file_sep>/Support Files/TCPP/list_macro.cpp /* list_macro.cpp 04/03/2017 <NAME> Implementation of List<T>:: macroscopic (whole list) mutators Merge, Reverse, Shuffle Copyright 2016, <NAME> */ //----------------------------------- // List<T>::Merge Implementations //----------------------------------- template < typename T > template < class P > void List<T>::Merge (List<T>& y, P& p) // merges x into this list; post: true = x.Empty() // if both lists are ordered result is ordered { if (this == &y) return; Link * xcurr = head_->next_; // x = this list Link * ycurr = y.head_->next_; // y = that list // merge while both lists are not empty while (xcurr != tail_ && ycurr != y.tail_) { if (p(ycurr->Tval_,xcurr->Tval_)) // y < x { ycurr = ycurr->next_; LinkIn(xcurr,ycurr->prev_); } else // x <= y { xcurr = xcurr->next_; } } // splice in remainder of y if (ycurr != y.tail_) { tail_->prev_->next_ = ycurr; ycurr->prev_ = tail_->prev_; tail_->prev_ = (y.tail_)->prev_; (y.tail_)->prev_->next_ = tail_; } // make y structurally correct for empty (y.head_)->next_ = y.tail_; (y.tail_)->prev_ = y.head_; } template < typename T > void List<T>::Merge (List<T>& y ) { fsu::LessThan<T> p; Merge(y,p); } //------------------------------------ // List<T>::Reverse Implementation //------------------------------------ template < typename T > void List<T>::Reverse () { if (head_->next_ == tail_) return; // swap prev_ and next_ for each link typename List<T>::Link * link(head_), * temp(nullptr); while (link != nullptr) { temp = link->next_; link->next_ = link->prev_; link->prev_ = temp; link = temp; // move to "old next" = link->prev_ } // swap head_ and tail_ temp = head_; head_ = tail_; tail_ = temp; } //------------------------------------ // List<T>::Shuffle Implementation //------------------------------------ template < typename T > void List<T>::Shuffle () { // if list is empty or size 1, nothing to do if (head_->next_ == tail_ || head_->next_->next_ == tail_) return; // manipulate pointers instead of using API which would call new/delete List<T> aux1,aux2; Iterator i = Begin(); Link * link; char semaphore = 0; // values cycle 0 -> 1 -> 2 -> 0 -> ... // step 1: put every 2nd, 3rd links into aux lists in reverse order // std::cout << Size() << " List: "; Display(std::cout, ' '); std::cout << '\n'; while (i != End()) { semaphore == 2 ? semaphore = 0 : semaphore += 1; if (semaphore == 0) { ++i; // leave in List } else { link = i.curr_; i.curr_ = i.curr_->next_; // ++i link = LinkOut(link); // Remove(i) if (semaphore == 1) LinkIn(aux1.head_->next_,link); // aux1.PushFront else LinkIn(aux2.head_->next_,link); // aux2.PushFront } } /* // show the three lists at this stage: std::cout << Size() << " aux0: "; Display(std::cout, ' '); std::cout << '\n'; std::cout << aux1.Size() << " aux1: "; aux1.Display(std::cout, ' '); std::cout << '\n'; std::cout << aux2.Size() << " aux2: "; aux2.Display(std::cout, ' '); std::cout << '\n'; // */ // step 2: splice aux2 to front of list and fix aux2 structure as empty list Link* afirst = aux2.head_->next_; Link* alast = aux2.tail_->prev_; head_->next_->prev_ = alast; alast->next_ = head_->next_; afirst->prev_ = head_; head_->next_ = afirst; aux2.tail_->prev_ = aux2.head_; aux2.head_->next_ = aux2.tail_; // step 3: splice aux1 to front of list and fix aux1 structure as empty list afirst = aux1.head_->next_; alast = aux1.tail_->prev_; head_->next_->prev_ = alast; alast->next_ = head_->next_; afirst->prev_ = head_; head_->next_ = afirst; aux1.tail_->prev_ = aux1.head_; aux1.head_->next_ = aux1.tail_; // */ /* // step 3 (alternate): splice aux1 to back of list and fix aux1 structure as empty list afirst = aux1.head_->next_; alast = aux1.tail_->prev_; tail_->prev_->next_ = afirst; afirst->prev_ = tail_->prev_; alast->next_ = tail_; tail_->prev_ = alast; aux1.tail_->prev_ = aux1.head_; aux1.head_->next_ = aux1.tail_; // */ // show the final shuffled list // std::cout << Size() << " List: "; Display(std::cout, ' '); std::cout << '\n'; } // end macromutators */ <file_sep>/Support Files/TCPP/gsort.h /* gsort_non-rec.h 09/15/16 <NAME> generic sort algorithms applicable to a range specified by iterators includes these generic sort algorithms: g_selection_sort // g_merge_sort g_merge_sort_bu g_insertion_sort // g_quick_sort note that g_heap_sort is located in gheap.h Copyright 2016, <NAME> */ #include <genalg.h> // Swap, g_copy #include <gset.h> // g_set_merge #include <debug.h> #ifndef _GSORT_H #define _GSORT_H // const int qs_cutoff_threshold = 7; // const int qs3w_cutoff_threshold = 7; // const int ms_cutoff_threshold = 7; namespace fsu { template < class ForwardIterator > void g_selection_sort (ForwardIterator beg, ForwardIterator end) { ForwardIterator i, j, k; for (i = beg; i != end; ++i) { k = i; for (j = i; j != end; ++j) if (*j < *k) k = j; Swap (*i, *k); } } template < class ForwardIterator, class Comparator > void g_selection_sort (ForwardIterator beg, ForwardIterator end, Comparator& cmp) { ForwardIterator i, j, k; for (i = beg; i != end; ++i) { k = i; for (j = i; j != end; ++j) if (cmp(*j,*k)) k = j; Swap (*i, *k); } } template < class BidirectionalIterator > void g_insertion_sort (BidirectionalIterator beg, BidirectionalIterator end) { BidirectionalIterator i, j, k; typename BidirectionalIterator::ValueType t; for (i = beg; i != end; ++i) { t = *i; for (k = i, j = k--; j != beg && t < *k; --j, --k) *j = *k; *j = t; } } template < class BidirectionalIterator, class Comparator > void g_insertion_sort (BidirectionalIterator beg, BidirectionalIterator end, Comparator& cmp) { BidirectionalIterator i, j, k; typename BidirectionalIterator::ValueType t; for (i = beg; i != end; ++i) { t = *i; for (k = i, j = k--; j != beg && cmp(t,*k); --j, --k) *j = *k; *j = t; } } // specialization for pointers template < typename T > void g_insertion_sort (T* beg, T* end) { // fsu::Debug ("g_insertion_sort"); if (end - beg < 2) return; T *i, *j, *k; T t; for (i = beg; i != end; ++i) { t = *i; for (k = i, j = k--; j != beg && t < *k; --j, --k) *j = *k; *j = t; } } // specialization for pointers template < typename T , class Comparator > void g_insertion_sort (T* beg, T* end, Comparator& cmp) { if (end - beg < 2) return; T *i, *j, *k; T t; for (i = beg; i != end; ++i) { t = *i; for (k = i, j = k--; j != beg && cmp(t,*k); --j, --k) *j = *k; *j = t; } } namespace mergesort { // these are the special "merge" functions supporting merge sort // for random access iterators and default order template < typename RAIterator > void Merge(RAIterator beg, RAIterator mid, RAIterator end) { // std::cerr << "mergesort::Merge(" << end - beg << ")\n"; fsu::Vector < typename RAIterator::ValueType > B(end-beg); // temp storage for merged copy g_set_merge(beg, mid, mid, end, B.Begin()); // merge the two parts of A to B g_copy(B.Begin(), B.End(), beg); // copy B back to A[p,r) } // for random access iterators and order determined by a predicate object template < typename RAIterator , class Comparator > void Merge(RAIterator beg, RAIterator mid, RAIterator end, Comparator& cmp) { // std::cerr << "mergesort::Merge(" << end - beg << ")\n"; fsu::Vector < typename RAIterator::ValueType > B(end-beg); g_set_merge(beg, mid, mid, end, B.Begin(),cmp); g_copy(B.Begin(), B.End(), beg); } // specialization for pointers and default order template < typename T > void Merge(T* beg, T* mid, T* end) { // std::cerr << "mergesort::Merge(" << end - beg << ")\n"; fsu::Vector < T > B(end-beg); g_set_merge(beg, mid, mid, end, B.Begin()); g_copy(B.Begin(), B.End(), beg); } // specialization for pointers and predicate order template < typename T , class Comparator > void Merge(T* beg, T* mid, T* end, Comparator& cmp) { // std::cerr << "mergesort::Merge(" << end - beg << ")\n"; fsu::Vector < T > B(end-beg); g_set_merge(beg, mid, mid, end, B.Begin(),cmp); g_copy(B.Begin(), B.End(), beg); } } // namespace mergesort template < class RAIterator , class Comparator > void g_merge_sort_bu (RAIterator beg, RAIterator end, Comparator& cmp) { size_t n = end - beg; if (n < 2) return; for (size_t i = 1; i < n; i = i+i) { for (size_t j = 0; j < n - i; j += i+i) { if (n < j+i+i) mergesort::Merge(beg + j, beg + j+i, end, cmp); else mergesort::Merge(beg + j, beg + j+i, beg + j+i+i, cmp); } } } template < class RAIterator > void g_merge_sort_bu (RAIterator beg, RAIterator end) { size_t n = end - beg; if (n < 2) return; for (size_t i = 1; i < n; i = i+i) { for (size_t j = 0; j < n - i; j += i+i) { if (n < j+i+i) mergesort::Merge(beg + j, beg + j+i, end); else mergesort::Merge(beg + j, beg + j+i, beg + j+i+i); } } } } // namespace #endif <file_sep>/Support Files/CPP/require.h /* require.h replaces assert macro: (1) improves formatting of report (2) shows values of variables at time of failure (3) x versions ensure that condition is executed when NDEBUG is defined Nore that these are defined in <cassert>: __FILE__ name of source code file where assertion failed __LINE__ line number in file where assertion failed __FUNCTION__ name of function where assertion failed */ #ifndef NDEBUG #include <cassert> #include <iostream> #define Require(condition) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n'; \ abort(); \ } \ } #define Require1(condition,x) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n' \ << " Variables: " << #x << " = " << x << '\n'; \ abort(); \ } \ } #define Require2(condition,x,y) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n' \ << " Variables: " << #x << " = " << x << '\n' \ << " " << #y << " = " << y << '\n'; \ abort(); \ } \ } #define Require3(condition,x,y,z) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n' \ << " Variables: " << #x << " = " << x << '\n' \ << " " << #y << " = " << y << '\n' \ << " " << #z << " = " << z << '\n'; \ abort(); \ } \ } #define Requirex(condition) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n'; \ abort(); \ } \ } #define Require1x(condition,x) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n' \ << " Variables: " << #x << " = " << x << '\n'; \ abort(); \ } \ } #define Require2x(condition,x,y) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n' \ << " Variables: " << #x << " = " << x << '\n' \ << " " << #y << " = " << y << '\n'; \ abort(); \ } \ } #define Require3x(condition,x,y,z) \ { \ if(!(condition)) \ { \ std::cerr << "Requirement failed at " << __FILE__ << ":" << __LINE__ << '\n' \ << " Function: " << __FUNCTION__ << '\n' \ << " Condition: " << #condition << '\n' \ << " Variables: " << #x << " = " << x << '\n' \ << " " << #y << " = " << y << '\n' \ << " " << #z << " = " << z << '\n'; \ abort(); \ } \ } #else #define Require(condition) #define Require1(condition, x) #define Require2(condition, x, y) #define Require3(condition, x, y, z) #define Requirex(condition) (condition) #define Require1x(condition, x) (condition) #define Require2x(condition, x, y) (condition) #define Require3x(condition, x, y, z) (condition) #endif <file_sep>/FSU MovieMatch/dfsurvey.h /* dfsurvey.h <NAME> COP 4530 This is the header file for the depth-first survey. It defines and implements the DFSurvery class which is used to do a depth-first search of a given graph. Note that the code is self-documenting. */ #ifndef DFSURVEY_H #define DFSURVEY_H #include <vector.h> #include <deque.h> namespace fsu { template < class G > class DFSurvey { public: typedef G Graph; typedef typename Graph::Vertex Vertex; typedef typename Graph::AdjIterator AdjIterator; DFSurvey (const Graph & g); DFSurvey (const Graph & g, Vertex start); void Search (); void Search (Vertex v); void Reset (); void Reset (Vertex start); private: const Graph & g_; Vertex start_; size_t time_; size_t forever_; Vertex null_; AdjIterator NextNeighbor(Vertex x); //returns iterator to next unvisited neighbor of x fsu::Vector<Vertex> dtime_; //discovery time fsu::Vector<Vertex> ftime_; //finishing time, up to 2|V| fsu::Vector<Vertex> parent_; //for DFS tree fsu::Vector<char> color_; fsu::Vector<AdjIterator> neighbor_; //vector of list iterators (points to neighbor) fsu::Deque<Vertex> conQ_; //the control stack public: const fsu::Vector<Vertex>& DTime () const {return dtime_;} const fsu::Vector<Vertex>& FTime () const {return ftime_;} const fsu::Vector<Vertex>& Parent () const {return parent_;} const fsu::Vector<char>& Color () const {return color_;} size_t VrtxSize () const {return g_.VrtxSize();} size_t EdgeSize () const {return g_.EdgeSize();} size_t InfiniteTime () const {return forever_;} Vertex NullVertex () const {return null_;} //developer helper methods bool traceQue; void ShowQueSetup (std::ostream& os) const; void ShowQue (std::ostream& os) const; }; //end class DFSurvey //---- //DFSurvery Implementations //---- template < class G > DFSurvey<G>::DFSurvey (const Graph & g) : g_(g), start_(0), time_(0), forever_(2*g_.VrtxSize()), null_((Vertex)g_.VrtxSize()), dtime_ (g_.VrtxSize(), forever_), ftime_ (g_.VrtxSize(), forever_), parent_ (g_.VrtxSize(), null_), color_ (g_.VrtxSize(), 'w'), neighbor_ (g_.VrtxSize()), conQ_() { for (Vertex x = 0; x < g_.VrtxSize(); ++x) neighbor_[x] = g_.Begin(x); } template < class G > DFSurvey<G>::DFSurvey (const Graph & g, Vertex start) : g_(g), start_(start), time_(0), forever_(2*g_.VrtxSize()), null_((Vertex)g_.VrtxSize()), dtime_ (g_.VrtxSize(), forever_), ftime_ (g_.VrtxSize(), forever_), parent_ (g_.VrtxSize(), null_), color_ (g_.VrtxSize(), 'w'), neighbor_ (g_.VrtxSize()), conQ_() { for (Vertex x = 0; x < g_.VrtxSize(); ++x) neighbor_[x] = g_.Begin(x); } template < class G > void DFSurvey<G>::Search() { Reset(); if (traceQue) { ShowQueSetup(std::cout); ShowQue(std::cout); } for (Vertex v = start_; v < g_.VrtxSize(); ++v) { if (color_[v] == 'w') Search(v); } for (Vertex v = 0; v < start_; ++v) { if (color_[v] == 'w') Search(v); } } template < class G > void DFSurvey<G>::Search(Vertex v) { dtime_[v] = time_++; conQ_.PushBack(v); if (traceQue) ShowQue(std::cout); color_[v] = 'g'; Vertex top; AdjIterator i; while (!conQ_.Empty()) { top = conQ_.Back(); i = NextNeighbor(top); if (i != g_.End(top)) { dtime_[*i] = time_++; conQ_.PushBack(*i); if (traceQue) ShowQue(std::cout); parent_[*i] = top; color_[*i] = 'g'; } else { conQ_.PopBack(); if (traceQue) ShowQue(std::cout); color_[top] = 'b'; ftime_[top] = time_++; } } } template < class G > void DFSurvey<G>::Reset() { time_ = 0; conQ_.Clear(); if (color_.Size() != g_.VrtxSize()) //changed vertex size { forever_ = 2*g_.VrtxSize(); null_ = (Vertex)g_.VrtxSize(); dtime_.SetSize (g_.VrtxSize(), forever_); ftime_.SetSize (g_.VrtxSize(), forever_); parent_.SetSize (g_.VrtxSize(), null_); color_.SetSize (g_.VrtxSize(), 'w'); neighbor_.SetSize(g_.VrtxSize()); for (Vertex x = 0; x < g_.VrtxSize(); ++x) neighbor_[x] = g_.Begin(x); } else { for (Vertex x = 0; x < g_.VrtxSize(); ++x) { dtime_[x] = forever_; ftime_[x] = forever_; parent_[x] = null_; color_[x] = 'w'; neighbor_[x] = g_.Begin(x); } } } template < class G > typename DFSurvey<G>::AdjIterator DFSurvey<G>::NextNeighbor (Vertex x) { while (neighbor_[x] != g_.End(x) && 'w' != color_[*neighbor_[x]]) ++neighbor_[x]; //this is a list iterator return neighbor_[x]; } //Developer helper methods template < class G > void DFSurvey<G>::ShowQueSetup (std::ostream& os) const { os << "\n conStack\n" << " ------->\n"; } template < class G > void DFSurvey<G>::ShowQue (std::ostream& os) const { os << " "; if (conQ_.Empty()) os << "NULL"; else conQ_.Display(os, ' '); os << '\n'; } } //end namespace fsu #endif /* DFSURVEY_H */ <file_sep>/Support Files/TCPP/graph_util.h /* graph_util.h <NAME> 03/19/17 Copyright 2016, <NAME> */ #ifndef _GRAPH_UTIL_H #define _GRAPH_UTIL_H #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <cstring> #include <map> #include <cmath> #include <graph.h> #include <compare.h> #include <gsort.h> #include <pair.h> template < class G > void OutDegreeFrequencyDistribution (const G& g, fsu::Vector<size_t>& v) { std::map<size_t, size_t> degcount; size_t deg, maxdeg = 0; for (size_t i = 0; i < g.VrtxSize(); ++i) { deg = g.OutDegree(i); if (maxdeg < deg) maxdeg = deg; ++degcount[deg]; } v.SetSize(1+maxdeg,0); for(auto pr : degcount) { v[pr.first] = pr.second; } } template < class G > void OutDegreeFrequencyDistribution (const G& g, std::ostream& os = std::cout) { fsu::Vector<size_t> v(0); OutDegreeFrequencyDistribution(g,v); int cw = floor(log10(g.VrtxSize())); if (cw < 4) cw = 4; cw += 3; os << " out-degree frequency distribution:" << '\n'; os << std::setw(cw) << " deg" << std::setw(cw) << "freq" << '\n' << std::setw(cw) << " ---" << std::setw(cw) << "----" << '\n'; for (size_t i = v.Size(); i > 0; ) { --i; if (v[i] > 0) os << std::setw(cw) << i << std::setw(cw) << v[i] << '\n'; } } template < class G > bool OutDegreeFrequencyDistribution (const G& g, const char* filename) { std::ofstream ofs; ofs.open(filename); if (ofs.fail()) return 0; OutDegreeFrequencyDistribution(g,ofs); ofs.close(); return 1; } template < class G > void OutDegreeSequence (const G& g, fsu::Vector < fsu::Pair < size_t , size_t > > & degree) { degree.SetSize(g.VrtxSize()); for (size_t i = 0; i < degree.Size(); ++i) { degree[i].first_ = g.OutDegree(i); degree[i].second_ = i; } fsu::GreaterThan < fsu::Pair < size_t , size_t > > gt; fsu::g_merge_sort_bu(degree.Begin(),degree.End(),gt); } template < class G > void OutDegreeSequence (const G& g, size_t maxToDisplay, std::ostream& os = std::cout) { int cw1 = floor(log10(g.VrtxSize())); if (cw1 < 4) cw1 = 4; cw1 += 3; fsu::Vector < fsu::Pair < size_t , size_t > > degree(0); OutDegreeSequence(g,degree); size_t enough = degree.Size(); if (0 < maxToDisplay && maxToDisplay < enough) enough = maxToDisplay; if (degree.Size() == enough) os << " complete out-degree sequence:" << '\n'; else os << " top " << enough << " vertex out-degrees ranked by degree:" << '\n'; os << std::setw(cw1) << "rank" << std::setw(cw1) << "deg" << std::setw(cw1) << "vrtx" << '\n' << std::setw(cw1) << "----" << std::setw(cw1) << "---" << std::setw(cw1) << "----" << '\n'; for (size_t i = 0; i < enough; ++i) { os << std::setw(cw1) << 1 + i << std::setw(cw1) << degree[i].first_ << std::setw(cw1) << degree[i].second_ << '\n'; if (degree[i].first_ == 0 && 1 + i < degree.Size()) { os << std::setw(cw1) << '*' << std::setw(cw1) << 0 << std::setw(cw1) << " (the remaining " << (degree.Size() - i - 1) << " vertices have degree 0)\n"; break; } } } template < class G > bool OutDegreeSequence (const G& g, size_t maxToDisplay, const char* outFile) { std::ofstream outStream; outStream.open(outFile); if (outStream.fail()) { return 0;; } OutDegreeSequence(g, maxToDisplay, outStream); outStream.close(); return 1; } template < class G > bool CheckSymmetry (const G& g, bool verbose = 1, std::ostream& os = std::cout) { bool symmetric = 1; for (typename G::Vertex v = 0; v < g.VrtxSize(); ++v) { for (typename G::AdjIterator j = g.Begin(v); j != g.End(v); ++j) { if (!g.HasEdge(*j,v)) { symmetric = 0; if (verbose) { os << " ** Symmetry ALERT: graph is asymmetric at" << " (" << v << ',' << *j << ")\n"; } /* else // Carolyn Wyllis innovation { return symmetric; } // */ } } } return symmetric; } template < class G > bool Load (std::istream& inStream, G& g) { typename G::Vertex v, w; // general purpose vertex variables char ch; // general purpose file read variable // skip documentation -- '#' in column 1 ch = inStream.peek(); while (ch == '#') { ch = inStream.get(); while ((ch != '\n') && (!inStream.eof())) ch = inStream.get(); ch = inStream.peek(); } // read graph data and build graph inStream >> v; if (inStream.fail()) { std::cerr << " ** Load error: vertex size not readable\n"; return 0; } g.SetVrtxSize(v); while (inStream >> v >> w) { g.AddEdge(v,w); } return 1; } template < class G > bool Load (const char* inFile, G& g) { std::ifstream inStream; inStream.open(inFile); if (inStream.fail()) { return 0;; } bool status = Load(inStream,g); inStream.clear(); inStream.close(); return status; } template < class G > bool Save_UG (const char* filenameBase, const G& g) { size_t size = strlen(filenameBase); char filename [size+4]; strcpy(filename,filenameBase); filename[size] = '.'; filename[size+1] = 'u'; filename[size+2] = 'g'; filename[size+3] = '\0'; std::ofstream outStream; outStream.open(filename); if (outStream.fail()) { return 0;; } typename G::Vertex v; typename G::AdjIterator i; outStream << g.VrtxSize() << '\n'; for (v = 0; v < g.VrtxSize(); ++v) { for (i = g.Begin(v); i != g.End(v); ++i) { if (v < *i) outStream << v << '\t' << *i << '\n'; } } outStream.close(); std::cout << " ungraph saved as " << filename << '\n'; return 1; } template < class G > bool Save_DG (const char* filenameBase, const G& g) { size_t size = strlen(filenameBase); char filename [size+4]; strcpy(filename,filenameBase); filename[size] = '.'; filename[size+1] = 'd'; filename[size+2] = 'g'; filename[size+3] = '\0'; std::ofstream outStream; outStream.open(filename); if (outStream.fail()) { return 0;; } typename G::Vertex v; typename G::AdjIterator i; outStream << g.VrtxSize() << '\n'; for (v = 0; v < g.VrtxSize(); ++v) { for (i = g.Begin(v); i != g.End(v); ++i) { outStream << v << '\t' << *i << '\n'; } } outStream.close(); std::cout << " digraph saved as " << filename << '\n'; return 1; } template < class G > void ShowAL (const G& g, std::ostream& os = std::cout) { typedef typename G::Vertex Vertex; typename G::AdjIterator i; for (Vertex v = 0; v < g.VrtxSize(); ++v) { os << '[' << v << "]->"; i = g.Begin(v); if (i != g.End(v)) { os << *i; ++i; } for ( ; i != g.End(v); ++i) { os << ',' << *i; } os << '\n'; } } const char* GraphTypeName(const char* code) { switch(code[0]) { case 'U': switch(code[1]) { case 'L': return "undirected adjacency list"; case 'M': return "undirected adjacency matrix"; } case 'D': switch(code[1]) { case 'L': return "directed adjacency list"; case 'M': return "directed adjacency matrix"; } default: return "unknown typecode"; } } void FileSpec(std::ostream& os) { os << " -----------------------------------------------------------------------\n" << " Graph File Specs \n" << " ---------------- \n" << " 1 File documentation at beginning of file, lines begin with '#' \n" << " 2 Remainder of file consists of unsigned integers in decimal notation \n" << " 2.1 First number is vertex size \n" << " 2.2 Remaining numbers occur in pairs \n" << " 2.3 Pair represents an edge \"from\" \"to\" \n" << " 2.4 Edge vertices must be in range determined by 2.1 \n" << " -----------------------------------------------------------------------\n"; } #endif
caeca9b829276d810c334b6315694bed2eb697b8
[ "C++" ]
12
C++
ajw170/FSU-KevinBacon
07759d0731fa60702d90349b6e9bc57b5cbbee15
a8537e44474a8fed7d66e419e59b0bce366e5ec3
refs/heads/master
<repo_name>aksnell/rhythm-erd<file_sep>/rhythm.sql CREATE TABLE "Albums" ( "Id" SERIAL, "Title" TEXT NOT NULL, "IsExplicit" BOOL, "ReleaseDate" DATE, "BandID" INT, ); CREATE TABLE "Bands" ( "Id" SERIAL, "Name" TEXT, "CountyOfOrigin" CHAR(3), -- ISO County Code "Website" TEXT, "Style" TEXT, "IsSigned" BOOL, "ContactName" TEXT, "ContactPhoneNumber" BIGINT ) INSERT INTO "Bands" VALUES (DEFAULT, 'Streelight Manifesto', 'USA', 'streetlightmanifesto.com', 'Ska', TRUE, DEFAULT, DEFAULT) SELECT * FROM "Bands" INSERT INTO "Albums" VALUES (DEFAULT, 'Album Title', TRUE, '01/01/01', (SELECT "Id" FROM "Bands" WHERE "Name" = 'Streetlight Manifesto')); UPDATE "Bands" SET "IsSigned" = FALSE WHERE "Name" = '<NAME>' UPDATE "Bands" SET "IsSigned" = TRUE WHERE "Name" = '<NAME>' SELECT "Albums".* FROM "Albums" JOIN "Bands" ON "Albums"."BandID" = "Bands"."Id" SELECT * FROM "Albums" ORDER BY "ReleaseDate" SELECT * FROM "Bands" WHERE "IsSigned" SELECT * FROM "Bands" WHERE NOT "IsSigned"
3aa1851fa5dd424b0c03647c4c1e58d3193cc1fe
[ "SQL" ]
1
SQL
aksnell/rhythm-erd
a0fad01caa940120670484c9222e9d5abde50c15
7fd204a00b95049cdc0a3f4464f5ba716d47d943
refs/heads/master
<file_sep>require.config({ baseUrl: '/news-web/asset/js/', paths: { 'libs': 'libs', 'components': 'components', 'jquery': 'libs/jquery-3.1.1.min', 'lozad': 'libs/lozad.min', 'css': 'libs/css', 'semantic': 'components/semantic/semantic.min', 'pace': 'components/pace/pace.min', 'swiper': 'components/swiper/swiper.min', 'swiperAnimates': 'components/swiper/swiper.animate1.0.3.min' }, shim: { semantic: { deps: ['jquery'] }, swiper: { deps: ['css!components/swiper/swiper.min.css', 'jquery'] }, swiperAnimates: { deps: ['css!components/swiper/animate.min.css', 'jquery'] } } }); require(['pace', 'semantic', 'lozad'], function (pace, semantic, lozad) { // pace.start({ document: false }); // var observer = lozad(); observer.observe(); }) <file_sep>require(['main'], function () { require(['swiper'], function (Swiper) { var swiper = new Swiper('#focus-news-images', { pagination: { el: '.swiper-pagination', clickable: true, renderBullet: function (index, className) { return '<span class="' + className + '">' + (index + 1) + '</span>'; }, }, }); }) })
54d7b003d31192660b525e39f8d61b7914bb8b40
[ "JavaScript" ]
2
JavaScript
CrazyDissolute/news-web
5f0e3bf3b9ba18d61d93b8304b5130c7699f913b
5e1073217958e152fa12083e33000159af1575fb
refs/heads/master
<repo_name>7inug1/java_oop_chess<file_sep>/chessgui2/Chess.java /** @author <NAME> 100227640 Date finished : 6/24/19 (Mon) */ /** * * */ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; public class Chess { public static void main(String[] args) { GameControllerComponent component = new GameControllerComponent(); class MousePressedListener implements MouseListener { @Override public void mouseClicked(MouseEvent event) { // TODO Auto-generated method stub component.click(event.getX(), event.getY()); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } // Frame JFrame frame = new JFrame(); final int FRAME_WIDTH = 570; final int FRAME_HEIGHT = 600; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("Chess"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // component instantiated and then added onto the frame MousePressedListener listener = new MousePressedListener(); component.addMouseListener(listener); frame.add(component); frame.setVisible(true); // Note that you should call after set frame to visible. } } <file_sep>/chessgui2/Dummy.java /** @author <NAME> 100227640 Date finished : 6/24/19 (Mon) */ /** * * Dummy class represents an empty box of the board. */ import java.awt.Graphics2D; // 1. each piece should print itself // 2. each piece has a color // 3. each piece should report and color public class Dummy extends Piece { public Dummy(int x, int y) { super(x, y); } /** * get the type of the piece */ public int getType() { return Def.DUMMY; } /** * Draw nothing for dummy */ public void draw(Graphics2D g2) { } } <file_sep>/chessgui2/Bishop.java /** @author <NAME> 100227640 Date finished : 6/24/19 (Mon) */ /** * Class Bishop represents a Bishop piece in the chess game. * */ import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; //1. each piece should print itself //2. each piece has a color //3. each piece should report and color //in piece, 2 constructors, getColor, print, getType public class Bishop extends Piece { private BufferedImage img; public Bishop(int color, int x, int y) { super(color, x, y); try { if (color == Def.BLACK) img = ImageIO.read(new File(Def.BISHOP_BLACK)); else img = ImageIO.read(new File(Def.BISHOP_WHITE)); } catch (IOException e) { // We will learn about this later // For now just use it as is. } } /** * get the type of the piece */ public int getType() { return Def.BISHOP; } /** * Draw the piece in designated place */ public void draw(Graphics2D g2) { int offsetX = (Def.LENGTH - img.getWidth()) / 2; int offsetY = (Def.LENGTH - img.getHeight()) / 2; g2.drawImage(img, offsetX + Def.GAP + getX() * Def.LENGTH, offsetY + Def.GAP + getY() * Def.LENGTH, img.getWidth(), img.getHeight(), null); } } <file_sep>/chessgui2/Pawn.java /** @author <NAME> 100227640 Date finished : 6/24/19 (Mon) */ /** * * Class Pawn represents a Pawn piece in the chess game. */ import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.IOException; import java.io.File; public class Pawn extends Piece { private BufferedImage img; public Pawn(int color, int x, int y) { super(color, x, y); try { if (color == Def.BLACK) img = ImageIO.read(new File(Def.PAWN_BLACK)); else img = ImageIO.read(new File(Def.PAWN_WHITE)); } catch (IOException e) { // We will learn about this later // For now just use it as is. } } /** * get the type of the piece */ public int getType() { return Def.PAWN; } /** * Draw the piece in designated place */ public void draw(Graphics2D g2) { int offsetX = (Def.LENGTH - img.getWidth()) / 2; int offsetY = (Def.LENGTH - img.getHeight()) / 2; g2.drawImage(img, offsetX + Def.GAP + getX() * Def.LENGTH, offsetY + Def.GAP + getY() * Def.LENGTH, img.getWidth(), img.getHeight(), null); // g2.drawImgage(1.img, 2. x place, 3. y place, 4. image width, 5. image height) } } <file_sep>/chessgui2/ChessBoard.java /** @author <NAME> 100227640 Date finished : 6/24/19 (Mon) */ /** * * ChessBoard class */ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.BasicStroke; import java.awt.Color; import javax.swing.JComponent; public class ChessBoard { private int SIZE = 8; private Box[][] board; private Piece[][] pieces; private BasicStroke stroke; public ChessBoard() { board = new Box[SIZE][SIZE]; pieces = new Piece[SIZE][SIZE]; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { board[i][j] = new Box(Def.GAP + j * Def.LENGTH, Def.GAP + i * Def.LENGTH, Def.LENGTH); } } populate(); } /** * A method that checks whether there is a piece inside. * @param x * @param y * @return pieces */ public Piece clickedPiece(double x, double y) { for(int i=0; i<SIZE; i++) { for(int j=0; j<SIZE; j++) { if(board[i][j].isInside(x, y)) { return pieces[j][i]; } } } return null; } /** * Making a chessboard that has a switching tile. * * @param g2 */ public void draw(Graphics2D g2) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if ((i + j) % 2 == 0) board[i][j].draw(g2); else board[i][j].fill(g2); } } for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { //draw a circle of the size of the box //graphically when clicked. if(pieces[i][j].isClicked()) { Ellipse2D circle = new Ellipse2D.Double(Def.GAP + pieces[i][j].getX()* Def.LENGTH, Def.GAP + pieces[i][j].getY()*Def.LENGTH, Def.LENGTH, Def.LENGTH); g2.setColor(Color.red); g2.setStroke(new BasicStroke(5)); g2.draw(circle); } pieces[i][j].draw(g2); } } } /** * Chess coordinates : * a b c d e f g h * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 0 * * (0,0)Rook (7,0)Rook * * * * (0,7)Rook (7,7)Rook */ public void populate() { pieces[0][0] = new Rook(Def.BLACK, 0, 0); pieces[7][0] = new Rook(Def.BLACK, 7, 0); pieces[1][0] = new Knight(Def.BLACK, 1, 0); pieces[6][0] = new Knight(Def.BLACK, 6, 0); pieces[2][0] = new Bishop(Def.BLACK, 2, 0); pieces[5][0] = new Bishop(Def.BLACK, 5, 0); pieces[3][0] = new Queen(Def.BLACK, 3, 0); pieces[4][0] = new King(Def.BLACK, 4, 0); pieces[0][7] = new Rook(Def.WHITE, 0, 7); pieces[7][7] = new Rook(Def.WHITE, 7, 7); pieces[1][7] = new Knight(Def.WHITE, 1, 7); pieces[6][7] = new Knight(Def.WHITE, 6, 7); pieces[2][7] = new Bishop(Def.WHITE, 2, 7); pieces[5][7] = new Bishop(Def.WHITE, 5, 7); pieces[3][7] = new Queen(Def.WHITE, 3, 7); pieces[4][7] = new King(Def.WHITE, 4, 7); for (int i = 0; i < 8; i++) { pieces[i][1] = new Pawn(Def.BLACK, i, 1); pieces[i][6] = new Pawn(Def.WHITE, i, 6); } for (int i = 0; i < SIZE; i++) { for (int j = 2; j < SIZE - 2; j++) { pieces[i][j] = new Dummy(i, j); } } // (0,1)~(7,1) // (0,6)~(7,6) } /** * Move method that does all the parts about moving pieces. * @param from_row * @param from_column * @param to_row * @param to_column */ public void move(Piece pre, Piece after) { pieces[after.getX()][after.getY()] = pre; pieces[pre.getX()][pre.getY()] = new Dummy(pre.getX(), pre.getY()); pre.move(after.getX(), after.getY()); after = null; } //lookUp and remove method from the previous lab have been //removed as they are not required anymore. } <file_sep>/README.md # java_oop_chess GUI Chess Program made in Java
46c33f50ad8e9a5b79b88bf4900e297bcdefd6d1
[ "Markdown", "Java" ]
6
Java
7inug1/java_oop_chess
c57effd3c40662a2184bc595bf6dd8a5fb4f776d
e8cc2f8f279887f4891baac521bca345716a2f2b
refs/heads/master
<repo_name>WillxD/cons<file_sep>/header.php <!doctype html> <html lang="en" class="no-js"> <head> <meta charset="<?php bloginfo('charset'); ?>"> <!--[if IE]><![endif]--> <title><?php wp_title( '|', true, 'right' ); ?> <?php bloginfo('name'); ?></title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> <?php if ( file_exists(TEMPLATEPATH .'/favicon.ico') ) : ?> <link rel="shortcut icon" href="<?php bloginfo('template_url'); ?>/favicon.ico"> <?php endif; ?><?php if ( file_exists(TEMPLATEPATH .'/apple-touch-icon.png') ) : ?> <link rel="apple-touch-icon" href="<?php bloginfo('template_url'); ?>/apple-touch-icon.png"> <?php endif; ?><link rel="stylesheet" href="<?php bloginfo( 'stylesheet_url' ); ?>"> <?php wp_head(); ?> </head><?php $body_classes = join( ' ', get_body_class() ); ?> <!--[if lt IE 7 ]><body class="ie6 <?php echo $body_classes; ?>"><![endif]--> <!--[if IE 7 ]><body class="ie7 <?php echo $body_classes; ?>"><![endif]--> <!--[if IE 8 ]><body class="ie8 <?php echo $body_classes; ?>"><![endif]--> <!--[if IE 9 ]><body class="ie9 <?php echo $body_classes; ?>"><![endif]--> <!--[if (gt IE 9)|!(IE)]><!--><body class="<?php echo $body_classes; ?>"><!--<![endif]--> <header id="header" role="banner"> <?php if (is_home() || is_front_page()) : ?> <h1 id="logo"><a href="<?php bloginfo('url'); ?>/"><?php bloginfo('name'); ?></a></h1> <?php else : ?> <div id="logo"><a href="<?php bloginfo('url'); ?>/"><?php bloginfo('name'); ?></a></div> <?php endif; ?> <span class="f1"></span> <span class="f2"></span> <span class="f3"></span> <span class="f4"></span> <span class="f5"></span> </header> <nav id="main-nav" role="navigation"><?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?></nav> <div id="main" role="main">
81de961dbf1c19e04b9897965850e44bb51b984b
[ "PHP" ]
1
PHP
WillxD/cons
c02c6b5c9872fe8a3fb773b7a21acf25e6983d1d
910a90f95bad4da6ec00e66f6d3270c1d7a0c892
refs/heads/master
<repo_name>blossoml/ele-ui_demo1<file_sep>/src/components/table.js export var arr = [{ date: "2016-03-14", name: "胡1", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡2", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡3", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡4", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡5", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡6", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡7", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡8", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡9", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡10", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡11", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡1", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡2", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡3", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡4", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡5", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡6", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡7", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "胡8", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡9", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡10", address: "甘肃省 金昌市 永昌县 " }, { date: "2016-03-14", name: "2胡11", address: "甘肃省 金昌市 永昌县 " }, ]
e86a5f4b93ff5a8f08f4e33f6565a1013517e5cc
[ "JavaScript" ]
1
JavaScript
blossoml/ele-ui_demo1
9ed1b7edf95c83a334d31e9e08b25a1f21ca30ec
b19450c5a97e586a959179d5ed2923476199b0db
refs/heads/master
<file_sep>// // MusicViewController.swift // MusicApp // // Created by <NAME> on 09/04/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class MusicViewController: UIViewController, MPMediaPickerControllerDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet var songNameLabel: UILabel! @IBOutlet var controlSlider: UISlider! @IBOutlet var startTimeLabel: UILabel! @IBOutlet var endTimeLabel: UILabel! @IBOutlet var playPauseButton: UIButton! @IBOutlet var forwardButton: UIButton! @IBOutlet var backwardButton: UIButton! @IBOutlet var volumeView: UIView! var mediaPicker = MPMediaPickerController() let mediaQuary = MPMediaQuery.songs() var mediaPlayer = MPMusicPlayerController() override func viewDidLoad() { super.viewDidLoad() do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) let _ = try AVAudioSession.sharedInstance().setActive(true) UIApplication.shared.beginReceivingRemoteControlEvents() } catch let error as NSError { print("an error occurred when audio session category.\n \(error)") } //Create view that has volume of controller view let volumeSlider = MPVolumeView(frame: volumeView.layer.bounds) volumeView.addSubview(volumeSlider) Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) NotificationCenter.default.addObserver(self, selector:#selector(updatePlayingCurrentInfo), name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Function to pull track info and update labels @objc func updateTimer() { let currentTrack = mediaPlayer.nowPlayingItem let albumImage = currentTrack?.artwork?.image(at: imageView.bounds.size) imageView.image = albumImage songNameLabel.text = currentTrack?.title let trackDuration = currentTrack?.playbackDuration let trackElapsed = mediaPlayer.currentPlaybackTime if trackElapsed.isNaN { return } let elapsedMinutes = Int(trackElapsed / 60) let elapsedSeconds = Int(trackElapsed.truncatingRemainder(dividingBy: 60)) if elapsedSeconds < 10 { startTimeLabel.text = "\(elapsedMinutes):0\(elapsedSeconds)" } else { startTimeLabel.text = "\(elapsedMinutes):\(elapsedSeconds)" } let trackRemaining = Int(trackDuration!) - Int(trackElapsed) let remainingMinutes = trackRemaining / 60 let remainingSeconds = trackRemaining % 60 if remainingSeconds < 10 { endTimeLabel.text = "\(remainingMinutes):0\(remainingSeconds)" } else { endTimeLabel.text = "\(remainingMinutes):\(remainingSeconds)" } //set maximum value of the slider controlSlider.maximumValue = Float(trackDuration!) //changes slider to as song progresses controlSlider.value = Float(trackElapsed) // For Control Center MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle: currentTrack!.title ?? "", MPMediaItemPropertyAlbumTitle: currentTrack?.albumTitle ?? "", MPMediaItemPropertyArtist: currentTrack?.albumArtist ?? "", MPMediaItemPropertyPlaybackDuration: currentTrack?.playbackDuration ?? 0, MPNowPlayingInfoPropertyElapsedPlaybackTime: 20, MPMediaItemPropertyArtwork: currentTrack?.artwork ?? ""] } // Creating function to change labels to current track info based on previous @objc func updatePlayingCurrentInfo() { Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } // MARK : **** IBActions **** @IBAction func playPauseButtonPressed(_ sender: UIButton) { if mediaPlayer.playbackState == .paused { playPauseButton.setImage(UIImage (named: "Pause"), for: .normal) mediaPlayer.play() } else if mediaPlayer.playbackState == .playing { playPauseButton.setImage(UIImage (named: "Play"), for: .normal) mediaPlayer.pause() } else if mediaPlayer.playbackState == .stopped { playPauseButton.setImage(UIImage (named: "Pause"), for: .normal) mediaPlayer = MPMusicPlayerController.applicationMusicPlayer mediaPlayer.setQueue(with: mediaQuary) mediaPlayer.play() } } @IBAction func nextButtonPressed(_ sender: UIButton) { mediaPlayer.skipToNextItem() } @IBAction func previousButtonPressed(_ sender: UIButton) { mediaPlayer.skipToPreviousItem() } @IBAction func controlSeekSliderAction(_ sender: UISlider) { mediaPlayer.currentPlaybackTime = TimeInterval(sender.value) } @IBAction func addMusicButtonAction(_ sender: UIBarButtonItem) { mediaPicker = MPMediaPickerController(mediaTypes: .music) mediaPicker.delegate = self mediaPicker.allowsPickingMultipleItems = true present(mediaPicker, animated: true, completion: {}) } func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) { self.dismiss(animated: true, completion: nil) let selectedSongs = mediaItemCollection mediaPlayer.setQueue(with: selectedSongs) mediaPlayer.play() } func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) { self.dismiss(animated: true, completion: nil) } //response to remote control events func remoteControlReceivedWithEvent(_ receivedEvent:UIEvent) { if (receivedEvent.type == .remoteControl) { switch receivedEvent.subtype { case .remoteControlTogglePlayPause: if mediaPlayer.currentPlaybackRate > 0.0 { mediaPlayer.pause() } else { mediaPlayer.play() } case .remoteControlPlay: mediaPlayer.play() case .remoteControlPause: mediaPlayer.pause() default: print("received sub type \(receivedEvent.subtype) Ignoring") } } } }
e6e023560c85254c2d1c40a8ad9c932335729179
[ "Swift" ]
1
Swift
adityabril/musicapp
b21514f1dd903f548c04e5be7a9b7828c3b226a3
fd8cdc6ef42a02cb571ecd13ddbbd71da3fd9c33
refs/heads/master
<file_sep>package com.example.getandpostrequests import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { val apiInterface = APIClient().getClient()?.create(APIInterface::class.java) private lateinit var btnAdd: Button private lateinit var tv: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tv = findViewById(R.id.tv) btnAdd = findViewById(R.id.btnAdd) if (apiInterface != null) { apiInterface.getName().enqueue(object : Callback<Data?> { override fun onResponse(call: Call<Data?>, response: Response<Data?>) { val names = response.body()!! var text = "" for (name in names) { text += " ${name.pk}\n ${name.name}\n\n" } tv.text = text } override fun onFailure(call: Call<Data?>, t: Throwable) { Toast.makeText(applicationContext, "Error ", Toast.LENGTH_SHORT).show() } }) } btnAdd.setOnClickListener { startActivity(Intent(applicationContext, AddName::class.java)) } } }<file_sep>package com.example.getandpostrequests class Data : ArrayList<DataItem>()<file_sep>package com.example.getandpostrequests import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import retrofit2.Call import retrofit2.Callback import retrofit2.Response class AddName : AppCompatActivity() { private lateinit var ed: EditText private lateinit var btn: Button val apiInterface=APIClient().getClient()?.create(APIInterface::class.java) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_name) ed = findViewById(R.id.ed) btn = findViewById(R.id.btn) btn.setOnClickListener { val newName=DataItem(ed.text.toString()) if (apiInterface!=null){ apiInterface.addName(newName).enqueue(object : Callback<DataItem?> { override fun onResponse(call: Call<DataItem?>, response: Response<DataItem?>) { ed.setText("") Toast.makeText(applicationContext, "user added", Toast.LENGTH_SHORT).show() } override fun onFailure(call: Call<DataItem?>, t: Throwable) { Toast.makeText(applicationContext, "Error ", Toast.LENGTH_SHORT).show() } }) } }}}<file_sep>package com.example.getandpostrequests data class DataItem( val name: String, val pk: Int?=0 ) <file_sep>package com.example.getandpostrequests import retrofit2.Call import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST interface APIInterface { @GET("/custom-people/") fun getName():Call<Data> @POST("/custom-people/") fun addName(@Body obUser:DataItem):Call<DataItem> }
970fc893afc21c4ad623a14504334bdc20eded8d
[ "Kotlin" ]
5
Kotlin
fatengh/GETandPOSTRequests
a3dca4cfb6054e340c94df83c355cac38ec1bdb7
edafe30dd3ac566dda55fbc708670da3d24e09a4
refs/heads/master
<file_sep>/* <NAME> Teacher: Dr_T Inheritace1_Jayasinghe 01-05-2019 */ #include <iostream> using namespace std; class Polygon{ // base class parent protected: // child can access these int width, height, side; public: void set_values(int a, int b){ width = a; height = b; } void set_values(int c){ side = c; } }; class Rectangle : public Polygon{ public: int area(){return width * height;} }; class Triangle : public Polygon{ public: int area(){return width * height * 0.5;} }; class Pentagon : public Polygon{ public: double area(){ return (1/4)*(5*(5+2*(5^(1/2))^(1/2)))*(side*side); } }; class Decagon : public Pentagon{ public: double area(){ return (5/2)*(side^2)*((5+(2*((5)^(1/2))))^(1/2)); //return 2.5 * pow(width,2.0)*sqrt(5.0+2.0*sqrt(5.0)); } }; class Vehicle{ //parent protected: string manufacturer; public: //write a default constructeor for the vehicle Vehicle(){manufacturer = "Default Manufacturer";} //Vehicle(string m){manufacturer = m;} //write a parametized constructor for the vehicle, long way Vehicle(string m) : manufacturer(m) {} //new style for parameterized constructor. Short way void setManufacturer(string m){ manufacturer = m; } }; class Car : public Vehicle{ //child private: char transmissionType; // A or M string engineType; string color; string driveType; public: //write a default constructer for the car Car() : Vehicle(){ transmissionType = 'A'; engineType = "V6"; color = "White"; driveType = "AWD"; } //write a parametized constructor for the vehicle Car(char t, string e, string c, string d, string m): Vehicle(m){ transmissionType = t; engineType = e; color = c; driveType = d; manufacturer = "Cars default manufacturer"; } void setTransmissionType(char t){transmissionType = t;} char getTransmissionType() const {return transmissionType;} void setEngineType(string e){engineType = e;} string getEngineType() const {return engineType;} void setColor(string c){color = c;} string getColor() const {return color;} void setDriveType(string dt) {driveType = dt;} string getDriveType() const {return driveType;} //function to print the vehicle to screen void printCar(){ cout << "\nCar Details" << endl; cout << "Transmission Type: " << getTransmissionType() << endl; cout << "Engine Type: " << getEngineType() << endl; cout << "Color: " << getColor() << endl; cout << "Drive Type: " << getDriveType() << endl; cout << "Manufacturer: " << manufacturer << endl; //protected variable } }; int main() { Rectangle rect; //instantiated a child object Triangle trgl; //instantiated a child object Pentagon pent; Decagon deca; rect. set_values(4, 5); //call the parent's member trgl.set_values(4, 5); //call the parent's member pent.set_values(5); deca.Polygon::set_values(4,1); //calling the parent set values deca.set_values(4); cout << "Rectangle Area: " << rect.area() << endl; //call the child's area() member cout << "Triangle Area: " << trgl.area() << endl; //call the child's area() member cout << "Pentagon Area: " << pent.area() << endl; cout << "Decagon Area: " << deca.area() << endl; char t = '\0'; string e = "", c = "", d = "", m = ""; cout << "t [space] e [space] c [space] d [space] m: " << endl; cin >> t >> e >> c >> d >> m; Car(t,e,c,d,m); // call the paramertized constructor Car genesis; genesis.printCar(); // print the child return 0; }
c43ac98d3dbba19e853d85469214f93ff582d7b8
[ "C++" ]
1
C++
vibhavicharm/Inheritance1_Jayasinghe
42452ffd73651d3fbf9e5e74799b7873be8cb8eb
f98616e1e2ea5e1c8658f0451470e12a247f7ae8
refs/heads/master
<repo_name>darder44/test001<file_sep>/test/xxxxxTest.php <?php use PHPUnit\Framework\TestCase; class HelloTest extends TestCase { function testHello() { $this->assertEquals('bar', 'bar'); } function testLogin2() { $this->assertEquals('xxx', 'xxx'); } function testHello_Failed() { $this->assertEquals('bar', 'bars'); } } ?>
34494dcb7edae2f80f97ff7f5ee98f5b3ab4fa20
[ "PHP" ]
1
PHP
darder44/test001
a2796bac283ce3fa90e8524f84b8bb2145835964
c09cbf9e8ff9a26c0d99e39fa02c8c6f952f3742
refs/heads/master
<repo_name>claesn/vedaweb<file_sep>/vedaweb-frontend/src/LegalNotice.js import React, { Component } from "react"; import { Row, Col, Icon } from 'antd'; class ContentView extends Component { render() { document.title = "VedaWeb | Legal Notice"; return ( <Row type="flex" justify="center" className="page-content"> <Col xl={14} lg={18} md={20} sm={24}> <div className="card"> <h4><Icon type="paper-clip"/> Legal Notice</h4> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> </div> </Col> </Row> ); } } export default ContentView;<file_sep>/vedaweb-frontend/src/SearchGrammar.js import React, { Component } from "react"; import { Row, Col, Icon } from 'antd'; import { view } from 'react-easy-state'; import searchGrammarStore from "./stores/searchGrammarStore"; import SearchBlock from "./SearchBlock"; import HelpButton from "./HelpButton"; import './css/SearchGrammar.css' class SearchGrammar extends Component { constructor(props){ super(props); this.addBlock = this.addBlock.bind(this); this.removeBlock = this.removeBlock.bind(this); } componentDidMount(){ if (searchGrammarStore.data.blocks.length === 0) this.addBlock(); } addBlock(){ searchGrammarStore.addBlock(); } removeBlock(blockId){ searchGrammarStore.removeBlock(blockId); } render() { const {data} = searchGrammarStore; return ( <div className="search-container"> <HelpButton type="grammarSearch" /> <div className="search-block-list top-gap"> {data.blocks.map((block, i) => ( <SearchBlock key={block.id} id={block.id} form={block.form} distance={block.distance} isFirstBlock={i === 0} fields={block.fields} showRemoveButton={data.blocks.length > 1} onRemoveBlock={this.removeBlock} /> ))} <Row className={"search-block-list-controls" + (data.blocks.length >= 4 ? " hidden" : "")} type="flex" align="middle"> <Col span={1}> <div className={"search-block-add content-center"} onClick={this.addBlock}> <Icon type="plus"/> </div> </Col> <Col span={23} className="secondary-font translucent font-18"> <Icon type="arrow-left" className="gap-left-big"/> Click here to add additional search terms </Col> </Row> </div> </div> ); } } export default view(SearchGrammar);<file_sep>/vedaweb-frontend/src/ErrorMessage.js import React, { Component } from "react"; import { Icon } from 'antd'; class ErrorMessage extends Component { render() { return ( <div className="card-nobox content-center secondary-font"> <div className="inline-block content-left"> <Icon type="meh-o" className="gap-right" /> <b>There was an error requesting the data.</b> <br/> <br/> <Icon type="info-circle-o" className="gap-right" /> This might be for one of the following reasons: <br/> <ul style={{"marginTop":"1rem"}}> <li>You requested a document that simply doesn't exist</li> <li>Someone gave you the URL to this page and you missed a few characters copying it</li> <li>The syntax of your search request was invalid</li> <li>There is some technical problem with our server</li> </ul> </div> </div> ); } } export default ErrorMessage;<file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/data/VerseVersion.java package de.unikoeln.vedaweb.data; public class VerseVersion { private String id; private String source; private String language; private String[] form; private String type; public VerseVersion( String source, String language, String[] form, String type) { super(); this.source = source; this.language = language; this.form = form; this.type = type; generateId(); } public String getId() { return this.id; } public void generateId() { this.id = (type + "_" + source.replaceAll("\\P{L}", "")).toLowerCase(); } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String[] getForm() { return form; } public void setForm(String[] form) { this.form = form; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return source + " (" + language + ")"; } } <file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/search/SearchData.java package de.unikoeln.vedaweb.search; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonProperty; public class SearchData { @JsonProperty("mode") private String mode; @JsonProperty("input") private String input; @JsonProperty("field") private String field; @JsonProperty("scopes") private List<SearchScope> scopes; @JsonProperty("meta") private Map<String, String[]> meta; @JsonProperty("blocks") private List<Map<String, Object>> blocks; @JsonProperty("from") private int from; @JsonProperty("size") private int size; public SearchData(){ blocks = new ArrayList<Map<String, Object>>(); } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public String getInput() { return input; } public void setInput(String input) { this.input = input.trim(); } public String getField() { return field; } public void setField(String field) { this.field = field; } public List<SearchScope> getScopes() { return scopes; } public void setScopes(List<SearchScope> scopes) { this.scopes = scopes; } public Map<String, String[]> getMeta() { return meta; } public void setMeta(Map<String, String[]> meta) { this.meta = meta; } public List<Map<String, Object>> getBlocks() { return blocks; } public void setBlocks(List<Map<String, Object>> blocks) { this.blocks = blocks; } public void addBlock(Map<String, Object> block) { this.blocks.add(block); } public int getFrom() { return from; } public void setFrom(int from) { this.from = from; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } @Override public String toString() { return "mode:" + mode + (input != null ? " input:" + input : ""); } public void cleanAndFormatFields(){ //clean search blocks for (Map<String, Object> block : blocks){ block.values().removeAll(Collections.singleton("")); for (String field : block.keySet()){ if (block.get(field) instanceof String && ((String)block.get(field)).matches("-?\\d+")){ block.put(field, Integer.parseInt(((String)block.get(field)))); } } } //clean search scopes if (scopes != null) scopes.stream() .filter(scope -> !scope.isEmpty()) .collect(Collectors.toList()); } } <file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/controllers/SearchController.java package de.unikoeln.vedaweb.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import de.unikoeln.vedaweb.search.SearchData; import de.unikoeln.vedaweb.search.SearchHits; import de.unikoeln.vedaweb.services.ElasticSearchService; import de.unikoeln.vedaweb.services.MappingService; @RestController @RequestMapping("api") public class SearchController { @Autowired private ElasticSearchService search; @Autowired private MappingService mappingService; @PostMapping(value = "/search", produces = {"application/json"}) public String searchView(@RequestBody SearchData searchData) { SearchHits hits = new SearchHits(search.search(searchData)); return mappingService.mapObjectToJSON(hits); } } <file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/util/XmlDataImport.java package de.unikoeln.vedaweb.util; import java.io.File; import java.util.List; import javax.xml.transform.stream.StreamSource; import de.unikoeln.vedaweb.data.Pada; import de.unikoeln.vedaweb.data.Token; import de.unikoeln.vedaweb.data.Verse; import de.unikoeln.vedaweb.data.VerseVersion; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.SaxonApiUncheckedException; import net.sf.saxon.s9api.XPathCompiler; import net.sf.saxon.s9api.XdmItem; import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmValue; public class XmlDataImport { public static void collectVersesFromXML(File xmlFile, List<Verse> versesList) throws SaxonApiException{ //xml parsing prep Processor processor = new Processor(false); XdmNode xmlDoc = processor.newDocumentBuilder().build(new StreamSource(xmlFile)); XPathCompiler compiler = processor.newXPathCompiler(); //compiler.declareNamespace("xml", "http://www.tei-c.org/ns/1.0"); //iterate: hymns XdmValue hymns = compiler.evaluate(".//*:div[@type='hymn']", xmlDoc); for(XdmItem hymn : hymns){ //collect hymn data String hymnAddressee = compiler.evaluate("*:div[@type='dedication']/*:div[@type='addressee']/*:p[@*:lang='en']/text()[1]", hymn) .itemAt(0).getStringValue(); String hymnGroup = compiler.evaluate("*:div[@type='dedication']/*:div[@type='group']/*:p[@*:lang='en']/text()[1]", hymn) .itemAt(0).getStringValue(); int hymnAbs = Integer.parseInt(compiler.evaluate("@*:ana", hymn) .itemAt(0).getStringValue()); //iterate: verses XdmValue verses = compiler.evaluate("*:div[@type='verse']", hymn); for(XdmItem verse : verses){ String[] verseLocationData = compiler.evaluate("@*:n", verse).itemAt(0).getStringValue().split("\\."); //verse obj data Verse verseObj = new Verse(); verseObj.setBook(Integer.parseInt(verseLocationData[0])); verseObj.setHymn(Integer.parseInt(verseLocationData[1])); verseObj.setVerse(Integer.parseInt(verseLocationData[2])); verseObj.setHymnAbs(hymnAbs); verseObj.setId(verseLocationData[0] + verseLocationData[1] + verseLocationData[2]); verseObj.setHymnAddressee(hymnAddressee); verseObj.setHymnGroup(hymnGroup); verseObj.setStrata(compiler.evaluate("*:lg[@*:source='gunkel_ryan']/*:lg/*:fs/*:f[@*:name='strata']/text()", verse).itemAt(0).getStringValue()); //iterate: padas int padaIndex = 0; XdmValue padaForms = compiler.evaluate("*:lg[@*:source='zurich']/*:l[@*:n]", verse); for (XdmItem padaForm : padaForms){ String padaId = compiler.evaluate("@*:n", padaForm).itemAt(0).getStringValue(); String padaXmlId = compiler.evaluate("@*:id", padaForm).itemAt(0).getStringValue().replaceFirst("_zur$", "_tokens_zur"); XdmValue padaTokens = compiler.evaluate("*:lg[@*:source='zurich']/*:l[@*:id='" + padaXmlId + "']/*:fs", verse); verseObj.addPada(generatePadaObject( verse, padaIndex, padaId, padaForm.getStringValue(), padaTokens, compiler )); padaIndex++; } //set token indices int tokenIndex = 0; for (Pada p : verseObj.getPadas()){ for (Token t : p.getTokens()){ t.setIndex(tokenIndex++); } } //// verse versions (translations etc.) //// XdmValue temp; XdmItem versionNode; VerseVersion version; String[] versionForm; // SAMITHA / gunkel_ryan temp = compiler.evaluate("*:l[@*:source='grassmann']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l[@*:ana='samitha']", versionNode)); version = new VerseVersion( "Samitha (Gunkel, Ryan)", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // Samitha / gunkel_ryan temp = compiler.evaluate("*:lg[@*:source='gunkel_ryan']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l[@*:ana='samhita']", versionNode)); version = new VerseVersion( "<NAME>", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // SASA PATHA / lubotsky temp = compiler.evaluate("*:lg[@*:source='gunkel_ryan']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l[@*:ana='sasa_patha']", versionNode)); version = new VerseVersion( "Lubotsky", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // <NAME> / vnh temp = compiler.evaluate("*:lg[@*:source='vnh']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l", versionNode)); version = new VerseVersion( "<NAME>", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // Aufrecht / aufrecht temp = compiler.evaluate("*:lg[@*:source='aufrecht']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l", versionNode)); version = new VerseVersion( "Aufrecht", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // Padapatha / padapatha temp = compiler.evaluate("*:l[@*:source='padapatha']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = new String[]{versionNode.getStringValue().replaceAll("\\s+", " ").trim()}; version = new VerseVersion( "Padapatha", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // Devanagari / detlef temp = compiler.evaluate("*:lg[@*:source='detlef']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l", versionNode)); version = new VerseVersion( "Detlef", compiler.evaluate("@*:lang", versionNode).itemAt(0).getStringValue(), versionForm, "version" ); verseObj.addVersion(version); } // Translation (de) / geldner temp = compiler.evaluate("*:l[@*:source='geldner']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = new String[]{versionNode.getStringValue()}; version = new VerseVersion( "Geldner", "de", versionForm, "translation" ); verseObj.addVersion(version); } // Translation (de) / grassmann temp = compiler.evaluate("*:l[@*:source='grassmann']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = new String[]{versionNode.getStringValue()}; version = new VerseVersion( "Graßmann", "de", versionForm, "translation" ); verseObj.addVersion(version); } // Translation (de) / otto temp = compiler.evaluate("*:l[@*:source='otto']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = new String[]{versionNode.getStringValue()}; version = new VerseVersion( "Otto", "de", versionForm, "translation" ); verseObj.addVersion(version); } // Translation (en) / griffith temp = compiler.evaluate("*:lg[@*:source='griffith']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = concatTextContents(compiler.evaluate(".//*:l", versionNode)); version = new VerseVersion( "Griffith", "en", versionForm, "translation" ); verseObj.addVersion(version); } // Translation (de) / mac donell temp = compiler.evaluate("*:l[@*:source='macdonell']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = new String[]{versionNode.getStringValue()}; version = new VerseVersion( "MacDonell", "en", versionForm, "translation" ); verseObj.addVersion(version); } // Translation (fr) / renou temp = compiler.evaluate("*:l[@*:source='renou']", verse); if (temp.size() > 0) { versionNode = temp.itemAt(0); versionForm = new String[]{versionNode.getStringValue()}; version = new VerseVersion( "Renou", "fr", versionForm, "translation" ); verseObj.addVersion(version); } //add verse object to verses list versesList.add(verseObj); } } } private static Pada generatePadaObject( XdmItem verse, int padaIndex, String padaId, String padaForm, XdmValue padaTokens, XPathCompiler compiler) throws IndexOutOfBoundsException, SaxonApiUncheckedException, SaxonApiException{ Pada pada = new Pada(); pada.setForm(padaForm); pada.setIndex(padaIndex); pada.setLine(padaId.charAt(padaId.length() - 1)); //label (by gunkel/ryan) String padaXmlId = compiler.evaluate("@*:id", padaTokens.itemAt(0)) .itemAt(0).getStringValue().replaceFirst("_\\d\\d_zur$", "_gunkel_ryan"); XdmValue strataNode = compiler.evaluate("*:lg[@*:source='gunkel_ryan']/*:lg[@*:id='" + padaXmlId + "']/*:fs/*:f[@*:name='label']/text()", verse); if (strataNode.size() > 0) pada.setLabel(strataNode.itemAt(0).getStringValue()); for (XdmItem token : padaTokens){ Token tokenObj = new Token(); XdmValue graLemmaNode = compiler.evaluate("*:f[@*:name='gra_lemma']/*:string", token); XdmValue graGrammNode = compiler.evaluate("*:f[@*:name='gra_gramm']/*:symbol/@*:value", token); XdmValue formNode = compiler.evaluate("*:f[@*:name='surface']/*:string", token).itemAt(0); XdmValue tokenAttributes = compiler.evaluate("*:f[@*:name='morphosyntax']/*:fs/*:f", token); if (graLemmaNode.size() > 0) { tokenObj.setLemma(((XdmNode)graLemmaNode.itemAt(0)).getStringValue()); tokenObj.setLemmaRef(extractLemmaRefs((XdmNode)graLemmaNode)); } tokenObj.setForm(((XdmNode)formNode).getStringValue().trim()); //iterate token attributes for (XdmItem tokenAttribute : tokenAttributes){ String attName = compiler.evaluate("@*:name", tokenAttribute).itemAt(0).getStringValue(); String attValue = compiler.evaluate("*:symbol/@*:value", tokenAttribute).itemAt(0).getStringValue(); tokenObj.addGrammarAttribute(attName, attValue); } //lemma-type if (graGrammNode.size() > 0) tokenObj.addGrammarAttribute("lemma type", ((XdmNode)graGrammNode.itemAt(0)).getStringValue()); //add to tokens pada.addToken(tokenObj); } return pada; } private static String[] extractLemmaRefs(XdmNode token) { //sample for lemmaRef attribute value: "#lemma_id_1695 #lemma_iq_1681" return token.getAttributeValue(new QName("source")) .replaceAll("#", "") .split("\\s+"); } private static String[] concatTextContents(XdmValue nodes) { String[] lines = new String[nodes.size()]; for (int i = 0; i < lines.length; i++) { lines[i] = nodes.itemAt(i).getStringValue(); } return lines; } } <file_sep>/vedaweb-frontend/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; import { BrowserRouter as Router } from 'react-router-dom' import Browserizr from 'browserizr'; //just alert if IE or mobile if (Browserizr.is_ie) { alert("We suspect you are using the Internet Explorer.\nUnfortunately, VedaWeb only works with modern web browsers.\nYou will need to use Firefox, Chrome or something similar instead."); } else if (Browserizr.is_mobile) { alert("We suspect you are using a mobile device.\nUnfortunately, VedaWeb is not designed to work on mobile devices. You will need to try to use a desktop browser instead."); } else{ //render app ReactDOM.render( <Router basename={process.env.PUBLIC_URL}> <App /> </Router> , document.getElementById('root') ); registerServiceWorker(); } <file_sep>/vedaweb-frontend/src/Footer.js import React, { Component } from "react"; import { Row, Col } from 'antd'; import logoCPDO from "./img/logo_cpdo.png"; import logoCSALT from "./img/logo_csalt.png"; import logoCSALTAPI from "./img/logo_csalt_api.png"; import logoCSL from "./img/logo_csl.png"; import logoTCSL from "./img/logo_tcsl.png"; import { Link } from 'react-router-dom'; import "./css/Footer.css"; class Footer extends Component { render() { return ( <div id="footer" className="box-shadow"> <Row type="flex" justify="center" align="top"> <Col span={3} className="footer-box"> <a href="http://c-salt.uni-koeln.de" target="_blank" rel="noopener noreferrer"> <div className="footer-box"> <img src={logoCSALT} alt="" /><br/><br/> C-SALT </div> </a> </Col> <Col span={3} className="footer-box"> <a href="http://sanskrit-lexicon.uni-koeln.de" target="_blank" rel="noopener noreferrer"> <div className="footer-box"> <img src={logoCSL} alt="" /><br/><br/> Cologne Sanskrit<br/>Lexicon </div> </a> </Col> <Col span={3}> <a href="http://sanskrit-lexicon.uni-koeln.de/csl" target="_blank" rel="noopener noreferrer"> <div className="footer-box"> <img src={logoTCSL} alt="" /><br/><br/> TEI Cologne Sanskrit<br/>Lexicon </div> </a> </Col> <Col span={3} className="footer-box"> <a href="http://cpd.uni-koeln.de" target="_blank" rel="noopener noreferrer"> <div className="footer-box"> <img src={logoCPDO} alt="" /><br/><br/> Critical Pāli<br/>Dictionary Online </div> </a> </Col> <Col span={3} className="footer-box"> <a href="https://api.c-salt.uni-koeln.de/" target="_blank" rel="noopener noreferrer"> <div className="footer-box"> <img src={logoCSALTAPI} alt="" /><br/><br/> C-SALT APIs<br/>for Dictionaries </div> </a> </Col> </Row> <Row className="top-gap"> <Col span={24} className="content-center"> <div style={{padding: '3rem 0'}}> <Link to="/legal">Legal Notice</Link> <span className="gap-left-big gap-right-big">&#8213;</span> <Link to="/privacy">Privacy Notice</Link> </div> </Col> </Row> </div> ); } } export default Footer;<file_sep>/vedaweb-backend/legacy-classes/VWIndexTest.java package de.unikoeln.vedaweb.legacy; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import de.unikoeln.vedaweb.services.ElasticService; import de.unikoeln.vedaweb.services.SearchService; public class VWIndexTest { // private MongoClient mongoClient; // private MongoDatabase database; // private MongoCollection<Document> collection; // private IndexService index; // private SearchService search; // // // public static void main(String[] args) { // VWIndexTest vwit = new VWIndexTest(); // vwit.init(); // // Scanner scan = new Scanner(System.in); // String input; // while (!(input = scan.nextLine()).equals("exit")){ // //vwit.search(input); // } // scan.close(); // // vwit.shutdown(); // } // // // private void init(){ // System.out.println("[INFO] Initializing..."); // // search = new SearchService(); // // index = new IndexService(); // index.init(); // // if (!index.indexExists()){ // mongoClient = new MongoClient("localhost"); // database = mongoClient.getDatabase("temp"); // collection = database.getCollection("merged"); // index.createIndex(collection.find().iterator()); // } else { // System.out.println("[INFO] Index already exists."); // } // // System.out.println("[INFO] Initialization done."); // } // // // private void search(String queryString){ // SearchRequest sr = new SearchRequest(); // // for (String query : queryString.split("\\s*\\&\\s*")){ // Map<String, Object> searchBlock = new HashMap<String, Object>(); // for (String queryPart : query.split(" ")){ // String[] queryPartElements = queryPart.split(":"); // searchBlock.put(queryPartElements[0], queryPartElements[1].matches("\\d+") ? Integer.parseInt(queryPartElements[1]) : queryPartElements[1]); // } // sr.addBlock(searchBlock); // } // // SearchResults results = search.search(sr); // System.out.println("[INFO] Final # of results after joining: " + results.size()); // // for (SearchResult result : results.getSortedResultsList()){ // System.out.println(result); // } // } // // // private void shutdown(){ // if (mongoClient != null) // mongoClient.close(); // } // } <file_sep>/vedaweb-frontend/src/SearchResults.js import React, { Component } from "react"; import { Table } from 'antd'; import { Link, withRouter } from 'react-router-dom'; import ErrorMessage from "./ErrorMessage"; import './css/SearchResults.css'; import { view } from 'react-easy-state'; import axios from 'axios'; import { Base64 } from 'js-base64'; import searchResultsStore from "./stores/searchResultsStore"; const fieldDisplayMapping = { "form": "Verse text", "form_raw": "Verse text", "translation": "Translation", "lemmata": "Lemmata", "lemmata_raw": "Lemmata" } class SearchResults extends Component { constructor(props) { super(props) this.state = { isLoaded: false } document.title = "VedaWeb | Search Results"; this.loadData = this.loadData.bind(this); this.handleTableChange = this.handleTableChange.bind(this); this.handleTableChange = this.handleTableChange.bind(this); this.handleNewQuery = this.handleNewQuery.bind(this); } componentDidMount(){ this.handleNewQuery(this.props.match.params.querydata); } componentDidUpdate(){ if (searchResultsStore.queryEncoded !== this.props.match.params.querydata) this.handleNewQuery(this.props.match.params.querydata); } handleTableChange(pagination) { searchResultsStore.page = pagination.current; searchResultsStore.size = pagination.pageSize; this.loadData(searchResultsStore.queryJSON); } handleNewQuery(queryData) { this.setState({ isLoaded: false }); searchResultsStore.queryEncoded = queryData; searchResultsStore.page = 1; let queryJSON = {}; try { queryJSON = JSON.parse(Base64.decode(queryData)); queryJSON.from = 0; queryJSON.size = searchResultsStore.size; searchResultsStore.queryJSON = queryJSON; } catch (e) { this.setState({ isLoaded: true, error: "Invalid search data." }); return; } this.loadData(queryJSON); } loadData = (queryJSON) => { //console.log("QUERY: " + JSON.stringify(queryJSON)); let queryDisplay = queryJSON.mode === "grammar" ? "grammar search" : queryJSON.input; this.setState({ isLoaded: false, error: undefined, queryDisplay: queryDisplay }); document.title = "VedaWeb | Search Results for '" + queryDisplay + "'"; queryJSON.from = ((searchResultsStore.page - 1) * searchResultsStore.size); queryJSON.size = searchResultsStore.size; //request search api data axios.post(process.env.PUBLIC_URL + "/api/search", queryJSON) .then((response) => { //console.log(JSON.stringify(response.data)); searchResultsStore.resultsData = response.data; searchResultsStore.total = response.data.total; this.setState({ isLoaded: true, tableData: response.data.hits === undefined ? {} : response.data.hits.map( (hit, i) => ({ key: 'result_' + i, location: hit.docId, text: <div dangerouslySetInnerHTML={this.createHighlightHTML(hit)}></div>, addressee: hit.hymnAddressee, group: hit.hymnGroup, strata: hit.verseStrata })) }); }) .catch((error) => { this.setState({ isLoaded: true, error: error }); }); } createHighlightHTML(hit) { let html = ""; if (hit.highlight !== undefined && Object.keys(hit.highlight).length > 0){ Object.keys(hit.highlight).forEach(highlightField => { html += "<span class='red main-font'>" + (fieldDisplayMapping[highlightField] !== undefined ? fieldDisplayMapping[highlightField] : highlightField) + ":</span> " + hit.highlight[highlightField] + "<br/>"; }); } else if (hit.source.tokens !== undefined){ html += hit.source.tokens.map(t => ( " " + t.form + " (" + Object.keys(t.grammar).filter(k => k !== "lemma type").map(key => t.grammar[key])) + ")" ); } else { html += hit.source.form_raw.join(" / "); } return {__html: html}; } render() { const { error, isLoaded } = this.state; const data = searchResultsStore.resultsData; //define table columns const columns = [{ title: 'Location', dataIndex: 'location', key: 'location', className: 'loc-col', render: loc => <Link to={"/view/id/" + loc}>{loc}</Link>, }, { title: 'Text', dataIndex: 'text', key: 'text', render: content => <span className="text-font">{content}</span> }, { title: 'Addressee', dataIndex: 'addressee', key: 'addressee', render: content => <span className="text-font">{content}</span> }, { title: 'Group', dataIndex: 'group', key: 'group', render: content => <span className="text-font">{content}</span> }, { title: 'Strata', dataIndex: 'strata', key: 'strata', }]; return ( <div className="page-content"> {/** ERROR **/} { isLoaded && error !== undefined && <ErrorMessage/> } {/** SEARCH RESULT VIEW **/} { error === undefined && <div id="search-results" className="card"> <h4> Search Results for <span className="text-font grey">"{this.state.queryDisplay}"</span> </h4> {/** SEARCH STATS **/} <div className="search-stats secondary-font"> { isLoaded && data.hits !== undefined ? data.total > 0 ? <span>Found { data.total } matching verses in { data.took } ms</span> : "" : <span>Searching ...</span> } </div> {/** RESULTS **/} <Table columns={columns} dataSource={this.state.tableData} loading={!this.state.isLoaded} locale={{emptyText: 'There are no results for this search.'}} pagination={{ pageSize: searchResultsStore.size, current: searchResultsStore.page, total: searchResultsStore.total, position: 'both', showSizeChanger: true, pageSizeOptions: ['10','25','50','100'] }} onChange={this.handleTableChange} /> </div> } </div> // </Spin> ); } } export default withRouter(view(SearchResults));<file_sep>/vedaweb-frontend/src/FeedbackModal.js import React, { Component } from "react"; import { Modal, Input, Button } from 'antd'; import axios from 'axios'; import logo from './img/logo.png'; import RichTextEditor from 'react-rte'; import "./css/FeedbackModal.css"; const modalHeader = <div className="secondary-font red bold"> <img src={logo} alt="" style={{height:"32px", paddingRight:"1rem"}}/> <span style={{verticalAlign:"middle"}}>Beta Feedback</span> </div>; const toolbarConfig = { // Optionally specify the groups to display (displayed in the order listed). display: ['INLINE_STYLE_BUTTONS', 'BLOCK_TYPE_BUTTONS', 'LINK_BUTTONS'], INLINE_STYLE_BUTTONS: [ {label: 'Bold', style: 'BOLD', className: 'custom-css-class'}, {label: 'Italic', style: 'ITALIC'}, {label: 'Underline', style: 'UNDERLINE'} ], BLOCK_TYPE_BUTTONS: [ {label: 'UL', style: 'unordered-list-item'}, {label: 'OL', style: 'ordered-list-item'} ] }; class FeedbackModal extends Component { constructor(props) { super(props); this.state = { isLoaded: true, error: undefined, sentFeedback: false, senderName: '', message: RichTextEditor.createValueFromString('','html') } this.close = this.close.bind(this); this.sendFeedback = this.sendFeedback.bind(this); } sendFeedback(){ this.setState({ isLoaded: false, error: undefined, sentFeedback: false }); axios.post("api/feedback", {senderName: this.state.senderName, message: this.state.message.toString('html')}) .then((response) => { this.setState({ isLoaded: true, error: undefined, sentFeedback: true }); }) .catch((error) => { this.setState({ isLoaded: true, error: error, sentFeedback: false }); }); } close(){ this.setState({ isLoaded: true, error: undefined, sentFeedback: false, senderName: '', message: RichTextEditor.createValueFromString('','html') }); this.props.onCancel(); } render() { const {isLoaded, error, sentFeedback, message, senderName} = this.state; const footer = [ <Button key="cancel" onClick={this.close}>Close</Button>, <Button key="submit" type="primary" loading={!isLoaded} onClick={this.sendFeedback} disabled={sentFeedback}> Send </Button>, ]; return ( <Modal title={modalHeader} destroyOnClose centered footer={footer} onCancel={this.close} visible={this.props.visible}> {!sentFeedback && <div> <Input value={senderName} onChange={e => this.setState({senderName: e.target.value})} placeholder="Your name"/> <br/><br/> <RichTextEditor toolbarConfig={toolbarConfig} lines={8} placeholder="Your feedback message" value={message} onChange={v => this.setState({message: v})} editorClassName="feedback-editor"/> </div> } {sentFeedback && isLoaded && error === undefined && <div> <span className="bold">Thank you for your feedback!</span> </div> } </Modal> ); } } export default FeedbackModal;<file_sep>/vedaweb-frontend/src/SearchBlock.js import React, { Component } from "react"; import { Row, Col, Icon, Input, Tooltip, Select } from 'antd'; import searchGrammarStore from "./stores/searchGrammarStore"; import searchMetaStore from "./stores/searchMetaStore"; import { view } from 'react-easy-state'; import SearchAttributeField from "./SearchAttributeField"; import TransliterationPreview from "./TransliterationPreview"; import './css/SearchBlock.css'; const Option = Select.Option; const distanceOptions = Array(10).fill(0).map((e, i) => ( i === 0 ? "none" : i + " token" + (i > 1 ? "s" : "") )); class SearchBlock extends Component { render() { const transliteration = ( <TransliterationPreview input={this.props.form} transliteration={searchMetaStore.transliteration}/> ); return ( <Row type="flex" align="middle" className="search-block"> <Col span={1}> <div className={'search-block-tab content-center' + (!this.props.showRemoveButton ? ' hidden' : '')} onClick={() => this.props.onRemoveBlock(this.props.id)}> <Icon type="close"/> </div> </Col> <Col span={23}> <Row type="flex" align="middle" justify="center"> <Col span={9} className="search-input-label content-right"> <span className="secondary-font font-18">Search term:</span> </Col> <Col span={9}> <Tooltip title={transliteration} overlayClassName="transliteration-tooltip" trigger="focus" placement="bottom"> <Input value={this.props.form} onChange={e => searchGrammarStore.updateForm(this.props.id, e.target.value)} placeholder="(optional)" className="search-block-input" /> </Tooltip> </Col> <Col span={4}> {/* ??? */} </Col> </Row> <Row type="flex" align="middle" justify="center" className={true || this.props.isFirstBlock ? "hidden" : ""}> <Col span={9} className="search-input-label content-right"> <span className="secondary-font">Maximum distance to previous term:</span> </Col> <Col span={9} className="search-block-input"> <Select value={this.props.distance} onSelect={(value, o) => searchGrammarStore.updateDistance(this.props.id, value)} disabled={this.props.isFirstBlock} style={{ width: '100%' }} > {distanceOptions.map((e, i) => ( <Option key={'distance_' + this.props.id + '_' + i} value={i}>{e}</Option> ))} </Select> </Col> <Col span={4}></Col> </Row> {this.props.fields.map((field, i) => ( <SearchAttributeField key={field.id} id={field.id} parentBlockId={this.props.id} fieldName={field.name} fieldValue={field.value} isRemovable={this.props.fields.length > 1} isLastField={this.props.fields.length < 4 && this.props.fields.length === i + 1} grammarData={this.props.grammarData} /> ))} </Col> </Row> ); } } export default view(SearchBlock);<file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/search/SearchHit.java package de.unikoeln.vedaweb.search; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; public class SearchHit implements Comparable<SearchHit>{ private float score; private String docId; private Map<String, String> highlight; private String hymnAddressee; private String hymnGroup; private String verseStrata; private Map<String, Object> source; public SearchHit() { this.highlight = new HashMap<String, String>(); } @JsonProperty("score") public float getScore() { return score; } public void setScore(float score) { this.score = score; } @JsonProperty("docId") public String getDocId() { return docId; } public void setDocId(int book, int hymn, int verse) { this.docId = String.format("%02d", book) + "." + String.format("%03d", hymn) + "." + String.format("%02d", verse); } @JsonProperty("highlight") public Map<String, String> getHighlight(){ return highlight; } public void addHighlight(String label, String highlight) { this.highlight.put(label, highlight); } @JsonProperty("hymnAddressee") public String getHymnAddressee() { return hymnAddressee; } public void setHymnAddressee(String hymnAddressee) { this.hymnAddressee = hymnAddressee; } @JsonProperty("hymnGroup") public String getHymnGroup() { return hymnGroup; } public void setHymnGroup(String hymnGroup) { this.hymnGroup = hymnGroup; } @JsonProperty("verseStrata") public String getVerseStrata() { return verseStrata; } public void setVerseStrata(String verseStrata) { this.verseStrata = verseStrata; } @JsonProperty("source") public Map<String, Object> getSource() { return source; } public void setSource(Map<String, Object> source) { this.source = source; } @Override public int compareTo(SearchHit o) { return (int) (o.getScore() - score); } @Override public boolean equals(Object obj) { return obj != null && obj instanceof SearchHit && ((SearchHit)obj).getDocId().equals(docId); } @Override public int hashCode() { return docId.hashCode(); } @Override public String toString() { return docId + "\t(" + score + ")"; } } <file_sep>/vedaweb-frontend/src/HelpButton.js import React, { Component } from "react"; import { Icon, Modal } from 'antd'; import help from "./img/help.png"; import "./css/HelpButton.css"; const helpTexts = { transliteration: { title: "Input Transliteration", content: <div> <p> You can select one of the available transliteration standards for your search inputs. This setting also applies to the Quick Search in the page header and will be saved as long as you stay on this website. </p> </div> }, start: { title: "There you go!", content: <div> <p> Right, this is how it works. But this particular help button was meant for demonstration purposes only. </p> </div> }, grammarSearch : { title: "Grammar Search", content: <div> <p> Using the grammar search, you can find verses containing terms with certain grammatical properties. </p> <p> Define a search term (optional) and select an attribute (like case, number, person, etc.) and the value you are looking for (optional). This will also search for matching lemmata. You may add more properties to your search term by clicking the plus-button to the right. </p> <p> To add more than one term to find in a verse, click on the plus-button below. This will display another block which lets you define the additional term. </p> </div> }, searchScope : { title: "Search Range", content: <div> <p> The search range setting lets you specify ranges of books (and hymns) to limit the search to. You may add more ranges by clicking the plus-button to the right of each line. </p> </div> }, searchMetaFilters : { title: "Meta Filters", content: <div> <p> By setting up meta filters, you can limit your search to verses matching the specified meta properties. </p> <p> It is possible to select multiple values per property. The results will only contain verses that match one of the selected values of each property specified! </p> </div> }, zurichIso : { title: "Rigveda version in ISO-15919", content: <div> <p> The Rigveda data from the University of Zurich is the basis of VedaWeb's grammar and full text search tools. </p> </div> }, zurichGlossing : { title: "Morphological glossings from Zurich", content: <div> <p> The morphological annotation was carried out at the University of Zurich.<br/> It follows the Leipzig Glossing Rules. The abbreviations used are listed below: </p> <table style={{width: 'auto'}}><tbody> <tr><td className="bold">1</td><td>first person</td></tr> <tr><td className="bold">2</td><td>second person</td></tr> <tr><td className="bold">3</td><td>third person</td></tr> <tr><td className="bold">ABL</td><td>ablative</td></tr> <tr><td className="bold">ACC</td><td>accusative</td></tr> <tr><td className="bold">ACT</td><td>actor</td></tr> <tr><td className="bold">AOR</td><td>aorist</td></tr> <tr><td className="bold">COND</td><td>conditional</td></tr> <tr><td className="bold">CVB</td><td>converb</td></tr> <tr><td className="bold">DAT</td><td>dative</td></tr> <tr><td className="bold">DU</td><td>dual</td></tr> <tr><td className="bold">F</td><td>feminine</td></tr> <tr><td className="bold">FUT</td><td>future</td></tr> <tr><td className="bold">GEN</td><td>genitive</td></tr> <tr><td className="bold">IMP</td><td>imperative</td></tr> <tr><td className="bold">IND</td><td>indicative</td></tr> <tr><td className="bold">INF</td><td>infinitive</td></tr> <tr><td className="bold">INJ</td><td>injuctive</td></tr> <tr><td className="bold">INS</td><td>instrumental</td></tr> <tr><td className="bold">IPRF</td><td>imperfect</td></tr> <tr><td className="bold">LOC</td><td>locative</td></tr> <tr><td className="bold">M</td><td>mascuiline</td></tr> <tr><td className="bold">MED</td><td>middle voice</td></tr> <tr><td className="bold">N</td><td>neuter</td></tr> <tr><td className="bold">NOM</td><td>nominative</td></tr> <tr><td className="bold">OPT</td><td>optative</td></tr> <tr><td className="bold">PASS</td><td>passive voice</td></tr> <tr><td className="bold">PL</td><td>plural</td></tr> <tr><td className="bold">PLUPRF</td><td>past perfect</td></tr> <tr><td className="bold">PPP</td><td>na participle perfective passive</td></tr> <tr><td className="bold">PPP</td><td>ta participle perfective passive</td></tr> <tr><td className="bold">PRF</td><td>perfect</td></tr> <tr><td className="bold">PRS</td><td>present</td></tr> <tr><td className="bold">PTCP</td><td>participle</td></tr> <tr><td className="bold">SBJV</td><td>subjunctive</td></tr> <tr><td className="bold">SG</td><td>singular</td></tr> <tr><td className="bold">VOC</td><td>vocative</td></tr> </tbody></table> </div> }, quickSearch : { title: "Quick Search", content: <div> <p> The Quick Search is a versatile search for, well, quick searches. It is why it is present at the top of each page at all time. You can search for several things in several ways: </p> <h2>Verse location:</h2> <p> Just type a Rigveda verse location in the form of <strong>1.2.3</strong> or <strong>01.002.03</strong> or even <strong>0100203</strong> to be redirected to this verse's page without further detours. </p> <h2>Simple text search:</h2> <p> By setting the place to search in to <strong>Rigveda</strong> or <strong>Translation</strong>, you can search for words in the Rigveda verses or in their translations, respectively. It's also possible to search for <strong>multiple words</strong> at once, in which case the <strong>verses containing the most</strong> of what you are looking for will be <strong>ranked higher</strong> in the search results. </p> <h2>Transliteration</h2> <p> If you search for terms in the Rigveda verses, you can <strong>use a transliteration method of your choice</strong>. Our data is in ISO-15919 (so if you want to type in ISO-15919 you can just do that), but your search input can be transliterated from several other standards to ISO-15919. The <strong>default setting is Harvard-Kyoto (HK)</strong>, but you can change this in the <strong>Advanced Search Settings</strong>. </p> <h2>Wildcards</h2> <p> It is possible to search for words starting or ending with a certain substring. Searching for <strong>agni*</strong> will find agnim, agniḥ, agnināgniḥ, and so on - so the Asterisk (<strong>*</strong>) works as a simple placeholder. You can use this in the beginning (<strong>*dāḥ</strong>), the end (<strong>agni*</strong>) or both (<strong>*dak*</strong>). </p> <h2>Logical operators</h2> <p> Using the <strong>AND</strong> and <strong>OR</strong> operators, you can construct little logical statements. Searching for <strong>agnim OR indra</strong>, you'll find every verse containing one of the words <strong>agnim</strong> or <strong>indra</strong>. The same works for the <strong>AND</strong> operator: <strong>agnim AND indra</strong> will give you the verses containing both words. </p> <h2>Required and prohibited terms</h2> <p> With <strong>+</strong> and <strong>-</strong>, you can specify terms that <strong>must</strong> or <strong>must not</strong> occur in a verse to be found. So, for example, <strong>agnim -indra</strong> finds verses containing <strong>agnim</strong> and not containing <strong>indra</strong>, while <strong>agnim +indra</strong> finds verses that <i>might</i> contain <strong>agnim</strong> but defenitely contain <strong>indra</strong>. </p> </div> }, version_detlef : { title: "Detlef", content: <div> <p> Devanagari version provided by Detlef Eichler.<br/> <a href="http://www.detlef108.de/Rigveda.htm" target="_blank" rel="noopener noreferrer">http://www.detlef108.de/Rigveda.htm</a> </p> </div> }, version_vannootenholland : { title: "Van <NAME>", content: <div> <p> Nooten, <NAME> & <NAME> (eds.). 1994. Rig Veda: a metrically restored text with an introduction and notes. Cambridge, Mass. [u.a.]: Harvard University Press. </p> </div> }, version_aufrecht : { title: "Aufrecht", content: <div> <p> Aufrecht, Theodor. 1955. Die Hymnen des Rigveda. Erster Teil. Mandala I-VI. Darmstadt: Wissenschaftliche Buchgesellschaft. UND Aufrecht, Theodor. 1955. Die Hymnen des Rigveda. Zweiter Teil. Mandala VII-X. Darmstadt: Wissenschaftliche Buchgesellschaft. </p> </div> }, version_padapatha : { title: "Padapatha", content: <div> <p> (source info is yet to be provided) </p> </div> }, version_gunkelryan : { title: "Samitha (Gunkel/Ryan)", content: <div> <p> provided by <NAME> and <NAME> </p> </div> }, version_lubotsky : { title: "Sasa Patha (Lubotsky)", content: <div> <p> Lubotsky, Alexander. 1997. A Rgvedic word concordance. (2 Vols.) New Haven, Conn.: American Oriental Society. </p> </div> }, translation_griffith : { title: "Griffith", content: <div> <p> Griffith, <NAME>. 1890. The Hymns of the Rigveda. E.J. Lazarus. </p> </div> }, translation_renou : { title: "Renou", content: <div> <p> <NAME>. (1955-1964) Études védiques et pāṇinéennes (several vols). Paris: Boccard. </p> </div> }, translation_geldner : { title: "Geldner", content: <div> <p> Geldner, <NAME>. 1951. Der Rig-Veda (aus d. Sanskrit ins Dt. übers. u. mit e. laufenden Kommentar versehen). Cambridge, Mass.: Harvard University Press. </p> </div> }, translation_grassmann : { title: "Graßmann", content: <div> <p> <NAME>. 1876, 1877. Rig-Veda (Vol 1 and 2). Leipzig. </p> </div> }, translation_otto : { title: "Otto", content: <div> <p> <NAME>. 1948. Varuna-Hymnen des Rig-Veda. Bonn: Ludwig Röhrscheid Verlag. </p> </div> }, translation_macdonell : { title: "MacDonell", content: <div> <p> MacDonell, <NAME>. 1922. Hymns from the Rigveda. Selected and Metrically Translated. London: Oxford University Press. </p> </div> }, metaLabels : { title: "Pada Labels", content: <div> <p> provided by <NAME> and <NAME> </p> <table style={{width: 'auto'}}><tbody> <tr><td className="bold">D</td><td>genre D</td></tr> <tr><td className="bold">E2</td><td>epic anuṣṭubh (424)</td></tr> <tr><td className="bold">R</td><td>repeated line</td></tr> <tr><td className="bold">E3a</td><td>epic anuṣṭubh (292)</td></tr> <tr><td className="bold">H</td><td>12 = 5+7, ending LHX|| — a type of hypersyllabic triṣṭubh.</td></tr> <tr><td className="bold">S</td><td>line affected by realignment</td></tr> <tr><td className="bold">V</td><td>Vālakhilya</td></tr> <tr><td className="bold">M</td><td>genre M</td></tr> <tr><td className="bold">4</td><td>12 = 8+4</td></tr> <tr><td className="bold">5</td><td>pentad (decasyllabic), including Arnold’s “pure” and “mixed”; see Prolegomena 95–8 and VM 238–40.</td></tr> <tr><td className="bold">B</td><td>bhārgavī; see VM 240–1.</td></tr> <tr><td className="bold">h</td><td>11 = 4+7, ending HLX|| — a type of hyposyllabic jagatī.</td></tr> <tr><td className="bold">G</td><td>gautamī; see VM 240–1</td></tr> <tr><td className="bold">O</td><td>Oldenberg's gāyatrī-corpus, cf. Oldenberg (1888: 9f.).</td></tr> <tr><td className="bold">T</td><td>Trochaic gāyatrī; see Prolegomena 25 and Vedic Metre (VM) 165.</td></tr> <tr><td className="bold">U</td><td>uneven lyric; see VM 154, 244 (Appendix III).</td></tr> <tr><td className="bold">4b</td><td>11 = 8+3</td></tr> <tr><td className="bold">v</td><td>virāṭsthānā; see Prolegomena 86–95 and VM 240–1, 246.</td></tr> <tr><td className="bold">P</td><td>popular</td></tr> <tr><td className="bold">E1</td><td>epic anuṣṭubh (525)</td></tr> <tr><td className="bold">E3b</td><td>epic anuṣṭubh (380)</td></tr> </tbody></table> </div> }, metaStrata : { title: "Verse Strata", content: <div> <p> <NAME>. 'Sketch of the Historical Grammar of the Rig and Atharva Vedas'. Journal of the American Oriental Society 18 (1897): 203–352. <a href="https://www.jstor.org/stable/592303" target="_blank" rel="noopener noreferrer"> https://www.jstor.org/stable/592303</a> </p> <table style={{width: 'auto'}}><tbody> <tr><td className="bold">A</td><td>Archaic</td></tr> <tr><td className="bold">a</td><td>Archaic on metrical evidence alone</td></tr> <tr><td className="bold">S</td><td>Strophic</td></tr> <tr><td className="bold">s</td><td>Strophic on metrical evidence alone</td></tr> <tr><td className="bold">N</td><td>Normal</td></tr> <tr><td className="bold">n</td><td>Normal on metrical evidence alone</td></tr> <tr><td className="bold">C</td><td>Cretic</td></tr> <tr><td className="bold">c</td><td>Cretic on metrical evidence alone</td></tr> <tr><td className="bold">P</td><td>Popular for linguistic reasons, and possibly also for non-linguistic reasons</td></tr> <tr><td className="bold">p</td><td>Popular for non-linguistic reasons</td></tr> </tbody></table> </div> }, metaAdrGroup : { title: "Hymn Addressees / Hymn Groups", content: <div> <p> Geldner, <NAME>. <i>Der Rig-Veda. Aus dem Sanskrit ins Deutsche übersetzt und mit einem laufenden Kommentar versehen von <NAME>.</i> Cambridge (Mass.) [repr. 2003]: Harvard Univ. Pr., 1951. </p> </div> } }; class HelpButton extends Component { state = { visible: false } showModal = () => { if (helpTexts.hasOwnProperty(this.props.type)){ this.setState({ visible: true, }); } else { console.log("Error: '" + this.props.type + "' is not a valid help text type, so i won't open the help view.") } } hideModal = () => { this.setState({ visible: false, }); } render() { const modalHeader = !helpTexts.hasOwnProperty(this.props.type) ? "" : <div className="secondary-font red bold"> <img src={help} alt="" style={{height:"32px", paddingRight:"1rem"}}/> <span style={{verticalAlign:"middle"}}> {helpTexts[this.props.type].title} </span> </div>; const containerStyle = { textAlign: this.props.align ? this.props.align : "right", float: this.props.float ? (this.props.align === undefined ? "right" : this.props.align) : "none", display: this.props.inline ? "inline-block" : "block" } //apply styles from props for(var style in this.props.style) containerStyle[style] = this.props.style[style]; return ( <div style={containerStyle}> <Icon type="question-circle" theme="outlined" className="help-button-icon" onClick={this.showModal} title={helpTexts[this.props.type] !== undefined ? "Show help: \"" + helpTexts[this.props.type].title + "\"" : undefined} /> {this.state.visible && <Modal title={modalHeader} centered footer={null} visible={this.state.visible} onOk={this.hideModal} onCancel={this.hideModal} okText="OK"> {helpTexts[this.props.type].content} </Modal> } </div> ); } } export default HelpButton;<file_sep>/vedaweb-frontend/src/SearchSmart.js import React, { Component } from "react"; import { Input, Tooltip, Select } from 'antd'; import searchSmartStore from "./stores/searchSmartStore"; import searchMetaStore from "./stores/searchMetaStore"; import uiDataStore from "./stores/uiDataStore"; import { view } from 'react-easy-state'; import TransliterationPreview from "./TransliterationPreview"; import { withRouter } from 'react-router-dom'; import { Base64 } from 'js-base64'; import "./css/SearchSmart.css"; import SanscriptAccents from "./SanscriptAccents"; const Option = Select.Option; const Search = Input.Search; class SearchSmart extends Component { constructor(props){ super(props); this.handleSearch = this.handleSearch.bind(this); } handleSearch(input){ if (/\d/.test(input)){ this.props.history.push("/view/id/" + input); } else { let jsonData = { mode: "smart", input: searchSmartStore.data.field === "form" ? SanscriptAccents.t(input, "hk", "iso") : input, field: searchSmartStore.data.field }; this.props.history.push("/results/" + Base64.encodeURI(JSON.stringify(jsonData))); } } render() { const selectBefore = ( <Select defaultValue="form" value={searchSmartStore.data.field} onSelect={(value, option) => searchSmartStore.setField(value)} style={{ width: 125 }} className="secondary-font"> {uiDataStore.search.smart.fields.map(field => ( <Option key={'simple_field_' + field.field} value={field.field} className="secondary-font"> {field.ui} </Option> ))} </Select> ); const transliteration = ( searchSmartStore.data.field === "form" ? <TransliterationPreview input={searchSmartStore.data.input} transliteration="hk" /> : null ); return ( <div id="search-smart"> <Tooltip title={transliteration} trigger="focus" placement="top" overlayClassName="transliteration-tooltip"> <Search value={searchSmartStore.data.input} onChange={e => searchSmartStore.setInput(e.target.value)} onSearch={this.handleSearch} addonBefore={selectBefore} placeholder={"Quick search: " + (searchSmartStore.data.field === "form" ? searchMetaStore.transliteration.toUpperCase() + " or verse no." : "Translation or verse no.") } /> </Tooltip> </div> ); } } export default withRouter(view(SearchSmart));<file_sep>/vedaweb-frontend/src/NavBar.js import React, { Component } from "react"; import { Row, Icon, Menu } from 'antd'; import HelpButton from "./HelpButton"; import SearchSmart from "./SearchSmart"; import logo from "./img/logo.png"; import "./css/NavBar.css"; import searchMetaStore from "./stores/searchMetaStore"; import { view } from 'react-easy-state'; import { NavLink } from 'react-router-dom' const SubMenu = Menu.SubMenu; class NavBar extends Component { constructor(props){ super(props); this.state = { showFeedbackModal: false } } render() { const menuStyle = { backgroundColor: "transparent", borderBottom: "none", textAlign: "right", width: "99%" }; return ( <Row type="flex" align="middle" id="navbar" className="box-shadow"> <NavLink to={"/home"} className="v-middle"> <img src={logo} className="navbar-logo" alt="" /> <div className="navbar-app-title"> <span className="bold">VedaWeb</span><br/> Rigveda online </div> </NavLink> <div className="flex-grow-1"> <SearchSmart /> </div> <HelpButton type="quickSearch" style={{paddingLeft:'1rem'}} /> <div className="flex-grow-2"> <Menu selectedKeys={[]} mode="horizontal" style={menuStyle} onClick={() => {this.setState({showFeedbackModal: true})}}> <SubMenu title={<div className="content-center"><Icon type="book"/><br/>Browse Rigveda</div>} className="right"> {searchMetaStore.scopeDataRaw.map((hymns, i) => ( <Menu.Item key={'view_' + i}> <NavLink to={"/view/id/" + (i+1) + ".1.1"}> Book {('0' + (i+1)).slice(-2)} ({hymns} Hymns) </NavLink> </Menu.Item> ))} </SubMenu> <Menu.Item key="search"> <NavLink to={"/search"} className="content-center"> <Icon type="zoom-in"/><br/>Advanced Search </NavLink> </Menu.Item> <Menu.Item key="betafb"> <NavLink to={"/betafeedback"} className="content-center"> <Icon type="message"/><br/>Beta Feedback </NavLink> </Menu.Item> {/* <Menu.Item key="feedback"> <Icon type="message"/>Beta Feedback </Menu.Item> */} </Menu> </div> {/* <FeedbackModal visible={this.state.showFeedbackModal} onCancel={() => this.setState({showFeedbackModal: false})} /> */} </Row> ); } } export default view(NavBar);<file_sep>/vedaweb-backend/legacy-classes/SearchResults.java package de.unikoeln.vedaweb.legacy; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class SearchResults { private Set<SearchResult> results; public SearchResults(){ results = new HashSet<SearchResult>(); } public void add(SearchResult result){ results.add(result); } public Set<SearchResult> getResults(){ return results; } public List<SearchResult> getSortedResultsList(){ List<SearchResult> resultsList = new ArrayList<SearchResult>(results); Collections.sort(resultsList); return resultsList; } public boolean containsLocationId(String locationId){ return results.contains(new SearchResult(0, locationId, null, null)); } public boolean isEmpty(){ return results.isEmpty(); } public void retainCommon(SearchResults newSearchResults){ if (results.isEmpty()){ results = newSearchResults.getResults(); } else { Set<SearchResult> other = newSearchResults.getResults(); System.out.println("[DEBUG] Joining:\tnew(" + other.size() + ")\told(" + results.size() + ") ..."); other.retainAll(results); results.retainAll(other); System.out.println("[DEBUG] Retained:\tnew(" + other.size() + ")\told(" + results.size() + ") ..."); results.addAll(other); System.out.println("[DEBUG] Joined:\t\tnew(" + other.size() + ")\told(" + results.size() + ") ..."); } } public int size(){ return results.size(); } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (SearchResult r : results) sb.append(r + "\n"); return sb.toString(); } } <file_sep>/vedaweb-frontend/src/SearchView.js import React, { Component } from "react"; import { Row, Col, Button, Icon, Tabs, Collapse } from 'antd'; import SearchGrammar from "./SearchGrammar"; import SearchScopeContainer from "./SearchScopeContainer"; import SearchTransliteration from "./SearchTransliteration"; import SearchScopeIndicator from "./SearchScopeIndicator"; import SearchMetaFilterList from "./SearchMetaFilterList"; import HelpButton from "./HelpButton"; import SanscriptAccents from './SanscriptAccents'; import './css/SearchView.css'; import { view } from 'react-easy-state'; import { withRouter } from 'react-router-dom'; import { Base64 } from 'js-base64'; import searchMetaStore from "./stores/searchMetaStore"; import uiDataStore from "./stores/uiDataStore"; import searchGrammarStore from "./stores/searchGrammarStore"; const TabPane = Tabs.TabPane; const Panel = Collapse.Panel; class SearchView extends Component { constructor(props){ super(props); this.switchMode = this.switchMode.bind(this); this.handleSubmit = this.handleSubmit.bind(this); document.title = "VedaWeb | Advanced Search"; } switchMode(key){ if (key !== "help") searchMetaStore.mode = key; } handleSubmit(e){ let jsonData = { mode: searchMetaStore.mode, scopes: searchMetaStore.scopes, meta: searchMetaStore.meta }; if (searchMetaStore.mode === "grammar"){ jsonData["blocks"] = JSON.parse(JSON.stringify(searchGrammarStore.data.blocks)); for (let block of jsonData.blocks){ block.form = SanscriptAccents.t(block.form, searchMetaStore.transliteration, "iso"); for (let field of block.fields){ if (field.value.length > 0) block[field.name] = field.value } delete block.fields; delete block.id; } } jsonData.scopes = jsonData.scopes.filter(scope => ( (scope.fromBook + scope.toBook + scope.fromHymn + scope.toHymn) > 0 )); this.props.history.push("/results/" + Base64.encodeURI(JSON.stringify(jsonData))); } handleReset(e){ searchMetaStore.reset(); searchGrammarStore.reset(); } render() { //TEMP DEV const customPanelStyle = { background: '#fafafa', borderRadius: 2, marginBottom: 24, border: '1px solid #b4b1ae', overflow: 'hidden', fontSize: '18px' }; const searchTransliterationPanelHeader = <div> {"Selected Transliteration: "} <span className="red"> {uiDataStore.search.meta.transliterations .filter(t => t.id === searchMetaStore.transliteration)[0].name} </span> </div> const searchScopePanelHeader = <div> {"Delimit Search Range: "} <span className="red"> <SearchScopeIndicator /> </span> </div> const customMetaFilterPanelHeader = <div> Meta Filters: {searchMetaStore.hasMetas() ? <span className="red"> Adressee ({searchMetaStore.meta.hymnAddressee.length}), Group ({searchMetaStore.meta.hymnGroup.length}), Strata ({searchMetaStore.meta.strata.length}) </span> : <span className="red"> none</span> } </div> return ( <Row type="flex" justify="center" id="search-view" className="page-content" key="search-view"> <Col xl={14} lg={18} md={20} sm={24}> <div className="card"> <h4>Advanced Search</h4> <h3><Icon type="edit" className="gap-right"/>Input Transliteration</h3> <Collapse bordered={false}> <Panel header={searchTransliterationPanelHeader} key={"transliteration"} style={customPanelStyle} forceRender={true}> <HelpButton type="transliteration" /> <SearchTransliteration/> </Panel> </Collapse> <h3><Icon type="search" className="gap-right"/>What are you searching for?</h3> <Tabs onChange={this.switchMode} type="card" id="search-mode-selector" tabBarGutter={8} className="bottom-gap"> <TabPane tab="Grammar Search" key="grammar"> <SearchGrammar /> </TabPane> {/* <TabPane tab="Simple Search" key="simple"> <SearchSimple/> </TabPane> */} <TabPane tab="Other Search" key="somemode"> <div className="search-container"> More search modes will follow ... </div> </TabPane> </Tabs> <h3><Icon type="tool" className="gap-right"/>Additional Search Settings</h3> <Collapse bordered={false}> <Panel header={searchScopePanelHeader} key="scope" style={customPanelStyle} forceRender={true}> <HelpButton type="searchScope" /> <SearchScopeContainer/> </Panel> <Panel header={customMetaFilterPanelHeader} key="metafilters" style={customPanelStyle} > <HelpButton type="searchMetaFilters" /> <SearchMetaFilterList label="Hymn Addressees" placeholder="all Addressees" items={uiDataStore.meta.hymnAddressee} selected={searchMetaStore.meta.hymnAddressee} handleChange={v => {searchMetaStore.meta.hymnAddressee = v}}/> <SearchMetaFilterList label="Hymn Groups" placeholder="all Groups" items={uiDataStore.meta.hymnGroup} selected={searchMetaStore.meta.hymnGroup} handleChange={v => {searchMetaStore.meta.hymnGroup = v}}/> <SearchMetaFilterList label="Verse Strata" placeholder="all Strata" items={uiDataStore.meta.strata} selected={searchMetaStore.meta.strata} handleChange={v => {searchMetaStore.meta.strata = v}}/> </Panel> </Collapse> <Row> <Col span={24} className="content-right"> <Button icon="delete" size="large" className={"secondary-font"} htmlType="reset" onClick={this.handleReset}> Reset </Button> <Button type="primary" icon="search" size="large" className={"secondary-font gap-left-big"} onClick={this.handleSubmit}> Search </Button> </Col> </Row> </div> </Col> </Row> ); } } export default withRouter(view(SearchView));<file_sep>/readme.md # VedaWeb ### This project is currently in a kind of 'proof of concept' phase. It is not yet documented and many parts are still implemented in a quick and dirty way. In the future there will be a lot of refactoring and documentation to be done. This is the cody repository for the VedaWeb application, which is being developed in the context of the VedaWeb project. German description for the VedaWeb project: > Das Projekt hat zum Ziel, eine webbasierte, frei zugängliche Plattform für die sprachwissenschaftliche Erforschung altindischer Texte aufzubauen. Das altindische Textkorpus soll digital einsehbar, morphologisch und metrisch annotiert sowie nach lexikographischen und korpuslinguistischen Kriterien durchsuchbar zur Verfügung gestellt werden. Als Pilottext wird der Rigveda eingespeist werden, der mit den Wörterbüchern Cologne Digital Sanskrit Dictionaries verknüpft werden soll. Die morphologische Annotation dieses Textes wurde an der Universität Zürich (UZH) durchgeführt und dem Projekt zur Verfügung gestellt. In Zukunft wird über die URL vedaweb.uni-koeln.de die Vedaweb-Anwendung erreichbar sein. <file_sep>/vedaweb-frontend/src/Start.js import React, { Component } from "react"; import { Row, Col, Icon, Button } from 'antd'; import feedbackMailAddress from "./feedbackMailAddress.js"; import HelpButton from "./HelpButton"; class ContentView extends Component { render() { document.title = "VedaWeb | Rigveda online"; return ( <Row type="flex" justify="center" className="page-content"> <Col xl={14} lg={18} md={20} sm={24}> <div className="card"> <h4><Icon type="experiment"/> VedaWeb beta</h4> <span className="secondary-font red">Project time frame: July 2017 - June 2020</span><br/><br/> <div> This is a beta version for testing some of our planned concepts and getting feedback from potential users.<br/> There are numerous things yet to be implemented, some of which are:<br/><br/> <ul> <li>Metric analysis (search and display)</li> <li>Data export</li> <li>Additional translations (Renou etc.)</li> <li>Additional search modes</li> <li>...</li> </ul> Look out for the <HelpButton type="start" inline/> buttons to get explanations of the different features.<br/> Feel free to send us your <strong>feedback on functionality, usability and data correctness:</strong> <br/><br/> <Button type="primary" href={"mailto:" + feedbackMailAddress.mail + "?subject=VedaWeb beta feedback"} className="secondary-font"> <Icon type="mail" /> {feedbackMailAddress.mail} </Button> <br/><br/> Thank you for testing the <span className="secondary-font red bold">VedaWeb</span> beta! <br/><br/> </div> </div> </Col> </Row> ); } } export default ContentView;<file_sep>/vedaweb-frontend/src/stores/searchGrammarStore.js import { store } from 'react-easy-state'; import uiDataStore from "./uiDataStore"; const searchGrammarStore = store({ data: { blocks: [] }, addBlock(){ let blockId = 'block_' + Date.now() searchGrammarStore.data.blocks = searchGrammarStore.data.blocks.concat({ id: blockId, form: '', distance: 0, fields: [] }); searchGrammarStore.addFieldToBlock(blockId); }, removeBlock(blockId){ searchGrammarStore.data.blocks = searchGrammarStore.data.blocks.filter(block => block.id !== blockId); searchGrammarStore.data.blocks[0].distance = 0; }, addFieldToBlock(blockId){ for (let i = 0; i < searchGrammarStore.data.blocks.length; i++){ if (searchGrammarStore.data.blocks[i].id === blockId){ searchGrammarStore.data.blocks[i].fields.push({ id: 'field_' + Date.now(), name: '', value: '' }); break; } } }, removeFieldFromBlock(blockId, fieldId){ for (let i = 0; i < searchGrammarStore.data.blocks.length; i++){ if (searchGrammarStore.data.blocks[i].id === blockId){ searchGrammarStore.data.blocks[i].fields = searchGrammarStore.data.blocks[i].fields.filter(field => field.id !== fieldId); break; } } }, updateField(blockId, fieldId, fieldProp, value){ for (let i = 0; i < searchGrammarStore.data.blocks.length; i++){ if (searchGrammarStore.data.blocks[i].id === blockId){ for (let j = 0; j < searchGrammarStore.data.blocks[i].fields.length; j++){ if (searchGrammarStore.data.blocks[i].fields[j].id === fieldId){ searchGrammarStore.data.blocks[i].fields[j][fieldProp] = value; if (fieldProp === "name" && value.length === 0){ searchGrammarStore.data.blocks[i].fields[j].value = ""; } else if (fieldProp === "name" && value.length > 0){ searchGrammarStore.data.blocks[i].fields[j].value = searchGrammarStore.getValueOptionsForFieldName(value)[0]; } break; } } break; } } }, updateForm(blockId, form){ for (let i = 0; i < searchGrammarStore.data.blocks.length; i++){ if (searchGrammarStore.data.blocks[i].id === blockId){ searchGrammarStore.data.blocks[i].form = form; break; } } }, updateDistance(blockId, distance){ for (let i = 0; i < searchGrammarStore.data.blocks.length; i++){ if (searchGrammarStore.data.blocks[i].id === blockId){ searchGrammarStore.data.blocks[i].distance = distance; break; } } }, getUsedFieldNamesForBlock(blockId){ let usedFieldNames = []; for (let block of searchGrammarStore.data.blocks){ if (block.id === blockId){ for (let field of block.fields){ usedFieldNames.push(field.name); } } break; } return usedFieldNames; }, getValueOptionsForFieldName(fieldName){ for (let grammar of uiDataStore.search.grammar.tags){ if (grammar.field === fieldName){ return grammar.values; } } return []; }, reset(){ searchGrammarStore.data = { blocks: [] }; this.addBlock(); } }) export default searchGrammarStore;<file_sep>/vedaweb-backend/legacy-classes/Part.java package de.unikoeln.vedaweb.legacy; import java.util.List; import java.util.Map; public class Part { private Integer index; private String form; private List<Map<String, Object>> tokens; public Part(){ //... } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public List<Map<String, Object>> getTokens() { return tokens; } public void setTokens(List<Map<String, Object>> tokens) { this.tokens = tokens; } } <file_sep>/vedaweb-backend/legacy-classes/SearchRequest.java package de.unikoeln.vedaweb.legacy; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; public class SearchRequest { private int scopeBook; private int scopeHymn; private List<Map<String, Object>> blocks; public SearchRequest(){ blocks = new ArrayList<Map<String, Object>>(); this.scopeBook = -1; this.scopeHymn = -1; } public List<Map<String, Object>> getBlocks() { return blocks; } public int getScopeBook() { return scopeBook; } @JsonProperty("book") public void setScopeBook(int scopeBook) { this.scopeBook = scopeBook; } public int getScopeHymn() { return scopeHymn; } @JsonProperty("hymn") public void setScopeHymn(int scopeHymn) { this.scopeHymn = scopeHymn; } @JsonProperty("blocks") public void setBlocks(List<Map<String, Object>> blocks) { this.blocks = blocks; } public void addBlock(Map<String, Object> block) { this.blocks.add(block); } @Override public String toString() { return "book:" + scopeBook + " hymn:" + scopeHymn + " blocks:" + blocks; } public void cleanAndFormatFields(){ for (Map<String, Object> block : blocks){ block.values().removeAll(Collections.singleton("")); for (String field : block.keySet()){ if (block.get(field) instanceof String && ((String)block.get(field)).matches("\\d+")){ block.put(field, Integer.parseInt(((String)block.get(field)))); } } } } } <file_sep>/vedaweb-frontend/src/stores/searchMetaStore.js import { store } from 'react-easy-state'; const searchMetaStore = store({ mode: 'grammar', scopes: [ { id: 'scope_0', fromBook: 0, fromHymn: 0, toBook: 0, toHymn: 0 } ], scopeDataRaw: [], transliteration: "hk", meta: { hymnAddressee: [], hymnGroup: [], strata: [] }, hasMetas(){ return searchMetaStore.meta.hymnAddressee.length > 0 || searchMetaStore.meta.hymnGroup.length > 0 || searchMetaStore.meta.strata.length > 0 }, setSearchMode(mode){ searchMetaStore.mode = mode; }, setTransliteration(id){ searchMetaStore.transliteration = id; }, setScopeFromBook(scopeId, index){ for (let i = 0; i < searchMetaStore.scopes.length; i++){ if (searchMetaStore.scopes[i].id === scopeId){ searchMetaStore.scopes[i].fromBook = index; searchMetaStore.scopes[i].fromHymn = 0; searchMetaStore.scopes[i].toBook = 0; searchMetaStore.scopes[i].toHymn = 0; break; } } }, setScopeFromHymn(scopeId, index){ for (let i = 0; i < searchMetaStore.scopes.length; i++){ if (searchMetaStore.scopes[i].id === scopeId){ searchMetaStore.scopes[i].fromHymn = index; searchMetaStore.scopes[i].toHymn = (searchMetaStore.scopes[i].fromBook === searchMetaStore.scopes[i].toBook && index > searchMetaStore.scopes[i].toHymn) ? index : searchMetaStore.scopes[i].toHymn; break; } } }, setScopeToBook(scopeId, index){ for (let i = 0; i < searchMetaStore.scopes.length; i++){ if (searchMetaStore.scopes[i].id === scopeId){ searchMetaStore.scopes[i].toBook = index; searchMetaStore.scopes[i].toHymn = 0; break; } } }, setScopeToHymn(scopeId, index){ for (let i = 0; i < searchMetaStore.scopes.length; i++){ if (searchMetaStore.scopes[i].id === scopeId){ searchMetaStore.scopes[i].toHymn = index; break; } } }, addScope(){ let scopeId = 'scope_' + Date.now(); searchMetaStore.scopes = searchMetaStore.scopes.concat({ id: scopeId, fromBook: 0, fromHymn: 0, toBook: 0, toHymn: 0 }); }, removeScope(scopeId){ searchMetaStore.scopes = searchMetaStore.scopes.filter(scope => scope.id !== scopeId); }, getScopeSettings(scopeId){ for (let i = 0; i < searchMetaStore.scopes.length; i++){ if (searchMetaStore.scopes[i].id === scopeId){ return searchMetaStore.scopes[i]; } } return {}; }, getRanges(scopeId){ for (let i = 0; i < searchMetaStore.scopes.length; i++){ if (searchMetaStore.scopes[i].id === scopeId){ let scope = searchMetaStore.scopes[i]; return { fromBookRange: this.range(1, this.scopeDataRaw.length), fromHymnRange: scope.fromBook === 0 ? [] : this.range(1, this.scopeDataRaw[scope.fromBook === 0 ? 0 : scope.fromBook - 1]), toBookRange: scope.fromBook === 0 ? [] : this.range(scope.fromBook, this.scopeDataRaw.length), toHymnRange: scope.toBook === 0 ? [] : this.range(scope.fromBook === scope.toBook ? (scope.fromHymn === 0 ? 1 : scope.fromHymn) : 1, this.scopeDataRaw[scope.toBook === 0 ? 0 : scope.toBook - 1]) }; } } return {}; }, range(from, to) { return [...Array(to - from + 1).keys()].map(i => i + from); }, reset(){ searchMetaStore.scopes = [ { id: 'scope_0', fromBook: 0, fromHymn: 0, toBook: 0, toHymn: 0 } ]; searchMetaStore.meta = { hymnAddressee: [], hymnGroup: [], strata: [] }; } }); export default searchMetaStore;<file_sep>/vedaweb-frontend/src/ContentView_OLD.js import React, { Component } from "react"; import { Row, Col, Affix, Spin, Select, Button, Icon } from 'antd'; import ContentLocation from "./ContentLocation"; import ContentFilterSwitch from "./ContentFilterSwitch"; import ErrorMessage from "./ErrorMessage"; import "./css/ContentView.css"; import { withRouter } from 'react-router-dom'; import { view } from 'react-easy-state'; import scrollToComponent from 'react-scroll-to-component'; import axios from 'axios'; import uiDataStore from "./stores/uiDataStore"; import DictionaryView from "./DictionaryView"; import HelpButton from "./HelpButton"; const Option = Select.Option; class ContentView extends Component { constructor(props) { super(props) this.state ={ data: {}, isLoaded: false } } componentDidMount() { if (this.props.match.params.by === undefined || this.props.match.params.value === undefined){ this.props.history.push("/view/index/0"); } else { this.loadData(this.props.match.params.by, this.props.match.params.value); } } componentDidUpdate(prevProps, prevState) { if (this.props.match.params.by !== prevProps.match.params.by || this.props.match.params.value !== prevProps.match.params.value){ this.loadData(this.props.match.params.by, this.props.match.params.value); } } propsChanged(newProps){ return JSON.stringify(this.props) !== JSON.stringify(newProps); } loadData(by, value){ this.setState({ isLoaded: false, error: undefined, }); axios.get(process.env.PUBLIC_URL + "/api/document/" + by + "/" + value) .then((response) => { this.setState({ isLoaded: true, data: response.data }); //set page title document.title = "VedaWeb | " + ((response.data.id !== undefined) ? "Verse " + response.data.book + "." + response.data.hymn + "." + response.data.verse + " | " + response.data.hymnGroup : " Rigveda online"); }) .catch((error) => { this.setState({ isLoaded: true, error: error }); }); } filterChange(target, checked){ if (checked) uiDataStore.viewScrollTo = true; uiDataStore.viewFilter[target] = checked; } scrollTo(component){ if (uiDataStore.viewScrollTo){ scrollToComponent(component, {align:'top'}); uiDataStore.viewScrollTo = false; } } resolveAbbrevationToHTML(abb, cat){ return abb.split('').map((key, i) => ( <span key={"abb_" + i}> <span className="bold secondary-font">{key}</span> <span> - {uiDataStore.abbreviations[cat][key]}</span><br/> </span> )); } cleanLemmaString(lemma){ if (typeof lemma === 'string' || lemma instanceof String){ lemma = lemma.replace(/\s?\d/g,''); if (lemma.startsWith('\u221A') && lemma.charAt(lemma.length - 1) === '-'){ lemma = lemma.substr(0, lemma.length - 1); } } return lemma.trim(); } render() { const { error, isLoaded, data } = this.state; const exportOptions = ["PDF","XML","TEI-XML","Text"]; return ( <Spin size="large" delay={200} spinning={!isLoaded} > <div className="page-content"> {/** ERROR **/} { isLoaded && error !== undefined && <ErrorMessage/> } {/** LOADED, NO ERROR **/} { error === undefined && <div> <Row> {/** CONTENT **/} <Col span={18}> <div className="card"> { data.book !== undefined && <div> <ContentLocation key={'loc_' + data.id} currIndex={data.index} currId={data.id} book={data.book} hymn={data.hymn} verse={data.verse} /> <span className="bold gap-left-big">Hymn addressee: </span> <span className="text-font">{data.hymnAddressee}</span> <span className="bold gap-left-big">Hymn group: </span> <span className="text-font">{data.hymnGroup}</span> </div> } </div> { data.padas !== undefined && <div> <div className="content-plain content-block card"> <HelpButton type="zurichIso" float/> <h4 title={"Rigveda, book " + data.book + ", hymn " + data.hymn + ", verse " + data.verse}> {('0' + data.book).slice(-2)}. {('00' + data.hymn).slice(-3)}. {('0' + data.verse).slice(-2)} </h4> {data.padas.map(pada => ( <div className="bottom-gap-small" key={"p_plain_" + pada.index}> <span key={"p_plain_line" + pada.index} className="pada-line">{pada.line}</span> <span key={"p_plain_form" + pada.index} className="pada-form text-font">{pada.form}</span><br/> </div> ))} </div> {uiDataStore.viewFilter.devanagari && <div className="content-plain content-block card deva-font" ref={this.scrollTo}> <h4>Devanagari (Detlef)</h4> {data.versions.filter(v => v.language === 'deva').map(v => ( v.form.map((line, i) => ( <div key={"deva_" + i}>{line}</div> )) ))} </div> } {uiDataStore.viewFilter.padapatha && <div className="content-plain content-block card text-font" ref={this.scrollTo}> <h4>Padapatha</h4> {data.versions.filter(v => v.source === 'Padapatha').map(v => ( v.form.map((line, i) => ( <div key={"padapatha_" + i}>{line}</div> )) ))} </div> } {uiDataStore.viewFilter.sasapatha && <div className="content-plain content-block card text-font" ref={this.scrollTo}> <h4>Sasa Patha (Gunkel, Ryan)</h4> {data.versions.filter(v => v.source === 'Sasa Patha (Gunkel, Ryan)').map(v => ( v.form.map((line, i) => ( <div key={"sasa_" + i}>{line}</div> )) ))} </div> } {uiDataStore.viewFilter.vnh && <div className="content-plain content-block card text-font" ref={this.scrollTo}> <h4>Van Nooten, Holland</h4> {data.versions.filter(v => v.source === 'Van Nooten, Holland').map(v => ( v.form.map((line, i) => ( <div key={"vnh_" + i}>{line}</div> )) ))} </div> } {uiDataStore.viewFilter.aufrecht && <div className="content-plain content-block card text-font" ref={this.scrollTo}> <h4>Aufrecht</h4> {data.versions.filter(v => v.source === 'Aufrecht').map(v => ( v.form.map((line, i) => ( <div key={"aufrecht_" + i}>{line}</div> )) ))} </div> } {uiDataStore.viewFilter.glossing && <div className="glossing content-block card" ref={this.scrollTo}> <HelpButton type="zurichGlossing" float/> <h4>Morphological Glossing</h4> {data.padas.map(pada => ( <div className="glossing-line" key={"p_" + pada.index}> <span key={"p_gloss_line" + pada.index} className="pada-line"> {pada.line} </span> {pada.tokens.map(token => ( <div className="glossing-token text-font" key={"t_" + token.index}> {token.form} <br/> <div className="glossing-annotation"> {this.cleanLemmaString(token.lemma)} { Object.keys(token.grammar).map(key => ( <span key={"t_" + token.index + "_" + key}> .{token.grammar[key]} </span> )) } </div> </div> ))} </div> ))} </div> } {uiDataStore.viewFilter.translations && <div className="content-block card" ref={this.scrollTo}> <h4 className="inline-block">Translations</h4> <ContentFilterSwitch label="EN (Griffith)" onChange={(e) => {uiDataStore.disabledTranslations["Griffith"] = !e}} disabled={data.translations.filter(t => t.source === "Griffith").length === 0} checked={!uiDataStore.disabledTranslations["Griffith"]} inline={true} /> <ContentFilterSwitch label="DE (Geldner)" onChange={(e) => {uiDataStore.disabledTranslations["Geldner"] = !e}} disabled={data.translations.filter(t => t.source === "Geldner").length === 0} checked={!uiDataStore.disabledTranslations["Geldner"]} inline={true} /> <ContentFilterSwitch label="DE (Grassmann)" onChange={(e) => {uiDataStore.disabledTranslations["Grassmann"] = !e}} disabled={data.translations.filter(t => t.source === "Grassmann").length === 0} checked={!uiDataStore.disabledTranslations["Grassmann"]} inline={true} /> {data.translations.map(translation => ( !uiDataStore.disabledTranslations[translation.source] && <div key={"trans_" + translation.source} className="translation"> <span className="bold">{ translation.language.toUpperCase() === "DE" ? "German" : translation.language.toUpperCase() === "EN" ? "English" : translation.language.toUpperCase() === "FR" ? "French" : "?" }</span> <span className="first-cap"> ({translation.source})</span> <br/> <div className="text-font"> {translation.form.map((line, i) => ( <div key={"trans_" + i}>{line}</div> ))} </div> </div> ))} </div> } {uiDataStore.viewFilter.dictionary && <div className="glossing content-block card" ref={this.scrollTo}> <h4>Dictionary (Grassmann)</h4> <DictionaryView key={data.id} data={data.padas}/> </div> } {uiDataStore.viewFilter.metaInfo && <div className="glossing content-block card" ref={this.scrollTo}> <h4>Meta Info</h4> <table style={{width:'auto'}}> <tbody> <tr> <td> <span className="bold gap-right">Hymn Addressee:</span> </td> <td className="text-font"> {data.hymnAddressee} </td> </tr> <tr> <td> <span className="bold gap-right">Hymn Group:</span> </td> <td className="text-font"> {data.hymnGroup} </td> </tr> <tr> <td> <span className="bold gap-right">Strata (Arnold):</span> </td> <td className="text-font"> {this.resolveAbbrevationToHTML(data.strata, "strata")} </td> </tr> <tr> <td> <span className="bold gap-right">Pada Labels (Gunkel, Ryan):</span> </td> <td> {data.padas.map(pada => ( <div> <div style={{display:"inline-block", verticalAlign:"top"}} className="bold red gap-right">{pada.line}:</div> <div style={{display:"inline-block", verticalAlign:"top"}} className="text-font"> {this.resolveAbbrevationToHTML(pada.label, "label")} </div> </div> ))} </td> </tr> </tbody> </table> </div> } </div> } </Col> <Col span={6}> <Affix offsetTop={10}> <div className="card"> <h4><Icon type="filter" className="gap-right"/> View Filters</h4> <h5>Additional Versions</h5> <ContentFilterSwitch label="Devanagari" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.devanagari} onChange={(e) => this.filterChange("devanagari", e)} /> <ContentFilterSwitch label="Padapatha" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.padapatha} onChange={(e) => this.filterChange("padapatha", e)} /> <ContentFilterSwitch label="Sasa Patha" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.sasapatha} onChange={(e) => this.filterChange("sasapatha", e)} /> <ContentFilterSwitch label="Van Nooten, Holland" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.vnh} onChange={(e) => this.filterChange("vnh", e)} /> <ContentFilterSwitch label="Aufrecht" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.aufrecht} onChange={(e) => this.filterChange("aufrecht", e)} /> <h5>Metadata</h5> <ContentFilterSwitch label="Morphological Glossing" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.glossing} onChange={(e) => this.filterChange("glossing", e)} /> <ContentFilterSwitch label="Translations" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.translations} onChange={(e) => this.filterChange("translations", e)} /> <ContentFilterSwitch label="Dictionary" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.dictionary} onChange={(e) => this.filterChange("dictionary", e)} /> <ContentFilterSwitch label="Meta Tags" disabled={!isLoaded || error !== undefined} checked={uiDataStore.viewFilter.metaInfo} onChange={(e) => this.filterChange("metaInfo", e)} /> </div> <div className="card"> <h4><Icon type="export" className="gap-right"/>Export</h4> <Row> <Col span={20}> <Select defaultValue={"PDF"} onSelect={(value) => console.log("Export triggered: " + value)} style={{width:"100%"}} className="secondary-font"> {exportOptions.map((eOpt, i) => ( <Option key={'eOpt_' + i} value={eOpt} className="secondary-font"> {eOpt} </Option> ))} </Select> </Col> <Col span={2} offset={1}> <Button type="secondary" icon="download" onClick={() => {alert("Export functionality doesn't exist, yet.")}} /> </Col> </Row> </div> </Affix> </Col> </Row> </div> } </div> </Spin> ); } } export default withRouter(view(ContentView));<file_sep>/env.sh #!/bin/bash #arg check if [[ "$#" != 1 ]] then echo "only one argument (on/off) allowed." exit fi if [[ "$1" == 'on' ]] then sudo service mongod start sudo service elasticsearch start echo "started services." exit fi if [[ "$1" == 'off' ]] then sudo service mongod stop sudo service elasticsearch stop echo "stopped services." exit fi<file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/data/Token.java package de.unikoeln.vedaweb.data; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; public class Token { private int index; private String form; private String lemma; private String[] lemmaRef; private Map<String, String> grammar; public Token(){ grammar = new LinkedHashMap<String, String>(); form = ""; lemma = ""; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public String getLemma() { return lemma; } public void setLemma(String lemma) { this.lemma = lemma; } @JsonProperty("lemmaRef") public String[] getLemmaRef() { return lemmaRef; } public void setLemmaRef(String[] lemmaRef) { this.lemmaRef = lemmaRef; } public void addLemmaRef(String lemmaRef) { this.lemmaRef = Arrays.copyOf(this.lemmaRef, this.lemmaRef.length + 1); this.lemmaRef[this.lemmaRef.length - 1] = lemmaRef; } @JsonProperty("grammar") public Map<String, String> getGrammarAttributes(){ return grammar; } public String getGrammarAttribute(String key) { return grammar.get(key); } public void addGrammarAttribute(String key, String value) { if (grammar.containsKey(key)){ if (!grammar.get(key).contains(value)){ grammar.put(key, grammar.get(key) + "/" + value); } } else { grammar.put(key, value); } } @Override public String toString() { return index + ":" + form + "(" + lemma + ", " + Arrays.toString(lemmaRef) + ")" + grammar; } } <file_sep>/vedaweb-frontend/src/App.js import React, { Component } from "react"; import { BackTop, Spin, Icon } from 'antd'; import NavBar from './NavBar'; import SearchView from './SearchView'; import ContentView from './ContentView'; import Start from './Start'; import NotFound from './NotFound'; import Footer from './Footer'; import System from './System'; import LegalNotice from './LegalNotice'; import PrivacyNotice from './PrivacyNotice'; import "./css/App.css"; import uiDataStore from "./stores/uiDataStore"; import searchMetaStore from "./stores/searchMetaStore"; import { view } from 'react-easy-state'; import { Route, Switch, withRouter } from 'react-router-dom'; import SearchResults from "./SearchResults"; import Sanscript from 'sanscript'; import axios from 'axios'; import "./polyfills"; class App extends Component { constructor(props){ super(props); this.state = { isLoaded: false, error: undefined } //configure iso scheme for sanscript.js let iso = JSON.parse(JSON.stringify(Sanscript.schemes.iast)); iso.vowels = 'a ā i ī u ū r̥ r̥̄ l̥ l̥̄ ē e ai ō o au'.split(' '); iso.other_marks = ['ṁ', 'ḥ', '~']; Sanscript.addRomanScheme('iso', iso); //set global default spinner indicator Spin.setDefaultIndicator(<Icon type="loading" spin style={{ fontSize: 38 }}/>); //load ui data this.loadUiData(); } loadUiData(){ axios.get(process.env.PUBLIC_URL + "/api/uidata") .then((response) => { uiDataStore.search = response.data.search; uiDataStore.meta = response.data.meta; uiDataStore.abbreviations = response.data.abbreviations; uiDataStore.layers = response.data.layers; searchMetaStore.scopeDataRaw = uiDataStore.search.meta.scopes; searchMetaStore.transliteration = uiDataStore.search.meta.transliterations[0].id; this.setState({ isLoaded: true, error: undefined }); }) .catch((error) => { this.setState({ isLoaded: true, error: error }); }); } render() { const { error, isLoaded } = this.state; if (isLoaded && error !== undefined) console.log(JSON.stringify(error)); return ( <div id="app"> { !isLoaded && <Spin size="large" spinning={!isLoaded} className="spinner-loading"/> } {/* ERROR MESSAGE: FRONTEND UI DATA COULD NOT BE LOADED */} { isLoaded && error !== undefined && <div className="error-msg"> <Icon type="frown-o" className="gap-right"/> There was an error loading the application data. This could be due to a temporary server problem. </div> } { isLoaded && error === undefined && <div> <NavBar /> <Switch> <Route path="/view/:by/:value" component={ContentView} /> <Route path="/results/:querydata" component={SearchResults} /> <Route path="/search" component={SearchView} /> <Route path="/system/:auth" component={System} /> <Route path="/legal" component={LegalNotice} /> <Route path="/privacy" component={PrivacyNotice} /> <Route path="/betafeedback" component={Start} /> <Route path="/home" component={Start} /> <Route path="/" exact={true} component={ContentView} /> <Route component={NotFound} /> </Switch> <Footer/> <BackTop /> </div> } </div> ); } } export default withRouter(view(App));<file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/data/VerseLocation.java package de.unikoeln.vedaweb.data; public class VerseLocation { private int book; private int hymn; private int verse; public VerseLocation(int book, int hymn, int verse) { super(); this.book = book; this.hymn = hymn; this.verse = verse; } public VerseLocation(String locationString) { locationString = normalizeId(locationString); if (locationString == null) { this.book = 1; this.hymn = 1; this.verse = 1; } else { this.book = Integer.parseInt(locationString.substring(0, 2)); this.hymn = Integer.parseInt(locationString.substring(2, 5)); this.verse = Integer.parseInt(locationString.substring(5)); } } public int getBook() { return book; } public int getHymn() { return hymn; } public int getVerse() { return verse; } public void setNextFallbackLocation() { if (verse > 1) verse = 1; else if (hymn > 1) hymn = 1; else book = 1; } public static String normalizeId(String id){ if (id.matches("\\d{7}")) return id; else if (id.matches("\\D*\\d{2}\\D\\d{3}\\D\\d{2}\\D*")) id = id.replaceAll("\\D", ""); else id = constructId(id); return id; } public static String constructId(String input){ String[] digits = input.split("\\D+"); if (digits.length != 3) return null; StringBuffer sb = new StringBuffer(); sb.append(String.format("%02d", Integer.parseInt(digits[0]))); sb.append(String.format("%03d", Integer.parseInt(digits[1]))); sb.append(String.format("%02d", Integer.parseInt(digits[2]))); return sb.toString(); } @Override public String toString() { return book + "." + hymn + "." + verse; } } <file_sep>/vedaweb-backend/legacy-classes/VerseDocument.java package de.unikoeln.vedaweb.legacy; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="merged") public class VerseDocument { @Id private String id; private String index; private Integer book; private Integer hymn; private Integer verse; private String translation; private List<Part> parts; public VerseDocument(){ //... } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIndex() { return index; } public void setIndex(String index) { this.index = index; } public int getBook() { return book; } public void setBook(int book) { this.book = book; } public int getHymn() { return hymn; } public void setHymn(int hymn) { this.hymn = hymn; } public int getVerse() { return verse; } public void setVerse(int verse) { this.verse = verse; } public String getTranslation() { return translation; } public void setTranslation(String translation) { this.translation = translation; } public List<Part> getParts() { return parts; } public void setParts(List<Part> parts) { this.parts = parts; } @Override public String toString() { return index + "\t" + parts; } } <file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/services/MappingService.java package de.unikoeln.vedaweb.services; import java.util.Optional; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import de.unikoeln.vedaweb.exceptions.NotFoundException; @Service public class MappingService { private ObjectMapper mapper; public MappingService(){ mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); } public String mapOptionalToJSON(Optional<?> o){ if (!o.isPresent()) return mapObjectToJSON(null); else return mapObjectToJSON(o.get()); } public String mapObjectToJSON(Object o){ String json = "{}"; if (o == null){ throw new NotFoundException(); } try { json = mapper.writeValueAsString(o); } catch (JsonProcessingException e) { e.printStackTrace(); } return json; } } <file_sep>/vedaweb-frontend/src/ContentFilterSwitch.js import React, { Component } from "react"; import { Switch } from 'antd'; import "./css/ContentView.css"; class ContentViewFilterSwitch extends Component { render() { const switchStyle = { fontSize: this.props.size === 'small' ? '16px' : '20px', paddingTop: this.props.size === 'small' ? '0.2rem' : '0.5rem', paddingBottom: this.props.size === 'small' ? '0.2rem' : '0.5rem', paddingLeft: this.props.size === 'small' ? '1.05rem' : '0', filter:'opacity(' + (this.props.disabled ? '0.7' : '1') + ')' }; return ( <div className="view-filter" style={switchStyle}> <Switch defaultChecked style={{marginRight:'.8rem'}} onChange={this.props.onChange} disabled={this.props.disabled} checked={this.props.checked} size={this.props.size} /> {this.props.label + (this.props.disabled ? ' - missing' : '')} </div> ); } } export default ContentViewFilterSwitch;<file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/util/StringUtils.java package de.unikoeln.vedaweb.util; import java.text.Normalizer; import java.text.Normalizer.Form; public class StringUtils { public static String normalizeNFC(String s){ return s == null ? "" : Normalizer.normalize(s, Form.NFC); } public static String normalizeNFD(String s){ return s == null ? "" : Normalizer.normalize(s, Form.NFD); } public static int normalizeIndex(int index, int docCount){ if (index < 0) index = docCount + index; else if (index >= docCount) index = index - docCount; return index; } public static boolean containsAccents(String text) { return text == null ? false : normalizeNFD(text).matches(".*(\\u0301|\\u0300).*"); } public static String removeUnicodeAccents(String text, boolean nfc) { text = text == null ? "" : normalizeNFD(text) .replaceAll("\\u0301", "") .replaceAll("\\u0300", ""); if (nfc) return normalizeNFC(text); else return text; } } <file_sep>/vedaweb-backend/legacy-classes/IndexService.java package de.unikoeln.vedaweb.legacy; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.IntPoint; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.springframework.stereotype.Service; import com.mongodb.client.MongoCursor; //@Service public class IndexService { private static final String INDEX_DIR_PATH = "index"; private Directory indexDirectory; private IndexWriter indexWriter; private Analyzer analyzer; private IndexSearcher searcher; private IndexReader indexReader; public IndexService(){ init(); } public void init(){ initAnalyzer(); initIndexDirectory(); initIndexSearcher(); } public void createIndex(MongoCursor<org.bson.Document> dbDocs){ System.out.println("[INFO] No index found. Creating new index..."); initIndexWriter(); initAnalyzer(); int countPlainTokens = 0; //delete old index if (indexExists()){ try { indexWriter.deleteAll(); indexWriter.commit(); } catch (IOException e) { e.printStackTrace(); } } //add documents to index while (dbDocs.hasNext()){ org.bson.Document dbDoc = dbDocs.next(); int tokenPosition = 0; //parts/Halbverse List<org.bson.Document> parts = dbDoc.get("parts", List.class); for (org.bson.Document part : parts){ //Tokens from plain text List<String> plainTokens = new ArrayList<String>( Arrays.asList(part.getString("form").split("[\\s\\|\\‖]+"))); //TODO ??? //Tokens from grammar data List<org.bson.Document> gramTokens = part.get("tokens", List.class); //build documents for (org.bson.Document token : gramTokens){ //check if there is dup in plain tokens, remove plainTokens.remove(token.getString("form")); Document indexDoc = new Document(); //meta indexDoc.add(new StringField("location_id", dbDoc.getObjectId("_id").toString(), Store.YES)); indexDoc.add(new IntPoint("book", dbDoc.getInteger("book"))); indexDoc.add(new IntPoint("hymn", dbDoc.getInteger("hymn"))); indexDoc.add(new IntPoint("verse", dbDoc.getInteger("verse"))); indexDoc.add(new IntPoint("part", part.getInteger("index"))); indexDoc.add(new IntPoint("position", tokenPosition++)); //non-meta indexDoc.add(new TextField("form", token.getString("form"), Store.YES)); indexDoc.add(new TextField("lemma", token.getString("lemma"), Store.YES)); indexDoc.add(new TextField("casus", token.getString("casus"), Store.YES)); indexDoc.add(new TextField("genus", token.getString("genus"), Store.YES)); indexDoc.add(new TextField("tempus", token.getString("tempus"), Store.YES)); indexDoc.add(new TextField("person", token.getString("person"), Store.YES)); indexDoc.add(new TextField("modus", token.getString("modus"), Store.YES)); indexDoc.add(new TextField("numerus", token.getString("numerus"), Store.YES)); indexDoc.add(new TextField("diathesis", token.getString("diathesis"), Store.YES)); //add document try { indexWriter.addDocument(indexDoc); } catch (IOException e) { e.printStackTrace(); } } //add additional plain tokens for (String plainToken : plainTokens){ countPlainTokens++; System.out.println("FOUND ADDITIONAL PLAIN TOKEN: " + plainToken); Document indexDoc = new Document(); //meta indexDoc.add(new StringField("location_id", dbDoc.getObjectId("_id").toString(), Store.YES)); indexDoc.add(new IntPoint("book", dbDoc.getInteger("book"))); indexDoc.add(new IntPoint("hymn", dbDoc.getInteger("hymn"))); indexDoc.add(new IntPoint("verse", dbDoc.getInteger("verse"))); indexDoc.add(new IntPoint("part", part.getInteger("index"))); //token indexDoc.add(new TextField("form", plainToken, Store.YES)); //add document try { indexWriter.addDocument(indexDoc); } catch (IOException e) { e.printStackTrace(); } } } } //commit, close try { indexWriter.commit(); indexWriter.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("[INFO] Total # of additional plain text tokens: " + countPlainTokens); System.out.println("[INFO] Index created."); } public Analyzer getAnalyzer(){ return analyzer; } private void initIndexWriter(){ if (this.indexWriter != null) return; IndexWriterConfig config = new IndexWriterConfig(analyzer); try { this.indexWriter = new IndexWriter(this.indexDirectory, config); } catch (IOException e) { e.printStackTrace(); } } public boolean indexExists(){ try { return DirectoryReader.indexExists(indexDirectory); } catch (IOException e) { e.printStackTrace(); } return false; } private File getIndexDirectory(){ File indexDir = new File(INDEX_DIR_PATH); if (!indexDir.exists()) indexDir.mkdirs(); return indexDir; } private void initAnalyzer(){ if (this.analyzer != null) return; this.analyzer = new StandardAnalyzer(); } private void initIndexDirectory(){ if (this.indexDirectory != null) return; try { this.indexDirectory = FSDirectory.open( getIndexDirectory().toPath()); } catch (IOException e) { e.printStackTrace(); } } private void initIndexSearcher(){ if (this.indexReader == null){ try { this.indexReader = DirectoryReader.open(indexDirectory); } catch (IOException e) { e.printStackTrace(); } } if (this.searcher == null){ this.searcher = new IndexSearcher(indexReader); } } public IndexSearcher getSearcher(){ return searcher; } } <file_sep>/vedaweb-frontend/src/stores/uiDataStore.js import { store } from 'react-easy-state'; const uiDataStore = store({ //will be filled dynamically with data fetched from server search: {}, meta: {}, contentView: {}, viewScrollTo: false, layers: [], firstTime: true, toggleLayer(id, show){ for (let i = 0; i < uiDataStore.layers.length; i++) { const l = uiDataStore.layers[i]; if (l.id === id){ l.show = show; } if (id.endsWith('_') && l.id.startsWith(id)){ l.show = show; } if (id.startsWith(l.id) && show){ l.show = true; } } let cat = id.split('_')[0] + '_'; if (!id.endsWith('_') && !uiDataStore.isLayerCategoryVisible(cat)){ uiDataStore.toggleLayer(cat, false); } }, isLayerVisible(id){ let l = uiDataStore.layers.find(l => l.id === id); return l !== undefined ? l.show : false; }, isLayerCategoryVisible(catPrefix){ return uiDataStore.layers.find(l => l.id !== catPrefix && l.id.startsWith(catPrefix) && l.show) !== undefined; } }) export default uiDataStore;<file_sep>/vedaweb-backend/src/main/java/de/unikoeln/vedaweb/controllers/UiDataController.java package de.unikoeln.vedaweb.controllers; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import de.unikoeln.vedaweb.services.ElasticIndexService; import de.unikoeln.vedaweb.services.UiDataService; @RestController @RequestMapping("api") public class UiDataController { @Autowired private UiDataService uiDataService; @Autowired private ElasticIndexService indexService; @RequestMapping(value = "/uidata", produces = {"application/json"}) public String getUiDataJSON() { return uiDataService.getUiDataJSON().toString(); } @RequestMapping(value = "/uidata/count/verses/{book}/{hymn}", produces = {"application/json"}) public String getHymnCountJSON(@PathVariable("book") int book, @PathVariable("hymn") int hymn) { JSONObject response = new JSONObject(); response.put("count", indexService.countVerses(book, hymn)); return response.toString(); } // // @Autowired // private ElasticSearchService search; // // @Autowired // MongoTemplate mongoTemplate; // // // @RequestMapping(value = "/data/grammar/{field}", produces = {"application/json"}) // public String valuesForField( // @PathVariable("field") String field, // Model model, // HttpServletRequest request) { // // System.out.println("[INFO] Aggregations requested: grammar fields"); // JSONObject response = new JSONObject(); // // try { // response.put("values", // new JSONArray(mongoTemplate.getCollection("merged").distinct("parts.tokens." + field))); // } catch (JSONException e) { // e.printStackTrace(); // } // // return response.toString(); // } // // // @RequestMapping(value = "/data/grammar", produces = {"application/json"}) // public String valuesForAllGrammarFields( // Model model, // HttpServletRequest request) { // // System.out.println("[INFO] Aggregations requested: grammar fields"); // JSONObject response = new JSONObject(); // // try { // response.put("case", // new JSONArray(mongoTemplate.getCollection("merged").distinct("parts.tokens.casus"))); // response.put("mode", // new JSONArray(mongoTemplate.getCollection("merged").distinct("parts.tokens.modus"))); // } catch (JSONException e) { // e.printStackTrace(); // } // // return response.toString(); // } } <file_sep>/vedaweb-frontend/src/DictionaryView.js import React, { Component } from "react"; import { Icon, Modal, Button } from 'antd'; import axios from 'axios'; import "./css/DictionaryView.css"; const alphabet = ["a", "ā", "i", "ī", "u", "ū", "r̥", "r̥̄", "l̥", "l̥̄", "ē", "e", "ai", "ō", "o", "au", "k", "kh", "g", "gh", "ṅ", "c", "ch", "j", "jh", "ñ", "ṭ", "ṭh", "ḍ", "ḍh", "ṇ", "t", "th", "d", "dh", "n", "p", "ph", "b", "bh", "m", "y", "r", "l", "v", "ś", "ṣ", "s", "h", "ḻ", "kṣ", "jñ"]; class DictionaryView extends Component { constructor(props) { super(props) this.state = { isLoaded: false, modalVisible: false, modalData: undefined, dictData: [], error: undefined } } componentDidMount(){ let lemmaData = this.sort(this.transform(this.props.data)); this.setState({ dictData: lemmaData }); //collect lemma refs let lemmaRefs = []; for (let i = 0; i < lemmaData.length; i++) { const token = lemmaData[i]; if (token.lemmaRef !== undefined && token.lemmaRef !== null){ for (let j = 0; j < token.lemmaRef.length; j++) { lemmaRefs.push(token.lemmaRef[j]); } } } //construct GraphQL query const GQLQ = `{ ids(dictId:"gra", lemmaId: ` + JSON.stringify(lemmaRefs) + `, size: 30) { id headwordDeva headwordIso senseTxtIso } }`; //request API data axios.post("https://api.c-salt.uni-koeln.de/dicts/sa/graphql", {query: GQLQ}) .then((response) => { var dictData = []; const entries = response.data.data.ids; for (let i = 0; i < lemmaData.length; i++) { let t = lemmaData[i]; t["dict"] = t.lemmaRef.map(ref => { let entry = entries.find(e => e.id === ref); return entry === undefined ? {} : { graRef: ref, graDeva: entry.headwordDeva, graTxt: entry.senseTxtIso, graLemma: entry.headwordIso }; }); dictData.push(t); } this.setState({ isLoaded: true, dictData: dictData, error: undefined }); }) .catch((error) => { this.setState({ isLoaded: true, error: !Object.isEmpty(error) ? error : undefined }); }); } transform(padas){ let out = []; let done = []; for (let i = 0; i < padas.length; i++) { const pada = padas[i]; for (let j = 0; j < pada.tokens.length; j++) { const token = pada.tokens[j]; if (done.indexOf(token.lemma) === -1){ out.push({ lemma: token.lemma, lemmaRef: token.lemmaRef, tokens: [token.form] }); done.push(token.lemma); } else { let match = out.find(t => t.lemma === token.lemma); if (match.tokens.indexOf(token.form) === -1){ match.tokens.push(token.form); } } } } return out; } sort(tokenObjs){ let temp = Array(alphabet.length + 1); let unsorted = temp.length; for (let i = 0; i < tokenObjs.length; i++) { const token = tokenObjs[i]; let found = false; for (let j = 0; j < alphabet.length; j++) { const prefix = alphabet[j]; if (this.cleanLemma(token.lemma).startsWith(prefix)){ if (temp[j] !== undefined){ temp[j].push(token); } else { temp[j] = [token]; } found = true; break; } } if (!found){ if (temp[unsorted] !== undefined){ temp[unsorted].push(token); } else { temp[unsorted] = [token]; } } } let out = []; for (let i = 0; i < temp.length; i++) { if (temp[i] !== undefined){ for (let j = 0; j < temp[i].length; j++) { out.push(temp[i][j]); } } } return out; } cleanLemma(string){ return string.normalize('NFD').replace(/[\u0300\u0301\u221a]/g, '').normalize('NFC'); } openDict(modalData){ if (modalData === undefined) return; this.setState({ modalVisible: true, modalData: modalData }); } closeDict = () => { this.setState({ modalVisible: false, modalData: {} }); } render() { const {modalVisible, modalData, dictData, isLoaded, error} = this.state; return ( <div> <table className="teaser"> <thead> <tr> <th>Lemma</th> <th>Full Forms</th> <th>Excerpt</th> <th>Grassmann</th> <th>Others</th> </tr> </thead> <tbody> {dictData.map((token, i) => ( <tr key={token + i}> <td className="non-expanding bold text-font">{token.lemma}</td> <td className="non-expanding text-font" style={{color:'rgba(0,0,0,0.4)'}}> <span>({token.tokens.map((t, i ) => t + (i < token.tokens.length - 1 ? ", " : ""))})</span> </td> <td className="expanding text-font"> {token.dict !== undefined && token.dict[0].graTxt} </td> <td className="non-expanding"> {token.lemmaRef !== undefined && token.lemmaRef !== null && token.lemmaRef.map((ref, i) => { let entry = token.dict === undefined ? undefined : token.dict.find(d => d.graRef === ref); return <Button disabled={!isLoaded || error !== undefined} className="dict-link gap-right" onClick={e => this.openDict(entry)} title={"Show full entry for \"" + token.lemma + "\": #" + (i+1)} key={"lemma_" + i}> <Icon type="book"/> {" " + (i+1)} </Button>; })} </td> <td>n/a</td> </tr>))} </tbody> </table> {isLoaded && modalVisible && modalData !== undefined && error === undefined && <Modal title={<div><span className="bold">Grassmann: </span><span className="text-font">{modalData.graLemma}</span></div>} centered footer={null} visible={true} onOk={this.closeDict} onCancel={this.closeDict} okText="OK"> <div key={modalData.lemmaRef}> <span className="deva-font" style={{color:"#000"}}>{modalData.graDeva}</span><br/> <p className="text-font">{modalData.graTxt}</p> </div> </Modal> } {isLoaded && error !== undefined && <span className="red secondary-font"> <Icon type="meh"/> There was an error loading the dictionary data. Please try again later. </span> } </div> ); } } export default DictionaryView;<file_sep>/vedaweb-frontend/src/ContentLocation.js import React, { Component } from "react"; import { Icon, Select } from 'antd'; import { Link, withRouter } from 'react-router-dom'; import { view } from 'react-easy-state'; import "./css/ContentLocation.css"; import mouseTrap from 'react-mousetrap'; import axios from 'axios'; import uiDataStore from "./stores/uiDataStore"; const Option = Select.Option; class ContentLocation extends Component { constructor(props){ super(props); this.state = {verseCount: 0, isLoaded: false, error: undefined}; this.browseNext = this.browseNext.bind(this); this.browsePrevious = this.browsePrevious.bind(this); } componentWillUnmount(){ this.props.unbindShortcut('right'); this.props.unbindShortcut('left'); } componentDidMount(){ this.props.bindShortcut('right', this.browseNext); this.props.bindShortcut('left', this.browsePrevious); if (this.props.book !== undefined && this.props.hymn !== undefined){ axios.get(process.env.PUBLIC_URL + "/api/uidata/count/verses/" + this.props.book + "/" + this.props.hymn) .then((response) => { this.setState({ verseCount: response.data.count, isLoaded: true, error: undefined }); }) .catch((error) => { this.setState({ verseCount: 0, isLoaded: true, error: error }); }); } } browseNext(){ this.props.history.push("/view/index/" + (this.props.currIndex + 1)); } browsePrevious(){ this.props.history.push("/view/index/" + (this.props.currIndex - 1)); } handleSelect(changed, value){ let id; switch(changed){ case "book": id = value + ".1.1"; break; case "hymn": id = this.props.book + "." + value + ".1"; break; case "verse": id = this.props.book + "." + this.props.hymn + "." + value; break; default: break; } this.props.history.push("/view/id/" + id); } render() { const {book, hymn, verse} = this.props; const bookCount = uiDataStore.search.meta.scopes.length; const hymnCount = uiDataStore.search.meta.scopes[book-1]; const verseCount = this.state.verseCount; const selectStyle = { fontSize: '18px', fontWeight: 'bold', width: '80px' } return ( this.props.book !== undefined && this.props.hymn !== undefined && <div className="inline-block"> <Link to={"/view/index/" + (this.props.currIndex - 1)} className="location-controls"> <Icon type="left"/> </Link> <span className="location-display"> <Select style={selectStyle} showSearch value={book} onSelect={(v) => this.handleSelect("book", v)} > {Array(bookCount).fill(0).map((n, i) => ( <Option key={'book_' + i+1} value={i+1}> {('0' + (i+1)).slice(-2)} </Option> ))} </Select> . <Select style={selectStyle} showSearch value={hymn} onSelect={(v) => this.handleSelect("hymn", v)} > {Array(hymnCount).fill(0).map((n, i) => ( <Option key={'hymn_' + i+1} value={i+1}> {('00' + (i+1)).slice(-3)} </Option> ))} </Select> . <Select style={selectStyle} showSearch value={verse} onSelect={(v) => this.handleSelect("verse", v)} > {Array(verseCount).fill(0).map((n, i) => ( <Option key={'verse_' + i+1} value={i+1}> {('0' + (i+1)).slice(-2)} </Option> ))} </Select> </span> <Link to={"/view/index/" + (this.props.currIndex + 1)} className="location-controls"> <Icon type="right"/> </Link> </div> ); } } export default mouseTrap(withRouter(view(ContentLocation)));
e08a08063ffc94fa13ee0d43b057811e27e0f662
[ "JavaScript", "Java", "Markdown", "Shell" ]
39
JavaScript
claesn/vedaweb
eb52bfde2abd603c1fbee81178535df559c34b96
35f98f61ae5d2c3f465a7ab8b5d33af8c878c498
refs/heads/master
<file_sep>// Required packages const express = require('express'); // Router creation const router = express.Router(); module.exports = router; // GET - /api/slack/test router.get('/test', (req, res, next) => { console.log('In slack route'); res.send('in slack'); }); <file_sep>// Main application file // Required libraries const express = require('express'); const volleyball = require('volleyball'); const bodyParser = require('body-parser'); const axios = require('axios') const fs = require('fs'); // Required files const routerApi = require('./api/routes'); // App creation const app = express(); const PORT = 8585; // Auth const WebClient = require('@slack/client').WebClient; const RtmClient = require('@slack/client').RtmClient; const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS; const RTM_EVENTS = require('@slack/client').RTM_EVENTS; // const token = process.env.SLACK_API_TOKEN || ''; const token = require('./.secrets.js').apiToken; const web = new WebClient(token); // reads JSON file and pushes new message text as string into messages array, before re-writing the JSON file const writeToDB = message => { fs.readFile('./database.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { let obj = JSON.parse(data); //now it an object obj.messages.push(message); //add some data let json = JSON.stringify(obj); //convert it back to json fs.writeFile('./database.json', json, 'utf8', (error) => { if (error) throw error; console.log('Saved!') }); // write it back }}); } const Andrew = 'U2VTX4JKB'; var rtm = new RtmClient(token); rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function (rtmStartData) { console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`); }); rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) { if (message.user === Andrew) { console.log('Andrew said: ', message); // console.log(typeof message.text) writeToDB(message.text); } }); rtm.start(); // Middleware // Logging app.use(volleyball); // Parsing app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Routers app.use('/api', routerApi); app.use((req, res, next) => { web.channels.list(function(err, info) { if (err) { console.log('Error:', err); } else { for(var i in info.channels) { console.log(info.channels[i].name); } } }); // console.log('messages', web.messages.channel); // web.chat.postMessage('#something', 'Hello there', function(err, res) { // if (err) { // console.log('Error:', err); // } else { // console.log('Message sent: ', res); // } // }); }); // Start the server app.listen(PORT, () => { console.log(`We're online on port ${PORT}`); }); // Error logging middleware app.use((err, req, res, next) => { console.error(err); res.status(err.status || 500).send(err.message || 'Internal server error'); }); <file_sep>// API router // Required packages const express = require('express'); // Required files const routerSlack = require('./slack'); // Router creation const router = express.Router(); module.exports = router; router.use('/slack', routerSlack); router.use((req, res, next) => { console.log('in /api'); res.send('In router'); });
c75fc9fabc61a3164eac213e96fd37e51091ff95
[ "JavaScript" ]
3
JavaScript
runandrew/fs-fellow-hackathon
0ff7afb0d5702ad140ccd0c6f696f6ffac7714a6
bc6b77bae18c3727cb5bdee86582887b481cba1d
refs/heads/master
<file_sep>#include "Ticket.h" Ticket::Ticket() { } string* Ticket::GetFields(string ticket) { string fields[5]; string currentField; int j = 0; for (int i = 0; i < 5; i++) { currentField = ""; while (ticket[j] != ';') { currentField += ticket[j]; j++; } fields[i] = currentField; j++; } return fields; } <file_sep>#pragma once #include <string> using namespace std; class Service { public: Service(); static string* GetFields(string service); int Id; string Title; float Price; };<file_sep>#pragma once #include "DateTime.h" #include <string> using namespace std; class PatientCard { public: PatientCard(); static string* GetFields(string patientCard); int Id; string Name; string Surname; string Phone; string Email; DateTime DateOfBirth; DateTime DateOfRegistartion; }; <file_sep>#include "ServiceDAO.h" ServiceDAO::ServiceDAO() { } void ServiceDAO::LoadServices() { ifstream file(FILE_PATH); string serviceString; while (getline(file, serviceString)) { Service service; auto serviceFields = Service::GetFields(serviceString); service.Id = stoi(serviceFields[0]); service.Title = serviceFields[1]; service.Price = stof(serviceFields[2]); Services.push_back(service); } file.close(); } void ServiceDAO::SaveServices() { ofstream file(FILE_PATH); for each (Service service in Services) { file << service.Id << ";" << service.Title << ";" << service.Price << ";" << endl; } file.close(); } <file_sep>#include "TicketDAO.h" TicketDAO::TicketDAO() { } void TicketDAO::LoadTickets() { ifstream file(FILE_PATH); string ticketString; while (getline(file, ticketString)) { Ticket ticket; auto ticketFields = Ticket::GetFields(ticketString); ticket.Id = stoi(ticketFields[0]); ticket.PatientCardId = stoi(ticketFields[1]); ticket.ServiceId = stoi(ticketFields[2]); auto dateOfBirthFields = DateTime::GetFields(ticketFields[3]); ticket.DateTime.Days = stoi(dateOfBirthFields[0]); ticket.DateTime.Months = stoi(dateOfBirthFields[1]); ticket.DateTime.Years = stoi(dateOfBirthFields[2]); ticket.DateTime.Hours = stoi(dateOfBirthFields[3]); ticket.DateTime.Minutes = stoi(dateOfBirthFields[4]); ticket.DateTime.Seconds = stoi(dateOfBirthFields[5]); if (ticketFields[4] == "0" || ticketFields[4] == "false" || ticketFields[4] == "False" || ticketFields[4] == "FALSE") { ticket.IsUsed = false; } else{ ticket.IsUsed = true; } Tickets.push_back(ticket); } file.close(); } void TicketDAO::SaveTickets() { ofstream file(FILE_PATH); for each (Ticket ticket in Tickets) { file << ticket.Id << ";" << ticket.PatientCardId << ";" << ticket.ServiceId << ";" << ticket.DateTime.ToString() << ";" << ticket.IsUsed << ";" << endl; } file.close(); } <file_sep>#pragma once #include <string> using namespace std; class DateTime { public: DateTime(); static string* GetFields(string dateTime); string ToString(); int Seconds; int Minutes; int Hours; int Days; int Months; int Years; };<file_sep>#pragma once #include"Patient—ard.h" #include<string> #include<vector> #include<fstream> class PatientCardDAO { private: string FILE_PATH = "Data/PatientCards.txt"; public: PatientCardDAO(); vector<PatientCard> PatientCards; void LoadPatientCards(); void SavePatientCards(); }; <file_sep>#include "Service.h" Service::Service() { } string* Service::GetFields(string service) { string fields[3]; string currentField; int j = 0; for (int i = 0; i < 3; i++) { currentField = ""; while (service[j] != ';') { currentField += service[j]; j++; } fields[i] = currentField; j++; } return fields; } <file_sep>#include "Patient—ard.h" PatientCard::PatientCard() { } string* PatientCard::GetFields(string patientCard) { string fields[7]; string currentField; int j = 0; for (int i = 0; i < 7; i++) { currentField = ""; while (patientCard[j] != ';') { currentField += patientCard[j]; j++; } fields[i] = currentField; j++; } return fields; } <file_sep>#include "DateTime.h" DateTime::DateTime() { } string* DateTime::GetFields(string dateTime) { string fields[6]; fields[0] = dateTime[0] + dateTime[1]; fields[1] = dateTime[3] + dateTime[4]; fields[2] = dateTime[6] + dateTime[7]; fields[3] = dateTime[9] + dateTime[10]; fields[4] = dateTime[12] + dateTime[13]; fields[5] = dateTime[15] + dateTime[16]; return fields; } string DateTime::ToString() { return to_string(Days)+"."+to_string(Months)+"."+to_string(Years)+" "+to_string(Hours)+"."+to_string(Minutes)+"."+to_string(Seconds); } <file_sep>#pragma once #include<vector> #include<fstream> #include<string> #include"Ticket.h" using namespace std; class TicketDAO { private: string FILE_PATH = "Data/Tickets.txt"; public: TicketDAO(); vector<Ticket> Tickets; void LoadTickets(); void SaveTickets(); };<file_sep>#include "PatientCardDAO.h" PatientCardDAO::PatientCardDAO() { } void PatientCardDAO::LoadPatientCards() { ifstream file(FILE_PATH); string patientCardString; while (getline(file, patientCardString)) { PatientCard patientCard; auto patientCardFields = PatientCard::GetFields(patientCardString); patientCard.Id = stoi(patientCardFields[0]); patientCard.Name = patientCardFields[1]; patientCard.Surname = patientCardFields[2]; patientCard.Phone = patientCardFields[3]; patientCard.Email = patientCardFields[4]; auto dateOfBirthFields = DateTime::GetFields(patientCardFields[5]); patientCard.DateOfBirth.Days = stoi(dateOfBirthFields[0]); patientCard.DateOfBirth.Months = stoi(dateOfBirthFields[1]); patientCard.DateOfBirth.Years = stoi(dateOfBirthFields[2]); patientCard.DateOfBirth.Hours = stoi(dateOfBirthFields[3]); patientCard.DateOfBirth.Minutes = stoi(dateOfBirthFields[4]); patientCard.DateOfBirth.Seconds = stoi(dateOfBirthFields[5]); auto dateOfRegistrationFields = DateTime::GetFields(patientCardFields[6]); patientCard.DateOfRegistartion.Days = stoi(dateOfRegistrationFields[0]); patientCard.DateOfRegistartion.Months = stoi(dateOfRegistrationFields[1]); patientCard.DateOfRegistartion.Years = stoi(dateOfRegistrationFields[2]); patientCard.DateOfRegistartion.Hours = stoi(dateOfRegistrationFields[3]); patientCard.DateOfRegistartion.Minutes = stoi(dateOfRegistrationFields[4]); patientCard.DateOfRegistartion.Seconds = stoi(dateOfRegistrationFields[5]); PatientCards.push_back(patientCard); } file.close(); } void PatientCardDAO::SavePatientCards() { ofstream file(FILE_PATH); for each (PatientCard patientCard in PatientCards) { file << patientCard.Id << ";" << patientCard.Name << ";" << patientCard.Surname << ";" << patientCard.Phone << ";" << patientCard.Email << ";" << patientCard.DateOfBirth.ToString() << ";" << patientCard.DateOfRegistartion.ToString() << ";" << endl; } file.close(); } <file_sep>#pragma once #include<fstream> #include<string> #include<vector> #include"Service.h" using namespace std; class ServiceDAO { private: string FILE_PATH = "Data/Services.txt"; public: ServiceDAO(); void LoadServices(); void SaveServices(); vector<Service> Services; }; <file_sep>#pragma once #include "DateTime.h" class Ticket { public: Ticket(); static string* GetFields(string ticket); int Id; int PatientCardId; int ServiceId; DateTime DateTime; bool IsUsed; };
7186bc73058e0a81b36a1099ddc8ac1fe82b0771
[ "C++" ]
14
C++
TwiXyl9/DentalClinic
1d935ca7c1f681da8f7eb5d0d70427ef4cdca8f6
2aaace76898a2d76cd8c0d6f5b2cde4b92c903c9
refs/heads/master
<file_sep>import { ApiService } from './../../../services/api.service'; import { Component, OnInit } from '@angular/core'; import { LoadingController, ModalController } from '@ionic/angular'; @Component({ selector: 'app-buscar-funcionario', templateUrl: './buscar-funcionario.page.html', styleUrls: ['./buscar-funcionario.page.scss'], }) export class BuscarFuncionarioPage implements OnInit { funcionarios = [] constructor( public loadingController: LoadingController, public modalController: ModalController, private api: ApiService ) { } ngOnInit() { this.buscarFuncionarios() } async buscarFuncionarios() { let loading = await this.loadingController.create({ message: "Carregando funcionários..." }) loading.present(); let funcionarios = await this.api.get('funcionarios') console.log('funcionarios ===> ', funcionarios); loading.dismiss() this.funcionarios = funcionarios } fechar(funcionario?) { this.modalController.dismiss({ funcionario: funcionario }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AlertController, PopoverController, ModalController } from '@ionic/angular'; import * as moment from 'moment'; import { BuscarFuncionarioPage } from '../../funcionarios/buscar-funcionario/buscar-funcionario.page'; @Component({ selector: 'app-filtros', templateUrl: './filtros.page.html', styleUrls: ['./filtros.page.scss'], }) export class FiltrosPage implements OnInit { filtros = { status: '', data_inicial: '', data_final: '', utilizouProduto: '', funcionario_criou: '', funcionario_atribuido: '' } funcionario_criou funcionario_atribuido constructor( public alertController: AlertController, public popoverController: PopoverController, public modalController: ModalController ) { } ngOnInit() { } async filtroStatus() { const alert = await this.alertController.create({ header: 'Filtrar por Status', inputs: [ { name: 'todos', type: 'radio', label: 'Todos', value: 'Todos', checked: true }, { name: 'abertos', type: 'radio', label: 'Abertos', value: 'Aberto' }, { name: 'cancelados', type: 'radio', label: 'Cancelados', value: 'Cancelado' }, { name: 'resolvidos', type: 'radio', label: 'Resolvidos', value: 'Resolvido' }, { name: 'resolvidos', type: 'radio', label: 'Não Resolvidos', value: 'NaoResolvido' } ], buttons: ['OK'] }); await alert.present(); // this.popoverController.dismiss(query) let dados = await alert.onDidDismiss(); if (dados) { console.log('dados alerta', dados); this.filtros.status = dados.data.values } } async filtroProduto() { const alert = await this.alertController.create({ header: 'Filtrar por Uso de Produtos', inputs: [ { type: 'radio', label: 'Utilizou Produtos', value: 'true', checked: true }, { type: 'radio', label: 'Não Utilizou Produtos', value: 'false' } ], buttons: ['OK'] }); await alert.present(); // this.popoverController.dismiss(query) let dados = await alert.onDidDismiss(); console.log('dados alerta', dados); if (dados) this.filtros.utilizouProduto = dados.data.values } async filtroInicio() { const alert = await this.alertController.create({ header: 'Filtrar pelo Período', inputs: [ { name: 'inicio', label: 'Início', type: 'date' }, { name: 'final', label: 'Final', type: 'date' }, ], buttons: ['OK'] }) alert.present() let dados = await alert.onDidDismiss(); console.log('dados alerta', dados); if (dados) { this.filtros.data_inicial = dados.data.values.inicio this.filtros.data_final = dados.data.values.final } } retornar() { let chaves = Object.keys(this.filtros) let query = '?' // let query = dados.data.values == 'Todos'? '' : '?status='+dados.data.values for (let filtro of chaves) { if (this.filtros[filtro]) query += filtro + '=' + this.filtros[filtro] + '&' console.log(filtro, ': ', this.filtros[filtro]); } if (query.length == 1) query = '' else query = query.slice(0, query.length - 1) console.log('query ==> ', query); this.popoverController.dismiss(query) } retornarData(data) { return moment(data).format('DD/MM/YYYY') } async filtroFuncionario(funcionario) { let modal = await this.modalController.create({ component: BuscarFuncionarioPage, cssClass: 'modal-pequeno' }) modal.present() modal.onDidDismiss().then(async dados => { console.log('dados ==> ', dados); if (dados.data.funcionario) { this.filtros[funcionario] = dados.data.funcionario.matricula this[funcionario] = dados.data.funcionario } }) } sair(){ this.popoverController.dismiss() } } <file_sep>import { BuscarFuncionarioPage } from './../../funcionarios/buscar-funcionario/buscar-funcionario.page'; import { ApiService } from './../../../services/api.service'; import { Component, OnInit } from '@angular/core'; import { ModalController, ToastController, LoadingController } from '@ionic/angular'; @Component({ selector: 'app-abrir-chamado', templateUrl: './abrir-chamado.page.html', styleUrls: ['./abrir-chamado.page.scss'], }) export class AbrirChamadoPage implements OnInit { // descricao, funcionario_matricula, tipo_servico servicos = [ { "nome": 'ALTERAR CPS', "prioridade": 'Baixa' }, { "nome": 'AVISO DE LENTIDÃO', "prioridade": 'Alta' }, { "nome": 'DESTRAVAR SAÍDA', "prioridade": 'Baixa' }, { "nome": 'GERENCIAR USUÁRIO', "prioridade": 'Media' }, { "nome": 'MANUT. DE CÃMERAS', "prioridade": 'Media' }, { "nome": 'MANUT. DE COMPUTADOR', "prioridade": 'Alta' }, { "nome": 'MANUT. DE EMAIL', "prioridade": 'Media' }, { "nome": 'MANUT. DE IMP/SCAN.', "prioridade": 'Alta' }, { "nome": 'MANUT. DE INTERNET', "prioridade": 'Alta' }, { "nome": 'MANUT. OUTROS EQUIP.', "prioridade": 'Baixa' }, { "nome": 'MANUT. OUTROS PROG.', "prioridade": 'Baixa' }, { "nome": 'MANUT.DE TEL/RAMAL', "prioridade": 'Baixa' }, { "nome": 'MANUT. CALL CENTER', "prioridade": 'Alta' }, { "nome": 'MANUT. DO ECG/MAPA', "prioridade": 'Alta' }, { "nome": 'MANUT. SISTEMA CPC', "prioridade": 'Alta' }, { "nome": 'MANUT. SIS. DE PONTO', "prioridade": 'Alta' }, { "nome": '<NAME>. DO SUS', "prioridade": 'Baixa' }, { "nome": '<NAME>', "prioridade": 'Alta' }, { "nome": '<NAME>', "prioridade": 'Alta' }, { "nome": '<NAME>', "prioridade": 'Baixa' }, { "nome": '<NAME>', "prioridade": 'Baixa' }, { "nome": 'SOLICI.EQUIPAMENTOS', "prioridade": 'Baixa' }, { "nome": 'SUPORTE AO USUÁRIO', "prioridade": 'Baixa' }, { "nome": '<NAME>', "prioridade": 'Alta' }, { "nome": '<NAME>', "prioridade": 'Baixa' } ] chamado = { descricao: '', funcionario_matricula: '', funcionario_nome: '', tipo_servico: '' } constructor( public modalController: ModalController, public loadingController: LoadingController, public toastController: ToastController, private api: ApiService ) { } ngOnInit() { } fechar() { this.modalController.dismiss() } async buscarFuncionario() { let modal = await this.modalController.create({ component: BuscarFuncionarioPage, cssClass: 'modal-pequeno' }) modal.present() modal.onDidDismiss().then(dados => { console.log('dados ==> ', dados); if (dados.data.funcionario) { this.chamado.funcionario_matricula = dados.data.funcionario.matricula this.chamado.funcionario_nome = dados.data.funcionario.nome } }) } async salvar() { let loading = await this.loadingController.create({ message: 'Registrando Chamado...' }) loading.present() let produto = await this.api.post(JSON.stringify(this.chamado), 'chamados') console.log('produto ==> ', produto); loading.dismiss() let toast = await this.toastController.create({ message: "Chamado registrado com sucesso", duration: 3000 }) toast.present() this.fechar() } } <file_sep>import { FiltrosPage } from './filtros/filtros.page'; import { BuscarFuncionarioPage } from './../funcionarios/buscar-funcionario/buscar-funcionario.page'; import { ResolverChamadoPage } from './resolver-chamado/resolver-chamado.page'; import { AbrirChamadoPage } from './abrir-chamado/abrir-chamado.page'; import { ModalController, LoadingController, ActionSheetController, ToastController, PopoverController } from '@ionic/angular'; import { Component, OnInit } from '@angular/core'; import { ApiService } from 'src/app/services/api.service'; @Component({ selector: 'app-chamados', templateUrl: './chamados.page.html', styleUrls: ['./chamados.page.scss'], }) export class ChamadosPage implements OnInit { chamados = [] constructor( public loadingController: LoadingController, public modalController: ModalController, public actionSheetController: ActionSheetController, public toastController: ToastController, public popoverController: PopoverController, private api: ApiService ) { } ngOnInit() { this.buscarChamados() } async addChamado() { let modal = await this.modalController.create({ component: AbrirChamadoPage, cssClass: 'modal-pequeno' }) modal.present() modal.onDidDismiss().then(() => { this.buscarChamados() }) } async resolverChamado() { let modal = await this.modalController.create({ component: ResolverChamadoPage, cssClass: 'modal-pequeno' }) modal.present() } async buscarChamados(query='') { let loading = await this.loadingController.create({ message: "Carregando chamados..." }) loading.present(); let chamados = await this.api.get('chamados'+query) console.log('chamados ===> ', chamados); loading.dismiss() this.chamados = chamados } async abrirAction(id, e) { e.stopPropagation() let actionSheet = await this.actionSheetController.create({ header: 'Opções', buttons: [ { text: 'Atribuir Funcionário', handler: () => { this.atribuirFuncionario(id) } } ] }) actionSheet.present() } async atribuirFuncionario(id_chamado) { let atribuir = { id: id_chamado, funcionario_matricula: null } let modal = await this.modalController.create({ component: BuscarFuncionarioPage, cssClass: 'modal-pequeno' }) modal.present() modal.onDidDismiss().then(async dados => { console.log('dados ==> ', dados); if (dados.data.funcionario) { let loading = await this.loadingController.create({ message: "Atribuindo funcionário..." }) loading.present(); atribuir.funcionario_matricula = dados.data.funcionario.matricula console.log('atribuir ==> ', atribuir); let atribuirChamado = await this.api.post(JSON.stringify(atribuir), 'atribuir') loading.dismiss() let toast = await this.toastController.create({ message: "Funcionário atribuido com sucesso", duration: 3000 }) toast.present() } }) } async abrirChamado(id) { let modal = await this.modalController.create({ component: ResolverChamadoPage, cssClass: 'modal-pequeno', componentProps: { id: id } }) modal.present() modal.onDidDismiss().then(() => { this.buscarChamados() }) } async abrirFiltros(ev: any) { const popover = await this.popoverController.create({ component: FiltrosPage, event: ev, translucent: true }); await popover.present(); let dados = await popover.onDidDismiss() console.log('dados ==> ', dados); if(dados) this.buscarChamados(dados.data) } } <file_sep>### Equipe - <NAME>; - <NAME>; - <NAME> [TOCM] #Instalação ###Instalar Node.Js e NPM `$ sudo apt-get install nodejs` ###Verificar Instalação `$ node -v ` **v13.3.0** `$ npm -v ` **6.13.1** ###Instalar Pacotes `$ npm install ` #Executar aplicação `npm start` **Acessar no navegador link indicado no console**<file_sep>import { FiltrosPageModule } from './pages/chamados/filtros/filtros.module'; import { BuscarProdutosPageModule } from './pages/estoque/buscar-produtos/buscar-produtos.module'; import { BuscarFuncionarioPageModule } from './pages/funcionarios/buscar-funcionario/buscar-funcionario.module'; import { ApiService } from './services/api.service'; import { ResolverChamadoPageModule } from './pages/chamados/resolver-chamado/resolver-chamado.module'; import { AbrirChamadoPageModule } from './pages/chamados/abrir-chamado/abrir-chamado.module'; import { CadastrarProdutoPageModule } from './pages/estoque/cadastrar-produto/cadastrar-produto.module'; import { CadastrarFuncionarioPageModule } from './pages/funcionarios/cadastrar-funcionario/cadastrar-funcionario.module'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { CadastrarSetorPageModule } from './pages/funcionarios/cadastrar-setor/cadastrar-setor.module'; import { HttpClientModule } from '@angular/common/http'; import { ServiceWorkerModule } from '@angular/service-worker'; import { environment } from '../environments/environment'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [ BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule, CadastrarFuncionarioPageModule, CadastrarSetorPageModule, CadastrarProdutoPageModule, AbrirChamadoPageModule, ResolverChamadoPageModule, BuscarFuncionarioPageModule, BuscarProdutosPageModule, FiltrosPageModule, ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) ], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, ApiService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { ApiService } from './../../services/api.service'; import { CadastrarProdutoPage } from './cadastrar-produto/cadastrar-produto.page'; import { ModalController, LoadingController } from '@ionic/angular'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-estoque', templateUrl: './estoque.page.html', styleUrls: ['./estoque.page.scss'], }) export class EstoquePage implements OnInit { produtos = [] constructor( public modalCtrl: ModalController, public loadingController: LoadingController, private api: ApiService ) { } ngOnInit() { this.buscarEstoque() } async addProduto() { let modal = await this.modalCtrl.create({ component: CadastrarProdutoPage, cssClass: 'modal-pequeno' }); modal.present(); modal.onDidDismiss().then(() => { this.buscarEstoque() }) } async buscarEstoque() { let loading = await this.loadingController.create({ message: "Buscando produtos do estoque..." }) loading.present(); let produtos = await this.api.get('produtos') loading.dismiss() this.produtos = produtos } } <file_sep>import { ApiService } from './../../../services/api.service'; import { ModalController, LoadingController, ToastController } from '@ionic/angular'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-cadastrar-produto', templateUrl: './cadastrar-produto.page.html', styleUrls: ['./cadastrar-produto.page.scss'], }) export class CadastrarProdutoPage implements OnInit { produto = { nome: '', descricao: '', quantidade: null } constructor( public modalCtrl: ModalController, public loadingController: LoadingController, public toastController: ToastController, private api: ApiService, ) { } ngOnInit() { } async salvar() { let loading = await this.loadingController.create({message: 'Cadastrando Produto'}) loading.present() let produto = await this.api.post(JSON.stringify(this.produto), 'produtos') console.log('produto ==> ', produto); loading.dismiss() let toast = await this.toastController.create({message: "Produto cadastrado com sucesso", duration: 3000}) toast.present() this.fechar() } fechar() { this.modalCtrl.dismiss() } } <file_sep>import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', loadChildren: () => import('./pages/home/home.module').then(m => m.HomePageModule) }, { path: 'funcionarios', loadChildren: './pages/funcionarios/funcionarios.module#FuncionariosPageModule' }, { path: 'estoque', loadChildren: './pages/estoque/estoque.module#EstoquePageModule' }, { path: 'chamados', loadChildren: './pages/chamados/chamados.module#ChamadosPageModule' }, { path: 'cadastrar-funcionario', loadChildren: './pages/funcionarios/cadastrar-funcionario/cadastrar-funcionario.module#CadastrarFuncionarioPageModule' }, { path: 'cadastrar-setor', loadChildren: './pages/funcionarios/cadastrar-setor/cadastrar-setor.module#CadastrarSetorPageModule' }, { path: 'cadastrar-produto', loadChildren: './pages/estoque/cadastrar-produto/cadastrar-produto.module#CadastrarProdutoPageModule' }, { path: 'abrir-chamado', loadChildren: './pages/chamados/abrir-chamado/abrir-chamado.module#AbrirChamadoPageModule' }, { path: 'resolver-chamado/:id', loadChildren: './pages/chamados/resolver-chamado/resolver-chamado.module#ResolverChamadoPageModule' }, { path: 'buscar-funcionario', loadChildren: './pages/funcionarios/buscar-funcionario/buscar-funcionario.module#BuscarFuncionarioPageModule' }, { path: 'relatorios', loadChildren: './pages/relatorios/relatorios.module#RelatoriosPageModule' }, { path: 'buscar-produtos', loadChildren: './pages/estoque/buscar-produtos/buscar-produtos.module#BuscarProdutosPageModule' }, { path: 'filtros', loadChildren: './pages/chamados/filtros/filtros.module#FiltrosPageModule' } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule {} <file_sep>import { ApiService } from './../../../services/api.service'; import { ModalController, LoadingController, ToastController } from '@ionic/angular'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-cadastrar-funcionario', templateUrl: './cadastrar-funcionario.page.html', styleUrls: ['./cadastrar-funcionario.page.scss'], }) export class CadastrarFuncionarioPage implements OnInit { setores = [ 'ADMINISTRAÇÃO', 'ARQUIVO', 'ESTAGIÁRIO', 'AUDITÓRIA PRON.', 'AUTORIZAÇÃO', 'AUDITÓRIO', 'BIOIMAGEM', 'CENTRO CIRÚRG.', 'COLONOSCOPIA', 'COMERCIAL', 'CONTABIL. RH', 'ELETROCARD.', 'COOR. ENFERM.', 'FARMÁCIA', 'FATURAMENTO', 'FINANCEIRO', 'INTERNAMENTO', 'LABORATÓRIO', 'LECO', 'MANUTENÇÃO', 'HOTELARIA', 'MARKET. QUAL.', 'MÉDICOS', 'PABX', 'PORTARIA', 'POSTO ENFERM.', 'RECEPÇÃO', 'MARCAÇÃO', 'SND', 'ULTRASSOM', 'URODINÃMICA', 'UROFLUXO', 'TI', 'SERVIDORES' ] funcionario = { nome: '', matricula: null, tipo: null, senha: '', setor: '' } constructor( public modalCtrl: ModalController, public loadingCtrl: LoadingController, public tostCtrl: ToastController, private api: ApiService ) { } ngOnInit() { } fechar() { this.modalCtrl.dismiss() } async salvar() { let loading = await this.loadingCtrl.create({ message: 'Cadastrando...' }) loading.present() let funcionario = await this.api.post(JSON.stringify(this.funcionario), 'funcionarios') loading.dismiss() console.log('funcionario ==> ', funcionario); let toast = await this.tostCtrl.create({ message: "Funcionário cadastrado com sucesso!", duration: 3000 }) toast.present() this.fechar() } } <file_sep>import { ApiService } from './../../services/api.service'; import { CadastrarSetorPage } from './cadastrar-setor/cadastrar-setor.page'; import { CadastrarFuncionarioPage } from './cadastrar-funcionario/cadastrar-funcionario.page'; import { Component, OnInit } from '@angular/core'; import { ModalController, LoadingController } from '@ionic/angular'; @Component({ selector: 'app-funcionarios', templateUrl: './funcionarios.page.html', styleUrls: ['./funcionarios.page.scss'], }) export class FuncionariosPage implements OnInit { funcionarios = [] constructor( public modalCtrl: ModalController, public loadingController: LoadingController, private api: ApiService ) { } ngOnInit() { this.buscarFuncionarios() } async addFuncionario() { let modal = await this.modalCtrl.create({ component: CadastrarFuncionarioPage, cssClass: 'modal-pequeno' }) modal.present(); modal.onDidDismiss().then(()=>{ this.buscarFuncionarios() }) } async addSetor() { let modal = await this.modalCtrl.create({ component: CadastrarSetorPage, cssClass: 'modal-pequeno' }) modal.present(); } async buscarFuncionarios(){ let loading = await this.loadingController.create({message: "Carregando funcionários..."}) loading.present(); let funcionarios = await this.api.get('funcionarios') console.log('funcionarios ===> ', funcionarios); loading.dismiss() this.funcionarios = funcionarios } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; const CURRENT_URL_API = 'https://chamados-andro.herokuapp.com/' @Injectable({ providedIn: 'root' }) export class ApiService { constructor( public http: HttpClient ) { } post(body, endpoint) { return new Promise<any>(done => { console.log('body: ', body); const hdrs = new HttpHeaders({ 'Content-Type': 'application/json' }); let data = null; this.http.post(CURRENT_URL_API + endpoint, body, { headers: hdrs }).subscribe(dados => { data = dados; console.log('dados aleatórios: ', dados); done(dados) }, err => { data = err console.log('Error: ', err); done(err) }); }) } get(endpoint) { return new Promise<any>(done => { const hdrs = new HttpHeaders({ 'Content-Type': 'application/json' }); let data = null; this.http.get(CURRENT_URL_API + endpoint, { headers: hdrs }).subscribe(dados => { console.log('dados recebidos', dados); data = dados; done(data) }, err => { console.log('Error'); done(err) }) return data; }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { LoadingController, ModalController } from '@ionic/angular'; import { ApiService } from 'src/app/services/api.service'; @Component({ selector: 'app-buscar-produtos', templateUrl: './buscar-produtos.page.html', styleUrls: ['./buscar-produtos.page.scss'], }) export class BuscarProdutosPage implements OnInit { produtos = [] constructor( public loadingController: LoadingController, public modalController: ModalController, private api: ApiService ) { } ngOnInit() { this.buscarEstoque() } async buscarEstoque() { let loading = await this.loadingController.create({ message: "Buscando produtos do estoque..." }) loading.present(); let produtos = await this.api.get('produtos') loading.dismiss() this.produtos = produtos } fechar(produto?) { this.modalController.dismiss({ produto: produto }) } } <file_sep>import { BuscarProdutosPage } from './../../estoque/buscar-produtos/buscar-produtos.page'; import { ApiService } from 'src/app/services/api.service'; import { Component, OnInit } from '@angular/core'; import { LoadingController, ModalController, ToastController, NavParams } from '@ionic/angular'; import { ActivatedRoute } from '@angular/router'; import * as moment from 'moment'; import { BuscarFuncionarioPage } from '../../funcionarios/buscar-funcionario/buscar-funcionario.page'; @Component({ selector: 'app-resolver-chamado', templateUrl: './resolver-chamado.page.html', styleUrls: ['./resolver-chamado.page.scss'], }) export class ResolverChamadoPage implements OnInit { chamado = null atribuir = null finalizar = { descricao: '', status: '' } produto = { produto_id: '', produto_nome: '', quantidade: null } id constructor( public loadingController: LoadingController, public modalController: ModalController, public toastController: ToastController, public navParams: NavParams, private api: ApiService ) { } ngOnInit() { this.id = this.navParams.get('id') this.carregarChamado(this.id); } async carregarChamado(id) { // let loading = await this.loadingController.create({ message: "Carregando chamado..." }) // loading.present(); let chamado = await this.api.get('chamados/' + id) console.log('chamado ===> ', chamado); // loading.dismiss() this.chamado = chamado } fechar() { this.modalController.dismiss() } retornarData(data) { return moment(data).format('DD/MM/YYYY HH:mm') } async finalizarChamado() { this.finalizar['id'] = this.id let loading = await this.loadingController.create({ message: "Finalizando chamado..." }) loading.present(); await this.api.post(JSON.stringify(this.finalizar), 'finalizar') loading.dismiss() let toast = await this.toastController.create({ message: "Chamado finalizado com sucesso", duration: 3000 }) toast.present() this.fechar(); } async atribuirFuncionario() { let atribuir = { id: this.id, funcionario_matricula: null } let modal = await this.modalController.create({ component: BuscarFuncionarioPage, cssClass: 'modal-pequeno' }) modal.present() modal.onDidDismiss().then(async dados => { console.log('dados ==> ', dados); if (dados.data.funcionario) { let loading = await this.loadingController.create({ message: "Atribuindo funcionário..." }) loading.present(); atribuir.funcionario_matricula = dados.data.funcionario.matricula console.log('atribuir ==> ', atribuir); let atribuirChamado = await this.api.post(JSON.stringify(atribuir), 'atribuir') loading.dismiss() let toast = await this.toastController.create({ message: "Funcionário atribuido com sucesso", duration: 3000 }) toast.present() this.carregarChamado(this.id) } }) } // produto = { // produto_id: '', // produto_nome: '', // quantidade: null // } async buscarProduto() { let modal = await this.modalController.create({ component: BuscarProdutosPage, cssClass: 'modal-pequeno' }) modal.present() modal.onDidDismiss().then(dados => { console.log('dados ==> ', dados); if (dados.data.produto) { this.produto.produto_id = dados.data.produto._id this.produto.produto_nome = dados.data.produto.nome } }) } async adicionarProduto() { this.produto['id'] = this.id let loading = await this.loadingController.create({ message: "Adicionando produto..." }) loading.present(); let atribuirChamado = await this.api.post(JSON.stringify(this.produto), 'addProduto') loading.dismiss() let toast = await this.toastController.create({ message: "Produto adicionado com sucesso", duration: 3000 }) toast.present() this.carregarChamado(this.id) } }
cee949d629ead02e22736c3bd835445e077f47ac
[ "Markdown", "TypeScript" ]
14
TypeScript
yurirssilva/app-chamados
f430f7d6c69dc0fac413f62ce0d363d3c2808ba2
1124ff0b03f8c30c9fa9dd8e8bbf8b27aa221af2
refs/heads/master
<repo_name>jery-oshin/explore-air<file_sep>/src/components/stepThree/stepThree.component.jsx import React from 'react' import './stepThree.style.css'; import logo from './logo.png'; import product from './product-3.png'; const StepThree = () => { return ( <div className="step-four"> <div className="step-four-header"> <div className="selection-qualifies"> <img className='step-four-logo' src={logo} alt=""/> <div className="free-shipping"> <p>This selection qualifies for</p> <p>FREE SHIPPING</p> </div> </div> <div className="explore-air-image"> <img src={product} alt=""/> </div> </div> <h2 className='step-title'>Step 3: Shihpping Details</h2> <form action=""> <div class="input-group mb-3"> <select class="custom-select" id="inputGroupSelect01"> <option selected>Choose...</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Town/City" aria-label="Town/City" aria-describedby="basic-addon1"/> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Street & House Number" aria-label="Street-House-Number" aria-describedby="basic-addon1"/> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Zip / Postal Code" aria-label="Zip-Postal-Code" aria-describedby="basic-addon1"/> </div> </form> </div> ); } export default StepThree;<file_sep>/src/components/lastSteps/lastSteps.component.jsx import React, {useState} from 'react' import StepFive from '../stepFive/stepFive.component'; import StepFour from '../stepFour/stepFour.component'; import StepThree from '../stepThree/stepThree.component'; import SendMeButton from '../submit/submit.component'; import Footer from '../footer/footer.component'; import './lastSteps.style.css'; const LastSteps = () => { const [check, setCheck ] = useState(true); const showStepFive = () => { setCheck(!check); } return ( <div className='last-steps'> <StepThree /> <StepFour handleRadioState={showStepFive} radioState={check} /> {check === true ? <StepFive /> : null} <SendMeButton /> <Footer /> </div> ); } export default LastSteps;<file_sep>/src/components/header/header.component.jsx import React from 'react'; import logo from './logo.png'; import './header.style.css'; const Header = () => { return ( <div className='image'> <img className='headerImage' src={logo}/> </div> ); } export default Header;<file_sep>/src/components/stepTwo/stepTwo.component.jsx import React from 'react' import './stepTwo.style.css'; const StepTwo = () => { return ( <div className='step-two'> <h2 className='step-title'>Stem 2: Contact Information </h2> <form className='step-two-form'> <div className="gender"> <div class="form-check"> <input class="form-check-input" type="radio" name="gender" id="Mr" value="Mr"/> <label class="form-check-label" for="Mr"> Mr </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="gender" id="Mrs" value="Mrs"/> <label class="form-check-label" for="Mrs"> Mr </label> </div> </div> <div className="personal-information"> <div class="input-group mb-3"> <input type="text" className="form-control" placeholder="Last Name" aria-label="Last-Name" aria-describedby="basic-addon1"/> </div> <div class="input-group mb-3"> <input type="text" className="form-control" placeholder="First Name" aria-label="First Name" aria-describedby="basic-addon1"/> </div> <div class="form-group"> <input type="email" className="form-control" placeholder='Email Address' id="exampleInputEmail1" aria-describedby="emailHelp"/> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div className="form-group"> <div class="input-group mb-3"> <div class="input-group-prepend"> <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">country</button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> <div role="separator" class="dropdown-divider"></div> <a class="dropdown-item" href="#">Separated link</a> </div> </div> <input type="text" class="form-control" placeholder='(829) 312 9631' aria-label="Text input with dropdown button" pattern='^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$'/> </div> </div> </div> </form> </div> ); } export default StepTwo;<file_sep>/src/components/stepOne/stepOne.component.jsx import React from 'react'; import './stepOne.style.css'; import bestseller from './bestseller.png'; const StepOne = () => { return ( <div className='step-one'> <h2 className='step-title'>Step 1: Choose The Number of Items </h2> <div className='step-one-subtitle'> <h3>Article</h3> <h3>Total Price</h3> </div> <form className='step-one-form' action=""> <div className="choose form-check"> <img className='bestseller' src={bestseller} alt=""/> <input className="step-one-input form-check-input" type="radio" name="buy-article" id="exampleRadios0" value="option1"/> <div className='articles'> <div className="label"> <label className="form-check-label" for="exampleRadios0"> Buy 3 Explore AIR, GET 2 </label> <label className="form-check-label" for="exampleRadios0"> FREE (3 458 RD$/each) </label> </div> <label className="form-check-label" for="exampleRadios0"> 17 291 RD$ </label> </div> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="buy-article" id="exampleRadios1" value="option1"/> <div className='articles'> <div className="label"> <label className="form-check-label" for="exampleRadios1"> Buy 3 Explore AIR, GET 2 </label> <label className="form-check-label" for="exampleRadios1"> FREE (3 458 RD$/each) </label> </div> <label className="form-check-label" for="exampleRadios1"> 17 291 RD$ </label> </div> </div> <div class="form-check"> <input className="form-check-input" type="radio" name="buy-article" id="exampleRadios2" value="option2"/> <div className='articles'> <div className="label"> <label class="form-check-label" for="exampleRadios2"> Buy 3 Explore AIR, GET 2 </label> <label class="form-check-label" for="exampleRadios2"> FREE (3 458 RD$/each) </label> </div> <label class="form-check-label" for="exampleRadios2"> 17 291 RD$ </label> </div> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="buy-article" id="exampleRadios3" value="option3"/> <div className='articles'> <div className="label"> <label className="form-check-label" for="exampleRadios3"> Buy 3 Explore AIR, GET 2 </label> <label className="form-check-label" for="exampleRadios3"> FREE (3 458 RD$/each) </label> </div> <label className="form-check-label" for="exampleRadios3"> 17 291 RD$ </label> </div> </div> <div className="form-check"> <input class="form-check-input" type="radio" name="buy-article" id="exampleRadios4" value="option4"/> <div className='articles'> <div className="label"> <label className="form-check-label" for="exampleRadios4"> Buy 3 Explore AIR, GET 2 </label> <label className="form-check-label" for="exampleRadios4"> FREE (3 458 RD$/each) </label> </div> <label className="form-check-label" for="exampleRadios4"> 17 291 RD$ </label> </div> </div> </form> </div> ); } export default StepOne;<file_sep>/src/components/off/off.component.jsx import React from 'react' import './off.style.css'; const Off = () => { return ( <div className='off'> <div className='off-card'> <div className='off-subcard'> 50% OFF </div> </div> <div className="off-description"> Your 50% Descount has been applied IMPORTANT ! Offer Valid for : 0:00 </div> <div className="off-description-note"> Do not browse away from this page ! Free Delivery Available Today ! </div> </div> ); } export default Off;<file_sep>/src/components/stepFour/stepThree.component.jsx // import React from 'react' // import './stepThree.style.css'; // import logo from './logo.png'; // import product from './product-3.png'; // import paypal from './paypal.svg'; // import card from './card.svg'; // import visa from './visa.svg'; // import mastercard from './mastercard.svg'; // const StepFour = () => { // return ( // <div className="step-four"> // <div className="step-four-header"> // <div className="selection-qualifies"> // <img className='step-four-logo' src={logo} alt=""/> // <div className="free-shipping"> // <p>This selection qualifies for</p> // <p>FREE SHIPPING</p> // </div> // </div> // <div className="explore-air-image"> // <img src={product} alt=""/> // </div> // </div> // <h2 className='step-title'>Step 3: Payment Method</h2> // <div className="payment-method"> // <label className="form-check-label payment-card credit-card form-check" for="credit-card"> // <input className="payment-radio form-check-input" type="radio" name="payment" id="credit-card" value="credit-card"/> // <div className="option"> // <img className='card' src={card} alt=""/> // Credit Card // <div className="type-of-card"> // <img src={visa} alt=""/> // <img src={mastercard} alt=""/> // </div> // </div> // </label> // <label className="payment-card paypal form-check" for="paypal"> // <input className="payment-radio form-check-input" type="radio" name="payment" id="paypal" value="paypal"/> // <img src={paypal} alt=''/> // </label> // </div> // </div> // ); // } // export default StepFour;<file_sep>/src/components/stepFive/stepFive.component.jsx import React from 'react' import './stepFive.style.css'; const StepFive = () => { return ( <div className='step-five'> <h2 className='step-title'>Step 5: Payment Details</h2> <div className="payment-details"> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Card Number" aria-label="Card-Number" aria-describedby="basic-addon1"/> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="MM / YYYY" aria-label="MM-YYYY" aria-describedby="basic-addon1" pattern="^((0[1-9])|(1[0-2]))\/((2009)|(20[1-2][0-9]))$"/> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Security Code" aria-label="Security-Code" aria-describedby="basic-addon1"/> </div> </div> </div> ); } export default StepFive;<file_sep>/src/components/discount/discount.component.jsx import React from 'react' import './discount.style.css'; import discount from './discount.png'; import StepOne from '../stepOne/stepOne.component'; import StepTwo from '../stepTwo/stepTwo.component'; const Discount = () => { return ( <div className='card-discount'> <div className="image-discount"> <img src={discount} alt="" align='left'/> </div> <div className="description-discount"> <p>Your 50 % Discount Code has been applied </p> <p>ATTENTION, This Code Expires In : 0:00</p> <p> Do not browse away from this page! </p> <p>Free Delivery Available Today! </p> </div> <StepOne /> <StepTwo /> </div> ); } export default Discount;<file_sep>/src/components/firstSteps/firstSteps.component.jsx import React from 'react' import StepOne from '../stepOne/stepOne.component'; const FirsSteps = () => { return ( <div className='first-steps'> <StepOne /> </div> ); } export default FirsSteps;<file_sep>/src/components/offer/offer.component.jsx import React from 'react' import { ReactComponent as Icon } from './truc.svg'; import './offer.style.css'; const Offer = () => { return ( <div className='offer'> <h6>SPECIAL OFFER:</h6> <p>Get Explore AIR now at the special promo price of</p> <div className="price"> <p>RD$ 5 761 RD $11 522</p> </div> <div className="save"> SAVE 50% </div> <div className='card'> <div className='freeShipping'> <Icon className='icon' /> <p> FREE SHIPPING </p> </div> <p>on All Today's Order !</p> </div> </div> ); } export default Offer;
2ea173491f78856f99a97adafaf595eab03230be
[ "JavaScript" ]
11
JavaScript
jery-oshin/explore-air
24a5ec59d0d1adbfa1744033c1755beb607bf9fc
01b7950428573a9713bf797a28b14a09aac707d0
refs/heads/master
<repo_name>TrisTOON/web-academy<file_sep>/practical-works/03-js/resources/correction.js /* ~~~~ Constants ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const headers = ["Nom", "Population", "Surface", "Département", "Région"]; const keys = ["nom", "population", "surface", "codeDepartement", "codeRegion"]; const types = ["string", "number", "number", "string", "string"]; /* ~~~~ Helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const getSearchParams = (form) => { const formData = new FormData(form); const searchParams = new URLSearchParams(formData); return searchParams; }; const getLocalURL = (searchParams) => { const localURL = new URL(location); localURL.hash = ""; localURL.search = searchParams; return localURL; }; const getRemoteURL = (searchParams) => { const remoteURL = new URL("https://geo.api.gouv.fr/communes"); remoteURL.search = searchParams; return remoteURL; }; /* ~~~~ Initialization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const initForm = () => { const form = document.querySelector("header > form"); const currentURL = new URL(location); const currentSearchParams = currentURL.searchParams; if (currentSearchParams.has("nom")) { const input = computeInput(currentSearchParams); renderField(form, input); } return form; }; const initTable = () => { const main = document.querySelector("main"); const table = document.createElement("table"); main.append(table); table.createCaption(); const head = table.createTHead(); const row = head.insertRow(); for (const header of headers) { const cell = document.createElement("th"); row.append(cell); cell.textContent = header; cell.tabIndex = 0; } table.createTBody(); return table; }; /* ~~~~ State computing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const computeState = async (searchParams) => { const input = computeInput(searchParams); const output = await computeOutput(searchParams); return { input: input, output: output, }; }; const computeInput = (searchParams) => { const input = searchParams.get("nom"); return input; }; const computeOutput = async (searchParams) => { const remoteURL = getRemoteURL(searchParams); const response = await fetch(remoteURL); const output = await response.json(); return output; }; /* ~~~~ State rendering ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const renderState = (form, table, state) => { const input = state.input; const output = state.output; renderForm(form, input); renderTable(table, input, output); }; const renderForm = (form, input) => { renderField(form, input); }; const renderTable = (table, input, output) => { renderCaption(table, input, output); renderBody(table, output); }; const renderField = (form, input) => { const elements = form.elements; const name = elements.namedItem("nom"); name.value = input; }; const renderCaption = (table, input, output) => { const caption = table.caption; const length = output.length; const content = length === 0 ? "Aucun résultat pour la recherche «\u{00a0}" + input + "\u{00a0}»" : length === 1 ? "1 résultat pour la recherche «\u{00a0}" + input + "\u{00a0}»" : String(length) + " résultats pour la recherche «\u{00a0}" + input + "\u{00a0}»"; caption.textContent = content; }; const renderBody = (table, output) => { const bodies = table.tBodies; const oldBody = bodies.item(0); const newBody = document.createElement("tbody"); for (const item of output) { const row = newBody.insertRow(); for (const key of keys) { const cell = row.insertCell(); const content = item[key]; cell.textContent = content; } } oldBody.replaceWith(newBody); }; /* ~~~~ State logging ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const logState = (state) => { const input = state.input; const output = state.output; console.groupCollapsed(JSON.stringify(input) + ":"); console.table(output, ["nom", "codeDepartement", "codeRegion"]); console.groupEnd(); }; /* ~~~~ State sorting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const sortState = (state, column) => { let order = 1; if (column < 0) { column = ~column; order = -1; } const output = state.output; const key = keys[column]; const type = types[column]; switch (type) { case "number": { output.sort((a, b) => { return (a[key] - b[key]) * order; }); break; } case "string": { output.sort((a, b) => { return a[key].localeCompare(b[key], "fr") * order; }); break; } } }; export {getSearchParams, getLocalURL, getRemoteURL, initForm, initTable, computeState, renderState, logState, sortState}; <file_sep>/examples/02-html/resources/index.js const meta = /\r\n|\r|\n|&|<|>/gu; const entities = { "\r\n": "<br/>", "\r": "<br/>", "\n": "<br/>", "&": "&amp;", "<": "&lt;", ">": "&gt;", }; const likesField = function likesField(checkbox) { return checkbox.checked ? "j'aime" : "je n'aime pas"; }; const hasField = function hasField(radioButtons) { return radioButtons.value === "yes" ? "j'ai" : "je n'ai pas"; }; const escapeField = function escapeField(textarea) { return textarea.value.replace(meta, ($0) => entities[$0]); }; const {my_form} = document.forms; const {name, age, biography, banana, apple, orange, driver_license, password, token, result} = my_form; my_form.querySelector("button[type=\"button\"]").addEventListener("click", () => { result.innerHTML = `\ Je suis ${name.value || "anonyme"} et j'ai ${age.value || "arrêté de compter les"} ans.\ <br/>\ Voici ma biographie :\ <br/>\ ${escapeField(biography)}\ <br/>\ Sachez que ${likesField(banana)} les bananes, que ${likesField(apple)} les pommes et que ${likesField(orange)} les oranges.\ <br/>\ Ah, et puis ${hasField(driver_license)} le permis.\ <br/>\ Mon mot de passe fait ${password.value.length} caractères de long et le token anti-CSRF vaut ${token.value}.\ `; }); <file_sep>/practical-works/01-html/correction.html <!DOCTYPE html> <html dir="ltr" lang="fr"> <head> <title>CV d'<NAME></title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width"/> </head> <body> <h1><NAME></h1> <address> <dl> <dt>Adresse postale</dt> <dd><NAME><br/>42 rue Dominique Dupont<br/>54000 Nancy</dd> <dt>Tél</dt> <dd>06 01 23 45 67</dd> <dt>Mél</dt> <dd><EMAIL></dd> </dl> </address> <p><img src="./resources/portrait.png" alt="Portrait d'<NAME>, souriant" width="224" height="288"/></p> <h2>Études</h2> <dl> <dt><time datetime="2017">2017</time>&nbsp;-&nbsp;<time datetime="2020">2020</time></dt> <dt>Telecom Nancy, Villers-Lès-Nancy</dt> <dd>Formation d'ingénieur en informatique</dd> <dt><time datetime="2015">2015</time>&nbsp;-&nbsp;<time datetime="2017">2017</time></dt> <dt>CPGE au Lycée général Durand, Nancy</dt> <dd>Formation scientifique spécialisée en mathématiques, physique et sciences industrielles</dd> </dl> <h2>Expériences professionnelles</h2> <dl> <dt><time datetime="2018-07">Juillet 2018</time>&nbsp;-&nbsp;<time datetime="2018-08">Août 2018</time></dt> <dt>Caissier à <NAME></dt> <dd>Gestion des encaissements dans un magasin de proximité dans le cadre du stage ouvrier de la formation d'ingénieur</dd> <dt><time datetime="2016-07">Juillet 2016</time>&nbsp;-&nbsp;<time datetime="2016-08">Août 2016</time></dt> <dt>Serveur à Légumes Express</dt> <dd>Prise de commande et service à table midi et soir dans une chaîne de restauration rapide</dd> </dl> <h2>Centres d'intérêt</h2> <ul> <li>Magicarpe</li> <li>Châteaux de cartes</li> <li>Chatons</li> </ul> </body> </html> <file_sep>/package.sh #!/bin/bash node package.js <file_sep>/readme.md # *Web Academy* [<img width="100" height="100" alt="" src="resources/web-academy.png" align="right"/>](//tristoon.github.io/web-academy/) ## Présentation La *Web Academy* est une formation sur le *web* dispensée aux élèves de [*Telecom Nancy*](//telecomnancy.univ-lorraine.fr/) par l'association [*Telecom Nancy Services*](//tnservices.fr/). Ce dépôt contient les supports de cours, les sujets de travaux pratiques, des exercices et leur correction ainsi que des exemples pour les sessions 2018-2019 et 2019-2020. ## Documents ### Supports de cours - [Introduction au développement *web*](chapters/01-web/index.html.pdf) - [Structuration de page *web* en *HTML*](chapters/02-html/index.html.pdf) - [Mise en forme de page *web* en *CSS*](chapters/03-css/index.html.pdf) - [Manipulation de page *web* en *JS*](chapters/04-js/index.html.pdf) ### Sujets de travaux pratiques ***HTML*** : - Structure d'un *CV* ([sujet](practical-works/01-html/subject.html.pdf), [squelette](practical-works/01-html/index.html), [correction](practical-works/01-html/correction.html)) ***CSS*** : - Reproduction du style du site d'un club ([sujet](practical-works/02-css/subject.html.pdf), [squelette](practical-works/02-css/resources/index.css), [objectif](practical-works/02-css/goal.png), [correction](practical-works/02-css/resources/correction.css)) ***ECMAScript*** : - Conception d'un moteur de recherche ([sujet](practical-works/03-js/subject.html.pdf), [squelette](practical-works/03-js/resources/index.js), [correction](practical-works/03-js/resources/correction.js)) ### Exercices ***HTML*** : - Mon super site ([sujet](exercices/01-html/subject.html.pdf), [squelette](exercices/01-html/index.html), [objectif](exercices/01-html/goal.png), [correction](exercices/01-html/correction.html)) - Tableaux ([sujet](exercices/02-html/subject.html.pdf), [squelette](exercices/02-html/index.html), [objectif](exercices/02-html/goal.png), [correction](exercices/02-html/correction.html)) - Formulaires ([sujet](exercices/03-html/subject.html.pdf), [squelette](exercices/03-html/index.html), [objectif](exercices/03-html/goal.png), [correction](exercices/03-html/correction.html)) ### Exemples ***HTML*** : - [Document vide](examples/01-html/index.html) - [Présentation des formulaires](examples/02-html/index.html) ## Lancement du serveur local À partir d'un certain point de la formation, vous aurez besoin d'un serveur local pour effectuez vos tests. Le script [`package.js`](package.js) vous permet d'en lancer un rapidement, avec le minimum de configuration. Pour cela, installez au préalable *Node.js* au moins en version 13.2.0 (à l'aide de [*nvm*](https://github.com/nvm-sh/nvm) par exemple) et clonez ce dépôt. Ensuite, à la racine du projet, exécutez le fichier `package.sh` si vous êtes dans un environnement de type *Unix*, `package.bat` sous *Windows* ou bien la commande suivante : ```sh $ npm start ``` ## Note sur les fichiers `.html.pdf` Les supports de cours et les sujets de travaux pratiques et d'exercices qui portent l'extension `.html.pdf` ont été générés via le navigateur *Firefox 67.0.4* sous *Ubuntu 19.04* à partir d'une page *web* codée en *HTML* et *CSS*.
62a30d66c68ad306240f1cf3e0f9f5d64f76323e
[ "JavaScript", "HTML", "Markdown", "Shell" ]
5
JavaScript
TrisTOON/web-academy
0e65990bf1a50e48621d494b7d2382c094a715c8
1fa04d8ad30f80ab2939e0a34dd2c5aa3881f217
refs/heads/master
<file_sep>#!/bin/bash SUDO="$(which sudo 2>/dev/null)" PROJECT_DIR=~/.docker-blueprint EXEC_PATH="$(which docker-blueprint 2>/dev/null)" if [[ -n $EXEC_PATH ]]; then printf "Removing link..." $SUDO rm -f $EXEC_PATH printf " done\n" fi EXEC_PATH="$(which dob 2>/dev/null)" if [[ -n $EXEC_PATH ]]; then printf "Removing link..." $SUDO rm -f $EXEC_PATH printf " done\n" fi if [[ -d "$PROJECT_DIR" ]]; then printf "Removing project directory..." rm -rf $PROJECT_DIR printf " done\n" fi echo "Successfuly removed docker-blueprint." <file_sep>#!/bin/bash PROGRAM="$1" # Escape backslashes first PROGRAM="$(echo "$PROGRAM" | sed -E 's/\\/\\\\/g')" # Escape variable sign ($) to execute it inside runtime PROGRAM="$(echo "$PROGRAM" | sed -E 's/\$/\\\$/g')" # Then escape double-quotes, since they are used to enclose the program PROGRAM="$(echo "$PROGRAM" | sed -E 's/"/\\"/g')" echo "$PROGRAM" <file_sep>#!/bin/bash BLUEPRINT="$1" if [[ -z $SILENT ]]; then SILENT=true fi if [[ -z "$BLUEPRINT" ]]; then yq_read_value BLUEPRINT 'from' export BLUEPRINT fi if [[ -z "$BLUEPRINT" ]]; then printf "${RED}ERROR${RESET}: \$BLUEPRINT cannot be empty\n" exit 1 fi debug_print "Populating environment variables for blueprint: ${BLUEPRINT}" if [[ -z "$BLUEPRINT_QUALIFIED_NAME" ]]; then # Get blueprint fully-qualified name to show to the user export BLUEPRINT_QUALIFIED_NAME="$(AS_FUNCTION=true bash "$ENTRYPOINT" pull "$BLUEPRINT" --get-qualified-name)" fi debug_print "BLUEPRINT_QUALIFIED_NAME=${BLUEPRINT_QUALIFIED_NAME}" if ! $SILENT; then printf "Pulling blueprint '$BLUEPRINT_QUALIFIED_NAME'...\n" fi if [[ -z "$BLUEPRINT_DIR" ]]; then # Try to pull the blueprint and get the returned directory path export BLUEPRINT_DIR="$(AS_FUNCTION=true bash "$ENTRYPOINT" pull "$BLUEPRINT")" fi debug_print "BLUEPRINT_DIR=${BLUEPRINT_DIR}" if [[ $? -ne 0 ]]; then printf "${RED}ERROR${RESET}: Unable to pull blueprint '$BLUEPRINT'.\n" exit 1 fi if [[ -z "$ENV_NAME" ]]; then yq_read_value ENV_NAME "environment" export ENV_NAME fi debug_print "ENV_NAME=${ENV_NAME}" if [[ -z "$ENV_DIR" ]] && [[ -n "$ENV_NAME" ]]; then export ENV_DIR="$BLUEPRINT_DIR/env/$ENV_NAME" if [[ ! -d "$ENV_DIR" ]]; then printf "${RED}ERROR${RESET}: Environment '$ENV_NAME' doesn't exist\n" exit 1 fi fi debug_print "ENV_DIR=${ENV_DIR}" <file_sep>#!/bin/bash # Is stdout is a terminal? if [[ -t 1 ]] && [[ -z ${DOCKER_BLUEPRINT_NO_COLOR:+x} ]]; then # Does it support colors? ncolors=$(tput colors) if [[ $ncolors -ge 8 ]]; then export BLACK="\033[0;30m" export RED="\033[0;31m" export GREEN="\033[0;32m" export ORANGE="\033[0;33m" export BLUE="\033[0;34m" export PURPLE="\033[0;35m" export CYAN="\033[0;36m" export LIGHT_GRAY="\033[0;37m" export DARK_GRAY="\033[1;30m" export LIGHT_RED="\033[1;31m" export LIGHT_GREEN="\033[1;32m" export YELLOW="\033[1;33m" export LIGHT_BLUE="\033[1;34m" export LIGHT_PURPLE="\033[1;35m" export LIGHT_CYAN="\033[1;36m" export WHITE="\033[1;37m" export RESET="\033[0;0m" fi fi export EXE_COL=$BLUE export SRV_COL=$LIGHT_GRAY export CMD_COL=$GREEN export ARG_COL=$RESET export FLG_COL=$RED export FLG_VAL_COL=$RESET export ICON_EMPTY=" " export ICON_CHECK="\xE2\x9C\x94" <file_sep>#!/bin/bash debug_switch_context "COMPILE" debug_print "Running the command..." BLUEPRINT="$1" if [[ -z "$BLUEPRINT" ]]; then printf "${RED}ERROR${RESET}: \$BLUEPRINT cannot be empty\n" exit 1 fi if [[ -z "$TEMP_DIR" ]]; then printf "${RED}ERROR${RESET}: \$TEMP_DIR cannot be empty\n" exit 1 fi if [[ -z $SILENT ]]; then SILENT=false fi SILENT=$SILENT source "$ROOT_DIR/includes/blueprint/populate_env.sh" $BLUEPRINT yq_read_value CHECKPOINT 'version' # Set the blueprint repository to the version specified. # This allows to always safely reproduce previous versions of the blueprint. if [[ -n $CHECKPOINT ]]; then cd "$BLUEPRINT_DIR" git checkout $CHECKPOINT 2> /dev/null if [[ $? -eq 0 ]]; then printf "Version: ${CYAN}$CHECKPOINT${RESET}\n" else printf "${RED}ERROR${RESET}: Unable to checkout version $CHECKPOINT\n" exit 1 fi cd "$PROJECT_DIR" if [[ -n "$ENV_NAME" ]] && [[ ! -d "$ENV_DIR" ]]; then printf "${RED}ERROR${RESET}: Environment '$ENV_NAME' does not exist for version $CHECKPOINT\n" exit 1 fi else if ! $SILENT; then printf "${YELLOW}WARNING${RESET}: Blueprint version is not specified - future upstream changes can potentially break this project!\n" printf "Use ${EXE_COL}docker-blueprint${RESET} ${CMD_COL}lock${RESET} to lock the project to the current version of the blueprint\n" fi fi ! $SILENT && non_debug_print "Generating blueprint file..." source "$ROOT_DIR/includes/blueprint/merge.sh" # export BLUEPRINT_FILE_TMP # Collect modules to load from temporary preset file and CLI arguments yq_read_array MODULES "modules" "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." MODULES_TO_LOAD=() for module in "${MODULES[@]}"; do MODULES_TO_LOAD+=($module) done for module in "${ARG_WITH[@]}"; do ALREADY_DEFINED=false for defined_module in "${MODULES_TO_LOAD[@]}"; do if [[ "$module" = "$defined_module" ]]; then ALREADY_DEFINED=true break fi done if ! $ALREADY_DEFINED; then MODULES_TO_LOAD+=($module) fi done if [[ ${#MODULES_TO_LOAD[@]} > 0 ]]; then SILENT=$SILENT source "$ROOT_DIR/includes/resolve-dependencies.sh" ${MODULES_TO_LOAD[@]} fi # Generate a list of YAML files to merge # depending on chosen modules FILES_TO_MERGE=() function append_file_to_merge() { if [[ -f "$1" ]]; then FILES_TO_MERGE+=("$1") fi } for module in "${MODULES_TO_LOAD[@]}"; do # Each module can extend base blueprint file="$BLUEPRINT_DIR/modules/$module/blueprint.yml" if [[ -f "$file" ]]; then debug_print "Using module blueprint: ${file#$BLUEPRINT_DIR/}" append_file_to_merge "$file" fi # If environment is specified, additionally load module # blueprint files specific to the environment file="$ENV_DIR/modules/$module/blueprint.yml" if [[ -d "$ENV_DIR" ]] && [[ -f "$file" ]]; then debug_print "Using environment module blueprint: ${file#$BLUEPRINT_DIR/}" append_file_to_merge "$file" fi ! $SILENT && non_debug_print "." done # Merge user-provided blueprint file last to overwrite all the properties append_file_to_merge "$BLUEPRINT_FILE_TMP" debug_print "Merging files:" for file in "${FILES_TO_MERGE[@]#$BLUEPRINT_DIR/}"; do debug_print "- $file" done if [[ -z "${FILES_TO_MERGE[1]}" ]]; then printf -- "$(cat "${FILES_TO_MERGE[0]}")" >"$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." else printf -- "$(yq_merge ${FILES_TO_MERGE[@]})" >"$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." fi # Get current blueprint commit hash... cd $BLUEPRINT_DIR hash=$(git rev-parse HEAD) 2>/dev/null && \ ! $SILENT && non_debug_print "." if [[ $? > 0 ]]; then unset hash fi cd $PROJECT_DIR # ... and store it for the version lock if [[ -n $hash ]]; then yq -i eval ".version = \"$hash\" | .version style=\"single\"" "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." fi # Store blueprint name yq -i eval ".from = \"$BLUEPRINT\" | .from style=\"single\"" "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." # Store blueprint environment if [[ -n $ENV_NAME ]]; then yq -i eval ".environment = \"$ENV_NAME\" | .environment style=\"single\"" "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." fi # Save build arguments to give the user ability to overwrite them later yq_read_keys BUILD_ARGS_KEYS 'build_args' "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." for variable in ${BUILD_ARGS_KEYS[@]}; do yq_read_value value "build_args.$variable" "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." if [[ -n ${!variable+x} ]]; then value="${!variable:-}" fi yq -i eval ".build_args.$variable = \"$value\" | .build_args.$variable style=\"single\"" "$BLUEPRINT_FILE_TMP" && \ ! $SILENT && non_debug_print "." done ! $SILENT && non_debug_print " ${GREEN}done${RESET}\n" debug_print "Created blueprint file: $BLUEPRINT_FILE_TMP" BLUEPRINT_HASH="$(printf "%s" "$BLUEPRINT$(date +%s)" | openssl dgst -sha1 | sed 's/^.* //')" BLUEPRINT_PATH="$TEMP_DIR/blueprint-$BLUEPRINT_HASH" mv "$BLUEPRINT_FILE_TMP" "$BLUEPRINT_PATH" export BLUEPRINT_PATH <file_sep>#!/bin/bash printf "Modular ephemeral development environments.\n" printf "\n" printf "Usage:\n" printf " $EXE_COL$EXECUTABLE_NAME$RESET [${FLG_COL}options${RESET}] ${ARG_COL}<command>${RESET}" printf "\tRun program command or 'exec' command in the default service\n" printf " ${FLG_COL}-h${RESET}, ${FLG_COL}--help${RESET}" printf "\t\t\t" printf "Display this help message\n" printf " ${FLG_COL}-T${RESET}" printf "\t\t\t\tDisable pseudo-tty allocation. Propagates -T to 'docker-compose exec'\n" printf " ${FLG_COL}--context${RESET} <name>" printf "\tForce to use the given project context instead of default\n" printf "\n" printf "Commands:\n" printf " [${SRV_COL}service${RESET}] [${CMD_COL}exec${RESET}] ${ARG_COL}<command>${RESET}" printf "\t" printf "Execute 'docker-compose exec' as current host user\n" printf " [${SRV_COL}service${RESET}] ${CMD_COL}sudo${RESET} ${ARG_COL}<command>${RESET}" printf "\t" printf "Execute 'docker-compose exec' as root against service\n" printf "\t\t\t\t" printf "(service parameter can be omitted to run against the default)\n" FILES=("$ROOT_DIR/commands/"*.sh) for file in "${FILES[@]}"; do command=$(basename "$file" .sh) case "$command" in help | module | env) continue ;; *) printf "$(bash $ENTRYPOINT $command --help | pr -To 2)\n" ;; esac done <file_sep>#!/bin/bash debug_switch_context "BUILD" debug_print "Running the command..." # Blueprint BUILD command shift # # Read arguments # MODE_FORCE=false MODE_DRY_RUN=false MODE_SKIP_COMPOSE=false MODE_SKIP_DOCKERFILE=false MODE_NO_CACHE=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}build${RESET} [${FLG_COL}options${RESET}] [${ARG_COL}<tag>${RESET}]" printf "\tBuild containerized technology stack defined in docker-blueprint.yml\n" printf " ${FLG_COL}-f${RESET}, ${FLG_COL}--force${RESET}" printf "\t\t\tAlways generate new docker files. This ${RED}WILL OVERWRITE${RESET} existing files\n" printf " ${FLG_COL}--dry-run${RESET}" printf "\t\t\tRun the command without writing any files\n" printf " ${FLG_COL}--skip-compose${RESET}" printf "\t\tDon't generate docker-compose files\n" printf " ${FLG_COL}--skip-dockerfile${RESET}" printf "\t\tDon't generate dockerfiles\n" printf " ${FLG_COL}--no-cache${RESET}" printf "\t\t\tDon't use docker image cache\n" exit ;; -f | --force) MODE_FORCE=true ;; --dry-run) MODE_DRY_RUN=true ;; --skip-compose | --no-compose) MODE_SKIP_COMPOSE=true ;; --skip-dockerfile | --no-dockerfile) MODE_SKIP_DOCKERFILE=true ;; --no-cache) MODE_NO_CACHE=true ;; *) TARGET_IMAGE=$1 ;; esac shift done if [[ ! -f "$PWD/$PROJECT_BLUEPRINT_FILE" ]]; then printf "${RED}ERROR${RESET}: docker-blueprint.yml doesn't exist.\n" printf "Create one by running: ${BLUE}docker-blueprint ${GREEN}new${RESET}\n" exit 1 fi # # Initialize path variables # printf "Loading blueprint..." # Use base metadata from `docker-blueprint.yml` in order to derive full blueprint yq_read_value BLUEPRINT 'from' && printf "." yq_read_value ENV_NAME 'environment' && printf "." yq_read_array MODULES_TO_LOAD 'modules' && printf "." printf " ${GREEN}done${RESET}\n" # export BLUEPRINT_PATH source "$ROOT_DIR/includes/blueprint/compile.sh" "$BLUEPRINT" if [[ $? -ne 0 ]]; then printf "\n${RED}ERROR${RESET}: Unable to compile blueprint '$BLUEPRINT'.\n" exit 1 fi debug_switch_context "BUILD" debug_newline_print "Resolving dependencies..." source "$ROOT_DIR/includes/resolve-dependencies.sh" ${MODULES_TO_LOAD[@]} non_debug_print " ${GREEN}done${RESET}\n" # # Read generated configuration # # export SCRIPT_VARS # export SCRIPT_VARS_ENV # export SCRIPT_VARS_BUILD_ARGS source "$ROOT_DIR/includes/get-script-vars.sh" # # Build docker-compose.yml # printf "Building docker-compose files...\n" # Select all unique docker-compose files (even in disabled modules) if ! $MODE_SKIP_COMPOSE; then FILE_NAMES=($( find "$BLUEPRINT_DIR" -name "docker-compose*.yml" -type f | xargs basename -a | sort | uniq )) fi for name in ${FILE_NAMES[@]}; do CURRENT_DOCKER_COMPOSE_FILE="$PWD/$name" # Make sure file doesn't exist in the project directory, # otherwise print a warning and skip it if $MODE_FORCE; then if ! $MODE_DRY_RUN; then rm -f "$CURRENT_DOCKER_COMPOSE_FILE" fi elif [[ -f "$CURRENT_DOCKER_COMPOSE_FILE" ]]; then printf "${BLUE}INFO${RESET}: ${YELLOW}$name${RESET} already exists, skipping generation (run with --force to override).\n" continue fi debug_newline_print "Generating ${YELLOW}$name${RESET}..." docker_compose_file_paths=() # Add base file if it exists file="$BLUEPRINT_DIR/$name" if [[ -f "$file" ]]; then docker_compose_file_paths+=("$file") fi # Then add environment file if it exists file="$ENV_DIR/$name" if [[ -f "$file" ]]; then docker_compose_file_paths+=("$file") fi # For each enabled module add files to merge for module in ${MODULES_TO_LOAD[@]}; do # Add base blueprint module files first file="$BLUEPRINT_DIR/modules/$module/$name" if [[ -f "$file" ]]; then docker_compose_file_paths+=("$file") fi # Then add environment module files file="$ENV_DIR/modules/$module/$name" if [[ -f "$file" ]]; then docker_compose_file_paths+=("$file") fi done debug_print "Merging files:" for file in ${docker_compose_file_paths[@]}; do debug_print "- ${file#$BLUEPRINT_DIR/}" if [[ ! -f "$CURRENT_DOCKER_COMPOSE_FILE" ]]; then cp -f "$file" "$CURRENT_DOCKER_COMPOSE_FILE" else printf -- "$( yq_merge \ "$CURRENT_DOCKER_COMPOSE_FILE" "$file" )" >"$CURRENT_DOCKER_COMPOSE_FILE" fi non_debug_print "." done if [[ -f "$CURRENT_DOCKER_COMPOSE_FILE" ]]; then # Remove empty lines sed -ri '/^\s*$/d' "$CURRENT_DOCKER_COMPOSE_FILE" substitute_vars() { env "${SCRIPT_VARS[@]}" \ bash "$ROOT_DIR/includes/preprocessor/substitute-vars.sh" $@ } temp_file="$TEMP_DIR/$name" mkdir -p "$(dirname "$temp_file")" rm -f "$temp_file" && touch "$temp_file" OLD_IFS="$IFS" # Source https://stackoverflow.com/a/18055300/2467106 IFS= # Substitute blueprint variables while read -r line || [[ -n "$line" ]]; do echo $(substitute_vars "$line" "~") >>"$temp_file" non_debug_print "." done <"$CURRENT_DOCKER_COMPOSE_FILE" mv -f "$temp_file" "$CURRENT_DOCKER_COMPOSE_FILE" rm -f "$temp_file" && touch "$temp_file" # Remove lines with non-substituted variables while read -r line || [[ -n "$line" ]]; do if [[ "$line" =~ "~" ]]; then if [[ -n "$replaced" ]]; then echo "$replaced" >>"$temp_file" fi else echo "$line" >>"$temp_file" fi non_debug_print "." done <"$CURRENT_DOCKER_COMPOSE_FILE" IFS="$OLD_IFS" if ! $MODE_DRY_RUN; then mv -f "$temp_file" "$CURRENT_DOCKER_COMPOSE_FILE" fi rm -f "$temp_file" debug_print "Created docker-compose file: '$name':" non_debug_print " ${GREEN}done${RESET}\n" fi done # # Build dockerfile # printf "Building dockerfiles...\n" for file in $BLUEPRINT_DIR/[Dd]ockerfile*; do # https://stackoverflow.com/a/43606356/2467106 # http://mywiki.wooledge.org/BashPitfalls#line-57 [ -e "$file" ] || continue DOCKER_FILE=$(basename "$file") CURRENT_DOCKERFILE="$PWD/$DOCKER_FILE" if $MODE_SKIP_DOCKERFILE; then continue fi if $MODE_FORCE; then if ! $MODE_DRY_RUN; then rm -f "$CURRENT_DOCKERFILE" fi elif [[ -f "$CURRENT_DOCKERFILE" ]]; then printf "${BLUE}INFO${RESET}: ${YELLOW}$DOCKER_FILE${RESET} already exists, skipping generation (run with --force to override).\n" continue fi env "${SCRIPT_VARS[@]}" bash $ENTRYPOINT process "$file" if [[ $? > 0 ]]; then printf "\n${RED}ERROR${RESET}: There was an error processing $file\n" exit 1 fi if ! $MODE_DRY_RUN; then cp "$file.out" "$CURRENT_DOCKERFILE" fi if [[ $? > 0 ]]; then printf "\n${RED}ERROR${RESET}: Unable to copy processed file\n" exit 1 fi # Clean up after processing rm -f "$file.out" done # # Build containers # if $MODE_NO_CACHE; then SCRIPT_VARS_BUILD_ARGS+=("--no-cache") fi command="$DOCKER_COMPOSE build ${SCRIPT_VARS_BUILD_ARGS[@]}" debug_print "Running command: $command" status=0 if ! $MODE_DRY_RUN; then eval "$command" status=$? fi if [[ $status -eq 0 ]] && [[ -n "$TARGET_IMAGE" ]]; then printf "Applying tag ${YELLOW}$TARGET_IMAGE${RESET} to the newly built image...\n" if ! $MODE_DRY_RUN; then docker tag "${PROJECT_NAME}_${DEFAULT_SERVICE}" "$TARGET_IMAGE" status=$? fi fi if [[ "$status" > 0 ]]; then printf "${RED}ERROR${RESET}: Couldn't finish building blueprint.\n" exit $status fi <file_sep>#!/bin/bash debug_print() { if [[ $DEBUG -eq 1 ]]; then prefix="${DEBUG_PREFIX:-DEBUG}" # Source: https://stackoverflow.com/a/7265130/2467106 n=$(md5sum <<<"$prefix") # Get md5 hash of a string n=$((0x${n%% *})) # Convert to base 10 n=${n#-} # Remove negative sign ((n = $n % 7 + 1)) # Clamp values to the range [1; 6] color="\e[38;5;${n}m" # Generate color code printf "$color[$prefix]$RESET " if [[ -n "${2+x}" ]]; then printf "$@" else printf "%s\n" "$1" fi fi } export -f debug_print debug_switch_context() { prefix="DEBUG" if [[ -n "$1" ]]; then prefix="$1" fi export DEBUG_PREFIX="$prefix" } export -f debug_switch_context non_debug_print() { if [[ -z $DEBUG || $DEBUG -eq 0 ]]; then printf -- "$1" fi } export -f non_debug_print debug_newline_print() { if [[ -z $DEBUG || $DEBUG -eq 0 ]]; then printf -- "$1" elif [[ $DEBUG -eq 1 ]]; then printf -- "$1\n" fi } export -f debug_newline_print <file_sep>#!/bin/bash printf " Laravel application development environment\n" printf "\n" printf " Create PHP development environment for Laravel framework\n" printf " with intl & gd extensions and MySQL & Redis integration:\n" printf " $EXE_COL$EXECUTABLE_NAME$RESET ${CMD_COL}new${RESET} ${ARG_COL}php${RESET} ${FLG_COL}--env${RESET} ${FLG_VAL_COL}laravel${RESET} ${FLG_COL}--with${RESET} ${FLG_VAL_COL}intl gd mysql redis${RESET}\n" printf "\n" printf " Compile front-end assets:\n" printf " $EXE_COL$EXECUTABLE_NAME$RESET ${ARG_COL}npm run dev${RESET}" printf "\t\t" printf "Executes command in the default service" printf "\n" printf " $EXE_COL$EXECUTABLE_NAME$RESET ${SRV_COL}app${RESET} ${CMD_COL}exec${RESET} ${ARG_COL}npm run dev${RESET}" printf "\t" printf "Does the same thing, but service name is specified explicitly" printf "\n\n" printf " Connect to MySQL as root user:\n" printf " $EXE_COL$EXECUTABLE_NAME$RESET ${SRV_COL}database${RESET} ${CMD_COL}sudo${RESET} ${ARG_COL}mysql${RESET}\n" <file_sep>#!/bin/bash # MIT License # # Copyright (c) 2020-2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. export EXECUTABLE_NAME=$(basename "${BASH_SOURCE}") export PROJECT_DIR=$PWD [[ -n $PROJECT_NAME ]] && GOT_PROJECT_NAME_FROM_ENV=true [[ -z $GOT_PROJECT_NAME_FROM_ENV ]] && PROJECT_NAME=$(basename $PROJECT_DIR) export DIR_NAME=.docker-blueprint export ROOT_DIR=~/.docker-blueprint export LOCAL_DIR="$PROJECT_DIR/$DIR_NAME" export TEMP_DIR="$LOCAL_DIR/tmp" export ENTRYPOINT="$ROOT_DIR/entrypoint.sh" export PROJECT_BLUEPRINT_FILE=docker-blueprint.yml # Delete temporary files older than 5 minutes mkdir -p "$TEMP_DIR" find "$TEMP_DIR" -mindepth 1 -type f -mmin +5 -delete mkdir -p $LOCAL_DIR source "$ROOT_DIR/includes/update-gitignore.sh" if [[ -z $UID ]]; then UID=$(id -u) fi if [[ -z "$GID" ]]; then GID=$(id -g) fi source "$ROOT_DIR/includes/colors.sh" source "$ROOT_DIR/includes/debug.sh" source "$ROOT_DIR/includes/yq.sh" if [[ -f "$PROJECT_BLUEPRINT_FILE" ]]; then [[ -z $PROJECT_CONTEXT ]] && yq_read_value PROJECT_CONTEXT "project.context" "$PROJECT_BLUEPRINT_FILE" yq_read_value name "project.name" "$PROJECT_BLUEPRINT_FILE" [[ -z $GOT_PROJECT_NAME_FROM_ENV && -n $name ]] && export PROJECT_NAME="$name" fi # Parse global arguments for arg in $@; do case $arg in --context) if [[ -z $2 ]]; then printf "${RED}ERROR${RESET}: Context name is required\n" exit 1 fi export PROJECT_CONTEXT="$2" shift 2 if [[ ! -f "docker-compose.$PROJECT_CONTEXT.yml" ]]; then printf "${RED}ERROR${RESET}: No docker-compose file found for context ${YELLOW}$PROJECT_CONTEXT${RESET}\n" exit 1 fi ;; --) shift break ;; esac done source "$ROOT_DIR/includes/entrypoint/init-compose.sh" init_default_service() { DEFAULT_SERVICE=$(cat $LOCAL_DIR/default_service 2>/dev/null) if [[ -z $DEFAULT_SERVICE ]] && [[ -f "$PROJECT_BLUEPRINT_FILE" ]]; then yq_read_value DEFAULT_SERVICE "default_service" "$PROJECT_BLUEPRINT_FILE" echo "$DEFAULT_SERVICE" >"$LOCAL_DIR/default_service" fi } if [[ -z "$DEFAULT_SERVICE" ]]; then init_default_service fi if [[ -f "$ROOT_DIR/commands/$1.sh" ]]; then if [[ -z $AS_FUNCTION ]]; then AS_FUNCTION=false fi source "$ROOT_DIR/commands/$1.sh" exit fi MODE_NO_TTY=false if [[ $# -eq 0 ]]; then source "$ROOT_DIR/commands/help.sh" exit fi while [[ "$#" -gt 0 ]]; do case $1 in start | stop | restart | down) $DOCKER_COMPOSE "$1" ${@:2} exit ;; -h | --help) source "$ROOT_DIR/commands/help.sh" exit ;; -v | --version) AS_FUNCTION=false source "$ROOT_DIR/commands/version.sh" exit ;; -T) MODE_NO_TTY=true ;; *) if [[ ! -z "$1" ]]; then COMMAND=("$DOCKER_COMPOSE exec") if $MODE_NO_TTY; then COMMAND+=("-T") fi ENV_VARS=() while [[ "$#" -gt 0 ]]; do case $1 in -e* | --env*) COMMAND+=("$1") shift ;; *) break ;; esac done if [[ ! -z "$2" ]] && [[ "$2" == "sudo" ]]; then COMMAND+=("$1 ${@:3}") elif [[ "$1" == "sudo" ]]; then COMMAND+=("$DEFAULT_SERVICE ${@:2}") elif [[ ! -z "$2" ]] && [[ "$2" == "exec" ]]; then COMMAND+=("--user=$UID:$GID $1 ${@:3}") elif [[ "$1" == "exec" ]]; then COMMAND+=("--user=$UID:$GID $DEFAULT_SERVICE ${@:2}") else CURRENT_SERVICE="$DEFAULT_SERVICE" # Get currently available docker-compose project services. # NOTICE: This adds significant execution delay. # SERVICE_LIST=($(eval "$DOCKER_COMPOSE ps --services")) # for service in "${SERVICE_LIST[@]}"; do # if [[ "$1" = "$service" ]]; then # CURRENT_SERVICE="$service" # shift # break # fi # done COMMAND+=("--user=$UID:$GID $CURRENT_SERVICE ${@:1}") fi if [[ -z "$DEFAULT_SERVICE" ]]; then echo "Cannot execute command against default service - no default service specified." exit 1 else debug_print "Running command: ${COMMAND[*]}" eval "${COMMAND[*]}" fi else source "$ROOT_DIR/commands/help.sh" fi exit ;; esac shift done <file_sep>#!/bin/bash debug_switch_context "UP" debug_print "Running the command..." shift # # Read arguments # ARGS=() MODE_SYNC=true SYNC_ARGS=() MODE_NO_BUILD=false BUILD_ARGS=() MODE_NO_SCRIPTS=false MODE_SCRIPTS_ONLY=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}up${RESET} [${FLG_COL}options${RESET}]" printf "\t\t\t" printf "Bring up docker containers and initialize them\n" printf "\t\t\t\t" printf "You can use any of the options options for a regular docker-compose command\n" printf " ${FLG_COL}--no-sync${RESET}" printf "\t\t\tDon't attempt to sync service container with the local environment\n" printf " ${FLG_COL}--no-chown${RESET}" printf "\t\t\tPass --no-chown to 'sync' command\n" printf " ${FLG_COL}--no-build${RESET}" printf "\t\t\tDon't attempt to build the blueprint\n" printf " ${FLG_COL}--no-scripts${RESET}" printf "\t\tDon't attempt to run scripts\n" printf " ${FLG_COL}--scripts-only${RESET}" printf "\t\tOnly run scripts - don't attempt to bring up the containers\n" printf " ${FLG_COL}--no-cache${RESET}" printf "\t\t\tDon't use docker image cache\n" printf " ${FLG_COL}-f${RESET}, ${FLG_COL}--force${RESET}" printf "\t\t\tPass --force to 'build' command\n" printf "\t\t\t\tThis will force to regenerate new docker files\n" printf "\t\t\t\tpotentially overwriting current ones\n" exit ;; -f | --force) BUILD_ARGS+=('--force') ;; --no-build) MODE_NO_BUILD=true ;; --no-cache) BUILD_ARGS+=("--no-cache") ;; --no-scripts) MODE_NO_SCRIPTS=true ;; --scripts-only) MODE_SCRIPTS_ONLY=true ;; --no-chown) SYNC_ARGS+=('--no-chown') ;; --no-sync) MODE_SYNC=false ;; --skip-compose | --no-compose) BUILD_ARGS+=("--skip-compose") ;; --skip-dockerfile | --no-dockerfile) BUILD_ARGS+=("--skip-dockerfile") ;; *) ARGS+=($1) ;; esac shift done if ! $MODE_SCRIPTS_ONLY; then if ! $MODE_NO_BUILD; then bash $ENTRYPOINT build ${BUILD_ARGS[@]} if [[ $? > 0 ]]; then exit 1 fi fi eval "$DOCKER_COMPOSE up -d --remove-orphans ${ARGS[@]}" if [[ $? > 0 ]]; then exit 1 fi if $MODE_SYNC; then bash $ENTRYPOINT sync ${SYNC_ARGS[@]} fi fi script_paths=() source "$ROOT_DIR/includes/blueprint/populate_env.sh" "" # Add base blueprint module scripts first path="$BLUEPRINT_DIR/scripts/up.$PROJECT_CONTEXT.sh" if [[ -f "$path" ]]; then script_paths+=("$path") debug_print "Found: ${path#$BLUEPRINT_DIR/}" fi # Then add environment module scripts if [[ -n "$ENV_NAME" ]]; then path="$ENV_DIR/scripts/up.$PROJECT_CONTEXT.sh" else path="$BLUEPRINT_DIR/env/.empty/scripts/up.$PROJECT_CONTEXT.sh" fi if [[ -f "$path" ]]; then script_paths+=("$path") debug_print "Found: ${path#$BLUEPRINT_DIR/}" fi source "$ROOT_DIR/includes/resolve-dependencies.sh" "" ACTIVE_MODULES_LIST=(${MODULES_TO_LOAD[@]}) for module in ${MODULES_TO_LOAD[@]}; do debug_print "Searching scripts for module: $module" # Add base blueprint module scripts path="$BLUEPRINT_DIR/modules/$module/scripts/up.$PROJECT_CONTEXT.sh" if [[ -f "$path" ]]; then script_paths+=("$path") debug_print "Found: ${path#$BLUEPRINT_DIR/}" fi # Then add environment module scripts path="$ENV_DIR/modules/$module/scripts/up.$PROJECT_CONTEXT.sh" if [[ -f "$path" ]]; then script_paths+=("$path") debug_print "Found: ${path#$BLUEPRINT_DIR/}" fi done status=0 if ! $MODE_NO_SCRIPTS; then printf "Running up scripts for ${YELLOW}$PROJECT_CONTEXT${RESET} context...\n" # export SCRIPT_VARS # export SCRIPT_VARS_ENV # export SCRIPT_VARS_BUILD_ARGS source "$ROOT_DIR/includes/get-script-vars.sh" for path in "${script_paths[@]}"; do printf "Running script: ${path#$BLUEPRINT_DIR/}\n" PROGRAM="$(source "$ROOT_DIR/includes/script/prepare.sh" "$(cat "$path")")" command="bash -c \"$PROGRAM\"" bash $ENTRYPOINT "${SCRIPT_VARS_ENV[@]}" $DEFAULT_SERVICE exec "$command" status=$? if [[ $status > 0 ]]; then break fi done fi if [[ $status > 0 ]]; then printf -- "${RED}ERROR${RESET}: Up script returned non-zero code: ${path#$BLUEPRINT_DIR/}\n" exit $status fi if ! $MODE_SCRIPTS_ONLY && $MODE_SYNC; then bash $ENTRYPOINT sync --no-chown --skip-user fi <file_sep>#!/bin/bash debug_switch_context "PROCESS" if ! $AS_FUNCTION; then debug_print "Running the command..." fi # Blueprint PROCESS command # # This command preprocesses dockerfile templates that are used in blueprints: # # 1) Substitutes all environment variables prefixed with BLUEPRINT_ and # uncomments the lines where they are used if such variable is defined. # Blueprint variables have a different symbol in front of them in order # to distinguish them from build arguments during the build. # # For example the following input: # # > # RUN echo "%BLUEPRINT_DIR" # this is a dockerfile template # # Produces this output, since BLUEPRINT_DIR is always defined: # # > RUN echo ".docker-blueprint/<path-to-the-blueprint-root>" # # 2) Processes docker blueprint specific directives: # - `#include <resource>` # # Include a dockerfile _partial_ inside the current dockerfile template. # Resource path can include blueprint variables. In this case they are # resolved before trying to include the file. # # If the file specified doesn't exist, then the line with this directive # is removed from the final file. # # Before inserting, the content of the file is also processed by this # command. Because of this nested includes are possible. # shift # # Read arguments # MODE_INLINE=false if [[ -z "$1" ]]; then printf "Usage:\n" bash $ENTRYPOINT process --help exit 1 fi while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}process${RESET} [${FLG_COL}options${RESET}] ${ARG_COL}<path>${RESET}" printf "\t" printf "Preprocess dockerfile template from the blueprint\n" printf " ${FLG_COL}-i${RESET}, ${FLG_COL}--inline${RESET}" printf "\t\tOutput processed file to STDOUT instead of saving a copy with .out suffix\n" exit ;; -i | --inline) MODE_INLINE=true AS_FUNCTION=true ;; *) if [[ -z $DOCKERFILE ]]; then DOCKERFILE=$1 fi ;; esac shift done # # Initialize preprocessor for the file # if $AS_FUNCTION; then MODE_QUIET=true fi if ! $AS_FUNCTION; then debug_newline_print "Processing $(basename $DOCKERFILE)..." fi if [[ ! -f $DOCKERFILE ]]; then if ! $AS_FUNCTION; then printf "\n${RED}ERROR${RESET}: Cannot find $DOCKERFILE\n" fi exit 1 fi OUTPUT_FILE="$DOCKERFILE.out" cp -f "$DOCKERFILE" "$OUTPUT_FILE" # Process the dockerfile parse_directive() { bash "$ROOT_DIR/includes/preprocessor/parse-directive.sh" "$1" } substitute_vars() { bash "$ROOT_DIR/includes/preprocessor/substitute-vars.sh" "$1" } temp_file="$DOCKERFILE.tmp" # Parse dockerfile directives rm -f "$temp_file" && touch "$temp_file" while read -r line || [[ -n "$line" ]]; do if ! $AS_FUNCTION; then non_debug_print "." debug_print "${LIGHT_GRAY}<<<${RESET} %s\n" "$line" fi result="$(parse_directive "$line")" if [[ $? -eq 0 ]]; then echo "$result" >>"$temp_file" if ! $AS_FUNCTION && [[ "$result" != "$line" ]]; then debug_print "${RED}>>>${RESET}\n%s\n" "$result" fi fi done <"$OUTPUT_FILE" # https://stackoverflow.com/a/4160535/2467106 mv -f "$temp_file" "$OUTPUT_FILE" # Substitute blueprint variables rm -f "$temp_file" && touch "$temp_file" while read -r line || [[ -n "$line" ]]; do echo "$(substitute_vars "$line")" >>"$temp_file" ! $AS_FUNCTION && non_debug_print "." done <"$OUTPUT_FILE" mv -f "$temp_file" "$OUTPUT_FILE" # Remove lines with non-substituted variables rm -f "$temp_file" && touch "$temp_file" while read -r line || [[ -n "$line" ]]; do if [[ "$line" =~ "%" ]]; then replaced="$(echo "$line" | sed -E "s/#\s*(.*%.+)//g")" if [[ -n "$replaced" ]]; then echo "$replaced" >>"$temp_file" fi else echo "$line" >>"$temp_file" fi ! $AS_FUNCTION && non_debug_print "." done <"$OUTPUT_FILE" mv -f "$temp_file" "$OUTPUT_FILE" rm -f "$temp_file" if ! $AS_FUNCTION; then printf " ${GREEN}done${RESET}\n" fi if $MODE_INLINE; then cat "$OUTPUT_FILE" rm -f "$OUTPUT_FILE" else if $AS_FUNCTION; then printf "%s" "$OUTPUT_FILE" fi fi <file_sep>#!/bin/bash bash $ENTRYPOINT modules ${@:2} <file_sep>#!/bin/bash debug_switch_context "MODULES" debug_print "Running the command..." shift # # Read arguments # ACTION="" AVAILABLE_ACTIONS=( 'list' 'add' 'remove' ) MODULES=() MODE_FORCE=false MODE_QUIET=false MODE_NO_BUILD=false MODE_NO_SCRIPTS=false MODE_PRINT_ACTIVE_ONLY=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}modules${RESET} ${ARG_COL}<action>${RESET} [${ARG_COL}<module>${RESET}]" printf "\tAdd or remove a modules from the base blueprint to the current project\n" printf " ${FLG_COL}-a${RESET}, ${FLG_COL}--active${RESET}" printf "\t\tOnly list active modules\n" printf " ${FLG_COL}--no-build${RESET}" printf "\t\t\tDon't attempt to build\n" printf " ${FLG_COL}--no-scripts${RESET}" printf "\t\tDon't attempt to run scripts\n" exit ;; -f | --force) MODE_FORCE=true ;; -q | --quiet) MODE_QUIET=true ;; --no-build) MODE_NO_BUILD=true ;; --no-scripts) MODE_NO_SCRIPTS=true ;; -a | --active) MODE_PRINT_ACTIVE_ONLY=true ;; *) if [[ -z "$ACTION" ]]; then ACTION="$1" else MODULES+=("$1") fi ;; esac shift done if [[ -z "$ACTION" ]]; then bash $ENTRYPOINT modules --help printf "${GREEN}%s${RESET}:\n" "Available actions" for action in "${AVAILABLE_ACTIONS[@]}"; do printf -- "- %s\n" "$action" done exit 1 fi VALID_ACTION=false for action in "${AVAILABLE_ACTIONS[@]}"; do if [[ "$action" = "$ACTION" ]]; then VALID_ACTION=true break fi done if ! $VALID_ACTION; then printf -- "${RED}ERROR${RESET}: Unknown action '%s'\n" "$ACTION" exit 1 fi source "$ROOT_DIR/includes/blueprint/populate_env.sh" "" yq_read_array MODULES_TO_LOAD 'modules' EXPLICIT_MODULES_LIST=(${MODULES_TO_LOAD[@]}) source "$ROOT_DIR/includes/resolve-dependencies.sh" ${MODULES_TO_LOAD[@]} ACTIVE_MODULES_LIST=(${MODULES_TO_LOAD[@]}) MODULES_LIST=() ENV_MODULES_LIST=() BASE_MODULES_LIST=() if [[ -n "$ENV_DIR" ]]; then for module in $ENV_DIR/modules/*; do name="$(basename "$module")" ENV_MODULES_LIST+=("$name") MODULES_LIST+=("$name") done fi for module in $BLUEPRINT_DIR/modules/*; do name="$(basename "$module")" BASE_MODULES_LIST+=("$name") MODULES_LIST+=("$name") done if [[ ${#MODULES[@]} -eq 0 ]] || [[ "$ACTION" = "list" ]]; then bash $ENTRYPOINT modules --help if [[ ${#MODULES_LIST[@]} > 0 ]]; then printf "${GREEN}Available modules${RESET}:\n" for module in "${MODULES_LIST[@]}"; do IS_ENV_MODULE=false IS_BASE_MODULE=false IS_ACTIVE_MODULE=false IS_EXPLICIT_MODULE=false for env_module in "${ENV_MODULES_LIST[@]}"; do if [[ "$module" = "$env_module" ]]; then IS_ENV_MODULE=true break fi done for base_module in "${BASE_MODULES_LIST[@]}"; do if [[ "$module" = "$base_module" ]]; then IS_BASE_MODULE=true break fi done for active_module in "${ACTIVE_MODULES_LIST[@]}"; do if [[ "$module" = "$active_module" ]]; then IS_ACTIVE_MODULE=true break fi done for explicit_module in "${EXPLICIT_MODULES_LIST[@]}"; do if [[ "$module" = "$explicit_module" ]]; then IS_EXPLICIT_MODULE=true break fi done attributes=() if $IS_BASE_MODULE && $IS_ENV_MODULE; then attributes+=("${YELLOW}extended${RESET} by $ENV_NAME") elif ! $IS_BASE_MODULE && $IS_ENV_MODULE; then attributes+=("${CYAN}provided${RESET} by $ENV_NAME") fi if $IS_EXPLICIT_MODULE; then attributes+=("specified in ${BLUE}docker-blueprint.yml${RESET}") fi attribute_text="" if [[ ${#attributes[@]} > 0 ]]; then attribute_text+="(" i=1 for attribute in "${attributes[@]}"; do attribute_text+="$attribute" if [[ $i < ${#attributes[@]} ]]; then attribute_text+=", " fi ((i = i + 1)) done attribute_text+=")" fi icon="$ICON_EMPTY" if $IS_ACTIVE_MODULE; then icon="$ICON_CHECK" elif $MODE_PRINT_ACTIVE_ONLY; then continue fi printf -- "$icon %s $attribute_text\n" "$module" done else printf "The base blueprint '${YELLOW}$BLUEPRINT_QUALIFIED_NAME${RESET}' has no modules.\n" fi exit 1 else for MODULE in "${MODULES[@]}"; do FOUND=false for module in "${MODULES_LIST[@]}"; do if [[ "$module" == "$MODULE" ]]; then FOUND=true break fi done if ! $FOUND; then printf -- "${RED}ERROR${RESET}: Unable to find module '%s'.\n" "$MODULE" exit 1 fi done fi needs_rebuild=false for MODULE in "${MODULES[@]}"; do case "$ACTION" in add) exists="$(yq eval ".modules[] | select(. == \"$MODULE\")" "$PROJECT_BLUEPRINT_FILE")" if [[ -z "$exists" ]]; then yq eval ".modules = ((.modules // []) + [\"$MODULE\"])" -i "$PROJECT_BLUEPRINT_FILE" printf -- "Added module '%s' to the project blueprint.\n" "$MODULE" needs_rebuild=true else printf -- "${BLUE}INFO${RESET}: Project blueprint already has module '%s'.\n" "$MODULE" fi ;; remove) exists="$(yq eval ".modules[] | select(. == \"$MODULE\")" "$PROJECT_BLUEPRINT_FILE")" if [[ -n "$exists" ]]; then yq eval "del(.modules[] | select(. == \"$MODULE\"))" -i "$PROJECT_BLUEPRINT_FILE" printf -- "Removed module '%s' from the project blueprint.\n" "$MODULE" needs_rebuild=true else printf -- "${BLUE}INFO${RESET}: Project blueprint doesn't have module '%s'.\n" "$MODULE" fi ;; esac if ! $MODE_QUIET && ! $MODE_NO_BUILD && $needs_rebuild; then if ! $MODE_FORCE; then printf "Do you want to rebuild the project? (run with ${FLG_COL}--force${RESET} to always build)\n" printf "${YELLOW}WARNING${RESET}: This will ${RED}overwrite${RESET} existing docker files [y/N] " read -n 1 -r echo "" if [[ $REPLY =~ ^[Yy]$ ]]; then bash $ENTRYPOINT build --force else continue fi else bash $ENTRYPOINT build --force fi fi if ! $MODE_NO_SCRIPTS; then script_paths=() # Add base blueprint module scripts first path="$BLUEPRINT_DIR/modules/$MODULE/scripts/$ACTION.sh" if [[ -f "$path" ]]; then script_paths+=("$path") fi # Then add environment module scripts path="$ENV_DIR/modules/$MODULE/scripts/$ACTION.sh" if [[ -f "$path" ]]; then script_paths+=("$path") fi status=0 # export SCRIPT_VARS # export SCRIPT_VARS_ENV # export SCRIPT_VARS_BUILD_ARGS source "$ROOT_DIR/includes/get-script-vars.sh" for path in "${script_paths[@]}"; do printf "Running script for module '$MODULE'...\n" debug_print "Running script: ${path#$BLUEPRINT_DIR/}" PROGRAM="$(source "$ROOT_DIR/includes/script/prepare.sh" "$(cat "$path")")" command="bash -c \"$PROGRAM\"" bash $ENTRYPOINT "${SCRIPT_VARS_ENV[@]}" $DEFAULT_SERVICE exec "$command" status=$? if [[ $status > 0 ]]; then break fi done if [[ $status > 0 ]]; then printf -- "${RED}ERROR${RESET}: Module script returned non-zero code: ${path#$BLUEPRINT_DIR/}\n" exit $status fi fi done <file_sep>#!/bin/bash BLUEPRINT_FILE_TMP=$BLUEPRINT_DIR/blueprint.tmp BLUEPRINT_FILE_BASE=$BLUEPRINT_DIR/blueprint.yml debug_print "Generating blueprint file..." if [[ ! -f "$BLUEPRINT_FILE_BASE" ]]; then printf "\n${RED}ERROR${RESET}: Base blueprint.yml doesn't exist.\n" exit 1 fi # Start by making a copy of the base blueprint file cp "$BLUEPRINT_FILE_BASE" "$BLUEPRINT_FILE_TMP" # Merge environment blueprint debug_print "Using base blueprint: ${BLUEPRINT_FILE_BASE#$BLUEPRINT_DIR/}" file="$ENV_DIR/blueprint.yml" if [[ -n $ENV_DIR ]] && [[ -f "$file" ]]; then debug_print "Using environment blueprint: ${file#$BLUEPRINT_DIR/}" printf -- "$(yq_merge $BLUEPRINT_FILE_TMP $file)" >"$BLUEPRINT_FILE_TMP" fi # Merge project blueprint if [[ -f "$PROJECT_BLUEPRINT_FILE" ]]; then debug_print "Using project blueprint: ${PROJECT_BLUEPRINT_FILE}" printf -- "$(yq_merge $BLUEPRINT_FILE_TMP $PROJECT_BLUEPRINT_FILE)" >"$BLUEPRINT_FILE_TMP" fi export BLUEPRINT_FILE_TMP <file_sep>#!/bin/bash # Substitue yq with a docker container version, # if it isn't already present in the system. # # This affects performance, but allows to run docker-blueprint # without installing external dependencies. YQ_INSTALLED=false which yq > /dev/null if [[ $? -eq 0 ]]; then version=$(yq --version | sed -E 's/.+\s([[:digit:]])/\1/') if [[ $version =~ ^4 ]]; then YQ_INSTALLED=true fi fi if ! $YQ_INSTALLED; then if [[ -z $YQ_WARNING_SHOWN || ! $YQ_WARNING_SHOWN ]] && [[ -z $AS_FUNCTION || ! $AS_FUNCTION ]]; then printf "${YELLOW}WARNING${RESET}: It appears that yq (version 4) is not installed locally.\n" printf "We are going to use docker version of yq, however it will be much slower.\n" printf "Install yq in order to make building faster: ${GREEN}https://github.com/mikefarah/yq#install${RESET}\n" printf "=============================================================\n" fi yq() { docker run --rm -i -v "${PWD}":/workdir mikefarah/yq:4 "$@" } fi export YQ_WARNING_SHOWN=true yq_merge() { yq eval-all '. as $item ireduce ({}; . *+ $item )' $@ } yq_read_value() { if [[ -z "$3" ]]; then FILE="$PROJECT_BLUEPRINT_FILE" else FILE="$3" fi printf -v "$1" "%s" "$(yq eval ".$2 // \"\"" "$FILE" 2>/dev/null)" } yq_write_value() { if [[ -z "$3" ]]; then FILE="$PROJECT_BLUEPRINT_FILE" else FILE="$3" fi yq eval ".$1 = \"$2\" | .$1 style=\"single\"" -i "$FILE" } yq_read_array() { if [[ -z "$3" ]]; then FILE="$PROJECT_BLUEPRINT_FILE" else FILE="$3" fi readarray -t "$1" < <(yq eval ".$2[]" "$FILE") } yq_read_keys() { if [[ -z "$3" ]]; then FILE="$PROJECT_BLUEPRINT_FILE" else FILE="$3" fi readarray -t "$1" < <(cat "$FILE" | yq eval ".$2 // []" - | yq eval "keys" - | yq eval ".[]" -) } <file_sep>#!/bin/bash bash $ENTRYPOINT environment ${@:2} <file_sep>#!/bin/bash if [[ -z $SILENT ]]; then SILENT=false fi debug_print "Resolving dependencies..." MODULES_TO_LOAD=($@) MODULES_TO_DISABLE=() debug_print "Requested modules: ${MODULES_TO_LOAD[*]}" source "$ROOT_DIR/includes/blueprint/merge.sh" # export BLUEPRINT_FILE_TMP # Collect modules to load from temporary preset file and CLI arguments yq_read_array MERGED_MODULES_TO_LOAD "modules" "$BLUEPRINT_FILE_TMP" for module in "${MERGED_MODULES_TO_LOAD[@]}"; do # Remove duplicates FOUND=false for existing_module in "${MODULES_TO_LOAD[@]}"; do if [[ "$module" = "$existing_module" ]]; then FOUND=true break fi done if ! $FOUND; then MODULES_TO_LOAD+=($module) fi done # Resolve all modules and their dependencies # Notice: cyclic dependencies WILL cause undefined behavior i=0 while [[ $i -lt ${#MODULES_TO_LOAD[@]} ]]; do module="${MODULES_TO_LOAD[i]}" module_dirs=() path="$BLUEPRINT_DIR/modules/$module" if [[ -d "$path" ]]; then debug_print "Found module '$module'" module_dirs+=("$path") fi path="$ENV_DIR/modules/$module" if [[ -d "$path" ]]; then debug_print "Found environment module '$module'" module_dirs+=("$path") fi if [[ ${#module_dirs[@]} -eq 0 ]]; then printf "${RED}ERROR${RESET}: Module '$module' not found.\n" exit 1 fi FOUND=false for entry in "${MODULES_TO_LOAD[@]}"; do if [[ $entry == $module ]]; then FOUND=true break fi done # Read disables from each module file for dir in "${module_dirs[@]}"; do file="$dir/blueprint.yml" if [[ -f "$file" ]]; then yq_read_array DISABLES 'disables' "$file" if [[ ${#DISABLES[@]} > 0 ]]; then debug_print "Module '$module' disables: ${DISABLES[*]}" fi # For each dependency to be disabled, add it to the list for dependency in "${DISABLES[@]}"; do MODULES_TO_DISABLE+=("$dependency") done fi done # Read depends_on from each module file for dir in "${module_dirs[@]}"; do file="$dir/blueprint.yml" if [[ -f "$file" ]]; then yq_read_array DEPENDS_ON 'depends_on' "$file" if [[ ${#DEPENDS_ON[@]} > 0 ]]; then debug_print "Module '$module' dependencies: ${DEPENDS_ON[*]}" fi FOUND=false # For each dependency, check whether it # already has been added to the list for dependency in "${DEPENDS_ON[@]}"; do FOUND=false for entry in "${MODULES_TO_LOAD[@]}"; do if [[ $entry == $dependency ]]; then FOUND=true break fi done # If dependency has not been already added, # replace current module with the dependency # and append module to the end of the list if ! $FOUND; then # Add missing dependencies for the current module # If those dependencies have their own dependencies, # they will also be checked and added on the next # iteration. MODULES_TO_LOAD+=("$dependency") fi done fi done ((i = i + 1)) ! $SILENT && non_debug_print "." done debug_print "Resolved module list: ${MODULES_TO_LOAD[*]}" debug_print "Modules to disable: ${MODULES_TO_DISABLE[*]}" PROCESSED_MODULE_LIST=() for module in "${MODULES_TO_LOAD[@]}"; do IS_DISABLED=false for disabled_module in "${MODULES_TO_DISABLE[@]}"; do if [[ "$module" = "$disabled_module" ]]; then IS_DISABLED=true break fi done if ! $IS_DISABLED; then PROCESSED_MODULE_LIST+=("$module") fi done MODULES_TO_LOAD=(${PROCESSED_MODULE_LIST[@]}) debug_print "Final module list: ${MODULES_TO_LOAD[*]}" <file_sep>#!/bin/bash substitute_vars() { bash "$ROOT_DIR/includes/preprocessor/substitute-vars.sh" "$1" } # Line starts with a comment symbol with a non-whitespace # symbol following right after it, so it can potentially be a directive. if [[ "$(echo "$1" | cut -c1)" = "#" ]]; then # Strip comment symbol from the beginning of the string INPUT="$(echo "$1" | cut -c2-)" IFS_OLD="$IFS" IFS=' ' read -r -a items <<<$INPUT IFS="$IFS_OLD" if [[ "${items[0]}" = "include" ]]; then resource_path="$(substitute_vars "${items[1]}")" file="$(AS_FUNCTION=true bash $ENTRYPOINT process "$resource_path")" if [[ -f "$file" ]]; then printf "%s" "$(cat $file)" rm -f "$file" # Clean up after processing exit # The given path was read successfully fi exit 1 # Unable to include the given path fi fi printf "%s" "$1" <file_sep>#!/bin/bash REQUIREMENTS=( git docker docker-compose ) for PROGRAM in "${REQUIREMENTS[@]}"; do if [[ -z $(which $PROGRAM) ]]; then echo "Error: '$PROGRAM' is not installed. Please install '$PROGRAM' first." exit 1 fi done PROJECT_DIR=~/.docker-blueprint ENTRYPOINT="$PROJECT_DIR/entrypoint.sh" if [[ -d "$PROJECT_DIR" ]]; then echo "Updating docker-blueprint to the latest version..." cd "$PROJECT_DIR" git pull else echo "Downloading the latest version of docker-blueprint..." git clone https://github.com/docker-blueprint/core.git "$PROJECT_DIR" chmod +x "$ENTRYPOINT" fi SUDO="$(which sudo 2>/dev/null)" which docker-blueprint >/dev/null if [[ $? > 0 ]]; then BIN_DIRS=( /usr/local/bin /usr/bin ) for DIR in "${BIN_DIRS[@]}"; do if [[ -d "$DIR" ]]; then echo "Creating link in '$DIR'..." $SUDO ln -sf "$ENTRYPOINT" "$DIR/docker-blueprint" $SUDO ln -sf "$ENTRYPOINT" "$DIR/dob" if [[ $? -eq 0 ]]; then echo "Installed successuflly." echo "" echo "Run the program by typing 'dob' (or the long version: docker-blueprint)" exit 0 else echo "Unable to create link." exit 1 fi fi done fi <file_sep>#!/bin/bash debug_switch_context "SYNC" debug_print "Running the command..." shift # # Read arguments # MODE_NO_CHOWN=false MODE_SKIP_USER=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}sync${RESET}" printf "\t\t\t\t" printf "Synchronize development environment container\n" printf " ${FLG_COL}--no-chown${RESET}" printf "\t\t\tDo not attempt to chown home directory (i.e. when there are a lot of local files)\n" exit ;; --no-chown) MODE_NO_CHOWN=true ;; --skip-user) MODE_SKIP_USER=true ;; esac shift done yq_read_value SYNC_USER "user" # # Synchronize container user with the current host # if ! $MODE_SKIP_USER && [[ -n "$SYNC_USER" ]]; then debug_print "SYNC_USER is defined" echo "Synchronizing user '$SYNC_USER'..." echo "Setting UID to $UID..." $DOCKER_COMPOSE exec "$DEFAULT_SERVICE" usermod -u "$UID" "$SYNC_USER" if ! $MODE_NO_CHOWN; then HOME_DIR="$($DOCKER_COMPOSE exec --user="$SYNC_USER" "$DEFAULT_SERVICE" env | grep '^HOME=' | sed -r 's/^HOME=(.*)/\1/' | sed 's/\r//' | sed 's/\n//')" if [[ -n "$HOME_DIR" ]]; then echo "Recursively chowning home directory '$HOME_DIR'..." $DOCKER_COMPOSE exec "$DEFAULT_SERVICE" chown -R "$SYNC_USER" "$HOME_DIR" else printf "${YELLOW}WARNING${RESET}: Unable to detect home directory.\n" echo "Is HOME defined inside the container?" fi fi fi if [[ -f .env ]]; then debug_print "Found .env file in the project directory" debug_print "Looking for docker-compose files..." temp_file="$TEMP_DIR/docker-compose.env" for file in docker-compose*; do debug_print "Found file: $file" if [[ ! -f "$temp_file" ]]; then debug_print "$temp_file doesn't exist - copying the first file..." cp -f "$file" "$temp_file" else debug_print "$temp_file exists - merging files..." printf -- "$(yq_merge $temp_file $file)" >"$temp_file" fi done readarray -t VARIABLES < <(yq eval '.services.*.environment | select(. != null) | keys | .[]' "$temp_file") temp_env_file="$TEMP_DIR/.env" cp -f ".env" "$temp_env_file" for variable in "${VARIABLES[@]}"; do value="$(yq eval ".services.*.environment.\"$variable\" // \"\"" "$temp_file")" # remove leading whitespace characters value="${value#"${value%%[![:space:]]*}"}" # remove trailing whitespace characters value="${value%"${value##*[![:space:]]}"}" # Check if value is a substituion if [[ "$value" =~ "$" ]]; then debug_print "Value of variable '$variable' is a substitution - replacing..." value="$(echo "$value" | sed -E 's/\$\{.+:\-(.*)\}/\1/')" debug_print "${RED}>>>${RESET} %s\n" "$value" fi while read -r line || [[ -n "$line" ]]; do # Parse each line into the parts before and after equal sign before="${line%=*}" after="${line#*=}" if [[ "$before" = "$variable" ]]; then if [[ "$after" =~ "#" ]]; then # Check if there is already a comment on this line debug_print "Variable '$variable' has a comment - skipping" elif [[ "$after" = "$value" ]]; then # Check if the value is the same debug_print "Variable '$variable' has the same value - skipping" elif [[ "$value" =~ "$" ]]; then # Check if value is a substituion debug_print "Variable '$variable' value is a substitution - skipping" else debug_print "Setting '$variable' to '$value'" echo "$before=$value # Value replaced by docker-blueprint: $after" >&2 continue fi fi echo "$line" >&2 done <"$temp_env_file" 2>"$temp_env_file.copy" mv -f "$temp_env_file.copy" "$temp_env_file" done cp -f "$temp_env_file" ".env" rm -f "$temp_env_file" rm -f "$temp_file" echo "Commented environment variables used by docker-compose" fi # # Restart container to apply chown # if ! $MODE_NO_CHOWN; then echo "Restarting container '$DEFAULT_SERVICE'..." $DOCKER_COMPOSE restart "$DEFAULT_SERVICE" fi <file_sep>#!/bin/bash # # Update .gitignore to exclude .docker-blueprint # CONTENT="$DIR_NAME/\n" if [[ -f .gitignore ]]; then if [[ -z $(cat .gitignore | grep "$DIR_NAME/") ]]; then printf "$CONTENT" >> .gitignore fi else printf "$CONTENT" > .gitignore fi <file_sep>#!/bin/bash ENV_PREFIX=() ENV_PREFIX+=("COMPOSE_PROJECT_NAME=${PROJECT_NAME}") FILES=() FILES+=("-f docker-compose.yml") if [[ -n "$PROJECT_CONTEXT" ]]; then FILES+=("-f docker-compose.$PROJECT_CONTEXT.yml") fi export DOCKER_COMPOSE="env ${ENV_PREFIX[@]} docker-compose ${FILES[@]}" <file_sep>#!/bin/bash if [[ -z "$BLUEPRINT_PATH" ]]; then # export BLUEPRINT_PATH SILENT=false source "$ROOT_DIR/includes/blueprint/compile.sh" "$BLUEPRINT" fi # Read values from merged blueprint debug_newline_print "Reading configuration..." yq_read_keys BUILD_ARGS_KEYS "build_args" "$BLUEPRINT_PATH" && non_debug_print "." SCRIPT_VARS=() add_variable() { debug_print "Added variable $1='$2'" SCRIPT_VARS+=("BLUEPRINT_$1=$2") } add_variable "BLUEPRINT_DIR" "${BLUEPRINT_DIR#"$PWD/"}" add_variable "ENV_DIR" "${ENV_DIR#"$PWD/"}" add_variable "ENV_NAME" "$ENV_NAME" for variable in ${BUILD_ARGS_KEYS[@]}; do yq_read_value value "build_args.$variable" "$BLUEPRINT_PATH" && non_debug_print "." # Replace build argument value with env variable value if it is set if [[ -n ${!variable+x} ]]; then value="${!variable:-}" fi add_variable "$variable" "$value" && non_debug_print "." done yq_read_keys DEPENDENCIES_KEYS "dependencies" "$BLUEPRINT_PATH" && non_debug_print "." for key in "${DEPENDENCIES_KEYS[@]}"; do yq_read_array DEPS "dependencies.$key" "$BLUEPRINT_PATH" && non_debug_print "." key="$(echo "$key" | tr [:lower:] [:upper:])" add_variable "DEPS_$key" "${DEPS[*]}" done yq_read_keys PURGE_KEYS "purge" "$BLUEPRINT_PATH" && non_debug_print "." for key in "${PURGE_KEYS[@]}"; do yq_read_array PURGE "purge.$key" "$BLUEPRINT_PATH" && non_debug_print "." key="$(echo "$key" | tr [:lower:] [:upper:])" add_variable "PURGE_$key" "${PURGE[*]}" done env_name="$(echo "$ENV_NAME" | tr [:lower:] [:upper:] | tr - _)" if [[ -n "$ENV_NAME" ]]; then add_variable "ENV_${env_name}_DIR" "$ENV_DIR" fi for module in "${MODULES_TO_LOAD[@]}"; do module_name="$(echo "$module" | tr [:lower:] [:upper:] | tr "/-" _)" path="${BLUEPRINT_DIR#"$PWD/"}/modules/$module" if [[ -d "$path" ]]; then add_variable "MODULE_${module_name}_DIR" "$path" fi path="${ENV_DIR#"$PWD/"}/modules/$module" if [[ -d "$path" ]]; then add_variable "ENV_${env_name}_MODULE_${module_name}_DIR" "$path" fi done non_debug_print " ${GREEN}done${RESET}\n" export SCRIPT_VARS SCRIPT_VARS_BUILD_ARGS=() for var in "${SCRIPT_VARS[@]}"; do name="$(echo "$var" | cut -d'=' -f1)" value="$(echo "$var" | cut -d'=' -f2)" SCRIPT_VARS_BUILD_ARGS+=("--build-arg $name='$value'") done export SCRIPT_VARS_BUILD_ARGS SCRIPT_VARS_ENV=() for var in "${SCRIPT_VARS[@]}"; do name="$(echo "$var" | cut -d'=' -f1)" value="$(echo "$var" | cut -d'=' -f2)" SCRIPT_VARS_ENV+=("-e $name='$value'") done export SCRIPT_VARS_ENV <file_sep><p align="center"> <a href="https://docker-blueprint.github.io" target="_blank"> <img src="https://raw.githubusercontent.com/docker-blueprint/docker-blueprint.github.io/master/docs/_media/icon.png" width="600"> </a> </p> <p align="center"> <img alt="Platform: Linux" src="https://img.shields.io/badge/platform-linux-lightgrey"> <a href="https://github.com/docker-blueprint/core/blob/master/LICENSE"> <img alt="License" src="https://img.shields.io/github/license/docker-blueprint/core"> </a> </p> - 💻 **Ephemeral development environments** - easily build up and tear down local development environments for your projects on any machine that can run docker. - 📦 **Modular blueprints** - create your own unique development environment. Use the specific technologies that your project requires - build your own stack by choosing the database, cache & other technologies. - 🐳 **Automatic dockerfile & docker-compose.yml file generation** - set up your development environment first - learn all the intricacies of docker later! - ✏️ **Extensible** - tweak the generated files as you please, or better yet - extend existing blueprint, so other people could use the same features that you will implement. # About Docker Blueprint `docker-blueprint` provides an ability to create modular **ephemeral** development environments. ## Create This allows developers to easily bring up local development environment on any machine, building `Dockerfile` and `docker-compose.yml` files with a simple command: ``` docker-blueprint new php --env laravel --with mysql redis horizon ``` ## Interact Better yet, `docker-blueprint` makes working with a containerized development environment a breeze - blurring the line between files on your work machine and runtime environment inside the container! Access your development environment seamlessly: ``` docker-blueprint npm run watch ``` ## Share Once you have initialized the blueprint for your project - you will have a `docker-blueprint.yml` file in its directory, which describes your project configuration. Now you can push these changes into a VCS repository and reproduce this same development environment on another machine: ``` docker-blueprint up ``` Interested in setting up your development environment? # Try it yourself! Get started by installing `docker-blueprint` on your machine https://docker-blueprint.github.io/#/getting-started <file_sep>#!/bin/bash shift case $1 in -h | --help) printf "${CMD_COL}update${RESET}\t\t\tUpdate docker-blueprint to the latest version\n" exit ;; esac bash -c "$(curl -fsSL https://raw.githubusercontent.com/docker-blueprint/core/master/install.sh)" bash $ENTRYPOINT version <file_sep>#!/bin/bash shift while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}example${RESET} ${ARG_COL}<name>${RESET}" printf "\t\tShow technology-specific usage example\n" exit ;; *) EXAMPLE_NAME=$1 ;; esac shift done if [[ -z "$EXAMPLE_NAME" ]]; then bash $ENTRYPOINT example -h fi FILES=("$ROOT_DIR/examples/"*.sh) EXAMPLES_LIST=() for file in "${FILES[@]}"; do name=$(basename "$file" .sh) number=$(echo $name | cut -d'-' -f1 | sed 's/^0*//') title=$(echo $name | cut -d'-' -f2) case $EXAMPLE_NAME in "$number" | "$title") printf "\n" eval "$(cat "$file")" printf "\n" exit ;; *) EXAMPLES_LIST+=("$title") ;; esac done printf "${GREEN}Available examples:${RESET}\n" for example in ${EXAMPLES_LIST[@]}; do printf -- "- %s\n" "$example" done exit 1 <file_sep>#!/bin/bash # Blueprint PULL command # # This command resolves blueprint name in format [VENDOR/]NAME[:TAG] and # tries to clone the repository from GitHub. # Default vendor is `docker-blueprint`, default tag is `master`. # # If NAME is a local directory & has at least one slash (/) the command # generates sha1 hash of the path and copies this directory instead. # This mode is useful for local blueprint development. # # This command supports two modes: # - interactive (AS_FUNCTION=false): prints the progress to stdout # - bash function (AS_FUNCTION=true): prints only the result to stdout # # Function mode allows to use this command in conjunction # with others (i.e. create). # # Read arguments # shift # Remove command name from the argument list CLEAN_INSTALL=false MODE_DRY_RUN=false MODE_GET_QUALIFIED=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}pull${RESET} ${ARG_COL}<blueprint>${RESET} [${FLG_COL}options${RESET}]" printf "\tDownload the latest version of blueprint\n" printf " ${FLG_COL}--clean${RESET}" printf "\t\t\tRemove already existing copy of a blueprint and install fresh download\n" exit ;; --clean) CLEAN_INSTALL=true ;; --dry-run) MODE_DRY_RUN=true ;; --get-qualified-name) MODE_GET_QUALIFIED=true ;; *) if [[ -z "$1" ]]; then printf "Usage: " bash $ENTRYPOINT pull --help exit 1 fi if [[ -z $BLUEPRINT ]]; then BLUEPRINT=$1 fi ;; esac shift done # # Parse blueprint name and branch # IFS=':' read -r -a BLUEPRINT_PART <<<$BLUEPRINT BLUEPRINT=${BLUEPRINT_PART[0]} if [[ -z ${BLUEPRINT_PART[1]} ]]; then BLUEPRINT_BRANCH="master" else BLUEPRINT_BRANCH=${BLUEPRINT_PART[1]} fi # # Parse blueprint maintainer and name # IFS='/' read -r -a BLUEPRINT_PART <<<$BLUEPRINT BLUEPRINT_MAINTAINER=${BLUEPRINT_PART[0]} BLUEPRINT_NAME=${BLUEPRINT_PART[1]} if [[ -z ${BLUEPRINT_PART[1]} ]]; then # This is an official blueprint BLUEPRINT_MAINTAINER="docker-blueprint" BLUEPRINT_NAME=${BLUEPRINT_PART[0]} else # This is a third-party blueprint BLUEPRINT_MAINTAINER=${BLUEPRINT_PART[0]} BLUEPRINT_NAME=${BLUEPRINT_PART[1]} fi BLUEPRINT_QUALIFIED_NAME="$BLUEPRINT_MAINTAINER/$BLUEPRINT_NAME:$BLUEPRINT_BRANCH" if $MODE_GET_QUALIFIED; then if $AS_FUNCTION; then printf $BLUEPRINT_QUALIFIED_NAME else echo $BLUEPRINT_QUALIFIED_NAME fi exit fi # # Check if blueprint is a local directory # if [[ -d $BLUEPRINT ]] && [[ $BLUEPRINT =~ "/" || $BLUEPRINT =~ "." || $BLUEPRINT =~ ".." ]]; then mkdir -p "$LOCAL_DIR/blueprints/.local" HASH=$(echo -n "$BLUEPRINT" | openssl dgst -sha1 | sed 's/^.* //') BLUEPRINT_DIR="$LOCAL_DIR/blueprints/.local/$HASH" if ! $AS_FUNCTION; then echo "Copying '$BLUEPRINT'..." fi rm -rf $BLUEPRINT_DIR cp -rf $BLUEPRINT $BLUEPRINT_DIR else # # Build path for the resolved blueprint # if [[ $BLUEPRINT_MAINTAINER = "docker-blueprint" ]]; then BLUEPRINT_DIR="$LOCAL_DIR/blueprints/_/$BLUEPRINT_NAME" else BLUEPRINT_DIR="$LOCAL_DIR/blueprints/$BLUEPRINT_MAINTAINER/$BLUEPRINT_NAME" fi PREVIOUS_DIR=$PWD if $AS_FUNCTION; then GIT_ARGS="-q" fi # # Try to clone or update blueprint repository # if ! $AS_FUNCTION; then echo "Pulling blueprint '$BLUEPRINT_QUALIFIED_NAME'..." fi if $CLEAN_INSTALL; then echo "Removing previous version of the blueprint..." rm -rf $BLUEPRINT_DIR fi if [[ ! -d $BLUEPRINT_DIR ]]; then BASE_URL="https://github.com/$BLUEPRINT_MAINTAINER/$BLUEPRINT_NAME" # # Check if repository exists and is a blueprint # if curl --output /dev/null --silent --head --fail "$BASE_URL/blob/master/blueprint.yml"; then if ! $MODE_DRY_RUN; then GIT_TERMINAL_PROMPT=0 \ git clone "$BASE_URL.git" $GIT_ARGS \ $BLUEPRINT_DIR fi else printf "${RED}ERROR${RESET}: Provided repository is not a blueprint.\n" exit 1 fi else PREVIOUS_DIR="$PWD" cd "$BLUEPRINT_DIR" git fetch >/dev/null cd "$PREVIOUS_DIR" fi fi if ! $MODE_DRY_RUN; then # # Reset to specified branch or tag # cd $BLUEPRINT_DIR # Always checkout master first git checkout master &>/dev/null BRANCHES=($(git --no-pager branch -a --list --color=never | grep -v HEAD | sed -e 's/\s*remotes\/origin\///' | sed -E 's/\* //' | sed -E 's/\s+//' | sort | uniq)) TAGS=($(git --no-pager tag --list --color=never)) for tag in "${TAGS[@]}"; do BRANCHES+=($tag) done FOUND=false for branch in "${BRANCHES[@]}"; do if [[ $BLUEPRINT_BRANCH = $branch ]]; then if $AS_FUNCTION; then git checkout $BLUEPRINT_BRANCH &>/dev/null else git checkout $BLUEPRINT_BRANCH fi FOUND=true break fi done if ! $FOUND; then if ! $AS_FUNCTION; then printf "${RED}ERROR${RESET}: Unable to find version '$BLUEPRINT_BRANCH'.\n" fi exit 1 else if ! $AS_FUNCTION; then echo "Successfuly pulled version '$BLUEPRINT_BRANCH'." fi fi cd $PREVIOUS_DIR fi if $AS_FUNCTION; then printf $BLUEPRINT_DIR fi <file_sep>#!/bin/bash debug_switch_context "NEW" debug_print "Running the command..." shift if [[ -z "$1" ]]; then bash $ENTRYPOINT new --help exit 1 fi FORCE_GENERATE=false MODE_DRY_RUN=false UP_ARGS=() # # Read arguments # while [[ "$#" -gt 0 ]]; do case $1 in -m | --with) ARG_WITH=() while [[ -n "$2" ]] && [[ "$2" != -* ]]; do ARG_WITH+=($2) shift done if [[ -z "${ARG_WITH[0]}" ]]; then bash $ENTRYPOINT new --help exit 1 fi ;; -e | --env) ENV_NAME=$2 shift if [[ -z "$ENV_NAME" ]]; then bash $ENTRYPOINT new --help exit 1 fi ;; -f | --force) FORCE_GENERATE=true ;; --clean) printf "This will ${RED}completely wipe out${RESET} current directory.\n" read -p "Are you sure? [y/N] " -n 1 -r echo "" if [[ $REPLY =~ ^[Yy]$ ]]; then rm -rf $(ls -A $PWD) else printf "${YELLOW}You answered 'no', stopping here.\n" exit 1 fi ;; -h | --help) printf "${CMD_COL}new${RESET} ${ARG_COL}<blueprint>${RESET} [${FLG_COL}options${RESET}]" printf "\tCreate containerized technology stack for the project in current directory\n" printf " ${FLG_COL}-e${RESET}, ${FLG_COL}--env${RESET} ${FLG_VAL_COL}<environment>${RESET}" printf "\tSet technology-specific environment (for example framework)\n" printf " ${FLG_COL}-m${RESET}, ${FLG_COL}--with${RESET} ${FLG_VAL_COL}<module>${RESET} ..." printf "\tA list of modules to include from this technology blueprint\n" printf " ${FLG_COL}-f${RESET}, ${FLG_COL}--force${RESET}" printf "\t\t\tAlways generate new docker-blueprint.yml, even if it already exists\n" printf " ${FLG_COL}--clean${RESET}" printf "\t\t\tRemove all files in current directory before building a blueprint\n" printf " ${FLG_COL}--dry-run${RESET}" printf "\t\t\tRun the command without writing any files\n" printf " ${FLG_COL}--no-cache${RESET}" printf "\t\t\tDon't use docker image cache\n" printf " ${FLG_COL}--no-chown${RESET}" printf "\t\t\tPass --no-chown to 'sync' command\n" printf " ${FLG_COL}--no-scripts${RESET}" printf "\t\tDon't attempt to run scripts\n" exit ;; --dry-run) MODE_DRY_RUN=true ;; --no-cache) UP_ARGS+=("--no-cache") ;; --no-chown) UP_ARGS+=("--no-chown") ;; --no-scripts) UP_ARGS+=("--no-scripts") ;; *) if [[ -z "$1" ]]; then bash $ENTRYPOINT new --help exit 1 fi BLUEPRINT=$1 ;; esac shift done # # Build project blueprint file # # Generate only when the file is not present # or force rebuild when the FORCE flag is supplied # if $FORCE_GENERATE; then rm -f "$PWD/$PROJECT_BLUEPRINT_FILE" elif [[ -f "$PWD/$PROJECT_BLUEPRINT_FILE" ]]; then printf "${RED}ERROR${RESET}: ${YELLOW}$PROJECT_BLUEPRINT_FILE${RESET} already exists (run with --force to override).\n" exit 1 fi if ! [[ -f "$PWD/$PROJECT_BLUEPRINT_FILE" ]]; then # export BLUEPRINT_PATH SILENT=false source "$ROOT_DIR/includes/blueprint/compile.sh" "$BLUEPRINT" debug_switch_context "NEW" # Populate project blueprint # Create empty YAML file echo "---" >"$PWD/$PROJECT_BLUEPRINT_FILE" fields_to_set=( 'from' 'user' 'version' 'environment' 'default_service' ) # Set blueprint field values for field in ${fields_to_set[@]}; do debug_print "Updating blueprint field: $field" yq_read_value value "$field" "$BLUEPRINT_PATH" if ! $MODE_DRY_RUN && [[ -n "$value" ]]; then yq_write_value "$field" "$value" "$PROJECT_BLUEPRINT_FILE" fi done environment="$(yq_read_value "environment" "$BLUEPRINT_PATH")" if ! $MODE_DRY_RUN && [[ -n "$environment" ]]; then debug_print "Setting environment: $environment" bash $ENTRYPOINT environment set "$environment" --quiet fi fields_to_merge=( 'build_args' 'project' ) # Merge blueprint key-value fields for field in ${fields_to_merge[@]}; do debug_print "Merging blueprint field: $field" yq_read_value value "$field" "$BLUEPRINT_PATH" if ! $MODE_DRY_RUN && [[ -n "$value" ]]; then yq eval-all ".$field = ((.$field // {}) as \$item ireduce ({}; . *+ \$item)) | select(fi == 0)" -i \ "$PROJECT_BLUEPRINT_FILE" "$BLUEPRINT_PATH" fi done # Append modules that were defined with `--with` option for module in "${ARG_WITH[@]}"; do debug_print "Adding module: $module" if ! $MODE_DRY_RUN; then bash $ENTRYPOINT modules add "$module" --quiet --no-scripts if [[ $? > 0 ]]; then printf "${RED}ERROR${RESET}: The was an error while adding module '$module'\n" exit 1 fi fi done rm -f "$BLUEPRINT_PATH" fi if $FORCE_GENERATE; then UP_ARGS+=("--force") fi command="$ENTRYPOINT up ${UP_ARGS[@]}" debug_print "Running command: $command" if ! $MODE_DRY_RUN; then bash $command fi <file_sep>#!/bin/bash shift MODE_FORCE=false MODE_QUIET=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}environment ${ARG_COL}<name> | clear${RESET}" printf "\tSet or clear current specified environemnt\n" exit ;; -f | --force) MODE_FORCE=true ;; -q | --quiet) MODE_QUIET=true ;; *) ENVIRONMENT=$1 ;; esac shift done if [[ "$ENVIRONMENT" != "clear" ]]; then source "$ROOT_DIR/includes/blueprint/populate_env.sh" "" if [[ -n "$ENV_NAME" ]]; then printf "Current environment: %s\n" "$ENV_NAME" fi if [[ -z "$ENVIRONMENT" ]]; then if [[ -d "$BLUEPRINT_DIR/env" ]]; then printf "${GREEN}%s${RESET}:\n" "Available environments" for environment in $BLUEPRINT_DIR/env/*; do printf -- "- %s\n" "${environment#"$BLUEPRINT_DIR/env/"}" done else printf "The blueprint '${YELLOW}$BLUEPRINT_QUALIFIED_NAME${RESET}' has no environments.\n" fi exit 1 fi if [[ ! -d "$BLUEPRINT_DIR/env/$ENVIRONMENT" ]]; then printf "${RED}ERROR${RESET}: No such environment '$ENVIRONMENT'.\n" exit 1 fi yq_write_value "environment" "$ENVIRONMENT" else yq eval "del(.environment)" -i "$PROJECT_BLUEPRINT_FILE" fi if ! $MODE_QUIET; then if ! $MODE_FORCE; then printf "Do you want to rebuild the project? (run with ${FLG_COL}--force${RESET} to always build)\n" printf "${YELLOW}WARNING${RESET}: This will ${RED}overwrite${RESET} existing docker files [y/N] " read -n 1 -r if [[ $REPLY =~ ^[Yy]$ ]]; then echo "" bash $ENTRYPOINT build --force fi else bash $ENTRYPOINT build --force fi fi <file_sep>#!/bin/bash shift # # Read arguments # case $1 in -h | --help) printf "${CMD_COL}default${RESET} ${ARG_COL}<service> | clear${RESET}" printf "\tSet or clear default service to run commands against (usually set by the blueprint)\n" exit ;; *) SERVICE=$1 ;; esac if [[ -z "$SERVICE" ]]; then if [[ -z "$DEFAULT_SERVICE" ]]; then echo "No default service set" else echo "Current default service: $DEFAULT_SERVICE" fi echo "" echo "Usage: $EXECUTABLE_NAME default <service>" else if [[ "$SERVICE" == "clear" ]]; then if [[ -f $LOCAL_DIR/default_service ]]; then rm $LOCAL_DIR/default_service fi echo "Default service cleared" else SERVICES=$($DOCKER_COMPOSE ps --services) if [[ ${SERVICES[@]} =~ $SERVICE ]]; then echo "$SERVICE" >$LOCAL_DIR/default_service init_default_service echo "Default service set: $SERVICE" else echo "Unknown service '$SERVICE'." echo "Available services:" "$SERVICES" fi fi fi <file_sep>#!/bin/bash PREFIX="BLUEPRINT_" VARIABLES=($(env | awk -F= '{ print $1 }' | grep "^$PREFIX")) BUFFER="$1" SYMBOL="${2-%}" for variable in "${VARIABLES[@]}"; do # Escape variable value to use with sed value="$(echo ${!variable} | sed -E 's|[][\\/.*^$]|\\&|g')" # Uncomment the line where the variable is used BUFFER="$(echo "$BUFFER" | sed -E "s/#\s*(.*${SYMBOL}${variable#"$PREFIX"})/\1/g")" # Substitute the variable with its value BUFFER="$(echo "$BUFFER" | sed -E "s/${SYMBOL}${variable#"$PREFIX"}/$value/g")" done printf "%s" "$BUFFER" <file_sep>#!/bin/bash shift case $1 in -h | --help) printf "${CMD_COL}version${RESET}\t\t\tGet current version\n" exit ;; esac if ! $AS_FUNCTION; then printf "Current version: " fi PREVIOUS_DIR=$PWD cd $ROOT_DIR printf "$(git describe --match "v*" --abbrev=0 --tags)" printf " ($(git rev-parse --short HEAD))" if ! $AS_FUNCTION; then printf "\n" fi cd $PREVIOUS_DIR <file_sep>#!/bin/bash debug_switch_context "RUN" shift # # Read arguments # while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}run${RESET} ${ARG_COL}<command>${RESET}" printf "\t\t\tRun a command in specified environment\n" printf " ${FLG_COL}-T${RESET}" printf "\t\t\t\tDisable pseudo-tty allocation. Propagates -T to 'docker-compose exec'\n" exit ;; -T) MODE_NO_TTY='true' ;; *) COMMAND=$1 break ;; esac shift done SILENT=true source "$ROOT_DIR/includes/blueprint/populate_env.sh" "" # export BLUEPRINT_PATH SILENT=true source "$ROOT_DIR/includes/blueprint/compile.sh" "$BLUEPRINT" debug_switch_context "RUN" yq_read_keys POSSIBLE_COMMANDS "commands" "$BLUEPRINT_PATH" if [[ -z "$COMMAND" ]]; then bash $ENTRYPOINT run --help if [[ ${#POSSIBLE_COMMANDS[@]} > 0 ]]; then printf "${GREEN}Possible commands${RESET}:\n" for key in "${POSSIBLE_COMMANDS[@]}"; do printf -- "- $key\n" done printf "\n" else printf "${YELLOW}This project has no commands\n" fi exit 1 fi COMMAND_ROOT="commands.[\"$COMMAND\"]" yq_read_value PROGRAM "$COMMAND_ROOT.script" "$BLUEPRINT_PATH" if [[ -z "$PROGRAM" ]]; then printf "${YELLOW}No command '$COMMAND'\n" exit 1 fi debug_print "Setting up command to run..." ENV_PREFIX=() ENTRYPOINT_ARGS=() yq_read_keys ENVIRONMENT_KEYS "$COMMAND_ROOT.environment" "$BLUEPRINT_PATH" for key in "${ENVIRONMENT_KEYS[@]}"; do yq_read_value value "$COMMAND_ROOT.environment.$key" "$BLUEPRINT_PATH" # If there is already an environment variable # defined in the current environemnt if [[ -n ${!key} ]]; then # Then pass it to the program ENV_PREFIX+=("$key=\"${!key}\"") debug_print "Setting environment variable from current environment: $key=\"${!key}\"" else # Otherwise set it to the value defined in the blueprint ENV_PREFIX+=("$key=\"$value\"") debug_print "Setting environment variable: $key=\"$value\"" fi done i=0 for arg in "${@:2}"; do ((i = i + 1)) ENV_PREFIX+=("ARG_$i=\"$arg\"") debug_print "Setting argument as environment variable: ARG_$i=\"$arg\"" done ENV_PREFIX+=("COMMAND_NAME=\"$COMMAND\"") yq_read_value RUNTIME "$COMMAND_ROOT.runtime" "$BLUEPRINT_PATH" if [[ -z "$RUNTIME" ]]; then RUNTIME='sh -c' fi debug_print "Runtime: $RUNTIME" if [[ -z $MODE_NO_TTY ]]; then yq_read_value MODE_NO_TTY "$COMMAND_ROOT.no_tty" "$BLUEPRINT_PATH" MODE_NO_TTY="$(echo $MODE_NO_TTY | grep -P '^yes|true|1$')" fi if [[ -n "$MODE_NO_TTY" ]]; then ENTRYPOINT_ARGS+=('-T') fi COMMAND_VERB="exec" yq_read_value MODE_AS_ROOT "$COMMAND_ROOT.as_root" "$BLUEPRINT_PATH" MODE_AS_ROOT="$(echo $MODE_AS_ROOT | grep -P '^yes|true|1$')" [[ -n "$MODE_AS_ROOT" ]] && COMMAND_VERB="sudo" yq_read_value SERVICE "$COMMAND_ROOT.service" "$BLUEPRINT_PATH" if [[ -z "$SERVICE" ]]; then SERVICE="$DEFAULT_SERVICE" fi debug_print "Service: $SERVICE" yq_read_value CONTEXT "$COMMAND_ROOT.context" "$BLUEPRINT_PATH" if [[ -n "$CONTEXT" ]]; then export PROJECT_CONTEXT=$CONTEXT debug_print "Using COMMAND context: $CONTEXT" elif [[ -n "$PROJECT_CONTEXT" ]]; then debug_print "Using DEFAULT context: $PROJECT_CONTEXT" fi # Escape backslashes first PROGRAM="$(echo "$PROGRAM" | sed -E 's/\\/\\\\/g')" # Escape variable sign ($) to execute it inside runtime PROGRAM="$(echo "$PROGRAM" | sed -E 's/\$/\\\$/g')" # Then escape double-quotes, since they are used to enclose the program PROGRAM="$(echo "$PROGRAM" | sed -E 's/"/\\"/g')" command="env ${ENV_PREFIX[*]} $RUNTIME \"$PROGRAM\"" debug_print "Program to run:\n$PROGRAM" debug_print "Running..." bash $ENTRYPOINT ${ENTRYPOINT_ARGS[*]} -- $SERVICE $COMMAND_VERB "$command" for key in "${ENVIRONMENT_KEYS[@]}"; do unset $key done <file_sep>#!/bin/bash debug_switch_context "LOCK" debug_print "Running the command..." shift MODE_FORCE=false MODE_NO_BUILD=false while [[ "$#" -gt 0 ]]; do case $1 in -h | --help) printf "${CMD_COL}lock${RESET}" printf "\t\t\t\tLock blueprint version to the current latest version\n" exit ;; -f | --force) MODE_FORCE=true ;; --no-build) MODE_NO_BUILD=true ;; esac shift done yq_read_value CHECKPOINT 'version' debug_print "Current version: $CHECKPOINT" # Set the blueprint repository to the version specified. # This allows to always safely reproduce previous versions of the blueprint. if ! $MODE_FORCE && [[ -n $CHECKPOINT ]]; then printf "${BLUE}INFO${RESET}: Blueprint version is already locked (run with --force to override)\n" exit fi source "$ROOT_DIR/includes/blueprint/populate_env.sh" "" cd "$BLUEPRINT_DIR" CHECKPOINT="$(git rev-parse HEAD)" if [[ $? -eq 0 ]]; then printf "Locked version: ${CYAN}$CHECKPOINT${RESET}\n" else printf "${RED}ERROR${RESET}: Unable to checkout version $CHECKPOINT\n" exit 1 fi cd "$PROJECT_DIR" debug_print "Writing current version: $CHECKPOINT" yq_write_value "version" "$CHECKPOINT" if ! $MODE_NO_BUILD; then if ! $MODE_FORCE; then printf "Do you want to rebuild the project? (run with ${FLG_COL}--force${RESET} to always build)\n" printf "${YELLOW}WARNING${RESET}: This will ${RED}overwrite${RESET} existing docker files [y/N] " read -n 1 -r echo "" if [[ $REPLY =~ ^[Yy]$ ]]; then bash $ENTRYPOINT build --force fi else bash $ENTRYPOINT build --force fi fi
de206bf46bf68818e0e0f08f695bfefd0263577d
[ "Markdown", "Shell" ]
35
Shell
dlewisIII/docker-blueprint-core
bfc91c8fd1f4c9de204a9935febe5950a021f6ab
67587bab3815180d3c24a25c387ab4c5e708b1d2
refs/heads/master
<file_sep><?php declare(strict_types=1); use PHPUnit\Framework\TestCase; use Vicchi\GeoJson\Rewind; final class RewindTest extends TestCase { public function testFeatureGood(): void { $input = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/featuregood.input.geojson'); $expected = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/featuregood.output.geojson'); $actual = Rewind::rewind($input); $this->assertEquals($expected, $actual); } public function testCollection(): void { $input = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/collection.input.geojson'); $expected = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/collection.output.geojson'); $actual = Rewind::rewind($input); $this->assertEquals($expected, $actual); } public function testFlip(): void { $input = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/flip.input.geojson'); $expected = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/flip.output.geojson'); $actual = Rewind::rewind($input); $this->assertEquals($expected, $actual); } public function testMultiPolygon(): void { $input = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/multipolygon.input.geojson'); $expected = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/multipolygon.output.geojson'); $actual = Rewind::rewind($input); $this->assertEquals($expected, $actual); } public function testReverse(): void { $input = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/rev.input.geojson'); $expected = $this->getTestData(dirname(__FILE__) . '/../tests/rewind/rev.output.geojson'); $actual = Rewind::rewind($input); $this->assertEquals($expected, $actual); } private function getTestData($file) { $data = file_get_contents($file); if ($data === false) { throw new \Exception(sprintf("Failed to read %s\n", $file)); } $geojson = json_decode($data, true); if ($geojson === null) { throw new \Exception(sprintf("Failed to JSON-ify %s (%s)\n", $file, json_last_error_msg())); } return $geojson; } } ?> <file_sep>[![Build Status](https://travis-ci.org/vicchi/geojson-rewind.svg?branch=master)](https://travis-ci.org/vicchi/geojson-rewind) # geojson-rewind A set of PHP helper classes to assist in generating GeoJSON geometries that are compliant with the [GeoJSON specification](https://tools.ietf.org/html/rfc7946). Polygon ring order was undefined in the original GeoJSON spec, but since RFC7946 the _[right hand rule](https://tools.ietf.org/html/rfc7946#section-3.1.6)_ is mandated. > A linear ring MUST follow the right-hand rule with respect to the area it bounds, i.e., exterior rings are counterclockwise, and holes are clockwise. (If you know British English rather than American English, simply substitute _anticlockwise_ for _counterclockwise_.) ## Acknowledgements `geojson-rewind` is a port to PHP of Mapbox's Node.JS [`geojson-rewind`](https://github.com/mapbox/geojson-rewind) module by [<NAME>](https://github.com/tmcw) et al. Full credits, kudos and acknowledgements are due to Tom and the rest of the [Mapbox](https://www.mapbox.com/) team. ## Install The easiest way to install `geojson-rewind` is by using [composer](https://getcomposer.org/): ``` $> composer require vicchi/geojson-rewind ``` ## Usage ```php <?php include "vendor/autoload.php"; $source = [ 'type' => 'Polygon', 'coordinates' => [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] ]; $enforce_rfc7946=true; $output = Vicchi\GeoJson\Rewind::rewind($source, $enforce_rfc7946); // show output for demonstration purposes var_dump($output); ?> ``` The output could look like this (`$>` is the command line prompt). ``` $> php test.php array(2) { ["type"]=> string(7) "Polygon" ["coordinates"]=> array(2) { [0]=> array(5) { [0]=> array(2) { [0]=> float(100) [1]=> float(0) } [1]=> array(2) { [0]=> float(101) [1]=> float(0) } [2]=> array(2) { [0]=> float(101) [1]=> float(1) } [3]=> array(2) { [0]=> float(100) [1]=> float(1) } [4]=> array(2) { [0]=> float(100) [1]=> float(0) } } [1]=> array(5) { [0]=> array(2) { [0]=> float(100.2) [1]=> float(0.2) } [1]=> array(2) { [0]=> float(100.2) [1]=> float(0.8) } [2]=> array(2) { [0]=> float(100.8) [1]=> float(0.8) } [3]=> array(2) { [0]=> float(100.8) [1]=> float(0.2) } [4]=> array(2) { [0]=> float(100.2) [1]=> float(0.2) } } } } ``` ## License `geojson-rewind` is published under the [BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause) license. See [License File](LICENSE.txt) for more information. <file_sep><?php include "../vendor/autoload.php"; $source = [ 'type' => 'Polygon', 'coordinates' => [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] ]; $enforce_rfc7946=true; $output = Vicchi\GeoJson\Rewind::rewind($source, $enforce_rfc7946); // show output for demonstration purposes var_dump($output); ?> <file_sep><?php namespace Vicchi\GeoJson; class WGS84 { const RADIUS = 6378137; const FLATTENING_DENOM = 298.257223563; const FLATTENING = 1 / self::FLATTENING_DENOM; const POLAR_RADIUS = self::RADIUS * (1 - self::FLATTENING); } ?> <file_sep><?php declare(strict_types=1); use PHPUnit\Framework\TestCase; use Vicchi\GeoJson\Area; final class AreaTest extends TestCase { protected static $all; protected static $illinois; public static function setUpBeforeClass() { self::$all = self::getTestData(dirname(__FILE__) . '/../tests/area/all.geojson'); self::$illinois = self::getTestData(dirname(__FILE__) . '/../tests/area/illinois.geojson'); } public function testIllinoisArea(): void { $this->assertEquals(145978332359.36716, Area::geometry(self::$illinois), '', 0.1); } public function testWorldArea(): void { $this->assertEquals(511207893395811.06, Area::geometry(self::$all)); } public function testZeroPoint(): void { $data = [ 'type' => 'Point', 'coordinates' => [0, 0] ]; $this->assertEquals(0, Area::geometry($data)); } public function testZeroLineString(): void { $data = [ 'type' => 'LineString', 'coordinates' => [ [0, 0], [1, 1] ] ]; $this->assertEquals(0, Area::geometry($data)); } public function testGeometryCollection(): void { $data = [ 'type' => 'GeometryCollection', 'geometries' => [self::$all, self::$illinois] ]; $this->assertEquals(511353871728170.44, Area::geometry($data)); } private static function getTestData($file) { $data = file_get_contents($file); if ($data === false) { throw new \Exception(sprintf("Failed to read %s\n", $file)); } $geojson = json_decode($data, true); if ($geojson === null) { throw new \Exception(sprintf("Failed to JSON-ify %s (%s)\n", $file, json_last_error_msg())); } return $geojson; } } ?> <file_sep><?php namespace Vicchi\GeoJson; class Rewind { static public function rewind($geojson, $enforce_rfc7946=true) { switch ($geojson['type']) { case 'FeatureCollection': $geojson['features'] = array_map(function($item) use($enforce_rfc7946) { return self::rewind($item, $enforce_rfc7946); }, $geojson['features']); return $geojson; case 'Feature': $geojson['geometry'] = self::rewind($geojson['geometry'], $enforce_rfc7946); return $geojson; case 'Polygon': case 'MultiPolygon': return self::correct($geojson, $enforce_rfc7946); default: return $geojson; } } static private function correct($feature, $enforce_rfc7946) { if ($feature['type'] === 'Polygon') { $feature['coordinates'] = self::correctRings($feature['coordinates'], $enforce_rfc7946); } else if ($feature['type'] === 'MultiPolygon') { $feature['coordinates'] = array_map(function($item) use($enforce_rfc7946) { return self::correctRings($item, $enforce_rfc7946); }, $feature['coordinates']); } return $feature; } static private function correctRings($coords, $enforce_rfc7946) { $enforce_rfc7946 = boolval($enforce_rfc7946); $coords[0] = self::wind($coords[0], !$enforce_rfc7946); for ($i = 1; $i < count($coords); $i++) { $coords[$i] = self::wind($coords[$i], $enforce_rfc7946); } return $coords; } static private function wind($coords, $dir) { return self::clockwise($coords) === $dir ? $coords : array_reverse($coords); } static private function clockwise($coords) { return (Area::ringArea($coords) >= 0); } } ?> <file_sep><?php namespace Vicchi\GeoJson; class Area { static function geometry($geojson) { $area = 0; switch ($geojson['type']) { case 'Polygon': return self::polygonArea($geojson['coordinates']); case 'MultiPolygon': foreach ($geojson['coordinates'] as $coords) { $area += self::polygonArea($coords); } return $area; case 'Point': case 'MultiPoint': case 'LineString': case 'MultiLineString': return 0; case 'GeometryCollection': foreach ($geojson['geometries'] as $geometry) { $area += self::geometry($geometry); } return $area; default: throw new \Exception('Unknown GeoJSON type "' . $geojson['type'] . '"'); } } static function polygonArea($coords) { $area = 0; if (!empty($coords) && (count($coords) > 0)) { $area += abs(self::ringArea($coords[0])); array_shift($coords); foreach($coords as $coord) { $area -= abs(self::ringArea($coord)); } } return $area; } /** * Calculate the approximate area of the polygon were it projected onto * the earth. Note that this area will be positive if ring is oriented * clockwise, otherwise it will be negative. * * Reference: * <NAME> and <NAME>, "Some Algorithms for * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409 * * Returns: * {float} The approximate signed geodesic area of the polygon in square * meters. */ static function ringArea($coords) { $area = 0; $len = count($coords); if ($len > 2) { for ($i = 0; $i < $len; $i++) { if ($i === ($len - 2)) { $lowerIndex = $len - 2; $middleIndex = $len - 1; $upperIndex = 0; } else if ($i === ($len - 1)) { $lowerIndex = $len - 1; $middleIndex = 0; $upperIndex = 1; } else { $lowerIndex = $i; $middleIndex = $i + 1; $upperIndex = $i + 2; } $p1 = $coords[$lowerIndex]; $p2 = $coords[$middleIndex]; $p3 = $coords[$upperIndex]; $area += (self::rad($p3[0]) - self::rad($p1[0])) * sin(self::rad($p2[1])); } $area = $area * WGS84::RADIUS * WGS84::RADIUS / 2; } return $area; } static function rad($coord) { return $coord * M_PI / 180; } } ?>
40af0acefb6052e7c4516a62184407a1ab711157
[ "Markdown", "PHP" ]
7
PHP
avvertix/geojson-rewind
be2434c6b72587b8da957976824f39f0be8afe29
1a0087669473801112d11a066084253fbb988dd9
refs/heads/master
<file_sep>import AbstractSocketHandler from "./../Core/AbstractSocketHandler.js"; import {SocketConstants as SC} from "./../../server/Socket/SocketConstants.js"; import AppEvent from "./../Events/AppEvent.js"; import {browserHistory} from 'react-router'; export default class ChatSocketHandler extends AbstractSocketHandler { constructor(global, socket) { super(socket); global.cH = this; } onConnected() { super.onConnected(); this.socket.on(SC.on_youJoinRoom, this.onYouJoinRoom.bind(this)); this.socket.on(SC.on_userJoinRoom, this.onUserJoinRoom.bind(this)); this.socket.on(SC.on_userLeaveRoom, this.onUserLeaveRoom.bind(this)); this.socket.on(SC.on_chatMessage, this.onChatMessage.bind(this)); } onDisconnected() { super.onDisconnected(); this.socket.off(SC.on_youJoinRoom); this.socket.off(SC.on_userJoinRoom); this.socket.off(SC.on_userLeaveRoom); this.socket.off(SC.on_chatMessage); } /* ------------- PROPERTIES ------------- */ get userName() { return this.name; } set userName(value) { this.name = value; } get roomName() { return this.room; } set roomName(value) { this.room = value; } isInRoom() { return this.roomName !== undefined; } /* ------------- OUT BOUND MESSAGES ------------- */ createChatRoom(isFreeForAll) { if(this.isConnected()) { this.emit(SC.on_createRoom, this.userName, isFreeForAll); } } joinChatRoom(roomName) { if(this.isConnected()) { this.emit(SC.on_userJoinRoom, this.userName, roomName); } } leaveChatRoom() { if(this.isConnected() && this.isInRoom()) { this.socket.emit(SC.on_userLeaveRoom); } this.onYouLeaveRoom(); } sendChatMessage(message) { if(message !== undefined && message !== "" && message.length > 0) { //send the message back to yourself this.onChatMessage(this.userName, message); if(this.isConnected() && this.isInRoom()) { this.emit(SC.on_chatMessage, message); } } } /* ------------- IN BOUND MESSAGES ------------- */ onYouJoinRoom(roomName) { this.roomName = roomName; this.dispatchEvent(AppEvent.YouJoinRoom, this.roomName); //redirect user to room url. this url is used to send to friends browserHistory.push("/" + roomName); } onUserJoinRoom(userName) { this.dispatchEvent(AppEvent.UserJoinRoom, userName, this.roomName); } onYouLeaveRoom() { this.dispatchEvent(AppEvent.YouLeaveRoom, this.roomName); delete this.roomName; } onUserLeaveRoom(userName) { this.dispatchEvent(AppEvent.UserLeaveRoom, userName, this.roomName); } onChatMessage(userName, message, messageType) { this.dispatchEvent(AppEvent.ChatMessage, userName, message); } } <file_sep>"use_strict"; module.exports.SocketConstants = class { /* ------------- SOCKET IO MESSAGES ------------- */ static get on_connected() { return "connection"; } static get on_disconnected() { return "disconnect"; } /* ------------- APP MESSAGES ------------- */ //chat room static get on_userJoinRoom() { return "join_room"; } static get on_youJoinRoom() { return "you_join_room"; } static get on_userLeaveRoom() { return "leave_room"; } static get on_chatMessage() { return "chat_msg"; } //create room static get on_createRoom() { return "create_room"; } //video static get on_videoPlay() { return "video_play"; } static get on_videoPause() { return "video_pause"; } static get on_videoChange() { return "video_change"; } }; <file_sep># grouptube Watch a youtube video with a group of friends <file_sep>//http://stackoverflow.com/questions/6248666/how-to-generate-short-uid-like-ax4j9z-in-js module.exports.getUid = function generateUIDNotMoreThan1million() { return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).slice(-4); }; <file_sep>export default class AppEvent { //Chat static get YouJoinRoom(){ return 1; } static get UserJoinRoom(){ return 2; } static get YouLeaveRoom(){ return 3; } static get UserLeaveRoom(){ return 4; } static get ChatMessage(){ return 5; } //Video player static get VideoPlayerReady(){ return 6; } static get VideoPlay(){ return 7; } static get VideoPause(){ return 8; } static get VideoChange(){ return 9; } } <file_sep>//scss require("./../SCSS/video.scss"); import React from "react"; export default class VideoComponent extends React.Component { constructor(props) { super(props); this.state = { text: "" }; } onSubmit(event) { event.preventDefault(); let textValue = this.state.text; this.setState({ text: "" }); ytw.changeVideo(textValue); } onInputChange(event) { this.setState({ text: event.target.value }); } render() { return ( <div className="videoContainer"> <div id="video"></div> <div className="videoInput"> <form onSubmit={this.onSubmit.bind(this)}> <input type="text" onChange={this.onInputChange.bind(this)} value={this.state.text}/> <button type="submit">Update Video</button> </form> </div> </div> ); } } <file_sep>//scss require("./../SCSS/modal.scss"); import React from "react"; import {Image} from "./StateLessComponents.jsx"; class ModalComponent extends React.Component { render() { if(this.props.open) { return ( <div className="modal-background"> <div className="modal"> <Image className="modal-icon" src="/img/grouptube-logo.svg"/> {this.props.children} </div> </div> ); } else { return ( <div></div> ); } } } export class CreateRoomModal extends ModalComponent { constructor(props) { super(props); this.state = { open: true, userName: "", freeForAll: true }; } closeModal() { this.setState({ open: false }); } onSubmit(event) { event.preventDefault(); if(this.state.userName !== "") { cH.userName = this.state.userName; cH.createChatRoom(this.state.freeForAll); this.closeModal(); } } onUserNameChange(event) { this.setState({ userName: event.target.value }); } onRoomNameChange(event) { this.setState({ roomName: event.target.value }); } onFreeForAllClicked(event) { this.setState({ freeForAll: event.target.checked }); } render() { return ( <ModalComponent open={this.state.open}> <form className="modal-form" onSubmit={this.onSubmit.bind(this)}> <input type="text" onChange={this.onUserNameChange.bind(this)} value={this.state.userName} placeholder="<NAME>"/> <input type="checkbox" onChange={(e)=>{}} onClick={this.onFreeForAllClicked.bind(this)} checked={this.state.freeForAll}/><h2>Free For All Mode</h2> <button type="submit">Create Room</button> </form> </ModalComponent> ); } } export class JoinRoomModal extends ModalComponent { constructor(props) { super(props); this.state = { open: !cH.isInRoom() //close the modal if the user is already in a room }; } closeModal() { this.setState({ open: false }); } onSubmit(event) { event.preventDefault(); //join room if(this.state.userName !== "") { cH.userName = this.state.userName; cH.joinChatRoom(this.props.params.room); this.closeModal(); } } onUserNameChange(event) { this.setState({ userName: event.target.value }); } onRoomNameChange(event) { this.setState({ roomName: event.target.value }); } render() { return ( <ModalComponent open={this.state.open}> <form className="modal-form" onSubmit={this.onSubmit.bind(this)}> <input type="text" onChange={this.onUserNameChange.bind(this)} value={this.state.userName} placeholder="<NAME>"/> <button type="submit">Join Room</button> </form> </ModalComponent> ); } } <file_sep>import {SocketConstants as SC} from "./../../server/Socket/SocketConstants.js"; import EventDispatcher from "./../Utils/EventDispatcher.js"; export default class AbstractSocketHandler { constructor(socket) { this.socket = socket; this.dispatcher = new EventDispatcher(); this.connected = false; //listen to the base connect and disconnect events this.socket.on("connect", this.onConnected.bind(this)); this.socket.on(SC.on_disconnected, this.onDisconnected.bind(this)); } /* ------------- EVENT DISPATCHER ------------- */ addEventListener(eventName, handler) { this.dispatcher.addEventListener(eventName, handler); } dispatchEvent(eventName, ...properties) { this.dispatcher.dispatchEvent(eventName, ...properties); } removeEventListener(eventName, handler) { this.dispatcher.removeEventListener(eventName, handler); } removeEventListerners(eventName) { this.dispatcher.removeEventListerners(eventName); } /* ------------- SOCKET EVENTS AND METHODS ------------- */ isConnected() { return this.connected; } onConnected() { this.connected = true; } onDisconnected() { this.connected = false; } emit(socketEvent, ...properties) { this.socket.emit(socketEvent, ...properties); } } <file_sep>//scss require("./../SCSS/chat.scss"); import React from "react"; import ReactDOM from "react-dom"; import AppEvent from "./../Events/AppEvent.js"; import HeaderComponent from "./Header.jsx"; export default class ChatComponent extends React.Component { constructor(props){ super(props); this.state = { messages: [] }; this.chatColours = [ "#00e9ff", "#00ff8d", "#ff00ff", "#0072ff", "#7ac0ee", "#95003b", "#ff00a8", "#2e0061", "#0018b0", "#00ffb7", "#e600ff", "#ff4ea8", "#381d8e", "#68bb41", "#084460" ]; this.users = new Map(); this.maxMessages = 100; cH.addEventListener(AppEvent.YouJoinRoom, this.onYouJoinRoom.bind(this)); cH.addEventListener(AppEvent.UserJoinRoom, this.onUserJoinedRoom.bind(this)); cH.addEventListener(AppEvent.YouLeaveRoom, this.onYouLeaveRoom.bind(this)); cH.addEventListener(AppEvent.UserLeaveRoom, this.onUserLeaveRoom.bind(this)); cH.addEventListener(AppEvent.ChatMessage, this.onChatMessage.bind(this)); /*ytw.addEventListener(AppEvent.VideoPlay, this.onVideoPlay.bind(this)); ytw.addEventListener(AppEvent.VideoPause, this.onVideoPause.bind(this)); ytw.addEventListener(AppEvent.VideoChange, this.onVideoChange.bind(this));*/ } randomColour() { return this.chatColours[Math.floor(Math.random() * this.chatColours.length)]; } //chat onYouJoinRoom(roomName) { this.onChatMessage(undefined, "You joined the room " + roomName, "notification"); this.users.set(cH.userName, this.randomColour()); } onUserJoinedRoom(userName, roomName) { this.onChatMessage(undefined, userName + " joined the room", "notification"); this.users.set(userName, this.randomColour()); } onYouLeaveRoom(roomName) { this.onChatMessage(undefined, "You left the room " + roomName, "notification"); this.users.clear(); this.setState({ messages: [] }); } onUserLeaveRoom(userName, roomName) { this.onChatMessage(undefined, userName + " left the room " + roomName, "notification"); this.users.delete(userName); } onChatMessage(from, message, type) { let newMessages = this.state.messages; newMessages.push({ from: from, message: message, type: type }); this.setState({ messages: newMessages }); } //video /*onVideoPlay() { this.onChatMessage(undefined, "Video Played", "update"); } onVideoPause() { this.onChatMessage(undefined, "Video Paused", "update"); } onVideoChange(videoId) { this.onChatMessage(undefined, "Video Changed to " + videoId, "update"); }*/ //react methods componentWillUpdate() { //check if the user has scrolled to the bottom of the chat this.shouldScrollBottom = this.refs.chatArea.scrollTop + this.refs.chatArea.offsetHeight === this.refs.chatArea.scrollHeight; } componentDidUpdate() { if (this.shouldScrollBottom) { //if scrolled to the bottom, change the scroll top to the height to force scroll to the bottom when a new message is inserted this.refs.chatArea.scrollTop = this.refs.chatArea.scrollHeight; } } render() { let users = this.users; return ( <div className="side-bar"> <HeaderComponent/> <div className="chatArea" ref="chatArea"> { this.state.messages.map(function(element, index){ switch(element.type) { case "notification": return <PromptMessage className={"chatNotification"} message={element.message} key={index} />; case "error": return <PromptMessage className={"chatError"} message={element.message} key={index} />; case "warning": return <PromptMessage className={"chatWarning"} message={element.message} key={index} />; case "update": return <PromptMessage className={"chatUpdate"} message={element.message} key={index} />; default: return <ChatMessage className={"chatMsg"} from={element.from} colour={users.has(element.from) ? users.get(element.from) : "#000000"} message={element.message} key={index}/>; } }) } </div> <ChatIU/> </div> ); } } class ChatIU extends React.Component { constructor(props) { super(props); this.state = { text: "" }; } onSubmit(event) { event.preventDefault(); let textValue = this.state.text; this.setState({ text: "" }); cH.sendChatMessage(textValue); } onInputChange(event) { this.setState({ text: event.target.value }); } render() { return ( <div className="chatUI"> <form onSubmit={this.onSubmit.bind(this)}> <input type="text" onChange={this.onInputChange.bind(this)} value={this.state.text}/> <button type="submit">Send</button> </form> </div> ); } } class PromptMessage extends React.Component { render() { return ( <div className={this.props.className}> <span className="messageNotification">{this.props.message}</span> </div> ); } } class ChatMessage extends React.Component { render() { return ( <div className={this.props.className}> <p> <span className="from" style={{color: this.props.colour}}>{this.props.from}: </span> <span className="message">{this.props.message}</span> </p> </div> ); } } <file_sep>//scss require("./SCSS/global.scss"); //react import React from "react"; import {render as reactRender} from "react-dom"; //router import { Router, Route, IndexRoute, browserHistory } from 'react-router'; //components import VideoComponent from "./Ui/Video.jsx"; import ChatComponent from "./Ui/Chat.jsx"; import {CreateRoomModal, JoinRoomModal} from "./Ui/Modals.jsx"; //libraries import ChatSocketHandler from "./Core/ChatSocketHandler.js"; import VideoSocketHandler from "./Core/VideoSocketHandler.js"; let socket = io.connect(); new ChatSocketHandler(window, socket); new VideoSocketHandler(window, socket); class AppRootComponent extends React.Component { render() { return ( <div> <VideoComponent/> <ChatComponent/> {this.props.children} </div> ); } } /*reactRender(<VideoComponent/>, document.getElementById("video")); reactRender(<HeaderComponent/>, document.getElementById("header")); reactRender(<ChatComponent/>, document.getElementById("chat"));*/ // Opt-out of persistent state. removes the hash from the url reactRender( <Router history={browserHistory}> <Route path="/" component={AppRootComponent}> <IndexRoute component={CreateRoomModal}/> <Route path="/:room" component={JoinRoomModal}/> </Route> </Router>, document.getElementById("app")); <file_sep>export default class EventDispatcher { constructor() { this.events = new Map(); } addEventListener(eventName, handler) { if(handler !== undefined || handler !== null) { if(!this.events.has(eventName)){ this.events.set(eventName, []); } this.events.get(eventName).push(handler); } } dispatchEvent(eventName, ...properties) { if(this.events.has(eventName)) { let callbacks = this.events.get(eventName); for(let i = 0; i < callbacks.length; i++) { callbacks[i](...properties); } } } removeEventListener(eventName, handler) { if(this.events.has(eventName)) { let index = this.events.get(eventName).indexOf(eventName); if(index !== -1) { this.events.get(eventName).splice(index, 0); } } } removeEventListerners(eventName) { if(this.events.has(eventName)) { this.events.delete(eventName); } } } <file_sep>var SocketConstants = require("./SocketConstants.js").SocketConstants; var getUid = require("./../Utils/UidGenerator.js").getUid; var roomData = new Map(); module.exports.SocketClient = class SocketClient { constructor(io, socket) { this.io = io; this.socket = socket; this.isInRoom = false; //chat and room this.socket.on(SocketConstants.on_disconnected, this.onDisconnected.bind(this)); this.socket.on(SocketConstants.on_userJoinRoom, this.onUserJoinedRoom.bind(this)); this.socket.on(SocketConstants.on_userLeaveRoom, this.onUserLeftRoom.bind(this)); this.socket.on(SocketConstants.on_chatMessage, this.onChatMessage.bind(this)); //room creation this.socket.on(SocketConstants.on_createRoom, this.onCreateRoom.bind(this)); //video this.socket.on(SocketConstants.on_videoPlay, this.onPlayVideo.bind(this)); this.socket.on(SocketConstants.on_videoPause, this.onPauseVideo.bind(this)); this.socket.on(SocketConstants.on_videoChange, this.onChangeVideo.bind(this)); } /* ------------- UTILITY METHODS ------------- */ sendToClient(method, ...args) { this.socket.emit(method, ...args); } sendToOthersInRoom(method, ...args) { this.socket.broadcast.to(this.roomName).emit(method, ...args); } sendToAllInRoom(method, ...args) { this.io.sockets.in(this.roomName).emit(method, ...args); } /* ------------- IN BOUND MESSAGES ------------- */ onDisconnected() { if(this.isInRoom) { //notify other users of user left this.sendToOthersInRoom(SocketConstants.on_userLeaveRoom, this.userName); } //remove event listeners this.socket.removeAllListeners(SocketConstants.on_disconnected); this.socket.removeAllListeners(SocketConstants.on_userJoinRoom); this.socket.removeAllListeners(SocketConstants.on_userLeaveRoom); this.socket.removeAllListeners(SocketConstants.on_chatMessage); this.socket.removeAllListeners(SocketConstants.on_videoPlay); this.socket.removeAllListeners(SocketConstants.on_videoPause); this.socket.removeAllListeners(SocketConstants.on_videoChange); this.socket.removeAllListeners(SocketConstants.on_createRoom); //remove free for all mode if the leader leaves if(roomData.has(this.roomName) && roomData.get(this.roomName) === this.socket.id) { roomData.delete(this.roomName); } //delete no longer needed references delete this.io; delete this.socket; delete this.isInRoom; delete this.userName; delete this.roomName; } //join an already created room onUserJoinedRoom(userName, roomName) { //set our username this.userName = userName; //set the room name this.roomName = roomName; //join the chat room this.socket.join(this.roomName); //flag that we are in a room this.isInRoom = true; //message back to client on room joined //this.sendToClient("joined_room", this.roomName); //notify other users of connected user this.sendToClient(SocketConstants.on_youJoinRoom, this.roomName); this.sendToOthersInRoom(SocketConstants.on_userJoinRoom, this.userName); } onUserLeftRoom() { if(this.isInRoom) { //only send message to user //this.sendToClient("left_room", this.roomName); //notify other users of user left this.sendToOthersInRoom(SocketConstants.on_userLeaveRoom, this.userName); //leave the room this.isInRoom = false; this.socket.leave(this.roomName); delete this.roomName; } } onChatMessage(message, messageType) { if(this.isInRoom) { //todo perhaps parse a command? else send as a chat message //broadcast to room, the new message this.sendToOthersInRoom(SocketConstants.on_chatMessage, this.userName, message, messageType); } } onCreateRoom(userName, isFreeForAll) { let roomId = getUid(); if(!isFreeForAll) { //only store free for all data if the room flags it //set the creator as the ruler of the room roomData.set(roomId, this.socket.id); } this.onUserJoinedRoom(userName, roomId, isFreeForAll); } //VIDEO canPerformAction() { return roomData.has(this.roomName) ? roomData.get(this.roomName) === this.socket.id : true; } onPlayVideo() { if(this.isInRoom && this.canPerformAction()) { //broadcast to room, the new video state this.sendToOthersInRoom(SocketConstants.on_videoPlay); } } onPauseVideo() { if(this.isInRoom && this.canPerformAction()) { //broadcast to room, the new video state this.sendToOthersInRoom(SocketConstants.on_videoPause); } } onChangeVideo(videoData) { if(this.isInRoom && this.canPerformAction()) { //broadcast to room, the new video state this.sendToOthersInRoom(SocketConstants.on_videoChange, videoData); } } }; <file_sep>var path = require("path"); var express = require('express'); var app = express(); var http = require("http").Server(app); var io = require("socket.io")(http); var SocketConstants = require("./Socket/SocketConstants.js").SocketConstants; var SocketClient = require("./Socket/SocketClient").SocketClient; //serve files out of the public folder app.use(express.static(__dirname + "/../public")); app.get("*", function(request, response) { response.sendFile(path.resolve(__dirname, "../public", "index.html")); }); io.on(SocketConstants.on_connected, function(socket) { let client = new SocketClient(io, socket); }); var server = http.listen(80, function() { console.log("server started on port " + server.address().port); }); <file_sep>//scss require("./../SCSS/header.scss"); import React from "react"; import {Image} from "./StateLessComponents.jsx"; export default class HeaderComponent extends React.Component { render() { return ( <div className="header"> <ul> <li><Image src="/img/grouptube-logo.svg"/></li> <li><h1>GroupTube</h1></li> </ul> </div> ); } }
6283a6ddf9856357cc222c65e57cd4fcdfb68011
[ "JavaScript", "Markdown" ]
14
JavaScript
andwoo/grouptube
4329cd06a26cb30a4ce0f5ebf36b280c91e200cc
bbfc3aa2a99a71d691d19fa90e9107f63760d27a
refs/heads/master
<file_sep> # mixup training of GAN This is a demo implementation of using _mixup_ in GAN training of two 2-d toy examples as shown in the [paper](https://arxiv.org/abs/1710.09412). ## Training Simply run ``` python example_gan.py ``` You will need PyTorch and the `tqdm` package to run this script. ## Results It may take a few hours (about 5 hours on a Nvidia GTX 1070) to run all the settings in this script. After the experiments finish, you should see a set of images similar to the ones shown here in the `images` folder, which are visualizations of the target distribution and generated samples during the training process. The `samples` folder contains the `(x, y)` values of corresponding samples. ![](images/gan_results.png) <file_sep>import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import torch from torch.autograd import Variable, grad from torch.nn.functional import binary_cross_entropy_with_logits as bce from tqdm import tqdm import os if not os.path.exists('./samples'): os.makedirs('./samples') n_iterations = 20001 n_latent = 2 n_layers = 3 n_hidden = 512 bs = 128 extraD = 5 use_cuda = True for shape in ['ring', 'grid']: for n_latent in [2, 5, 10]: for mixup in [0, 0.1, 0.2, 0.5, 1]: class Perceptron(torch.nn.Module): def __init__(self, sizes, final=None): super(Perceptron, self).__init__() layers = [] for i in range(len(sizes) - 1): layers.append(torch.nn.Linear(sizes[i], sizes[i + 1])) if i != (len(sizes) - 2): layers.append(torch.nn.ReLU(inplace=True)) if final is not None: layers.append(final()) self.net = torch.nn.Sequential(*layers) def forward(self, x): return self.net(x) def plot(x, y, mixup, iteration): lims = (x.min() - .25, x.max() + .25) plt.figure(figsize=(2, 2)) plt.plot(x[:, 0], x[:, 1], '.', label='real') plt.plot(y[:, 0], y[:, 1], '.', alpha=0.25, label='fake') plt.axis('off') plt.gca().axes.get_xaxis().set_visible(False) plt.gca().axes.get_yaxis().set_visible(False) plt.xlim(*lims) plt.ylim(*lims) plt.tight_layout(0, 0, 0) plt.show() plt.savefig("images/example_z=%d_%s_%1.1f_%06d.png" % (n_latent, shape, mixup, iteration), bbox_inches='tight', pad_inches=0) plt.close() def means_circle(k=8): p = 3.14159265359 t = torch.linspace(0, 2 * p - (2 * p / k), k) m = torch.cat((torch.sin(t).view(-1, 1), torch.cos(t).view(-1, 1)), 1) return m def means_grid(k=25): m = torch.zeros(k, 2) s = int(torch.sqrt(torch.Tensor([k]))[0] / 2) cnt = 0 for i in range(- s, s + 1): for j in range(- s, s + 1): m[cnt][0] = i m[cnt][1] = j cnt += 1 return m / s def sample_real(n, shape, std=0.01): if shape == 'ring': m = means_circle() else: m = means_grid() i = torch.zeros(n).random_(m.size(0)).long() s = torch.randn(n, 2) * std + m[i] s = Variable(s, requires_grad=True) if use_cuda: s = s.cuda() return s def sample_noise(bs, d): z = torch.randn(bs, d) z = Variable(z, requires_grad=True) if use_cuda: z = z.cuda() return z netD = Perceptron([2] + [n_hidden] * n_layers + [1]) netG = Perceptron([n_latent] + [n_hidden] * n_layers + [2]) if use_cuda: netD.cuda() netG.cuda() optD = torch.optim.Adam(netD.parameters()) optG = torch.optim.Adam(netG.parameters()) p_real = sample_real(1000, shape) p_nois = sample_noise(1000, n_latent) def mixup_batch(mixup=0.0): def one_batch(): real = sample_real(bs, shape) fake = netG(sample_noise(bs, n_latent)) data = torch.cat((real, fake)) ones = Variable(torch.ones(real.size(0), 1)) zeros = Variable(torch.zeros(fake.size(0), 1)) perm = torch.randperm(data.size(0)).view(-1).long() if use_cuda: ones = ones.cuda() zeros = zeros.cuda() perm = perm.cuda() labels = torch.cat((ones, zeros)) return data[perm], labels[perm] d1, l1 = one_batch() if mixup == 0: return d1, l1 d2, l2 = one_batch() alpha = Variable(torch.randn(d1.size(0), 1).uniform_(0, mixup)) if use_cuda: alpha = alpha.cuda() d = alpha * d1 + (1. - alpha) * d2 l = alpha * l1 + (1. - alpha) * l2 return d, l for iteration in tqdm(range(n_iterations)): for extra in range(extraD): data, labels = mixup_batch(mixup) optD.zero_grad() lossD = bce(netD(data), labels) lossD.backward() optD.step() data, labels = mixup_batch(0) optG.zero_grad() lossG = - bce(netD(data), labels) lossG.backward() optG.step() if iteration in [10, 100, 1000, 10000, 20000]: plot_real = p_real.cpu().data.numpy() plot_fake = netG(p_nois).cpu().data.numpy() torch.save((plot_real, plot_fake), 'samples/example_z=%d_%s_%1.1f_%06d.pt' % (n_latent, shape, mixup, iteration)) plot(plot_real, plot_fake, mixup, iteration) <file_sep>This repo contains demo reimplementations of the CIFAR-10 training code and the GAN experiment in PyTorch based on the following paper: > <NAME>, <NAME>, <NAME> and <NAME>. _mixup: Beyond Empirical Risk Minimization._ https://arxiv.org/abs/1710.09412 ## CIFAR-10 The following table shows the median test errors of the last 10 epochs in a 200-epoch training session. (Please refer to Section 3.2 in the paper for details.) | Model | weight decay = 1e-4 | weight decay = 5e-4 | |:-------------------|---------------------:|---------------------:| | ERM | 5.53% | 5.18% | | _mixup_ | 4.24% | 4.68% | ## Generative Adversarial Networks (GAN) ![](gan/images/gan_results.png) ## Other implementations - [A Tensorflow implementation of mixup](https://github.com/ppwwyyxx/tensorpack/tree/master/examples/ResNet#cifar10-preact18-mixuppy) which reproduces our results in [tensorpack](https://github.com/ppwwyyxx/tensorpack) - [Official Facebook implementation of the CIFAR-10 experiments](https://github.com/facebookresearch/mixup-cifar10) ## Acknowledgement The CIFAR-10 reimplementation of _mixup_ is adapted from the [pytorch-cifar](https://github.com/kuangliu/pytorch-cifar) repository by [kuangliu](https://github.com/kuangliu). <file_sep># mixup training for CIFAR-10 ## Training ```bash # training with default parameters (weight_decay=1e-4 and alpha=1) python easy_mixup.py --sess my_session_1 --seed 11111 ``` The above bash script will download the CIFAR data and train the network with 1e-4 weight decay and mixup parameter alpha=1.0; alternatively, we can experiment with other weight decay and alpha value using corresponding options: ```bash # training with weight_decay=5e-4 and alpha=0 (no mixup) python easy_mixup.py --sess my_session_2 --seed 22222 --decay 5e-4 --alpha 0. ``` The other choices (network architecture, #epochs, learning rate schedule, momentum, data augmentation etc.) are hard coded but modifications are hopefully straightfoward. By default, the trained model with the best validation accuracy resides in `./checkpoint` folder, and the training log (including training loss/accuracy and validation loss/accuracy for each epoch) is saved in `./results` as a `.csv` file. ## Results **_mixup_ reduces overfitting and improves generalization.** The following plots show test error curves of a typical training session using the PreAct ResNet-18 architecture (default; you can make changes [here](https://github.com/hongyi-zhang/mixup/blob/8b43d663501b10ccb8e21d88be9d42d3bab0fd2f/easy_mixup.py#L78)). Note that compared with the ERM baseline, **_mixup_ prefers a smaller weight decay** (1e-4 vs. 5e-4), indicating its regularization effects. | Model | weight decay = 1e-4 | weight decay = 5e-4 | |:-------------------|---------------------:|---------------------:| | ERM | 5.53% | 5.18% | | _mixup_ | 4.24% | 4.68% | ![](images/cifar10_wd1em4.png) ![](images/cifar10_wd5em4.png) ## Other frameworks - [A Tensorflow implementation of mixup](https://github.com/ppwwyyxx/tensorpack/tree/master/examples/ResNet#cifar10-preact18-mixuppy) which reproduces our results in [tensorpack](https://github.com/ppwwyyxx/tensorpack) ## Acknowledgement This reimplementation is adapted from the [pytorch-cifar](https://github.com/kuangliu/pytorch-cifar) repository by [kuangliu](https://github.com/kuangliu).
5cbe9d9d4e0f10b73c18e194ec803ae572f17b9a
[ "Markdown", "Python" ]
4
Markdown
guixianjin/mixup
520b3dbe4aead196ba9b05efff2127dd74d282a0
e75ce5da00405020931820ffa2a16809382de5ea
refs/heads/develop
<file_sep>import React from 'react'; import Loader from "react-loader-spinner"; export const LoadingSpinner = () => ( <Loader className="loader" type="ThreeDots" color="#FFF" height={10} width={30} /> )<file_sep>import { Helmet, HelmetProvider } from 'react-helmet-async'; import * as yup from 'yup'; import { Formik } from 'formik'; import { Box, Button, Container, Card, TextField, Typography, } from '@material-ui/core'; import LinearProgress from '@material-ui/core/LinearProgress'; import './login.css'; export const Login = ({onSubmit, loading, onChange }) => { return ( <HelmetProvider> <Helmet> <title>Login | StoreManager</title> </Helmet> {loading ? <LinearProgress /> : null} <Card className="card-body"> <Box sx={{ backgroundColor: 'background.default', display: 'flex', flexDirection: 'column', height: '100%', justifyContent: 'center' }}> <Container maxWidth="sm"> <Formik initialValues={{ username: '', password: '' }} validationSchema={yup.object().shape({ username: yup.string().required(), password: yup.string().required() })} > {({handleChange, errors, touched, values, handleBlur}) => ( <form onSubmit={onSubmit}> <Box sx={{ pb: 1, pt: 3 }} > <Typography align="center" color="textPrimary" variant="h5" > STORE MANAGER </Typography> </Box> <TextField error={Boolean(touched.username && errors.username)} fullWidth helperText={touched.username && errors.username} label="Username" margin="normal" name="username" type="text" value={values.username} onBlur={handleBlur} onChange={handleChange} variant="outlined" /> <TextField error={Boolean(touched.password && errors.password)} fullWidth helperText={touched.password && errors.password} label="Password" margin="normal" name="password" type="password" value={values.password} onBlur={handleBlur} onChange={handleChange} variant="outlined" /> <Box sx={{ py: 2 }}> <Button color="primary" fullWidth size="large" type="submit" variant="contained" > LOGIN </Button> </Box> </form>)}</Formik> </Container> </Box> </Card> </HelmetProvider> ); }; export default Login; <file_sep>import React from 'react'; import { BrowserRouter, Route, Routes } from 'react-router-dom'; import { LoginContainer } from './containers/Login'; export const App = () => ( <BrowserRouter> <Routes> <Route path="/" element={<LoginContainer />} /> </Routes> </BrowserRouter> ); <file_sep>### StoreManager-FrontEnd-React Store Manager is a web application that helps store owners manage sales and product inventory records. This application is meant for use in a single store. ### Features - Admin can add a product - Admin or store attendant can get all products - Admin or store attendant can get a specific product. - Store attendant can add a sale order. - Admin can get all sale order details. - Getting started with the app ### Technologies used to build the application - [ReactJS](https://reactjs.org) - [Webpack](https://webpack.js.org/) - [Material-UI](https://material-ui.com/) - [Apollo Client](https://www.apollographql.com/docs/react/api/core/ApolloClient/) ### Getting Started - Install dependencies using yarn install - Run locally using `yarn dev` - To run tests `yarn test`
23574e4a9b9de2bb37463c57701a07569d7f2a9e
[ "JavaScript", "Markdown" ]
4
JavaScript
mariamiah/Store-Manager-Apollo-Client
83880cfafbed66c92988c31c9b01f5cb119ccabc
2543a668830f6ac9eecb14816588fb9f2f32efd2
refs/heads/master
<repo_name>chenlianggit/python<file_sep>/game.py me.spawns ['Spawn1'].spawnCreep(WORK,CARRY,MOVE],'Harvester1'); <file_sep>/script.py module.exports.loop = function () { var creep = Game.creeps['Harvester1']; var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0]); } } module.exports.loop = function () { var creep = Game.creeps['Harvester1']; if(creep.carry.energy < creep.carryCapacity) { var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0]); } } else { if( creep.transfer(Game.spawns['Spawn1'], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE ) { creep.moveTo(Game.spawns['Spawn1']); } } }
39bd16ebf8adabaa262eea622dbc91e00041d72c
[ "Python" ]
2
Python
chenlianggit/python
8ec7ebbe00b8e8d2b3e61e3db023c51ccd3da147
9b37999a6d09c2027bea9e19ffb38f1dd89d39a8
refs/heads/master
<file_sep>package com.walmart.principal; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class ReadMsg { public void getLastMsg(WebDriver driver) { List<WebElement> allBubbleConversation = driver.findElements(By.className("FTBzM")); int index = allBubbleConversation.size() - 1; WebElement containerMsg = allBubbleConversation.get(index); WebElement child=containerMsg.findElement(By.className("_12pGw")); WebElement spanMsg = child.findElement(By.tagName("span")); System.out.println(spanMsg.getText()); } }
b592f921a45ac4380f0d95e1eb48c007299eeffe
[ "Java" ]
1
Java
laloneferrero/templateBotWhatsapp
27d2759d0524f84bfa95c1bf484c22d996298ec1
cdca58052e2cba21613d499a19897fdf8171075e
refs/heads/master
<repo_name>for-mao/inspect-proxies<file_sep>/run/add_root_path.py from sys import path from os.path import dirname from os.path import abspath root_path = dirname(dirname(abspath(__file__))) path.append(root_path)<file_sep>/inspect_proxies/output.py from queue import Queue from typing import Callable from inspect_proxies.utils.function import output_format from inspect_proxies.utils.function import output_position_console class Output(object): def __init__( self, data: Queue, _format: Callable=output_format, position: Callable=output_position_console, **kwargs ): self.data = data self.format = _format self.position = position self.kwargs = kwargs def output(self): while not self.data.empty(): self.position(self.format(self.data.get()), **self.kwargs) <file_sep>/tests/test_storage.py import unittest from unittest import TestCase from inspect_proxies.storage import Storage def generate_storage(): yield {'scheme': 'https', 'ip': '127.0.0.1', 'port': 8899, 'username': 'hello', 'password': '<PASSWORD>'} class StorageCase(TestCase): def setUp(self): self.storage = Storage(generate_storage=generate_storage) self.expected = {'https': 'https://hello:world@127.0.0.1:8899'} def tearDown(self): pass def test_storage(self): for i in self.storage.get_proxies(): self.assertDictEqual(i, self.expected) if __name__ == '__main__': unittest.main() <file_sep>/inspect_proxies/utils/__init__.py from collections import namedtuple from pprint import PrettyPrinter pp = PrettyPrinter(indent=4) InspectResult = namedtuple('InspectResult', ['url', 'proxy', 'response', 'error']) <file_sep>/inspect_proxies/inspector.py from queue import Queue from threading import Thread from threading import current_thread from typing import Tuple from requests.api import request from inspect_proxies.output import Output from inspect_proxies.utils import InspectResult from inspect_proxies.utils.logs import create_logger from inspect_proxies.utils.logs import root_logger logger = create_logger(__name__) class ThreadProxyInspector(object): def __init__(self, storage, **kwargs): """ :param storage: :param kwargs: """ root_logger.setLevel(kwargs.get('log_level', root_logger.level)) self.proxies = Queue() self.result = Queue() self.__threads = None self.thread_number = kwargs.get('thread_number', 20) self.url = kwargs.get('url', 'www.httpbin.org/ip') self.requests_params = kwargs.get('requests_params', {}) self.storage = storage self.storage_params = kwargs.get('storage_params') self.output_c = kwargs.get('output', Output) self.output_params = kwargs.get('output_params', {}) self.output = None self.print_msg() def print_msg(self): logger.info( 'Start to inspect proxies ' 'with multiple threads[{}]'.format(self.thread_number) ) logger.info('Await inspect url>>>{}'.format(self.url)) @property def threads(self) -> [Tuple, None]: return self.__threads def run(self): self.create_threads() self.load_proxies() self.output = self.output_c(self.result, **self.output_params) logger.info('The environment initialization is complete') self.await_task_done() logger.info('output result with {}'.format(self.output_c.__name__)) self.output.output() def thread_task(self): while True: proxy = self.proxies.get() params = self.requests_params.copy() try: url = "{scheme}://{url}".format( scheme=next(iter(proxy.keys())), url=self.url ) resp = request( params.pop('method', 'get'), url, proxies=proxy, **params) except Exception as exc: res = InspectResult( response=None, proxy=proxy, error=exc, url=self.url) else: res = InspectResult( response=resp, proxy=proxy, error=None, url=self.url ) finally: logger.debug('[{name}] inspect proxy {proxy} ({result})'.format( name=current_thread().name, proxy=next(iter(proxy.values())), result=res.response or res.error )) self.result.put(res) self.proxies.task_done() def create_threads(self): logger.debug('Start to create threads') _list = [] for i in range(self.thread_number): t = Thread( target=self.thread_task, name='proxy_inspector_{}'.format(i), ) t.setDaemon(True) t.start() _list.append(t) self.__threads = tuple(_list) def load_proxies(self): """ from storage load proxy to self.proxies :return: """ logger.debug('Start to load proxies from {}'.format( self.storage.__name__)) storage = self.storage(**self.storage_params) count = 0 for proxy in storage.get_proxies(): count += 1 self.proxies.put(proxy) logger.info('Successfully load {} proxies'.format(count)) def await_task_done(self): logger.info('Wait for all inspection tasks to be completed.') self.proxies.join() <file_sep>/run/run_check_search_engine_proxy.py import add_root_path from random import choice from inspect_proxies.inspector import ThreadProxyInspector from inspect_proxies.output import Output from inspect_proxies.storage import Storage from inspect_proxies.utils.function import create_request_proxy from inspect_proxies.utils.function import mongodb_storage from inspect_proxies.utils.function import output_format_view_proxy from inspect_proxies.utils.function import output_format_filter_invalid_proxy from inspect_proxies.utils.function import output_position_mongodb from private_settings import MONGO_URI from private_settings import URLS from logging import DEBUG from settings import HEADERS from settings import USER_AGENTS from pymongo import MongoClient client = MongoClient(MONGO_URI) params = { 'log_level': DEBUG, 'thread_number': 50, # default 20 # 'url': choice(URLS), # default https://httpbin.org # 'url': 'https://www.linkedin.com', 'requests_params': { 'method': 'get', # default get 'timeout': 20, # no default 'allow_redirects': False, # default True 'headers': HEADERS.update({'User-Agent': choice(USER_AGENTS)}), }, 'output': Output, # class default Output 'output_params': { # '_format': output_format_view_proxy, # default dict '_format': output_format_filter_invalid_proxy, # default dict 'position': output_position_mongodb, # default console 'coll': client['search-engine']['service_shadowsocks_new'] }, # your output instantiation required params 'storage': Storage, # required 'storage_params': { 'parse': create_request_proxy, # required 'generate_storage': mongodb_storage, # required 'mongo_uri': MONGO_URI, # callable of generate_storage required param 'db': 'vps_management', # 'coll': 'tencent_shadowsocks_service' 'coll': 'service_new_email_shadowsocks', # '_filter': {'scheme': 'https', # 'account_username': {'$exists': 1}} } } if __name__ == '__main__': inspector = ThreadProxyInspector(**params) inspector.run() client['search-engine']['service_shadowsocks'].rename('service_shadowsocks_dup') client['search-engine']['service_shadowsocks_new'].rename('service_shadowsocks') client['search-engine']['service_shadowsocks_dup'].drop() <file_sep>/tests/test_output.py import unittest from unittest import TestCase from queue import Queue import requests from inspect_proxies.output import Output from inspect_proxies.utils import InspectResult class OutPut(TestCase): def setUp(self): data = Queue() self.result = InspectResult( url='http://httpbin.org/ip', proxy={'http': 'http://127.0.0.1:8899'}, response=requests.get('http://httpbin.org/ip'), error=None) self.position_data = [] data.put(self.result) self.output = Output( data, position=lambda x: self.position_data.append({'position': True, 'data': x}) ) def tearDown(self): pass def test_start_status(self): self.assertEqual(self.output.data.empty(), False) def test_output(self): self.output.output() for i in self.position_data: self.assertEqual(i['position'], True) self.assertEqual( i['data'], self.output.format(self.result, **self.output.kwargs) ) self.assertEqual(self.output.data.empty(), True) if __name__ == '__main__': unittest.main() <file_sep>/run/settings_demo.py MONGO_URI = 'mongodb://username:password@url_or_ip:port' URLS = [ 'await inspect urls' ] <file_sep>/tests/test_utils.py import unittest from json.decoder import JSONDecodeError from unittest import TestCase import requests from inspect_proxies.utils import InspectResult from inspect_proxies.utils import function as func class TestParseRequestsProxy(TestCase): def setUp(self): self.func = func.parse_requests_proxy def tearDown(self): pass def test_require_auth(self): proxy = {'https': 'https://hello:world@127.0.0.1:8899'} expected = {'scheme': 'https', 'ip': '127.0.0.1', 'port': 8899, 'username': 'hello', 'password': '<PASSWORD>'} self.assertEqual(self.func(proxy), expected) def test_no_auth(self): proxy = {'http': 'http://127.0.0.1:18899'} expected = {'scheme': 'http', 'ip': '127.0.0.1', 'port': 18899, 'username': None, 'password': <PASSWORD>} self.assertEqual(self.func(proxy), expected) def test_empty_input(self): proxy = {} expected = None self.assertEqual(self.func(proxy), expected) def test_error_input(self): error_proxies = [None, 'None', [None], {None}] for i in error_proxies: with self.assertRaises(AttributeError) as exc: self.func(i) class TestCreateRequestsProxy(TestCase): def setUp(self): self.func = func.create_request_proxy def tearDown(self): pass def test_require_auth(self): proxy = {'scheme': 'https', 'ip': '127.0.0.1', 'port': 8899, 'username': 'hello', 'password': '<PASSWORD>'} expected = {'https': 'https://hello:world@127.0.0.1:8899'} self.assertEqual(self.func(proxy), expected) proxy = "{'scheme': 'https', 'ip': '127.0.0.1', 'port': 8899, " \ "'username': 'hello', 'password': '<PASSWORD>'}," self.assertEqual(self.func(proxy), expected) def test_no_auth(self): proxy = {'scheme': 'http', 'ip': '127.0.0.1', 'port': 18899, 'username': None, 'password': <PASSWORD>} expected = {'http': 'http://127.0.0.1:18899'} self.assertEqual(self.func(proxy), expected) proxy = "{'scheme': \"http\", 'ip': '127.0.0.1', " \ "'port': 18899, 'username': null, 'password': <PASSWORD>}" self.assertEqual(self.func(proxy), expected) def test_empty_input(self): proxy = {} expected = {} self.assertEqual(self.func(proxy), expected) def test_error_input(self): error_proxies = [None, 'None', [None], {None}] for i in error_proxies: with self.assertRaises((TypeError, JSONDecodeError)) as exc: self.func(i) class TestOutputFormat(TestCase): def setUp(self): self.func = func.output_format self.data = InspectResult( url='http://httpbin.org/ip', proxy={'http': 'http://127.0.0.1:8899'}, response=requests.get('http://httpbin.org/ip'), error=None ) def tearDown(self): pass def testResultType(self): self.assertIsInstance(self.func(self.data), dict) def testResultKeys(self): result = self.func(self.data) for i in ['proxy', 'url', 'spend_time', 'status', 'exception']: self.assertIn(i, result.keys()) def testResultValue(self): result = self.func(self.data) self.assertEqual('{"http": "http://127.0.0.1:8899"}', result['proxy']) self.assertEqual('http://httpbin.org/ip', result['url']) self.assertIsInstance(result['spend_time'], float) self.assertEqual(200, result['status']) self.assertEqual(None, result['exception']) class TestOutputFormatViewProxy(TestCase): def setUp(self): self.func = func.output_format_view_proxy self.data = InspectResult( url='http://httpbin.org/ip', proxy={'http': 'http://127.0.0.1:8899'}, response=requests.get('http://httpbin.org/ip'), error=None ) def tearDown(self): pass def testResult(self): result = self.func(self.data) self.assertIsInstance(result, dict) for i in ['url', 'spend_time', 'status', 'exception', 'scheme', 'username', 'password', 'ip', 'port']: self.assertIn(i, result.keys()) self.assertNotIn('proxy', result.keys()) spend_time = result.pop('spend_time') self.assertIsInstance(spend_time, float) self.assertDictEqual(result, { 'url': 'http://httpbin.org/ip', 'status': 200, 'exception': 'None', 'scheme': 'http', 'username': None, 'password': <PASSWORD>, 'ip': '127.0.0.1', 'port': 8899 }) if __name__ == '__main__': unittest.main() <file_sep>/inspect_proxies/storage.py from typing import Callable from typing import Generator from inspect_proxies.utils.function import create_request_proxy from inspect_proxies.utils.function import file_storage class Storage(object): def __init__(self, parse: Callable=create_request_proxy, generate_storage: Callable=file_storage, **kwargs ): self.parse = parse self.storage = generate_storage(**kwargs) def get_proxies(self) -> Generator: """ :return: {'scheme':'scheme://domain or ip:port',} """ for doc in self.storage: yield self.parse(doc) <file_sep>/inspect_proxies/utils/function.py from json import dumps from json import loads from typing import Dict from typing import Generator from urllib.parse import urlparse from pymongo.cursor import Cursor from pymongo import MongoClient from pymongo.collection import Collection from inspect_proxies.utils import InspectResult from inspect_proxies.utils import pp def total_numbers(func): numbers = {'invalid': 0, 'valid': 0} def wrapper(doc, *args, **kwargs): if doc.get('exception') and doc.get('exception') != 'None': numbers['invalid'] += 1 else: numbers['valid'] += 1 res = func(doc, *args, **kwargs) print(numbers) return res return wrapper def collect_invalid_ips(func): import datetime from os.path import abspath from os.path import dirname path = dirname(dirname(dirname(abspath(__file__)))) with open('{}/invalid_ips.txt'.format(path), 'a') as f: f.write('\n\n\n{} invalid proxy\n'.format(datetime.datetime.today())) def wrapper(doc, *args, **kwargs): if doc.error and doc.error != 'None': proxy = parse_requests_proxy(doc.proxy) with open('{}/invalid_ips.txt'.format(path), 'a') as f: f.write('ip:{} port:{}\n'.format(proxy['ip'], proxy['port'])) res = func(doc, *args, **kwargs) return res return wrapper def _parse_auth_uri(uri: str) -> Dict: if '@' in uri: split_res = uri.split('@') user, pwd = split_res[0].split(':') host, port = split_res[1].split(':') else: user, pwd = (None, None) host, port = uri.split(':') return { 'username': user, 'password': pwd, 'ip': host, 'port': int(port) } def parse_requests_proxy(proxy: Dict) -> Dict: """ :param proxy: {'http': 'http://...'} :return: Dict: keys include username, password, ip, port """ for scheme, p in proxy.items(): res = {'scheme': scheme} auth = urlparse(p).netloc res.update(_parse_auth_uri(auth)) return res def output_format_view_proxy(doc: InspectResult) -> Dict: """ Handle result of output_format view proxy document :param doc: :return: """ res = output_format(doc) del res['proxy'] res['exception'] = str(res['exception']) res.update(parse_requests_proxy(doc.proxy)) return res @collect_invalid_ips def output_format_filter_invalid_proxy(doc: InspectResult) -> Dict: """ Handle result of output_format view proxy document :param doc: :return: """ res = output_format(doc) if res['exception'] is None and res['status'] == 200: del res['proxy'] del res['exception'] res.update(parse_requests_proxy(doc.proxy)) return res else: return dict() def output_format(doc: InspectResult) -> Dict: """ from once inspect result extract message :param doc: result of inspect proxy :return: """ resp = doc.response if resp: seconds = resp.elapsed.total_seconds() status = resp.status_code else: seconds = None status = None return { 'proxy': dumps(doc.proxy), 'url': doc.url, 'spend_time': seconds, 'status': status, 'exception': type(doc.error) if doc.error is not None else None } @total_numbers def output_position_console(doc: Dict): pp.pprint(doc) def output_position_mongodb(doc: Dict, coll: Collection): if doc: coll.insert_one(doc) def create_request_proxy(line: [str, Dict]) -> Dict: """ :param line: dict or json {'ip': '', 'port': '', 'username': '', 'password':'', 'scheme': ''} :return: dict: {'scheme': 'proxy'} """ if type(line) is str: line = loads(line.strip(',').replace("'", '"')) if type(line) is not dict: raise TypeError( "excepted type of line is dict, is not {}".format(type(line)) ) if not line: return {} if line.get('username'): return { line['scheme']: '{scheme}://{username}:{password}@' '{ip}:{port}'.format( scheme=line['scheme'], username=line['username'], password=line['password'], ip=line.get('ip') or line['domain'], port=line.get('port', 80 if line['scheme'] == 'http' else 443) ) } else: return { line['scheme']: '{scheme}://{ip}:{port}'.format( scheme=line['scheme'], ip=line.get('ip') or line['domain'], port=line.get('port', 80 if line['scheme'] == 'http' else 443) ) } def file_storage(path: str) -> Generator: """ :param path: file path :return: line """ with open(path) as f: for _ in f: line = _.strip() if line: yield line def mongodb_storage( mongo_uri: str, db: str, coll: str, _filter: Dict={} ) -> Cursor: client = MongoClient(mongo_uri) coll = client[db][coll] return coll.find(_filter, no_cursor_timeout=False) if __name__ == '__main__': storage = file_storage('../../tests/docs/proxies_demo.txt') for i in storage: print(create_request_proxy(i)) <file_sep>/README.md # Description inspect proxy with multi threads # Start to project ```shell $ cd run $ mv settings_demo.py private_settings.py # config private_settings $ python run_check_proxy.py ``` <file_sep>/run/settings.py # user-agent USER_AGENTS = [ ('Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/57.0.2987.110 ' 'Safari/537.36'), # chrome ('Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/60.0.3112.113 ' 'Safari/537.36'), # chrome ('Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/61.0.3163.91 ' 'Safari/537.36'), # chrome ('Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) ' 'Gecko/20100101 ' 'Firefox/55.0'), # firefox ] HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'en-US, en; q=0.8', 'Cache-Control': 'max-age=0', } <file_sep>/inspect_proxies/utils/logs.py import logging from logging import Logger formatter = logging.Formatter( '%(asctime)s [%(name)s] %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S' ) root_logger = logging.getLogger('inspect-proxies') ch = logging.StreamHandler() ch.setFormatter(formatter) ch.setLevel(logging.DEBUG) root_logger.addHandler(ch) root_logger.setLevel(logging.INFO) def create_logger(logger_name: str) -> Logger: logger = root_logger.getChild(logger_name) return logger
c1805a977bdb0fd1627f4e1ac3c2e6f5eae32445
[ "Markdown", "Python" ]
14
Python
for-mao/inspect-proxies
5db9b862d16d5f5f618bcad57b67d82adc7c2427
ccb729bbe69d9cd39fc70934f08d13139894c8b7
refs/heads/master
<file_sep>/* SAKURA Internet IoT Communication Module Library for mbed * * The MIT License (MIT) * * Copyright (c) SAKURA Internet Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _SAKURAIO_H_ #define _SAKURAIO_H_ #include "mbed.h" #include <SakuraIO/commands.h> class SakuraIO { protected: virtual void begin() {} virtual void end() {} virtual void sendByte(uint8_t data) {} //virtual void finishSending(){} virtual uint8_t startReceive(uint8_t length) { return length; }; virtual uint8_t receiveByte() { return 0x00; } virtual uint8_t receiveByte(bool stop) { return 0x00; } //virtual void finishReceiving(){} uint8_t executeCommand(uint8_t cmd,uint8_t requestLength, uint8_t *request, uint8_t *responseLength, uint8_t *response); uint8_t enqueueTxRaw(uint8_t ch, uint8_t type, uint8_t length, uint8_t *data, uint64_t offset); public: uint8_t getConnectionStatus(); uint8_t getSignalQuarity(); // Deprecated uint8_t getSignalQuality(); uint64_t getUnixtime(); uint8_t echoback(uint8_t length, uint8_t *data, uint8_t *response); uint16_t getADC(uint8_t channel); // Deprecated uint8_t enqueueTx(uint8_t ch, int32_t value, uint64_t offset); uint8_t enqueueTx(uint8_t ch, uint32_t value, uint64_t offset); uint8_t enqueueTx(uint8_t ch, int64_t value, uint64_t offset); uint8_t enqueueTx(uint8_t ch, uint64_t value, uint64_t offset); uint8_t enqueueTx(uint8_t ch, float value, uint64_t offset); uint8_t enqueueTx(uint8_t ch, double value, uint64_t offset); uint8_t enqueueTx(uint8_t ch, uint8_t value[8], uint64_t offset); uint8_t enqueueTx(uint8_t ch, int32_t value); uint8_t enqueueTx(uint8_t ch, uint32_t value); uint8_t enqueueTx(uint8_t ch, int64_t value); uint8_t enqueueTx(uint8_t ch, uint64_t value); uint8_t enqueueTx(uint8_t ch, float value); uint8_t enqueueTx(uint8_t ch, double value); uint8_t enqueueTx(uint8_t ch, uint8_t value[8]); uint8_t sendImmediatelyRaw(uint8_t ch, uint8_t type, uint8_t length, uint8_t *data, uint64_t offset); uint8_t sendImmediately(uint8_t ch, int32_t value, uint64_t offset); uint8_t sendImmediately(uint8_t ch, uint32_t value, uint64_t offset); uint8_t sendImmediately(uint8_t ch, int64_t value, uint64_t offset); uint8_t sendImmediately(uint8_t ch, uint64_t value, uint64_t offset); uint8_t sendImmediately(uint8_t ch, float value, uint64_t offset); uint8_t sendImmediately(uint8_t ch, double value, uint64_t offset); uint8_t sendImmediately(uint8_t ch, uint8_t value[8], uint64_t offset); uint8_t sendImmediately(uint8_t ch, int32_t value); uint8_t sendImmediately(uint8_t ch, uint32_t value); uint8_t sendImmediately(uint8_t ch, int64_t value); uint8_t sendImmediately(uint8_t ch, uint64_t value); uint8_t sendImmediately(uint8_t ch, float value); uint8_t sendImmediately(uint8_t ch, double value); uint8_t sendImmediately(uint8_t ch, uint8_t value[8]); uint8_t getTxQueueLength(uint8_t *available, uint8_t *queued); uint8_t clearTx(); uint8_t getTxStatus(uint8_t *queue, uint8_t *immediate); uint8_t send(); uint8_t dequeueRx(uint8_t *ch, uint8_t *type, uint8_t *value, int64_t *offset); uint8_t peekRx(uint8_t *ch, uint8_t *type, uint8_t *value, int64_t *offset); uint8_t getRxQueueLength(uint8_t *available, uint8_t *queued); uint8_t clearRx(); uint8_t startFileDownload(uint16_t fileId); uint8_t cancelFileDownload(); uint8_t getFileMetaData(uint8_t *status, uint32_t *totalSize, uint64_t *timestamp, uint32_t *crc); uint8_t getFileDownloadStatus(uint8_t *status, uint32_t *currentSize); uint8_t getFileData(uint8_t *size, uint8_t *data); uint16_t getProductID(); uint8_t getUniqueID(char *data); uint8_t getFirmwareVersion(char *data); uint8_t unlock(); uint8_t updateFirmware(); uint8_t getFirmwareUpdateStatus(); uint8_t reset(); }; class SakuraIO_SPI : public SakuraIO { protected: SPI &spi; DigitalOut &cs; virtual void begin(); virtual void end(); virtual void sendByte(uint8_t data); virtual uint8_t receiveByte(bool stop); virtual uint8_t receiveByte(); public: SakuraIO_SPI(SPI &_spi, DigitalOut &_cs); }; class SakuraIO_I2C : public SakuraIO { protected: I2C *i2c_p; I2C &i2c; int _length; virtual void begin(); virtual void end(); virtual void sendByte(uint8_t data); virtual uint8_t startReceive(uint8_t length); virtual uint8_t receiveByte(bool stop); virtual uint8_t receiveByte(); uint8_t mode; public: SakuraIO_I2C (I2C &_i2c); SakuraIO_I2C (PinName sda, PinName scl); }; #endif // _SAKURAIO_H_ <file_sep>/* SAKURA Internet IoT Communication Module Library for mbed * * The MIT License (MIT) * * Copyright (c) SAKURA Internet Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __SAKURA_IO_DEBUG_H__ #define __SAKURA_IO_DEBUG_H__ #if defined(SAKURA_DEBUG) #define dbg(...) printf(__VA_ARGS__) #define dbgln(...) DEBUG_PRINTF_LN(__VA_ARGS__, "\r\n") #define DEBUG_PRINTF_LN(type, fmt, ...) printf(fmt "%s", __VA_ARGS__) #else #define dbg(...) #define dbgln(...) #endif #endif //__SAKURA_IO_DEBUG_H__ <file_sep># Maintenance ## Sync with github.com ### Setup hg-git ```bash pip install mercurial hg-git ``` #### ~/.hgrc ``` [extensions] hggit = ``` ### mbed.org to github.com ```bash hg clone https://developer.mbed.org/teams/SAKURA-Internet/code/SakuraIO/ SakuraIOmbed-sync cd SakuraIOmbed-sync hg push git+ssh://git@github.com:sakuraio/SakuraIOmbed.git ``` ### github.com to mbed.org ```bash hg pull git+ssh://git@github.com:sakuraio/SakuraIOmbed.git hg outgoing https://developer.mbed.org/teams/SAKURA-Internet/code/SakuraIO/ # check diff hg push https://developer.mbed.org/teams/SAKURA-Internet/code/SakuraIO/ ``` <file_sep>/* SAKURA Internet IoT Communication Module Library for mbed * * The MIT License (MIT) * * Copyright (c) SAKURA Internet Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Common #define CMD_GET_CONNECTION_STATUS 0x01 #define CMD_GET_SIGNAL_QUALITY 0x02 #define CMD_GET_DATETIME 0x03 #define CMD_ECHO_BACK 0x0f // IO #define CMD_READ_ADC 0x10 // Transmit #define CMD_TX_ENQUEUE 0x20 #define CMD_TX_SENDIMMED 0x21 #define CMD_TX_LENGTH 0x22 #define CMD_TX_CLEAR 0x23 #define CMD_TX_SEND 0x24 #define CMD_TX_STAT 0x25 // Receive #define CMD_RX_DEQUEUE 0x30 #define CMD_RX_PEEK 0x31 #define CMD_RX_LENGTH 0x32 #define CMD_RX_CLEAR 0x33 // File Download #define CMD_START_FILE_DOWNLOAD 0x40 #define CMD_GET_FILE_METADATA 0x41 #define CMD_GET_FILE_DOWNLOAD_STATUS 0x42 #define CMD_CANCEL_FILE_DOWNLOAD 0x43 #define CMD_GET_FILE_DATA 0x44 // Operation #define CMD_GET_PRODUCT_ID 0xA0 #define CMD_GET_UNIQUE_ID 0xA1 #define CMD_GET_FIRMWARE_VERSION 0xA2 #define CMD_UNLOCK 0xA8 #define CMD_UPDATE_FIRMWARE 0xA9 #define CMD_GET_UPDATE_FIRMWARE_STATUS 0xAA #define CMD_SOFTWARE_RESET 0xAF // Response #define CMD_ERROR_NONE 0x01 #define CMD_ERROR_PARITY 0x02 #define CMD_ERROR_MISSING 0x03 #define CMD_ERROR_INVALID_SYNTAX 0x04 #define CMD_ERROR_RUNTIME 0x05 #define CMD_ERROR_LOCKED 0x06 #define CMD_ERROR_BUSY 0x07 // FileStatus #define FILE_STATUS_ERROR 0x01 #define FILE_STATUS_INVALID_REQUEST 0x02 #define FILE_STATUS_NOTFOUND 0x81 #define FILE_STATUS_SERVER_ERROR 0x82 #define FILE_STATUS_INVALID_DATA 0x83 <file_sep>/* SAKURA Internet IoT Communication Module Library for mbed * * The MIT License (MIT) * * Copyright (c) SAKURA Internet Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "mbed.h" #include "SakuraIO.h" #include "debug.h" #define SAKURAIO_SLAVE_ADDR 0x4F #define MODE_IDLE 0x00 #define MODE_WRITE 0x01 #define MODE_READ 0x02 void SakuraIO_I2C::begin() { mode = MODE_IDLE; } void SakuraIO_I2C::end() { switch (mode) { case MODE_WRITE: i2c.stop(); break; case MODE_READ: while (_length > 0) { _length--; i2c.read(_length > 0 ? 1 : 0); } i2c.stop(); break; } mode = MODE_IDLE; } void SakuraIO_I2C::sendByte(uint8_t data) { if (mode != MODE_WRITE) { dbg("beginTr\r\n"); i2c.start(); i2c.write(SAKURAIO_SLAVE_ADDR << 1); mode = MODE_WRITE; } dbg("Write=%02x\r\n", data); i2c.write(data); } uint8_t SakuraIO_I2C::startReceive(uint8_t length) { if (mode != MODE_IDLE) { dbg("endTransmission\r\n"); i2c.stop(); } dbg("requestForm=%d\r\n", length); _length = length; wait_ms(10); i2c.start(); i2c.write(SAKURAIO_SLAVE_ADDR << 1 | 1); mode = MODE_READ; return 0; } uint8_t SakuraIO_I2C::receiveByte() { return receiveByte(false); } uint8_t SakuraIO_I2C::receiveByte(bool stop) { uint8_t ret = 0; if (_length > 0) { _length--; ret = i2c.read(_length > 0 ? 1 : 0); } if (stop) { end(); } dbg("Read=%d\r\n", ret); return ret; } SakuraIO_I2C::SakuraIO_I2C(I2C &_i2c) : i2c(_i2c) { mode = MODE_IDLE; } SakuraIO_I2C::SakuraIO_I2C(PinName sda, PinName scl) : i2c_p(new I2C(sda, scl)), i2c(*i2c_p) { mode = MODE_IDLE; } <file_sep>/* SAKURA Internet IoT Communication Module Library for mbed * * The MIT License (MIT) * * Copyright (c) SAKURA Internet Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "mbed.h" #include "SakuraIO.h" #include "SakuraIO/debug.h" void SakuraIO_SPI::begin(){ dbgln("CS=0"); cs = 0; } void SakuraIO_SPI::end(){ dbgln("CS=1"); cs = 1; wait_us(20); } void SakuraIO_SPI::sendByte(uint8_t data){ wait_us(20); dbg("Send="); dbgln(data); wait_us(10); spi.write(data); } uint8_t SakuraIO_SPI::receiveByte(bool stop){ return receiveByte(); } uint8_t SakuraIO_SPI::receiveByte(){ uint8_t ret; wait_us(10); ret = spi.write(0x00); dbg("Recv="); dbgln(ret); return ret; } SakuraIO_SPI::SakuraIO_SPI(SPI &_spi, DigitalOut &_cs): spi(_spi), cs(_cs){ cs = 1; }
edd4833ca68698010deecf957f639e472885cfbe
[ "Markdown", "C", "C++" ]
6
C++
sakuraio/SakuraIOmbed
66747489ed6f7bcaed5568bde943418aa8316805
62e58ec7bab6ec66eb1055696c5cf134c398cab8
refs/heads/master
<file_sep>int DTR=5; int RTS=4; bool dtr; bool rts; int baud=115200; void readback() { if (dtr != Serial.getDTR()) { dtr = Serial.getDTR(); if (dtr) digitalWrite(DTR, LOW); else digitalWrite(DTR, HIGH); } if (rts != Serial.getRTS()) { rts = Serial.getRTS(); if(rts) digitalWrite(RTS,LOW); else digitalWrite(RTS,HIGH); } } void setup() { pinMode(DTR,OUTPUT); pinMode(RTS,OUTPUT); digitalWrite(RTS, LOW); digitalWrite(DTR, HIGH); delay(100); digitalWrite(RTS, HIGH); ANSELC = 0x00; LATC = LATC & (~0x04); TRISC |= 0x04; // CNPUC = CNPUC & (~0x04); dtr = Serial.getDTR(); rts = Serial.getRTS(); if (dtr) digitalWrite(DTR, LOW); else digitalWrite(DTR,HIGH); if(rts) digitalWrite(RTS, LOW); else digitalWrite(RTS,HIGH); Serial.begin(1000000); delay(100); Serial0.begin(115200); delay(100); Serial1.begin(115200); delay(100); } void loop() { readback(); //digitalWrite(DTR, !Serial.getDTR()); //digitalWrite(RTS, !Serial.getRTS()); while(Serial.available() || Serial0.available() || Serial1.available()) { if (Serial.available()) { Serial0.write(Serial.read()); } if (Serial0.available()) { Serial.write(Serial0.read()); } if(Serial1.available()) { Serial1.write(Serial1.read()); } } if (Serial.getBaudRate() != baud) { baud = Serial.getBaudRate(); Serial0.begin(Serial.getBaudRate()); } } <file_sep># ESP32-PRO Open-source hardware ESP32 IoT board with 4MB external RAM, 4MB external flash, LiPo charger, USB-OTG, external crypto engine option. The board uses PIC32 as USB-serial converter. Product page: https://www.olimex.com/Products/IoT/ESP32/ESP32-PRO/open-source-hardware <file_sep>update=30.07.2018 (пн) 10:23:47 EEST version=1 last_client=kicad [cvpcb] version=1 NetIExt=net [general] version=1 [eeschema] version=1 LibDir= [pcbnew] version=1 PageLayoutDescrFile= LastNetListRead=ESP32-PRO_Rev_B1.net CopperLayerCount=2 BoardThickness=1.6 AllowMicroVias=0 AllowBlindVias=0 RequireCourtyardDefinitions=0 ProhibitOverlappingCourtyards=1 MinTrackWidth=0.1524 MinViaDiameter=0.4 MinViaDrill=0.3 MinMicroViaDiameter=0 MinMicroViaDrill=0 MinHoleToHole=0.25 TrackWidth1=0.1524 TrackWidth2=0.1524 TrackWidth3=0.2 TrackWidth4=0.381 TrackWidth5=0.508 TrackWidth6=0.762 TrackWidth7=1.016 TrackWidth8=1.27 TrackWidth9=2.54 ViaDiameter1=0.5 ViaDrill1=0.3 ViaDiameter2=0.5 ViaDrill2=0.3 ViaDiameter3=0.9 ViaDrill3=0.6 dPairWidth1=0.2032 dPairGap1=0.25 dPairViaGap1=0.25 SilkLineWidth=0.15 SilkTextSizeV=1 SilkTextSizeH=1 SilkTextSizeThickness=0.15 SilkTextItalic=0 SilkTextUpright=1 CopperLineWidth=0.508 CopperTextSizeV=1.5 CopperTextSizeH=1.5 CopperTextThickness=0.3 CopperTextItalic=0 CopperTextUpright=1 EdgesAndCourtyardsLineWidth=0.254 OthersLineWidth=0.15 OthersTextSizeV=1 OthersTextSizeH=1 OthersTextSizeThickness=0.15 OthersTextItalic=0 OthersTextUpright=1 SolderMaskClearance=0.0508 SolderMaskMinWidth=0 SolderPasteClearance=0 SolderPasteRatio=0 [pcbnew/Layer.F.Cu] Name=F.Cu Type=2 [pcbnew/Layer.B.Cu] Name=B.Cu Type=2 <file_sep>This example works with Espressif package 1.0.0v. With 1.0.1v compiling fails. <file_sep>#include <WiFi.h> #include <FS.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> enum STATE_MACHINE { STATE_INIT, STATE_CLIENT, STATE_SERVER } SM_STATE; uint8_t SM_TASKS; const char *ssid = "YourSSID"; const char *password = "<PASSWORD>"; AsyncWebServer http_server(80); // We need http server for manual trying to connect with ip. WiFiServer my_server(1111); WiFiClient my_client; WiFiClient remote_client; String header; String RX_BUFFER; String TX_BUFFER; String Rip; //remote ip in string format IPAddress RemoteIP = IPAddress(0,0,0,0); //remote ip address in IPAddress type; void wait_client() { WiFiClient this_client; RemoteIP = IPAddress(0,0,0,0); // Wait for setup via WEB or TCP connection Serial.println("\n=========== Waiting for income Connection ===========\n"); while(RemoteIP == IPAddress(0,0,0,0)) { this_client = my_server.available(); if(this_client) { if(this_client.connected()) { Serial.println("\n=========== Someone is trying to connect ===========\n"); Serial.print("IP address: "); Serial.println(this_client.remoteIP()); if((this_client.remoteIP() == RemoteIP) || (RemoteIP == IPAddress(0,0,0,0)) ) { Serial.println("*** Connection Accepted ***\n\n"); remote_client = this_client; SM_STATE = STATE_SERVER; break; } else { Serial.println("*** Unauthorized client. Connection closed!!! ***"); this_client.stop(); } } } } } void client_state() { uint8_t tx_buffer, rx_buffer; Serial.flush(); my_client.flush(); Serial.print("\n\n=========== Trying to connect to \""); Serial.print(RemoteIP); Serial.println("\"===========\n\n"); if(my_client.connect(RemoteIP, 1111)) { Serial.println("**** CONNECTED ****"); while(my_client.connected()) { if(Serial.available() || my_client.available()) { if(Serial.available()) { my_client.write(Serial.read()); } if(my_client.available()) { Serial.write(my_client.read()); } } } Serial.println("\n\n=========== Connection was closed by Server ===========\n\n"); SM_STATE = STATE_INIT; } } void server_state() { char rx_buffer=0, tx_buffer=0; Serial.flush(); my_client.flush(); while(remote_client.connected()) { if(Serial.available() || remote_client.available()) { if(Serial.available()) { remote_client.write(Serial.read()); } if(remote_client.available()) { Serial.write(remote_client.read()); } } } Serial.println("\n\n=========== Connection was closed by Client ===========\n\n"); SM_STATE = STATE_INIT; } void setup() { SM_STATE = STATE_INIT; Serial.begin(2000000); while(Serial.read() < 0); Serial.print("Connecting to: "); Serial.println(ssid); WiFi.begin(ssid, password); while(WiFi.status() != WL_CONNECTED) delay(500); Serial.print("\nIP: "); Serial.println(WiFi.localIP()); my_server.begin(); http_server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ AsyncResponseStream *response = request->beginResponseStream("text/html"); response->addHeader("Server","ESP Async Web Server"); response->printf("<!DOCTYPE html><html><head><title>ESP32 Connection Setup </title></head>"); response->print("<body>"); //response->print("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"></script><style>"); response->print("<h2>ESP32 Connection Setup</h2>"); response->print("<p>Enter the IP in the textbox and click SAVE button </br> </p>"); response->print("<fieldset>"); response->print("<legend>ESP32 UART: setup</legend>"); response->print("<form method=\"post\">"); response->printf("Destination IP:<br>"); response->printf("<input type=\"text\" name=\"IP\" value=\"Enter destination IP\" style=\"width: 200px\">"); response->print("<br><br>"); response->printf("<input type=\"submit\" value=\"SAVE\">"); response->printf(" </fieldset>"); response->printf("</form>"); response->printf("</body>"); response->printf(" </html>"); //send the response last request->send(response); }); http_server.on("/", HTTP_POST, [](AsyncWebServerRequest *request){ Serial.print("HOST: "); Serial.println(request->host()); RemoteIP.fromString(request->arg("IP")); Serial.print("***** RemoteIP TO: "); Serial.print(RemoteIP); Serial.println(" *****"); AsyncResponseStream *response = request->beginResponseStream("text/html"); AsyncClient *client = request->client(); //Serial.print(client->remoteIP()); response->addHeader("Server","ESP Async Web Server"); response->printf("<!DOCTYPE html><html><head><title>ESP32 Connection Setup </title></head>"); response->print("<body>"); //response->print("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"></script><style>"); response->print("<h2>ESP32 Connection Setup</h2>"); response->print("<p>Enter the IP in the textbox and click SAVE button </br> </p>"); response->print("<fieldset>"); response->print("<legend>ESP32 UART: setup</legend>"); response->print("<form method=\"post\">"); response->printf("Destination IP:<br>"); response->printf("<input type=\"text\" name=\"IP\" value=\"\" style=\"width: 200px\">"); response->print("<br><br>"); response->printf("<input type=\"submit\" value=\"SAVE\">"); response->printf(" </fieldset>"); response->printf("</form>"); response->printf("</body>"); response->printf(" </html>"); response->printf("Settings saved."); //send the response last request->send(response); SM_STATE = STATE_CLIENT; // If we change the IP address, we need to reinitialize the TCP/IP connection with the client }); http_server.begin(); } void loop() { while(1) { switch (SM_STATE) { case STATE_INIT: wait_client(); break; case STATE_CLIENT: client_state(); break; case STATE_SERVER: server_state(); break; default: break; } } }
b49a127b61d999fa4fbe2bb8ad758fe68425f2e4
[ "Markdown", "Text", "C++", "INI" ]
5
C++
OLIMEX/ESP32-PRO
4bd4bf14bb5dce214031d86d047348e9d7a4d32e
a3c2b6521a3cee3f50f2b09f93c507b6582c6db0
refs/heads/main
<repo_name>ykancal12/Columbia_Robotics_Studio_BPM_Calculator<file_sep>/Mic_BPM_helloworld.py from lx16a import * from math import sin, cos from aubio import source, tempo from numpy import median, diff import numpy import time import threading import pyaudio import wave def get_file_bpm(path, params=None): """ Calculate the beats per minute (bpm) of a given file. path: path to the file param: dictionary of parameters """ if params is None: params = {} # default: samplerate, win_s, hop_s = 44100, 1024, 512 #44100*2, 1024*2, 512*2 if 'mode' in params: if params.mode in ['super-fast']: # super fast samplerate, win_s, hop_s = 4000, 128, 64 elif params.mode in ['fast']: # fast samplerate, win_s, hop_s = 8000, 512, 128 elif params.mode in ['default']: pass else: raise ValueError("unknown mode {:s}".format(params.mode)) # manual settings if 'samplerate' in params: samplerate = params.samplerate if 'win_s' in params: win_s = params.win_s if 'hop_s' in params: hop_s = params.hop_s s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break def beats_to_bpm(beats, path): # if enough beats are found, convert to periods then to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60./diff(beats) return median(bpms) else: print("not enough beats found in {:s}".format(path)) return 0 return beats_to_bpm(beats, path) def bpm_every_5_sec(): # Call this function again in 5 seconds threading.Timer(5.0, bpm_every_5_sec).start() form_1 = pyaudio.paInt16 # 16-bit resolution chans = 1 # 1 channel samp_rate = 48000 # 44.1kHz sampling rate chunk = 8192 # 2^12 samples for buffer record_secs = 5 # seconds to record dev_index = 0 # device index found by p.get_device_info_by_index(ii) wav_output_filename = 'test1.wav' # name of .wav file audio = pyaudio.PyAudio() # create pyaudio instantiation # create pyaudio stream stream = audio.open(format = form_1,rate = samp_rate,channels = chans, \ input_device_index = dev_index,input = True, \ frames_per_buffer=chunk) print("recording") frames = [] # loop through stream and append audio chunks to frame array for ii in range(0,int((samp_rate/chunk)*record_secs)): data = stream.read(chunk) frames.append(data) print("finished recording") # stop the stream, close it, and terminate the pyaudio instantiation stream.stop_stream() stream.close() audio.terminate() # save the audio frames as .wav file wavefile = wave.open(wav_output_filename,'wb') wavefile.setnchannels(chans) wavefile.setsampwidth(audio.get_sample_size(form_1)) wavefile.setframerate(samp_rate) wavefile.writeframes(b''.join(frames)) wavefile.close() for f in args.sources: bpm = get_file_bpm(f, params = args) print("{:6s} {:s}".format("{:2f}".format(bpm), f)) print(bpm) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-m', '--mode', help="mode [default|fast|super-fast]", dest="mode", default='default') parser.add_argument('sources', nargs='+', help="input_files") args = parser.parse_args() for f in args.sources: bpm = get_file_bpm(f, params = args) print("{:6s} {:s}".format("{:2f}".format(bpm), f)) # This is the port that the controller board is connected to # This will be different for different computers # On Windows, try the ports COM1, COM2, COM3, etc... # On Raspbian, try each port in /dev/ LX16A.initialize("/dev/ttyUSB0") # There should two servos connected, with IDs 1 and 2 servo1 = LX16A(1) t = 0 bpm_every_5_sec() while True: # Two sine waves out of phase # The servos can rotate between 0 and 240 degrees, # So we adjust the waves to be in that range servo1.moveTimeWrite(sin(t) * 5 + 120) t += 0.01
4781d6c6ffb0dbd490adcd6586c60e5081a708fd
[ "Python" ]
1
Python
ykancal12/Columbia_Robotics_Studio_BPM_Calculator
05a92616865761b1fd34735bb8bffbd294750fe4
79250ef849c7242eebffdeb0cbeba3a66653cc86
refs/heads/master
<file_sep> #%% [markdown] # # Iris Data Species import pandas as pd pd.set_option('max_columns', None) import numpy as np #%% stocks=pd.read_csv("/home/rahul/Desktop/Link to rahul_environment/Projects/Machine_Learning Projects/CrypotoCurrency/crypto-markets.csv",parse_dates=['date']) stocks.tail(10) #%% stocks=stocks[stocks['symbol'] == "NANOX"].set_index('date') #%% stocks.head() #%% shelter_outcomes=pd.read_csv("/home/rahul/Desktop/Link to rahul_environment/Projects/Machine_Learning Projects/CrypotoCurrency/crypto-markets.csv",parse_dates=['date_of_birth','datetime']) shelter_outcomes.head(10) #%%
9d513593e87a1c2b78a3e4ee8193ecfc6971df4f
[ "Python" ]
1
Python
irahulcse/EDA_CRYPTOCURRENCY
30d2daa3b0fe9064d48424511e575ed6cea37b39
caed234b81bddd9c0f3c4c764ecb3e8a59afa8ea
refs/heads/main
<repo_name>Maderlaine1993/Ejercicio-11-Parcial-Programaci-n<file_sep>/Ejercicio 11 2do. parcial/Ejercicio 11 2do. Parcial.cpp /* <NAME> 0909-20-6881 Ingenieria en Sistemas Programación I 2do. Parcial Ejercicio 11*/ //Declaración de librerias #include <iostream> #include <windows.h> #include <conio.h> using namespace std; //declaración de variables públicas int vectorA[3], vectorB[3], vectorC[3], suma; //declaración de arrays float promedio;// promedio vector C int i; //variable tipo pointer //Programación por partes void datosvectorA() { for(i=0; i<3; i++) { cout<< "Ingreso de Datos del Vector A" << i + 1 <<endl; cin>>vectorA[i]; } } void datosvectorB() { for(i=0; i<3; i++) { cout<<"Ingreso de Datos del Vector B" << i + 1 <<endl; cin>>vectorB[i]; } } void resta() { for(i=0; i<3; i++) { vectorC[i]= vectorA[i] - vectorB[i]; } } void datospromedio() { for(i=0; i<3; i++) { suma= suma + vectorC[i]; } promedio = suma / 3; } int main () { cout<< "Calculo de vectores"<<endl; datosvectorA(); datosvectorB(); resta(); datospromedio(); cout<<endl; cout<<" Vector A"<<endl; cout<< vectorA[0] << " " << vectorA[1] << " " << vectorA[2] <<endl; cout<<endl; cout<<" Vector B"<<endl; cout<< vectorB[0] << " " << vectorB[1] << " " << vectorB[2] <<endl; cout<<endl; cout<<" Vector C"<<endl; cout<< vectorC[0] << " " << vectorC[1] << " " << vectorC[2] <<endl; cout<<endl; cout<<"Promedio del Vector C = "<< promedio <<endl; getch(); } /* <NAME> 0909-20-6881 Ingenieria en Sistemas Programación I 2do. Parcial Ejercicio 11*/
d31ba968a89abe7343354d4e27e279f37e8b345f
[ "C++" ]
1
C++
Maderlaine1993/Ejercicio-11-Parcial-Programaci-n
c6f8419e862a1198e405b4ce22850531c2b87a08
259cbdeb000f7fbcb68534eb9b35cb7498e97583
refs/heads/master
<file_sep>// Package slopeone provides an implementation of the Slope One algorithm // used for collaborative filtering. // // The algorithm is introduced in: // Slope One Predictors for Online Rating-Based Collaborative Filtering (2005) // // <NAME> and <NAME> // // This paper is available here: http://lemire.me/fr/documents/publications/lemiremaclachlan_sdm05.pdf // // Slope One is an incredibly simple item-item collaborative filtering // algorithm, which uses user-item ratings to provide a model to predict // users' ratings for items they have yet to rate. package slopeone // This type is just for semantic intent. // UserRatings is a set of item ratings belonging to a user. type UserRatings map[int]float64 // S1 implements the Slope One algorithm. type S1 struct { // d maintains a mapping between items and their rating differences // to other items. For examples, given item1 with a rating of 3.5 // and item2 with a rating of 4.5, one could add the following to // the d: // d["item1"]["item2"] = -1.0 d map[int]map[int]float64 // f maintains a mapping between items and the number of times // differenes in ratings have been calculated for other items. // For example, if the difference between item1 and item2 was // calculated, then the following would be added to f: // f["item1"]["item2"]++ f map[int]map[int]int } // NewS1 returns an *S1 ready for use. func NewS1() *S1 { return &S1{ d: make(map[int]map[int]float64), f: make(map[int]map[int]int), } } // AddRatings adds user ratings for sets of items to the S1. // Ratings for added items will be taken into consideration in future // predictions. func (s1 *S1) AddRatings(users []UserRatings) { for _, user := range users { // For each item and rating generate the difference in rating // between this one and all other items. for i1, r1 := range user { if _, ok := s1.d[i1]; !ok { s1.d[i1] = make(map[int]float64) s1.f[i1] = make(map[int]int) } // Update the frequency of i1 vs i2 and the total rating // difference observed. for i2, r2 := range user { s1.f[i1][i2]++ s1.d[i1][i2] += (r1 - r2) } } } // Normalise the difference in ratings for each pair of items, by // the number of times each item-pair have had their differences // calculated. for i1, diffs := range s1.d { for i2 := range diffs { diffs[i2] /= float64(s1.f[i1][i2]) } } } // Predict returns predicted ratings for items the provided user has not // yet rated, based on the rating they provide for items they have // rated. // // Items the user has rated are not included in the returned // UserPredictions. func (s1 *S1) Predict(ur UserRatings) map[int]float64 { p, f := make(map[int]float64), make(map[int]int) var gf int // For each item-rating the user has rated we will compare it to // all global item-ratings, and update our prediction of unrated // items for the user. for i, r := range ur { for gi, gr := range s1.d { // If items have never been analysed or we will want to // remove them from the predicted set anyway, then move on. if gf = s1.f[gi][i]; gf == 0 || gi == i { continue } // Update our prediction of the unrated item's rating for // the user according to the global rating difference // between the user's rated item (i) and the other item // we're looking at (gi). This difference gives us a // direction to modify they user's providing rating for i // by, in order to predict their rating of gi. p[gi] += (float64(gf) * (gr[i] + r)) f[gi] += gf } } // Normalise each predicted rating, and remove ones that were in the // set of provided ratings. for i := range p { p[i] /= float64(f[i]) for j := range ur { if i == j { delete(p, j) } } } return p } <file_sep># slopeone [![GoDoc](https://godoc.org/github.com/e-dard/slopeone?status.svg)](https://godoc.org/github.com/e-dard/slopeone) A Go implementation of the Slope One Collaborative Filtering algorithm, as introduced in: > [Slope One Predictors for Online Rating-Based Collaborative Filtering](http://lemire.me/fr/documents/publications/lemiremaclachlan_sdm05.pdf) > > <NAME> and <NAME> (2005) ## A What? Collaborative filtering is an approach to implementing part or all of a recommendation system, wherein you recommend or suggest items to users by analysing other users' preferences to those items. Typically, CF algorithms fall into two types: #### User-based algorithms These algorithms focus on identifying similarities between the user you want to predict item preferences for *u1*, and other uses in the system. Once you have identified other similar users you then use their preferences for items to predict *u1*'s preferences. Slope One is not one of these algorithms #### Item-based algorithms Item-based algorithms don't consider the relationship between users at all, instead they use the relationship between *pairs of items*. Slope One is one of these types of algorithms (maybe the simplest, actually). The general idea is a sparse item-item matrix is generated, where each cell within the matrix describes a difference in preferences between those items. These differences are calculated for each user in the dataset, but they're merged to give a global matrix describing how all users perceives differences between pairs of items. To make a prediction for a new user, some existing preferences for that user need to be provided. Using these preferences, predictions of the user's preferences of all other items in the system can be extracted. ## Usage ``` $ go get github.com/e-dard/slopeone ``` > Note: Currently it's not possible to add new user preferences to the > model, or to update existing ones, though I might add this in the > future. A basic use-case for the current model would be to > recalculate all recommendations for all users, in batches, and then > cache the results until the next time you run the model (with more > data). To incorporate the model, you can do something like this: ```go package main import ( "fmt" "github.com/e-dard/slopeone" ) func main() { // Each UserRatings map represents a single user's set of preferences // over some items. In this case we have three users' preferences. userRatings := []slopeone.UserRatings{ {2005: 2.4, 5513: 1.3, 13035: 2.0}, {5513: 4, 359602: 5, 13035: 1.5, 29074: 4}, {29074: 4.3, 359602: 2.5, 2005: 5}, } s1 := slopeone.NewS1() // Add user preferences to the model. s1.AddRatings(userRatings) // Predict will return predicted ratings for a user preds := s1.Predict(slopeone.UserRatings{2005: 2.0, 29074: 3.2}) for item, rating := range preds { fmt.Printf("item: %d\trating: %0.1f\n", item, rating) } } ``` results in: ``` item: 359602 rating: 1.7 item: 5513 rating: 2.1 item: 13035 rating: 1.2 ```
e851c5eef92bc74d9c2c2fa941de01719bfbe22d
[ "Markdown", "Go" ]
2
Go
postfix/slopeone
a7ae05407d0fe480cfa61a136b5d933750c9b02c
e29b8617d2fc62f1cf06ac31d7d24978a2e87f82
refs/heads/master
<repo_name>defulee/diagram-maker<file_sep>/src/main/java/io/github/defulee/diagram/graph/graphviz/Graphviz.java package io.github.defulee.diagram.graph.graphviz; import org.apache.commons.collections4.CollectionUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import static java.nio.charset.StandardCharsets.UTF_8; /** * @author defu * @description: 生成GraphViz图形源码的工具 * @date 2019/10/17 */ public class Graphviz { private String name; private Node nodeConfig; private Edge edgeConfig; private List<Node> nodes; private List<Edge> edges; public Graphviz(String name) { this.name = name; this.nodes = new ArrayList<>(); this.edges = new ArrayList<>(); } public static Graphviz of(String name) { return new Graphviz(name); } public Graphviz config(Node node) { this.nodeConfig = node; this.nodeConfig.setName("node"); return this; } public Graphviz config(Edge edge) { this.edgeConfig = edge; this.edgeConfig.setName("edge"); return this; } public Graphviz addNode(Node node) { this.nodes.add(node); return this; } public Graphviz addEdge(Edge edge) { this.edges.add(edge); return this; } public Graphviz addEdge(String srcNodeName, String dstNodeName, String label) { this.edges.add(new Edge(new Node(srcNodeName), new Node(dstNodeName), label)); return this; } public String build() { return toString(); } public String render() { if (name == null || name.isEmpty()) { return ""; } String ln = System.lineSeparator(); StringBuilder builder = new StringBuilder("digraph "); builder.append(name).append(" {").append(ln); if (nodeConfig != null) { builder.append("\t").append(nodeConfig.toString()).append(ln); } if (edgeConfig != null) { builder.append("\t").append(edgeConfig.toString()).append(ln); } if (CollectionUtils.isNotEmpty(nodes)) { for (Node node : nodes) { builder.append("\t").append(node.toString()).append(ln); } } if (CollectionUtils.isNotEmpty(edges)) { for (Edge edge : edges) { builder.append("\t").append(edge.toString()).append(ln); } } return builder.append("}").toString(); } public File render(String outputFilePath) throws IOException { String content = render(); return toFile(content, new File(outputFilePath)); } private File toFile(String content, File target) throws IOException { Files.createDirectories(target.getAbsoluteFile().getParentFile().toPath()); try (final Writer out = new OutputStreamWriter(new FileOutputStream(target), UTF_8)) { out.write(content); } return target; } @Override public String toString() { return render(); } } <file_sep>/src/main/java/io/github/defulee/diagram/graph/graphviz/FixedSize.java package io.github.defulee.diagram.graph.graphviz; /** * @author defu * @date 2019/10/22 */ public enum FixedSize { TRUE, FALSE, SHAPE; public String render() { return String.format("fixedsize=\"%s\"", this.name().toLowerCase()); } } <file_sep>/src/main/java/io/github/defulee/diagram/graph/graphviz/Style.java package io.github.defulee.diagram.graph.graphviz; /** * graphviz node style * * @author defu * @date 2019/10/17 * @see <a href="https://www.graphviz.org/doc/info/shapes.html">https://www.graphviz.org/doc/info/shapes.html</a> */ public enum Style { FILLED, INVISIBLE, DIAGONALS, ROUNDED, DASHED, DOTTED, SOLID, BOLD; @Override public String toString() { return value(); } public String value() { return this.name().toLowerCase(); } } <file_sep>/src/main/java/io/github/defulee/diagram/graph/graphviz/Shape.java package io.github.defulee.diagram.graph.graphviz; /** * graphviz node shape * * @author defu * @date 2019/10/17 * @see <a href="https://www.graphviz.org/doc/info/shapes.html">https://www.graphviz.org/doc/info/shapes.html</a> */ public enum Shape { CIRCLE, POLYGON, PARALLELOGRAM, OCTAGON, MDIAMOND, MSQUARE, SIGNATURE, ASSEMBLY, INSULATOR, NOVERHANG, THREE_POVERHANG, FIVE_POVERHANG, FOLDER, NOTE, TAB, MCIRCLE, INVHOUSE, HOUSE, HEXAGON, DOUBLE_OCTAGON, ELLIPSE, BOX, RECTANGLE, RECT, DOUBLE_CIRCLE, UNDERLINE, PLAIN, PLAINTEXT, DIAMOND, CYLINDER, COMPONENT, RARROW, LARROW; public String render() { return String.format("shape=\"%s\"", this.name().toLowerCase().replaceAll("_", "")); } } <file_sep>/src/main/java/io/github/defulee/diagram/graph/graphviz/Edge.java package io.github.defulee.diagram.graph.graphviz; import com.google.common.base.Joiner; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import org.apache.commons.collections4.CollectionUtils; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author defu * @date 2019/10/17 */ @Data @Builder @AllArgsConstructor public class Edge { private String name; private Node src; private Node dst; private String label; private ArrowType arrowHead; private ArrowType arrowTail; private Color color; private List<Style> styles; public Edge(Node src, Node dst) { this(src, dst, null); } public Edge(Node src, Node dst, String label) { this(src, dst, label, null, null, null); } public Edge(Node src, Node dst, String label, ArrowType arrowTail, Color color, Style... styles) { this.src = src; this.dst = dst; this.label = label; if (styles != null) { this.styles = Arrays.stream(styles).collect(Collectors.toList()); } else { this.styles = Collections.emptyList(); } this.arrowTail = arrowTail; this.color = color; } @Override public String toString() { StringBuilder builder = new StringBuilder(); if (src != null && dst != null) { //正常的边关系 builder.append(src.getName()).append("->").append(dst.getName()); } else if (name != null) { //边配置时 builder.append(name); } if (label == null && CollectionUtils.isEmpty(styles) && arrowHead == null && arrowTail == null && color == null) { return builder.append(";").toString(); } builder.append(" [ "); if (label != null) { builder.append("label=\"").append(label).append("\", "); } if (arrowHead != null) { builder.append(arrowHead.render("arrowhead")).append(", "); } if (arrowTail != null) { builder.append(arrowTail.render("arrowtail")).append(", "); } if (color != null) { builder.append(color.render(false)).append(", "); } if (CollectionUtils.isNotEmpty(styles)) { builder.append("style=\"").append(Joiner.on(",").skipNulls().join(styles)).append("\", "); } builder = builder.delete(builder.lastIndexOf(","), builder.length()); return builder.append(" ];").toString(); } } <file_sep>/src/main/java/io/github/defulee/diagram/graph/examples/graphviz/SimpleGraphvizExample.java package io.github.defulee.diagram.graph.examples.graphviz; import io.github.defulee.diagram.graph.graphviz.Color; import io.github.defulee.diagram.graph.graphviz.Edge; import io.github.defulee.diagram.graph.graphviz.Node; import io.github.defulee.diagram.graph.graphviz.Shape; import io.github.defulee.diagram.graph.graphviz.Style; import io.github.defulee.diagram.graph.graphviz.ArrowType; import io.github.defulee.diagram.graph.graphviz.Graphviz; import java.util.Arrays; /** * @author defu * @date 2019/10/20 */ public class SimpleGraphvizExample { public static void main(String[] args) { Node nodeConfig = Node.builder().shape(Shape.RECTANGLE).styles(Arrays.asList(Style.FILLED, Style.ROUNDED)).color(Color.LIGHTBLUE).build(); Edge edgeConfig = Edge.builder().color(Color.GREEN).arrowTail(ArrowType.NORMAL).build(); Node startNode = Node.builder().name("START").shape(Shape.DOUBLE_CIRCLE).styles(Arrays.asList(Style.FILLED)).color(Color.LIGHTBLUE).build(); Node node1 = Node.builder().name("node1").label("node-1").build(); Node node2 = Node.builder().name("node2").label("node-2").build(); Node node3 = Node.builder().name("node3").label("node-3").shape(Shape.DIAMOND).build(); Node node4 = Node.builder().name("node4").label("node-4").build(); Node node5 = Node.builder().name("node5").label("node-5").build(); Graphviz graphViz = Graphviz.of("SimpleGraphvizExample"); graphViz.config(nodeConfig); graphViz.config(edgeConfig); graphViz.addNode(startNode); graphViz.addNode(node1); graphViz.addNode(node2); graphViz.addNode(node3); graphViz.addNode(node4); graphViz.addNode(node5); graphViz.addEdge(Edge.builder().src(startNode).dst(node1).build()); graphViz.addEdge(Edge.builder().src(node1).dst(node2).label("node1->node2").build()); graphViz.addEdge(Edge.builder().src(node1).dst(node3).label("node1->node3").build()); graphViz.addEdge(Edge.builder().src(node2).dst(node4).label("node2->node4").build()); graphViz.addEdge(Edge.builder().src(node2).dst(node5).label("node2->node5").build()); graphViz.addEdge(Edge.builder().src(node1).dst(node5).build()); System.out.println(graphViz.render()); } } <file_sep>/README.md # GraphBuilder build graphviz graph # Usage - use node & edge: ```java Node nodeConfig = Node.builder().shape(Shape.RECTANGLE).styles(Arrays.asList(Style.filled, Style.rounded)).color(Color.LIGHTBLUE).build(); Edge edgeConfig = Edge.builder().color(Color.GREEN).arrowTail(ArrowType.NORMAL).build(); Node startNode = Node.builder().name("START").shape(Shape.DOUBLE_CIRCLE).styles(Arrays.asList(Style.filled)).color(Color.LIGHTBLUE).build(); Node node1 = Node.builder().name("node1").label("node-1").build(); Node node2 = Node.builder().name("node2").label("node-2").build(); Node node3 = Node.builder().name("node3").label("node-3").shape(Shape.DIAMOND).build(); Node node4 = Node.builder().name("node4").label("node-4").build(); Node node5 = Node.builder().name("node5").label("node-5").build(); Graphviz graphViz = Graphviz.of("SimpleGraphvizExample"); graphViz.config(nodeConfig); graphViz.config(edgeConfig); graphViz.addNode(startNode); graphViz.addNode(node1); graphViz.addNode(node2); graphViz.addNode(node3); graphViz.addNode(node4); graphViz.addNode(node5); graphViz.addEdge(Edge.builder().src(startNode).dst(node1).build()); graphViz.addEdge(Edge.builder().src(node1).dst(node2).label("node1->node2").build()); graphViz.addEdge(Edge.builder().src(node1).dst(node3).label("node1->node3").build()); graphViz.addEdge(Edge.builder().src(node2).dst(node4).label("node2->node4").build()); graphViz.addEdge(Edge.builder().src(node2).dst(node5).label("node2->node5").build()); graphViz.addEdge(Edge.builder().src(node1).dst(node5).build()); System.out.println(graphViz.render()); ``` output is: ``` digraph SimpleGraphvizExample { node [ shape="rectangle", color="lightblue", style="filled,rounded" ]; edge [ arrowtail="normal", color="green" ]; START [ shape="doublecircle", color="lightblue", style="filled" ]; node1 [ label="node-1" ]; node2 [ label="node-2" ]; node3 [ label="node-3", shape="diamond" ]; node4 [ label="node-4" ]; node5 [ label="node-5" ]; START->node1; node1->node2 [ label="node1->node2" ]; node1->node3 [ label="node1->node3" ]; node2->node4 [ label="node2->node4" ]; node2->node5 [ label="node2->node5" ]; node1->node5; } ``` - use edge only: ```java Node nodeConfig = Node.builder().shape(Shape.RECTANGLE).styles(Arrays.asList(Style.filled, Style.rounded)).color(Color.LIGHTBLUE).build(); Edge edgeConfig = Edge.builder().color(Color.GREEN).arrowTail(ArrowType.NORMAL).build(); Graphviz graphViz = Graphviz.of("SimpleGraphvizExample"); graphViz.config(nodeConfig); graphViz.config(edgeConfig); graphViz.addEdge("node1", "node2", "node1->node2"); graphViz.addEdge("node1", "node3", "node1->node3"); graphViz.addEdge("node2", "node4", "node2->node4"); graphViz.addEdge("node2", "node5", "node2->node5"); graphViz.addEdge("node1", "node5", "node1->node5"); System.out.println(graphViz.render()); ``` output: ``` digraph SimpleGraphvizExample { node [ shape="rectangle", color="lightblue", style="filled,rounded" ]; edge [ arrowtail="normal", color="green" ]; node1->node2 [ label="node1->node2" ]; node1->node3 [ label="node1->node3" ]; node2->node4 [ label="node2->node4" ]; node2->node5 [ label="node2->node5" ]; node1->node5 [ label="node1->node5" ]; } ```
32aa23a66107325176d6e1a1f88cb1cddd58a66c
[ "Markdown", "Java" ]
7
Java
defulee/diagram-maker
441bc420348cd85293df1a96a59cad242618587c
55a97432f50d38d9687c2ff7d4005eb8392ad0ee
refs/heads/master
<repo_name>AndrewNowosad/DirScanNet<file_sep>/DirScanNet/Models/FSItem.cs using System; using System.Collections.Generic; using System.IO; namespace DirScanNet.Models { abstract class FSItem { static public readonly string ComputerRootAlias = "<Компьютер>"; static protected Dictionary<string, FSItem> ItemsCache { get; private set; } = new Dictionary<string, FSItem>(); static public void ResetCache() { ItemsCache = new Dictionary<string, FSItem>(); } public string Name { get; protected set; } public string FullPhysicalPath { get; protected set; } public long Weight { get; protected set; } protected FSItem(string path) { FullPhysicalPath = path; if (path == ComputerRootAlias) Name = ComputerRootAlias; else { Name = Path.GetFileName(path); if (Name == "") Name = FullPhysicalPath; } ItemsCache[path] = this; } public Folder GetParent() { if (FullPhysicalPath == ComputerRootAlias) throw new NotSupportedException($"Операция не поддерживается для {ComputerRootAlias}"); string parentPath = Path.GetDirectoryName(FullPhysicalPath); if (parentPath == null) return ComputerRoot.GetComputerRoot(); return Folder.GetFolder(parentPath); } } }<file_sep>/DirScanNet/Models/Folder.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace DirScanNet.Models { class Folder : FSItem { static public Folder GetFolder(string path) { if (ItemsCache.ContainsKey(path)) return (Folder)ItemsCache[path]; return new Folder(path); } protected Folder(string path) : base(path) { RescanPath(); } protected List<FSItem> childElements; public IReadOnlyList<FSItem> ChildElements => childElements; protected virtual void RescanPath() { childElements = new List<FSItem>(); IEnumerable<string> dirs; try { dirs = Directory.EnumerateDirectories(FullPhysicalPath); } catch (UnauthorizedAccessException) { return; } foreach (var dir in dirs) childElements.Add(GetFolder(dir)); foreach (var file in Directory.EnumerateFiles(FullPhysicalPath)) childElements.Add(File.GetFile(file)); Weight = childElements.Sum(item => item.Weight); } public override string ToString() { if (Name == "") return $"Drive: {FullPhysicalPath}"; return $"Folder: {Name}"; } } }<file_sep>/DirScanNet/Models/FSScanner.cs using System.Threading.Tasks; namespace DirScanNet.Models { class FSScanner { public Folder GetFolder(string path) => Folder.GetFolder(path); public async Task<Folder> GetFolderAsync(string path) { return await Task.Run(() => GetFolder(path)); } public Folder GetParent(FSItem fsItem) => fsItem.GetParent(); public async Task<Folder> GetParentAsync(FSItem fsItem) { return await Task.Run(() => GetParent(fsItem)); } public ComputerRoot GetComputerRoot() => ComputerRoot.GetComputerRoot(); public async Task<ComputerRoot> GetComputerRootAsync() { return await Task.Run(() => GetComputerRoot()); } } }<file_sep>/DirScanNet/Views/Converters/FileLengthConverter.cs using System; using System.Globalization; using System.Windows.Data; namespace DirScanNet.Views.Converters { [ValueConversion(typeof(long), typeof(string))] public class FileLengthConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double fileLength = (long)value; if (fileLength < 1024) return $"{fileLength:0} Б"; fileLength /= 1024; if (fileLength < 1024) return $"{fileLength:0.0} кБ"; fileLength /= 1024; if (fileLength < 1024) return $"{fileLength:0.0} МБ"; fileLength /= 1024; if (fileLength < 1024) return $"{fileLength:0.0} ГБ"; fileLength /= 1024; return $"{fileLength:0.0} ТБ"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/DirScanNet/ViewModels/MainVM.cs using DirScanNet.Models; using DirScanNet.SettingsHelper; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; namespace DirScanNet.ViewModels { class MainVM : WindowVM { string currentPath; public string CurrentPath { get => currentPath; set => Set(ref currentPath, value); } Folder currentFolder; public Folder CurrentFolder { get => currentFolder; set { Set(ref currentFolder, value); NotifyPropertyChanged(nameof(Items)); NotifyPropertyChanged(nameof(MaxWeight)); } } public IEnumerable<FSItem> Items { get => CurrentFolder?.ChildElements.OrderByDescending(item => item.Weight); } public long? MaxWeight => Items?.FirstOrDefault()?.Weight; bool isProcess; public bool IsProcess { get => isProcess; protected set => Set(ref isProcess, value); } DelegateCommand scanFolderCommand; public ICommand ScanFolderCommand { get { if (scanFolderCommand == null) scanFolderCommand = new DelegateCommand(async o => await ScanFolderAsync()); return scanFolderCommand; } } DelegateCommand openFolderCommand; public ICommand OpenFolderCommand { get { if (openFolderCommand == null) openFolderCommand = new DelegateCommand(o => OpenFolder((FSItem)o)); return openFolderCommand; } } DelegateCommand upLevelCommand; public ICommand UpLevelCommand { get { if (upLevelCommand == null) upLevelCommand = new DelegateCommand(async o => await GoToUpLevelAsync()); return upLevelCommand; } } DelegateCommand saveCommand; public ICommand SaveCommand { get { if (saveCommand == null) saveCommand = new DelegateCommand(o => SaveSettings()); return saveCommand; } } protected async Task ScanFolderAsync() { IsProcess = true; CurrentFolder = await new FSScanner().GetFolderAsync(CurrentPath); IsProcess = false; } protected void OpenFolder(FSItem item) { var folder = item as Folder; if (folder == null) return; CurrentFolder = folder; } protected async Task GoToUpLevelAsync() { if (CurrentFolder == null) return; IsProcess = true; try { CurrentFolder = await new FSScanner().GetParentAsync(CurrentFolder); } catch (NotSupportedException) { } IsProcess = false; } public MainVM() { Title = "DirScanNet 1.0.0"; LoadSettings(); PropertyChanged += OnPropertyChanged; } void LoadSettings() { var settings = Settings.Instance.MainWindowSettings; WindowState = settings.WindowState; Width = settings.Width; Height = settings.Height; Left = settings.Left; Top = settings.Top; CurrentPath = settings.CurrentPath; } void SaveSettings() { var settings = Settings.Instance.MainWindowSettings; settings.WindowState = WindowState; settings.Width = Width; settings.Height = Height; settings.Left = Left; settings.Top = Top; settings.CurrentPath = CurrentPath; Settings.Save(); } void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(CurrentFolder): OnCurrentFolderPropertyChanged(); return; } } void OnCurrentFolderPropertyChanged() { CurrentPath = CurrentFolder.FullPhysicalPath; } } }<file_sep>/DirScanNet/SettingsHelper/Settings.cs using System; using System.IO; using System.Xml; using System.Xml.Serialization; namespace DirScanNet.SettingsHelper { [XmlRoot("Settings")] public sealed class Settings { static readonly string path = "Settings.xml"; static readonly XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("") }); static readonly XmlSerializer serializer = new XmlSerializer(typeof(Settings)); static readonly Lazy<Settings> instance = new Lazy<Settings>(LoadSettings); public static Settings Instance => instance.Value; static Settings LoadSettings() { if (!File.Exists(path)) return new Settings(); using (Stream stream = File.OpenRead(path)) return (Settings)serializer.Deserialize(stream); } public static void Save() => Instance.SaveSettings(); Settings() { } void SaveSettings() { using (Stream stream = File.Create(path)) serializer.Serialize(stream, this, namespaces); } public MainWindowSettings MainWindowSettings { get; set; } = new MainWindowSettings(); } }<file_sep>/DirScanNet/SettingsHelper/MainWindowSettings.cs using System.Windows; namespace DirScanNet.SettingsHelper { public class MainWindowSettings { public WindowState WindowState { get; set; } = WindowState.Normal; public double Width { get; set; } = 840; public double Height { get; set; } = 500; public double Left { get; set; } = 250; public double Top { get; set; } = 110; public string CurrentPath { get; set; } = @"C:\"; } }<file_sep>/DirScanNet/App.xaml.cs using DirScanNet.ViewModels; using DirScanNet.Views; using System.Windows; namespace DirScanNet { public partial class App : Application { public App() { var mainVM = new MainVM(); var mainView = new MainWindow { DataContext = mainVM }; mainView.Show(); } } }<file_sep>/DirScanNet/Models/ComputerRoot.cs using System.Collections.Generic; using System.IO; using System.Linq; namespace DirScanNet.Models { class ComputerRoot : Folder { static public ComputerRoot GetComputerRoot() { if (ItemsCache.ContainsKey(ComputerRootAlias)) return (ComputerRoot)ItemsCache[ComputerRootAlias]; return new ComputerRoot(); } ComputerRoot() : base(ComputerRootAlias) { } protected override void RescanPath() { childElements = new List<FSItem>(); var drives = DriveInfo.GetDrives() .Select(d => d.RootDirectory.FullName); foreach (var drive in drives) childElements.Add(GetFolder(drive)); } public override string ToString() { return ComputerRootAlias; } } }<file_sep>/DirScanNet/ViewModels/WindowVM.cs using System.Windows; namespace DirScanNet.ViewModels { abstract class WindowVM : VMBase { WindowState windowState; public WindowState WindowState { get => windowState; set => Set(ref windowState, value); } double width; public double Width { get => width; set => Set(ref width, value); } double height; public double Height { get => height; set => Set(ref height, value); } double left; public double Left { get => left; set => Set(ref left, value); } double top; public double Top { get => top; set => Set(ref top, value); } string title; public string Title { get => title; protected set => Set(ref title, value); } } }<file_sep>/DirScanNet/Views/Converters/StringPathToBitmapSourceConverter.cs using System; using System.Drawing; using System.Globalization; using System.IO; using System.Windows; using System.Windows.Data; using System.Windows.Interop; using System.Windows.Media.Imaging; namespace DirScanNet.Views.Converters { [ValueConversion(typeof(string), typeof(BitmapSource))] public class StringPathToBitmapSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string path = (string)value; if (File.Exists(path)) return GetFileIcon(path); return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } object GetFileIcon(string path) { using (var sysicon = Icon.ExtractAssociatedIcon(path)) return Imaging.CreateBitmapSourceFromHIcon(sysicon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } } }<file_sep>/DirScanNet/Models/File.cs using System.IO; namespace DirScanNet.Models { class File : FSItem { static public File GetFile(string path) { if (ItemsCache.ContainsKey(path)) return (File)ItemsCache[path]; return new File(path); } File(string path) : base(path) { Weight = new FileInfo(path).Length; } public override string ToString() => $"File: {Name}"; } }
fa5eb72c00c513356361360460cebb8d826db1b2
[ "C#" ]
12
C#
AndrewNowosad/DirScanNet
0ad8f03024f18b0ac4afefbe3dace24b72d381f7
b55337347a1b95a1903b0950fb3be6440e2f3841
refs/heads/master
<file_sep>require "pry" songs = [ "Phoenix - 1901", "Tokyo Police Club - Wait Up", "<NAME> - Too Much", "The Naked and the Famous - Young Blood", "(Far From) Home - Tiga", "The Cults - Abducted", "Phoenix - Consolation Prizes", "<NAME> - Cats in the Cradle", "<NAME> - Keep It Loose, Keep It Tight" ] def help puts "I accept the following commands:" puts "- help : displays this help message" puts "- list : displays a list of songs you can play" puts "- play : lets you choose a song to play" puts "- exit : exits this program" end def list (songs) songs.each_with_index do |song, index| number=index+1 puts "#{number}. #{song}" end end def play (songs) puts "Please enter a song name or number:" user_input=gets.strip songs.each_with_index do |song, index| number=index+1 binding.pry if user_input == song puts "Playing #{song}" elsif user_input.to_i == number puts "Playing #{song}" end end puts "Invalid input, please try again" end def exit_jukebox puts "Goodbye" end def run(songs) loop do puts "Please enter a command:" user_input=gets.strip if user_input=="exit" exit_jukebox break elsif user_input=="list" list(songs) elsif user_input=="play" play(songs) elsif user_input=="help" help end end end
0415680971ed5ab8e3f3bdaf5ceca3dae19b9a81
[ "Ruby" ]
1
Ruby
brianchz/cli-applications-jukebox-atx01-seng-ft-022221
6e8fbe42b75fed8b068d6c2c8bf104d2434a6a2b
e75950deee83a0c48e8ab9e4d59c74bd7ce3029d
refs/heads/main
<file_sep>'use strict'; if(window.document.title==='Maintenance Request | Home Maintenance Hub'){ let name1 =document.getElementById('name1'); let contact1 =document.getElementById('contact1'); let email1 =document.getElementById('email1'); let address1 =document.getElementById('address1'); let city1 =document.getElementById('city1'); let reach1 =document.getElementById('reach'); let category =document.getElementById('category'); let discription1 =document.getElementById('discription'); let date1 =document.getElementById('date'); let mincost1 =document.getElementById('mincost'); let maxcost1 =document.getElementById('maxcost'); let divEl=document.getElementById('x'); let verifyIn=document.getElementById('verify'); //////////////////global scope////////////////////// //let requestForm1 =document.getElementById('requestForm'); ////////////////////////construct function //////////////////////////////////////// function MaintenanceRequest(name,contact,email,address,city,reach,category,discription,date,minCost,maxCost){ this.name=name; this.contact=contact; this.email=email; this.address=address; this.city=city; this.reach=reach; this.category=category;//PrimaryKey this.discription=discription; this.date=date; this.minCost=minCost; this.maxCost=maxCost; MaintenanceRequest.array.push(this); saveToLocalStorage(); } MaintenanceRequest.array=[]; // console.log(MaintenanceRequest.array); ////////////////////render function (outter loop)//////////////////// function render1(renderdobj){ let fieldsetEl =document.createElement('fieldset'); divEl.appendChild(fieldsetEl); let ulEl =document.createElement('ul'); fieldsetEl.appendChild(ulEl); let liElx=document.createElement('li');// changed form h3 to li ulEl.appendChild(liElx); liElx.textContent=`Maintenance Request Gategory: ${renderdobj.category}`; //console.log(renderdobj.category); let liEl=document.createElement('li'); ulEl.appendChild(liEl); liEl.textContent=`Homeowner Name: ${renderdobj.name}`; let liEl1=document.createElement('li'); ulEl.appendChild(liEl1); liEl1.textContent=`Contact Number: ${renderdobj.contact}`; let liEl2=document.createElement('li'); ulEl.appendChild(liEl2); liEl2.textContent=`Email: ${renderdobj.email}`; let liEl3=document.createElement('li'); ulEl.appendChild(liEl3); liEl3.textContent=`Address: ${renderdobj.address}`; let liEl4=document.createElement('li'); ulEl.appendChild(liEl4); liEl4.textContent=`City: ${renderdobj.city}`; let liEl5=document.createElement('li'); ulEl.appendChild(liEl5); liEl5.textContent=` How did your hear about us: ${renderdobj.reach}`; let liEl6=document.createElement('li'); ulEl.appendChild(liEl6); liEl6.textContent=`Maintenance Discription: ${renderdobj.discription}`; let liEl9=document.createElement('li'); ulEl.appendChild(liEl9); liEl9.textContent=`Maintenance Appointment Date: ${renderdobj.date}`; let liEl7=document.createElement('li'); ulEl.appendChild(liEl7); liEl7.textContent=`Minimum Cost: ${renderdobj.minCost}`; let liEl8=document.createElement('li'); ulEl.appendChild(liEl8); liEl8.textContent=`Maximum Cost: ${renderdobj.maxCost}`; } /////////////rendering function (inner loop) Provider/////////// function render (renderedObj){ let fieldsetEl=document.createElement('fieldset'); divEl.appendChild(fieldsetEl); let ulEl =document.createElement('ul'); fieldsetEl.appendChild(ulEl); let liElc=document.createElement('li');//Change made here h3 to li ulEl.appendChild(liElc); liElc.textContent= `Service Provider Craft: ${renderedObj.craft}`; let liEl=document.createElement('li'); ulEl.appendChild(liEl); liEl.textContent=`Service Provider Name: ${renderedObj.name}`; let liEl2=document.createElement('li'); ulEl.appendChild(liEl2); liEl2.textContent=`Contact Number: ${renderedObj.contact}`; let liEl3=document.createElement('li'); ulEl.appendChild(liEl3); liEl3.textContent=`Email: ${renderedObj.email}`; let liEl4=document.createElement('li'); ulEl.appendChild(liEl4); liEl4.textContent=`Address: ${renderedObj.address}`; let liEl8=document.createElement('li'); ulEl.appendChild(liEl8); liEl8.textContent=`City: ${renderedObj.city}`; let liEl5=document.createElement('li'); ulEl.appendChild(liEl5); liEl5.textContent=`Contract & Payment Method: ${renderedObj.contract}`; let liEl6=document.createElement('li'); ulEl.appendChild(liEl6); liEl6.textContent=`Available Days: ${renderedObj.days}`; let liEl7=document.createElement('li'); ulEl.appendChild(liEl7); liEl7.textContent=`Available Shifts: ${renderedObj.shifts}`; } //////////////////save local storage function Request////////////////////// function saveToLocalStorage() { localStorage.setItem('RequestData', JSON.stringify(MaintenanceRequest.array)); } ///////////////////get from local storage function Request////////////////////// function getFromLocalStorage(){ let getdata=JSON.parse(localStorage.getItem('RequestData')); if(getdata){ MaintenanceRequest.array=getdata; } } //////////Get form Local Storage Provider//////////// let providerData=[]; function getFormData () { providerData = JSON.parse(localStorage.getItem('formData')); // console.log('provider data: ' + providerData); // console.log('Get provider sata'); } ////////////////////////////// showbutton ///////////////////////////////////// let bouttonEl2=document.createElement('button'); divEl.appendChild(bouttonEl2); bouttonEl2.textContent='SHOW YOUR INFO CLICK ME '; bouttonEl2.hidden=true; function showButton(){ getFromLocalStorage();//request getFormData ();//provider // Nested loops for Complex rendering: Calling render from provider.js in the inner loop for(let i=0 ; i<MaintenanceRequest.array.length ;i++){ render1(MaintenanceRequest.array[i]);//Render Maintenamce Reguests for(let j=0; j<providerData.length;j++){ if(providerData[j].craft===MaintenanceRequest.array[i].category)// checking category===?craft render(providerData[j]);// Rendering Service Providers } } bouttonEl2.removeEventListener('click',showButton); } bouttonEl2.addEventListener('click',showButton); //////////////////////////////event function ////////////////////////////////// let submit1 =document.getElementById('button'); let num = '1234'; function handileSubmit(event){ event.preventDefault(); if( num === verifyIn.value){ alert('Successfully submited request'); console.log({name1}) console.log({contact1}) console.log({email1}) console.log({name1}) new MaintenanceRequest(name1.value,contact1.value,email1.value,address1.value,city1.value,reach1.value,category.value,discription1.value,date1.value,mincost1.value,maxcost1.value); // console.log(category.value); if(MaintenanceRequest.array){ bouttonEl2.hidden=false; submit1.removeEventListener('click',handileSubmit ); } }else{ alert('Please try again!'); } } submit1.addEventListener('click',handileSubmit ); } //////////////////////////////////////// /////////////////////////////////////// /////////////////////////////////////// ///////////////////////////////////////// ///////////provider///////////////////// if(window.document.title==='Service Providers | Home Maintenance Hub'){ let divEl = document.getElementById('x'); let uname=document.getElementById('name1'); let contact=document.getElementById('contact1'); let emailEl=document.getElementById('email1'); let addressEl=document.getElementById('address1'); let selectCity=document.getElementById('city1'); let craftEl=document.getElementById('craft1'); let contractEl=document.getElementById('contract'); let buttonEl=document.getElementById('button'); let buttonEl2=document.createElement('button'); // buttonEl2.style('z-index',2) divEl.appendChild(buttonEl2);//Holy error buttonEl2.textContent = 'to show offers click here'; buttonEl2.hidden=true; let verify=document.getElementById('verify'); /////////////////// let arrOfObjects1 =[]; let availableDayes=[]; let availableShift=[]; function ProviderServiceForm (name,contact,email,address,city,craft,contract){ this.name=name; this.contact=contact; this.email=email; this.address=address; this.city=city; this.craft=craft; this.contract=contract; this.days=days(); this.shifts=shifts(); arrOfObjects1.push(this); console.log('constr' +this.craft); setFormData(); } let checkBoxEl1= document.getElementById('sunday'); let checkBoxEl2= document.getElementById('monday'); let checkBoxEl3= document.getElementById('tuesday'); let checkBoxEl4= document.getElementById('wednesday'); let checkBoxEl5= document.getElementById('thursday'); let checkBoxEl6= document.getElementById('friday'); let checkBoxEl7= document.getElementById('saturday'); function days(){ if(checkBoxEl1.checked){availableDayes.push(checkBoxEl1.value);} if(checkBoxEl2.checked){availableDayes.push(checkBoxEl2.value);} if(checkBoxEl3.checked){availableDayes.push(checkBoxEl3.value);} if(checkBoxEl4.checked){availableDayes.push(checkBoxEl4.value);} if(checkBoxEl5.checked){availableDayes.push(checkBoxEl5.value);} if(checkBoxEl6.checked){availableDayes.push(checkBoxEl6.value);} if(checkBoxEl7.checked){availableDayes.push(checkBoxEl7.value);} return availableDayes ; } let shift1=document.getElementById('shiftA'); let shift2=document.getElementById('shiftB'); let shift3=document.getElementById('shiftC'); function shifts(){ if(shift1.checked){availableShift.push(shift1.name);} if(shift2.checked){availableShift.push(shift2.name);} if(shift3.checked){availableShift.push(shift3.name);} return availableShift; } function setFormData(){ localStorage.setItem('formData',JSON.stringify(arrOfObjects1)); } let inputV='1234'; function submitButton (event){ event.preventDefault(); let naji=craftEl.value; // console.log(naji); if( inputV === verify.value){ // alert('your form submit '); // new Request(name1.value,contact1.value,email1.value,address1.value,city1.value,reach1.value,category1.value,discription1.value,date1.value,mincost1.value,maxcost1.value); new ProviderServiceForm (uname.value,contact.value,emailEl.value,addressEl.value,selectCity.value,craftEl.value,contractEl.value); confirm ('Thank you, we have received your information and it is being processed'); if(arrOfObjects1){buttonEl2.hidden=false;} buttonEl.removeEventListener('click',submitButton); }else{ alert('please try again '); } } buttonEl.addEventListener('click',submitButton); function render (renderedObj){ let fieldsetEl=document.createElement('fieldset'); divEl.appendChild(fieldsetEl); let ulEl =document.createElement('ul'); fieldsetEl.appendChild(ulEl); let liEln=document.createElement('li'); ulEl.appendChild(liEln); liEln.textContent= `Service Provider Craft: ${renderedObj.craft}`; let liEl=document.createElement('li'); ulEl.appendChild(liEl); liEl.textContent=`Service Provider Name: ${renderedObj.name}`; let liEl2=document.createElement('li'); ulEl.appendChild(liEl2); liEl2.textContent=`Service Provider Contact Number: ${renderedObj.contact}`; let liEl3=document.createElement('li'); ulEl.appendChild(liEl3); liEl3.textContent=`Service Provider Email: ${renderedObj.email}`; let liEl4=document.createElement('li'); ulEl.appendChild(liEl4); liEl4.textContent=`Service Provider City: ${renderedObj.city}`; let liEl5=document.createElement('li'); ulEl.appendChild(liEl5); liEl5.textContent=`Service Provider Contract${renderedObj.contract}`; let liEl6=document.createElement('li'); ulEl.appendChild(liEl6); //here is bug !!!! liEl6.textContent=` Service Provider Day Availability: ${availableDayes}`; let liEl7=document.createElement('li'); ulEl.appendChild(liEl7); liEl7.textContent=`Service Provider Shift Availability: ${availableShift}`; } ////////////////////render function (outter loop)//////////////////// function render1(renderdobj){ let fieldsetEl =document.createElement('fieldset'); divEl.appendChild(fieldsetEl); let ulEl =document.createElement('ul'); fieldsetEl.appendChild(ulEl); let liElm=document.createElement('li'); ulEl.appendChild(liElm); liElm.textContent=`Maintenance Request Gategory: ${renderdobj.category}`; let liEl=document.createElement('li'); ulEl.appendChild(liEl); liEl.textContent=`Homeowner Name: ${renderdobj.name}`; let liEl1=document.createElement('li'); ulEl.appendChild(liEl1); liEl1.textContent=`Contact Number: ${renderdobj.contact}`; let liEl2=document.createElement('li'); ulEl.appendChild(liEl2); liEl2.textContent=`Email: ${renderdobj.email}`; let liEl3=document.createElement('li'); ulEl.appendChild(liEl3); liEl3.textContent=`Address: ${renderdobj.address}`; let liEl4=document.createElement('li'); ulEl.appendChild(liEl4); liEl4.textContent=`City: ${renderdobj.city}`; let liEl5=document.createElement('li'); ulEl.appendChild(liEl5); liEl5.textContent=`How did your hear about us: ${renderdobj.reach}`; let liEl6=document.createElement('li'); ulEl.appendChild(liEl6); liEl6.textContent=`Maintenance Discription: ${renderdobj.discription}`; let liEl9=document.createElement('li'); ulEl.appendChild(liEl9); liEl9.textContent=`Maintenance Appointment Date: ${renderdobj.date}`; let liEl7=document.createElement('li'); ulEl.appendChild(liEl7); liEl7.textContent=`Minimum Cost: ${renderdobj.minCost}`; let liEl8=document.createElement('li'); ulEl.appendChild(liEl8); liEl8.textContent=`Maximum Cost: ${renderdobj.maxCost}`; } /////////////Show Button Clicking///////// function showButton(event){ event.preventDefault(); getFromLocalStorage();//request getFormData ();//provider // Nested loops for Complex rendering: Calling render request in the inner loop for(let i=0 ; i<arrOfObjects1.length ;i++){ render(arrOfObjects1[i]);//Render Provider for(let j=0; j<getdata.length;j++){ console.log('for :'+ arrOfObjects1[i].craft + ' n ' +getdata[j].category);/////// if(arrOfObjects1[i].craft===getdata[j].category)// checking category===?craft render1(getdata[j]);// Rendering Request } } buttonEl2.removeEventListener('click',showButton); } /////////////B2 Event Listener//////////// buttonEl2.addEventListener('click',showButton); //////////Get form Local Storage provider//////////// function getFormData () { arrOfObjects1 = JSON.parse(localStorage.getItem('formData')); } ///////////////////get from local storage function Request////////////////////// let getdata; function getFromLocalStorage(){ getdata=JSON.parse(localStorage.getItem('RequestData')); } } <file_sep># home-maintenance-hub ## Home Maintenance Hub Project **Discription:** In this project, we develop a website for connecting both _Users_ (i.e., users seeking some sort of home maintenance services) and _Service Providers_ (e.g., Electricians, Plumbers, Carpenters, etc.). Users can post their requests, providing a discription of the problem they have, the category of service they are seeking, emergancy level of the problem, price range, location, contact, etc. Maenwhile, service providers can navigate and review users requests, then offer their services upon acceptance and availabelity, or can reply to users requests a suggestion on how to fix the problem if the emergancy level is not high. The website will be developed using _HTML_, _Javascrip_t and _CSS_. This project is going to be developed by the following members using _GitHub_ for deployment and for version control using _Git_. **Authers (Team Members):** - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> (_Team Leader_) **Roles:** - Duha Alazzam (Styling the website using css) - <NAME> (Styling the website using css) - <NAME> (Working on Javascript, Colors and Theme) - <NAME> (Working on Javascript, General Assistant) - <NAME> (Team Leader, Help Working on Javascript, Help Styling the website using css, Creating the HTML docs, Content Editor, General Assistant)
ad68583d0770b60fbbc1daae4494a4e5c9b93d05
[ "JavaScript", "Markdown" ]
2
JavaScript
coding-geeks-team/home-maintenance-hub
0fbb4d934491799220634cf585166ccd281d96da
20d8ef9ba7614be700141ea19420a19dcdf6b934
refs/heads/master
<file_sep>// // ViewController.swift // Handshake // // Created by <NAME> on 10/10/15. // Copyright © 2015 Prodigies. All rights reserved. // import UIKit import Parse import CoreBluetooth import KVNProgress import WatchConnectivity import SDWebImage class HomeViewController: UIViewController, CBPeripheralManagerDelegate, CLLocationManagerDelegate, WCSessionDelegate { // MARK: - Properties @IBOutlet weak var userLabel: UILabel! /* ### iBeacon ### */ // Will contain all the people around you, if any are around you var peopleNearby: [CLBeacon] = [] // Manages device (peripheral) as iBeacon var peripheralManager: CBPeripheralManager? // Manages device's location var locationManager: CLLocationManager? // The last/nearest beacon var lastProximity: CLProximity? // Payload of data the phone emits as a beacon var beaconPeripheralData: NSDictionary? // The person who's hand you just Suge Night var nearestBeacon: CLBeacon! // The dictionary containing the user's info who you just shook hands with var nameWithImageDictionary: [String:AnyObject]! // A boolean that will notify you if the dictionary has been filled var haveFormattedDictionary: Bool! // A boolean that will notify you if you have exited the region var haveExitedRegion: Bool! // MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. haveFormattedDictionary = false haveExitedRegion = false (UIApplication.sharedApplication().delegate as! AppDelegate).homeVC = self // Should never be nil here let currentUser = PFUser.currentUser()! userLabel.text = "Hey \(currentUser.username!)!\n\n Go meet some people 👫" // Get the minor value from the cached user let minorNSNumber = currentUser["minor"] as! NSNumber let minor = UInt16(minorNSNumber.intValue) // Set up this phone to detect other beacons detectOtherBeacons() // Set up this phone as an ibeacon phoneAsBeacon(0, minor: minor, identifier: "A handshake") // if (WCSession.isSupported()) { // let session = WCSession.defaultSession() // session.delegate = self // conforms to WCSessionDelegate // session.activateSession() // } } override func viewWillAppear(animated: Bool) { (UIApplication.sharedApplication().delegate as! AppDelegate).homeVC = self // Dismiss progress view if KVNProgress.isVisible() { KVNProgress.dismiss() } } // MARK: - Initialization // Set up phone as beacon func phoneAsBeacon(major: UInt16, minor: UInt16, identifier: String) { // --- Initialize your phone as a beacon --- // 1) Instantiate UUID // app uuid - EC36069A-8377-438E-B02F-9A9E78BD6089 (created using uuidgen on the command line) let proximityUUID = NSUUID(UUIDString:"EC36069A-8377-438E-B02F-9A9E78BD6089") // 2) Set up the beacon region let phoneBeaconRegion: CLBeaconRegion = CLBeaconRegion(proximityUUID: proximityUUID!, major: major, minor: minor, identifier: identifier) // 3) Create dictionary of data to be shared across the BlueToothLE signal // Create a dictionary of advertisement data. self.beaconPeripheralData = phoneBeaconRegion.peripheralDataWithMeasuredPower(nil) // 4) Start advertising this phone's data // Create the peripheral manager. let me = self as NSObject self.peripheralManager = CBPeripheralManager(delegate: (me as! CBPeripheralManagerDelegate), queue: nil, options: nil) // Start advertising your beacon's data. self.peripheralManager!.startAdvertising((self.beaconPeripheralData! as! [String : AnyObject])) } // Function to detect other phones as iBeacons with a specific uuid func detectOtherBeacons() { // DETECTS OTHER BEACONS let uuidString = "EC36069A-8377-438E-B02F-9A9E78BD6089" let beaconIdentifier = "A handshake" let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString)! let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier) locationManager = CLLocationManager() if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) { locationManager!.requestAlwaysAuthorization() //println("Registered location permissions") } else { //println("Did not get location permissions") } locationManager!.delegate = self as CLLocationManagerDelegate locationManager!.pausesLocationUpdatesAutomatically = false locationManager!.startMonitoringForRegion(beaconRegion) locationManager!.startRangingBeaconsInRegion(beaconRegion) locationManager!.startUpdatingLocation() } // MARK: - CLLocationManagerDelegate Protocol func peripheralManagerIsReadyToUpdateSubscribers() { print("peripheral manager is ready to update subscribers") } func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) { if(beacons.count > 0) { print("Found someone by you") nearestBeacon = beacons[0] self.userLabel.text = "About to send local notification" // Send local notification, or send remote from parse let nameReminder = UILocalNotification() nameReminder.userInfo = nameWithImageDictionary UIApplication.sharedApplication().scheduleLocalNotification(nameReminder) switch nearestBeacon.proximity { case CLProximity.Immediate: print("Immediate range") //userLabel.text = "PERSON BY YOU IMMEDIATE!!" case CLProximity.Near: print("Near you") case CLProximity.Far: print("Far!!") //if haveFormattedDictionary! == true //{ //} default: break } } else { // Reset //self.nearestBeacon = CLBeacon() } } func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { manager.startRangingBeaconsInRegion(region as! CLBeaconRegion) manager.startUpdatingLocation() NSLog("You entered the region") //sendLocalNotificationWithMessage("You entered the region") } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { manager.stopRangingBeaconsInRegion(region as! CLBeaconRegion) manager.stopUpdatingLocation() // Send notification to phone now //self.sendShakerDataToWatch(self.nameWithImageDictionary) // // Pray the query finishes in time // //self.haveExitedRegion = true // // NSLog("You exited the region") // // // Send with the actual data // sendLocalNotificationWithMessage("You exited the region") } // MARK: - CBPeripheralManagerDelegate Protocol func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { if (peripheral.state == CBPeripheralManagerState.PoweredOn) { //println("Powered On") self.peripheralManager!.startAdvertising((self.beaconPeripheralData! as! [String : AnyObject])) } else if (peripheral.state == CBPeripheralManagerState.PoweredOff) { //println("Powered Off") self.peripheralManager!.stopAdvertising() } } // MARK: - Message Passing/Receiving To Watch func sendShakerDataToWatch(data: [String:AnyObject]) { // check the reachablity if WCSession.defaultSession().reachable == false { let alert = UIAlertController( title: "Failed to send", message: "Apple Watch is not reachable.", preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction( title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) return } print("Sending message to watch") // Send this message to the watch WCSession.defaultSession().sendMessage( data, replyHandler: { (replyMessage) -> Void in }) { (error) -> Void in print(error) } } func queryParseForShaker() { //print("Fuckk") } // MARK: - Utils func sendLocalNotificationWithMessage(message: String!) { let notification:UILocalNotification = UILocalNotification() notification.alertBody = message UIApplication.sharedApplication().scheduleLocalNotification(notification) } }<file_sep>// // Handshake-Bridging-Header.h // Handshake // // Created by <NAME> on 10/10/15. // Copyright © 2015 Prodigies. All rights reserved. // #ifndef Handshake_Bridging_Header_h #define Handshake_Bridging_Header_h // Parse //#import <Parse/Parse.h> // //// Custom Progess View //#import <KVNProgress/KVNProgress.h> //#import <SVProgressHUD/SVProgressHUD.h> //#import <SDWebImage/UIImageView+WebCache.h> #endif /* Handshake_Bridging_Header_h */ <file_sep># handshake Cal Hacks '15 UC Davis iBeacon Links: http://blog.passkit.com/configure-iphone-ibeacon-transmitter/ https://developer.apple.com/ibeacon/ https://www.bignerdranch.com/blog/watchkit-2-hardware-bits-the-accelerometer/ Core Data: http://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial Contacts: https://developer.apple.com/library/ios/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Chapters/DirectInteraction.html#//apple_ref/doc/uid/TP40007744-CH6-SW1 http://www.appcoda.com/ios-contacts-framework/ Core Motion (Accelerometer): https://developer.apple.com/library/prerelease/watchos/documentation/CoreMotion/Reference/CoreMotion_Reference/index.html#//apple_ref/doc/uid/TP40009686 Watch: http://nshipster.com/watchkit/ Watch orientation must be set to Right Wrist, Digital Crown on right side Camera: http://www.appcoda.com/ios-programming-camera-iphone-app/ <file_sep>// // ViewController.swift // Handshake // // Created by <NAME> on 10/10/15. // Copyright © 2015 Prodigies. All rights reserved. // import UIKit import Parse import CoreBluetooth import KVNProgress class HomeViewController: UIViewController, CBPeripheralManagerDelegate, CLLocationManagerDelegate { // MARK: - Properties @IBOutlet weak var userLabel: UILabel! /* ### iBeacon ### */ // Will contain all the people around you, if any are around you var peopleNearby: [CLBeacon] = [] // Manages device (peripheral) as iBeacon var peripheralManager: CBPeripheralManager? // Manages device's location var locationManager: CLLocationManager? // The last/nearest beacon var lastProximity: CLProximity? // Payload of data the phone emits as a beacon var beaconPeripheralData: NSDictionary? // MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Should never be nil here let currentUser = PFUser.currentUser()! userLabel.text = currentUser.username // Get the minor value from the cached user let minorNSNumber = currentUser["minor"] as! NSNumber let minor = UInt16(minorNSNumber.intValue) // Set up this phone as an ibeacon //phoneAsBeacon(0, minor: minor, identifier: "A handshake") detectOtherBeacons() } override func viewWillAppear(animated: Bool) { // Dismiss progress view if KVNProgress.isVisible() { KVNProgress.dismiss() } } // MARK: - Initialization // Set up phone as beacon func phoneAsBeacon(major: UInt16, minor: UInt16, identifier: String) { // --- Initialize your phone as a beacon --- // 1) Instantiate UUID // app uuid - EC36069A-8377-438E-B02F-9A9E78BD6089 (created using uuidgen on the command line) let proximityUUID = NSUUID(UUIDString:"EC36069A-8377-438E-B02F-9A9E78BD6089") // 2) Set up the beacon region let phoneBeaconRegion: CLBeaconRegion = CLBeaconRegion(proximityUUID: proximityUUID!, major: major, minor: minor, identifier: identifier) // 3) Create dictionary of data to be shared across the BlueToothLE signal // Create a dictionary of advertisement data. self.beaconPeripheralData = phoneBeaconRegion.peripheralDataWithMeasuredPower(nil) // 4) Start advertising this phone's data // Create the peripheral manager. let me = self as NSObject self.peripheralManager = CBPeripheralManager(delegate: (me as! CBPeripheralManagerDelegate), queue: nil, options: nil) // Start advertising your beacon's data. self.peripheralManager!.startAdvertising((self.beaconPeripheralData! as! [String : AnyObject])) } // Function to detect other phones as iBeacons with a specific uuid func detectOtherBeacons() { // DETECTS OTHER BEACONS let uuidString = "EC36069A-8377-438E-B02F-9A9E78BD6089" let beaconIdentifier = "A handshake" let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString)! let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier) locationManager = CLLocationManager() if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) { locationManager!.requestAlwaysAuthorization() //println("Registered location permissions") } else { //println("Did not get location permissions") } locationManager!.delegate = self as CLLocationManagerDelegate locationManager!.pausesLocationUpdatesAutomatically = false locationManager!.startMonitoringForRegion(beaconRegion) locationManager!.startRangingBeaconsInRegion(beaconRegion) locationManager!.startUpdatingLocation() } // MARK: - CLLocationManagerDelegate Protocol func peripheralManagerIsReadyToUpdateSubscribers() { print("peripheral manager is ready to update subscribers") } func sendLocalNotificationWithMessage(message: String!) { let notification:UILocalNotification = UILocalNotification() notification.alertBody = message UIApplication.sharedApplication().scheduleLocalNotification(notification) } func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) { //NSLog("didRangeBeacons"); //var message:String = "" print("Beacons count: \(beacons.count)") if(beacons.count > 0) { // Pass beacons to home screen self.peopleNearby = beacons let nearestBeacon:CLBeacon = beacons[0] if(nearestBeacon.proximity == lastProximity || nearestBeacon.proximity == CLProximity.Unknown) { return; } lastProximity = nearestBeacon.proximity; if nearestBeacon.proximity == CLProximity.Immediate { } var ids = [NSNumber]() for beacon: CLBeacon in beacons { ids.append(beacon.minor) } let query = PFQuery(className: "_User") query.whereKey("minor", containedIn: ids) query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if error == nil { for object in objects! { let shakerName = object["minor"] as! String print("You are nearby \(shakerName)!!!") } } else { print("Error querying for beacon minor with error: \(error!.description)") } } // switch nearestBeacon.proximity { // case CLProximity.Far: // message = "You are far away from the beacon" // case CLProximity.Near: // message = "You are near the beacon" // case CLProximity.Immediate: // message = "You are within range to P.I.N.G."} //case CLProximity.Unknown: // return // } else { // message = "No beacons are nearby" } else { // Stop glowing of the beacon button, need to check if animation exists before?? // if beaconsButton.layer.animationKeys().count > 0 // { // beaconsButton.layer.removeAllAnimations() // // } // Clear array self.peopleNearby = [] //message = "No beacons nearby" } //NSLog("%@", message) //sendLocalNotificationWithMessage(message) } func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { manager.startRangingBeaconsInRegion(region as! CLBeaconRegion) manager.startUpdatingLocation() NSLog("You entered the region") //sendLocalNotificationWithMessage("You entered the region") } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { manager.stopRangingBeaconsInRegion(region as! CLBeaconRegion) manager.stopUpdatingLocation() // Send notification to phone now // NSLog("You exited the region") // sendLocalNotificationWithMessage("You exited the region") } // MARK: - CBPeripheralManagerDelegate Protocol func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { if (peripheral.state == CBPeripheralManagerState.PoweredOn) { //println("Powered On") self.peripheralManager!.startAdvertising((self.beaconPeripheralData! as! [String : AnyObject])) } else if (peripheral.state == CBPeripheralManagerState.PoweredOff) { //println("Powered Off") self.peripheralManager!.stopAdvertising() } } } <file_sep>// // InterfaceController.swift // Handshake WatchKit Extension // // Created by <NAME> on 10/10/15. // Copyright © 2015 Prodigies. All rights reserved. // import WatchKit import Foundation import CoreMotion import WatchConnectivity class InterfaceController: WKInterfaceController, WCSessionDelegate { let motionManager = CMMotionManager() var pushSent = false @IBOutlet var resetButton: WKInterfaceButton! // MARK: - Accelerometer Code override func willActivate() { super.willActivate() // DO NOT RESET if (motionManager.accelerometerAvailable == true) { let handler:CMAccelerometerHandler = {(data: CMAccelerometerData?, error: NSError?) -> Void in self.resetButton.setBackgroundColor(UIColor.clearColor()) let currentNumber = ((NSString(format: "%.5f", data!.acceleration.x)).doubleValue * 100) if currentNumber < 10 && !self.pushSent { // Send notification to watch to look up minor from Parse print(currentNumber) print("sending push") let message = ["request": "fireLocalNotification"] WCSession.defaultSession().sendMessage( message, replyHandler: { (replyMessage) -> Void in }) { (error) -> Void in print(error.localizedDescription) } self.pushSent = true } // } else if currentNumber > 60 && self.pushSent { // print(currentNumber) // print("resetting push") // self.pushSent = false // } } motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: handler) } else { print("Accelerometer not available") } } override func didDeactivate() { super.didDeactivate() motionManager.stopAccelerometerUpdates() } // MARK: - Message Passing Code override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Activate the session on both sides to enable communication. if (WCSession.isSupported()) { let session = WCSession.defaultSession() session.delegate = self // conforms to WCSessionDelegate session.activateSession() } motionManager.accelerometerUpdateInterval = 0.1 // Configure interface objects here. } // Received message from iPhone func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { let shakerName = message["name"] print(__FUNCTION__) guard message["request"] as? String == "showAlert" else {return} let defaultAction = WKAlertAction( title: "Save Contact", style: WKAlertActionStyle.Default) { () -> Void in } let actions = [defaultAction] self.presentAlertControllerWithTitle( "\(shakerName)", message: "", preferredStyle: WKAlertControllerStyle.SideBySideButtonsAlert, actions: actions) } // MARK: - Actions @IBAction func reset() { resetButton.setBackgroundColor(UIColor.redColor()) self.pushSent = false } } <file_sep>// // NotificationController.swift // Handshake WatchKit Extension // // Created by <NAME> on 10/10/15. // Copyright © 2015 Prodigies. All rights reserved. // import WatchKit import Foundation class NotificationController: WKUserNotificationInterfaceController { @IBOutlet var shakerName: WKInterfaceLabel! @IBOutlet var shakerPic: WKInterfaceImage! override init() { // Initialize variables here. super.init() shakerName.setText("<NAME>") shakerPic.setImage(UIImage(named: "mattCrop")) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func didReceiveLocalNotification(localNotification: UILocalNotification, withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) { // This method is called when a local notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification interface as quickly as possible. let shakerData = localNotification.userInfo! let shakerImageData = shakerData["image"] as! NSData self.shakerPic.setImage(UIImage(data: shakerImageData)) self.shakerName.setText(shakerData["name"] as? String) print("\(localNotification)") // After populating your dynamic notification interface call the completion block. completionHandler(.Custom) } /* override func didReceiveRemoteNotification(remoteNotification: [NSObject : AnyObject], withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) { // This method is called when a remote notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification interface as quickly as possible. // // After populating your dynamic notification interface call the completion block. completionHandler(.Custom) } */ } <file_sep>#!/bin/sh "${SRCROOT}/Pods/Target Support Files/Pods-Handshake/Pods-Handshake-resources.sh" <file_sep>// // AppDelegate.swift // Handshake // // Created by <NAME> on 10/10/15. // Copyright © 2015 Prodigies. All rights reserved. // import UIKit import Parse import WatchConnectivity import SDWebImage @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate { var window: UIWindow? var homeVC = HomeViewController() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Parse.enableLocalDatastore() Parse.setApplicationId("BZgVVYapIDNl3kVbOg0nY7UgHs8wfGGjGavd2zL6", clientKey: "<KEY>") // Override point for customization after application launch. let settings = UIUserNotificationSettings( forTypes: [.Badge, .Sound, .Alert], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) if (WCSession.isSupported()) { let session = WCSession.defaultSession() session.delegate = self // conforms to WCSessionDelegate session.activateSession() } if(application.respondsToSelector("registerUserNotificationSettings:")) { application.registerUserNotificationSettings( UIUserNotificationSettings( forTypes: [.Alert, .Sound], categories: nil) ) } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func sessionWatchStateDidChange(session: WCSession) { print(__FUNCTION__) print(session) print("reachable:\(session.reachable)") } func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { // Tell the home view controller to query for the data print(__FUNCTION__) guard message["request"] as? String == "fireLocalNotification" else {return} let query = PFQuery(className: "_User") print("Querying parse for shaker") homeVC.userLabel.text = "About to send local notification" query.whereKey("minor", equalTo: homeVC.nearestBeacon.minor) query.getFirstObjectInBackgroundWithBlock { (object: PFObject?, error: NSError?) -> Void in if error == nil { let shakerName = (object! as! PFUser).username! print("Shaker's name is \(shakerName)") let shakerPicURL = NSURL(string: (object!["imageAsPFFile"] as! PFFile).url!) let manager = SDWebImageManager.sharedManager() manager.downloadImageWithURL(shakerPicURL, options: [], progress: nil) { (image: UIImage?, error: NSError?, cacheType: SDImageCacheType, finished: Bool, imageURL: NSURL?) -> Void in // --- Send data to watch once request completes --- let imageAsData = UIImageJPEGRepresentation(image!, 0.5)! self.homeVC.nameWithImageDictionary = ["name" : shakerName, "image" : imageAsData] self.homeVC.haveFormattedDictionary = true self.homeVC.userLabel.text = "Query completed" } } else { print("Error query for minor value on line \(__LINE__) with error: \(error!.description)") } } let localNotification = UILocalNotification() localNotification.alertBody = "Handshake Executed" localNotification.fireDate = NSDate() localNotification.soundName = UILocalNotificationDefaultSoundName; UIApplication.sharedApplication().scheduleLocalNotification(localNotification) self.homeVC.queryParseForShaker() } } <file_sep># Uncomment this line to define a global platform for your project platform :ios, '8.0' # Uncomment this line if you're using Swift use_frameworks! target 'Handshake' do pod 'KVNProgress' pod 'SVProgressHUD' pod 'Parse' pod 'SDWebImage', '~>3.7' end target 'Handshake WatchKit App' do end target 'Handshake WatchKit Extension' do end
9fda613d0ece47e48a089c0507278429da3f28c1
[ "Ruby", "Swift", "Markdown", "C", "Shell" ]
9
Swift
mattgabor/handshake
6edecb173b9a29791cd5f00c385f0e660ba88741
54cc84c425c2addcbf84481dd80b9bb67e296916
refs/heads/master
<file_sep>import org.testng.annotations.Test; import pages.CartPopupPage; import pages.MainPage; import pages.ProductPage; import pages.ShopPage; public class WixTestCase extends BaseTest { @Test public void testWixShop() { MainPage mainPage = new MainPage(driver); ShopPage shopPage = mainPage .openBaseURL() .clickShopButton(); ProductPage productPage = shopPage .switchIntoShopFrame() .clickOnItemWithName("Premium Glasses"); CartPopupPage cartPopupPage = productPage .switchIntoProductFrame() .clickAddToCartButton(); cartPopupPage .switchIntoCartPopupFrame() .removeItemFromCartPopup(0) .closePopup(); productPage .switchIntoProductFrame() .clickAddToCartButton(); cartPopupPage .switchIntoCartPopupFrame() .closePopup(); productPage .switchIntoProductFrame() .clickStoresButton(); shopPage .switchIntoCartWidgetFrame() .clickOnCartWidgetButton() .switchIntoCartPopupFrame() .closePopup(); shopPage .switchIntoShopFrame() .clickOnItemWithName("I\'m a product"); productPage .switchIntoProductFrame() .clickAddToCartButton(); cartPopupPage .switchIntoCartPopupFrame() .clickViewCart(); } } <file_sep>package utils; import io.github.bonigarcia.wdm.ChromeDriverManager; import io.github.bonigarcia.wdm.EdgeDriverManager; import io.github.bonigarcia.wdm.FirefoxDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import static org.openqa.selenium.remote.BrowserType.*; public class WebDriverFactory { private static String browserType = System.getProperty("browser", GOOGLECHROME); private static final long IMPLICIT_WAIT = 2; private static final long PAGE_WAIT = 30; private static final long SCRIPT_WAIT = 10; public static WebDriver setWebDriver() { WebDriver driver = null; switch (browserType) { case GOOGLECHROME: case CHROME: case "Chrome": ChromeDriverManager.getInstance().setup(); driver = new ChromeDriver(); break; case FIREFOX: case "Firefox": case "Mozilla": FirefoxDriverManager.getInstance().setup(); driver = new FirefoxDriver(); break; case EDGE: case "Edge": case "edge": EdgeDriverManager.getInstance().setup(); driver = new EdgeDriver(); break; } if (driver != null) { driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(PAGE_WAIT, TimeUnit.SECONDS); driver.manage().timeouts().setScriptTimeout(SCRIPT_WAIT, TimeUnit.SECONDS); } return driver; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wix</groupId> <artifactId>automation_test_task</artifactId> <version>1.0-SNAPSHOT</version> <name>java_automation</name> <url>https://georgel8.wixsite.com/ait-ht</url> <developers> <developer> <id>artemmlg</id> <name><NAME></name> </developer> </developers> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <testNG_version>6.11</testNG_version> <selenium_version>3.9.1</selenium_version> <webdrivermanager_version>2.1.0</webdrivermanager_version> </properties> <dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testNG_version}</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>${selenium_version}</version> </dependency> <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>${webdrivermanager_version}</version> </dependency> </dependencies> </project><file_sep>package pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class MainPage extends BasePage { public MainPage(WebDriver driver) { super(driver); } @FindBy(xpath = ".//*[@id='comp-jhalo8eilink']") private WebElement shopBtn; public MainPage openBaseURL() { driver.get("https://georgel8.wixsite.com/ait-ht"); return this; } public ShopPage clickShopButton() { shopBtn.click(); return new ShopPage(driver); } }
c044bce6b70859fc26b74e836ac2dac0795d571c
[ "Java", "Maven POM" ]
4
Java
artmlg/WIX_Automation_Task
44a2e123b92e7cfe959ef9fa621dcd915ca7bbb3
17dedff2fcd183b951741d98a93833f25d1912ae
refs/heads/master
<file_sep>/* * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.ready.spi; import org.opendaylight.infrautils.ready.SystemReadyMonitorMXBean; import org.opendaylight.infrautils.ready.SystemState; /** * SystemReadyMonitorMXBean implementation. * * @author <NAME>, based on code by Faseela originally in KarafSystemReady */ public class DelegatingSystemReadyMonitorMXBean extends AbstractMXBean implements SystemReadyMonitorMXBean { private static final String JMX_OBJECT_NAME = "SystemState"; private static final String MBEAN_TYPE = "ready"; private final SystemReadyMonitorMXBean delegate; public DelegatingSystemReadyMonitorMXBean(SystemReadyMonitorMXBean delegate) { super(JMX_OBJECT_NAME, MBEAN_TYPE, null); this.delegate = delegate; } @Override public SystemState getSystemState() { return delegate.getSystemState(); } @Override public String getFailureCause() { return delegate.getFailureCause(); } } <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus; import java.util.Collection; /** * DiagStatus ServiceDescriptor which lets users register/retrieve for particular service status details. * * <p>The term "service" in this context refers to a "higher-level functional service", not an OSGi Service interface. * (It could map to an OSGi service interface, or several of them, or none.) * * <p>Implementations of this interface are expected to be thread-safe. * * @author <NAME> * @author <NAME> */ public interface DiagStatusService { /** * Register a service for status monitoring. * * @param serviceIdentifier * unique identifier for the service being registered * * @return Registration status */ ServiceRegistration register(String serviceIdentifier); /** * Retrieve the status of a service specified by the identifier. * * @param serviceIdentifier * unique identifier for a service */ ServiceDescriptor getServiceDescriptor(String serviceIdentifier); /** * Retrieve the status of all services registered so far. * * @return status set for all registered services */ Collection<ServiceDescriptor> getAllServiceDescriptors(); /** * Retrieve the status of all services registered so far. * * @return status as a {@link ServiceStatusSummary} */ ServiceStatusSummary getServiceStatusSummary(); } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils; import com.google.errorprone.annotations.Var; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; /** * JUnit Rule which nicely separates {@literal @}Test/s in the log. * * <p> * Usage (NB the use of {@literal @}Rule instead of {@literal @}ClassRule): * * <pre> * public {@literal @}Rule LogRule logRule = new LogRule(); * * {@literal @}Test ... * </pre> * * @author <NAME> */ public class LogRule implements TestRule { private static final String HEADER = "-".repeat(120); private static final String MESSAGE = "{} ({}ms) @Test {}()"; private static final Marker MARKER = MarkerFactory.getMarker(LogRule.class.getName()); public static Marker getMarker() { return MARKER; } @Override // findbugs-slf4j does not understand that a static final String IS a Constant, so SLF4J_FORMAT_SHOULD_BE_CONST // findbugs-slf4j cannot understand what we are doing here with a Logger variable instead of class field, so: @SuppressFBWarnings({ "SLF4J_FORMAT_SHOULD_BE_CONST", "SLF4J_LOGGER_SHOULD_BE_PRIVATE" }) public Statement apply(Statement statement, Description description) { Logger testLog = LoggerFactory.getLogger(description.getTestClass()); return new Statement() { @Override @SuppressWarnings("checkstyle:IllegalCatch") @SuppressFBWarnings("SLF4J_FORMAT_SHOULD_BE_CONST") public void evaluate() throws Throwable { testLog.info(MARKER, HEADER); testLog.info(MARKER, "BEGIN @Test {}()", description.getMethodName()); long startTimeInMS = System.currentTimeMillis(); @Var Throwable caughtThrowable = null; try { statement.evaluate(); } catch (Throwable throwable) { caughtThrowable = throwable; throw throwable; } finally { long durationInMS = System.currentTimeMillis() - startTimeInMS; if (caughtThrowable == null) { testLog.info(MARKER, MESSAGE, "ENDED", durationInMS, description.getMethodName()); } else { testLog.error(MARKER, MESSAGE, "FAILED", durationInMS, description.getMethodName(), caughtThrowable); } } } }; } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.utils.concurrent; import static java.util.Objects.requireNonNull; import java.lang.Thread.UncaughtExceptionHandler; import org.slf4j.Logger; /** * Thread's UncaughtExceptionHandler which logs to slf4j. * * @author <NAME> */ public final class LoggingThreadUncaughtExceptionHandler implements UncaughtExceptionHandler { /** * Factory method to obtain an instance of this bound to the passed slf4j Logger. */ public static UncaughtExceptionHandler toLogger(Logger logger) { return new LoggingThreadUncaughtExceptionHandler(logger); } private final Logger logger; private LoggingThreadUncaughtExceptionHandler(Logger logger) { this.logger = requireNonNull(logger, "logger"); } @Override public void uncaughtException(Thread thread, Throwable throwable) { logger.error("Thread terminated due to uncaught exception: {}", thread.getName(), throwable); } } <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus.internal; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import com.google.common.net.InetAddresses; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.inject.Singleton; import javax.management.JMException; import org.apache.commons.lang3.StringUtils; import org.opendaylight.infrautils.diagstatus.ClusterMemberInfo; import org.opendaylight.infrautils.diagstatus.MBeanUtils; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of {@link ClusterMemberInfo} service using the JMX MBeans * exposed by Akka framework used in ODL controller. * * @author <NAME> * @author <NAME> converted former static utility to service (for testability) */ @Deprecated(forRemoval = true) @Singleton @Component(immediate = true) public final class ClusterMemberInfoImpl implements ClusterMemberInfo { private static final Logger LOG = LoggerFactory.getLogger(ClusterMemberInfoImpl.class); @Override public InetAddress getSelfAddress() { Object clusterStatusMBeanValue; try { clusterStatusMBeanValue = MBeanUtils.getMBeanAttribute("akka:type=Cluster", "ClusterStatus"); } catch (JMException e) { throw new IllegalStateException("getMBeanAttribute(\"akka:type=Cluster\", \"ClusterStatus\") failed", e); } checkState(clusterStatusMBeanValue != null, "getMBeanAttribute(\"akka:type=Cluster\", \"ClusterStatus\") == null?!"); String clusterStatusText = clusterStatusMBeanValue.toString(); String selfAddressMbean = requireNonNull(StringUtils.substringBetween(clusterStatusText, "\"self-address\": ", ","), "null substringBetween() for: " + clusterStatusText); return InetAddresses.forString(extractAddressFromAkka(selfAddressMbean)); } @Override public List<InetAddress> getClusterMembers() { Object clusterMemberMBeanValue; try { clusterMemberMBeanValue = MBeanUtils.getMBeanAttribute("akka:type=Cluster", "Members"); } catch (JMException e) { LOG.error("Problem to getMBeanAttribute(\"akka:type=Cluster\", \"Members\"); returning empty List", e); return List.of(); } if (clusterMemberMBeanValue == null) { return List.of(); } return Arrays.stream(((String)clusterMemberMBeanValue).split(",", -1)) .map(clusterMember -> InetAddresses.forString(extractAddressFromAkka(clusterMember))) .collect(Collectors.toUnmodifiableList()); } @Override public boolean isLocalAddress(InetAddress ipAddress) { return ipAddress.equals(InetAddress.getLoopbackAddress()) || ipAddress.equals(getSelfAddress()); } @Activate void activate() { LOG.info("ClusterMemberInfo activated"); } @Deactivate void deactivate() { LOG.info("ClusterMemberInfo deactivated"); } private static String extractAddressFromAkka(String clusterMember) { if (clusterMember.contains("@[")) { // IPv6 address return requireNonNull(StringUtils.substringBetween(clusterMember, "@[", "]"), "null substringBetween() for IPv6: " + clusterMember); } // IPv4 or hostname return requireNonNull(StringUtils.substringBetween(clusterMember, "@", ":"), "null substringBetween() for IPv4: " + clusterMember); } } <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.ready.spi; import com.google.errorprone.annotations.Var; import java.lang.management.ManagementFactory; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.ReflectionException; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is inspired from the original implementation in controller. * * @author <NAME> * @author <NAME> */ public abstract class AbstractMXBean { private static final Logger LOG = LoggerFactory.getLogger(AbstractMXBean.class); public static final String BASE_JMX_PREFIX = "org.opendaylight.infrautils:"; private final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); private final String mbeanName; private final String mbeanType; private final @Nullable String mbeanCategory; /** * Constructor. * * @param mbeanName Used as the <code>name</code> property in the bean's ObjectName. * @param mbeanType Used as the <code>type</code> property in the bean's ObjectName. * @param mbeanCategory Used as the <code>Category</code> property in the bean's ObjectName. */ protected AbstractMXBean(@NonNull String mbeanName, @NonNull String mbeanType, @Nullable String mbeanCategory) { this.mbeanName = mbeanName; this.mbeanType = mbeanType; this.mbeanCategory = mbeanCategory; } private ObjectName getMBeanObjectName() throws MalformedObjectNameException { StringBuilder builder = new StringBuilder(BASE_JMX_PREFIX) .append("type=").append(getMBeanType()); if (getMBeanCategory() != null) { builder.append(",Category=").append(getMBeanCategory()); } builder.append(",name=").append(getMBeanName()); return new ObjectName(builder.toString()); } /** * This method is a wrapper for registerMBean with void return type so it can be invoked by dependency * injection frameworks such as Spring and Blueprint. */ public void register() { registerMBean(); } /** * Registers this bean with the platform MBean server with the domain defined by * {@link #BASE_JMX_PREFIX}. * * @return true is successfully registered, false otherwise. */ public final boolean registerMBean() { @Var boolean registered = false; try { // Object to identify MBean ObjectName mbeanObjectName = this.getMBeanObjectName(); LOG.debug("Register MBean {}", mbeanObjectName); // unregistered if already registered if (server.isRegistered(mbeanObjectName)) { LOG.debug("MBean {} found to be already registered", mbeanObjectName); try { unregisterMBean(mbeanObjectName); } catch (MBeanRegistrationException | InstanceNotFoundException e) { LOG.warn("unregister mbean {} caused exception", mbeanObjectName, e); } } server.registerMBean(this, mbeanObjectName); registered = true; LOG.debug("MBean {} registered successfully", mbeanObjectName.getCanonicalName()); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | MalformedObjectNameException e) { LOG.error("MBean {} registration failed", mbeanName, e); } return registered; } /** * This method is a wrapper for unregisterMBean with void return type so it can be invoked by dependency * injection frameworks such as Spring and Blueprint. */ public void unregister() { unregisterMBean(); } /** * Unregisters this bean with the platform MBean server. * * @return true is successfully unregistered, false otherwise. */ public boolean unregisterMBean() { @Var boolean unregister = false; @Var ObjectName mbeanobjectname = null; try { mbeanobjectname = this.getMBeanObjectName(); unregisterMBean(mbeanobjectname); unregister = true; } catch (InstanceNotFoundException | MBeanRegistrationException | MalformedObjectNameException e) { LOG.debug("Failed when unregistering MBean {}", mbeanobjectname, e); } return unregister; } private void unregisterMBean(ObjectName mbeanObjectName) throws MBeanRegistrationException, InstanceNotFoundException { server.unregisterMBean(mbeanObjectName); } /** * invoke an mbean function with the platform MBean server. * * @return Object if successfully executed, "" otherwise. */ public Object invokeMBeanFunction(String functionName) { @Var Object result = ""; @Var ObjectName objectName = null; try { objectName = this.getMBeanObjectName(); MBeanServer mplatformMbeanServer = ManagementFactory.getPlatformMBeanServer(); result = mplatformMbeanServer.invoke(objectName, functionName, null, null); } catch (InstanceNotFoundException | MBeanException | ReflectionException | MalformedObjectNameException e) { LOG.error("Failed when executing MBean function {} in {}", functionName, objectName, e); } return result; } /** * Read an mbean attribute from the platform MBean server. * * @return Object if successfully executed, "" otherwise. */ public Object readMBeanAttribute(String attribute) { @Var Object attributeObj = ""; @Var ObjectName objectName = null; try { objectName = this.getMBeanObjectName(); MBeanServer platformMbeanServer = ManagementFactory.getPlatformMBeanServer(); attributeObj = platformMbeanServer.getAttribute(objectName, attribute); } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException | MalformedObjectNameException e) { LOG.info("Failed when reading MBean attribute {} from {}", attribute, objectName, e); } return attributeObj; } /** * Returns the <code>name</code> property of the bean's ObjectName. */ public String getMBeanName() { return mbeanName; } /** * Returns the <code>type</code> property of the bean's ObjectName. */ public String getMBeanType() { return mbeanType; } /** * Returns the <code>Category</code> property of the bean's ObjectName. */ public @Nullable String getMBeanCategory() { return mbeanCategory; } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.opendaylight.infrautils.testutils.LogCaptureRule; import org.opendaylight.infrautils.testutils.LogRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit test, and example, of how to use the {@link LogCaptureRule}. * * @author <NAME> */ public class LogCaptureRuleTest { private static final Logger LOG = LoggerFactory.getLogger(LogCaptureRuleTest.class); @Rule public LogRule logRule = new LogRule(); @Rule public LogCaptureRule logCaptureRule = new LogCaptureRule(); @Test // (expected = LogCaptureRuleException.class) @Ignore // because expected does not work, because that can't handle what's from a Rule public void logUnexpectedError() { LOG.error("boum", new IllegalStateException("unexpected")); } @Test @Ignore // as above // NB: The LogCaptureRuleException thrown by this includes "bam!" (as Suppressed) // and does not have "FAILED @Test logUnexpectedErrorAndThrow" (from LogRule) as message public void logUnexpectedErrorAndThrow() throws Exception { LOG.error("boum", new IllegalStateException("unexpected")); throw new Exception("bam!", new IllegalArgumentException("bad")); } @Test public void logError() { logCaptureRule.expectError("boum"); LOG.error("boum"); } @Test public void logTwoErrors() { logCaptureRule.expectError("boum", 1); LOG.error("boum"); LOG.error("bam"); } @Test public void logErrorWithException() { Exception ko = new IllegalArgumentException("KO"); logCaptureRule.expectError("boum"); LOG.error("boum", ko); assertEquals(ko, logCaptureRule.getLastErrorThrowable()); } @Test public void logErrorWithOneMessageFormatArgument() { logCaptureRule.expectError("bada boum"); LOG.error("{} boum", "bada"); } @Test public void logErrorWithTwoMessageFormatArguments() { logCaptureRule.expectError("bada boum kadum"); LOG.error("{} boum {}", "bada", "kadum"); } @Test public void logErrorWithThreeMessageFormatArguments() { logCaptureRule.expectError("bada boum kadum tabam"); LOG.error("{} boum {} {}", "bada", "kadum", "tabam"); } @Test public void logErrorExpectContaining() { logCaptureRule.expectLastErrorMessageContains("kadum"); LOG.error("{} boum {} {}", "bada", "kadum", "tabam"); } @Test public void logErrorExpectAnyError() { logCaptureRule.handleErrorLogs(logCaptures -> { }); LOG.error("boum"); } @Test public void logErrorExpectWithSpecificMatcher() { Exception ko = new IllegalArgumentException("KO"); logCaptureRule.handleErrorLogs(logCaptures -> { assertEquals(1, logCaptures.size()); var first = logCaptures.get(0); assertEquals("boum", first.getMessage()); assertSame(ko, first.getCause().orElseThrow()); }); LOG.error("boum", ko); assertSame(ko, logCaptureRule.getLastErrorThrowable()); } // TODO logErrorInBackgroundThread @Test public void logInfo() { LOG.info("FYI"); } @Test public void noLog() { // all good, LogCaptureRule should do nothing in this case } } <file_sep>InfraUtils Design Specifications ================================ Starting from Carbon, InfraUtils project uses RST format Design Specification document for all new features. These specifications are perfect way to understand various InfraUtils features. Contents: .. toctree:: :maxdepth: 1 Design Specification Template <specs-template> status-and-diagnostics <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- vi: set et smarttab sw=2 tabstop=2: --> <!-- Copyright © 2017 Red Hat, Inc. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.opendaylight.odlparent</groupId> <artifactId>bundle-parent</artifactId> <version>13.0.3</version> <relativePath/> </parent> <groupId>org.opendaylight.infrautils</groupId> <artifactId>parent</artifactId> <version>6.0.2-SNAPSHOT</version> <!-- <name> formatting is used by autorelease to parse and notify projects on build failure. Please do not modify this unless you have a good reason. --> <name>ODL :: infrautils :: ${project.artifactId}</name> <packaging>pom</packaging> <properties> <!-- Enforce all of odlparent's optional code quality checks: --> <pmd.cpd.fail>true</pmd.cpd.fail> <!-- Fails build for copy/pasted code --> <duplicate-finder.skip>false</duplicate-finder.skip> <!-- Fails build if duplicate classpath entries on dependencies (odlparent 3.0.0) --> <odlparent.modernizer.enforce>true</odlparent.modernizer.enforce> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.opendaylight.infrautils</groupId> <artifactId>infrautils-artifacts</artifactId> <version>6.0.2-SNAPSHOT</version> <scope>import</scope> <type>pom</type> </dependency> <dependency> <!-- ClassGraph is used both in the ClasspathHellDuplicatesCheckRule as well as in the ClassPathScanner --> <groupId>io.github.classgraph</groupId> <artifactId>classgraph</artifactId> <version>4.8.158</version> </dependency> <dependency> <groupId>com.mycila.guice.extensions</groupId> <artifactId>mycila-guice-jsr250</artifactId> <version>5.0</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>6.0.0</version> <exclusions> <exclusion> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.errorprone</groupId> <artifactId>error_prone_annotations</artifactId> <!-- Keep this version in sync with annotationProcessorPaths declaration below --> <version>2.21.1</version> <optional>true</optional> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> </plugin> </plugins> </build> <profiles> <profile> <id>errorprone</id> <!-- Run Error Prone (see http://errorprone.info) UNLESS we're running Maven inside the Eclipse IDE under M2E (i.e. only on the "mvn" CLI) because in M2E it causes havoc for the m2e-apt extension (which configures Annotations Processors, such as e.g. http://Immutables.org, for the Eclipse JDT APT support); see full details in https://github.com/jbosstools/m2e-apt/issues/62. Not running errorprone within the Eclipse IDE is not a problem, because that's not yet supported, anyway; see http://errorprone.info/docs/installation#Eclipse. --> <activation> <property> <name>!m2e.version</name> </property> <!-- JDK18 is an unknown, let's not activate with it just now --> <jdk>[8,18)</jdk> </activation> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <!-- Needed for add-{exports,opens} below --> <fork>true</fork> <compilerArgs combine.children="append"> <arg>-XDcompilePolicy=simple</arg> <!-- Needed until EP uses something else than private APIs --> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg> <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg> <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg> <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg> <arg>-Xplugin:ErrorProne \ <!-- TODO evaluate further which other non-default error prone bug patterns could also be enabled... \ http://errorprone.info/bugpatterns --> \ -XepExcludedPaths:.*/target/.* \ -XepDisableWarningsInGeneratedCode \ <!-- TODO Do we need and want <arg>-Xep:OperatorPrecedence:OFF</arg> ? --> \ <!-- There are lots of disabled goodies in error-prone which only emit warnings (which nobody will ever look at!), \ so let us enable them all as least as warnings, and then selectively turn some of them into ERROR, and suppress \ those we really don't want (or can't enforce for whatever reason) with OFF. --> \ -XepAllDisabledChecksAsWarnings \ <!-- StaticOrDefaultInterfaceMethod is an Android specific warning which we don't care about --> \ -Xep:StaticOrDefaultInterfaceMethod:OFF \ <!-- To "Use parameter comments to document ambiguous literals" is unrealistic on a large existing code base --> \ -Xep:BooleanParameter:OFF \ -Xep:InconsistentOverloads:ERROR \ -Xep:MethodCanBeStatic:ERROR \ -Xep:ThrowsUncheckedException:OFF \ <!-- TODO -Xep:TestExceptionChecker:ERROR once all @Test with expected use org.opendaylight.infrautils.testutils.Asserts.assertThrows() instead --> \ -Xep:RedundantThrows:ERROR \ -Xep:Var:ERROR \ <!-- Following are things which seem useful to enforce, found in other projects; \ we could relax these again if during enforcement all over infrautils we find them to be too strict --> \ -Xep:ConstantField:ERROR \ -Xep:EmptySetMultibindingContributions:ERROR \ -Xep:MixedArrayDimensions:ERROR \ -Xep:MultipleTopLevelClasses:ERROR \ -Xep:MultiVariableDeclaration:ERROR \ -Xep:PackageLocation:ERROR \ -Xep:PrivateConstructorForNoninstantiableModule:ERROR \ -Xep:RemoveUnusedImports:ERROR \ -Xep:UnnecessaryStaticImport:ERROR \ -Xep:UseBinds:ERROR \ -Xep:WildcardImport:ERROR \ <!-- FutureReturnValueIgnored is better (stronger) than error-prone's own (and FindBug's) @CheckReturnValue annotation, as it checks that ANY return Future are checked, not just those from methods annotated @CheckReturnValue --> \ -Xep:FutureReturnValueIgnored:ERROR \ -Xep:IntLongMath:ERROR \ -Xep:FloatCast:ERROR \ -Xep:ClassNewInstance:ERROR \ -Xep:ThreeLetterTimeZoneID:ERROR \ -Xep:UnsafeFinalization:ERROR \ -Xep:SynchronizeOnNonFinalField:ERROR \ -Xep:WaitNotInLoop:ERROR \ -Xep:SwitchDefault:ERROR \ -Xep:ReachabilityFenceUsage:ERROR \ -Xep:BoxedPrimitiveConstructor:ERROR \ -Xep:InjectOnConstructorOfAbstractClass:ERROR \ -Xep:StringSplitter:ERROR \ -Xep:UnnecessaryDefaultInEnumSwitch:ERROR \ -Xep:DefaultCharset:ERROR \ -Xep:StreamResourceLeak:ERROR \ <!-- new in 2.3.0 --> \ -Xep:InconsistentCapitalization:ERROR \ -Xep:TruthIncompatibleType:ERROR \ -Xep:ByteBufferBackingArray:ERROR \ -Xep:OrphanedFormatString:ERROR \ -Xep:CatchAndPrintStackTrace:ERROR \ -Xep:VarTypeName:ERROR \ <!-- new in 2.3.1 --> \ -Xep:ObjectToString:ERROR \ -Xep:AssertThrowsMultipleStatements:ERROR \ -Xep:FieldCanBeFinal:ERROR \ <!-- new in 2.3.2 --> \ -Xep:AndroidJdkLibsChecker:OFF \ -Xep:Java7ApiChecker:OFF \ -Xep:Java8ApiChecker:OFF</arg> </compilerArgs> <annotationProcessorPaths combine.children="append"> <path> <groupId>com.google.errorprone</groupId> <artifactId>error_prone_core</artifactId> <!-- Keep this version in sync with dependency declaration above --> <version>2.21.1</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep>/* * Copyright (c) 2017, 2018 Ericsson Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.utils.concurrent; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; /** * Additional factory and utility methods for executors. * * <p>Use this instead of {@link java.util.concurrent.Executors}, because * it ensures that the returned Executor uses a {@link ThreadFactory} that is * named, has a logging UncaughtExceptionHandler, and returns (Guava's) ListenableFuture. */ public final class Executors { public static final long DEFAULT_TIMEOUT_FOR_SHUTDOWN = 10; public static final TimeUnit DEFAULT_TIMEOUT_UNIT_FOR_SHUTDOWN = TimeUnit.SECONDS; private Executors() { // Hidden on purpose } /** * Creates a single thread executor with a {@link ThreadFactory} that uses * the provided prefix for its thread names and logs uncaught exceptions * with the specified {@link Logger}. * * @param namePrefix Prefix for this executor thread names * @param logger Logger used to log uncaught exceptions * @return the newly created single-threaded Executor */ public static ListeningExecutorService newListeningSingleThreadExecutor(String namePrefix, Logger logger) { return MoreExecutors.listeningDecorator(java.util.concurrent.Executors.newSingleThreadExecutor( createThreadFactory(namePrefix, logger))); } public static ListeningExecutorService newFixedThreadPool(int size, String namePrefix, Logger logger) { return MoreExecutors.listeningDecorator(java.util.concurrent.Executors.newFixedThreadPool(size, createThreadFactory(namePrefix, logger))); } public static ListeningExecutorService newListeningCachedThreadPool(String namePrefix, Logger logger) { return MoreExecutors.listeningDecorator(java.util.concurrent.Executors.newCachedThreadPool( createThreadFactory(namePrefix, logger))); } public static ListeningScheduledExecutorService newListeningSingleThreadScheduledExecutor(String namePrefix, Logger logger) { return MoreExecutors.listeningDecorator(java.util.concurrent.Executors.unconfigurableScheduledExecutorService( java.util.concurrent.Executors.newSingleThreadScheduledExecutor(createThreadFactory(namePrefix, logger)))); } public static ListeningScheduledExecutorService newListeningScheduledThreadPool(int corePoolSize, String namePrefix, Logger logger) { return MoreExecutors.listeningDecorator(java.util.concurrent.Executors.newScheduledThreadPool(corePoolSize, createThreadFactory(namePrefix, logger))); } public static void shutdownAndAwaitTermination(ExecutorService executorService) { MoreExecutors.shutdownAndAwaitTermination(executorService, DEFAULT_TIMEOUT_FOR_SHUTDOWN, DEFAULT_TIMEOUT_UNIT_FOR_SHUTDOWN); } private static ThreadFactory createThreadFactory(String namePrefix, Logger logger) { return ThreadFactoryProvider.builder().namePrefix(namePrefix).logger(logger).build().get(); } } <file_sep>/* * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus.internal; import static com.google.common.base.Verify.verifyNotNull; import com.google.common.annotations.Beta; import java.util.List; import org.opendaylight.infrautils.diagstatus.DiagStatusService; import org.opendaylight.infrautils.diagstatus.ServiceStatusProvider; import org.opendaylight.infrautils.ready.SystemReadyMonitor; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Beta @Component(immediate = true, service = DiagStatusService.class) public final class OSGiDiagStatusService extends AbstractDiagStatusService { private static final Logger LOG = LoggerFactory.getLogger(OSGiDiagStatusService.class); @Reference volatile List<ServiceStatusProvider> serviceStatusProviders = null; @Reference SystemReadyMonitor systemReadyMonitor = null; @Override Iterable<? extends ServiceStatusProvider> serviceStatusProviders() { return verifyNotNull(serviceStatusProviders); } @Override SystemReadyMonitor systemReadyMonitor() { return verifyNotNull(systemReadyMonitor); } @Activate @SuppressWarnings("static-method") void activate() { LOG.info("Diagnostic Status Service started"); } @Deactivate @SuppressWarnings("static-method") void deactivate() { LOG.info("Diagnostic Status Service stopped"); } } <file_sep>/* * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.ready.spi; import static org.opendaylight.infrautils.ready.SystemState.ACTIVE; import static org.opendaylight.infrautils.ready.SystemState.BOOTING; import static org.opendaylight.infrautils.ready.SystemState.FAILURE; import com.google.common.base.Throwables; import java.util.Optional; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; import org.opendaylight.infrautils.ready.SystemReadyListener; import org.opendaylight.infrautils.ready.SystemReadyMonitor; import org.opendaylight.infrautils.ready.SystemState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link SystemReadyMonitor} implementation for a "simple" (standalone, Java SE) environment. * Also used as the base class for the Karaf/OSGi specific implementation. * * @author <NAME>, based on code from myself, Tom (concurrency) &amp; Faseela in KarafSystemReadyImpl */ public class SimpleSystemReadyMonitor implements SystemReadyMonitor { private static final Logger LOG = LoggerFactory.getLogger(SimpleSystemReadyMonitor.class); private final Queue<SystemReadyListener> listeners = new ConcurrentLinkedQueue<>(); private final AtomicReference<SystemState> currentSystemState = new AtomicReference<>(BOOTING); private final AtomicReference<Throwable> currentSystemFailureCause = new AtomicReference<>(); @Override @SuppressWarnings("checkstyle:IllegalCatch") public void registerListener(SystemReadyListener listener) { SystemState state; synchronized (listeners) { state = currentSystemState.get(); if (state == BOOTING) { listeners.add(listener); } } if (state == ACTIVE) { try { listener.onSystemBootReady(); } catch (Exception e) { LOG.error("SystemReadyListener.onSystemBootReady() threw Exception; " + "but state was already ACTIVE, going back to FAILURE now", e); currentSystemState.set(FAILURE); currentSystemFailureCause.set(e); // Do not re-throw. } } } @Override public SystemState getSystemState() { return currentSystemState.get(); } @Override public String getFailureCause() { return Optional.ofNullable(currentSystemFailureCause.get()) .map(throwable -> Throwables.getStackTraceAsString(throwable)).orElse(""); } @SuppressWarnings("checkstyle:IllegalCatch") // below public void ready() { SystemReadyListener[] toNotify; synchronized (listeners) { toNotify = listeners.toArray(new SystemReadyListener[listeners.size()]); currentSystemState.set(ACTIVE); } LOG.info("System ready; AKA: Aye captain, all warp coils are now operating at peak efficiency! [M.]"); if (toNotify.length > 0) { LOG.info("Now notifying all its registered SystemReadyListeners..."); } try { for (SystemReadyListener element : toNotify) { element.onSystemBootReady(); } } catch (Exception e) { // this, intentionally, also catches any RuntimeException LOG.error("Boot failed; a SystemReadyListener.onSystemBootReady() threw an Exception; " + "other registered SystemReadyListeners were not called; SystemState FAILURE", e); setSystemState(FAILURE); setSystemFailureCause(e); // intentionally *NOT* re-throwing } } protected void setSystemState(SystemState state) { currentSystemState.set(state); } protected void setSystemFailureCause(Throwable cause) { currentSystemFailureCause.set(cause); } } <file_sep> .. contents:: Table of Contents :depth: 4 =================== Infrautils Features =================== This project offers technical utilities and infrastructures for other projects to use. The conference presentation slides linked to in the references section at the end give a good overview of the project. Check out the JavaDoc on https://javadocs.opendaylight.org/org.opendaylight.infrautils/fluorine/. Features ======== @Inject DI ---------- See https://wiki.opendaylight.org/view/BestPractices/DI_Guidelines Utils incl. org.opendaylight.infrautils.utils.concurrent -------------------------------------------------------- Bunch of small (non test related) low level general utility classes à la Apache (Lang) Commons or Guava and similar incl. utils.concurrent: * ListenableFutures toCompletionStage & addErrorLogging * CompletableFutures completedExceptionally * CompletionStages completedExceptionally * LoggingRejectedExecutionHandler, LoggingThreadUncaughtExceptionHandler, ThreadFactoryProvider, Executors newSingleThreadExecutor Test Utilities -------------- * LogRule which logs (using slf4j-api) the start and stop of each @Test method * LogCaptureRule which can fail a test if something logs any ERROR from anywhere (This work even if the LOG.error() is happening in a background thread, not the test's main thread... which can be particularly interesting.) * RunUntilFailureRule which allows to keep running tests indefinitely; for local usage to debug "flaky" (sometimes passing, sometimes failing) tests until they fail * ClasspathHellDuplicatesCheckRule verifies, and guarantees future non-regression, against JAR hell due to duplicate classpath entries. Tests with this JUnit Rule will fail if their classpath contains duplicate class. This could be caused e.g. by changes to upstream transitive dependencies. See also http://jhades.github.io (which this internally uses, not exposed). see https://github.com/opendaylight/infrautils/blob/master/testutils/src/test/java/org/opendaylight/infrautils/testutils/tests/ExampleTest.java * Also some low level general utility classes helpful for unit testing concurrency related things in infrautils.testutils.concurrent: - AwaitableExecutorService - SlowExecutor - CompletionStageTestAwaiter, see CompletionStageAwaitExampleTest Job Coordinator --------------- JobCoordinator service which enables executing jobs in a parallel/sequential fashion based on their keys. Ready Service ------------- Infrastructure to detect when Karaf is ready. The implementation internally uses the same Karaf API that e.g. the standard "diag" Karaf CLI command uses. This checks both if all OSGi bundles have started as well if their blueprint initialization has been successfully fully completed. It builds on top of the bundles-test-lib from odlparent, which is what we run as SingleFeatureTest (SFT) during all of our builds to ensure that all projects' features can be installed without broken bundles. The infrautils.diagstatus modules builds on top of this infrautils.ready. What infrautils.ready adds on top of the underlying raw Karaf API is operator friendly logging, a convenient API and a correctly implemented polling loop in a background thread with SystemReadyListener registrations and notifications, instead of ODL applications re-implementing this. The infrautils.ready project intentionally API isolates consumers from the Karaf API. We encourage all ODL projects to use this infrautils.ready API instead of trying to reinvent the wheel and directly depending on the Karaf API, so that application code could be used outside of OSGi, in environment such as unit and component tests, or something such as honeycomb. Applications can use this SystemReadyMonitor registerListener(SystemReadyListener) in a constructor to register a listener for and get notified when all bundles are "ready" in the technical sense (have been started in the OSGi sense and have completed their blueprint initialization), and could on that event do any further initialization it had to delay in the original blueprint initialization. This cannot directly be used to express functional dependencies BETWEEN bundles (because that would deadlock infrautils.ready; it would stay in BOOTING forever and never reach SystemState ACTIVE). The natural way to make one bundle await another is to use Blueprint OSGi service dependency. If there is no technical service dependency but only a logical functional one, then in infrautils.ready.order there is a convenience sugar utility to publish "marker" FunctionalityReady interfaces to the OSGi service registry; unlike real services, these have no implementing code, but another bundle could depend on one to enforce start up order one (using regular Blueprint <reference> in XML or @Reference annotation). A known limitation of the current implementation of infrautils.ready is that its "wait until ready" loop runs only once, after installation of infrautils.ready (by boot feature usage, or initial single line feature:install). So SystemState will go from BOOTING to ACTIVE or FAILURE, once. So if you do more feature:install after a time gap, there won’t be any further state change notification; the currently implementation won't "go back" from ACTIVE to BOOTING. (It would be absolutely possible to extend SystemReadyListener onSystemBootReady() with an onSystemIsChanging() and onSystemReadyAgain(), but the original author has no need for this; as "hot" installing additional ODL application features during operational uptime was not a real world requirement to the original author. If this is important to you, then your contributions for extending this would certainly be welcome.) infrautils' ready, like other infrautils APIs, is available as a separate Karaf feature. Downstream projects using infrautils.ready will therefore NOT pull in other bundles for other infrautils functionalities. Integration Test Utilities (itestutils) --------------------------------------- See https://bugs.opendaylight.org/show_bug.cgi?id=8438 and https://git.opendaylight.org/gerrit/#/c/56898/ Used for non-regression self-testing of features in this project (and available to others). Diagstatus ---------- To be documented. References ========== [2] `ODL DDF - LA 2018 <https://docs.google.com/presentation/d/1C2jbZP8C8FwoR9yoFMrMs-kKt8Uiv8r8vtXc1bocb7c/>`__ [3] `ODL DDF 2017 <https://docs.google.com/presentation/d/1S7WBPumuQxMBiGLf9Xt8SJkUTNgvrIZmwlBNYArRHzk/>`__ [4] `infrautils JavaDoc <https://javadocs.opendaylight.org/org.opendaylight.infrautils/fluorine/>`__ <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.tests; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.opendaylight.infrautils.testutils.ClasspathHellDuplicatesCheckRule; import org.opendaylight.infrautils.testutils.LogCaptureRule; import org.opendaylight.infrautils.testutils.LogRule; import org.opendaylight.infrautils.testutils.RunUntilFailureClassRule; import org.opendaylight.infrautils.testutils.RunUntilFailureRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit test, and example, of how to use the different new JUnit Rules. * * @author <NAME> */ public class ExampleTest { private static final Logger LOG = LoggerFactory.getLogger(ExampleTest.class); @ClassRule public static RunUntilFailureClassRule classRepeater = new RunUntilFailureClassRule(10); @Rule public RunUntilFailureRule repeater = new RunUntilFailureRule(classRepeater); @Rule public LogRule logRule = new LogRule(); @Rule public LogCaptureRule logCaptureRule = new LogCaptureRule(); @ClassRule public static ClasspathHellDuplicatesCheckRule jHades = new ClasspathHellDuplicatesCheckRule(); @Test public void testA() throws InterruptedException { LOG.info("doin' stuff in testA..."); Thread.sleep(50); // LOG.error("boum"); } @Test public void testB() throws InterruptedException { LOG.info("doin' stuff in testB..."); Thread.sleep(100); // fail("failure"); } } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.inject.guice.testutils.tests; import static org.junit.Assert.assertTrue; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.mycila.guice.ext.closeable.CloseableModule; import com.mycila.guice.ext.jsr250.Jsr250Module; import org.junit.Test; /** * Example Guice Test without using Rule, just for illustration. * * @see ExampleGuiceRuleTest * * @author <NAME> */ public class ExamplePureGuiceTest { @Test public void testPostConstruct() { Injector injector = Guice.createInjector(new TestModule()); SomeClassWithPostConstruct someClass = injector.getInstance(SomeClassWithPostConstruct.class); assertTrue(someClass.isInit); } static class TestModule extends AbstractModule { @Override protected void configure() { install(new CloseableModule()); install(new Jsr250Module()); bind(SomeClassWithPostConstruct.class).asEagerSingleton(); } } } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils; import com.google.errorprone.annotations.Var; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.eclipse.jdt.annotation.Nullable; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * See {@link RunUntilFailureRule}. * * @author <NAME> */ public class RunUntilFailureClassRule implements TestRule { private static final String HEADER = "=".repeat(120); // package local boolean isRunning = true; private final @Nullable Long maximumNumberOfTimesToRun; @SuppressFBWarnings(value = "NP_STORE_INTO_NONNULL_FIELD", justification = "TYPE_USE and SpotBugs") public RunUntilFailureClassRule() { this.maximumNumberOfTimesToRun = null; } public RunUntilFailureClassRule(long maximumNumberOfTimesToRun) { if (maximumNumberOfTimesToRun < 1) { throw new IllegalArgumentException("maximumNumberOfTimesToRun must be positive"); } this.maximumNumberOfTimesToRun = maximumNumberOfTimesToRun; } @Override public Statement apply(Statement statement, Description description) { return new RunUntilFailureStatement(statement, description); } // findbugs-slf4j does not understand that a static final String IS a Constant, so SLF4J_FORMAT_SHOULD_BE_CONST // findbugs-slf4j cannot understand what we are doing here with a Logger variable instead of class field, so: @SuppressFBWarnings({ "SLF4J_FORMAT_SHOULD_BE_CONST", "SLF4J_LOGGER_SHOULD_BE_PRIVATE" }) private class RunUntilFailureStatement extends Statement { final Statement statement; final Logger testLog; RunUntilFailureStatement(Statement statement, Description description) { this.statement = statement; testLog = LoggerFactory.getLogger(description.getTestClass()); } @Override public void evaluate() throws Throwable { @Var int runNumber = 1; do { testLog.info(HEADER); testLog.info("RunUntilFailureRule #{}/{}", runNumber++, maximumNumberOfTimesToRun == null ? "∞" : maximumNumberOfTimesToRun); statement.evaluate(); } while (isRunning && (maximumNumberOfTimesToRun == null || runNumber < maximumNumberOfTimesToRun + 1)); } } } <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.time.Instant; import java.util.Collection; import java.util.Objects; import java.util.Set; import org.opendaylight.infrautils.ready.SystemState; /** * Summary of overall system service status. * * @author <NAME> */ public final class ServiceStatusSummary { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().serializeNulls() .registerTypeAdapterFactory(ThrowableAdapterFactory.INSTANCE) .registerTypeAdapter(Instant.class, new InstantSerializer()) .registerTypeAdapter(Instant.class, new InstantDeserializer()) .create(); private final Instant timeStamp; private final boolean isOperational; private final SystemState systemReadyState; private final String systemReadyStateErrorCause; private final Set<ServiceDescriptor> statusSummary; public static ServiceStatusSummary fromJSON(String json) { return GSON.fromJson(json, ServiceStatusSummary.class); } public ServiceStatusSummary(boolean isOperational, SystemState systemState, String systemReadyErrorCause, Set<ServiceDescriptor> statusSummary) { this.timeStamp = Instant.now(); this.isOperational = isOperational; this.systemReadyState = systemState; this.statusSummary = statusSummary; this.systemReadyStateErrorCause = systemReadyErrorCause; } public String toJSON() { return GSON.toJson(this); } public boolean isOperational() { return isOperational; } public SystemState getSystemReadyState() { return systemReadyState; } public String getSystemReadyStateErrorCause() { return systemReadyStateErrorCause; } public Collection<ServiceDescriptor> getStatusSummary() { return statusSummary; } public Instant getTimeStamp() { return timeStamp; } @Override public boolean equals(Object obj) { return this == obj || obj instanceof ServiceStatusSummary that && this.isOperational == that.isOperational && Objects.equals(this.systemReadyState, that.systemReadyState) && Objects.equals(this.systemReadyStateErrorCause, that.systemReadyStateErrorCause) && Objects.equals(this.statusSummary, that.statusSummary) && Objects.equals(this.timeStamp, that.timeStamp); } @Override public int hashCode() { return Objects.hash(isOperational(), getSystemReadyState(), getSystemReadyStateErrorCause(), getStatusSummary(), getTimeStamp()); } @Override public String toString() { return "ServiceStatusSummary{" + "timeStamp='" + timeStamp.toString() + '\'' + ", isOperational=" + isOperational + ", systemReadyState=" + systemReadyState + ", systemReadyStateErrorCause='" + systemReadyStateErrorCause + '\'' + ", statusSummary=" + statusSummary + '}'; } } <file_sep>/* * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.inject.guice; /** * Guice Module with classpath scanning based autowiring. * * @author <NAME> */ public class AutoWiringModule extends AbstractCheckedModule { protected final GuiceClassPathBinder classPathBinder; private final String packagePrefix; public AutoWiringModule(GuiceClassPathBinder classPathBinder, String packagePrefix) { this.classPathBinder = classPathBinder; this.packagePrefix = packagePrefix; } @Override protected final void checkedConfigure() throws Exception { classPathBinder.bindAllSingletons(packagePrefix, binder()); configureMore(); } protected void configureMore() throws Exception { } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.ready.karaf.internal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Dictionary; import org.junit.Before; import org.junit.Test; import org.opendaylight.infrautils.ready.order.FunctionalityReady; import org.opendaylight.infrautils.ready.order.FunctionalityReadyNotifier; import org.opendaylight.infrautils.ready.order.FunctionalityReadyRegistration; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; /** * Unit test for {@link FunctionalityReadyNotifier}. * * @author <NAME> */ public class FunctionalityReadyNotifierTest { private static Object registeredService; private abstract static class AbstractBundleContextImpl implements BundleContext { @Override @SuppressWarnings("unchecked") public <S> ServiceRegistration<S> registerService(Class<S> clazz, S service, Dictionary<String, ?> properties) { registeredService = service; return mock(ServiceRegistration.class); } } private final BundleContext mockBundleContext = mock(AbstractBundleContextImpl.class); private final FunctionalityReadyNotifierImpl notifier = new FunctionalityReadyNotifierImpl(); @Before public void before() { notifier.activate(mockBundleContext); } @Test @SuppressWarnings("unchecked") public void testRegisterTestReady() throws InvalidSyntaxException { when(mockBundleContext.getAllServiceReferences(TestReady.class.getName(), null)) .thenReturn(new ServiceReference[] {}); when(mockBundleContext.registerService((Class<TestReady>) any(), any(TestReady.class), any())) .thenCallRealMethod(); FunctionalityReadyRegistration<?> registration = notifier.register(TestReady.class); assertNotNull(registration); assertNotNull(registeredService); assertNotNull(registeredService.toString()); assertThat(registeredService.hashCode(), greaterThan(0)); assertFalse(registeredService.equals(null)); } @Test(expected = NullPointerException.class) public void testRegisterNull() { notifier.register(null); } @Test(expected = IllegalArgumentException.class) public void testTestClassReadyInsteadOfInterface() { notifier.register(TestClassReady.class); } private interface TestReady extends FunctionalityReady { } private static class TestClassReady implements FunctionalityReady { } } <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus; /** * ServiceState for {@link ServiceState}. * * @author <NAME> */ public enum ServiceState { /** * This state is used only by the monitor implementation and not by monitored services. */ UNREGISTERED, /** * Move to this state when registration call is received from monitored service. */ STARTING, /** * This state is used only by the monitored services for reactive and proactive reporting. */ OPERATIONAL, /** * This state is used only by the monitor implementation and not by monitored services. */ SUSPECTED, /** * This state is used only by the monitor implementation and not by monitored services. */ RECOVERED, /** * This state is used only by the monitored services for reactive and proactive reporting. */ ERROR, } <file_sep>/* * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.utils.concurrent; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.FluentFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.JdkFutureAdapters; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import java.util.concurrent.Future; import org.slf4j.Logger; /** * Utility methods to add completion/failure logging to various kinds of Futures. * * @author <NAME> - Initial author * @author <NAME> - moved here from JdkFutures &amp; ListenableFutures */ @Beta public final class LoggingFutures { private LoggingFutures() { } /** * Adds a callback to a Future which logs any failures. * * @param future the future to add logging to * @param logger logger to use * @param message message to log * @return ListenableFuture backed by the supplied future * @throws NullPointerException if any of the arguments is null */ public static <V> ListenableFuture<V> addErrorLogging(Future<V> future, Logger logger, String message) { return addErrorLogging(JdkFutureAdapters.listenInPoolThread(future), logger, message); } /** * Adds a callback to a Future which logs any failures. * * @param future the future to add logging to * @param logger logger to use * @param format format string conforming to {@link String#format(String, Object...)} * @param arg single format argument * @return ListenableFuture backed by the supplied future * @throws NullPointerException if any of the arguments is null */ public static <V> ListenableFuture<V> addErrorLogging(Future<V> future, Logger logger, String format, Object arg) { return addErrorLogging(JdkFutureAdapters.listenInPoolThread(future), logger, format, arg); } /** * Adds a callback to a ListenableFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param format format string conforming to {@link String#format(String, Object...)} * @param args format arguments * @return ListenableFuture backed by the supplied future * @throws NullPointerException if any of the arguments is null */ public static <V> ListenableFuture<V> addErrorLogging(Future<V> future, Logger logger, String format, Object... args) { return addErrorLogging(JdkFutureAdapters.listenInPoolThread(future), logger, format, args); } /** * Adds a callback to a ListenableFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param message message to log * @return The future * @throws NullPointerException if any of the arguments is null */ public static <V> ListenableFuture<V> addErrorLogging(ListenableFuture<V> future, Logger logger, String message) { return addCallback(future, new FailureMessageLoggingFutureCallback<>(logger, message)); } /** * Adds a callback to a ListenableFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param format format string conforming to {@link String#format(String, Object...)} * @param arg single format argument * @return The future * @throws NullPointerException if any of the arguments is null */ public static <V> ListenableFuture<V> addErrorLogging(ListenableFuture<V> future, Logger logger, String format, Object arg) { return addCallback(future, new FailureFormat1ArgumentLoggingFutureCallback<V>(logger, format, arg)); } /** * Adds a callback to a ListenableFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param format format string conforming to {@link String#format(String, Object...)} * @param args format arguments * @return The future * @throws NullPointerException if any of the arguments is null */ public static <V> ListenableFuture<V> addErrorLogging(ListenableFuture<V> future, Logger logger, String format, Object... args) { return addCallback(future, new FailureFormatMoreArgumentsLoggingFutureCallback<V>(logger, format, args)); } /** * Adds a callback to a ListenableFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param message message to log * @return The future * @throws NullPointerException if any of the arguments is null */ public static <V> FluentFuture<V> addErrorLogging(FluentFuture<V> future, Logger logger, String message) { return addCallback(future, new FailureMessageLoggingFutureCallback<>(logger, message)); } /** * Adds a callback to a ListenableFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param format format string conforming to {@link String#format(String, Object...)} * @param arg single format argument * @return The future * @throws NullPointerException if any of the arguments is null */ public static <V> FluentFuture<V> addErrorLogging(FluentFuture<V> future, Logger logger, String format, Object arg) { return addCallback(future, new FailureFormat1ArgumentLoggingFutureCallback<>(logger, format, arg)); } /** * Adds a callback to a FluentFuture which logs any failures. * * <p>Instead of using this helper, you should consider directly using * {@link Futures#addCallback(ListenableFuture, FutureCallback, java.util.concurrent.Executor)} to add a callback * which does real error recovery in case of a failure instead of just logging an error, if you can. * * @param future the future to add logging to * @param logger logger to use * @param format format string conforming to {@link String#format(String, Object...)} * @param args format arguments * @return The future * @throws NullPointerException if any of the arguments is null */ public static <V> FluentFuture<V> addErrorLogging(FluentFuture<V> future, Logger logger, String format, Object... args) { return addCallback(future, new FailureFormatMoreArgumentsLoggingFutureCallback<V>(logger, format, args)); } private static <V, F extends ListenableFuture<V>> F addCallback(F future, FutureCallback<V> callback) { Futures.addCallback(future, callback, MoreExecutors.directExecutor()); return future; } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.itestutils.it; import org.junit.Test; import org.opendaylight.infrautils.itestutils.AbstractIntegrationTest; import org.ops4j.pax.exam.options.UrlReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Example Integration Test. * @author <NAME> */ // @ExamReactorStrategy(PerClass.class) IFF the default PerMethod (which provides better isolation!) really is too slow? public class SampleIntegrationTest extends AbstractIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(SampleIntegrationTest.class); @Test public void testEmptyJustToMakeSureKarafStartedOK() { LOG.info("info log is not visible, as not enabled"); LOG.warn("warn log is visible"); } @Override protected UrlReference featureRepositoryURL() { // We really don't actually need / want to install a feature here // but is exceptional, any normal real IT would want to... return null; } @Override protected String featureName() { // We really don't actually need / want to install a feature here // but is exceptional, any normal real IT would want to... return null; } // @Test // public void testGoogleTruthWorksInsideOSGi() { // assertThat(Boolean.TRUE).isTrue(); // } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.ready; /** * System State. * * @author <NAME> */ public enum SystemState { // NB: There is a very similar enum in org.opendaylight.odlparent.bundlestest.lib.SystemState, // but this is intentionally copied here instead of referenced from there, because: // // (a) we consider odlparent.bundles[4]test an implementation details of infrautils.ready-impl, // which should never be exposed to consumer of the simple infrautils.ready API (impl may change) // // (b) we need a 5th new "Changing" state here, which we don't have (and need) there BOOTING, ACTIVE, // TODO uncomment when SystemReadyListener's onSystemIsChanging() will get implemented // /** See {@link SystemReadyListener#onSystemIsChanging()}. */ // CHANGING, // TODO this is not implemented, yet; but could be, once we have Robert's hooks into Karaf's shutdown available // STOPPING, FAILURE, } <file_sep>/* * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.Map; import org.junit.Test; import org.opendaylight.infrautils.testutils.ClasspathHellDuplicatesChecker; /** * Unit test for {@link ClasspathHellDuplicatesChecker}. * * @author <NAME> */ public class ClasspathHellDuplicatesCheckerTest { @Test public void testNoDuplicates() { assertEquals(Map.of(), new ClasspathHellDuplicatesChecker().getDuplicates()); } @Test public void testDuplicates() { // Just to make sure that is actually does something, if we were not to filter anything, there would be some: assertFalse(new ClasspathHellDuplicatesChecker() { @Override protected boolean isHarmlessDuplicate(String resourcePath) { return false; } }.getDuplicates().isEmpty()); } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- vi: set et smarttab sw=4 tabstop=4: --> <!-- Copyright (c) 2020 PANT<EMAIL>, s.r.o. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.opendaylight.odlparent</groupId> <artifactId>bundle-parent</artifactId> <version>13.0.3</version> <relativePath/> </parent> <groupId>org.opendaylight.infrautils</groupId> <artifactId>infrautils-docs</artifactId> <version>6.0.2-SNAPSHOT</version> <packaging>jar</packaging> <name>${project.artifactId}</name> <description>Infra Utils documentation</description> <dependencyManagement> <dependencies> <dependency> <groupId>org.opendaylight.infrautils</groupId> <artifactId>infrautils-artifacts</artifactId> <version>6.0.2-SNAPSHOT</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- General utilities --> <dependency> <groupId>${project.groupId}</groupId> <artifactId>infrautils-util</artifactId> </dependency> <!-- Test utilities --> <dependency> <groupId>${project.groupId}</groupId> <artifactId>infrautils-testutils</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>inject.guice.testutils</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>itestutils</artifactId> </dependency> <!-- Diagnostic Status --> <dependency> <groupId>${project.groupId}</groupId> <artifactId>diagstatus-api</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>diagstatus-impl</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>diagstatus-shell</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>diagstatus-web</artifactId> </dependency> <!-- Platform Readiness --> <dependency> <groupId>${project.groupId}</groupId> <artifactId>ready-api</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>ready-impl</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>ready-guice</artifactId> </dependency> <!-- APIs & runtime utilities --> <dependency> <groupId>${project.groupId}</groupId> <artifactId>inject</artifactId> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>inject.guice</artifactId> </dependency> <!-- Also add dependencies we are using --> <dependency> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-annotations</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.component.annotations</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.http.whiteboard</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.opendaylight.odlparent</groupId> <artifactId>bundles-test-lib</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.karaf.bundle</groupId> <artifactId>org.apache.karaf.bundle.core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.karaf.shell</groupId> <artifactId>org.apache.karaf.shell.console</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.karaf.shell</groupId> <artifactId>org.apache.karaf.shell.core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-junit4</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-container-karaf</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.ops4j.pax.url</groupId> <artifactId>pax-url-aether</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.immutables</groupId> <artifactId>value</artifactId> <classifier>annotations</classifier> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-webapp</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack-sources</id> <phase>process-classes</phase> <goals> <goal>unpack-dependencies</goal> </goals> <configuration> <silent>true</silent> <classifier>sources</classifier> <includes>org/opendaylight/**</includes> <includeGroupIds>org.opendaylight.infrautils</includeGroupIds> <outputDirectory>${project.build.directory}/src</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <executions> <execution> <id>add-source</id> <phase>process-classes</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/src</source> </sources> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <!-- prepare-package so we build the source package before javadoc --> <phase>prepare-package</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> <!-- FIXME: remove this section once we can activate javadoc-links profile --> <configuration combine.children="append"> <links> <link>https://junit.org/junit4/javadoc/4.13/</link> <link>http://hamcrest.org/JavaHamcrest/javadoc/2.2/</link> <link>http://www.slf4j.org/apidocs/</link> <link>https://google.github.io/guava/releases/31.1-jre/api/docs/</link> <link>https://commons.apache.org/proper/commons-lang/apidocs/</link> <link>https://www.javadoc.io/doc/org.opendaylight.odlparent/odlparent-docs/13.0.3/</link> </links> <groups> <group> <title>Common utilities</title> <packages>org.opendaylight.infrautils.util*</packages> </group> </groups> </configuration> </plugin> </plugins> </build> </project> <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.internal; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.helpers.SubstituteLogger; /** * A slf4j logger implementation which logs via a delegate logger. * The delegate is set once, during construction. * * @see SubstituteLogger * * @author <NAME> */ // findbugs-slf4j cannot understand what we are doing here, so: @SuppressFBWarnings({ "SLF4J_FORMAT_SHOULD_BE_CONST", "SLF4J_UNKNOWN_ARRAY" }) // package-local not public (for the time being) class DelegatingLogger implements Logger { private final Logger delegate; DelegatingLogger(Logger delegate) { this.delegate = delegate; } @Override public String getName() { return delegate.getName(); } @Override public boolean isTraceEnabled() { return delegate.isTraceEnabled(); } @Override public boolean isTraceEnabled(Marker marker) { return delegate.isTraceEnabled(marker); } @Override public void trace(String msg) { delegate.trace(msg); } @Override public void trace(String format, Object arg) { delegate.trace(format, arg); } @Override public void trace(String format, Object arg1, Object arg2) { delegate.trace(format, arg1, arg2); } @Override public void trace(String format, Object... arguments) { delegate.trace(format, arguments); } @Override public void trace(String msg, Throwable throwable) { delegate.trace(msg, throwable); } @Override public void trace(Marker marker, String msg) { delegate.trace(marker, msg); } @Override public void trace(Marker marker, String format, Object arg) { delegate.trace(marker, format, arg); } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { delegate.trace(marker, format, arg1, arg2); } @Override public void trace(Marker marker, String format, Object... argArray) { delegate.trace(marker, format, argArray); } @Override public void trace(Marker marker, String msg, Throwable throwable) { delegate.trace(marker, msg, throwable); } @Override public boolean isDebugEnabled() { return delegate.isDebugEnabled(); } @Override public boolean isDebugEnabled(Marker marker) { return delegate.isDebugEnabled(marker); } @Override public void debug(String msg) { delegate.debug(msg); } @Override public void debug(String format, Object arg) { delegate.debug(format, arg); } @Override public void debug(String format, Object arg1, Object arg2) { delegate.debug(format, arg1, arg2); } @Override public void debug(String format, Object... arguments) { delegate.debug(format, arguments); } @Override public void debug(String msg, Throwable throwable) { delegate.debug(msg, throwable); } @Override public void debug(Marker marker, String msg) { delegate.debug(marker, msg); } @Override public void debug(Marker marker, String format, Object arg) { delegate.debug(marker, format, arg); } @Override public void debug(Marker marker, String format, Object arg1, Object arg2) { delegate.debug(marker, format, arg1, arg2); } @Override public void debug(Marker marker, String format, Object... arguments) { delegate.debug(marker, format, arguments); } @Override public void debug(Marker marker, String msg, Throwable throwable) { delegate.debug(marker, msg, throwable); } @Override public boolean isInfoEnabled() { return delegate.isInfoEnabled(); } @Override public boolean isInfoEnabled(Marker marker) { return delegate.isInfoEnabled(marker); } @Override public void info(String msg) { delegate.info(msg); } @Override public void info(String format, Object arg) { delegate.info(format, arg); } @Override public void info(String format, Object arg1, Object arg2) { delegate.info(format, arg1, arg2); } @Override public void info(String format, Object... arguments) { delegate.info(format, arguments); } @Override public void info(String msg, Throwable throwable) { delegate.info(msg, throwable); } @Override public void info(Marker marker, String msg) { delegate.info(marker, msg); } @Override public void info(Marker marker, String format, Object arg) { delegate.info(marker, format, arg); } @Override public void info(Marker marker, String format, Object arg1, Object arg2) { delegate.info(marker, format, arg1, arg2); } @Override public void info(Marker marker, String format, Object... arguments) { delegate.info(marker, format, arguments); } @Override public void info(Marker marker, String msg, Throwable throwable) { delegate.info(marker, msg, throwable); } @Override public boolean isWarnEnabled() { return delegate.isWarnEnabled(); } @Override public boolean isWarnEnabled(Marker marker) { return delegate.isWarnEnabled(marker); } @Override public void warn(String msg) { delegate.warn(msg); } @Override public void warn(String format, Object arg) { delegate.warn(format, arg); } @Override public void warn(String format, Object... arguments) { delegate.warn(format, arguments); } @Override public void warn(String format, Object arg1, Object arg2) { delegate.warn(format, arg1, arg2); } @Override public void warn(String msg, Throwable throwable) { delegate.warn(msg, throwable); } @Override public void warn(Marker marker, String msg) { delegate.warn(marker, msg); } @Override public void warn(Marker marker, String format, Object arg) { delegate.warn(marker, format, arg); } @Override public void warn(Marker marker, String format, Object arg1, Object arg2) { delegate.warn(marker, format, arg1, arg2); } @Override public void warn(Marker marker, String format, Object... arguments) { delegate.warn(marker, format, arguments); } @Override public void warn(Marker marker, String msg, Throwable throwable) { delegate.warn(marker, msg, throwable); } @Override public boolean isErrorEnabled() { return delegate.isErrorEnabled(); } @Override public boolean isErrorEnabled(Marker marker) { return delegate.isErrorEnabled(marker); } @Override public void error(String msg) { delegate.error(msg); } @Override public void error(String format, Object arg) { delegate.error(format, arg); } @Override public void error(String format, Object arg1, Object arg2) { delegate.error(format, arg1, arg2); } @Override public void error(String format, Object... arguments) { delegate.error(format, arguments); } @Override public void error(String msg, Throwable throwable) { delegate.error(msg, throwable); } @Override public void error(Marker marker, String msg) { delegate.error(marker, msg); } @Override public void error(Marker marker, String format, Object arg) { delegate.error(marker, format, arg); } @Override public void error(Marker marker, String format, Object arg1, Object arg2) { delegate.error(marker, format, arg1, arg2); } @Override public void error(Marker marker, String format, Object... arguments) { delegate.error(marker, format, arguments); } @Override public void error(Marker marker, String msg, Throwable throwable) { delegate.error(marker, msg, throwable); } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.utils.concurrent.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.opendaylight.infrautils.utils.concurrent.LoggingFutures.addErrorLogging; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import org.junit.Rule; import org.junit.Test; import org.opendaylight.infrautils.testutils.LogCaptureRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit test, and example, for how to correctly log failures from async calls * returning Future. * * @author <NAME> */ public class FutureListenerLogTest { private static final Logger LOG = LoggerFactory.getLogger(FutureListenerLogTest.class); @Rule public LogCaptureRule logCaptureRule = new LogCaptureRule(); @Test public void testFailingListenableFuture() { logCaptureRule.expectError("Future (eventually) failed: duh"); ListenableFuture<Void> failedFuture = Futures.immediateFailedFuture(new Exception("some problem")); assertSame(failedFuture, addErrorLogging(failedFuture, LOG, "duh")); } @Test public void testPassingListenableFuture() { ListenableFuture<String> stringFuture = Futures.immediateFuture("hello"); assertSame(stringFuture, addErrorLogging(stringFuture, LOG, "huh?!")); } @Test public void testFailingListenableFutureWithOneMessageFormatArgument() { logCaptureRule.expectError("Future (eventually) failed: duh dah"); ListenableFuture<Integer> failedFuture = Futures.immediateFailedFuture(new Exception("some problem")); assertSame(failedFuture, addErrorLogging(failedFuture, LOG, "duh {}", new ObjectWithToString("dah"))); } @Test public void testFailingListenableFutureWithTwoMessageFormatArguments() { logCaptureRule.expectError("Future (eventually) failed: duh bah doo"); ListenableFuture<Integer> failedFuture = Futures.immediateFailedFuture(new Exception("some problem")); assertSame(failedFuture, addErrorLogging(failedFuture, LOG, "duh {} {}", new ObjectWithToString("bah"), new ObjectWithToString("doo"))); } @Test public void testFailingListenableFutureWithThreeMessageFormatArguments() { logCaptureRule.expectError("Future (eventually) failed: ho/he/do"); ListenableFuture<Integer> failedFuture = Futures.immediateFailedFuture(new Exception("some problem")); assertSame(failedFuture, addErrorLogging(failedFuture, LOG, "{}/{}/{}", new ObjectWithToString("ho"), new ObjectWithToString("he"), new ObjectWithToString("do"))); assertEquals("some problem", logCaptureRule.getLastErrorThrowable().getMessage()); } private static final class ObjectWithToString { private final String string; ObjectWithToString(String string) { this.string = string; } @Override public String toString() { return string; } } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- vi: set et smarttab sw=2 tabstop=2: --> <!-- Copyright © 2017 Red Hat, Inc. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.opendaylight.infrautils</groupId> <artifactId>parent</artifactId> <version>6.0.2-SNAPSHOT</version> <relativePath>../../common/parent</relativePath> </parent> <artifactId>itestutils</artifactId> <packaging>bundle</packaging> <!-- <name> formatting is used by autorelease to parse and notify projects on build failure. Please do not modify this unless you have a good reason. --> <name>ODL :: infrautils :: ${project.artifactId}</name> <properties> <!-- TODO Figure out and fix the Found duplicate and different classes in [org.ops4j.pax.url:pax-url-aether:2.5.3, org.ops4j.pax.url:pax-url-commons:2.5.3] --> <duplicate-finder.skip>true</duplicate-finder.skip> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>infrautils-testutils</artifactId> <scope>compile</scope> </dependency> <!-- Dependencies for PAX Exam karaf container --> <dependency> <groupId>com.guicedee.services</groupId> <artifactId>javax.inject</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>osgi.core</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-container-karaf</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-junit4</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.ops4j.pax.url</groupId> <artifactId>pax-url-link</artifactId> <scope>compile</scope> </dependency> <!-- <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-link-assembly</artifactId> <scope>compile</scope> </dependency> --> <!-- TODO Remove pax-url-aether once alta-maven-plugin switch is fully completed which will require fixing https://ops4j1.jira.com/browse/PAXEXAM-813 --> <dependency> <groupId>org.ops4j.pax.url</groupId> <artifactId>pax-url-aether</artifactId> <scope>compile</scope> </dependency> <!-- <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>org.apache.karaf.features.core</artifactId> </dependency> --> <dependency> <groupId>org.opendaylight.odlparent</groupId> <artifactId>opendaylight-karaf-empty</artifactId> <version>13.0.3</version> <type>tar.gz</type> <exclusions> <!-- The transitive dependencies are unnecessary, because PAX Exam uses the distribution. it has absolutely no value/advantage having this here; on the contrary, the disadvantages include: * conceptually wrong in OSGi, the tests classpath should not have the container's code * practically wrong, and screws up the test's classpath, which e.g. breaks the logging in the console/surefire * every build re-downloads this huge SNAPSHOT artifact unncessarily, even if you're not running the IT The test enforces that this is not present on the classpath, and fails if Karaf's main is on the CP! --> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>standard</artifactId> <classifier>features</classifier> <type>xml</type> </dependency> </dependencies> </project> <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- Copyright © 2017 Red Hat, Inc. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.opendaylight.infrautils</groupId> <artifactId>parent</artifactId> <version>6.0.2-SNAPSHOT</version> <relativePath>../../common/parent</relativePath> </parent> <artifactId>ready-impl</artifactId> <packaging>bundle</packaging> <!-- <name> formatting is used by autorelease to parse and notify projects on build failure. Please do not modify this unless you have a good reason. --> <name>ODL :: infrautils :: ${project.artifactId}</name> <dependencies> <dependency> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-annotations</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.framework</artifactId> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.metatype.annotations</artifactId> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.component.annotations</artifactId> </dependency> <dependency> <groupId>org.opendaylight.infrautils</groupId> <artifactId>ready-api</artifactId> </dependency> <dependency> <groupId>org.opendaylight.infrautils</groupId> <artifactId>infrautils-util</artifactId> </dependency> <dependency> <groupId>org.opendaylight.odlparent</groupId> <artifactId>bundles-test-lib</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.karaf.bundle</groupId> <artifactId>org.apache.karaf.bundle.core</artifactId> <scope>provided</scope> </dependency> <!-- We HAVE to list hamcrest and awaitility as dependencies here, not because we need to compile against it, but so that the Embed-Dependency in the maven-bundle-plugin below works! --> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <scope>compile</scope> <exclusions> <exclusion> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> </exclusion> <exclusion> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.opendaylight.infrautils</groupId> <artifactId>infrautils-testutils</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <configuration> <instructions> <Automatic-Module-Name>org.opendaylight.infrautils.ready.karaf</Automatic-Module-Name> <Embed-Dependency>bundles-test-lib,awaitility,hamcrest</Embed-Dependency> <!-- Do NOT <Embed-Transitive>true</Embed-Transitive> --> </instructions> </configuration> </plugin> </plugins> </build> </project> <file_sep> .. contents:: Table of Contents :depth: 3 ================================ Status And Diagnostics Framework ================================ https://git.opendaylight.org/gerrit/#/q/topic:s-n-d Status reporting is an important part of any system. This document explores and describes various implementation options for achieving the feature. Problem description =================== Today ODL does not have a centralized mechanism to do status and diagnostics of the various service modules, and have predictable system initialization. This leads to a lot of confusions on when a particular service should start acting upon the various incoming system events, because in many cases(like restarts) services end up doing premature service handling. The feature aims at developing a status and diagnostics framework for ODL, which can : * Orchestrate predictable system initialization, by enabling external interfaces, including northbound and southbound interfaces depending on a set of selected services declaring their availability. This in turn can prevent the system from processing northbound (eg: OpenStack), or southbound (eg: OVSDB or OpenFlow) events prematurely before all services are ready. * Perform continuous monitoring of registered modules or internal services to ensure overall health of the system. This can additionally trigger alarms, or node reboots when individual services fail. Use Cases --------- This feature will support following use cases: * Use case 1: diagstatus module uses apis to create an application which can declare the system as UP. * Use case 2: Core services can include existing netvirt and genius services like ELAN, L3VPN, ITM, interface-manager, DataStore and additional services may be ACL, QoS etc as needed. Applications can take necessary actions based on the aggregate system status, for eg: OpenFlow port open, OVSDB port open, and S&D status update(for consumption by other NBs such as ODL Mechanism Driver) * Use case 3: Registered Service Modules should expose their status to diagstatus module which inturn will use this information to expose the service status to others. * Use case 4: All southbound plugins should leverage the status provided by diagstatus module, as well as config file settings, to block or unblock the southbound interface * Use case 5: diagstatus module should monitor the health of all dependant services on a regular basis using JMX. * Use case 6: diagstatus module should raise traps whenever health check on a module fails. * Use case 7 : diagstatus module should develop the capability to do a node/cluster reboot in future for scenarios mentioned in usecase 6. * Use case 8 : diagstatus module should leverage on the counters support provided by infrautils to expose some debug and diagnostics counters. Proposed change =============== The proposed feature adds a new module in infrautils called "diagstatus", which allows CLI or alternative suitable interface to query the status of the services running in context of the controller (interface like Openflow, OVSDB, ELAN,ITM, IFM, Datastore etc.). This also allows individual services to push status-changes to this centralized module via suitable API-based notification. There shall be a generic set of events which application can report to the central monitoring module/service which shall be used by the service to update the latest/current status of the services. Service startup Requirements ---------------------------- * Since the statuses are stored local to the node and represents the states of individual services instances of the node, there is no data-sync-up requirements for this service * When the service starts-up, required local map for managing service-wise status entries shall be initialized * It must be ensured that the status-monitoring-service starts-up fast as service whenever is started/re-booted. Service API requirements ------------------------ Status model object encapsulating the metadata of status such as: * Node-name – may be this could be populated internally by framework if the node-name is available from within the framework with lesser / no external dependencies * Module-name – populated by status-reporting module * Service-name – populated by status-reporting module * Service-status – populated by status-reporting module * Current timestamp – internally populated * Status Description – Any specific textual content which service can add to aid better troubleshooting of reported status Service Internal Functionality Requirements ------------------------------------------- * Data for current status of the changes alone must be maintained. Later we can improve it to maintain history of statuses for a given service * Since the statuses of services are dynamic there is no persistence requirement to store the statuses * Status entry of given service shall be updated based on the metadata of provided by services * Entries for service statuses shall be created lazily - if they are not already present, as and when first API invocation is made by the application-module towards the status/health monitoring service * Read APIs of Monitoring-Service expose the service statuses on per cluster-node basis only. A separate module shall be developed as part of “cluster-services” user-story which can combine cross-cluster status collation * All output of the read-APIs shall return results as Map with URI as key and current service-status and last-update timestamp combined as value * In order to check the status of registered services, Status-Monitoring Service shall use standard scheduled timer service to invoke status-check callback on registered services * Scheduled probe timer interval shall be configurable in config.ini. Any changes to this configuration shall require the system restart Service Shutdown Requirements ----------------------------- * Currently no specific requirements around this area as restarting or node moving to quiescent state results in loss of all local data Instrumentation Requirements ---------------------------- Applications must invoke status-reporting APIs as required across the lifecycle of the services in start-up, operational and graceful shutdown phases In order to emulate a simpler state-machine, we can have services report following statuses * STARTING – at the start of onSessionInitiated() on instrumented service * OPERATIONAL – at the end of onSessionInitiated() on instrumented service * ERROR – if any exception is caught during the service bring-up of if the service goes into an ERROR state dynamically * REGISTER – on successful registration of instrumented service * UNREGISTER – when a service does unregister from diagstatus on its own YANG changes ------------ N/A Workflow -------- Register Service ^^^^^^^^^^^^^^^^ Whenever the new service comes up, the service provider should register new service in service registry. Report Status ^^^^^^^^^^^^^ Application can report their status using diagstatus APIs Read Service Status ^^^^^^^^^^^^^^^^^^^ Whenever applications/CLI try to fetch the service status, diagstatus module will query the status through the respective Service implementations exposed by each service, and an aggregated result is provided as response. Clustering considerations ------------------------- * The CLIs/APIs provided by diagstatus module will be cluster wide. * Every node shall expose a Status Check MBean for querying the current status which is local to the node being queried. * Every node shall also expose a Clusterwide Status Check MBean for querying the clusterwide Status of services. * For local status CLI shall query local MBean. * For clusterwide status CLI shall query local MBean AS WELL AS and remote MBean instances across all current members of the cluster by accessing respective PlatformMBeanServer locally and remotely. * It is assumed that IP Addresses of the current nodes of cluster and standard JMX Port details are available for clusterwide MBeans * CLI local to any of the cluster members shall invoke clusterwide MBean on ANY ONE of current set of cluster nodes * Every node of cluster shall query all peer nodes using the JMX interface and consolidate the statuses reported by each node of cluster and return combined node-wise statuses across the cluster Other Infra considerations -------------------------- N.A. Security considerations ----------------------- N.A. Scale and Performance Impact ---------------------------- N/A as it is a new feature which does not impact any current functionality. Targeted Release(s) ------------------- Carbon. Known Limitations ----------------- The initial feature will not have the health check functionality. The initial feature will not have integration to infrautils counter framework for dispalying diag-counters. Alternatives ------------ N/A Usage ===== Features to Install ------------------- This feature adds a new karaf feature, which is odl-infrautils-diagstatus. JAVA API -------- Following are the service APIs which must be supported by the Framework : * Accept Service-status from services which invoke the framework * Get the current statuses of all services of a given cluster-node * A registration API to allow monitored service to register the callback * An interface which is to be implemented by monitored module which could be periodically invoked by Status-Monitoring framework on each target module to check status * Each service implements their own logic to check the local-health status using the interface and report the status CLI --- Following CLIs will be supported as part of this feature: * showSvcStatus - get remote service status OSGI Services ------------- Following osgi services will be supported as part of this feature: * DiagStatusService - provides APIs for application to register and unregister services and report service status * ServiceStatusProvider - provide information of registered service from ServiceDescriptor Implementation ============== Assignee(s) ----------- Primary assignee: <<NAME>> Other contributors: <<NAME>> Work Items ---------- #. spec review #. diagstatus module bring-up #. API definitions #. Aggregate the status of services from each node #. Migrate All Application to Diagstatus #. Integrate all application #. Add CLI. #. Add UTs. #. Add Documentation Dependencies ============ This is a new module and requires the below libraries: * org.apache.maven.plugins * com.google.code.gson * com.google.guava This change is backwards compatible, so no impact on dependent projects. Projects can choose to start using this when they want. Following projects currently depend on InfraUtils: * Netvirt * Genius Testing ======= Unit Tests ---------- Appropriate UTs will be added for the new code coming in once framework is in place. Integration Tests ----------------- Since Component Style unit tests will be added for the feature, no need for ITs CSIT ---- N/A Documentation Impact ==================== This will require changes to User Guide and Developer Guide. User Guide will need to add information on how to use status-and-diag APIs and CLIs Developer Guide will need to capture how to use the APIs of status-and-diag module to derive service specific actions. Also, the documentation needs to capture how services can expose their status via Mbean and integrate the same to status-and-diag module References ========== * https://wiki.opendaylight.org/view/Infrastructure_Utilities:Carbon_Release_Plan <file_sep>/* * Copyright © 2018 Red Hat, Inc. and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.inject.spi; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Test; public class ClassPathScannerTest { private static final String PREFIX = ClassPathScannerTest.class.getPackageName(); @Test public void testClasspathScanning() { Set<Class<?>> singletons = new HashSet<>(); Map<Class<?>, Class<?>> bindings = new HashMap<>(); new ClassPathScanner(PREFIX).bindAllSingletons(PREFIX, bindings::put, singletons::add); assertEquals(Map.of( ClassPathScannerTestTopInterface.class, ClassPathScannerTestImplementation.class, ClassPathScannerTestAnotherInterface.class, ClassPathScannerTestImplementation.class), bindings); assertEquals(Set.of(ClassPathScannerTestNoInterfacesImplementation.class), singletons); } @Test public void testClasspathExclusion() { Set<Class<?>> singletons = new HashSet<>(); Map<Class<?>, Class<?>> bindings = new HashMap<>(); new ClassPathScanner(PREFIX).bindAllSingletons("nope", bindings::put, singletons::add); assertEquals(Map.of(), bindings); assertEquals(Set.of(), singletons); } } <file_sep>/* * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus; import java.net.InetAddress; import java.util.List; /** * ODL cluster information. * * @author <NAME> */ @Deprecated(forRemoval = true) public interface ClusterMemberInfo { InetAddress getSelfAddress(); List<InetAddress> getClusterMembers(); boolean isLocalAddress(InetAddress ipAddress); } <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus.shell; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.net.InetAddresses; import java.net.Inet6Address; import java.net.InetAddress; import java.net.URI; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.Date; import java.util.List; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.Option; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.infrautils.diagstatus.ClusterMemberInfo; import org.opendaylight.infrautils.diagstatus.DiagStatusServiceMBean; import org.opendaylight.infrautils.diagstatus.ServiceDescriptor; import org.opendaylight.infrautils.diagstatus.ServiceStatusSummary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * CLI for showing registered service status. * * @author <NAME> */ @Command(scope = "diagstatus", name = "showSvcStatus", description = "show the status of registered services") @Service public class DiagStatusCommand implements Action { private static final Logger LOG = LoggerFactory.getLogger(DiagStatusCommand.class); private static final Duration HTTP_TIMEOUT = Duration.ofSeconds(5); private static final String DIAGSTATUS_URL_PREFIX = "http://"; @VisibleForTesting static final String DIAGSTATUS_URL_SUFFIX = "diagstatus"; @VisibleForTesting static final char DIAGSTATUS_URL_SEPARATOR = '/'; @Reference @VisibleForTesting DiagStatusServiceMBean diagStatusServiceMBean; @Reference @VisibleForTesting ClusterMemberInfo clusterMemberInfoProvider; @Reference @VisibleForTesting HttpClientService httpClient; @Option(name = "-n", aliases = {"--node"}) String nip; @Override @SuppressWarnings({ "checkstyle:IllegalCatch", "checkstyle:RegexpSinglelineJava" }) public @Nullable Object execute() throws Exception { StringBuilder strBuilder = new StringBuilder(); strBuilder.append("Timestamp: ").append(new Date().toString()).append("\n"); if (null != nip) { strBuilder.append(getNodeSpecificStatus(InetAddresses.forString(nip))); } else { List<InetAddress> clusterIPAddresses = clusterMemberInfoProvider.getClusterMembers(); if (!clusterIPAddresses.isEmpty()) { InetAddress selfAddress = clusterMemberInfoProvider.getSelfAddress(); for (InetAddress memberAddress : clusterIPAddresses) { try { if (memberAddress.equals(selfAddress)) { strBuilder.append(getLocalStatusSummary(memberAddress)); } else { strBuilder.append(getRemoteStatusSummary(memberAddress)); } } catch (Exception e) { strBuilder.append("Node IP Address: ") .append(memberAddress).append(" : status retrieval failed due to ") .append(e.getMessage()).append("\n"); LOG.error("Exception while reaching Host {}", memberAddress, e); } } } else { LOG.info("Could not obtain cluster members or the cluster-command is being executed locally\n"); strBuilder.append(getLocalStatusSummary(InetAddress.getLoopbackAddress())); } } System.out.println(strBuilder.toString()); return null; } @VisibleForTesting String getLocalStatusSummary(InetAddress memberAddress) { return "Node IP Address: " + memberAddress.getHostAddress() + "\n" + diagStatusServiceMBean.acquireServiceStatusDetailed(); } @VisibleForTesting String getRemoteStatusSummary(InetAddress memberAddress) throws Exception { return new StringBuilder() .append("Node IP Address: ").append(memberAddress.getHostAddress()).append("\n") .append(invokeRemoteDiagStatus(memberAddress)) .toString(); } String invokeRemoteDiagStatus(InetAddress host) throws Exception { String restUrl = buildRemoteDiagStatusUrl(host); LOG.info("invokeRemoteDiagStatus() REST URL: {}", restUrl); HttpRequest request = HttpRequest.newBuilder(new URI(restUrl)) .GET() .timeout(HTTP_TIMEOUT) .header("Accept", "application/json") .header("Content-Type", "application/json") .build(); LOG.debug("sending http request for accessing remote diagstatus"); HttpResponse<String> response = httpClient.sendRequest(request); // Response code for success should be 200 int httpResponseCode = response.statusCode(); LOG.debug("http response received for remote diagstatus {}", httpResponseCode); String respStr = response.body(); if (httpResponseCode > 299) { LOG.error("Non-200 http response code received {} for URL {}", httpResponseCode, restUrl); if (respStr == null) { return "Service Status Retrieval failed. HTTP Response Code : " + httpResponseCode + "\n"; } } LOG.trace("HTTP Response is - {} for URL {}", respStr, restUrl); return buildServiceStatusSummaryString(ServiceStatusSummary.fromJSON(respStr)); } private static String buildServiceStatusSummaryString(ServiceStatusSummary serviceStatusSummary) { StringBuilder statusSummary = new StringBuilder() .append("System is operational: ").append(serviceStatusSummary.isOperational()).append('\n') .append("System ready state: ").append(serviceStatusSummary.getSystemReadyState()).append('\n'); for (ServiceDescriptor status : serviceStatusSummary.getStatusSummary()) { statusSummary .append(" ") // the magic is the max String length of ServiceState enum values, plus padding .append(String.format("%-20s%-15s", status.getModuleServiceName(), ": " + status.getServiceState())); if (!Strings.isNullOrEmpty(status.getStatusDesc())) { statusSummary.append(" (").append(status.getStatusDesc()).append(')'); } // intentionally using Throwable.toString() instead of Throwables.getStackTraceAsString to keep CLI brief status.getErrorCause().ifPresent(cause -> statusSummary.append(cause.toString())); statusSummary.append("\n"); } return statusSummary.toString(); } @VisibleForTesting String buildRemoteDiagStatusUrl(InetAddress host) { String targetHostAsString; if (host instanceof Inet6Address) { targetHostAsString = '[' + host.getHostAddress() + ']'; } else { targetHostAsString = host.getHostAddress(); } return new StringBuilder().append(DIAGSTATUS_URL_PREFIX + targetHostAsString + ":" + httpClient.getHttpPort() + DIAGSTATUS_URL_SEPARATOR + DIAGSTATUS_URL_SUFFIX + DIAGSTATUS_URL_SEPARATOR).toString(); } @SuppressWarnings("checkstyle:IllegalCatch") private String getNodeSpecificStatus(InetAddress ipAddress) { StringBuilder strBuilder = new StringBuilder(); if (isIPAddressInCluster(ipAddress)) { InetAddress selfAddress = clusterMemberInfoProvider.getSelfAddress(); if (ipAddress.equals(selfAddress)) { // Local IP Address strBuilder.append(getLocalStatusSummary(ipAddress)); } else { // Remote IP try { strBuilder.append(getRemoteStatusSummary(ipAddress)); } catch (Exception e) { strBuilder.append("Remote Status retrieval JMX Operation failed for node: ").append(ipAddress); LOG.error("Exception while reaching Host: {}", ipAddress, e); } } } else { strBuilder.append("Invalid IP Address or Not a cluster member IP Address: ").append(ipAddress); } return strBuilder.toString(); } private boolean isIPAddressInCluster(InetAddress ipAddress) { List<InetAddress> clusterIPAddresses = clusterMemberInfoProvider.getClusterMembers(); if (!clusterIPAddresses.contains(ipAddress)) { LOG.error("specified ip {} is not present in cluster", ipAddress); return false; } return true; } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils; import java.util.List; import java.util.Map; import junit.framework.AssertionFailedError; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * JUnit Rule to run detect duplicate entries on the classpath. Usage: * * <pre>public static {@literal @}ClassRule ClasspathHellDuplicatesCheckRule * dupes = new ClasspathHellDuplicatesCheckRule();</pre> * * <p>NB that the basepom/duplicate-finder-maven-plugin already runs as part of odlparent. * It has a similar purpose, but covers build time instead of runtime testing. This JUnit Rule class is * thus recommended to be used in particular in tests which previously ran into JAR Hell issues, and for * which non-regression with a clear failure message in case of future similar problems is important. * (This provides more details at runtime than duplicate-finder-maven-plugin does at build time.) * * @author <NAME> */ public class ClasspathHellDuplicatesCheckRule implements TestRule { private final ClasspathHellDuplicatesChecker checker; public ClasspathHellDuplicatesCheckRule(ClasspathHellDuplicatesChecker checker) { this.checker = checker; } public ClasspathHellDuplicatesCheckRule() { this(ClasspathHellDuplicatesChecker.INSTANCE); } @Override public Statement apply(Statement base, Description description) { checkClasspath(); return base; } protected void checkClasspath() { Map<String, List<String>> dupes = checker.getDuplicates(); if (!dupes.isEmpty()) { throw new AssertionFailedError("Classpath duplicates detected: " + checker.toString(dupes)); } } } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ /** * The interfaces and classes in this package are "for convenience". Technically * you do NOT have to implement or extend any of these to work with Dependency * Injection - and could instead just apply these annotations to a class * yourself etc. But defining this once and encouraging projects to use this * establishes uniformity, which also helps other reading your code to recognize * a class as being of the respective kind. */ package org.opendaylight.infrautils.inject; <file_sep>/* * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.diagstatus.internal; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import org.opendaylight.infrautils.diagstatus.ServiceStatusProvider; import org.opendaylight.infrautils.ready.SystemReadyMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DiagStatusServiceImpl is the core class having the functionality for tracking the registered services * and aggregating the status of the same. * @author <NAME> */ @Singleton public class DiagStatusServiceImpl extends AbstractDiagStatusService { private static final Logger LOG = LoggerFactory.getLogger(DiagStatusServiceImpl.class); private final List<ServiceStatusProvider> serviceStatusProviders; private final SystemReadyMonitor systemReadyMonitor; @Inject public DiagStatusServiceImpl(List<ServiceStatusProvider> serviceStatusProviders, SystemReadyMonitor systemReadyMonitor) { this.systemReadyMonitor = systemReadyMonitor; this.serviceStatusProviders = serviceStatusProviders; LOG.info("{} started", getClass().getSimpleName()); } @Override SystemReadyMonitor systemReadyMonitor() { return systemReadyMonitor; } @Override Iterable<? extends ServiceStatusProvider> serviceStatusProviders() { return serviceStatusProviders; } } <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.inject.guice.testutils.tests; import static org.junit.Assert.assertThrows; import com.google.inject.AbstractModule; import org.junit.Test; import org.junit.runners.model.Statement; import org.opendaylight.infrautils.inject.guice.testutils.GuiceRule; /** * Tests friendly and more helpful than default error message in case * AnnotationsModule was forgotten to be found. * * @author <NAME> */ public class GuiceRuleForgotAnnotationsModuleTest { // This is intentional, with this it fails expectedly; remove to see how // public @Rule GuiceRule guice = new GuiceRule(TestModule.class); @Test public void testGuiceWithRule() { Statement stmt = new GuiceRule(TestModule.class).apply(null, null, null); assertThrows(IllegalStateException.class, () -> stmt.evaluate()); } public static class TestModule extends AbstractModule { @Override protected void configure() { } } } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.mockito; import com.google.errorprone.annotations.Var; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.regex.Pattern; import org.checkerframework.checker.regex.qual.Regex; /** * Nicer shorter toString() for {@link Method} than it's default. * * <p>Without modifiers, return type, FQN of class and exceptions; instead with parameter names (if javac -parameters). * * @author <NAME> */ final class MethodExtensions { // Intentionally just package local; if this is of interest elsewhere, // then move it to org.opendaylight.infrautils.utils instead of keeping it here. @Regex private static final String PARAM_PATTERN_STR = "\\[\\]$"; private static final Pattern PARAM_PATTERN = Pattern.compile(PARAM_PATTERN_STR); private MethodExtensions() { } public static String toString(Method method) { StringBuilder sb = new StringBuilder(); sb.append(method.getName()); // copy/paste from java.lang.reflect.Executable.sharedToGenericString(int, boolean) sb.append('('); Type[] params = method.getGenericParameterTypes(); // NEW Parameter[] parameters = method.getParameters(); for (int j = 0; j < params.length; j++) { @Var String param = params[j].getTypeName(); if (method.isVarArgs() && j == params.length - 1) { // replace T[] with T... param = PARAM_PATTERN.matcher(param).replaceFirst("..."); } sb.append(param); // NEW if (parameters[j].isNamePresent()) { sb.append(' '); sb.append(parameters[j].getName()); } // NEW END if (j < params.length - 1) { // NEW ", " instead of ',' sb.append(", "); } } sb.append(')'); return sb.toString(); } } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * JUnit Rule which allows to keep running tests indefinitely. * * <p>This is useful to add locally, never commit, if you would like to * keep running a "flaky" (sometimes passing, sometimes failing) test * until it fails. Usage: * * <pre> * public static {@literal @}ClassRule RunUntilFailureClassRule classRepeater = new RunUntilFailureClassRule(); * public {@literal @}Rule RunUntilFailureRule repeater = new RunUntilFailureRule(classRepeater); * * {@literal @}Test ...</pre> * * <p>The two rules are necessary because a ClassRule alone cannot stop the test on a failure, * and a normal Rule alone cannot keep running all {@literal @}Test (it would indefinitely run * only the first test). Alternatives to two rules would be to use a {@literal @}RunWith * with a custom TestRunner, or writing a test suite each time. * * @author <NAME> */ public class RunUntilFailureRule implements TestRule { private final RunUntilFailureClassRule classRepeaterRule; public RunUntilFailureRule(RunUntilFailureClassRule classRepeaterRule) { this.classRepeaterRule = classRepeaterRule; } @Override public Statement apply(Statement statement, Description description) { return new RunUntilFailureStatement(statement, description); } private class RunUntilFailureStatement extends Statement { final Statement statement; RunUntilFailureStatement(Statement statement, Description description) { this.statement = statement; } @Override @SuppressWarnings("checkstyle:IllegalCatch") public void evaluate() throws Throwable { try { statement.evaluate(); } catch (Throwable throwable) { classRepeaterRule.isRunning = false; throw throwable; } } } } <file_sep>/* * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.mockito; import java.io.Serializable; import org.mockito.Mockito; import org.mockito.internal.stubbing.answers.ThrowsException; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** * Mockito Answer which for un-stubbed methods throws an * UnstubbedMethodException (instead of Mockito's default of returning null). * * <p> * Usage: * * <pre> * import static ...testutils.mockito.MoreAnswers.exception; * * Mockito.mock(YourInterface.class, exception()) * </pre> * * @see Mockito#mock(Class, Answer) * * @see ThrowsException * * @author <NAME> */ final class ThrowsMethodExceptionAnswer implements Answer<Object>, Serializable { // intentionally just package local, // make public if there ever is any direct use for this instead through MoreAnswers private static final long serialVersionUID = -7316574192253912318L; static final ThrowsMethodExceptionAnswer INSTANCE = new ThrowsMethodExceptionAnswer(); private ThrowsMethodExceptionAnswer() { } @Override public Void answer(InvocationOnMock invocation) { throw new UnstubbedMethodException(invocation.getMethod()); } Object readResolve() { return INSTANCE; } } <file_sep>/* * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.inject.guice; import com.google.inject.Binder; import javax.inject.Singleton; import org.opendaylight.infrautils.inject.spi.ClassPathScanner; /** * Binds interfaces to implementations in Guice by scanning the classpath. */ public class GuiceClassPathBinder { private final ClassPathScanner scanner; public GuiceClassPathBinder(String prefix) { this.scanner = new ClassPathScanner(prefix); } /** * Binds all {@link Singleton} annotated classes discovered by scanning the class path to all their interfaces. * * @param prefix the package prefix of Singleton implementations to consider * @param binder The binder to set up. */ @SuppressWarnings("unchecked") public void bindAllSingletons(String prefix, Binder binder) { scanner.bindAllSingletons(prefix, (contract, implementation) -> binder.bind(contract).to(implementation), singleton -> binder.bind(singleton)); } } <file_sep>.. Infrautils documentation master file, created by sphinx-quickstart on Sun Dec 03 21:47:32 2016. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Infrautils Documentation ======================== This documentation provides critical information needed to help you write ODL Applications/Projects using Infrautils, which offers various generic utilities and infrastructure for ease of application development. Contents: .. toctree:: :maxdepth: 1 specs/index getting-started-guide/index <file_sep>/* * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.infrautils.testutils.internal; import static java.util.Collections.synchronizedList; import static org.opendaylight.infrautils.testutils.LogCapture.Level.ERROR; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.opendaylight.infrautils.testutils.LogCapture; import org.opendaylight.infrautils.testutils.LogRule; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; /** * A slf4j logger implementation which remembers log events. This class is thread-safe. * * @author <NAME> */ public class RememberingLogger extends DelegatingLogger { // TODO add the same for warn, info, debug trace ... private static final List<LogCapture> ERRORS = synchronizedList(new ArrayList<>()); RememberingLogger(Logger delegate) { super(delegate); } public static ImmutableList<LogCapture> getErrorLogCaptures() { return ImmutableList.copyOf(ERRORS); } public static Optional<String> getLastErrorMessage() { return getErrorMessage(0); } public static Optional<String> getErrorMessage(int howManyMessagesBack) { if (ERRORS.size() > howManyMessagesBack) { return Optional.ofNullable(ERRORS.get(ERRORS.size() - howManyMessagesBack - 1).getMessage()); } return Optional.empty(); } public static Optional<Throwable> getLastErrorThrowable() { return getErrorThrowable(0); } public static Optional<Throwable> getErrorThrowable(int howManyMessagesBack) { if (ERRORS.size() > howManyMessagesBack) { return ERRORS.get(ERRORS.size() - howManyMessagesBack - 1).getCause(); } return Optional.empty(); } public static void resetLastError() { ERRORS.clear(); } @Override public void error(String msg) { ERRORS.add(new LogCapture(ERROR, msg, null)); super.error(msg); } @Override public void error(String format, Object arg) { FormattingTuple mf = MessageFormatter.format(format, arg); ERRORS.add(new LogCapture(ERROR, mf.getMessage(), mf.getThrowable())); super.error(format, arg); } @Override public void error(String format, Object arg1, Object arg2) { FormattingTuple mf = MessageFormatter.format(format, arg1, arg2); ERRORS.add(new LogCapture(ERROR, mf.getMessage(), mf.getThrowable())); super.error(format, arg1, arg2); } @Override public void error(String format, Object... arguments) { FormattingTuple mf = MessageFormatter.arrayFormat(format, arguments); ERRORS.add(new LogCapture(ERROR, mf.getMessage(), mf.getThrowable())); super.error(format, arguments); } @Override public void error(String msg, Throwable throwable) { ERRORS.add(new LogCapture(ERROR, msg, throwable)); super.error(msg, throwable); } @Override public void error(Marker marker, String msg) { if (!LogRule.getMarker().equals(marker)) { ERRORS.add(new LogCapture(ERROR, msg, null)); } super.error(marker, msg); } @Override public void error(Marker marker, String format, Object arg) { if (!LogRule.getMarker().equals(marker)) { FormattingTuple mf = MessageFormatter.format(format, arg); ERRORS.add(new LogCapture(ERROR, mf.getMessage(), mf.getThrowable())); } super.error(marker, format, arg); } @Override public void error(Marker marker, String format, Object arg1, Object arg2) { if (!LogRule.getMarker().equals(marker)) { FormattingTuple mf = MessageFormatter.format(format, arg1, arg2); ERRORS.add(new LogCapture(ERROR, mf.getMessage(), mf.getThrowable())); } super.error(marker, format, arg1, arg2); } @Override public void error(Marker marker, String format, Object... arguments) { if (!LogRule.getMarker().equals(marker)) { FormattingTuple mf = MessageFormatter.arrayFormat(format, arguments); ERRORS.add(new LogCapture(ERROR, mf.getMessage(), mf.getThrowable())); } super.error(marker, format, arguments); } @Override public void error(Marker marker, String msg, Throwable throwable) { if (!LogRule.getMarker().equals(marker)) { ERRORS.add(new LogCapture(ERROR, msg, throwable)); } super.error(marker, msg, throwable); } }
dfcac5747886996899dfacc00c13f7f7f1b48112
[ "Java", "Maven POM", "reStructuredText" ]
43
Java
opendaylight/infrautils
9a10663724445185f4106d028a3cea8910965f3c
1ab8fdc0b68461758fef281c21652d80729d03ee
refs/heads/master
<file_sep>class MyIssues < Redmine::Hook::ViewListener def view_welcome_index_left(context={}) load_issues() end def view_layouts_base_html_head(context) stylesheet_link_tag('my_issues', :plugin => :redmine_my_issues) end def load_issues() html = '<div class="box list_issues" id="statuses">' html += '<h3 class="">' + "Issues" + '</h3>' all_projects = Project.visible().order("name ASC").where("status != 5") my_projects = [] #lets build our projects and issues array all_projects.each do |project| issues = Issue.visible().joins(:status).where("issue_statuses.is_closed != 1 AND status_id !=3 AND project_id = :project_id", {project_id: project.id}).order("issues.due_date DESC, priority_id DESC") my_projects << Array.new([project, Array.new(issues)]) end if my_projects.first html += '<ul class="projects_list">' my_projects.each do |project, issues| # html += "<li>" + project.map(:project).join(', ') + "</li>" if (issues.length != 0) html += "<li class='project_name'>" html += link_to_project(project) html += "<ul>" issues.each do |issue| html += link_to_issue(issue) end html += "</ul>" # html += "<li>" + project.join() + "</li>" html += "</li>" end end html += '</ul>' else html += '<p class="nodata">' + l(:label_no_data) + '</p>' end html += '</div>' return html end def link_to_issue(issue) priority = "priority_" + issue.priority.name.downcase priority_border = "priority_border_" + issue.priority.name.downcase html = "<li>" html += " <div class='status_bar " + priority + "' title='" + h(issue.done_ratio) + "% " + "'> <div class='priority' style='width:" + h(issue.done_ratio) + "% " + "'> <span>#{issue.priority.name}</span></div> </div>" html += "#"+"#{h(issue.id)}" + " #{link_to h(issue.subject), :controller => 'issues', :action => 'show', :id => issue} <br/>" html += " [#{issue.status.name}]" if(issue.due_date) html += " <strong>Due:</strong> #{issue.due_date}" end html += '</li>' return html end def link_to_project(project) html = "#{link_to h(project.name), :controller => 'projects', :action => 'show', :id => project }" return html end end <file_sep>require 'redmine' require_dependency 'my_issues/view_hook_listener' Redmine::Plugin.register :redmine_my_issues do name 'My Issues' author '<NAME>' description 'Displays Issues assigned to you on the home page' version '0.0.1' author_url 'http://www.mrpony.com.au' end
9de37d860400ac036b77ace52e32a9c00db0d573
[ "Ruby" ]
2
Ruby
mrvudo/redmine_my_issues
b856947fe5bc1f0935891112b64e9efe482dbfa2
430c49bcc81e28cc3f60310e7ec7fddcf44fb1b0
refs/heads/master
<file_sep><?php namespace Tulinkry\DI; use Nette\DI\CompilerExtension; use Nette\Utils\Validators; class ScriptExtension extends CompilerExtension { public $defaults = array( 'dir' => 'generated/js' ); public function loadConfiguration() { $config = $this->validateConfig($this->defaults); $builder = $this->getContainerBuilder(); Validators::assertField($config, 'dir', 'string:1..', 'configuration of \'%s\' in the script extension'); $builder->addDefinition($this->prefix("scripts")) ->setClass("Tulinkry\Script\Services\ScriptService") ->setInject(true); $builder->addDefinition($this->prefix("styles")) ->setClass("Tulinkry\Script\Services\StyleService") ->setInject(true); $builder->addDefinition($this->prefix("url")) ->setClass("Tulinkry\Script\Services\UrlService") ->addSetup("setOutputDirectory", [$config['dir']]) ->addSetup("setWwwDirectory", [$builder->parameters['wwwDir']]) ->setInject(true); } public function beforeCompile() { $builder = $this->getContainerBuilder(); $latte = $builder->getByType('Nette\Bridges\ApplicationLatte\ILatteFactory') ?: 'nette.latteFactory'; if ($builder->hasDefinition($latte)) { $builder->getDefinition($latte) ->addSetup('?->onCompile[] = function($engine) { ' . '\Tulinkry\Script\Macros\ScriptMacros::install($engine->getCompiler()); }', ['@self']); } if ($builder->hasDefinition('nette.latte')) { $builder->getDefinition('nette.latte') ->addSetup('?->onCompile[] = function($engine) { ' . '\Tulinkry\Script\Macros\ScriptMacros::install($engine->getCompiler()); }', ['@self']); } } } <file_sep><?php namespace Tulinkry\Script\Services; use Tulinkry\Script\Entity\InlineScript; use Tulinkry\Script\Entity\Script; class ScriptService extends AbstractScriptProvider { protected $inlineScripts; protected $fileScripts; /** * ScriptService constructor. */ public function __construct() { $this->inlineScripts = array(NULL => self::createEmptyData()); $this->fileScripts = array(NULL => self::createEmptyData()); } public function addScript(Script $script) { if ($script instanceof InlineScript) { return $this->addEntity($script, $this->inlineScripts); } return $this->addEntity($script, $this->fileScripts); } public function getFiles($tags = NULL) { return $this->getByTag($tags, $this->fileScripts); } public function getInlines($tags = NULL) { return $this->getByTag($tags, $this->inlineScripts); } } <file_sep><?php namespace Tulinkry\Script\Entity; abstract class FileScript extends \Tulinkry\Script\Entity\Script { public function __construct($attrs) { $url = null; if (isset($attrs['url'])) { $url = $attrs['url']; unset($attrs['url']); } else if (isset($attrs['source'])) { $url = $attrs['source']; unset($attrs['source']); } else if (isset($attrs['file'])) { $url = $attrs['file']; unset($attrs['file']); } else if (is_array($attrs)) { $url = array_shift($attrs); } else { $url = $attrs; $attrs = array(); } parent::__construct($url, $attrs); } public function getRaw() { return ''; } } <file_sep><?php namespace Tulinkry\Script\Entity; use Nette\Utils\Html; class InlineJsScript extends InlineScript { public function getHtml() { return Html::el("script")->type("text/javascript")->setHtml( "\n//<![CDATA[\n" . $this->source . "\n//]]>\n"); } } <file_sep><?php namespace Tulinkry\Script\Entity; use Nette\Utils\Html; class FileJsScript extends \Tulinkry\Script\Entity\FileScript { public function getHtml() { $source = $this->source; return Html::el("script") ->type("text/javascript") ->data('priority', $this->getPriority()) ->src($source); } } <file_sep><?php namespace Tulinkry\Script\Services; use Nette\Http\IRequest; use Tulinkry\Script\Entity\FileJsScript; use Tulinkry\Script\Entity\FileScript; use Tulinkry\Script\Entity\InlineScript; class UrlService { const DEFAULT_TAG = "all-together"; protected $wwwDir; protected $directory; /** * @var ScriptService @inject */ public $scripts; /** * @var StyleService @inject */ public $styles; /** @var IRequest @inject */ public $request; public function getOutputDirectory() { return $this->directory; } public function setOutputDirectory($directory) { $this->directory = $directory; return $this; } public function getWwwDirectory() { return $this->wwwDir; } public function setWwwDirectory($wwwDir) { $this->wwwDir = $wwwDir; return $this; } public function getBasePath() { return rtrim($this->request->getUrl()->getBasePath(), '/'); } public function getScriptElements($tags) { return $this->prepareElements($tags, 'scripts', '.js'); } public function getStyleElements($tags) { return $this->prepareElements($tags, 'styles', '.css'); } /** * Sort the input scripts by a priority. * @param $scripts array of scripts * @return array of scripts */ protected function sortScripts(&$scripts) { uasort($scripts, function ($a, $b) { return $a->getPriority() - $b->getPriority(); }); return $scripts; } /** * Prepare the elements in an array for all script of single type. * * @param $tags filter the scripts by tag before returning * @param $type use for this type (either scripts or styles) * @param string $suffix the file suffix * @return array of scripts/styles sorted based on priority */ protected function prepareElements($tags, $type, $suffix = '.js') { $results = []; $tags = is_array($tags) ? $tags : array($tags); if (count($tags) === 0) { $tags = array(self::DEFAULT_TAG); } sort($tags); switch ($type) { case 'scripts': $elements = $this->scripts->getFiles(); $elements += $this->scripts->getInlines(); break; case 'styles': $elements = $this->styles->getFiles(); $elements += $this->styles->getInlines(); break; } foreach ($elements as $element) { if ($element instanceof FileScript) { $results[] = $element; } } $data = []; foreach ($elements as $element) { if ($element instanceof InlineScript) { $data[] = $element->getRaw(); } } if (($generatedFile = $this->generateDataFile($data, $tags, $suffix)) !== null) { $results[] = $generatedFile; } return $this->sortScripts($results); } /** * Generates data file from the data be joining them and creating a file in the www directory. * * @param $data array of inline javascript snippets * @param $tags tags which were used to obtain such data * @param string $suffix the file suffix * @return FileJsScript|null the new instance of file js script or null of can not be created */ protected function generateDataFile($data, $tags, $suffix = '.js') { @mkdir($this->wwwDir . DIRECTORY_SEPARATOR . $this->directory, 0775, true); $data = implode(PHP_EOL . PHP_EOL . "// " . str_repeat('-', 100) . PHP_EOL . PHP_EOL, $data); if (trim($data) === '') { return NULL; } $tmpName = implode("-", $tags) . $suffix; file_put_contents($this->wwwDir . DIRECTORY_SEPARATOR . $this->directory . DIRECTORY_SEPARATOR . $tmpName, $data); return new FileJsScript(array('url' => $this->getBasePath() . '/' . $this->directory . '/' . $tmpName . '?t=' . time(), 'priority' => PHP_INT_MAX)); } } <file_sep><?php namespace Tulinkry\Script\Macros; use Latte\CompileException; use Latte\Compiler; use Latte\MacroNode; use Latte\Macros\MacroSet; use Latte\PhpWriter; use Nette\Utils\Strings; /** * Basic macros for Latte. * */ class ScriptMacros extends MacroSet { public static function install(Compiler $compiler) { $me = new static($compiler); $me->addMacro('script', array($me, 'macroScript'), array($me, 'macroScript')); $me->addMacro('style', array($me, 'macroStyle'), array($me, 'macroStyle')); $me->addMacro('fileScript', array($me, 'macroFileScript')); $me->addMacro('fileStyle', array($me, 'macroFileStyle')); $me->addMacro('scripts', array($me, 'macroScripts')); $me->addMacro('styles', array($me, 'macroStyles')); } /** * {script $tags, $priority} */ public function macroScript(MacroNode $node, PhpWriter $writer) { if ($node->closing) { $this->getCompiler()->setContext(NULL); return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\ScriptService")) { ' . ' $_l->tmp->addScript($_l->tmp->createElement("inlineJs", %modify(ob_get_clean()), %node.array)); ' . '}'); } else { $this->getCompiler()->setContext(Compiler::CONTENT_JS); return 'ob_start(function () {})'; } } /** * {style $tags, $priority} */ public function macroStyle(MacroNode $node, PhpWriter $writer) { if ($node->closing) { $this->getCompiler()->setContext(NULL); return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\ScriptService")) { ' . ' $_l->tmp->addStyle($_l->tmp->createElement("inlineCss", %modify(ob_get_clean()), %node.array)); ' . '}'); } else { $this->getCompiler()->setContext(Compiler::CONTENT_CSS); return 'ob_start(function () {})'; } } /** * {fileScript $path} */ public function macroFileScript(MacroNode $node, PhpWriter $writer) { if ($node->args === '') { throw new CompileException('Missing arguments in {fileScript} macro.'); } $unique = false; $key = null; if (!empty($node->modifiers)) { $modifiers = explode('|', $node->modifiers); foreach ($modifiers as $modifier) { if ($modifier === 'unique') { $unique = true; } if (Strings::startsWith($modifier, 'key:')) { $key = Strings::replace($modifier, '/key:\\s*/', ''); } } if ($unique && !$key) { throw new CompileException('Specified \'unique\' but no \'key\' given.'); } } if ($unique) { return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\ScriptService")) { ' . ' $_l->tmp->addScript($_l->tmp->createElement("fileJs", array_merge(%node.array, array("uniqueKey" => %escape("' . $key . '"))))); ' . '}'); } return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\ScriptService")) { ' . ' echo $_l->tmp->createElement("fileJs", %node.array)->getHtml()->render(); ' . '}'); } /** * {fileStyle $path} */ public function macroFileStyle(MacroNode $node, PhpWriter $writer) { if ($node->args === '') { throw new CompileException('Missing arguments in {fileScript} macro.'); } return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\StyleService")) { ' . ' echo $_l->tmp->createElement("fileCss", %node.array)->getHtml()->render(); ' . '}'); } /** * {scripts $tags} */ public function macroScripts(MacroNode $node, PhpWriter $writer) { $inline = preg_match("/\|inline/", $node->modifiers); $node->modifiers = preg_replace("/\|inline/", "", $node->modifiers); if ($inline) { return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\ScriptService")) { ' . ' $_l->tmp = $_l->tmp->getInlines(%node.array); ' . ' foreach($_l->tmp as $script) { ' . ' echo $script->getHtml()->render(); ' . ' echo "\n"; ' . ' } ' . '}'); } else { return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\UrlService")) { ' . ' if($_l->tmp = $_l->tmp->getScriptElements(%node.array)) { ' . ' foreach($_l->tmp as $script) { ' . ' echo $script->getHtml()->render(); ' . ' echo "\n"; ' . ' } ' . ' } ' . '}'); } } /** * {styles $tags} */ public function macroStyles(MacroNode $node, PhpWriter $writer) { $inline = preg_match("/\|inline/", $node->modifiers); $node->modifiers = preg_replace("/\|inline/", "", $node->modifiers); if ($inline) { return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\StyleService")) { ' . ' $_l->tmp = $_l->tmp->getInlines(%node.array); ' . 'foreach($_l->tmp as $style) { ' . ' echo $style->getHtml()->render(); ' . ' echo "\n"; ' . ' } ' . '}'); } else { return $writer->write('' . 'if($_l->tmp = $presenter->context->getByType("Tulinkry\Script\Services\UrlService")) { ' . ' if($_l->tmp = $_l->tmp->getStyleElements(%node.array)) { ' . ' foreach($_l->tmp as $script) { ' . ' echo $script->getHtml()->render(); ' . ' echo "\n"; ' . ' } ' . ' } ' . '}'); } } } <file_sep><?php namespace Tulinkry\Script\Entity; use Nette\Utils\Html; class InlineCssScript extends InlineScript { public function getHtml() { return Html::el("link")->rel("stylesheet")->type('text/css')->setHtml($this->source); } } <file_sep><?php /** * Created by PhpStorm. * User: ktulinger * Date: 2019-04-08 * Time: 17:36 */ namespace Tulinkry\Script\Services; use Tulinkry\Script\Entity\Script; interface ScriptProvider { public function addScript(Script $script); public function getFiles($tags = NULL); public function getInlines($tags = NULL); public function createElement(); }<file_sep><?php namespace Tulinkry\Script\Entity; use Nette\Utils\Html; class FileCssScript extends \Tulinkry\Script\Entity\FileScript { public function getHtml() { $source = $this->source; return Html::el("link") ->rel('stylesheet') ->type("text/css") ->data('priority', $this->getPriority()) ->href($source); } } <file_sep><?php /** * Created by PhpStorm. * User: ktulinger * Date: 2019-04-08 * Time: 17:37 */ namespace Tulinkry\Script\Services; use Nette\InvalidArgumentException; use ReflectionClass; use Tulinkry\Script\Entity\Script; abstract class AbstractScriptProvider implements ScriptProvider { abstract public function addScript(Script $script); abstract public function getFiles($tags = NULL); abstract public function getInlines($tags = NULL); protected function addEntity(Script $script, &$collection) { if (count($script->getTags())) { foreach ($script->getTags() as $tag) { if (!isset($collection[$tag])) { $collection[$tag] = self::createEmptyData(); } if ($script->getUniqueKey() !== null) { $collection[$tag]->uniques[$script->getUniqueKey()] = $script; } else { $collection[$tag]->entities[] = $script; } } } if ($script->getUniqueKey() !== null) { $collection[NULL]->uniques[$script->getUniqueKey()] = $script; } else { $collection[NULL]->entities[] = $script; } //\Tracy\Debugger::$maxDepth = 10; //dump($this); return $this; } public function createElement() { $args = func_get_args(); $name = array_shift($args); $class = 'Tulinkry\\Script\Entity\\' . ucfirst($name) . "Script"; if (!class_exists($class)) { throw new InvalidArgumentException("Class $class not found."); } $rc = new ReflectionClass($class); if (!$rc->isInstantiable()) { throw new InvalidArgumentException("Class $class is not instantiable."); } elseif ($constructor = $rc->getConstructor()) { return $rc->newInstanceArgs($args); } elseif ($args) { throw new InvalidArgumentException("No suitable constructor for class $class was found."); } return new $class; } protected function getByTag($tag, $collection) { return isset($collection[$tag]) ? array_merge($collection[$tag]->entities, $collection[$tag]->uniques) : array(); } protected function getByTags($tags, $collection) { if (count($tags) === 0) { return array_merge($collection[NULL]->entities, $collection[NULL]->uniques); } $ret = array(); foreach ($tags as $tag) { $ret = array_merge($ret, $this->getByTag($tag, $collection)); } return $ret; } protected static function createEmptyData() { $scriptsCollection = new \StdClass; $scriptsCollection->entities = array(); $scriptsCollection->uniques = array(); return $scriptsCollection; } }<file_sep><?php namespace Tulinkry\Script\Entity; abstract class InlineScript extends Script { } <file_sep><?php namespace Tulinkry\Script\Services; use Tulinkry\Script\Entity\InlineScript; use Tulinkry\Script\Entity\Script; class StyleService extends AbstractScriptProvider { protected $fileStyles; protected $inlineStyles; /** * StylesService constructor. */ public function __construct() { $this->fileStyles = array(NULL => self::createEmptyData()); $this->inlineStyles = array(NULL => self::createEmptyData()); } public function addScript(Script $script) { if ($script instanceof InlineScript) { return $this->addEntity($script, $this->inlineStyles); } return $this->addEntity($script, $this->fileStyles); } public function getFiles($tags = NULL) { return $this->getByTag($tags, $this->fileStyles); } public function getInlines($tags = NULL) { return $this->getByTag($tags, $this->inlineStyles); } } <file_sep><?php namespace Tulinkry\Script\Entity; abstract class Script { protected $source; protected $tags; protected $priority; protected $uniqueKey; protected $attrs; abstract public function getHtml(); public function __construct($source, $attrs = array()) { $this->source = $source; $this->priority = 0; if (isset($attrs['priority'])) { $this->priority = $attrs['priority']; unset($attrs['priority']); } $this->uniqueKey = null; if (isset($attrs['uniqueKey'])) { $this->uniqueKey = $attrs['uniqueKey']; unset($attrs['uniqueKey']); } $this->tags = array(); if (isset($attrs['tags'])) { $this->tags = $attrs['tags']; } else { $this->tags = $attrs; $attrs = array(); } $this->tags = is_array($this->tags) ? $this->tags : array($this->tags); $this->attrs = $attrs; } public function getPriority() { return $this->priority; } public function setPriority($priority) { $this->priority = $priority; return $this; } /** * @return mixed */ public function getUniqueKey() { return $this->uniqueKey; } /** * @param mixed $uniqueKey */ public function setUniqueKey($uniqueKey) { $this->uniqueKey = $uniqueKey; return $this; } public function getTags() { return $this->tags; } public function addTag($tag) { $this->tags[] = $tag; return $this; } public function hasTag($tag) { return !empty($this->tags[$tag]); } public function getRaw() { return $this->source; } }
56d177cc314196c84122314dbcde765d658d5a32
[ "PHP" ]
14
PHP
tulinkry/script
0f5d4d866b65d8e850d6dea5ee709d1f35d0a8c3
ea786adb42c4b4253848220d2747e8e0fa11d3da
refs/heads/master
<file_sep>import React, {Component} from 'react'; import './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import Survey from "./containers/Survey"; export default class App extends Component { constructor(props) { super(props); // TODO - load questions from API based on surveyId (so we can version them // TODO - load answers if we have any saved } render() { return ( <Survey/> ); } }
e31c7f3e2571b4b363dc758eeedd65370880fc61
[ "JavaScript" ]
1
JavaScript
mkipcak/react-survey-components
b09e24c8fce7e7873500228da0da2c3f7c8b426b
a1f2bcf5cacd65061e23ad8e891d511710117d56
refs/heads/master
<repo_name>AndreyBodulin/brackets<file_sep>/src/index.js module.exports = function check(s, bracketsConfig) { console.log(s); let sum = 0; const brackets = { ')': '(', ']': '[', '}': '{', }; // в качестве стека в JavaScript можно использовать обычный массив //(если пользоваться только «разрешенными» методами push & pop) const st = []; for (let i = 0; i < s.length; i++) { if (s[i] == '|') { sum += 1; continue; }; if (isClosedBracket(s[i])) { if (brackets[s[i]] !== st.pop()) return false; // это открывающая скобка, т.к. других символов по условию в строке нет } else { st.push(s[i]); } } if (sum % 2 == 0 && (s.indexOf('|') != -1)) return true; console.log(sum); return st.length === 0; function isClosedBracket(ch) { return [')', ']', '}'].indexOf(ch) > -1; } }
01d7dff5322a38f9ad9ee999b9b7f31b68bbd123
[ "JavaScript" ]
1
JavaScript
AndreyBodulin/brackets
490fc29010e342cbee2bb649869807412de2e0c9
23b2ffd795a1bc57b041b07588c5fc99cfadea34
refs/heads/main
<file_sep>import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import getpass from bs4 import BeautifulSoup import os, re import math def downloads(hrefs): for href in hrefs: driver.execute_script(href) html = driver.page_source bs = BeautifulSoup(html, 'html.parser') download = bs.find("a", attrs={"class": "btn_type05 down"}) driver.execute_script(download['onclick']) while(True): # driver.find_element_by_id("MyID")).value_of_css_property("display") if(driver.find_element_by_id("popup_wrap").value_of_css_property("display") == "none"): break options = webdriver.ChromeOptions() prefs = {"profile.default_content_settings.popups": 0, "profile.content_settings.pattern_pairs.*.multiple-automatic-downloads": 1, "download.prompt_for_download": False, "profile.default_content_setting_values.automatic_downloads" : 1 } options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(executable_path="./driver/chromedriver", chrome_options=options) time.sleep(2) #init driver.get('https://www.open.go.kr/othicInfo/infoList/orginlInfoList.do') time.sleep(5) html =driver.page_source bs = BeautifulSoup(html, 'html.parser') next_btn = driver.find_element_by_class_name("next") total = driver.find_element_by_id("totalPage").text.replace(",","") driver.execute_script("document.querySelector(\"select[name='veiwNum'] option\").value=\"" + total + "\";searchCallFn();") # 로드 해올 때까지 대기 while(True): print(driver.find_elements_by_id("imgLoading")) if(driver.find_elements_by_id("imgLoading") == []): break div = bs.find("div", attrs={"class":"info_list"}) lis = div.find_all("li") hrefs = [] for li in lis: hrefs.append(li.find("a")['href']) print("load complate") downloads(hrefs) driver.close() <file_sep># PublicDataCrawler 정보공개포털(www.open.go.kr) 공공데이터 원문 데이터 크롤러
c2aac8a73163f8972b00441a58173db5c552210b
[ "Markdown", "Python" ]
2
Python
hubeen/PublicDataCrawler
3e5814022c067b8a36a6cfd064376f1738b025af
9c71f3ff3cce1c6ba84be3f51e949b673c636c5c
refs/heads/master
<repo_name>armandomotum/EjemploSpringMVCHibernate<file_sep>/spring3-mvc-maven-xml-hello-world-master/src/main/java/com/ejemplo/backend/service/GenericServiceImplement.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ejemplo.backend.service; import com.ejemplo.backend.dao.GenericDaoInterface; import java.io.Serializable; import java.util.List; /** * * @author Ejercicioooooooooooo */ public abstract class GenericServiceImplement<T> implements GenericServiceInterface<T>{ private GenericDaoInterface dao; public GenericServiceImplement(GenericDaoInterface genericDaoInstance){ this.dao=genericDaoInstance; } @Override public List<T> findAll() { return this.dao.findAll(); } @Override public Serializable save(T t) { return this.dao.save(t); } @Override public void update(T t) { dao.update(t); } @Override public void delete(T t) { this.dao.delete(t); } @Override public T findById(Serializable id) { return (T)this.dao.findById(id); } } <file_sep>/spring3-mvc-maven-xml-hello-world-master/src/main/java/com/ejemplo/backend/dao/PendienteDaoImplement.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ejemplo.backend.dao; import com.ejemplo.backend.model.Pendiente; import org.springframework.stereotype.Repository; /** * * @author Ejercicioooooooooooo */ @Repository public class PendienteDaoImplement extends GenericDaoImplement<Pendiente,Integer> implements PendienteDaoInterface{ // public FamiliarDaoImplement(SessionFactory sf) { // super(sf); // } public PendienteDaoImplement() { super(NewHibernateUtil.getSessionFactory()); } } <file_sep>/spring3-mvc-maven-xml-hello-world-master/src/main/java/com/ejemplo/backend/service/GenericServiceInterface.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ejemplo.backend.service; import java.io.Serializable; import java.util.List; /** * * @author Ejercicioooooooooooo */ public interface GenericServiceInterface<T> { public List<T> findAll(); public Serializable save(T t); public void update(T t); public void delete(T t); public T findById(Serializable id); }
1e70d4db56f749b2623bcd59ad1941f279529f51
[ "Java" ]
3
Java
armandomotum/EjemploSpringMVCHibernate
76aecfbcaaa88da27de1b1ba6a90285cfbf8a77d
b3e12cb5769a343a6244787ef1296a5271a6edd1
refs/heads/master
<file_sep>var deadline = "2016-11-04 17:00:00".split(/[- :]/), date = new Date(deadline[0], deadline[1]-1, deadline[2], deadline[3], deadline[4], deadline[5]); function initMap() { var mapDiv = document.getElementById('map'); var coordinates = {lat: 50.291085, lng: 18.704754}; var options = { center: coordinates, zoom: 16, scrollwheel: false, draggable: false, navigationControl: false, mapTypeControl: true, scaleControl: false, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(mapDiv, options); var marker = new google.maps.Marker({ position: coordinates, map: map, title: 'Euvic' }); var content = '<div id="content"> \ <img src="img/euvic.png" style="margin-top: 10px;" height="20px" alt="Euvic" /> \ <h5 style="margin-bottom: 5px;">Siedziba główna - Gliwice, ul. Przewozowa 32</h5>\ </div>' var infowindow = new google.maps.InfoWindow({ content: content }); marker.addListener('click', function() { infowindow.open(map, marker); }); infowindow.open(map, marker); } function getLeftTime() { var time = Date.parse(date) - Date.parse(new Date()); if(time <= 0) { return { days: 0, hours: 0, minutes: 0, seconds: 0 } } return { days: Math.floor(time / (1000 * 3600 * 24)), hours: Math.floor( (time / (1000 * 3600)) % 24 ), minutes: Math.floor( (time / 60000) % 60 ), seconds: Math.floor( (time / 1000) % 60 ) } } function setTimer(refreshRate) { var leftTime = getLeftTime(deadline); $('#days').text(leftTime.days); $('#hours').text(leftTime.hours); $('#minutes').text(leftTime.minutes); $('#seconds').text(leftTime.seconds); setTimeout(setTimer, refreshRate); } $(window).scroll(function() { if($(this).scrollTop() > 100) { $('.logo-text').css('fill', '#1c5a7d'); } else if($(this).width() > 768) { $('.logo-text').css('fill', '#fff'); } }); $(document).ready(function(){ setTimer(1000); }); <file_sep>function isEmail(emailAddress) { var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i); return pattern.test(emailAddress); } function validateForm() { var error = false; $('#error-msg').hide(); var $input = $('#registration-form input[type=text]'); $input.removeClass('warning'); $input.each(function() { if(!isNaN(this.value)) { error = true; $(this).addClass('warning'); } }); var $rulesLabel = $('input[type="checkbox"] + label'); $rulesLabel.removeClass('warning-checkbox'); if(!$('#rules').prop('checked')) { $rulesLabel.addClass('warning-checkbox'); error = true; } if(error) { alert("Wszystkie pola są wymagane"); $('#error-msg').text('* Wszystkie pola są wymagane'); $('#error-msg').show(); } var $mail = $('#registration-form input[name=mail]'); $mail.each(function() { if(!error && !isEmail(this.value)) { error = true; $(this).addClass('warning'); alert('Niepoprawny format adresu e-mail'); $('#error-msg').text('* Niepoprawny format adresu e-mail'); $('#error-msg').show(); } }) return !error; } (function () { var maxCount = 4; var minCount = 1; var count = minCount; function addParticipant($addButton) { if(count < maxCount) { var $last = $('.participant-info').last(); $('#delete-participant').show(); $('<div class="row participant-info">\ <div class="col-lg-4">\ <input class="participant-field" name="name" type="text" placeholder="Imię"/>\ </div>\ <div class="col-lg-4">\ <input class="participant-field" name="surname" type="text" placeholder="Nazwisko"/>\ </div>\ <div class="col-lg-4">\ <input class="participant-field" name="mail" type="text" placeholder="E-mail"/>\ </div>\ </div>' ).insertAfter($last); ++count; if(count === maxCount) { $addButton.hide(); } } } function deleteParticipant($deleteButton) { if(count > minCount) { $('#add-participant').show(); var $last = $('.participant-info').last(); $last.remove(); --count; if(count === minCount) { $deleteButton.hide(); } } } $(document).ready(function(){ $('#add-participant').click(function() { addParticipant($(this)); }); $('#delete-participant').click(function() { deleteParticipant($(this)); }); $('#rules-label').click(function() { $('input[type="checkbox"] + label').removeClass('warning-checkbox'); }); $("#register-btn").click(function() { var form = $(this).attr('form'); $('#'+form).submit(); }); }); })()
a944f7fa35d91363bcccd670abb1a144f7cf0d70
[ "JavaScript" ]
2
JavaScript
whereiswolf/Hackathon
223b93f3cf5d4f1ced0caf3e42710b4080b9c15f
c090e868cf190925670001fcb5d6a408c9c110eb
refs/heads/master
<file_sep>package passwordmanager; import java.io.IOException; import java.util.List; /** * * @author <NAME> */ public class PMCtrl { private final PMMdl model; private final PMView view; public PMCtrl(){ model = new PMMdl(); view = new PMView(this); view.setVisible(true); } public void setUName(String name){ model.setUName(name); } public String getUName(){ return model.getUName(); } public void setAName(String aName){ model.setAName(aName); } public String getAName(){ return model.getAName(); } public void setUID(String UID){ model.setUID(UID); } public String getUID(){ return model.getUID(); } public void setPW(String PW){ model.setPW(PW); } public String getPW(){ return model.getPW(); } public void setList(){ model.setList(); } public List getList(){ return model.getList(); } public void setFileName(String name){ model.setFileName(name); } public String getFileName(){ return model.getFileName(); } public void setView(){ view.setVisible(true); } public void fileWrite() throws IOException{ model.fileWrite(); } public String readFile(String name, String acctname) throws IOException{ return model.readFile(name, acctname); } } <file_sep>#!/bin/sh cat SecurityLog-rev2.xml > NewLog.xml grep "<EventID>4624" SecurityLog-rev2.xml > Event4624.xml grep -c "<EventID>4625" SecurityLog-rev2.xml > Event4625.xml <file_sep>scores <- read.csv("http://data-analytics.zybooks.com/ExamScores.csv") exam_num <- 1 exam_mean <- sapply(scores, mean) exam_median <- median(scores[,exam_num]) print(c("The mean is ", exam_mean[exam_num], " The median is ", exam_median[exam_num])) count <- table(scores[,exam_num]) barplot(count) <file_sep>package roomschedulerrrk5140; public class RoomSchedulerrrk5140 { public static void main(String[] args) { RoomSchedulerFrame newFrame = new RoomSchedulerFrame(); newFrame.setVisible(true); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package EmployeeHierarchy; /** * * @author rrk5140 */ public class BasePlusCommissionCompensationModel extends CommissionCompensationModel { private double baseSalary; public BasePlusCommissionCompensationModel(double grossSales, double commissionRate, double baseSalary){ super(grossSales, commissionRate); if(baseSalary < 0.0){ throw new IllegalArgumentException("Base salary must be >= 0.0"); } this.baseSalary = baseSalary; } public double earnings(){ return baseSalary + super.earnings(); } @Override public String toString(){ return String.format("%s: %n%s: %.2f%n%s: %.2f%n%s: %.2f%n%s: %.2f", "Base Plus Commission Compensation with", "Gross Sales of", super.getGrossSales(), "Commission Rate of", super.getCommissionRate(), "Base Salary of", baseSalary, "Earnings", earnings()); } } <file_sep>def program_process(): first_name, last_name, username, tmp = datastorage() choice = choices() choice_response(choice, last_name, first_name, username, tmp) def datastorage(): first_name = {} last_name = {} username = {} lines = (line.rstrip('\n') for line in open("UD.txt")) tmp = [i for i in lines] for i in range(len(tmp[:-1])): first_name[tmp[i + 1].split(",")[0]] = tmp[i + 1] last_name[tmp[i + 1].split(",")[1]] = tmp[i + 1] username[tmp[i + 1].split(",")[2]] = tmp[i + 1] return first_name, last_name, username, tmp[1:] def choices(): choice = input("What would you like to do today? A: Search by last name, B: Search by first name, C: Search by username, D: Display all users alphabetically by First name, E: Display all users alphabetically by Last name, F: Insert a user. ") return choice def search_by_last_name(last_name): user_prompt = input("Enter user's last name: ") if user_prompt in last_name: print(last_name[user_prompt]) else: print("Not found") program_process() def search_by_first_name(first_name): user_prompt = input("Enter user's first name: ") if user_prompt in first_name: print(first_name[user_prompt]) else: print("Not found") program_process() def search_by_username(username): user_prompt = input("Enter user's username: ") if user_prompt in username: print(username[user_prompt]) else: print("Not found") program_process() def output(tmp, choice): if choice == 'D': alpha_first_name_tmp = sorted(tmp) print(alpha_first_name_tmp) elif choice == 'E': alpha_last_name_tmp = sorted(tmp, key=lambda x: x.split(",")[-3]) print(alpha_last_name_tmp) def insert_user(): user_info = input("Enter user info in the following format: First name, last name, username, password. ") split_user_info = user_info.split(", ") fn_new_user, ln_new_user, un_new_user, pw_new_user = split_user_info[0], split_user_info[1], split_user_info[2], split_user_info[3] user_file = open("UD.txt", 'a') print(fn_new_user + ',' + ln_new_user + ',' + un_new_user + ',' + pw_new_user, file=user_file) def choice_response(choice, last_name, first_name, username, tmp): if choice == 'A': search_by_last_name(last_name) elif choice == 'B': search_by_first_name(first_name) elif choice == 'C': search_by_username(username) elif choice == 'D' or choice == 'E': output(tmp, choice) elif choice == 'F': insert_user() program_process() <file_sep>def get_user_name(): fn = input("Enter first name ") ln = input("Enter last name ") return(fn,ln) def get_password(fn,ln): pw = input("Enter password, password should be more than 8 characters, with at least one digit, one symbol, and one uppercase ") if (fn.upper() and fn.lower() and ln.upper() and ln.lower() not in pw) and (len(pw) > 8) and set('1234567890').intersection(pw) and set('!@#$%^&*()_+').intersection(pw) and not (pw.isupper()) and not (pw.islower()): else: print("Did not meet password requirements, re-enter password.") print("Please reconfirm password.") get_password(fn,ln) def create_username(): un = fn[:2] + ln[:3] print("Hi " + fn + ", your username is " + un + ".") return(un) def write_file(): print(un + ',' + pw, file=upfile) upfile = open('UD.txt', 'w') print("USERNAME,PASSWORD", file=upfile) fn,ln = get_user_name() pw = get_password(fn,ln) un = create_username() write_file() upfile.close() <file_sep>package roomschedulerrrk5140; import java.util.Calendar; import java.util.Date; /** * * @author <NAME> */ public class WaitlistEntry { String Faculty; Date Date; int Seats; java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); } <file_sep>def start_login(): response = greeting() while response != 'L' and response != 'C': response = greeting() if response == 'L' and response == 'C': break if response == 'L': login() elif response == 'C': un, pw = create() pwcheck(un, pw) print("User created.") def greeting(): response = input("Login or create a new user? Select L to login, select C to create new user. ") return response def login(): logfile = open("UD.txt", 'r') txtfile = logfile.read() un = input("Please enter your user name and hit enter: ") if un in txtfile: pw = input("Enter password: ") if pw in txtfile: print("You are logged in") else: print("Wrong password") start_login() else: print("User not found") start_login() def create(): create_account = input("Please enter your first name, last name, and student ID, separated by a space: ") splitun = create_account.split(" ") fn, ln, sid = splitun[0], splitun[1], splitun[2] un = fn[:1] + ln[:2] + sid[:3] pw = input("Please enter password: ") return un, pw def pwcheck(un, pw): repw = input("Please reenter password: ") if pw == repw: logfile = open("UD.txt", 'a') print(un.lower() + ',' + pw, file=logfile) else: print("Password did not match") pwcheck(un, pw) start_login()
3d5925ee3360b2eeed3f044293adb78207133cc4
[ "Java", "Python", "R", "Shell" ]
9
Java
khanrr/Course-projects
78bf1aa7444db645d6d41d2d8b77909f92c0580f
8747077bd889af893d5affb1b7abb2bbf0b0abfd
refs/heads/master
<repo_name>akkipore/client<file_sep>/src/app/product-list/product-list.component.ts import { Component, OnInit } from '@angular/core'; import{HttpClient} from "@angular/common/http" @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit { products=[] httpCilent:HttpClient constructor( httpClient:HttpClient) { this.httpCilent=httpClient } loadProducts(){ const url = "http://localhost:3000/product" const request= this.httpCilent.get(url) request.subscribe(response=>{ console.log(`response`) console.log(response) if(response['status']=='success'){ this.products=response['data'] } }) } ngOnInit(): void { } } <file_sep>/src/app/login/login.component.ts import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { email='' password='' httpClient : HttpClient constructor(httpClient:HttpClient) { this.httpClient=httpClient } onLogin(){ const body={ email:this.email, password:<PASSWORD> } const url ="http://localhost:3001/user/signin" const request = this.httpClient.post(url,body) request.subscribe(response=>{ console.log(response) if(response['status']=='success'){ const data = response['data'] const firstName = data['firstName'] const lastName = data['lastName'] alert(`welcome ${firstName} ${lastName}`) }else{ alert('invalid email or password') } }) } onCancel(){ } ngOnInit(): void { } } <file_sep>/src/app/signup/signup.component.ts import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { firstName='' lastName='' email='' password='' httpClient : HttpClient constructor(httpClient:HttpClient) { this.httpClient=httpClient } onSignUp(){ const body = { firstName:this.firstName, lastName:this.lastName, email:this.email, password:<PASSWORD> } const url = "http://localhost:3001/user/signup" const request = this.httpClient.post(url, body) request.subscribe(response=>{ console.log(response) if(response['status']=='success'){ alert(`you have registered successfully`) }else{ alert('you have not registered successfully') } }) } onCancel(){ } ngOnInit(): void { } }
f998c4fb78e2f9c53399dc842729c7b427f5129e
[ "TypeScript" ]
3
TypeScript
akkipore/client
89ac1d8b1d50743bd0bd9f2b2ea2572fbca89877
ef24c728f7d42a24a84a03a3272db64be110438d
refs/heads/master
<repo_name>liucc0413/SpringCloudEureka<file_sep>/elk/src/main/java/com/example/elk/Controller/MyController.java package com.example.elk.Controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/elk") public class MyController { private final Logger logger = LoggerFactory.getLogger(MyController.class); @RequestMapping("/one") @ResponseBody public String test(){ logger.debug("This is a debug message"); logger.info("This is an info message"); logger.warn("This is a warn message"); logger.error("This is an error message"); return "hello"; } @RequestMapping("/springboot") public String Hello() { logger.debug("T念佛爱的解放军殴打司机开发ge"); logger.info("This is 的解放军殴打司机开发 info message"); logger.warn("This is a warn message"); logger.error("This is an error message"); return "Hello SpringBoot!"; } } <file_sep>/zuul/src/main/java/com/example/zuul/FilterUtil/Util.java package com.example.zuul.FilterUtil; import com.netflix.zuul.context.RequestContext; import javax.ws.rs.HEAD; import java.util.Map; import java.util.UUID; public class Util { public static final String HADER_ID = "lccid"; public static String getRequestID(){ RequestContext context = RequestContext.getCurrentContext(); Map<String, String> headers = context.getZuulRequestHeaders(); String id = headers.get(HADER_ID); if(id != null) { return id; } String uuID = UUID.randomUUID().toString(); context.addZuulRequestHeader(HADER_ID,uuID); return uuID; } } <file_sep>/feign_consumer/src/main/java/feign/Serivce/FeignSayHiService.java package feign.Serivce; import feign.Controller.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(value = "service-hi") public interface FeignSayHiService { @RequestMapping("/cloud/hi") public String sayHi(@RequestParam(name = "name") String name); @RequestMapping(value = "/cloud/user2", method = RequestMethod.POST) public void user(@RequestBody User user); } <file_sep>/zipkin_get/src/main/java/com/example/zipkin_get/Feign/ZipKinOneClient.java package com.example.zipkin_get.Feign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(value = "zipkinClientOne",path = "/zk") public interface ZipKinOneClient { @RequestMapping("/one") public String testOne() ; @RequestMapping("/two") public String testTwo() ; } <file_sep>/client/src/main/java/client/Controller/MyController.java package client.Controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/cloud") public class MyController { @Value("${server.port}") String port; private final static Logger logger = LoggerFactory.getLogger(MyController.class); @RequestMapping("/hi") @ResponseBody public String home(@RequestParam String name) { // try { //// Thread.sleep(1500); // } catch (InterruptedException e) { // e.printStackTrace(); // } logger.info("hi two"); return "hi " + name + ",i am from port:" + port; } @RequestMapping("/user") public Object user(@RequestParam String name) { Map<String, String> map = new HashMap(); map.put("name", name); map.put("maptest","**************"); return map; } @RequestMapping(value = "/user2", method = RequestMethod.POST) public void getUser(@RequestBody User user) { System.out.println(user.getId()+ " "+user.getName()); } @RequestMapping("/la") @ResponseBody public String test1(@RequestParam String name) { System.out.println("***************************"); return "lalala " + name + ",i am from port:" + port; } // @Value("${foo}") // String foo; // @RequestMapping(value = "/config") // @ResponseBody // public String hi(){ // return foo; // } } <file_sep>/zipkin_get/src/main/java/com/example/zipkin_get/ZipkinGetApplication.java package com.example.zipkin_get; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients //@EnableDiscoveryClient public class ZipkinGetApplication { public static void main(String[] args) { SpringApplication.run(ZipkinGetApplication.class, args); } } <file_sep>/zipkin_get/src/main/java/com/example/zipkin_get/Controller/MyController.java package com.example.zipkin_get.Controller; import com.example.zipkin_get.Feign.ZipKinOneClient; import com.example.zipkin_get.ZipkinGetApplication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("zkg") public class MyController { @Autowired ZipKinOneClient zipKinOneClient; @RequestMapping("one") @ResponseBody public String testOne(){ return zipKinOneClient.testOne(); } @RequestMapping("two") @ResponseBody public String testTwo(){ return zipKinOneClient.testTwo(); } } <file_sep>/hystrix/src/main/java/Com/Service/Impl/HystrixServiceImpl.java package Com.Service.Impl; import Com.Service.HystrixService; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import org.springframework.stereotype.Service; @Service public class HystrixServiceImpl implements HystrixService { @Override @HystrixCommand(fallbackMethod = "fallbackMethod") public String getLcc() { int i = 1/0; return "dfsdfdsaf"; } @Override @HystrixCommand(fallbackMethod = "fallbackMethod", commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1200")}) public String test2() { try { System.out.println("test2 threadName:"+Thread.currentThread().getName()); Thread.sleep(2000); int j = 0; for(int i = 0; i<200000 ;i++) { j+=i; } } catch (InterruptedException e) { e.printStackTrace(); } return "test2"; } @HystrixCommand(threadPoolKey = "test3",threadPoolProperties = {@HystrixProperty(name = "coreSize", value = "2") ,@HystrixProperty(name = "maxQueueSize",value = "2")}) public String test3() { System.out.println("test3 threadName:"+Thread.currentThread().getName()); return "test3"; } @HystrixCommand(fallbackMethod = "fallbackMethod",threadPoolKey = "test4",threadPoolProperties = {@HystrixProperty(name = "coreSize", value = "2") ,@HystrixProperty(name = "maxQueueSize",value = "2")},commandProperties = {@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "2"),@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50")}) public String test4() { System.out.println("test4 threadName:"+Thread.currentThread().getName()); test3(); return "test4"; } @HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE"),@HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests",value = "2")}) public String test5() { try { Thread.sleep(700); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test5 threadName:"+Thread.currentThread().getName()); return "test5"; } @HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE"),@HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests",value = "2")}) public String test6() { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test6 threadName:"+Thread.currentThread().getName()); return "test6"; } public String fallbackMethod() { System.out.println("fallbackMethod threadName:"+Thread.currentThread().getName()); return "fallbackMethod"; } } <file_sep>/feign_consumer/src/main/java/feign/Serivce/HystrixService.java package feign.Serivce; import feign.Controller.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(value = "hystrix",path = "/hy") public interface HystrixService { @RequestMapping("/test4") public String test4(); } <file_sep>/authentication/src/main/java/com/example/authentication/Controller/MyController.java package com.example.authentication.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/lcc") public class MyController { @RequestMapping("/test1") public String tets() { return "test1"; } }
19bac4c7fbe42b6e88c91127aca8e922b6d46920
[ "Java" ]
10
Java
liucc0413/SpringCloudEureka
2add1444b0f0f30f3063475af142fc008caa3086
1d915bf5f82b985c47b8713bb8c73c7989e8b3e9
refs/heads/master
<file_sep># ~*~ coding: utf-8 ~*~ """ fedora-software Unit tests - test.py This module tests fedora-software's in order to ensure that the various parts (units) behave as expected """ from django.conf import settings from django.core.urlresolvers import reverse, resolve from django.template.loader import render_to_string from django.test import TestCase from fedora_software.views import HomeView from fedora_software.models import Component, FeaturedApp class HelperSuite(TestCase): """ Suite which shares common helper methods between various test cases. """ def create_sample_component(self, type_id, type_="desktop"): """ Helper method created in order to populate the table 'Component' """ sample_component = Component() sample_component.type = type_ sample_component.type_id = type_id sample_component.save() return sample_component def create_sample_featured_app(self, component): """ Helper method created in order to populate the table 'FeaturedApp' """ sample_featured_app = FeaturedApp() sample_featured_app.component = component sample_featured_app.save() return sample_featured_app class ViewTest(HelperSuite): """ Suite of unit tests performed against views """ def test_root_url_resolves_to_home(self): """ Tests that the home page's url is correctly resolved """ resolved = resolve("/") self.assertEqual(type(resolved.func), type(HomeView.as_view())) def test_home_page_returns_correct_html(self): """ Tests that the HomeView seems to use the correct template """ # this test should be improved and made more useful sample_component = self.create_sample_component(type_id="gimp.desktop") self.create_sample_featured_app(component=sample_component) response = self.client.get(reverse('home')) template_html = render_to_string( 'home.html', {"LANGUAGES": settings.LANGUAGES[:]} ) self.assertAlmostEqual( len(response.content.decode())/1000, len(template_html)/1000, ) class ModelTest(HelperSuite): """ Suite of unit tests performed against models """ def test_create_component(self): """ Tests the creation of a Component """ first_component = Component() first_component.type = "desktop" first_component.type_id = "firefox.desktop" first_component.save() second_component = Component() second_component.type = "desktop" second_component.type_id = "xchat.desktop" second_component.save() saved_components = Component.objects.all() self.assertEqual(saved_components.count(), 2) def test_create_featured_app(self): """ Tests the creation of a FeaturedApp """ sample_component =self.create_sample_component( type_id="firefox.desktop" ) first_featured_app = FeaturedApp() first_featured_app.component = sample_component first_featured_app.save() sample_component = self.create_sample_component( type_id="ardour.desktop" ) second_featured_app = FeaturedApp() second_featured_app.component = sample_component second_featured_app.save() saved_featured_apps = FeaturedApp.objects.all() self.assertEqual(saved_featured_apps.count(), 2) <file_sep># ~*~ coding: utf-8 ~*~ """ fedora-software Functional tests - test_base.py This module tests fedora-software's main functionality by user's point of view. """ from selenium import webdriver from django.test import TestCase from fedora_software.models import FeaturedApp class FunctionalTest(TestCase): """ Suite of Acceptance tests. """ fixtures = ["fedora_software_testing.json"] def setUp(self): """ Sets up a testing environment. """ self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) self.browser.get("http://localhost:8000") def tearDown(self): """ Cleans the environment before testing. """ self.browser.quit() def test_if_fedora_software_is_reachable(self): """ Checks if the browser is able to reach fedora-software """ # Kathe is the user of our example. She has heard about a new # exciting software for her Fedora's workstation. She visits it # via Firefox. # She notices the page title mention 'Fedora-Software' self.assertIn("Welcome to Fedora Software", self.browser.title) def test_if_featured_apps_are_displayed_correctly(self): """ Tests if the featured apps are correctly displayed on the home """ # She also see a section which seems to contain some packages # listed as 'Featured apps'. featured_header_text = self.browser.find_element_by_tag_name('h1').text self.assertEqual("Featured apps", featured_header_text) # She notices that there some apps appears randomly app_link = self.browser.find_element_by_id("featured_app_href") app_link = app_link.get_attribute("href") app_pkgname = "None" i = 0 for app in FeaturedApp.objects.all(): app_name_from_link = app_link.split("/apps/")[1] if app_name_from_link in app.component.type_id: app_type_id = app.component.type_id break self.assertIn(app_name_from_link, app_type_id)
79191fb33594dce7c65bbc2a3cdeb18ccc138b02
[ "Python" ]
2
Python
pombredanne/fedora-software
061e6f25f45fbd91d13d4b0516fb14fcfeec0899
c22f2bb4b4490478c83bd6c691b520c3b1377061
refs/heads/master
<file_sep>The config files included here must be moved to /etc/rethinkdb To start rethinkdb sudo /etc/init.d/rethinkdb restart <file_sep>var request = require('request') var cheerio = require('cheerio') function getFrontPageStories() { request('http://www.mediapool.bg', function (error, response, html) { if (!error && response.statusCode == 200) { console.log('Links:'); var $ = cheerio.load(html); var headline = 'div.hot_news > div.big_title > a'; var other = 'a.news_in_a'; $(headline).add(other).each(function (i) { console.log((i+1) + "." + $(this).attr('title')); console.log($(this).attr('href')); }); } else { console.log(error); } }); } getFrontPageStories(); <file_sep># newsbg ## INSTALL - instal rethink db http://www.rethinkdb.com/docs/install/ - setup rethink db using the config file and instructions included - install node and npm https://nodejs.org/ - instal npm dependencies npm install <file_sep> View the RethinkDB admin interface -------------------------------- ssh -N -L 31337:localhost:8180 denchev.io Then open your browser to localhost:31337 <file_sep> /** * A function that returns a connection to the database * * @param db_name The name of the data base to which we would like to connect * */ function rdb(dbName) { r = require('rethinkdb'); r.connect({ host: 'localhost', port: 28115 }, function(err, conn) { if(err) { throw err; } }); return r; }
e61a87cfafa2f51579b5033c227fd1aa878c91dd
[ "Markdown", "JavaScript" ]
5
Markdown
NewsBG/newsbg
58caeea44d03fcbb1e92861866f699a52c3da139
c318fed87752b3b70736055a372c78f150953c41
refs/heads/master
<repo_name>davibennun/tradeinsManagmentYiiApp<file_sep>/common/api/responses/LoginResponse.php <?php namespace common\api\responses; use Phpro\SoapClient\Type\ResultInterface; class LoginResponse implements ResultInterface{ public $sessionId; public function __construct($sessionId) { $this->sessionId = $sessionId; } }<file_sep>/frontend/controllers/behaviours/EditableBehaviour.php <?php namespace frontend\controllers\behaviours; use Yii; use yii\base\ActionFilter; class EditableBehaviour extends ActionFilter{ public $modelName; public $model; public $validation; public function beforeAction($action) { $request= Yii::$app->request; if ($request->post('hasEditable')) { $this->model = (new $this->modelName)->findOne($request->post('editableKey') ? $request->post('editableKey') : $request->get('id')); $singleModelName = (new \ReflectionClass($this->modelName))->getShortName(); $posted = current($request->post($singleModelName)); $post= is_array($posted) ? [$singleModelName => $posted] : [ $singleModelName => $request->post($singleModelName) ]; if ($this->model->load($post)) { $out = ['output' => '', 'message' => '']; if (!$this->model->validate()) { $message = array_values($this->model->errors)[0][0]; $out['message'] = $message; }else{ $this->model->save(); } Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; Yii::$app->response->content = json_encode($out); } return false; } return parent::beforeAction($action); } }<file_sep>/tests/codeception/frontend/functional/AdminCept.php <?php namespace tests\codeception\frontend\functional; use tests\codeception\frontend\FunctionalTester; use tests\codeception\common\_pages\LoginPage; /* @var $scenario \Codeception\Scenario */ $I = new FunctionalTester($scenario); $I->wantTo('ensure admin protection works'); $I->amGoingTo('access users page as a guest'); $I->amOnPage('?r=tradein'); $I->expectTo('be redirected to login page'); $I->seeInCurrentUrl('?r=site%2Flogin'); $I->amGoingTo('access users page as a regular user'); $loginPage = LoginPage::openBy($I); $loginPage->login('erau', '<PASSWORD>'); $I->expectTo('see forbidden page'); $I->see('Forbidden'); $I->amGoingTo('access users page as an admin'); $loginPage = LoginPage::openBy($I); $loginPage->login('erau', '<PASSWORD>'); $I->expectTo('see users page'); $I->see('Users'); <file_sep>/tests/codeception/frontend/acceptance/SearchTradeinsCept.php <?php /* @var $scenario Codeception\Scenario */ $I = new tests\codeception\frontend\Step\Acceptance\OperatorSteps($scenario); $I->wantTo('search tradeins by first and last name, contact dates and model number'); $tradeins = $I->haveAListOfTradeins(3); $tradein = $tradeins[0]; $I->amInTradeinsListPage(); $I->searchTradeinsBy('first_name', $tradein->first_name); $I->onlySeeTradeinInGrid($tradein); $I->amInTradeinsListPage(); $I->searchTradeinsBy('last_name', $tradein->last_name); $I->onlySeeTradeinInGrid($tradein); $I->amInTradeinsListPage(); $I->searchTradeinsBy('model_number', $tradein->model_number); $I->onlySeeTradeinInGrid($tradein); $I->amInTradeinsListPage(); $humanDate = \DateTime::createFromFormat('Y-m-d',$tradein->first_contact)->format('m-d-Y'); $I->searchTradeinsByDate('first_contact', $humanDate); $I->onlySeeTradeinInGrid($tradein); $I->amInTradeinsListPage(); $humanDate = \DateTime::createFromFormat('Y-m-d', $tradein->last_contact)->format('m-d-Y'); $I->searchTradeinsByDate('last_contact', $humanDate); $I->onlySeeTradeinInGrid($tradein); <file_sep>/frontend/views/tradein/_expand-row-details.php <?php use common\models\Tradein; use kartik\editable\Editable; use kartik\file\FileInputAsset; use kartik\widgets\FileInput; use yii\helpers\Html; use yii\helpers\Json; use yii\helpers\Url; use dosamigos\fileupload\FileUploadUI; FileInputAsset::register($this); $fileUploadId = uniqid(); $beforeInput = function($attr) use ($model, $index, $key){ $strKey = !is_string($key) && !is_numeric($key) ? (is_array($key) ? Json::encode($key) : (string)$key) : $key; return $params = Html::hiddenInput('editableIndex', $index) . Html::hiddenInput('editableKey', $strKey) . Html::hiddenInput('editableAttribute', $attr); }; $gen = function ($attr, $opt = []) use ($model, $index, $key, $beforeInput) { return array_merge([ 'id' => 'tradein-' . $index . '-' . $attr, 'model' => $model, 'name' => 'Tradein[' . $index . '][' . $attr . ']', 'value' => $model->$attr, 'asPopover' => false, 'header' => $model->getAttributeLabel($attr), 'size' => 'md', 'options' => ['class' => 'form-control'], 'beforeInput'=> $beforeInput($attr), 'pluginEvents'=>[ 'editableSubmit' => "function(event, val, form) { var sel = '#td-'+$('input.kv-editable-input',form).attr('id'); $(sel).html(val); }", ] ], $opt); }; // Create a dummy grid $grid = Yii::createObject(['class' => 'kartik\grid\GridView', 'export' => false, 'dataProvider' => Yii::createObject('yii\data\ArrayDataProvider')]); $genDate = function($attr, $opt=[]) use ($grid, $model, $index, $key, $beforeInput) { return Yii::createObject(array_merge([ 'grid' => $grid, 'class' => 'kartik\grid\EditableColumn', 'attribute' => $attr, 'hAlign' => 'center', 'vAlign' => 'middle', 'format' => ['date', 'php:m-d-Y'], 'width' => '20%', 'xlFormat' => "mmm\\-dd\\, \\-yyyy", 'headerOptions' => ['class' => 'kv-sticky-column'], 'contentOptions' => ['class' => 'kv-sticky-column'], 'editableOptions' => [ 'header' => $model->getAttributeLabel($attr), 'size' => 'md', 'inputType' => \kartik\editable\Editable::INPUT_WIDGET, 'widgetClass' => 'kartik\datecontrol\DateControl', 'pluginEvents' => [ 'editableSubmit' => "function(event, val, form) { var sel = '#td-'+$('input.kv-editable-input',form).attr('id').replace('-disp',''); $(sel).html(val); console.log(sel, val); }" ], 'options' => [ 'type' => \kartik\datecontrol\DateControl::FORMAT_DATE, 'displayFormat' => 'php:m-d-Y', 'saveFormat' => 'php:Y-m-d', 'options' => [ 'name' => 'Tradein[' . $index . ']['.$attr.']', 'pluginOptions' => [ 'autoclose' => true ] ] ] ], ],$opt))->renderDataCellContent($model, $key, $index); }; $statusValueConfig = [ '10' => '<span class="label label-primary">Active</span>', '20' => '<span class="label label-default">Inactive</span>', '30' => '<span class="label label-danger">Closed</span>', '40' => '<span class="label label-success">Successful</span>', ]; $genImage = function($attr, $title) use ($model, $key, $index){ return empty($model->$attr) ? '' : '{ "key":"'.$attr.'", "name":"'.$title.'", "url": "'.$model->$attr.'", "thumbnailUrl": "'.$model->$attr.'", "deleteUrl": "'. Url::to(['tradein/delete-image','id'=>$model->id,'key'=>$attr]) .'", "deleteType":"DELETE" },'; }; ?> <h3> <?= Editable::widget($gen('status', [ 'inputType' => Editable::INPUT_DROPDOWN_LIST, 'asPopover' => true, 'data' => Tradein::$statusLabels, 'options' => ['class' => 'form-control', 'prompt' => 'Select status...'], 'displayValueConfig' => $statusValueConfig, 'pluginEvents' => [ 'editableSubmit' => "function(event, val, form) { var id = '#td-'+$('select',form).attr('id'); var valueConfig = ".json_encode($statusValueConfig)."; $(id).html(valueConfig[val]); }" ], ])); ?> Tradein # <?= $model->id ?> <small><?= \Datetime::createFromFormat('Y-m-d H:i:s', $model->creation_time)->format('m-d-Y h:i A'); ?></small> </h3> <table id="w7" class="table table-hover table-bordered detail-view" data-krajee-kvdetailview="kvDetailView_6af70826"> <tbody> <tr class="info"> <th colspan="2">Customer Information</th> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">First Name</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('first_name')); ?></div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Last Name</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('last_name')); ?></div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Email</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('email')); ?></div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Phone</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('phone')); ?></div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">First Contact</th> <td style="width:30%"> <div class="kv-attribute"> <?= $genDate('first_contact'); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Last Contact</th> <td style="width:30%"> <div class="kv-attribute"> <?= $genDate('last_contact'); ?> </div> </td> </tr> </tbody> </table> </td> </tr> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Contact Notes</th> <td style="width: 80%;"> <?= Editable::widget($gen('contact_notes',[ 'inputType'=> Editable::INPUT_TEXTAREA, 'submitOnEnter' => false, 'editableValueOptions' => ['style' => 'text-align:left'], 'displayValue' => nl2br($model->contact_notes), 'options' => ['class' => 'form-control', 'rows' => 5, 'style' => 'width:400px', 'placeholder' => 'Enter notes...'] ])); ?> </td> </tr> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Internal Notes</th> <td style="width: 80%;"> <?= Editable::widget($gen('internal_notes', [ 'inputType' => Editable::INPUT_TEXTAREA, 'editableValueOptions'=> ['style'=>'text-align:left'], 'displayValue'=> nl2br($model->internal_notes), 'submitOnEnter' => false, 'options' => ['class' => 'form-control', 'rows' => 5, 'style' => 'width:400px;', 'placeholder' => 'Enter notes...'] ])); ?> </td> </tr> <tr class="info"> <th colspan="2">Watch Info</th> </tr> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Images</th> <td> <?= FileUploadUI::widget([ 'model' => $model, 'attribute' => 'image1', 'options' => [ 'id' => $fileUploadId, ], 'downloadTemplateId' => 'template-download-2', 'url' => [Url::to('tradein/image-upload'), 'id' => $model->id], 'gallery' => false, 'fieldOptions' => [ 'accept' => 'image/*' ], 'clientOptions' => [ 'maxFileSize' => 2000000, 'maxNumberOfFiles' => 5 ], // ... 'clientEvents' => [ 'fileuploaddone' => 'function(e, data) { $("tbody.files").lightGallery({selector:"a"}); }', ], ]); $this->registerJs(' var files'.$fileUploadId.' = [ '.$genImage('image1', 'Image #1').' '.$genImage('image2', 'Image #2').' '.$genImage('image3', 'Image #3').' '.$genImage('image4', 'Image #4').' '.$genImage('image5', 'Image #5').' ]; $form = jQuery("#'.$fileUploadId.'-fileupload"); $form.fileupload("option", "done").call($form, $.Event("done"), {result: {files: files' . $fileUploadId . '}}); '); ?> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Brand</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('brand')); ?></div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Other Brand</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('other_brand')); ?></div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Model</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('model')); ?></div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Model Number</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('model_number')); ?></div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Condition</th> <td> <div class="kv-attribute" style="word-wrap: break-word !important; white-space: normal !important;"> <?= Editable::widget($gen('condition', [ 'inputType' => Editable::INPUT_TEXTAREA, 'submitOnEnter' => false, 'editableValueOptions' => ['style' => 'text-align:left'], 'displayValue' => nl2br($model->condition), 'options' => ['class' => 'form-control', 'rows' => 5, 'style' => 'width:400px', 'placeholder' => 'Enter condition...'] ])); ?> </div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Item worth if it was new</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('customeritem_if_new')); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Item retail value</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('customeritem_retail_value')); ?></div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Item vendor offer</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('customeritem_vendor_offer')); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Item jomashop offer</th> <td style="width:30%"> <div class="kv-attribute"><?= Editable::widget($gen('customeritem_jomashop_offer')); ?></div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Purchase date</th> <td style="width:30%"> <div class="kv-attribute"> <?= $genDate('purchase_date'); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Purchased from</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('purchased_from')); ?> </div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">Shipping label</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('shipping_label')); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Box papers</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('box_papers')); ?> </div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">New item customer wants</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('info_newitem_customer_wants')); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">New item cost</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('newitem_cost')); ?> </div> </td> </tr> </tbody> </table> </td> </tr> <tr class="kv-child-table-row"> <td class="kv-child-table-cell" colspan="2"> <table class="kv-child-table"> <tbody> <tr> <th style="width: 20%; text-align: right; vertical-align: middle;">New item jomashop current price </th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('newitem_jomashop_currentprice')); ?> </div> </td> <th style="width: 20%; text-align: right; vertical-align: middle;">Out of pocket price</th> <td style="width:30%"> <div class="kv-attribute"> <?= Editable::widget($gen('outofpocket_price')); ?> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table><file_sep>/tests/codeception/frontend/functional/AuthCept.php <?php namespace tests\codeception\frontend\functional; use tests\codeception\frontend\FunctionalTester; use tests\codeception\common\_pages\LoginPage; /* @var $scenario \Codeception\Scenario */ $I = new FunctionalTester($scenario); $I->wantTo('ensure auth works'); $I->amGoingTo('access trade-ins page as a guest'); $I->amOnPage('?r=tradein'); $I->expectTo('be redirected to login page'); $I->seeInCurrentUrl('?r=site%2Flogin'); $I->amGoingTo('access trade-ins page as a registered user'); $loginPage = LoginPage::openBy($I); $loginPage->login('erau', '<PASSWORD>'); $I->expectTo('see tradeins index page'); $I->seeInCurrentUrl('?r=tradein'); <file_sep>/common/models/TradeinSearch.php <?php namespace common\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use common\models\Tradein; use yii\data\ArrayDataProvider; /** * TradeinSearch represents the model behind the search form about `common\models\Tradein`. */ class TradeinSearch extends Tradein { /** * @inheritdoc */ public function rules() { return [ [['id'], 'integer'], [['status', 'first_name', 'last_name', 'model_number','brand', 'brand', 'email', 'shipping_label', 'phone', 'brand', 'other_brand', 'model', 'model_number', 'customeritem_if_new', 'customeritem_retail_value', 'customeritem_vendor_offer', 'customeritem_jomashop_offer', 'purchased_from', 'box_papers', 'condition', 'image1', 'image2', 'image3', 'image4', 'image5', 'info_newitem_customer_wants', 'newitem_cost', 'newitem_jomashop_currentprice', 'outofpocket_price'], 'safe'], [['first_contact', 'last_contact', 'purchase_date'], 'default', 'value' => null], [['first_contact', 'last_contact', 'purchase_date'], 'date', 'format' => 'php:Y-m-d'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Tradein::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // Order, recent first $query->orderBy('id DESC'); // grid filtering conditions $query->andFilterWhere([ 'id' => $this->id, ]); // Extract all fields from rules $fields = []; foreach($this->rules() as $rule){ array_walk($rule[0], function($field) use (&$fields){ $fields[] = $field; }); } // Mount query foreach($fields as $field){ $query->andFilterWhere(['like', $field, $this->$field]); } return $dataProvider; } } <file_sep>/console/migrations/m160603_190942_add_status_column_to_tradeins_table.php <?php use common\models\Tradein; use yii\db\Migration; /** * Handles adding status_column to table `tradeins_table`. */ class m160603_190942_add_status_column_to_tradeins_table extends Migration { /** * @inheritdoc */ public function up() { $this->addColumn('tradeins', 'status', $this->string()->defaultValue(Tradein::STATUS_ACTIVE)); } /** * @inheritdoc */ public function down() { $this->dropColumn('tradeins', 'status'); } } <file_sep>/console/controllers/TradeinController.php <?php namespace console\controllers; use common\api\clients\JomaShopClientFacade as JomaShopClient; use common\api\requests\LoginRequest; use common\api\requests\LogoutRequest; use common\api\requests\TradeinFormInfoPaginatedRequest; use common\models\Tradein; use yii\console\Controller; use Yii; class TradeinController extends Controller{ /** * @var \common\models\Tradein */ public $tradein; public function __construct($id, $module, $config = [], Tradein $tradein) { $this->tradein = $tradein; parent::__construct($id, $module, $config); } public function actionImport() { // Get the last incremented inserted tradein id, if there's no tradeins in table set it to 0 $lastTradein = $this->tradein->lastInserted(); $lastInsertedId = $lastTradein ? $lastTradein->id : 0; $lastInsertedId++; // Logs in $session_id = JomaShopClient::login(new LoginRequest(Yii::$app->params['jomaShopSoapUsername'], Yii::$app->params['jomaShopSoapApiKey'])); // Request just one tradein after the last inserted one $request = new TradeinFormInfoPaginatedRequest($session_id, $lastInsertedId, PHP_INT_MAX, 1, 1); // Make the request, gets the tradein and saves it, sets the startingFromId to this just inserted tradein // and make the request again until it return an empty array, meaning that there's no more tradeins while ($tradeins = JomaShopClient::tradeinFormInfoPaginated($request)->tradeins) { foreach ($tradeins as $tradein) { if ($tradein->save()) print_r($tradein->id); } $request->setStartingTradeinFormId($tradein->id + 1); } // Logs out JomaShopClient::logout(new LogoutRequest($session_id)); } }<file_sep>/common/api/components/SoapClientFacade.php <?php namespace common\api\components; abstract class SoapClientFacade { /** * The underlying instance. * * @var mixed */ private static $instance; /** * Get the underlying instance. * * We'll always cache the instance and reuse it. * * @return mixed */ public static function instance() { if (!self::$instance) { self::$instance = \Yii::$app->soap->build((new static)->getClientName()); } return self::$instance; } /** * Reset the underlying instance. * * @return mixed */ public static function reset() { self::$instance = null; return self::instance(); } /** * Return the client name for Soap Component. * Should be implemented by child class. * * @return string $clientName Client Name for SOAP Component */ abstract public function getClientName(); /** * Handle dynamic, static calls to the object. * * @codeCoverageIgnore * * @param string $method The method name. * @param array $arguments The arguments. * * @return mixed */ public static function __callStatic($method, $arguments) { switch (count($arguments)) { case 0: return self::instance()->$method(); case 1: return self::instance()->$method($arguments[0]); case 2: return self::instance()->$method($arguments[0], $arguments[1]); case 3: return self::instance()->$method($arguments[0], $arguments[1], $arguments[2]); default: return call_user_func_array([self::instance(), $method], $arguments); } } }<file_sep>/tests/codeception/frontend/_support/FactoryMuffinTrait.php <?php namespace tests\codeception\frontend; use saada\FactoryMuffin\FactoryMuffin; trait FactoryMuffinTrait { protected static $factoryMuffinInstance; public function fm() { if (!static::$factoryMuffinInstance) static::$factoryMuffinInstance = new FactoryMuffin($this->getModelDefinitions()); return static::$factoryMuffinInstance; } }<file_sep>/common/api/mappers/LoginMapper.php <?php namespace common\api\mappers; use common\api\responses\LoginResponse; use common\api\components\MapperInterface; class LoginMapper implements MapperInterface{ public function map($response) { return new LoginResponse($response); } }<file_sep>/frontend/controllers/TradeinController.php <?php namespace frontend\controllers; use HttpException; use Yii; use common\models\Tradein; use common\models\TradeinSearch; use frontend\controllers\behaviours\EditableBehaviour; use yii\filters\AccessControl; use yii\helpers\Json; use yii\helpers\Url; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\web\UploadedFile; /** * TradeinController implements the CRUD actions for Tradein model. */ class TradeinController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], 'editable' => [ 'class' => EditableBehaviour::class, 'modelName' => Tradein::class ] ]; } /** * Lists all Tradein models. * @return mixed */ public function actionIndex() { $searchModel = new TradeinSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Tradein model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Tradein model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Tradein(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Tradein model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Tradein model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } public function actionImageUpload() { $imageFile = UploadedFile::getInstanceByName('Tradein[image1]'); $directory = \Yii::getAlias('@frontend/web/uploads'); if (!is_dir($directory)) { mkdir($directory); } if ($imageFile) { $fileName = uniqid() . '.' . $imageFile->extension; $filePath = \Yii::getAlias('@frontend/web/uploads') . '/'. $fileName; $relativePath = '/uploads/'.$fileName; if ($imageFile->saveAs($filePath)) { $tradein = $this->findModel(Yii::$app->request->get('id')); if(! $imageColumn = $tradein->getNextAvailableImageSlot()) throw new HttpException(400, 'Maximum number of images exceeded.'); $tradein->$imageColumn = URL::to($relativePath,true); if($tradein->save()) return Json::encode([ 'files' => [[ 'name' => 'Image #' . substr($imageColumn, -1), 'key' => $imageColumn, 'size' => $imageFile->size, "url" => $relativePath, "thumbnailUrl" => $relativePath, "deleteUrl" => Url::to(['tradein/delete-image', 'id' => $tradein->id, 'key' => $imageColumn]), "deleteType" => "DELETE" ]] ]); } } return ''; } public function actionDeleteImage() { if (Yii::$app->request->isDelete) { if(! ($imageField = Yii::$app->request->get('key'))){ throw new BadRequestHttpException('Your requeset should contain a "key" attribute, ie. the image field you are trying to remove'); } $model = $this->findModel(Yii::$app->request->get('id')); $pathChunks = explode('/', $model->$imageField); unlink(\Yii::getAlias('@frontend/web/uploads') . '/' . end($pathChunks)); $model->$imageField = null; if($model->save()){ echo '{}'; }else{ echo json_encode(['error'=>$model->errors]); } } } /** * Finds the Tradein model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Tradein the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Tradein::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } } <file_sep>/common/api/requests/LogoutRequest.php <?php namespace common\api\requests; use Phpro\SoapClient\Type\RequestInterface; class LogoutRequest implements RequestInterface{ public $sessionId; public function __construct($sessionId) { $this->sessionId = $sessionId; } }<file_sep>/frontend/views/vendor-quotes/index.php <?php use common\widgets\Alert; use yii\helpers\Html; use kartik\grid\GridView as KartikGridView; /* @var $this yii\web\View */ /* @var $searchModel common\models\SearchVendorQuotes */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Vendor Quotes'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="vendor-quotes-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <?= Alert::widget() ?> <p> <?= Html::a('Create a Vendor Quote', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= KartikGridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'export' => false, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], ['class' => kartik\grid\EditableColumn::class, 'attribute' => 'brand'], ['class' => kartik\grid\EditableColumn::class, 'attribute' => 'model'], ['class' => kartik\grid\EditableColumn::class, 'attribute' => 'price'], ['class' => 'yii\grid\ActionColumn', 'visibleButtons' => [ 'view' => false, 'update' => false, ]], ], ]); ?> </div> <file_sep>/tests/codeception/frontend/acceptance/NavigateTroughAPageOfTradeinsCept.php <?php /* @var $scenario Codeception\Scenario */ $I = new tests\codeception\frontend\Step\Acceptance\OperatorSteps($scenario); $I->wantTo('navigate trough pages of tradeins'); $tradeins = $I->haveAListOfTradeins(50); $I->amInTradeinsListPage(); $I->seeNextPageButton();<file_sep>/console/migrations/m160516_154928_add_contact_notes_to_tradeins.php <?php use yii\db\Migration; /** * Handles adding contact_notes to table `tradeins`. */ class m160516_154928_add_contact_notes_to_tradeins extends Migration { /** * @inheritdoc */ public function up() { $this->addColumn('tradeins', 'contact_notes', $this->text()); } /** * @inheritdoc */ public function down() { $this->dropColumn('tradeins', 'contact_notes'); } } <file_sep>/common/models/Tradein.php <?php namespace common\models; use saada\FactoryMuffin\FactoryInterface; use League\FactoryMuffin\Faker\Facade as Faker; use Phpro\SoapClient\Type\ResultInterface; use Yii; /** * This is the model class for table "tradeins". * * @property integer $id * @property string $first_name * @property string $last_name * @property string $watch * @property string $model * @property string $brand * @property string $value */ class Tradein extends \yii\db\ActiveRecord implements FactoryInterface, ResultInterface { public $dateFormatter = ['display'=>'m-d-Y','save'=>'Y-m-d']; const STATUS_ACTIVE = 10; const STATUS_ACTIVE_LABEL = 'Active'; const STATUS_INACTIVE = 20; const STATUS_INACTIVE_LABEL = 'Inactive'; const STATUS_CLOSED = 30; const STATUS_CLOSED_LABEL = 'Closed'; const STATUS_SUCCESSFUL = 40; const STATUS_SUCCESSFUL_LABEL = 'Successful'; public static $statusLabels = [ self::STATUS_ACTIVE => self::STATUS_ACTIVE_LABEL, self::STATUS_INACTIVE => self::STATUS_INACTIVE_LABEL, self::STATUS_CLOSED => self::STATUS_CLOSED_LABEL, self::STATUS_SUCCESSFUL => self::STATUS_SUCCESSFUL_LABEL ]; /** * @inheritdoc */ public static function tableName() { return 'tradeins'; } /** * @inheritdoc */ public function rules() { return [ [['status', 'customeritem_if_new', 'customeritem_retail_value', 'customeritem_vendor_offer', 'customeritem_jomashop_offer', 'purchase_date', 'purchased_from', 'box_papers', 'condition', 'image1', 'image2', 'image3', 'image4', 'image5', 'info_newitem_customer_wants', 'newitem_cost', 'newitem_jomashop_currentprice', 'outofpocket_price'], 'safe'], [['first_name', 'last_name', 'model_number', 'brand', 'email','shipping_label','phone','brand','other_brand','model','model_number'], 'string', 'max' => 255], [['internal_notes', 'contact_notes'], 'string','max'=>65535], [['first_contact', 'last_contact', 'email', 'customeritem_if_new', 'customeritem_retail_value', 'customeritem_vendor_offer', 'customeritem_jomashop_offer', 'purchase_date', 'purchased_from', 'box_papers', 'condition', 'image1', 'image2', 'image3', 'image4', 'image5', 'info_newitem_customer_wants', 'newitem_cost', 'newitem_jomashop_currentprice', 'outofpocket_price'], 'default', 'value' => null], [['email'], 'email', 'skipOnEmpty'=>true], [['first_contact','last_contact', 'purchase_date'], 'date', 'format'=>'php:Y-m-d'], [['creation_time'], 'date', 'format'=>'php:Y-m-d H:i:s'], ]; } /** * Mainly to format dates */ public function beforeValidate() { parent::beforeValidate(); // Get model date values based on rules foreach($this->rules() as $rule){ $fields = $rule[0]; $type = $rule[1]; if($type == 'date'){ foreach($fields as $field){ if(empty($field)) continue; if($this->$field instanceOf \DateTime) $this->$field = $this->$field->format(str_replace('php:', '', $rule['format'])); $theDate = \DateTime::createFromFormat($this->dateFormatter['display'], $this->$field); // Formats date only if its valid if (\DateTime::getLastErrors()['error_count'] == 0) { $this->$field = $theDate->format($this->dateFormatter['save']); } } } } return true; } public function lastInserted() { return $this->find()->limit(1)->orderby('id DESC')->one(); } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'first_name' => '<NAME>', 'last_name' => '<NAME>', 'internal_notes' => 'Internal notes', 'first_contact' => 'First contact', 'last_contact' => 'Last contact', 'contact_notes'=> 'Contact notes', 'shipping_label'=> 'Shipping label', 'email'=>'Email', 'phone'=>'Phone', 'brand'=>'Brand', 'other_brand'=>'Other brand', 'model' => 'Model', 'model_number' => 'Model number', 'customeritem_if_new' => 'Item worth if it was new', 'customeritem_retail_value' => 'Customer item retail value', 'customeritem_vendor_offer' => 'Customer vendor offer', 'customeritem_jomashop_offer' => 'Customer item jomashop offer', 'purchase_date' => 'Purchase date', 'purchased_from' => 'Purchased from', 'box_papers' => 'Box or papers', 'condition' => 'Condition', 'image1' => 'Image #1', 'image2' => 'Image #2', 'image3' => 'Image #3', 'image4' => 'Image #4', 'image5' => 'Image #5', 'info_newitem_customer_wants' => 'New item customer wants', 'newitem_cost' => 'New item cost', 'newitem_jomashop_currentprice' => 'New item jomashop current price', 'outofpocket_price' => 'Out of pocket price', 'creation_time' => 'Creation time', 'importion_time' => 'Importion time', 'status' => 'Status' ]; } public function getStatusText() { $text = 'Active'; switch($this->status){ case static::STATUS_ACTIVE: $text = 'Active'; break; case static::STATUS_INACTIVE: $text = 'Inactive'; break; case static::STATUS_CLOSED: $text = 'Closed'; break; case static::STATUS_SUCCESSFUL: $text = 'Successful'; break; } return $text; } public function getNextAvailableImageSlot() { $imageSlots = ['image1', 'image2', 'image3', 'image4', 'image5']; return current(array_filter($imageSlots, function($slot){ return empty($this->$slot); })); } public static function definitions() { return [ [ 'first_name'=> Faker::firstName(), 'last_name'=> Faker::lastName(), 'model' => Faker::word(), 'brand' => Faker::company(), 'internal_notes' => Faker::paragraph(), 'first_contact' => Faker::date(), 'last_contact' => Faker::date(), 'contact_notes'=> Faker::paragraph(), 'shipping_label'=> Faker::uuid(), 'email' => Faker::email(), 'phone'=>Faker::phoneNumber(), 'other_brand'=> Faker::company(), 'model_number' => Faker::numerify('######'), 'customeritem_if_new' => Faker::boolean(), 'customeritem_retail_value' => Faker::numerify('###'), 'customeritem_vendor_offer' => Faker::numerify('###'), 'customeritem_jomashop_offer' => Faker::numerify('###'), 'purchase_date' => Faker::date(), 'purchased_from' => Faker::name(), 'box_papers' => Faker::randomElement(['yes','no']), 'condition' => Faker::randomElement(['new','used','refurbished']), 'image1' => 'http://placehold.it/140x100?text=not+set+1', 'image2' => 'http://placehold.it/140x100?text=not+set+2', 'image3' => 'http://placehold.it/140x100?text=not+set+3', 'image4' => 'http://placehold.it/140x100?text=not+set+4', 'image5' => 'http://placehold.it/140x100?text=not+set+5', 'info_newitem_customer_wants' => Faker::word(), 'newitem_cost' => Faker::numerify('###'), 'newitem_jomashop_currentprice' => Faker::numerify('###'), 'outofpocket_price' => Faker::numerify('###'), 'creation_time' => Faker::dateTime(), ] ]; } } <file_sep>/frontend/views/user/index.php <?php use common\widgets\Alert; use yii\grid\ActionColumn; use yii\helpers\Html; use kartik\grid\GridView as KartikGridView; use kartik\grid\SerialColumn; /* @var $this yii\web\View */ /* @var $searchModel common\models\UserSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Users'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="user-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= Alert::widget() ?> <?= KartikGridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => SerialColumn::class], [ 'class' => 'kartik\grid\EditableColumn', 'attribute' => 'username', ], [ 'class' => 'kartik\grid\EditableColumn', 'attribute' => 'email', ], [ 'class' => ActionColumn::class, 'buttons' => [ 'update'=> function($url, $model){ return Html::a('<span class="glyphicon glyphicon-asterisk"></span>', $url, ['title'=>'Change password']); } ], //Hide delete button when the row is equals to the logged user 'visibleButtons' => ['view'=>false,'delete'=>function($model){ return Yii::$app->user->id != $model->id; }], 'contentOptions' => ['style' => 'width:50px;'] ], ], 'responsive' => true, 'hover' => true, 'export' => false, ]); ?> </div> <file_sep>/common/api/requests/LoginRequest.php <?php namespace common\api\requests; use Phpro\SoapClient\Type\RequestInterface; class LoginRequest implements RequestInterface { /** * @var \SoapParam */ public $username; /** * @var \SoapParam */ public $apiKey; public function __construct($username, $apiKey) { $this->username = new \SoapParam($username, 'username'); $this->apiKey = new \SoapParam($apiKey, 'apiKey'); } }<file_sep>/console/migrations/m160602_211040_add_role_to_users_table.php <?php use yii\db\Migration; use common\models\User; /** * Handles adding role to table `users_table`. */ class m160602_211040_add_role_to_users_table extends Migration { /** * @inheritdoc */ public function up() { $this->addColumn('user', 'role', $this->string()->defaultValue(User::ROLE_USER)); } /** * @inheritdoc */ public function down() { $this->dropColumn('user', 'role'); } } <file_sep>/common/api/components/SoapComponent.php <?php namespace common\api\components; use Phpro\SoapClient\ClientBuilder; use Phpro\SoapClient\ClientFactory; use Phpro\SoapClient\Soap\ClassMap\ClassMap; class SoapComponent { public $clients = []; /** * @param string $clientName * @param string $fullWsdlPath * @param array $classMaps * @param array $options * @return $this */ public function register($clientName, $fullWsdlPath, $classMaps=[], $options=[]) { $clientInfo = [ 'clientName'=> $clientName, 'wsdl'=> $fullWsdlPath, 'options'=> $options, 'classMaps'=>$classMaps ]; $this->clients[] = $clientInfo; return $this; } /** * Adds a class map to a client * * @param string $clientName Client name * @param string $type SOAP Type to be mapped to class * @param string $class Class to bo mapped to type * @return $this */ public function addClassMap($clientName, $type, $class) { $info = $this->get($clientName); $info['classMaps'][] = [$type, $class]; $this->set($info); return $this; } /** * @param $clientName * @param bool $rebuild * @return \Phpro\SoapClient\ClientInterface */ public function build($clientName, $rebuild=false) { //check if client was already built if(isset($this->get($clientName)['theClient']) && !$rebuild){ return $this->get($clientName)['theClient']; } $clientInfo = $this->get($clientName); $clientFactory = new ClientFactory($clientInfo['clientName']); $clientBuilder = new ClientBuilder($clientFactory, $clientInfo['wsdl'], $clientInfo['options']); foreach($clientInfo['classMaps'] as $classMap) { $clientBuilder->addClassMap(new ClassMap($classMap[0], $classMap[1])); } $clientInfo['factory'] = $clientFactory; $clientInfo['builder'] = $clientBuilder; $clientInfo['theClient'] = $clientBuilder->build(); $this->set($clientInfo); return $clientInfo['theClient']; } public function get($clientName){ return current(array_filter($this->clients, function($clientInfo) use ($clientName){ return $clientInfo['clientName'] == $clientName; })); } public function set($clientInfo) { //Remove $cilentInfo from $this->clients (in case it exsits) $clientsClean = array_filter($this->clients, function ($client) use ($clientInfo) { return $client['clientName'] != $clientInfo['clientName']; }); $clientsClean[] = $clientInfo; $this->clients = $clientsClean; } }<file_sep>/frontend/views/tradein/view.php <?php use kartik\editable\Editable; use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\DetailView; use kartik\detail\DetailView as KartikDetailView; /* @var $this yii\web\View */ /* @var $model common\models\Tradein */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => 'Tradeins', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; $gen = function($attr, $opt=[]) use ($model){ return array_merge([ 'id'=> 'tradein-'.$attr, 'model' => $model, 'name' => 'Tradein[0]['.$attr.']', 'value' => $model->$attr, 'asPopover' => false, 'header' => 'Name', 'size' => 'md', 'options' => ['class' => 'form-control'] ], $opt); }; ?> <div class="tradein-view"> <p> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <table id="w0" class="table table-striped table-bordered detail-view"> <tbody> <tr> <th>ID</th> <td><?= $model->id; ?></td> </tr> <tr> <th>First Name</th> <td><?= Editable::widget($gen('first_name')); ?></td> </tr> <tr> <th>Last Name</th> <td><?= Editable::widget($gen('last_name')); ?></td> </tr> <tr> <th>Internal notes</th> <td> <?= Editable::widget($gen('internal_notes', [ 'asPopover' => false, 'name' => 'Tradein[0][internal_notes]', 'displayValue' => $model->internal_notes, 'inputType' => Editable::INPUT_TEXTAREA, 'header' => 'Internal notes', 'submitOnEnter' => false, 'editableValueOptions'=>['style'=>'text-align:left'], 'options' => [ 'class' => 'form-control', 'rows' => 5, 'style' => 'width:500px;text-align:left', 'placeholder' => 'Enter notes...' ] ])); ?> </td> </tr> <tr> <th>First contact</th> <td><?= Editable::widget( [ 'model'=>$model, 'attribute' => 'first_contact', 'header' => 'First contact', 'asPopover' => false, 'format' => 'php:m-d-Y', 'size' => 'md', 'inputType' => Editable::INPUT_DATE, 'header' => 'First contact', 'size' => 'md', 'inputType' => \kartik\editable\Editable::INPUT_WIDGET, 'widgetClass' => 'kartik\datecontrol\DateControl', 'options' => [ 'type' => \kartik\datecontrol\DateControl::FORMAT_DATE, 'displayFormat' => 'php:m-d-Y', 'saveFormat' => 'php:Y-m-d', 'options' => [ 'pluginOptions' => [ 'autoclose' => true ] ] ] ] ); ?></td> </tr> <tr> <th>Last contact</th> <td><?= Editable::widget( [ 'model' => $model, 'attribute' => 'last_contact', 'header' => 'Last contact', 'asPopover' => false, 'size' => 'md', 'inputType' => Editable::INPUT_DATE, 'header' => 'Last contact', 'size' => 'md', 'inputType' => \kartik\editable\Editable::INPUT_WIDGET, 'widgetClass' => 'kartik\datecontrol\DateControl', 'options' => [ 'type' => \kartik\datecontrol\DateControl::FORMAT_DATE, 'displayFormat' => 'php:m-d-Y', 'saveFormat' => 'php:Y-m-d', 'options' => [ 'pluginOptions' => [ 'autoclose' => true ] ] ] ] )?></td> </tr> <tr> <th>Contact notes</th> <td> <?= Editable::widget($gen('contact_notes', [ 'asPopover' => false, 'name' => 'Tradein[0][contact_notes]', 'displayValue' => $model->contact_notes, 'inputType' => Editable::INPUT_TEXTAREA, 'header' => 'Contact notes', 'editableValueOptions' => ['style' => 'text-align:left'], 'submitOnEnter' => false, 'options' => [ 'class' => 'form-control', 'rows' => 5, 'style' => 'width:500px', 'placeholder' => 'Enter notes...' ] ])); ?> </td> </tr> <tr> <th>Shipping label</th> <td><?= Editable::widget($gen('shipping_label')); ?></td> </tr> <tr> <th>Email</th> <td><?= Editable::widget($gen('email')); ?></td> </tr> <tr> <th>Phone</th> <td><?= Editable::widget($gen('phone')); ?></td> </tr> <tr> <th>Brand</th> <td><?= Editable::widget($gen('brand')); ?></td> </tr> <tr> <th>Other brand</th> <td><?= Editable::widget($gen('other_brand')); ?></td> </tr> <tr> <th>Model</th> <td><?= Editable::widget($gen('model')); ?></td> </tr> <tr> <th>Model number</th> <td><?= Editable::widget($gen('model_number')); ?></td> </tr> </tbody> </table> </div> <file_sep>/console/migrations/m160525_212913_add_missing_columns.php <?php use yii\db\Migration; class m160525_212913_add_missing_columns extends Migration { public function up() { $this->addColumn('tradeins', 'customeritem_if_new', $this->string()); $this->addColumn('tradeins', 'customeritem_retail_value', $this->string()); $this->addColumn('tradeins', 'customeritem_vendor_offer', $this->string()); $this->addColumn('tradeins', 'customeritem_jomashop_offer', $this->string()); $this->addColumn('tradeins', 'purchase_date', $this->string()); $this->addColumn('tradeins', 'purchased_from', $this->string()); $this->addColumn('tradeins', 'box_papers', $this->string()); $this->addColumn('tradeins', 'condition', $this->string()); $this->addColumn('tradeins', 'image1', $this->string()); $this->addColumn('tradeins', 'image2', $this->string()); $this->addColumn('tradeins', 'image3', $this->string()); $this->addColumn('tradeins', 'image4', $this->string()); $this->addColumn('tradeins', 'image5', $this->string()); $this->addColumn('tradeins', 'info_newitem_customer_wants', $this->string()); $this->addColumn('tradeins', 'newitem_cost', $this->string()); $this->addColumn('tradeins', 'newitem_jomashop_currentprice', $this->string()); $this->addColumn('tradeins', 'outofpocket_price', $this->string()); $this->addColumn('tradeins', 'creation_time', $this->dateTime() . ' DEFAULT NOW()'); } public function down() { $this->dropColumn('tradeins', 'customeritem_if_new'); $this->dropColumn('tradeins', 'customeritem_retail_value'); $this->dropColumn('tradeins', 'customeritem_vendor_offer'); $this->dropColumn('tradeins', 'customeritem_jomashop_offer'); $this->dropColumn('tradeins', 'purchase_date'); $this->dropColumn('tradeins', 'purchased_from'); $this->dropColumn('tradeins', 'box_papers'); $this->dropColumn('tradeins', 'condition'); $this->dropColumn('tradeins', 'image1'); $this->dropColumn('tradeins', 'image2'); $this->dropColumn('tradeins', 'image3'); $this->dropColumn('tradeins', 'image4'); $this->dropColumn('tradeins', 'image5'); $this->dropColumn('tradeins', 'info_newitem_customer_wants'); $this->dropColumn('tradeins', 'newitem_cost'); $this->dropColumn('tradeins', 'newitem_jomashop_currentprice'); $this->dropColumn('tradeins', 'outofpocket_price'); $this->dropColumn('tradeins', 'creation_time'); return true; } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ } <file_sep>/common/api/clients/BaseSoapClient.php <?php namespace common\api\clients; use common\api\components\MapperInterface; use Phpro\SoapClient\Client; use Phpro\SoapClient\Event; use Phpro\SoapClient\Events; use Phpro\SoapClient\Type\RequestInterface; use Phpro\SoapClient\Type\ResultProviderInterface; use SoapFault; class BaseSoapClient extends Client{ protected function call($method, RequestInterface $request, MapperInterface $mapper = null) { $requestEvent = new Event\RequestEvent($this, $method, $request); $this->dispatcher->dispatch(Events::REQUEST, $requestEvent); try { /** * Because of a weird behaviour of SoapClient I can't call the soap method like this * $soapClient->$method($request); * Instead I have to extract the public vars of $request and call $method and pass them as arguments: * $soapClient->$method($requestPublicAttr1, $requestPublicAttr2, $requestPublicAttr3 ...) */ $attrs = $this->getPublicAttrs($request); $result = call_user_func_array([$this->soapClient, $method], $attrs); $result = $mapper ? $mapper->map($result) : $result; if ($result instanceof ResultProviderInterface) { $result = $result->getResult(); } } catch (SoapFault $soapFault) { $this->dispatcher->dispatch(Events::FAULT, new Event\FaultEvent($this, $soapFault, $requestEvent)); throw $soapFault; } // $this->dispatcher->dispatch(Events::RESPONSE, new Event\ResponseEvent($this, $requestEvent, $result)); return $result; } private function getPublicAttrs($obj) { $publicProperties = (new \ReflectionClass($obj))->getProperties(); //Get public properties of obj $attrs = array_map(function ($prop) { return $prop->name; }, $publicProperties); // Mount an array of field => value $attrsValues = array_map(function ($field) use ($obj) { return $obj->$field; }, $attrs); return $attrsValues; } }<file_sep>/tests/codeception/frontend/acceptance/ListTradeinCept.php <?php /* @var $scenario Codeception\Scenario */ $I = new tests\codeception\frontend\Step\Acceptance\OperatorSteps($scenario); $I->wantTo('List tradeins'); $tradeins = $I->haveAListOfTradeins(5); $I->amInTradeinsListPage(); $I->seeTradeins($tradeins);<file_sep>/common/api/components/MapperInterface.php <?php namespace common\api\components; /** * Interface MapperInterface * @package components */ interface MapperInterface { /** * @param mixed $result * @return mixed */ public function map($result); }<file_sep>/tests/codeception/frontend/functional/UserCept.php <?php namespace tests\codeception\frontend\functional; use common\models\User; use tests\codeception\frontend\FunctionalTester; use tests\codeception\common\_pages\LoginPage; /* @var $scenario \Codeception\Scenario */ $I = new \tests\codeception\frontend\Step\Functional\OperatorSteps($scenario); $I->wantTo('ensure user management works'); $admin = $I->asAnAdmin(); $I->amGoingTo('create an user'); $I->visit('user/create'); $I->expectTo('see user form'); $user = $I->submitUserCreationForm(); $I->expectTo('see user was created successfully'); $I->see('User created successfully'); $I->seeUserInDatabase($user); $user = $user->lastInserted(); $I->amGoingTo('see that the new user can login'); $I->logout(); $I->seeAmOnPage('site/login'); $I->login($user); $I->expectTo('see tradeins page'); $I->see('Tradeins','h1'); $I->logout(); $I->asAnAdmin($admin); $I->amGoingTo('change user password'); $newPass = '<PASSWORD>'; $I->visit('user'); $I->click('a[href="/index-test.php?r=user%2Fupdate&id=' . $user->id . '"]'); $I->submitChangePasswordForm($newPass); $I->click('#logout-link'); $I->amGoingTo('try to login with new password'); $I->login($user, $newPass); $I->expectTo('see that user is logged'); $I->see($user->username); $I->dontSeeLink('Login'); $I->amGoingTo('delete a user'); $I->logout(); $I->asAnAdmin(); $I->visit('user'); $I->see($user->username); $I->click('a[href="/index-test.php?r=user%2Fdelete&id=' . $user->id . '"]'); $I->dontSee($user->username); <file_sep>/console/migrations/m160516_150054_update_tradein_table.php <?php use yii\db\Migration; class m160516_150054_update_tradein_table extends Migration { public function up() { $this->addColumn('tradeins', 'internal_notes', $this->text()); $this->addColumn('tradeins', 'first_contact', $this->date()); $this->addColumn('tradeins', 'last_contact', $this->date()); $this->addColumn('tradeins', 'shipping_label', $this->string()); $this->addColumn('tradeins', 'email', $this->string()); $this->addColumn('tradeins', 'phone', $this->string()); $this->addColumn('tradeins', 'other_brand', $this->string()); $this->addColumn('tradeins', 'model_number', $this->string()); $this->dropColumn('tradeins', 'watch'); $this->dropColumn('tradeins', 'value'); } public function down() { $this->dropColumn('tradeins', 'internal_notes'); $this->dropColumn('tradeins', 'first_contact'); $this->dropColumn('tradeins', 'last_contact'); $this->dropColumn('tradeins', 'shipping_label'); $this->dropColumn('tradeins', 'email'); $this->dropColumn('tradeins', 'phone'); $this->dropColumn('tradeins', 'brand'); $this->dropColumn('tradeins', 'other_brand'); $this->dropColumn('tradeins', 'model'); $this->dropColumn('tradeins', 'model_number'); $this->addColumn('tradeins', 'watch', $this->string()); $this->addColumn('tradeins', 'value', $this->string()); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ } <file_sep>/frontend/views/tradein/index.php <?php use common\models\Tradein; use kartik\dynagrid\DynaGrid; use kartik\export\ExportMenu; use yii\base\View; use yii\helpers\Html; use yii\grid\GridView; use kartik\grid\GridView as KartikGridView; /* @var $this yii\web\View */ /* @var $searchModel common\models\TradeinSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Tradeins'; $this->params['breadcrumbs'][] = $this->title; \kartik\detail\DetailViewAsset::register(Yii::$app->getView()); \frontend\assets\LightGalleryAsset::register(Yii::$app->getView()); $columns = array_keys( (new Tradein())->attributeLabels() ); $exportColumns = array_diff($columns, ['status']); $exportColumns[] = [ 'attribute' => 'status', 'value' => function ($model, $key, $index, $widget) { $labels = Tradein::$statusLabels; return $labels[$model->status]; } ]; $visibleColumns = ['status','first_name','last_name','first_contact','last_contact', 'model_number']; $hiddenColumns = array_diff($columns, $visibleColumns); $hiddenColumnsConfig = []; foreach($hiddenColumns as $hiddenColumn){ $hiddenColumnsConfig[] = [ 'attribute' => $hiddenColumn, 'visible' => false, 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; } ]; } $visibleColumnsConfig = [ [ 'class' => 'kartik\grid\ExpandRowColumn', 'order' => DynaGrid::ORDER_FIX_LEFT, 'width' => '50px', 'value' => function ($model, $key, $index, $column) { return \kartik\grid\GridView::ROW_COLLAPSED; }, 'detail' => function ($model, $key, $index, $column) { return Yii::$app->controller->renderPartial('_expand-row-details', ['model' => $model, 'key' => $key, 'index' => $index]); }, 'headerOptions' => ['class' => 'kartik-sheet-style'], 'expandOneOnly' => true, 'enableRowClick' => true ], [ 'attribute' => 'status', 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; }, 'format' => 'raw', 'width' => '130px', 'value' => function ($model, $key, $index, $widget) { $labels = [ Tradein::STATUS_ACTIVE => '<span class="label label-primary">'.Tradein::STATUS_ACTIVE_LABEL.'</span>', Tradein::STATUS_INACTIVE => '<span class="label label-default">'.Tradein::STATUS_INACTIVE_LABEL.'</span>', Tradein::STATUS_CLOSED => '<span class="label label-danger">'.Tradein::STATUS_CLOSED_LABEL.'</span>', Tradein::STATUS_SUCCESSFUL => '<span class="label label-success">'.Tradein::STATUS_SUCCESSFUL_LABEL.'</span>', ]; return $labels[$model->status]; }, 'filterType' => KartikGridView::FILTER_SELECT2, 'filter' => Tradein::$statusLabels, 'filterWidgetOptions' => [ 'hideSearch' => true, 'pluginOptions' => ['allowClear' => true], ], 'filterInputOptions' => ['placeholder' => 'Select status'], ], [ 'attribute' => 'first_name', 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; } ], [ 'attribute' => 'last_name', 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; } ], [ 'attribute' => 'first_contact', 'format' => ['date', 'php:m-d-Y'], 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; } ], [ 'attribute' => 'last_contact', 'format' => ['date', 'php:m-d-Y'], 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; } ], [ 'attribute' => 'model_number', 'contentOptions' => function ($model, $key, $index, $column) { return ['id' => 'td-tradein-' . $index . '-' . $column->attribute]; } ], ]; $tableColumnsConfig = array_merge($visibleColumnsConfig, $hiddenColumnsConfig); ?> <script id="template-download-2" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-download fade"> <td> <span class="preview"> {% if (file.thumbnailUrl) { %} <a href="{%=file.url%}" title="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a> {% } %} </span> </td> <td> <p class="name"> {%=file.name%} </p> {% if (file.error) { %} <div><span class="label label-danger">Error</span> {%=file.error%}</div> {% } %} </td> <td> {% if (file.deleteUrl) { %} <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}> <i class="glyphicon glyphicon-trash"></i> <span>Delete</span> </button> <input type="checkbox" name="delete" value="1" class="toggle"> {% } else { %} <button class="btn btn-warning cancel"> <i class="glyphicon glyphicon-ban-circle"></i> <span>Cancel</span> </button> {% } %} </td> </tr> {% } %} </script> <div class="tradein-index"> <h1> <?= Html::encode($this->title) ?> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <?= ExportMenu::widget([ 'dataProvider' => $dataProvider, 'columns' => array_merge($exportColumns), 'showColumnSelector' => false, 'exportConfig' => ['HTML' => false, 'TXT' => false, 'PDF' => false, 'Excel5' => false], 'clearBuffers'=>true, 'fontAwesome' => true, 'target' => ExportMenu::TARGET_SELF, 'dropdownOptions' => [ 'label' => 'Export', 'class' => 'btn btn-default' ] ]) ?> </h1> <?= DynaGrid::widget([ 'gridOptions' => [ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'export'=>false, 'showPageSummary' => false, 'floatHeader' => false, 'panel' => [ 'after' => false ], 'resizableColumns' => true, 'persistResize' => false, 'toolbar' => [ ['content' => '{dynagrid}'], '{export}', ] ], 'options' => ['id'=>'dynagrid-tradein-index-1'], 'showPersonalize' => true, // 'allowPageSetting' => false, // Setting allowPageSetting to false causes ordering feature to stop working 'allowSortSetting' => false, 'allowFilterSetting' => false, 'allowThemeSetting' => false, 'columns' => $tableColumnsConfig, ]); ?> </div> <?php $this->registerJs(" $(function(){ $('tbody.files').lightGallery({selector:'a'}); }); "); $this->registerJs(' $(".lightgallery .kv-file-remove").click(function(e){ e.preventDefault(); e.stopPropagation(); if(! confirm("Are you sure you want to remove this image?")) return; var that = this; $.post($(this).data("url"),{ key : $(this).data("key") }).done(function(){ $(that).closest(".image-container-link").fadeOut(); }).fail(function(){ alert("Error when removing image"); }); }) '); ?><file_sep>/common/api/responses/TradeinFormInfoPaginatedResponse.php <?php namespace common\api\responses; use Phpro\SoapClient\Type\ResultInterface; class TradeinFormInfoPaginatedResponse implements ResultInterface{ public $tradeins = []; public function __construct($tradeins) { $this->tradeins = $tradeins; } }<file_sep>/tests/codeception/frontend/_support/Step/Functional/OperatorSteps.php <?php namespace tests\codeception\frontend\Step\Functional; use common\models\User; use tests\codeception\frontend\FactoryMuffinTrait; class OperatorSteps extends \tests\codeception\frontend\FunctionalTester { use FactoryMuffinTrait; public $urlPrefix = '?r='; public function asAGuest() { $I = $this; } public function asAnUser($user=null) { if( !$user ) $user = $this->haveAnUser(); $this->login($user); return $user; } public function asAnAdmin($user=null) { if( !$user ) $user = $this->haveAnAdmin(); $this->login($user); return $user; } public function login($user, $pass=null) { $this->visit('site/login'); $this->fillLoginForm($user, $pass); return $user; } public function fillLoginForm($user, $pass=null) { $this->fillField('#loginform-username', $user->username); $this->fillField('#loginform-password', $pass ? $pass : '<PASSWORD>'); $this->click('login-button'); } public function submitChangePasswordForm($newPass) { $this->fillField('input[name="UserPassword[password]"]', $newPass); $this->fillField('input[name="UserPassword[password_repeat]"]', $newPass); $this->click('Update'); } public function visit($url) { $this->amOnPage($this->urlPrefix . urlencode($url)); } public function seeAmOnPage($url) { $this->seeInCurrentUrl($this->urlPrefix . urlencode($url)); } public function submitUserCreationForm($user=null) { $user = $this->imagineAnUser(); $this->visit('user/create'); $this->fillField('input[name="UserCreate[username]"]', $user->username); $this->fillField('input[name="UserCreate[email]"]', $user->email); $this->fillField('input[name="UserCreate[password]"]', '<PASSWORD>'); $this->fillField('input[name="UserCreate[password_repeat]"]', '<PASSWORD>'); $this->click('Create'); return $user; } public function logout() { $this->click('#logout-link'); } public function imagineAnUser($attr=[]) { return $this->fm()->instance(User::class, $attr); } public function haveAnUser($attr=[]) { $attr = array_merge($this->imagineAnUser()->getAttributes(), $attr, ['role' => User::ROLE_ADMIN]); return $this->fm()->create(User::class, $attr); } public function haveAnAdmin($attr=[]) { $attr = array_merge($this->imagineAnUser()->getAttributes(), $attr, ['role' => User::ROLE_ADMIN]); codecept_debug($attr); return $this->fm()->create(User::class, $attr); } public function seeUserInDatabase($user) { $this->seeRecord('common\models\User', [ 'username' => $user->username, 'email' => $user->email ]); } public function getModelDefinitions() { return [User::class]; } }<file_sep>/common/api/clients/JomaShopClient.php <?php namespace common\api\clients; use common\api\mappers\LoginMapper; use common\api\mappers\TradeinFormInfoPaginatedMapper; use common\api\requests\LoginRequest; use common\api\requests\LogoutRequest; use common\api\requests\TradeinFormInfoPaginatedRequest; class JomaShopClient extends BaseSoapClient { public function login(LoginRequest $request) { return $this->call('login', $request, new LoginMapper)->sessionId; } public function tradeinFormInfoPaginated(TradeinFormInfoPaginatedRequest $request) { return $this->call('tradeinFormInfoPaginated', $request, new TradeinFormInfoPaginatedMapper); } public function logout(LogoutRequest $request) { return $this->call('endSession', $request); } }<file_sep>/common/api/clients/JomaShopClientFacade.php <?php namespace common\api\clients; use common\api\components\SoapClientFacade; class JomaShopClientFacade extends SoapClientFacade{ public function getClientName() { return JomaShopClient::class; } }<file_sep>/common/api/mappers/TradeinFormInfoPaginatedMapper.php <?php namespace common\api\mappers; use common\api\responses\TradeinFormInfoPaginatedResponse; use common\api\components\MapperInterface; use common\models\Tradein; use yii\helpers\ArrayHelper; /** * Maps soap raw response to active record models * Class TradeinFormInfoPaginatedMapper * @package app\api\mappers */ class TradeinFormInfoPaginatedMapper implements MapperInterface{ public function map($result) { $tradeins = []; foreach ($result as $tradeinObj) { // Convert obj to array $tradeinArray = json_decode(json_encode($tradeinObj), true); // Trim values $tradeinArray = array_map('trim', $tradeinArray); // Convert empty strings to nulls $tradeinArray = array_map(function ($value) { return $value === "" ? null : $value; }, $tradeinArray); // Prepare attributes $tradeinArray['id'] = ArrayHelper::getValue($tradeinArray, 'tradeins_id'); unset($tradeinArray['tradeins_id']); $tradeinArray['creation_time'] = ArrayHelper::getValue($tradeinArray, 'created_time'); unset($tradeinArray['created_time']); $tradeinArray['brand'] = ArrayHelper::getValue($tradeinArray, 'watch_brand'); unset($tradeinArray['watch_brand']); $tradeinArray['box_papers'] = ArrayHelper::getValue($tradeinArray, 'box_or_papers'); unset($tradeinArray['box_or_papers']); $tradeinArray['info_newitem_customer_wants'] = ArrayHelper::getValue($tradeinArray, 'information'); unset($tradeinArray['information']); $tradeinArray['purchase_date'] = \DateTime::createFromFormat('Y-m-d H:i:s', $tradeinArray['purchase_date'])->format('Y-m-d'); // Quick and dirty image format conversion $tradeinArray['image5'] = ArrayHelper::getValue($tradeinArray, 'image4'); $tradeinArray['image4'] = ArrayHelper::getValue($tradeinArray, 'image3'); $tradeinArray['image3'] = ArrayHelper::getValue($tradeinArray, 'image2'); $tradeinArray['image2'] = ArrayHelper::getValue($tradeinArray, 'image1'); $tradeinArray['image1'] = ArrayHelper::getValue($tradeinArray, 'image0'); //criar imported_at e colocar como default now() e deixar o creation_time como importado, e nao permitir editalo na ui // Create Active Record instance $model = new Tradein(); $model->load($tradeinArray,''); // Sets id manually $model->id = $tradeinArray['id']; $tradeins[] = $model; } $response = new TradeinFormInfoPaginatedResponse($tradeins); return $response; } }<file_sep>/tests/codeception/frontend/_support/EditableStepsTrait.php <?php namespace tests\codeception\frontend; trait EditableStepsTrait { protected $optConfig = [ 'modelName'=>'', 'order'=>null, 'fieldSuffix'=>null ]; public function amDealingWithModel($model) { $this->optConfig['modelName'] = $model; } public function amDealingWithAGrid() { $this->optConfig['order'] = 0; } public function amNotDealingWithAGrid() { $this->optConfig['order'] = null; } public function submitEditableDateField($field, $value, $opt = []) { $this->editEditableField($field, $value, array_merge(['fieldSuffix' => 'disp'], $opt)); $this->click('body'); $this->wait(1); $this->clickEditableSubmit($field); } public function submitEditableDropDownField($field, $value, $opt=[]) { $this->clickInEditableButton($field, $opt); $this->wait(2); extract(array_merge($this->optConfig, $opt)); $sel = '#' . $modelName . '-' . ($this->_chk($order) ? $order . '-' : '') . $field; $this->selectOption($sel, $value); $this->clickEditableSubmit($field); } public function submitEditableField($field, $value, $opt=[]) { $this->editEditableField($field, $value, $opt); $this->clickEditableSubmit($field); } public function editEditableField($field, $value, $opt=[]) { $this->clickInEditableButton($field, $opt); $this->wait(2); $this->fillEditableField($field, $value, $opt); $this->wait(1); } public function seeEditableFieldUpdatedTheUi($value, $fieldName=null,$opt=[]) { if($fieldName){ extract(array_merge($this->optConfig, $opt)); $sel = '#' . $modelName . '-' . ($this->_chk($order) ? $order . '-' : '') . $fieldName . '-targ'; }else{ $sel = 'button'; } $this->waitForText($value, 5, $sel); } public function seeEditableFieldUpdatedTheDatabase($model, $attr, $value) { $model->refresh(); $this->assertEquals($model->$attr, $value); } public function clickInEditableButton($fieldName,$opt=[]) { extract(array_merge($this->optConfig, $opt)); $id = '#' . $modelName . '-' . ($this->_chk($order) ? $order . '-' : '') . $fieldName; $this->scrollTo(['css' => $id . '-targ'], null, -200); $this->wait(1); $this->click($id . '-targ'); } public function fillEditableField($fieldName, $value, $opt=[]) { extract(array_merge($this->optConfig, $opt)); $fieldId = '#'.$modelName.'-'. ( $this->_chk($order) ? $order.'-' : '') . $fieldName . ($fieldSuffix ? '-'.$fieldSuffix : ''); $this->fillField($fieldId, $value); if($fieldSuffix == 'disp') $fieldId = substr($fieldId, 0, -5); $this->executeJs(sprintf('$("%s").val("%s");', $fieldId, $value)); } public function clickEditableSubmit($fieldName, $opt=[]) { extract(array_merge($this->optConfig, $opt)); $id = '#' . $modelName . '-' . ($this->_chk($order) ? $order . '-' : '') . $fieldName; $this->scrollTo(['css' => $id . '-cont'], null, -200); $this->wait(1); $this->click($id.'-cont .kv-editable-submit'); } public function seeValidationError($fieldName, $opt=[]) { extract(array_merge($this->optConfig, $opt)); $this->waitForElement('#' . $modelName . '-' . ($this->_chk($order) ? $order . '-' : '') . $fieldName . '-cont .has-error', 5); } public function makeIdSelector($modelName=nul, $order=null) { $id = '#'.$modelName ? $modelName : $this->optConfigConfig['modelName']; $id = $id.'-'; } public function clickOnExpandableTradein($tradein) { $tr = 'tr[data-key="' . $tradein->id . '"]'; $this->scrollTo(['css' => $tr]); $this->wait(1); $this->click($tr); $this->wait(1); $this->optConfig['order'] = $this->grabAttributeFrom('.kv-expand-detail-row','data-index'); } public function seeRowIsUpdated($field, $value, $opt=[]) { extract(array_merge($this->optConfig, $opt)); $this->see($value, '#td-' . $modelName . '-' . ($this->_chk($order) ? $order . '-' : '') . $field . ''); } public function _configEditable($opt) { $this->optConfig = array_merge($this->optConfig, $opt); } public function getConfig($key=null) { return $key ? $this->optConfig[$key] : $this->optConfig; } public function _chk($val) { return $val !== null && $val !== ''; } }<file_sep>/common/api/requests/TradeinFormInfoPaginatedRequest.php <?php namespace common\api\requests; use Phpro\SoapClient\Type\RequestInterface; class TradeinFormInfoPaginatedRequest implements RequestInterface{ /** * @var \SoapParam */ public $sessionId; /** * @var \SoapParam */ public $startingTradeinFormId; /** * @var \SoapParam */ public $endingTradeinFormId; /** * @var \SoapParam */ public $pageSize; /** * @var \SoapParam */ public $pageNumber; public function __construct($sessionId, $startingTradeinForm, $endingTradeinFormId, $pageSize, $pageNumber) { $this->sessionId = new \SoapParam($sessionId, 'sessionId'); $this->startingTradeinFormId = new \SoapParam($startingTradeinForm, 'startingTradeinFormId'); $this->endingTradeinFormId = new \SoapParam($endingTradeinFormId, 'endingTradeinFormId'); $this->pageSize = new \SoapParam($pageSize, 'pageSize'); $this->pageNumber = new \SoapParam($pageNumber, 'pageNumber'); } /** * @param \SoapParam $startingTradeinFormId */ public function setStartingTradeinFormId($startingTradeinFormId) { $this->startingTradeinFormId = new \SoapParam($startingTradeinFormId, 'startingTradeinFormId'); } }<file_sep>/common/config/main.php <?php use common\api\clients\JomaShopClient; use common\api\components\SoapComponent; use common\models\Tradein; return [ 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'soap' => [ 'class' => SoapComponent::class, 'clients' => [ [ 'clientName' => JomaShopClient::class, 'wsdl' => null, 'options' => [ 'cache_wsdl' => WSDL_CACHE_NONE, 'trace' => 1, 'stream_context' => stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]]), 'location' => YII_ENV_PROD ? 'https://jomashop.com/index.php/api/v2_soap' : 'https://tatooine.jomashop.com/index.php/api/v2_soap', 'uri' => 'urn:Mage_Api_Model_Server_V2_HandlerAction' ], 'classMaps' => [['Tradein', Tradein::class]] ] ] ], ], ]; <file_sep>/common/models/UserPassword.php <?php namespace common\models; use yii\base\Model; class UserPassword extends User{ public $password; public $password_repeat; /** * @inheritdoc */ public function rules() { return [ ['password', 'required'], ['password', 'compare'], ['password', 'string'], ['password_repeat', 'safe'] ]; } public function savePassword() { $this->setPassword($this->password); $this->removePasswordResetToken(); return $this->save(false); } }<file_sep>/tests/codeception/frontend/acceptance/EditAGridTradeinCept.php <?php /* @var $scenario Codeception\Scenario */ $I = new tests\codeception\frontend\Step\Acceptance\OperatorSteps($scenario); $I->wantTo('edit a tradein'); $tradein = $I->haveATradein(); $newFirstContactDate = '10-10-2017'; $newLastContactDate = '10-10-2017'; $I->amInTradeinsListPage(); $I->amDealingWithModel('tradein'); $I->clickOnExpandableTradein($tradein); $I->seeImages([$tradein->image1, $tradein->image2, $tradein->image3, $tradein->image4, $tradein->image5] ); $I->deleteImage('image1'); $I->wait(5); $I->dontSeeImages([$tradein->image1]); $I->seeEditableFieldUpdatedTheDatabase($tradein, 'image1', null); $I->amInTradeinsListPage(); $I->amDealingWithModel('tradein'); $I->clickOnExpandableTradein($tradein); $fields = ['first_contact', 'last_contact']; foreach ($fields as $field) { $I->submitEditableDateField($field, $newFirstContactDate);{} $I->seeEditableFieldUpdatedTheUi($newFirstContactDate, $field); $I->seeEditableFieldUpdatedTheDatabase($tradein, $field, \DateTime::createFromFormat('m-d-Y', $newFirstContactDate)->format('Y-m-d')); $I->seeRowIsUpdated($field, $newFirstContactDate); } $I->amInTradeinsListPage(); $I->clickOnExpandableTradein($tradein); $I->submitEditableDropDownField('customeritem_if_new', 'NO'); $I->wait(3); $I->seeEditableFieldUpdatedTheUi('NO', 'customeritem_if_new'); $I->seeEditableFieldUpdatedTheDatabase($tradein, 'customeritem_if_new', 0); $I->amInTradeinsListPage(); $I->amDealingWithModel('tradein'); $I->clickOnExpandableTradein($tradein); $fields = ['first_name','last_name','model','model_number','customeritem_retail_value','customeritem_vendor_offer','customeritem_jomashop_offer','box_papers', 'purchased_from' , 'condition','info_newitem_customer_wants','newitem_cost','newitem_jomashop_currentprice','outofpocket_price']; $newTradein = $I->imagineATradein(); foreach($fields as $field) { $newFieldValue = $newTradein->$field; try { $I->submitEditableField($field, $newFieldValue); } catch (Exception $e) { $I->pauseExecution(); } $I->wait(3); $I->seeEditableFieldUpdatedTheUi($newFieldValue, $field); $I->seeEditableFieldUpdatedTheDatabase($tradein, $field, $newFieldValue); } $I->seeRowIsUpdated('first_name', $tradein->first_name); $I->seeRowIsUpdated('last_name', $tradein->last_name); $I->seeRowIsUpdated('model_number', $tradein->model_number);<file_sep>/tests/codeception/frontend/_support/Step/Acceptance/OperatorSteps.php <?php namespace tests\codeception\frontend\Step\Acceptance; use common\models\Tradein; use tests\codeception\frontend\EditableStepsTrait; use tests\codeception\frontend\FactoryMuffinTrait; class OperatorSteps extends \tests\codeception\frontend\AcceptanceTester { use EditableStepsTrait, FactoryMuffinTrait; public $baseURL = 'frontend/web/index-test.php?r='; public function amInTradeinsListPage() { $this->amOnPage('tradein'); $this->amDealingWithAGrid(); $this->amDealingWithModel('tradein'); } public function haveAListOfTradeins($qty) { $tradeins = []; foreach (range(1, $qty) as $i) { $tradeins[] = $this->haveATradein(); } return $tradeins; // return array_map([$this, 'haveATradein'], range(1, $qty)); } public function haveATradein($attr = []) { return $this->fm()->create(Tradein::class, $attr); } public function seeNextPageButton() { $this->seeElement('li.next'); } public function seeTradeins($tradeins) { array_map([$this, 'seeTradein'], $tradeins); } public function dontSeeTradeins($tradeins) { array_map([$this, 'dontSeeTradein'], $tradeins); } public function seeTradein($tradein) { $this->seeTradeinAttr($tradein->first_name, 'td'); $this->seeTradeinAttr($tradein->last_name, 'td'); } public function dontSeeTradein($tradein) { $this->dontSee($tradein->first_name, 'td'); $this->dontSee($tradein->last_name, 'td'); } public function seeTradeinAttr($value, $el = null) { $this->see($value, $el); } public function searchTradeinsByDate($field, $value) { $idInputHidden = sprintf('#%ssearch-%s', 'tradein', $field); $idInputText = $idInputHidden . '-disp'; $this->fillField($idInputText, $value); $this->executeJs(sprintf('$("%s").val("%s");', $idInputHidden, $value)); $this->executeJS(sprintf('$("%s").change();', $idInputText)); $this->wait(5); } public function searchTradeinsBy($field, $value) { $inputName = sprintf('TradeinSearch[%s]', $field); $input = sprintf('input[name="%s"]', $inputName); $this->fillField($input, $value); $this->executeJs(sprintf('$(\'%s\').val("%s");', $input, $value)); $this->executeJS(sprintf('$(\'%s\').change();', $input)); $this->pressKey($input, \WebDriverKeys::ENTER); $this->wait(5); } public function onlySeeTradeinsWith($field, $value, $tradeins) { //Get tradeins which does not contains the value we want to see //Ie. remove tradeins that has $field=>$value $tradeinsNotSupposedToSee = array_filter(array_map(function ($tradein) use ($field, $value) { return $tradein->$field != $value ? $tradein : false; }, $tradeins)); $this->seeTradeinAttr($value, 'td'); $this->dontSeeTradeins($tradeinsNotSupposedToSee); } public function onlySeeTradeinInGrid($tradein) { $this->see($tradein->first_name, "#tradein-0-first_name-targ"); $this->see($tradein->last_name, "#tradein-0-last_name-targ"); $this->see(\DateTime::createFromFormat('Y-m-d', $tradein->first_contact)->format('m-d-Y'), "#tradein-0-first_contact-targ"); $this->see(\DateTime::createFromFormat('Y-m-d', $tradein->last_contact)->format('m-d-Y'), "#tradein-0-last_contact-targ"); $this->see($tradein->model_number, "#tradein-0-model_number-targ"); $this->dontSee("#tradein-1-first_name-targ"); } public function amInTradeinsDetailsPage($id) { $this->amOnPage('tradein/view&id=' . $id); $this->amNotDealingWithAGrid(); $this->amDealingWithModel('tradein'); } public function seeAllInfoAboutTheTradein($tradein) { $this->see($tradein->first_name); $this->see($tradein->last_name); $this->see($tradein->model_number); $this->see($tradein->brand); } public function imagineATradein($attr = []) { return $this->fm()->instance(Tradein::class, $attr); } public function amOnTradeinEditPage($tradeinId) { $this->amOnPage('tradein/update&id=' . $tradeinId); } public function fillTradeinForm($newTradein) { $this->fillField('Tradein[first_name]', $newTradein->first_name); $this->fillField('Tradein[last_name]', $newTradein->last_name); $this->fillField('Tradein[model]', $newTradein->model); $this->fillField('Tradein[brand]', $newTradein->brand); } public function submitTradeinForm() { $this->click('Update'); } public function amOnPage($url) { return parent::amOnPage($this->baseURL . $url); } public function getModelDefinitions() { return [Tradein::class]; } public function seeImages($images) { foreach ($images as $image) { $this->seeElement('//img[@src="' . $image . '"]'); } } public function dontSeeImages($images) { foreach ($images as $image) { $this->dontSeeElement('img[src="' . $image . '"]'); } } public function deleteImage($image) { $sel = 'button[data-key="' . $image . '"]'; $this->scrollTo($sel, null, -200); $this->click($sel); } }
134db30382729d85b64f4a95efc5b18a27226565
[ "PHP" ]
41
PHP
davibennun/tradeinsManagmentYiiApp
fa8dc6b15046eb5e9daf51b5ffc76719e1c182a7
4fb0617e841f7bf6b17a92f1189f253a2cce0cb2
refs/heads/master
<file_sep>package br.com.secoti.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static SessionFactory factory; private static ServiceRegistry serviceRegistry; static { //factory = new AnnotationConfiguration().configure().buildSessionFactory(); Configuration cfg = new Configuration(); cfg.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); factory = cfg.buildSessionFactory(serviceRegistry); } public static Session getSession() throws HibernateException { return factory.openSession(); } }<file_sep>Hactiverecord ============= A activerecord patterns implementations for java with hibernate Using Hibernate version 4.2.6 to develop and use.<file_sep>package br.com.secoti.models; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name="lancamentos") @SequenceGenerator(name="idLancamento", sequenceName="lancamentos_id_seq",allocationSize=1,initialValue=1) public class Lancamento implements Serializable{ private static final long serialVersionUID = 1L; /* attributes */ @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="idLancamento") private Long id; private Double valor; private Date data; @ManyToOne @JoinColumn(name="conta_id") private Conta conta; /* getters and setters */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public Conta getConta() { return conta; } public void setConta(Conta conta) { this.conta = conta; } }
24d063423c0b08c797d4dd8b8ca7fb882e568812
[ "Markdown", "Java" ]
3
Java
sidriao/Hactiverecord
6497b57a79c56864413493c08fabeda2769af6b9
fd63eb2b950c5ba34b13d341ddcbe25ac326af90
refs/heads/master
<repo_name>manfredcml/Classical-stock-analytics<file_sep>/README.md # Classical methodology of stock returns analytics: An empirical study of a dually listed company ### Introduction The stock market activities in Hong Kong are active on trading days throughout a year. According to the Hong Kong Stock Exchange (HKSE), the average daily turnover for the first quarter of 2017 is as high as HKD 74.3 billion in the securities market and there are around 2,000 companies listed on HKSE, either on the Main Board or Growth Enterprise Market (GEM), as at the end of March 2017. Among the 2,000 companies, a number of them are the so-called “H-share companies”, which refer to companies incorporated in the mainland of China but allowed to list on HKSE and the letter “H” in the phrase “H-share” stands for Hong Kong. With reference to HKSE, the first batch of state enterprises was given approval of listing in Hong Kong 15 years ago in 1992. Since then, more and more companies incoporated in the mainland of China have listed on HKSE by issuing H-shares. As at April 2017, there are 243 H-share companies as reported by HKSE. Like the norm of stocks, H-shares are traded in terms of Hong Kong dollars despite the fact that they are jointly governed by the Chinese law, regulatory requirements of the Securities and Futures Ordinance (SFO) and the Listing Rules of HKSE. Apart from H-shares, there is also a type of shares known as “A-shares”, which refer to the stocks listed in the mainland of China and traded on either the Shanghai Stock Exchange (SSE) or the Shenzhen Stock Exchange. A company incorporated in the mainland of China can issue both H-shares and A-shares, in which case that firm is said to be dually listed in Hong Kong and the mainland. Examples include but not limited to Bank of China, Tsingtao Brewery and Petrochina. A natural question that follows is, for those dually listed companies, whether there are any differences in behaviours of returns on their A-shares and H-shares. One notable observation is the price differences between the 2 types of shares. The Hang Seng China AH Premium Index (HSAHP) captures the average price ratio of A-shares to H-shares for a portfolio of dually listed companies and over the past few years HSAHP has indicated that A-shares have higher prices than H-shares in general. The aforementioned information about H-shares and A-shares provides background for my elaboration of the major objective of this article: is it more profitable, in terms of average daily returns, to trade either the A-share or H-share than trading its respective counterpart issued by the same company due to their varying characteristics with the use of some kinds of trading rules? According to Efficient Market Hypothesis (EMH), if a market is at least weakly efficient, then the stock prices should reflect all the historical information, implying that utilizing past stock prices for analysis will not give you an edge in trading. In light of the EMH, another fundamental question to be addressed by this article is whether it is possible to gain statistically significant profits from either A-shares or H-shares based on certain trading rules, or in other words, whether the market is efficient. ## Methodology and findings Please refer to my blog article for details: [Predictability of stock returns: An empirical study of a dually listed company](https://manfredcml.blog/2017/04/26/predictability-of-stock-returnsan-empirical-study-of-a-dually-listed-company/) <file_sep>/R Script/main.R library(ggplot2) library(nlme) library(moments) #User needs to change this path!!! working_path <- 'SET THE PATH HERE!!!' setwd(working_path) #------------------------------------------------------------ #a) Load the data #------------------------------------------------------------ stock.a.df <- read.csv('Data/Stock Price/Yanzhou Coal A Share.csv') stock.h.df <- read.csv('Data/Stock Price/Yanzhou Coal H Share.csv') stock.a.df$Date <- as.Date(stock.a.df$Date,"%d/%m/%Y") stock.h.df$Date <- as.Date(stock.h.df$Date,"%d/%m/%Y") first.date.a <- stock.a.df$Date[1] first.date.h <- stock.h.df$Date[1] #------------------------------------------------------------ #b) Sychronize the period #------------------------------------------------------------ if (first.date.a > first.date.h){ stock.h.df <- stock.h.df[stock.h.df$Date >= first.date.a, ] } else{ stock.a.df <- stock.a.df[stock.a.df$Date >= first.date.h, ] } #------------------------------------------------------------ #c) Create log price and log daily return #------------------------------------------------------------ stock.a.df$Log.Close <- log(stock.a.df$Close) stock.h.df$Log.Close <- log(stock.h.df$Close) nobs.stock.a <- nrow(stock.a.df) nobs.stock.h <- nrow(stock.h.df) stock.a.df$Log.Return <- 0 stock.h.df$Log.Return <- 0 stock.a.df$Log.10day.Return <- 0 stock.h.df$Log.10day.Return <- 0 #Daily log return for (i in 1:(nobs.stock.a-1)) { stock.a.df$Log.Return[1+i] <- stock.a.df$Log.Close[1+i] - stock.a.df$Log.Close[i] } for (i in 1:(nobs.stock.h-1)) { stock.h.df$Log.Return[1+i] <- stock.h.df$Log.Close[1+i] - stock.h.df$Log.Close[i] } #Delete the first observation since return is undefined stock.a.df <- stock.a.df[-1,] stock.h.df <- stock.h.df[-1,] nobs.stock.a <- nobs.stock.a - 1 nobs.stock.h <- nobs.stock.h - 1 #------------------------------------------------------------ #d) Trading Rule: VMA #------------------------------------------------------------ vma.para <- read.csv('Data/VMA Choice.csv') n.vma.para <- nrow(vma.para) vma.result.a <- matrix(nrow = n.vma.para, ncol = 15) vma.result.h <- matrix(nrow = n.vma.para, ncol = 15) colnames(vma.result.a) <- c('Short term','Long term','Band','NBuy', 'NSell', 'Buy return','Sell return', 'Positive buy return','Positive sell return','Net return', 'Buy return t stat', 'Sell return t stat','Net return t stat', 'Buy sd', 'Sell sd') colnames(vma.result.h) <- c('Short term','Long term','Band','NBuy', 'NSell','Buy return','Sell return', 'Positive buy return','Positive sell return','Net return', 'Buy return t stat', 'Sell return t stat','Net return t stat', 'Buy sd', 'Sell sd') for (k in 1:2){ if (k==1){ nobs.stock <- nobs.stock.a #A share stock.df <- stock.a.df vma.result <- vma.result.a } else{ nobs.stock <- nobs.stock.h #H share stock.df <- stock.h.df vma.result <- vma.result.h } #For plotting graph long.term.MA.graph <- 0 price.graph <- 0 buy.graph <- 0 sell.graph <- 0 date.graph <- vector() date.graph <- as.Date(date.graph) for (i in 1:n.vma.para){ short.term <- vma.para$Short.Term[i] long.term <- vma.para$Long.Term[i] threshold <- vma.para$Threshold[i] stock.df$Signal <- 'No action' n.buy <- 0 n.buy.positive <- 0 buy.return <- 0 buy.return.vec <- 0 n.sell <- 0 n.sell.positive <- 0 sell.return <- 0 sell.return.vec <- 0 for (j in 1:(nobs.stock-long.term)){ n.total <- nobs.stock - long.term sample.var <- var(stock.df$Log.Return[long.term:(nobs.stock-1)]) sample.mean <- sum(stock.df$Log.Return[long.term:(nobs.stock-1)])/n.total short.term.MA <- mean(stock.df$Close[(j + long.term - short.term):(j + long.term - 1)]) long.term.MA <- mean(stock.df$Close[j:(j + long.term - 1)]) #for plot graph (first set of para only) if (i==1){ long.term.MA.graph <- c(long.term.MA.graph, long.term.MA) price.graph <- c(price.graph, stock.df$Close[j+long.term-1]) date.graph <- c(date.graph, stock.df$Date[j+long.term-1]) } if (short.term.MA > (1+threshold)*long.term.MA){ stock.df$Signal[j + long.term - 1] <- 'Buy' n.buy <- n.buy + 1 buy.return <- buy.return + stock.df$Log.Return[j+long.term] buy.return.vec <- c(buy.return.vec,stock.df$Log.Return[j+long.term]) n.buy.positive <- n.buy.positive + 1*(stock.df$Log.Return[j+long.term]>0) buy.graph <- c(buy.graph, stock.df$Close[j+long.term-1]) sell.graph <- c(sell.graph, NA) } else if (short.term.MA <= (1-threshold)*long.term.MA){ stock.df$Signal[j + long.term - 1] <- 'Sell' n.sell <- n.sell + 1 sell.return <- sell.return + stock.df$Log.Return[j+long.term] sell.return.vec <- c(sell.return.vec, stock.df$Log.Return[j+long.term]) n.sell.positive <- n.sell.positive + 1*(stock.df$Log.Return[j+long.term]>0) sell.graph <- c(sell.graph, stock.df$Close[j+long.term-1]) buy.graph <- c(buy.graph, NA) } else { buy.graph <- c(buy.graph, NA) sell.graph <- c(sell.graph, NA) } } buy.return.vec <- buy.return.vec[-1] sell.return.vec <- sell.return.vec[-1] vma.result[i,1] <- short.term vma.result[i,2] <- long.term vma.result[i,3] <- threshold vma.result[i,4] <- n.buy vma.result[i,5] <- n.sell vma.result[i,6] <- buy.return/n.buy vma.result[i,7] <- sell.return/n.sell vma.result[i,8] <- n.buy.positive/n.buy vma.result[i,9] <- n.sell.positive/n.sell vma.result[i,10] <- buy.return/n.buy - sell.return/n.sell vma.result[i,11] <- (buy.return/n.buy - sample.mean) / sqrt(sample.var*(1/n.total+1/n.buy)) vma.result[i,12] <- (sell.return/n.sell - sample.mean) / sqrt(sample.var*(1/n.total+1/n.sell)) vma.result[i,13] <- (buy.return/n.buy - sell.return/n.sell) / sqrt(sample.var*(1/n.buy+1/n.sell)) vma.result[i,14] <- sqrt(var(buy.return.vec)) vma.result[i,15] <- sqrt(var(sell.return.vec)) if(i==1){ #Create graph and export here long.term.MA.graph <- long.term.MA.graph[-1] price.graph <- price.graph[-1] buy.graph <- buy.graph[-1] sell.graph <- sell.graph[-1] graph.df <- data.frame(date.graph, price.graph, long.term.MA.graph, buy.graph, sell.graph) colnames(graph.df) <- c('Date', 'Price', 'Long.term.MA', 'Buy.point', 'Sell.point') graph.df$Buy.point <- as.numeric(graph.df$Buy.point) graph.df$Sell.point <- as.numeric(graph.df$Sell.point) graph.df <- graph.df[graph.df$Date >= '2010-01-01' & graph.df$Date <= '2011-12-31',] ts.illustration <- ggplot(data = graph.df, aes(Date, group = 1))+ geom_line(aes(y=Price, color = 'Closing price'), size = 0.5) + geom_line(aes(y=Long.term.MA, color = 'Long-term MA'), size = 1, linetype = 'dashed') + geom_point(aes(y=Buy.point, color = 'Buy signal'),size = 2,shape = 1,alpha=1) + geom_point(aes(y=Sell.point, color = 'Sell signal'), size = 2,shape = 4,alpha=1) + xlab('Date') + ylab('Price per share (HKD)') + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position="none")+ scale_color_manual(values=c("blue","black","darkgreen","red")) if (k==1){ ggsave('R Output/VMA Illustration (A Share).png', plot = ts.illustration, width = 10) } else{ ggsave('R Output/VMA Illustration (H Share).png', plot = ts.illustration, width = 10) } } } if (k==1){ vma.result.a <- vma.result } else{ vma.result.h <- vma.result } } vma.result.a.raw <- vma.result.a vma.result.h.raw <- vma.result.h #------------------------------------------------------------ #e) Trading Rule: FMA #------------------------------------------------------------ fma.para <- read.csv('Data/FMA Choice.csv') fma.fixed.length <- 10 n.fma.para <- nrow(fma.para) fma.result.a <- matrix(nrow = n.fma.para, ncol = 15) fma.result.h <- matrix(nrow = n.fma.para, ncol = 15) colnames(fma.result.a) <- c('Short term','Long term','Band','NBuy', 'NSell', 'Buy return','Sell return', 'Positive buy return','Positive sell return','Net return', 'Buy return t stat', 'Sell return t stat','Net return t stat', 'Buy sd', 'Sell sd') colnames(fma.result.h) <- c('Short term','Long term','Band','NBuy', 'NSell','Buy return','Sell return', 'Positive buy return','Positive sell return','Net return', 'Buy return t stat', 'Sell return t stat','Net return t stat', 'Buy sd', 'Sell sd') for (k in 1:2){ if (k==1){ nobs.stock <- nobs.stock.a #A share stock.df <- stock.a.df fma.result <- fma.result.a } else{ nobs.stock <- nobs.stock.h #H share stock.df <- stock.h.df fma.result <- fma.result.h } #For plotting graph long.term.MA.graph <- 0 price.graph <- 0 buy.graph <- 0 sell.graph <- 0 date.graph <- vector() date.graph <- as.Date(date.graph) for (i in 1:n.vma.para){ short.term <- fma.para$Short.Term[i] long.term <- fma.para$Long.Term[i] threshold <- fma.para$Threshold[i] stock.df$Signal <- 'No action' n.buy <- 0 n.buy.positive <- 0 buy.return <- 0 buy.return.vec <- 0 n.sell <- 0 n.sell.positive <- 0 sell.return <- 0 sell.return.vec <- 0 timer <- fma.fixed.length + 1 for (j in 1:(nobs.stock - long.term + 1 - fma.fixed.length)){ n.total <- nobs.stock - long.term + 1 - fma.fixed.length sample.var <- var(stock.df$Log.Return[long.term:(nobs.stock-fma.fixed.length)]) sample.mean <- sum(stock.df$Log.Return[long.term:(nobs.stock-fma.fixed.length)])/n.total short.term.MA <- mean(stock.df$Close[(j + long.term - short.term):(j + long.term - 1)]) long.term.MA <- mean(stock.df$Close[j:(j + long.term - 1)]) #for plot graph (first set of para only) if (i==1){ long.term.MA.graph <- c(long.term.MA.graph, long.term.MA) price.graph <- c(price.graph, stock.df$Close[j+long.term-1]) date.graph <- c(date.graph, stock.df$Date[j+long.term-1]) } if (timer > fma.fixed.length & short.term.MA > (1+threshold)*long.term.MA){ stock.df$Signal[j + long.term - 1] <- 'Buy' n.buy <- n.buy + 1 buy.return <- buy.return + stock.df$Log.Close[j+long.term+fma.fixed.length-1] - stock.df$Log.Close[j+long.term-1] buy.return.vec <- c(buy.return.vec, stock.df$Log.Close[j+long.term+fma.fixed.length-1] - stock.df$Log.Close[j+long.term-1]) n.buy.positive <- n.buy.positive + 1*(stock.df$Log.Close[j+long.term+fma.fixed.length-1] - stock.df$Log.Close[j+long.term-1]>0) timer <- 0 buy.graph <- c(buy.graph, stock.df$Close[j+long.term-1]) sell.graph <- c(sell.graph, NA) } else if (timer > fma.fixed.length & short.term.MA <= (1-threshold)*long.term.MA){ stock.df$Signal[j + long.term - 1] <- 'Sell' n.sell <- n.sell + 1 sell.return <- sell.return + stock.df$Log.Close[j+long.term+fma.fixed.length-1] - stock.df$Log.Close[j+long.term-1] sell.return.vec <- c(sell.return.vec, stock.df$Log.Close[j+long.term+fma.fixed.length-1] - stock.df$Log.Close[j+long.term-1]) n.sell.positive <- n.sell.positive + 1*(stock.df$Log.Close[j+long.term+fma.fixed.length-1] - stock.df$Log.Close[j+long.term-1]>0) timer <- 0 sell.graph <- c(sell.graph, stock.df$Close[j+long.term-1]) buy.graph <- c(buy.graph, NA) } else { buy.graph <- c(buy.graph, NA) sell.graph <- c(sell.graph, NA) } timer <- timer + 1 } buy.return.vec <- buy.return.vec[-1] sell.return.vec <- sell.return.vec[-1] fma.result[i,1] <- short.term fma.result[i,2] <- long.term fma.result[i,3] <- threshold fma.result[i,4] <- n.buy fma.result[i,5] <- n.sell fma.result[i,6] <- buy.return/n.buy fma.result[i,7] <- sell.return/n.sell fma.result[i,8] <- n.buy.positive/n.buy fma.result[i,9] <- n.sell.positive/n.sell fma.result[i,10] <- buy.return/n.buy - sell.return/n.sell fma.result[i,11] <- (buy.return/n.buy/fma.fixed.length - sample.mean) / sqrt(sample.var*(1/n.total+1/n.buy/fma.fixed.length)) fma.result[i,12] <- (sell.return/n.sell/fma.fixed.length - sample.mean) / sqrt(sample.var*(1/n.total+1/n.sell/fma.fixed.length)) fma.result[i,13] <- (buy.return/n.buy/fma.fixed.length - sell.return/n.sell/fma.fixed.length) / sqrt(sample.var*(1/n.buy/fma.fixed.length+1/n.sell/fma.fixed.length)) fma.result[i,14] <- sqrt(var(buy.return.vec)) fma.result[i,15] <- sqrt(var(sell.return.vec)) if(i==1){ #Create graph and export here long.term.MA.graph <- long.term.MA.graph[-1] price.graph <- price.graph[-1] buy.graph <- buy.graph[-1] sell.graph <- sell.graph[-1] graph.df <- data.frame(date.graph, price.graph, long.term.MA.graph, buy.graph, sell.graph) colnames(graph.df) <- c('Date', 'Price', 'Long.term.MA', 'Buy.point', 'Sell.point') graph.df$Buy.point <- as.numeric(graph.df$Buy.point) graph.df$Sell.point <- as.numeric(graph.df$Sell.point) graph.df <- graph.df[graph.df$Date >= '2010-01-01' & graph.df$Date <= '2011-12-31',] ts.illustration <- ggplot(data = graph.df, aes(Date, group = 1))+ geom_line(aes(y=Price, color = 'Closing price'), size = 0.5) + geom_line(aes(y=Long.term.MA, color = 'Long-term MA'), size = 1, linetype = 'dashed') + geom_point(aes(y=Buy.point, color = 'Buy signal'),size = 2,shape = 1,alpha=1) + geom_point(aes(y=Sell.point, color = 'Sell signal'), size = 2,shape = 4,alpha=1) + xlab('Date') + ylab('Price per share (HKD)') + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position="none")+ scale_color_manual(values=c("blue","black","darkgreen","red")) if (k==1){ ggsave('R Output/FMA Illustration (A Share).png', plot = ts.illustration, width = 10) } else{ ggsave('R Output/FMA Illustration (H Share).png', plot = ts.illustration, width = 10) } } } if (k==1){ fma.result.a <- fma.result } else{ fma.result.h <- fma.result } } fma.result.a.raw <- fma.result.a fma.result.h.raw <- fma.result.h #------------------------------------------------------------ #f) Trading Rule: Trading range break-out #------------------------------------------------------------ bma.para <- read.csv('Data/BMA Choice.csv') n.bma.para <- nrow(bma.para) bma.result.a <- matrix(nrow = n.bma.para, ncol = 15) bma.result.h <- matrix(nrow = n.bma.para, ncol = 15) colnames(bma.result.a) <- c('Short term','Long term','Band','NBuy', 'NSell', 'Buy return','Sell return', 'Positive buy return','Positive sell return','Net return', 'Buy return t stat', 'Sell return t stat','Net return t stat', 'Buy sd', 'Sell sd') colnames(bma.result.h) <- c('Short term','Long term','Band','NBuy', 'NSell','Buy return','Sell return', 'Positive buy return','Positive sell return','Net return', 'Buy return t stat', 'Sell return t stat','Net return t stat', 'Buy sd', 'Sell sd') for (k in 1:2){ if (k==1){ nobs.stock <- nobs.stock.a #A share stock.df <- stock.a.df bma.result <- bma.result.a } else{ nobs.stock <- nobs.stock.h #H share stock.df <- stock.h.df bma.result <- bma.result.h } #For plotting graph long.term.max.graph <- 0 long.term.min.graph <- 0 price.graph <- 0 buy.graph <- 0 sell.graph <- 0 date.graph <- vector() date.graph <- as.Date(date.graph) for (i in 1:n.bma.para){ short.term <- bma.para$Short.Term[i] long.term <- bma.para$Long.Term[i] threshold <- bma.para$Threshold[i] stock.df$Signal <- 'No action' n.buy <- 0 n.buy.positive <- 0 buy.return <- 0 buy.return.vec <- 0 n.sell <- 0 n.sell.positive <- 0 sell.return <- 0 sell.return.vec <- 0 for (j in 1:(nobs.stock-long.term-1)){ n.total <- nobs.stock - long.term - 1 sample.var <- var(stock.df$Log.Return[(long.term+1):(nobs.stock-1)]) sample.mean <- sum(stock.df$Log.Return[(long.term+1):(nobs.stock-1)])/n.total short.term.MA <- mean(stock.df$Close[(j + long.term - short.term + 1):(j + long.term)]) long.term.max <- max(stock.df$Close[j:(j + long.term - 1)]) long.term.min <- min(stock.df$Close[j:(j + long.term - 1)]) #for plot graph (first set of para only) if (i==1){ long.term.max.graph <- c(long.term.max.graph, long.term.max) long.term.min.graph <- c(long.term.min.graph, long.term.min) price.graph <- c(price.graph, stock.df$Close[j+long.term]) date.graph <- c(date.graph, stock.df$Date[j+long.term]) } if (short.term.MA > (1+threshold)*long.term.max){ stock.df$Signal[j + long.term] <- 'Buy' n.buy <- n.buy + 1 buy.return <- buy.return + stock.df$Log.Return[j+long.term+1] buy.return.vec <- c(buy.return.vec,stock.df$Log.Return[j+long.term+1]) n.buy.positive <- n.buy.positive + 1*(stock.df$Log.Return[j+long.term+1]>0) buy.graph <- c(buy.graph, stock.df$Close[j+long.term]) sell.graph <- c(sell.graph, NA) } else if (short.term.MA < (1-threshold)*long.term.min){ stock.df$Signal[j + long.term] <- 'Sell' n.sell <- n.sell + 1 sell.return <- sell.return + stock.df$Log.Return[j+long.term+1] sell.return.vec <- c(sell.return.vec, stock.df$Log.Return[j+long.term+1]) n.sell.positive <- n.sell.positive + 1*(stock.df$Log.Return[j+long.term+1]>0) sell.graph <- c(sell.graph, stock.df$Close[j+long.term]) buy.graph <- c(buy.graph, NA) } else { buy.graph <- c(buy.graph, NA) sell.graph <- c(sell.graph, NA) } } buy.return.vec <- buy.return.vec[-1] sell.return.vec <- sell.return.vec[-1] bma.result[i,1] <- short.term bma.result[i,2] <- long.term bma.result[i,3] <- threshold bma.result[i,4] <- n.buy bma.result[i,5] <- n.sell bma.result[i,6] <- buy.return/n.buy bma.result[i,7] <- sell.return/n.sell bma.result[i,8] <- n.buy.positive/n.buy bma.result[i,9] <- n.sell.positive/n.sell bma.result[i,10] <- buy.return/n.buy - sell.return/n.sell bma.result[i,11] <- (buy.return/n.buy - sample.mean) / sqrt(sample.var*(1/n.total+1/n.buy)) bma.result[i,12] <- (sell.return/n.sell - sample.mean) / sqrt(sample.var*(1/n.total+1/n.sell)) bma.result[i,13] <- (buy.return/n.buy - sell.return/n.sell) / sqrt(sample.var*(1/n.buy+1/n.sell)) bma.result[i,14] <- sqrt(var(buy.return.vec)) bma.result[i,15] <- sqrt(var(sell.return.vec)) if(i==1){ #Create graph and export here long.term.max.graph <- long.term.max.graph[-1] long.term.min.graph <- long.term.min.graph[-1] price.graph <- price.graph[-1] buy.graph <- buy.graph[-1] sell.graph <- sell.graph[-1] graph.df <- data.frame(date.graph, price.graph, long.term.max.graph, long.term.min.graph,buy.graph, sell.graph) colnames(graph.df) <- c('Date', 'Price', 'Long.term.max', 'Long.term.min','Buy.point', 'Sell.point') graph.df$Buy.point <- as.numeric(graph.df$Buy.point) graph.df$Sell.point <- as.numeric(graph.df$Sell.point) graph.df <- graph.df[graph.df$Date >= '2010-01-01' & graph.df$Date <= '2011-12-31',] ts.illustration <- ggplot(data = graph.df, aes(Date, group = 1))+ geom_line(aes(y=Price, color = 'Closing price'), size = 0.5) + geom_line(aes(y=Long.term.max, color = 'Long-term Max'), size = 0.5, linetype = 'dashed') + geom_line(aes(y=Long.term.min, color = 'Long-term Min'), size = 0.5, linetype = 'dashed') + geom_point(aes(y=Buy.point, color = 'Buy signal'),size = 3,shape = 1,alpha=1) + geom_point(aes(y=Sell.point, color = 'Sell signal'), size = 3,shape = 4,alpha=1) + xlab('Date') + ylab('Price per share (HKD)') + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position="none")+ scale_color_manual(values=c("blue","black","darkgreen","darkgreen", "red")) if (k==1){ ggsave('R Output/BMA Illustration (A Share).png', plot = ts.illustration, width = 10) } else{ ggsave('R Output/BMA Illustration (H Share).png', plot = ts.illustration, width = 10) } } } if (k==1){ bma.result.a <- bma.result } else{ bma.result.h <- bma.result } } bma.result.a.raw <- bma.result.a bma.result.h.raw <- bma.result.h #------------------------------------------------------------ #g) Various plots #------------------------------------------------------------ #Time series ts.h <- ggplot(data = stock.h.df, aes(Date, Log.Return)) + geom_line() + xlab('Year') + ylab('Log return') + ggtitle('Time series of log return of Yanzhou Coal (H Share)') + theme(plot.title = element_text(hjust = 0.5)) #move chart title to center ts.a <- ggplot(data = stock.a.df, aes(Date, Log.Return)) + geom_line() + xlab('Year') + ylab('Log return') + ggtitle('Time series of log return of Yanzhou Coal (A Share)') + theme(plot.title = element_text(hjust = 0.5)) #move chart title to center box.h <- ggplot(data = stock.h.df, aes(x='Yanzhou Coal (H Share)', y=Log.Return))+ geom_boxplot() + xlab('')+ ylab('Log return') + ggtitle('Time series of log return of Yanzhou Coal (H Share)') + theme(plot.title = element_text(hjust = 0.5)) #move chart title to center box.a <- ggplot(data = stock.a.df, aes(x='Yanzhou Coal (A Share)', y=Log.Return))+ geom_boxplot() + xlab('')+ ylab('Log return') + ggtitle('Time series of log return of Yanzhou Coal (A Share)') + theme(plot.title = element_text(hjust = 0.5)) #move chart title to center ggsave('R Output/Time Series (H Share).png', plot = ts.h) ggsave('R Output/Time Series (A Share).png', plot = ts.a) ggsave('R Output/Box Plot (H Share).png', plot = box.h) ggsave('R Output/Box Plot (A Share).png', plot = box.a) #------------------------------------------------------------ #h) Calculate autocorrelation, skewness and kurtosis #------------------------------------------------------------ z.value <- c(1.645, 1.96, 2.575) acf.z.value.a <- z.value/sqrt(nobs.stock.a) acf.z.value.h <- z.value/sqrt(nobs.stock.h) acf.a <- acf(stock.a.df$Log.Return)[[1]] acf.h <- acf(stock.h.df$Log.Return)[[1]] acf.summary.a <- data.frame(acf.a, abs(acf.a) > acf.z.value.a[1],abs(acf.a) > acf.z.value.a[2], abs(acf.a) > acf.z.value.a[3]) acf.summary.h <- data.frame(acf.h, abs(acf.h) > acf.z.value.h[1],abs(acf.h) > acf.z.value.h[2], abs(acf.h) > acf.z.value.h[3]) acf.summary.name <- c('ACF', '10% test','5% test','1% test') names(acf.summary.a) <- acf.summary.name names(acf.summary.h) <- acf.summary.name write.csv(acf.summary.a, 'R Output/acf_summary_Ashare.csv') write.csv(acf.summary.h, 'R Output/acf_summary_Hshare.csv') png(paste('R Output/ACF A Share_Plot.png', sep=''), res = 80) acf(stock.a.df$Log.Return, main = 'Autocorrelation of Log Return (A Share)') dev.off() png(paste('R Output/ACF H Share_Plot.png', sep=''), res = 80) acf(stock.h.df$Log.Return, main = 'Autocorrelation of Log Return (H Share)') dev.off() skew.test.a <- agostino.test(stock.a.df$Log.Return) skew.test.h <-agostino.test(stock.h.df$Log.Return) kur.test.a <- anscombe.test(stock.a.df$Log.Return) kur.test.h <- anscombe.test(stock.h.df$Log.Return) write.csv(skew.test.a[[1]], 'R Output/Skewness (A share).csv') write.csv(skew.test.h[[1]], 'R Output/Skewness (H share).csv') write.csv(kur.test.a[[1]], 'R Output/Kurtosis (A share).csv') write.csv(kur.test.h[[1]], 'R Output/Kurtosis (H share).csv') #------------------------------------------------------------ #i) Export final results #------------------------------------------------------------ write.csv(vma.result.a.raw, 'R Output/VMA (A Share).csv') write.csv(vma.result.h.raw, 'R Output/VMA (H Share).csv') write.csv(fma.result.a.raw, 'R Output/FMA (A Share).csv') write.csv(fma.result.h.raw, 'R Output/FMA (H Share).csv') write.csv(bma.result.a.raw, 'R Output/BMA (A Share).csv') write.csv(bma.result.h.raw, 'R Output/BMA (H Share).csv')
916fcc9e5b7c50193f2c03d955313824bb05a438
[ "Markdown", "R" ]
2
Markdown
manfredcml/Classical-stock-analytics
f6375d8d92caf6f310d159c02b50d3e1c94b70eb
605ca38bc2bf8b9419ed301f274f37a7b112ca0f
refs/heads/master
<file_sep>import React from 'react'; import { ThemeProvider as SCThemeProvider } from 'styled-components'; import merge from 'lodash/merge'; import { createTheme } from '../createTheme'; const ThemeProvider = props => { const theme = merge(createTheme(props.theme), props.theme); return <SCThemeProvider theme={theme}>{props.children}</SCThemeProvider>; }; export default ThemeProvider; <file_sep>import React from 'react'; import { renderWithTheme, fireEvent, wait } from '../../test/utils'; import Dropdown from './Dropdown'; jest.mock('popper.js', () => { const PopperJS = jest.requireActual('popper.js'); return class Popper { static placements = PopperJS.placements; constructor() { return { destroy: () => {}, scheduleUpdate: () => {}, }; } }; }); describe('<Dropdown />', () => { let renderUtils; const renderDropdown = (props = {}) => { const wrapper = document.createElement('div'); wrapper.setAttribute('tabindex', 1); const utils = renderWithTheme( <Dropdown {...props} portalNode={wrapper} trigger={<div>Trigger</div>}> <Dropdown.Title>Title</Dropdown.Title> <Dropdown.Item data-testid="item-one">One</Dropdown.Item> <Dropdown.Divider data-testid="divider" /> <Dropdown.Item data-testid="item-two">Two</Dropdown.Item> </Dropdown>, { container: document.body.appendChild(wrapper), } ); return { wrapper, ...utils, }; }; const assertDropdownOpen = (utils = renderUtils) => wait(() => { expect(utils.queryByText('Title')).toBeInTheDocument(); }); const assertDropdownClosed = (utils = renderUtils) => wait(() => { expect(utils.queryByText('Title')).not.toBeInTheDocument(); }); const openDropdown = async (utils = renderUtils) => { const trigger = utils.getByText('Trigger'); fireEvent.click(trigger, { stopPropagation: () => null }); return assertDropdownOpen(utils); }; beforeEach(() => { renderUtils = renderDropdown(); }); test('only renders trigger on mount', () => { expect(renderUtils.asFragment()).toMatchSnapshot(); }); // TODO: add cases for space and enter keypress events test('opens menu with focus when trigger is clicked', async () => { await openDropdown(); expect(renderUtils.asFragment()).toMatchSnapshot(); expect(renderUtils.getByTestId('dropdown-menu') === document.activeElement).toBeTruthy(); }); test('closes when escape is pressed', async () => { await openDropdown(); fireEvent.keyDown(document.body, { key: 'Escape' }); await assertDropdownClosed(); }); test('closes when menu loses focus', async () => { await openDropdown(); // Some issues with fireEvent.focus: https://github.com/kentcdodds/react-testing-library/issues/276#issuecomment-473392827 renderUtils.wrapper.focus(); await assertDropdownClosed(); }); test('arrow keys navigate to focusable elements', async () => { await openDropdown(); const itemOne = renderUtils.getByTestId('item-one'); const itemTwo = renderUtils.getByTestId('item-two'); const isFocused = node => node === document.activeElement; // First focusable element in tree should be selected on first arrow down fireEvent.keyDown(document.body, { key: 'ArrowDown' }); expect(isFocused(itemOne)).toBeTruthy(); // Arrow up on first item should bring us to last item fireEvent.keyDown(document.body, { key: 'ArrowUp' }); expect(isFocused(itemTwo)).toBeTruthy(); fireEvent.keyDown(document.body, { key: 'ArrowUp' }); expect(isFocused(itemOne)).toBeTruthy(); }); describe('prop: width', () => { test('wdith defaults to auto', async () => { const utils = renderDropdown(); await openDropdown(utils); expect(utils.getByTestId('dropdown-menu')).toHaveStyleRule('width', 'auto'); }); test('supports string widths', async () => { const utils = renderDropdown({ width: '2rem' }); await openDropdown(utils); expect(utils.getByTestId('dropdown-menu')).toHaveStyleRule('width', '2rem'); }); test('supports number widths', async () => { const utils = renderDropdown({ width: 200 }); await openDropdown(utils); expect(utils.getByTestId('dropdown-menu')).toHaveStyleRule('width', '200px'); }); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Box from '../Box'; import { createComponent } from '../utils'; // from https://flatuicolors.com/ const defaultColors = [ '#2ecc71', // emerald '#3498db', // peter river '#8e44ad', // wisteria '#e67e22', // carrot '#e74c3c', // alizarin '#1abc9c', // turquoise '#2c3e50', // midnight blue ]; const getInitials = (name = '') => name .split(' ') .slice(0, 2) .map(w => w[0]) .join(''); const AvatarContainer = createComponent({ name: 'Avatar', as: Box, style: ({ size, borderRadius, color, backgroundColor, src, theme }) => css` height: ${size}px; width: ${size}px; border-radius: ${borderRadius}; background: ${theme.colors[backgroundColor] || backgroundColor}; color: ${color}; text-align: center; line-height: ${size}px; font-size: ${size * 0.5}px; ${src && { backgroundImage: `url(${src})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', }}; `, }); const Avatar = ({ name = '', src, backgroundColor, ...props }) => ( <AvatarContainer {...props} src={src} backgroundColor={backgroundColor || defaultColors[name.length % defaultColors.length]} aria-label={name}> {src ? null : getInitials(name)} </AvatarContainer> ); Avatar.propTypes = { /** * We'll take the first letter of the first two words to create the initials */ name: PropTypes.string, /** * The size of the Avatar */ size: PropTypes.number, /** * Border radius of the Avatar */ borderRadius: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Colors of the initials */ color: PropTypes.string, /** * Background color when initials are used */ backgroundColor: PropTypes.string, }; Avatar.defaultProps = { size: 25, borderRadius: '100%', color: 'white', }; export default Avatar; <file_sep>import React from 'react'; import { renderWithTheme } from '../../test/utils'; import Linkify from './Linkify'; describe('Linkify', () => { test('converts links to anchor tags', () => { const { asFragment } = renderWithTheme(<Linkify source="Hello! https://google.com is a cool site." />); expect(asFragment()).toMatchSnapshot(); }); test('escapes HTML entities', () => { const { asFragment } = renderWithTheme( <Linkify source={`<img src="fake.jpg" onError={() => {}} alt="hacker" /><span>heheh got hacked</span>`} /> ); expect(asFragment()).toMatchSnapshot(); }); test('can receive linkStyle', () => { const { asFragment } = renderWithTheme( <Linkify linkStyle={{ color: 'magenta' }} source="Hello! https://google.com is a cool site." /> ); expect(asFragment()).toMatchSnapshot(); }); test('can render markdown', () => { const { asFragment } = renderWithTheme(<Linkify source="[this is a link](http://google.com)" />); expect(asFragment()).toMatchSnapshot(); }); test('reformats code blocks', () => { const linkContent = "dear doctor,\n\n I'm \"5'9\" and 160'"; const { asFragment } = renderWithTheme(<Linkify source={linkContent} />); expect(asFragment()).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import Modal from './Modal'; import ModalExample from './Modal.example'; import ModalDropdownExample from './Modal.dropdownExample'; import ModalNoAutoFocusExample from './Modal.noAutoFocusEx'; export default { title: 'Components|Modal', component: Modal, }; export const Basic = () => ( <ModalExample body="I am an example modal that displays example content to prove that I can actually do some things" maxWidth={300} /> ); export const LongContent = () => ( <ModalExample body={ <div> {new Array(50).fill(null).map(key => ( <p key={key}>I&apos;m really long annoying content.</p> ))} </div> } /> ); export const DropdownTrigger = () => <ModalDropdownExample body="I'm triggered by a dropdown" />; export const NoAutoFocus = () => <ModalNoAutoFocusExample body="I'm triggered by a dropdown" />; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Flex from '../Flex'; import { createComponent } from '../utils'; const getWidthPercent = (width, columns) => `${(width / columns) * 100}%`; const getColumnWidth = (width, columns) => { if (width / columns !== 1) { return css` display: block; flex-basis: ${getWidthPercent(width, columns)}; max-width: ${getWidthPercent(width, columns)}; `; } return css` max-width: 100%; width: 100%; flex: auto; `; }; const getPadding = ({ collapse, gutter, theme }) => { if (collapse) return 0; return typeof gutter === 'number' ? gutter / 2 : theme.gridGutter / 2; }; const getOffset = (offset, columns) => css` margin-left: ${offset === 0 ? 0 : getWidthPercent(offset, columns)}; `; const StyledColumn = createComponent({ name: 'Column', as: Flex, style: ({ theme, order, ...props }) => { const mediaQueries = Object.keys(theme.breakpoints).map(breakpoint => { if (!props[breakpoint]) { return null; } if (breakpoint === 'xs') { return css` ${getColumnWidth(props[breakpoint], theme.gridColumns)}; ${props[`${breakpoint}Offset`] && getOffset(props[`${breakpoint}Offset`], theme.gridColumns)}; `; } return css` @media (min-width: ${theme.breakpoints[breakpoint]}) { ${getColumnWidth(props[breakpoint], theme.gridColumns)}; ${props[`${breakpoint}Offset`] !== undefined && getOffset(props[`${breakpoint}Offset`], theme.gridColumns)}; } `; }); return css` box-sizing: border-box; flex: 1 0 auto; flex-direction: column; padding-left: ${getPadding}px; padding-right: ${getPadding}px; ${mediaQueries}; `; }, }); const Column = props => <StyledColumn {...props} />; Column.propTypes = { /** * Margin between columns */ gutter: PropTypes.number, /** * Collapse columns by removing gutters */ collapse: PropTypes.bool, }; Column.defaultProps = { collapse: false, }; export default Column; <file_sep>import EventEmitter from 'mitt'; import { Events } from './config'; export const emitter = new EventEmitter(); const toast = (options = {}) => { if (!options.message) { throw new Error('Molekule: Toast requires a message'); } emitter.emit(Events.ADD, options); }; toast.success = (message, options = {}) => { toast({ message, type: 'success', ...options }); }; toast.error = (message, options = {}) => { toast({ message, type: 'error', ...options }); }; toast.warn = (message, options = {}) => { toast({ message, type: 'warn', ...options }); }; toast.info = (message, options = {}) => { toast({ message, type: 'info', ...options }); }; export default toast; <file_sep>import React, { useState, useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { AsYouType, isSupportedCountry, getCountryCallingCode, parseDigits } from 'libphonenumber-js/min'; import examplePhoneNumbers from 'libphonenumber-js/examples.mobile.json'; import Input from './Input'; import { createEasyInput } from './EasyInput'; import { getNextCursorPosition } from '../utils'; export const getRawMaxLength = (countryCode, value) => { const countryCallingCode = getCountryCallingCode(countryCode); const beginsWithCountryCode = parseDigits(value).substr(0, countryCallingCode.length) === countryCallingCode; const examplePhoneNumber = examplePhoneNumbers[countryCode]; return beginsWithCountryCode ? countryCallingCode.length + examplePhoneNumber.length : examplePhoneNumber.length; }; export function PhoneInput({ countryCode, forwardedRef, value: propValue, onKeyDown, onChange, ...inputProps }) { const countryCodeSupported = isSupportedCountry(countryCode); if (!countryCodeSupported) { throw new Error(`${countryCode} is not supported`); } const format = value => { const phoneString = value || ''; const parsed = parseDigits(phoneString).substr(0, getRawMaxLength(countryCode, phoneString)); return new AsYouType(countryCode).input(parsed); }; const [currentValue, setValue] = useState(format(propValue)); const inputRef = forwardedRef || useRef(); useEffect(() => { if (propValue !== currentValue) { setValue(format(propValue)); } }, [propValue]); const handleKeyDown = event => { const isLetterLike = /^\w{1}$/.test(event.key); if (isLetterLike) { const cursorPos = event.target.selectionStart; const nextFormattedValue = format( currentValue.substring(0, cursorPos) + event.key + currentValue.substring(cursorPos) ); const nextValueRawLength = parseDigits(currentValue).length + 1; if (nextValueRawLength > getRawMaxLength(countryCode, nextFormattedValue)) { event.preventDefault(); event.stopPropagation(); } } if (onKeyDown) { onKeyDown(event); } }; const handleChange = (name, newValue, event) => { const nextValue = newValue.length < currentValue.length ? newValue.trim() : format(newValue); const nextCursorPosition = getNextCursorPosition(event.target.selectionStart, currentValue, nextValue); setValue(nextValue); setTimeout(() => { inputRef.current.setSelectionRange(nextCursorPosition, nextCursorPosition); }); if (onChange) { onChange(name, nextValue, event); } }; return ( <Input type="tel" forwardedRef={inputRef} value={currentValue} onKeyDown={handleKeyDown} onChange={handleChange} {...inputProps} /> ); } PhoneInput.propTypes = { ...Input.propTypes, countryCode: PropTypes.string, }; PhoneInput.defaultProps = { countryCode: 'US', }; export default createEasyInput(PhoneInput); <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Collapse from '../Collapse'; import { createComponent } from '../utils'; import Box from '../Box'; import Icon from '../Icon'; import Flex from '../Flex'; const AccordionItemProps = { title: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), content: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), renderHeader: PropTypes.func, renderContent: PropTypes.func, }; const AccordionContainer = createComponent({ name: 'Accordion', }); const AccordionItemContainer = createComponent({ name: 'AccordionItem', }); const AccordionHeader = createComponent({ name: 'AccordionItemHeader', tag: 'header', style: css` padding: 0.75rem 1rem; cursor: pointer; `, }); const AccordionTitle = createComponent({ name: 'AccordionItemTitle', tag: 'span', style: css``, }); const AccordionIcon = createComponent({ name: 'AccordionItemIcon', as: Icon, style: ({ isOpen }) => css` transition: 175ms transform; transform: rotate(${isOpen ? 90 : 0}deg); `, }); const AccordionContent = createComponent({ name: 'AccordionItemContent', }); const AccordionItem = ({ isOpen, title, content, contentContainerStyle, renderHeader, renderContent, onToggle }) => ( <AccordionItemContainer> <Collapse isOpen={isOpen} renderTrigger={() => renderHeader ? ( renderHeader({ isOpen, title, onToggle }) ) : ( <AccordionHeader onClick={onToggle}> <Flex> <Box flex={1}> <AccordionTitle>{title}</AccordionTitle> </Box> <AccordionIcon name="chevron-right" isOpen={isOpen} /> </Flex> </AccordionHeader> ) }> {renderContent ? ( renderContent({ isOpen, content }) ) : ( <AccordionContent style={contentContainerStyle}>{content}</AccordionContent> )} </Collapse> </AccordionItemContainer> ); AccordionItem.propTypes = AccordionItemProps; export default class Accordion extends Component { static propTypes = { /** * An array of AccordionItems */ items: PropTypes.arrayOf(PropTypes.shape(AccordionItemProps)).isRequired, /** * Only one accordion cell open at a time */ solo: PropTypes.bool, /** * Style passed to content container box */ contentContainerStyle: PropTypes.shape(), }; static Item = AccordionItem; state = { openList: [], }; handleItemToggle = idx => { const { solo } = this.props; this.setState(({ openList }) => { if (openList.indexOf(idx) >= 0) { return { openList: openList.filter(i => i !== idx) }; } return { openList: solo ? [idx] : [...openList, idx], }; }); }; render() { const { items, children, contentContainerStyle } = this.props; const { openList } = this.state; return ( <AccordionContainer> {children || items.map((item, i) => ( <AccordionItem key={item.title} contentContainerStyle={contentContainerStyle} isOpen={openList.indexOf(i) >= 0} {...item} onToggle={() => this.handleItemToggle(i)} /> ))} </AccordionContainer> ); } } <file_sep>import { css } from 'styled-components'; import { createComponent } from '../utils'; const Field = createComponent({ name: 'Field', style: css` position: relative; transition: 175ms; & + & { margin-top: 1rem; } `, }); export default Field; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Transition, TransitionGroup } from 'react-transition-group'; import * as animations from 'react-animations'; import { css, keyframes } from 'styled-components'; import Portal from '../Portal'; import Flex from '../Flex'; import Box from '../Box'; import Icon from '../Icon'; import { emitter } from './toast'; import { createComponent, themeGet } from '../utils'; import { Types, Events, Positions, PositionConfigs } from './config'; const VariantToColorMap = { success: 'green', error: 'red', warn: 'orange', info: 'blue', }; const getTransitionStyle = (state, position, duration) => { const { animationIn, animationOut } = PositionConfigs[position]; switch (state) { case 'entering': return css` animation: ${duration}ms ${keyframes`${animations[animationIn]}`}; `; case 'exiting': return css` animation: ${duration}ms ${keyframes`${animations[animationOut]}`}; `; default: return css``; } }; const ToastPortal = createComponent({ name: 'ToastPortal', style: ({ position }) => PositionConfigs[position].wrapperStyle, }); const Toast = createComponent({ name: 'Toast', style: ({ state, type, position, animationDuration, theme }) => css` padding: 0.75rem 1rem; min-width: 250px; max-width: 400px; cursor: pointer; color: white; font-weight: 600; border-radius: ${theme.radius}px; box-shadow: ${theme.shadow.soft}; background: ${theme.colors[VariantToColorMap[type]]}; transition: 175ms; z-index: 5000; ${getTransitionStyle(state, position, animationDuration)}; & + & { margin-top: 0.5rem; } &:hover { box-shadow: ${theme.shadow.hard}; } `, }); /** Toast positions will default to `top-center`. To change the positioning, you can pass the `position` prop to the `<ToastContainer />` to be used as the default. You can also pass the position to each individual toast you're rendering, which will override the default.rendering. */ export default class ToastContainer extends Component { counter = 0; state = { toasts: [], }; static propTypes = { type: PropTypes.string, position: PropTypes.string, timeout: PropTypes.number, animationDuration: PropTypes.number, autoClose: PropTypes.bool, closeOnClick: PropTypes.bool, showClose: PropTypes.bool, }; static defaultProps = { type: Types.INFO, position: Positions.TOP_CENTER, timeout: 5000, animationDuration: 250, autoClose: true, closeOnClick: true, showClose: true, }; componentDidMount() { emitter.on(Events.ADD, this.add); } componentWillUnmount() { emitter.off(Events.ADD, this.add); } add = (options = {}) => { const id = ++this.counter; // eslint-disable-line const toast = { ...this.props, ...options, id, }; this.setState( state => ({ ...state, toasts: [...state.toasts, toast], }), () => { if (toast.autoClose) { setTimeout(() => { this.remove(id); }, toast.timeout + toast.animationDuration); } } ); }; remove = id => { this.setState(state => ({ toasts: state.toasts.filter(t => t.id !== id), })); }; handleToastClick = toast => { if (toast.closeOnClick) { this.remove(toast.id); } }; render() { const { toasts } = this.state; return Object.keys(Positions).map(key => { const p = Positions[key]; return ( <Portal key={p}> <ToastPortal position={p}> <TransitionGroup> {toasts .filter(t => t.position === p) .map(toast => ( <Transition key={toast.id} timeout={toast.animationDuration} appear unmountOnExit> {state => ( <Toast {...toast} state={state} onClick={() => this.handleToastClick(toast)}> <Flex alignItems="flex-start"> <Box flex={1}>{toast.message}</Box> {toast.showClose && <Icon name="close" onClick={() => this.remove(toast.id)} />} </Flex> </Toast> )} </Transition> ))} </TransitionGroup> </ToastPortal> </Portal> ); }); } } <file_sep>import React from 'react'; import Linkify from './Linkify'; export default { title: 'Components|Linkify', component: Linkify, }; export const Basic = () => { const markdownString = `Checkout http://google.com. <span onmouseover="alert('yo')">Another</span> one that's not so great is http://bing.com. You could also checkout duckduckgo.com if you're into that whole privacy thing. <img src="fake.jpg" onError={() => {}} alt="hacker" /> Oh, and you should also check out https://heydoctor.co. And this [markdown link](https://heydoctor.com)\n\n\ I used to be interpreted as a code block but I shouldn't be anymore!!! And strings can have multiple spaces inside`; return <Linkify linkStyle={{ color: 'magenta' }} source={markdownString} />; }; <file_sep>import React from 'react'; import Modal from './Modal'; import Button from '../Button'; import Input from '../Form/Input'; export default class ModalDemo extends React.Component { state = { isModalOpen: false, isModalTwoOpen: false, }; toggle = () => { this.setState({ isModalOpen: !this.state.isModalOpen, isModalTwoOpen: false }); }; toggleModalTwo = () => { this.setState({ isModalTwoOpen: !this.state.isModalTwoOpen }); }; onCancel = () => { this.toggle(); setTimeout(() => { alert('Oh no! It has been canceled.'); }, 500); }; render() { const { body, bodyTwo = 'Im a nested modal!', ...props } = this.props; return ( <div> <Button onClick={this.toggle}>Open Modal</Button> <Modal open={this.state.isModalOpen} onClose={this.toggle} title="Example Modal" {...props}> <Modal.Body> <> {body} <Input autoFocus name="password" label="<PASSWORD>" /> </> <Modal open={this.state.isModalTwoOpen} onClose={this.toggleModalTwo} title="Example Modal Two" {...props}> <Modal.Body>{bodyTwo}</Modal.Body> <Modal.Footer> <Button.Group justifyContent="space-between"> <Button variant="grey" onClick={this.toggleModalTwo}> Cancel </Button> <Button variant="success" onClick={this.toggleModalTwo}> I&apos;m Done Anyways </Button> </Button.Group> </Modal.Footer> </Modal> </Modal.Body> <Modal.Footer> <Button.Group justifyContent="space-between"> <Button variant="grey" onClick={this.onCancel}> Cancel </Button> <Button variant="success" onClick={this.toggleModalTwo}> Open Another Modal </Button> </Button.Group> </Modal.Footer> </Modal> </div> ); } } <file_sep>import React from 'react'; import { renderWithTheme, fireEvent, act } from '../../test/utils'; import DateInput, { getRawMaxLength } from './DateInput'; import ThemeProvider from '../ThemeProvider'; describe('<DateInput />', () => { const renderInput = props => { const utils = renderWithTheme(<DateInput placeholder="Input" {...props} />); return { ...utils, input: utils.getByPlaceholderText('Input'), }; }; const updateInputValue = (input, value) => { act(() => { fireEvent.change(input, { target: { value } }); }); }; test('#getMaxDateLength', () => { expect(getRawMaxLength(['m', 'd', 'Y'])).toEqual(8); expect(getRawMaxLength(['m', 'd', 'y'])).toEqual(6); }); test('snapshot', () => { const { asFragment } = renderInput(); expect(asFragment()).toMatchSnapshot(); }); test('initally sets the value', () => { const value = '12/05/1992'; const { input } = renderInput({ value }); expect(input.value).toEqual(value); }); test("prefixes month and day block with a 0 when second number isn't possible", () => { const { input } = renderInput(); updateInputValue(input, '4'); expect(input.value).toEqual('04/'); updateInputValue(input, '04/4'); expect(input.value).toEqual('04/04/'); }); test("doesn't prefix when second number is possible", () => { const { input } = renderInput(); updateInputValue(input, '1'); expect(input.value).toEqual('1'); updateInputValue(input, '12/1'); expect(input.value).toEqual('12/1'); }); test('truncates a date string that is too long', () => { const { input } = renderInput({ value: '12/05/19922222' }); expect(input.value).toEqual('12/05/1992'); }); test('can remove trailing slash when backspacing', () => { const { input } = renderInput({ value: '12/05/' }); fireEvent.keyDown(input, { key: 'Backspace' }); updateInputValue(input, '12/05'); expect(input.value).toEqual('12/05'); }); test('takes custom delimter and pattern', () => { const { input } = renderInput({ value: '2000-5', pattern: ['Y', 'm', 'd'], delimiter: '-' }); expect(input.value).toEqual('2000-05-'); }); test('updates internally when value prop changes', () => { const { input, rerender } = renderInput({ value: '01/05' }); rerender( <ThemeProvider> <DateInput placeholder="input" value="01/09/1990" /> </ThemeProvider> ); expect(input.value).toEqual('01/09/1990'); }); test('initially displays initialValue if provided', () => { const { input } = renderInput({ initialValue: '01/01/2000', value: '2000-01-01' }); expect(input.value).toEqual('01/01/2000'); }); }); <file_sep>// import original module declarations import 'styled-components'; import { ThemeColors, ThemeBreakpoints, ThemeTypography, ThemeSizes, ThemeVariants } from 'src/types'; // and extend them! declare module 'styled-components' { export interface DefaultTheme extends Theme { classPrefix: string; space: number[]; gridWidth: number; gridGutter: number; gridColumns: number; radii: number[]; radius: number; shadow: { soft: string; hard: string; }; colors: ThemeColors; breakpoints: ThemeBreakpoints; typography: ThemeTypography; sizes: ThemeSizes; variants: ThemeVariants; } } <file_sep>import React, { useState } from 'react'; import Dropdown, { PLACEMENT_TRANSITION_ORIGINS } from './Dropdown'; import Flex from '../Flex'; import RadioGroup from '../Form/RadioGroup'; import Button from '../Button'; export default { title: 'Components|Dropdown', component: Dropdown, }; function BasicExample() { const [placement, setPlacement] = useState('bottom-start'); return ( <Flex justifyContent="center"> <Flex mr={5}> <RadioGroup label={<strong>Placement</strong>} value={placement} choices={Object.keys(PLACEMENT_TRANSITION_ORIGINS).map(p => ({ value: p, label: p, }))} onChange={(_, val) => setPlacement(val)} /> </Flex> <Flex alignSelf="center"> <Dropdown placement={placement} width={250} trigger={ <Button mr={3} variant="primary"> Basic Dropdown </Button> }> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item color="red">Cancel</Dropdown.Item> </Dropdown> </Flex> </Flex> ); } export const Basic = () => <BasicExample />; export const WithTitles = () => ( <Flex> <Dropdown placement="bottom-start" width={250} trigger={<Button variant="danger">Dropdown w/Titles</Button>}> <Dropdown.Title>Section Title</Dropdown.Title> <Dropdown.Item selected closeOnClick={false}> Dropdown Item </Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Title>Section Title</Dropdown.Title> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Item>Dropdown Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item color="red">Cancel</Dropdown.Item> </Dropdown> </Flex> ); export const WithIcons = () => ( <Flex> <Dropdown placement="bottom-start" width={250} trigger={ <Button mr={3} variant="success"> Dropdown w/Icons </Button> }> <Dropdown.Item icon="account-circle">Dropdown Item</Dropdown.Item> <Dropdown.Item icon="pencil">Dropdown Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item icon="stethoscope">Dropdown Item</Dropdown.Item> <Dropdown.Item icon="bell">Dropdown Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item icon="settings">Dropdown Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item icon="trash-can" color="red"> Cancel </Dropdown.Item> </Dropdown> </Flex> ); <file_sep>import React from 'react'; import { css } from 'styled-components'; import Box from '../Box'; import { createComponent } from '../utils'; const bubbleSize = 22; const StyledOrderedList = createComponent({ name: 'OrderedList', as: 'ol', style: ({ theme }) => css` counter-reset: my-counter; list-style: none; padding: 2px; /* Provide space for bubble */ padding-left: ${bubbleSize + theme.space[2]}px; > li { counter-increment: my-counter; position: relative; margin-top: 18px; &:first-of-type { margin-top: 0; } &::before { content: counter(my-counter); font-family: ${theme.typography.headerFontFamily || 'inherit'}; position: absolute; left: ${bubbleSize * -1 - theme.space[2]}px; line-height: ${bubbleSize}px; width: ${bubbleSize}px; height: ${bubbleSize}px; top: -2px; border-radius: 50%; text-align: center; border: 1px solid ${theme.colors.grey}; } } `, }); const OrderedList = React.forwardRef((props, ref) => <StyledOrderedList {...props} ref={ref} />); OrderedList.displayName = 'OrderedList'; OrderedList.propTypes = { ...Box.propTypes, }; export default OrderedList; <file_sep>import { DefaultTheme } from 'styled-components'; import { defaultThemeColors } from './defaultThemeColors'; import { defaultBreakpoints } from './defaultBreakpoints'; import { defaultThemeSizes } from './defaultThemeSizes'; import { defaultThemeVariants } from './defaultThemeVariants'; export const defaultTheme: DefaultTheme = { classPrefix: 're', colors: defaultThemeColors, space: [0, 4, 8, 16, 24, 32, 64, 126, 256], breakpoints: defaultBreakpoints, gridWidth: 1200, gridGutter: 16, gridColumns: 12, radii: [0, 2, 4, 8], radius: 8, shadow: { soft: '0px 2px 16px rgba(27, 32, 43, 0.1)', hard: '0px 0px 16px rgba(44, 53, 71, 0.2)', }, typography: { fontSize: 16, color: defaultThemeColors.black, bodyFontFamily: 'Avenir', headerFontFamily: 'Tiempos', }, sizes: defaultThemeSizes, variants: defaultThemeVariants, }; <file_sep>import React from 'react'; import Button from '../Button'; import Box from '../Box'; import Collapse from './Collapse'; export default { title: 'Components|Collapse', description: 'Collapse is used to show and hide content. Use a button, anchor, or other clickable element as triggers', component: Collapse, }; export const Basic = () => { class Example extends React.Component { constructor(props) { super(props); this.state = { isOpen: false, }; } toggle() { this.setState({ isOpen: !this.state.isOpen, }); } render() { return ( <React.Fragment> <Button onClick={() => this.toggle()}>Toggle</Button> <Collapse isOpen={this.state.isOpen}> <Box p={3} mt={3} style={{ background: 'gainsboro' }}> I'm in a collapsible element! </Box> </Collapse> </React.Fragment> ); } } return <Example />; }; export const CustomTrigger = () => ( <> <Collapse renderTrigger={({ toggle }) => <Button onClick={toggle}>Click the custom trigger</Button>}> <Box p={3} mt={3} style={{ background: 'gainsboro' }}> I'm in a collapsible element! </Box> </Collapse> </> ); <file_sep>export Accordion from './Accordion'; export Alert from './Alert'; export Avatar from './Avatar'; export Badge from './Badge'; export Box from './Box'; export Button from './Button'; export Card from './Card'; export Checkbox from './Form/Checkbox'; export CheckboxGroup from './Form/CheckboxGroup'; export Collapse from './Collapse'; export Column from './Grid/Column'; export Container from './Grid/Container'; export DateInput from './Form/DateInput'; export Dropdown from './Dropdown'; export Field from './Form/Field'; export Fieldset from './Form/Fieldset'; export Flex from './Flex'; export Form from './Form/Form'; export Formbot from './Form/Formbot'; export FormError from './Form/FormError'; export FormGroup from './Form/FormGroup'; export Icon from './Icon'; export Input from './Form/Input'; export Label from './Form/Label'; export Linkify from './Linkify'; export Modal from './Modal'; export OrderedList from './Lists/OrderedList'; export PhoneInput from './Form/PhoneInput'; export Placeholder from './Placeholder'; export Portal from './Portal'; export RadioGroup from './Form/RadioGroup'; export Row from './Grid/Row'; export Select from './Form/Select'; export Spinner from './Spinner'; export Switch from './Form/Switch'; export Tabs from './Tabs'; export Text from './Text'; export ThemeProvider from './ThemeProvider'; export * from './Toast'; export { createTheme } from './createTheme'; export * from './utils'; export { default as styled, css, keyframes, createGlobalStyle } from 'styled-components'; <file_sep>import React from 'react'; import Button from './Button'; export default { title: 'Components|Button', component: Button, }; export const All = () => ( <Button.Group> <Button>Primary Button</Button> <Button variant="secondary">Secondary Button</Button> <Button variant="grey">Grey Button</Button> <Button variant="primaryText">Text Button</Button> </Button.Group> ); export const Variants = () => ( <Button.Group> <Button variant="primary">Primary</Button> <Button variant="secondary">Secondary</Button> <Button variant="success">Successful</Button> <Button variant="danger">Dangerous</Button> <Button variant="warning">Cautious</Button> <Button variant="grey">Informational</Button> </Button.Group> ); export const IconButtons = () => ( <Button.Group> <Button leftIcon="alert">Primary Button</Button> <Button variant="success" rightIcon="alert-circle" rightIconProps={{ size: 24 }}> Success Button </Button> <Button leftIcon="alert" /> </Button.Group> ); export const ButtonGroups = () => ( <Button.Group> <Button>One</Button> <Button>Two</Button> <Button variant="secondary">Three</Button> </Button.Group> ); export const Sizes = () => ( <Button.Group> <Button size="sm">Small Button</Button> <Button>Medium Button</Button> <Button size="lg">Large Button</Button> </Button.Group> ); export const Loading = () => ( <Button.Group> <Button loading>Loading...</Button> <Button loading variant="secondary"> Loading... </Button> </Button.Group> ); export const FullWidth = () => <Button block>Full Width</Button>; <file_sep>import { defaultBreakpoints } from '../defaultBreakpoints'; type Transform<T> = { [P in keyof T]: string; }; export interface ThemeBreakpoints extends Transform<typeof defaultBreakpoints> {} <file_sep>import React from 'react'; import Box from '../Box'; import Flex from './Flex'; export default { title: 'Components|Flex', component: Flex, }; export const Basic = () => ( <Flex> <Box m={2} p={2} flex={1} style={{ backgroundColor: 'gainsboro' }}> I take up the remaining space </Box> <Box m={2} p={2} style={{ backgroundColor: 'gainsboro' }}> I am a Box </Box> <Box m={2} p={2} style={{ backgroundColor: 'gainsboro' }}> I am Box </Box> </Flex> ); <file_sep>import React, { useContext, createRef } from 'react'; import * as yup from 'yup'; import Formbot, { Context } from './Formbot'; import Form from './Form'; import Field from './Field'; import Fieldset from './Fieldset'; import FormError from './FormError'; import PhoneInput from './PhoneInput'; import DateInput from './DateInput'; import Select from './Select'; import CheckboxGroup from './CheckboxGroup'; import RadioGroup from './RadioGroup'; import Switch from './Switch'; import Button from '../Button'; import Input from './Input'; export default { title: 'Components|Forms/Formbot', component: Formbot, }; export const Basic = () => ( <Formbot validationSchema={{ email: yup .string() .email() .required(), password: <PASSWORD>() .<PASSWORD>() .min(4), }}> <Form> <Input name="email" label="Email" /> <Input name="password" label="<PASSWORD>" /> <Field> <Button type="submit">Sign In</Button> </Field> </Form> </Formbot> ); export const AsyncValidation = () => ( <Formbot validationSchema={{ random: yup.string().test( 'valid', 'This test was delayed by 2 seconds.', async value => new Promise(resolve => { setTimeout(() => { resolve(false); }, 2000); }) ), }}> <Form> <Input name="random" label="random" /> <Field> <Button type="submit">Sign In</Button> </Field> </Form> </Formbot> ); export const FullExample = () => { const selectValues = [{ id: 1, value: 'male', label: 'Male' }, { id: 1, value: 'female', label: 'Female' }]; const checkboxValues = [ { id: 1, value: 'test', label: 'Checkbox 1', }, { id: 2, value: 'test2', label: 'Checkbox 2', }, ]; const radioValues = [ { id: 1, value: 'radio1', name: 'radio1', label: 'Radio 1', }, { id: 2, value: 'radio2', name: 'radio2', label: 'Radio 2', }, ]; const Values = () => { const state = useContext(Context); return <pre>{JSON.stringify(state.values, null, 2)}</pre>; }; class FormbotExample extends React.Component { nameRef = createRef(); componentDidMount() { this.nameRef.current.focus(); } render() { return ( <Formbot validations={{ name: val => { if (val !== 'Bob') { throw new Error('Your name must be Bob'); } }, email: { required: true, }, gender: { required: true, }, message: { required: true, }, checkboxes: { required: true, }, radioGroup: { required: true, }, switch1: { required: true, }, }}> <Form> <Fieldset legend="A Group of Inputs"> <Input name="name" placeholder="Name (should autofocus)" label="Name" ref={this.nameRef} /> <Input name="email" placeholder="Email" label="Email" shouldRenderError={false} /> <FormError name="email"> {error => <span style={{ color: 'navy' }}>Hi, I am a custom error: {error}</span>} </FormError> <PhoneInput name="phone" placeholder="Phone Number" label="Phone" /> <DateInput name="dob" placeholder="MM/DD/YYYY" label="Date of Birth" /> <Select name="gender" placeholder="Select a Gender" label="Gender" options={selectValues} /> </Fieldset> <Fieldset legend="Another Group of Inputs"> <Input name="message" multiline size="md" autogrow placeholder="Your Message" label="Write a Message" /> <Input name="favorite_word" placeholder="Favorite Word" label="Favorite Word" /> <CheckboxGroup label="Checkboxes" name="checkboxes" choices={checkboxValues} /> <RadioGroup label="Radios" name="radioGroup" horizontal choices={radioValues} /> <Switch name="switch1" /> </Fieldset> <Button htmlType="submit" type="primary" size="sm"> Submit </Button> <Values /> </Form> </Formbot> ); } } return <FormbotExample />; }; <file_sep>import React from 'react'; import { renderWithTheme, fireEvent, act } from '../../test/utils'; import PhoneInput from './PhoneInput'; import ThemeProvider from '../ThemeProvider'; describe('<PhoneInput />', () => { const renderInput = props => { const utils = renderWithTheme(<PhoneInput placeholder="Input" {...props} />); return { ...utils, input: utils.getByPlaceholderText('Input'), }; }; const updateInputValue = (input, value) => { act(() => { fireEvent.change(input, { target: { value } }); }); }; test('snapshot', () => { const { asFragment } = renderInput(); expect(asFragment()).toMatchSnapshot(); }); test('initally sets the value', () => { const value = '4087213456'; const { input } = renderInput({ value }); expect(input.value).toEqual('(408) 721-3456'); }); test('area code and hyphens', () => { const { input } = renderInput({ value: '408' }); expect(input.value).toEqual('(408)'); updateInputValue(input, '(408) 7214'); expect(input.value).toEqual('(408) 721-4'); }); test('can delete paren', () => { const { input } = renderInput({ value: '(408)' }); fireEvent.keyDown(input, { key: 'Backspace' }); updateInputValue(input, '(408'); expect(input.value).toEqual('(408'); }); test('updates internally when value prop changes', () => { const { input, rerender } = renderInput({ value: '(408)' }); rerender( <ThemeProvider> <PhoneInput placeholder="input" value="4087213456" /> </ThemeProvider> ); expect(input.value).toEqual('(408) 721-3456'); }); test('handles country codes', () => { const { input } = renderInput({ value: '14088675309' }); expect(input.value).toEqual('1 (408) 867-5309'); }); describe('truncates a number that is too long', () => { test('with country code', () => { const { input } = renderInput({ value: '1408867530903133' }); expect(input.value).toEqual('1 (408) 867-5309'); }); test('without country code', () => { const { input } = renderInput({ value: '408867530903133' }); expect(input.value).toEqual('(408) 867-5309'); }); }); }); <file_sep>import React from 'react'; import { object, select, boolean } from '@storybook/addon-knobs/react'; import Formbot from './Formbot'; import Button from '../Button'; import { Input } from './Input'; export default { title: 'Components|Forms/Input', component: Input, }; const defaultInputProps = { label: 'Example', placeholder: 'Start typing here...', }; export const Basic = () => <Input label="Example" placeholder="Start typing here..." />; export const Controlled = () => { function ControlledInput() { return ( <Formbot onSubmit={console.log} initialValues={{ value: '' }} validations={{ value: value => { if (value !== 'secretpassword') { throw new Error('Try typing "secretpassword"'); } }, }}> {({ values, errors, onChange, onSubmit }) => ( <form onSubmit={onSubmit}> <Input label="Input with Formbot" name="value" value={values.value} error={errors.value} onChange={onChange} /> <Button mt={2} type="submit"> Submit </Button> </form> )} </Formbot> ); } return <ControlledInput />; }; export const Multiline = () => ( <Input {...defaultInputProps} multiline value="I already have a value! If provided a value, I become controlled, so I won't update when you type here..." /> ); export const MultilineFloating = () => <Input {...defaultInputProps} floating multiline />; export const Autogrow = () => <Input {...defaultInputProps} multiline autogrow />; export const FloatingLabel = () => <Input {...defaultInputProps} floating />; export const Disabled = () => <Input {...defaultInputProps} disabled />; export const Error = () => <Input {...defaultInputProps} error="This is an error message" />; export const Styles = () => ( <Input {...defaultInputProps} styles={{ Input: { background: 'beige', }, }} /> ); export const Icon = () => { const iconOptions = { Information: 'information-outline', Visibility: 'eye-outline', Alert: 'alert', 'Area 51': 'alien', }; return ( <Input floating={boolean('Floating', false)} disabled={boolean('Disabled', false)} leftIcon={select('Left Icon', iconOptions, 'information-outline')} leftIconProps={object('Left Icon Props', { color: 'greyDarker', size: 16 })} rightIcon={select('Right Icon', iconOptions, 'eye-outline')} rightIconProps={object('Right Icon Props', { color: 'greyDarker', size: 24 })} {...defaultInputProps} /> ); }; <file_sep>import React from 'react'; import { Select } from './Select'; export default { title: 'Components|Forms/Select', component: Select, }; const defaultProps = { id: 'select', name: 'select', label: 'Example', options: [{ id: 1, value: 'male', label: 'Male' }, { id: 1, value: 'female', label: 'Female' }], }; export const Basic = () => <Select {...defaultProps} />; export const FloatingLabel = () => <Select {...defaultProps} floating />; <file_sep>import React from 'react'; import Placeholder from './Placeholder'; export default { title: 'Components|Placeholder', component: Placeholder, }; export const Basic = () => <Placeholder delay={500} loading />; export const WithDelay = () => ( <Placeholder delay={2000} loading={false}> <span>Hey, I'm loaded asynchronously.</span> </Placeholder> ); /** If an error occurs during an async call, pass an error message to the Placeholder component. It will call `renderError` if provided, otherwise will fallback to default error UI. */ export const WithError = () => <Placeholder error="Some weird error occured..." />; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Icon from '../Icon'; import FormError from '../Form/FormError'; import { createEasyInput } from './EasyInput'; import { getComponentSize, createComponent } from '../utils'; const transitionTiming = '250ms cubic-bezier(0.4, 0, 0.2, 1)'; const HiddenInput = createComponent({ name: 'CheckboxInput', tag: 'input', style: css` border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; left: 1px; white-space: nowrap; `, }); const CheckIcon = createComponent({ name: 'CheckIcon', as: Icon, style: ({ theme, iconSize }) => { const sizeStyles = getComponentSize(theme, 'CheckIcon', iconSize); return css` position: absolute; color: white; opacity: 0; transition: opacity ${transitionTiming}; font-size: 20px; ${sizeStyles} `; }, }); const CheckboxShape = createComponent({ name: 'CheckboxShape', as: 'div', style: ({ theme, isRadio, isFocused, size }) => { const checkboxSizeStyles = getComponentSize(theme, 'Checkbox', size); const radioSizeStyles = getComponentSize(theme, 'Radio', size); return css` position: relative; display: inline-flex; align-items: center; justify-content: center; border-style: solid; border-radius: 2px; transition: background-color ${transitionTiming}, border-color ${transitionTiming}; &:before, &:after { content: ''; position: absolute; opacity: 0; transition: opacity ${transitionTiming}; box-sizing: border-box; } &:before { border: 4px solid ${theme.colors.colorFocus}; border-radius: 6px; box-sizing: content-box; z-index: -1; ${isRadio && css` border-radius: 50%; height: ${radioSizeStyles.height}; width: ${radioSizeStyles.width}; `} } ${checkboxSizeStyles} ${isFocused && css` &:before { opacity: 1; } `} ${isRadio && css` border-radius: 50%; &:after { opacity: 1; border-radius: 50%; border-style: solid; border-color: white; } ${radioSizeStyles} `} `; }, }); const CheckboxLabel = createComponent({ name: 'CheckboxLabel', as: 'span', style: ({ theme, size }) => { const sizeStyles = getComponentSize(theme, 'CheckboxLabel', size); return css` transition: color ${transitionTiming}; ${sizeStyles} `; }, }); const CheckboxContainer = createComponent({ name: 'CheckboxContainer', tag: 'label', style: ({ theme, isChecked, isDisabled, isHorizontal, size, color }) => { const sizeStyles = getComponentSize(theme, 'CheckboxContainer', size); return css` display: inline-flex; align-items: flex-start; justify-content: flex-start; margin-bottom: 4px; user-select: none; cursor: pointer; ${CheckboxShape} { border-color: ${theme.colors[color]}; } ${sizeStyles} &:hover { ${CheckboxShape} { border-color: ${theme.colors.greyDarker}; } } ${isHorizontal && css` @media (min-width: ${theme.breakpoints.sm}) { & + & { margin-left: 18px; } } `} ${isChecked && css` ${CheckIcon} { opacity: 1; } ${CheckboxShape} { background-color: ${theme.colors[color]}; border-color: ${theme.colors[color]} !important; } `} ${isDisabled && css` cursor: not-allowed; ${CheckboxShape} { border-color: ${theme.colors.grey} !important; background-color: transparent !important; } ${CheckboxLabel} { color: ${theme.colors.grey}; } ${isChecked && css` ${CheckboxShape} { background-color: ${theme.colors.grey} !important; } `} `} `; }, }); export class Checkbox extends React.Component { static propTypes = { id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), value: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]), valueTrue: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]), valueFalse: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]), onChange: PropTypes.func, size: PropTypes.string, horizontal: PropTypes.bool, disabled: PropTypes.bool, styles: PropTypes.shape(), colorOn: PropTypes.string, colorOff: PropTypes.string, ariaLabel: PropTypes.string, checkIconColor: PropTypes.string, checkIcon: PropTypes.string, }; static defaultProps = { size: 'md', valueTrue: true, valueFalse: false, colorOn: 'primary', colorOff: 'greyDark', horizontal: false, onChange() {}, disabled: false, styles: {}, label: null, checkIconColor: 'white', checkIcon: 'check', }; static getDerivedStateFromProps(props, state) { if (props.value !== undefined && props.value !== state.value) { return { value: props.value, }; } return null; } state = { value: this.props.value, }; get checked() { return this.state.value === this.props.valueTrue; } handleChange = () => { const { valueTrue, valueFalse, onChange } = this.props; const newValue = this.checked ? valueFalse : valueTrue; this.setState( { value: newValue, }, () => { onChange(this.props.name, newValue); } ); }; handleFocus = () => { this.setState({ isFocused: !this.state.isFocused }); }; handleActive = () => { this.setState({ isActive: !this.state.isActive }); }; render() { const { label, id, error, name, size, checkIcon, checkIconColor, isRadio, colorOn, colorOff, horizontal, disabled, styles, ariaLabel, } = this.props; const { checked } = this; const { isFocused, isActive } = this.state; return ( <> <CheckboxContainer isChecked={checked} isDisabled={disabled} isFocused={isFocused} isHorizontal={horizontal} style={styles.CheckboxContainer} htmlFor={id} size={size} color={checked ? colorOn : colorOff} onMouseDown={this.handleActive} onMouseUp={this.handleActive}> <HiddenInput aria-label={ariaLabel || label} id={id} name={name} type="checkbox" checked={checked} disabled={disabled} onChange={this.handleChange} onFocus={this.handleFocus} onBlur={this.handleFocus} /> <CheckboxShape size={size} isRadio={isRadio} isChecked={checked} isFocused={isFocused}> {checked && !isRadio && <CheckIcon name={checkIcon} color={checkIconColor} iconSize={size} />} </CheckboxShape> {label && ( <CheckboxLabel size={size} style={styles.Label}> {label} </CheckboxLabel> )} </CheckboxContainer> {!isFocused && !isActive && error ? <FormError>{error}</FormError> : null} </> ); } } export default createEasyInput(Checkbox); <file_sep>import React, { useState, useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import DateFormatter from 'cleave.js/src/shortcuts/DateFormatter'; import Input from './Input'; import { createEasyInput } from './EasyInput'; import { getNextCursorPosition } from '../utils'; export const getRawMaxLength = pattern => { const formatter = new DateFormatter(pattern, '1900-01-01', '2099-12-31'); const blocks = formatter.getBlocks(); return blocks.reduce((sum, block) => sum + block, 0); }; const formatDate = (pattern, delimiter, dateString = '') => { const formatter = new DateFormatter(pattern, '1900-01-01', '2099-12-31'); // Process our date string, bounding values between 1 and 31, and prepending 0s for // for single digit blocks that can't have 2 numbers, e.g. 5 let tmpDate = formatter.getValidatedDate(`${dateString}`); // Blocks look something like [2, 2, 4], telling us how long each chunk should be return formatter.getBlocks().reduce((str, blockLength, index, blockArr) => { const block = tmpDate.substring(0, blockLength); if (!block) { return str; } tmpDate = tmpDate.substring(blockLength); // Append the delimiter if our block is complete and we're not at the last block const shouldAppendDelimiter = block.length === blockLength && index < blockArr.length - 1; return `${str}${block}${shouldAppendDelimiter ? delimiter : ''}`; }, ''); }; export function DateInput({ delimiter, pattern, forwardedRef, initialValue, value: propValue, onKeyDown, onChange, ...inputProps }) { const format = value => formatDate(pattern, delimiter, value); const [currentValue, setValue] = useState(initialValue || format(propValue)); const inputRef = forwardedRef || useRef(); const previousValue = useRef(propValue); useEffect(() => { if (previousValue.current !== propValue && propValue !== currentValue) { setValue(format(propValue)); } previousValue.current = propValue; }, [propValue]); const handleKeyDown = event => { const isLetterLike = /^\w{1}$/.test(event.key); if (isLetterLike && currentValue.replace(/\D/g, '').length >= getRawMaxLength(pattern)) { event.preventDefault(); event.stopPropagation(); } if (onKeyDown) { onKeyDown(event); } }; const handleChange = (name, newValue, event) => { const nextValue = newValue.length < currentValue.length ? newValue.trim() : format(newValue); const nextCursorPosition = getNextCursorPosition(event.target.selectionStart, currentValue, nextValue); setValue(nextValue); setTimeout(() => { inputRef.current.setSelectionRange(nextCursorPosition, nextCursorPosition); }); if (onChange) { onChange(name, nextValue, event); } }; return ( <Input forwardedRef={inputRef} value={currentValue} onKeyDown={handleKeyDown} onChange={handleChange} {...inputProps} /> ); } DateInput.propTypes = { ...Input.propTypes, initialValue: PropTypes.string, pattern: PropTypes.arrayOf(PropTypes.string), delimiter: PropTypes.string, }; DateInput.defaultProps = { ...Input.defaultProps, pattern: ['m', 'd', 'Y'], delimiter: '/', }; export default createEasyInput(DateInput); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import { space } from 'styled-system'; import propTypes from '@styled-system/prop-types'; import { getComponentVariant, createComponent } from '../utils'; const StyledAlert = createComponent({ name: 'Alert', style: ({ variant, theme }) => { const variantStyles = getComponentVariant(theme, 'Alert', variant); return css` padding: 1rem; margin-bottom: 1rem; border: 0; font-size: 14px; font-family: ${theme.typography.fontFamily || 'inherit'}; border-radius: ${theme.radius}px; a { color: inherit; text-decoration: underline; } ${variantStyles} ${space}; `; }, }); /** Alerts are typically used to display meaningful copy to users - typically notifying the user of an important message. */ const Alert = React.forwardRef((props, ref) => <StyledAlert {...props} ref={ref} />); Alert.propTypes = { variant: PropTypes.string, ...propTypes.space, }; Alert.defaultProps = { variant: 'primary', }; export default Alert; <file_sep>import React from 'react'; import Text from './Text'; export default { title: 'Components|Text', component: Text, }; export const Basic = () => ( <> <Text>The basic text component renders as a {'<span />'}</Text> <Text as="h1">It can render as other tags, like this {'<H1/>'}</Text> <Text color="red">It can use colors from the theme</Text> </> ); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import { createComponent } from '../utils'; import { createEasyInput } from './EasyInput'; const SwitchThumb = createComponent({ name: 'SwitchThumb', as: 'i', style: ({ trackInset, thumbSize, value }) => css` border-radius: ${thumbSize * 2}px; position: absolute; top: 0; bottom: 0; left: 0; height: ${thumbSize - trackInset * 2}px; width: ${thumbSize - trackInset * 2}px; background-color: white; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1), 0px 4px 4px rgba(0, 0, 0, 0.1); transition: all 0.3s cubic-bezier(0.125, 0.85, 0.3, 1.125); ${value && css` transform: translateX(${thumbSize}px); `}; `, }); const SwitchTrack = createComponent({ name: 'SwitchTrack', as: 'label', style: ({ theme, trackColor, thumbSize, trackInset, value, isFocused, colorFocus = theme.colors.colorFocus }) => css` position: relative; display: inline-block; cursor: pointer; width: ${thumbSize * 2}px; height: ${thumbSize}px; background: ${value ? theme.colors[trackColor] : 'transparent'}; border: ${trackInset}px solid ${value ? theme.colors[trackColor] : theme.colors.grey}; border-radius: ${thumbSize}px; transition: background-color 0.2s, border-color 0.2s; z-index: 1; &:active { ${SwitchThumb} { transform: translateX(${value ? thumbSize - trackInset * 3 : 0}px); width: ${thumbSize + trackInset}px; } } &:before { transition: opacity 250ms; content: ''; position: absolute; left: -${trackInset + 4}px; top: -${trackInset + 4}px; width: ${thumbSize * 2}px; height: ${thumbSize}px; z-index: 0; opacity: 0; } ${isFocused && css` &:before { opacity: 1; border: 4px solid ${colorFocus}; border-radius: ${thumbSize}px; } `} `, }); const SwitchInput = createComponent({ name: 'SwitchInput', as: 'input', style: css` border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; left: 1px; white-space: nowrap; `, }); export class Switch extends React.Component { static propTypes = { name: PropTypes.string.isRequired, trackColor: PropTypes.string, trackInset: PropTypes.number, thumbSize: PropTypes.number, value: PropTypes.bool, }; static defaultProps = { trackColor: 'primary', trackInset: 2, thumbSize: 24, }; state = { value: !!this.props.value, isFocused: false, }; static getDerivedStateFromProps(props, state) { if (props.value !== undefined && props.value !== state.value) { return { value: props.value, }; } return null; } handleChange = () => { const { onChange, name } = this.props; if (typeof onChange === 'function') { onChange(name, !this.state.value); } else { this.setState(state => ({ value: !state.value })); } }; handleFocus = () => { this.setState({ isFocused: !this.state.isFocused }); }; render() { const { name, thumbSize, trackInset, colorFocus, ...props } = this.props; const { value, isFocused } = this.state; const sharedProps = { value, thumbSize, trackInset, isFocused, }; return ( <SwitchTrack colorFocus={colorFocus} {...props} {...sharedProps}> <SwitchInput name={name} type="checkbox" onChange={this.handleChange} onFocus={this.handleFocus} onBlur={this.handleFocus} /> <SwitchThumb {...sharedProps} /> </SwitchTrack> ); } } export default createEasyInput(Switch); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Box from '../Box'; import Button from '../Button'; import Spinner from '../Spinner'; import { createComponent } from '../utils'; const Container = createComponent({ name: 'Placeholder', style: css` display: flex; flex-direction: column; height: 100%; width: 100%; align-items: center; justify-content: center; min-height: 50px; `, }); /** Placeholder shows a spinner after a specified delay while content is loaded asynchronously. */ export default class Placeholder extends React.Component { static propTypes = { loading: PropTypes.bool, error: PropTypes.string, delay: PropTypes.number, renderLoading: PropTypes.func, renderError: PropTypes.func, onReload: PropTypes.func, }; static defaultProps = { loading: false, delay: 250, }; state = { delayed: false, }; componentDidMount() { this.runDelay(); } componentWillUnmount() { clearTimeout(this.delayTimer); } runDelay() { if (this.props.delay <= 0) return; this.setState({ delayed: true }, () => { this.delayTimer = setTimeout(() => { this.setState({ delayed: false, }); }, this.props.delay); }); } render() { const { children, loading, error, renderLoading, renderError, onReload } = this.props; if (loading && this.state.delayed) { return null; } if (loading) { return renderLoading ? ( renderLoading() ) : ( <Container> <Spinner /> </Container> ); } if (error) { return renderError ? ( renderError() ) : ( <Container textAlign="center"> <strong>Oh no!</strong> <Box mt={1} mb={3}> {error} </Box> <Button variant="primary" outline onClick={onReload}> Try Again </Button> </Container> ); } return typeof children === 'function' ? children() : children; } } <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Box from '../Box'; import Checkbox from './Checkbox'; import FormError from './FormError'; import { createEasyInput } from './EasyInput'; import GroupContainer from './GroupContainer'; export class CheckboxGroup extends Component { static propTypes = { name: PropTypes.string.isRequired, horizontal: PropTypes.bool, value: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), choices: PropTypes.arrayOf( PropTypes.shape({ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), label: PropTypes.string, disabled: PropTypes.bool, }) ).isRequired, onChange: PropTypes.func, colorOn: PropTypes.string, colorOff: PropTypes.string, }; static defaultProps = { horizontal: false, onChange() {}, colorOn: 'primary', colorOff: 'greyDark', }; state = { selected: Array.isArray(this.props.value) ? [...this.props.value] : [], }; createChangeHandler = choice => (name, value) => { const { selected } = this.state; let newSelected; if (!selected.includes(value)) { if (choice.exclusive) { newSelected = [value]; } else { newSelected = this.props.choices .filter(c => !c.exclusive && (c.value === value || selected.includes(c.value))) .map(c => c.value); } } else { const index = selected.indexOf(value); newSelected = [...selected.slice(0, index), ...selected.slice(index + 1)]; } this.setState( { selected: newSelected, }, () => { this.props.onChange(this.props.name, newSelected); } ); }; render() { const { name, choices, error, horizontal, colorOn, colorOff, ...checkboxProps } = this.props; const { selected } = this.state; return ( <Box> <GroupContainer horizontal={horizontal}> {choices.length && choices.map(choice => { const { value = choice.id } = choice; const key = `checkbox-${name}-${value}`; return ( <Checkbox {...checkboxProps} key={key} id={key} name={key} label={choice.label} colorOn={colorOn} colorOff={colorOff} horizontal={horizontal} value={selected && selected.includes(value) ? value : null} valueTrue={value} valueFalse={value} onChange={this.createChangeHandler(choice)} /> ); })} </GroupContainer> {!!error && <FormError>{error}</FormError>} </Box> ); } } export default createEasyInput(CheckboxGroup); <file_sep>import React from 'react'; import { renderWithTheme } from '../../test/utils'; import Tabs from './Tabs'; const TabContent = ({ body }) => <div>This is the content for Tab {body}</div>; const onActiveSpy = jest.fn(); const TABS = [ { id: 'test-one', title: 'Tab One', content: <TabContent body="one" />, }, { id: 'test-two', title: 'Tab Two', content: <TabContent body="two" />, onActive: onActiveSpy, }, ]; describe('<Tabs />', () => { afterEach(() => { onActiveSpy.mockClear(); }); test('renders', () => { const { asFragment } = renderWithTheme(<Tabs tabs={TABS} />); expect(asFragment()).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import Alert from './Alert'; import { text } from '@storybook/addon-knobs'; export default { title: 'Components|Alert', component: Alert, }; export const Basic = () => { const variant = text('Variant', 'success'); return ( <> <Alert variant={variant}> <strong>Well done!</strong> You successfully read this important <a href="google.com">alert link</a> message. </Alert> <Alert variant="info">This is a generic informational message.</Alert> <Alert variant="danger"> <strong>Oops!</strong> Something wen't wrong. </Alert> <Alert variant="warning"> <strong>Caution!</strong> There be dragons. </Alert> </> ); }; <file_sep>import React, { Component } from 'react'; import { css } from 'styled-components'; import PropTypes from 'prop-types'; import { createComponent } from '../utils'; const TabsProvider = createComponent({ name: 'Tabs', style: ({ vertical }) => css` display: flex; flex-direction: ${vertical ? 'row' : 'column'}; `, }); const TabList = createComponent({ name: 'TabList', tag: 'ul', style: ({ vertical, theme }) => css` display: flex; margin: 0; padding: 0; list-style: none; flex-direction: ${vertical ? 'column' : 'row'}; ${!vertical && css` border-bottom: 1px solid ${theme.colors.greyLighter}; `}; `, }); const TabListItem = createComponent({ name: 'TabListItem', tag: 'li', style: () => css` display: flex; margin: 0; padding: 0; `, }); const Tab = createComponent({ name: 'Tab', tag: 'button', style: ({ vertical, disabled }) => css` appearance: none; margin: 0; padding: 0; background: none; border: none; font-size: 14px; font-family: inherit; position: relative; justify-content: center; cursor: pointer; margin-${vertical ? 'left' : 'top'}: 1px; margin-${vertical ? 'right' : 'bottom'}: -1px; padding: ${vertical ? '0' : '0 12px'}; outline: none; white-space: nowrap; opacity: ${disabled ? 0.5 : 1}; &:active { outline: none; } `, }); const TabTitle = createComponent({ name: 'TabTitle', tag: 'span', style: ({ active, vertical, theme }) => css` display: block; color: ${active ? theme.colors.greyDarkest : theme.colors.greyDark}; padding: ${vertical ? '8px 12px 8px 8px' : '12px 8px'}; border-${vertical ? 'left' : 'bottom'}: 4px solid ${active ? theme.colors.primary : 'transparent'}; &::hover { color: #212b36; border-color: ${active ? theme.colors.primary : theme.colors.greyLight}; } `, }); const TabContent = createComponent({ name: 'TabContent', tag: 'div', style: css` width: 100%; `, }); class Tabs extends Component { static propTypes = { tabs: PropTypes.arrayOf(PropTypes.shape()).isRequired, active: PropTypes.number, vertical: PropTypes.bool, onChange: PropTypes.func, }; static defaultProps = { vertical: false, }; state = { active: this.props.active || 0, }; componentDidUpdate() { if (this.props.active && this.props.active !== this.state.active) { this.setState({ active: this.props.active, }); } } handleTabClick = selected => { if (this.props.onChange) { this.props.onChange(selected); } this.setState({ active: selected, }); }; renderHeadings() { return this.props.tabs.map((tab, i) => { const id = tab.id || i; return ( <TabListItem key={id}> <Tab id={id} disabled={tab.disabled} vertical={this.props.vertical} onClick={() => { if (tab.onActive) { tab.onActive(); } this.handleTabClick(i); }}> <TabTitle active={this.state.active === i} vertical={this.props.vertical}> {tab.title} </TabTitle> </Tab> </TabListItem> ); }); } renderContent() { const { content } = this.props.tabs[this.state.active]; if (React.isValidElement(content)) { return content; } throw new Error('Tab content must be a valid React element.'); } render() { return ( <TabsProvider vertical={this.props.vertical}> <TabList vertical={this.props.vertical}>{this.renderHeadings()}</TabList> <TabContent>{this.renderContent()}</TabContent> </TabsProvider> ); } } export default Tabs; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import ReactMarkdown from 'react-markdown'; const Link = styled.a.attrs(() => ({ target: '_blank', rel: 'noopener noreferrer', }))` color: inherit; text-decoration: underline; `; const Root = styled.div` white-space: pre-wrap; p:first-child { margin-top: 0; } div + div { margin-top: 8px; } `; /** Automatically parse links contained in a body of text. All props except for `linkStyle` are passed through directly to [react-markdown](https://github.com/rexxars/react-markdown), which `Linkify` uses internally. */ export default function Linkify({ source, linkStyle, renderers, ...props }) { if (typeof source !== 'string') { throw new Error('Molekule: source prop must be a valid markdown string'); } // Convert all carriage returns to new lines const markdownString = source.replace(/\r/g, '\n'); return ( <ReactMarkdown source={markdownString} renderers={{ paragraph: 'div', root: p => <Root {...p} />, link: p => <Link {...p} style={linkStyle} />, code: ({ value }) => <div>{value}</div>, ...renderers, }} {...props} /> ); } Linkify.propTypes = { source: PropTypes.string, className: PropTypes.string, renderers: PropTypes.shape(), linkStyle: PropTypes.shape(), }; Linkify.defaultProps = { className: 're-linkify', renderers: {}, }; <file_sep>import React from 'react'; import ToastContainer from './ToastContainer'; import toast from './toast'; import Button from '../Button'; export default { title: 'Components|Toast', component: ToastContainer, }; export const Basic = () => ( <> <h4>Variants</h4> <Button.Group> <Button variant="success" onClick={() => { toast.success('Yay!'); }}> Success </Button> <Button variant="danger" onClick={() => { toast.error('Danger!'); }}> Danger </Button> <Button variant="warning" onClick={() => { toast.warn('Warning!'); }}> Warning </Button> <Button variant="info" onClick={() => { toast.info('This is some serious info!'); }}> Info </Button> </Button.Group> <h4>Positioning</h4> <Button.Group> <Button variant="success" onClick={() => { toast.success('Yay!', { position: 'bottom-left', }); }}> Show a toast on the bottom left </Button> <Button variant="danger" onClick={() => { toast.error('Danger!', { position: 'top-right', }); }}> Show a toast on the top right </Button> </Button.Group> <ToastContainer /> </> ); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Box from '../Box'; import { themeGet, createComponent } from '../utils'; const StyledCard = createComponent({ name: 'Card', as: Box, style: ({ shadow, theme }) => css` background: white; box-shadow: ${shadow ? themeGet('shadow.soft', 'none') : 'none'}; border-radius: ${themeGet('radius', 0)}px; overflow: hidden; border: 1px solid ${theme.colors.greyLight}; `, }); /** Cards provide a flexible way to encapsulate content with multiple variants and options. */ const Card = React.forwardRef((props, ref) => <StyledCard ref={ref} {...props} />); Card.propTypes = { shadow: PropTypes.bool, }; Card.defaultProps = { shadow: false, }; Card.Footer = createComponent({ name: 'CardFooter', as: Box, style: css` padding: 16px; `, }); Card.Body = createComponent({ name: 'CardBody', as: Box, style: () => css` padding: 16px; & + ${Card.Footer} { padding-top: 0px; } `, }); Card.Header = createComponent({ name: 'CardHeader', as: Box, style: css` padding: 16px; font-weight: 700; & + ${Card.Body} { padding-top: 0px; } `, }); export default Card; <file_sep>import React from 'react'; import { renderWithTheme } from '../../test/utils'; import Text from './Text'; describe('Text', () => { test('default to <span>', () => { const { asFragment } = renderWithTheme(<Text>Hey!</Text>); expect(asFragment()).toMatchSnapshot(); }); test('"as" prop', () => { const { asFragment } = renderWithTheme(<Text as="h1">Hey!</Text>); expect(asFragment()).toMatchSnapshot(); }); test('"color" prop', () => { const { asFragment } = renderWithTheme(<Text color="red">Hey!</Text>); expect(asFragment()).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import Flex from '../Flex'; import { createComponent } from '../utils'; const getMargin = p => { if (p.collapse) return 0; return typeof p.gutter === 'number' ? p.gutter / 2 : p.theme.gridGutter / 2; }; const StyledRow = createComponent({ name: 'Row', as: Flex, style: ({ vertical, reverse }) => { const direction = vertical ? 'column' : 'row'; return css` flex: 0 1 auto; flex-direction: ${reverse ? `${direction}-reverse` : direction}; flex-wrap: wrap; margin-right: -${getMargin}px; margin-left: -${getMargin}px; `; }, }); /** Rows are usually found within a container to wrap columns. */ const Row = ({ children, gutter, reverse, collapse, vertical, ...props }) => ( <StyledRow {...props} gutter={gutter} reverse={reverse} collapse={collapse} vertical={vertical}> {React.Children.map(children, child => React.cloneElement(child, { gutter, collapse, vertical }))} </StyledRow> ); Row.displayName = 'Row'; Row.propTypes = { /** * Lay row out vertically */ vertical: PropTypes.bool, /** * Margin between columns */ gutter: PropTypes.number, /** * Reverse the order of the columns */ reverse: PropTypes.bool, /** * Collapse columns by removing gutters */ collapse: PropTypes.bool, }; Row.defaultProps = { vertical: false, reverse: false, collapse: false, }; export default Row; <file_sep>import React, { Component, createRef } from 'react'; import styled, { css } from 'styled-components'; import PropTypes from 'prop-types'; import Field from './Field'; import FormError from './FormError'; import Icon from '../Icon'; import Flex from '../Flex'; import Label from './Label'; import { createEasyInput } from './EasyInput'; import { createComponent } from '../utils'; const SelectContainer = createComponent({ name: 'SelectContainer', as: Flex, style: ({ theme }) => css` background: white; border: 1px solid ${theme.colors.greyLight}; height: 48px; outline: none; width: 100%; position: relative; border-radius: ${theme.radius}px; transition: 250ms all; -webkit-appearance: none; font-family: inherit; font-size: ${theme.typography.fontSize}px; vertical-align: middle; `, }); const IconContainer = styled(Flex)` position: absolute; height: 100%; right: 0; top: 0; z-index: 1; `; const SelectInput = createComponent({ name: 'Select', tag: 'select', style: ({ theme, value, isFloating }) => css` position: relative; z-index: 2; padding: 0 32px 0px 8px; outline: none; width: 100%; font-size: ${theme.typography.fontSize}px; font-family: inherit; background: transparent; color: ${value ? theme.typography.color : theme.colors.greyDarker}; border: none; -webkit-appearance: none; ${isFloating && css` margin-top: 16px; `}; `, }); const SelectOption = createComponent({ name: 'SelectOption', tag: 'option', }); export class Select extends Component { static propTypes = { name: PropTypes.string.isRequired, options: PropTypes.array.isRequired, placeholder: PropTypes.string, value: PropTypes.string, error: PropTypes.string, onChange: PropTypes.func, onBlur: PropTypes.func, size: PropTypes.string, label: PropTypes.string, }; static defaultProps = { onChange() {}, onBlur() {}, }; static getDerivedStateFromProps(props, state) { if (props.value !== undefined && props.value !== state.value) { return { value: props.value, }; } return null; } state = { value: '', }; innerRef = createRef(); get ref() { return this.props.forwardedRef || this.innerRef; } handleChange = e => { this.setState({ value: e.target.value }); this.props.onChange(e.target.name, e.target.value); }; handleBlur = e => { this.props.onBlur(e.target.name); }; render() { const { id, name, options, placeholder, error, size = 'md', label, floating, ...props } = this.props; const { value } = this.state; const isFloating = floating && value != undefined && `${value}`.trim(); const FloatingLabel = ( <Label htmlFor={id} size={size} isFloating={isFloating} isFloatable={floating}> {label} </Label> ); return ( <Field> {label && !floating && <Label size={size}>{label}</Label>} <SelectContainer value={value} size={size}> {label && isFloating && FloatingLabel} <SelectInput {...props} size={size} ref={this.ref} name={name} value={value} onChange={this.handleChange} isFloating={isFloating} onBlur={this.handleBlur}> <SelectOption value="">{placeholder || 'Select an option...'}</SelectOption> {options.map(option => ( <SelectOption key={option.value} value={option.value}> {option.label} </SelectOption> ))} </SelectInput> <IconContainer aria-hidden="true" mr={2} alignItems="center" justifyContent="center"> <Icon name="chevron-down" color="greyDarker" size={24} /> </IconContainer> </SelectContainer> {error && <FormError>{error}</FormError>} </Field> ); } } export default createEasyInput(Select); <file_sep>import React from 'react'; import OrderedList from './OrderedList'; export default { title: 'Components|OrderedList', component: OrderedList, }; export const Basic = () => ( <OrderedList> <li>Apple</li> <li> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </li> <li>Peaches</li> </OrderedList> ); <file_sep>import React from 'react'; import { renderWithTheme } from '../../test/utils'; import Card from './Card'; test('Card', () => { const { asFragment } = renderWithTheme( <Card> <Card.Header>Header</Card.Header> <Card.Body>Body</Card.Body> <Card.Footer>Footer</Card.Footer> </Card> ); expect(asFragment()).toMatchSnapshot(); }); <file_sep>import React, { forwardRef, useContext } from 'react'; import { Context } from './Formbot'; /** * useContext has some slight performance issues. Every update to context re-renders * each subscribed component and there's currently no way to bail out of renders if the * values we care about haven't changed. Below is a sufficient workaround below and redux maintainers are discussing here: https://github.com/facebook/react/issues/14110 */ const PureInput = React.memo(({ Component, ...props }) => <Component {...props} />); function EasyInput({ name, Component, shouldRenderError = true, ...props }) { const state = useContext(Context); if (!state) { return <PureInput name={name} Component={Component} {...props} />; } const value = state.values[name]; const defaultValue = Component.defaultProps && Component.defaultProps.defaultValue !== undefined ? Component.defaultProps.defaultValue : ''; return ( <PureInput name={name} value={value !== undefined ? value : defaultValue} error={shouldRenderError ? state.errors[name] : undefined} onChange={state.onChange} onBlur={state.onBlur} onFocus={state.onFocus} Component={Component} {...props} /> ); } export const createEasyInput = Component => forwardRef((props, ref) => <EasyInput Component={Component} forwardedRef={ref} {...props} />); // eslint-disable-line export default EasyInput; <file_sep>import '@babel/polyfill'; import 'jest-styled-components'; import 'jest-dom/extend-expect'; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; export const Context = React.createContext(null); const VALIDATIONS = { required: (val, isRequired) => { if (!isRequired) return; if (!val || (typeof val === 'string' && val === '')) { throw new Error('This field is required'); } }, minLength: (val, minLength) => { if (!val || `${val}`.length < minLength) { throw new Error(`This field must be at least ${minLength} characters`); } }, maxLength: (val, maxLength) => { if (val && `${val}`.length > maxLength) { throw new Error(`This field cannot be more than ${maxLength} characters`); } }, }; export default class Formbot extends React.Component { static propTypes = { initialValues: PropTypes.shape(), validations: PropTypes.shape(), validationSchema: PropTypes.shape(), onFocus: PropTypes.func, onChange: PropTypes.func, onBlur: PropTypes.func, onSubmit: PropTypes.func, }; static defaultProps = { initialValues: {}, validations: {}, validationSchema: null, onFocus() {}, onChange() {}, onBlur() {}, onSubmit() {}, }; state = { values: this.props.initialValues || {}, fields: {}, errors: {}, }; get validatableFields() { const { validationSchema, validations } = this.props; return Object.keys(validationSchema || validations || {}); } get validatable() { return !!this.validatableFields.length; } get isValid() { return Object.values(this.state.errors).every(val => !val); } get values() { return this.state.values; } getValues() { return this.validateAllFields().then(() => ({ isValid: this.isValid, values: this.values, })); } setValues = (values = {}) => new Promise(resolve => { this.setState( state => ({ values: { ...state.values, ...values, }, }), () => this.validateAllFields().then(resolve) ); }); setErrors = (errors = {}, cb) => this.setState( state => ({ errors: { ...state.errors, ...errors, }, }), cb ); updateField = (field, updates = {}) => new Promise(resolve => { this.setState( state => ({ fields: { ...state.fields, [field]: { ...state.fields[field], ...updates, }, }, }), resolve ); }); reset = () => { this.setState({ values: {}, fields: {}, errors: {}, }); }; validateField(field) { return new Promise(resolve => { const fieldState = this.state.fields[field] || {}; if (fieldState.validated) { resolve(); return; } const { validationSchema, validations } = this.props; const hasSchema = !!validationSchema; const validation = (validationSchema || validations || {})[field]; const validationOpts = { context: this.getContext() }; if (!validation) { resolve(); return; } const fieldValue = this.state.values[field]; const setFieldValidated = message => { this.updateField(field, { validated: true }).then(() => { this.setErrors({ [field]: message }, resolve); }); }; Promise.resolve() .then(() => { if (hasSchema && typeof validation.validate === 'function') { return validation.validate(fieldValue, validationOpts); } else if (typeof validation === 'function') { validation(fieldValue); } else { Object.keys(validation).forEach(method => { const validator = VALIDATIONS[method]; if (!validator) { throw new Error(`Formbot: "${method}" is not a built-in validator.`); } validator(fieldValue, validation[method]); }); } return true; }) .then(() => { setFieldValidated(); }) .catch(err => { setFieldValidated(err.message); }); }); } validateAllFields() { return Promise.all( this.validatableFields.map(field => this.updateField(field, { validated: false }).then(() => this.validateField(field)) ) ); } onFocus = field => { this.updateField(field, { focused: true }).then(() => { this.props.onFocus(field); }); }; onChange = (field, value) => { this.setState( state => ({ values: { ...state.values, [field]: value, }, }), () => { this.updateField(field, { validated: false }) .then(() => this.validateField(field)) .then(() => this.props.onChange(field, value, this.state.values)); } ); }; onBlur = field => { this.updateField(field, { blurred: true }) .then(() => this.validateField(field)) .then(() => { this.props.onBlur(field); }); }; onSubmit = event => { event.preventDefault(); this.validateAllFields().then(() => { this.props.onSubmit({ isValid: this.isValid, values: this.state.values, errors: this.state.errors, }); }); }; getContext() { return { ...this.props, values: this.state.values, errors: this.state.errors, onChange: this.onChange, onFocus: this.onFocus, onBlur: this.onBlur, onSubmit: this.onSubmit, reset: this.reset, }; } render() { const { children } = this.props; return ( <Context.Provider value={this.getContext()}> {typeof children === 'function' ? children(this.getContext()) : children} </Context.Provider> ); } } <file_sep>import { defaultBreakpoints } from 'src/defaultBreakpoints'; import { ExtendedCSSProperties } from './ExtendedCSSProperties'; type Transform<T> = { [P in keyof T]: ExtendedCSSProperties; }; export interface ThemeSize extends Partial<Transform<typeof defaultBreakpoints>> {} <file_sep>import React from 'react'; import Container from './Container'; export default { title: 'Components|Grid/Container', component: Container, }; export const Basic = () => ( <Container> <div>I'm a container with content</div> </Container> ); export const Fluid = () => ( <Container fluid> <div>I'm a fluid container so I take up all the space I'm given</div> </Container> ); <file_sep>import { css, keyframes } from 'styled-components'; import { rgba } from 'polished'; import { createComponent } from '../utils'; const spin = keyframes` from { transform: rotate(0deg); } from { transform: rotate(360deg); } `; const Spinner = createComponent({ name: 'Spinner', style: ({ size = 15 }) => css` height: ${size}px; width: ${size}px; border: ${size / 10}px solid ${p => rgba(p.theme.colors.primary, 0.3)}; border-right-color: ${p => p.theme.colors.primary}; border-radius: 50%; animation: ${spin} 1.1s infinite linear; `, }); export default Spinner; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styled, { css } from 'styled-components'; import { createComponent } from '../utils'; const Legend = createComponent({ name: 'Legend', tag: 'legend', style: ({ theme, color = theme.colors.greyDarkest }) => css` font-weight: 700; margin-bottom: 8px; font-size: 18px; color: ${color}; `, }); const Container = styled.fieldset` border: 0; padding: 0; margin: 0; * + & { margin-top: 1.5rem; } `; const Fieldset = ({ legend, children }) => ( <Container> {legend && <Legend>{legend}</Legend>} {children} </Container> ); Fieldset.propTypes = { legend: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), }; export default Fieldset; <file_sep>// Note - Typing is generated by this constant export const defaultBreakpoints = { xs: '400px', sm: '600px', md: '900px', lg: '1200px', xl: '1500px', } as const; <file_sep>import { useCallback, useEffect } from 'react'; export default function useKeyPress(targetKeys, callback, keyEvent = 'keydown') { const keys = [].concat(targetKeys); const pressHandler = useCallback( event => { if (keys.indexOf(event.key) >= 0) { callback(event); } }, [targetKeys, callback] ); useEffect(() => { window.addEventListener(keyEvent, pressHandler); return () => window.removeEventListener(keyEvent, pressHandler); }, [targetKeys, callback, keyEvent]); } <file_sep>import React from 'react'; import { css } from 'styled-components'; import Box from '../Box'; import { createComponent } from '../utils'; const StyledFlex = createComponent({ name: 'Flex', as: Box, style: () => css` display: flex; `, }); /** Quickly manage the layout, alignment, and sizing of grid columns, navigation, components, and more with a full suite of responsive flexbox utilities. For more complex implementations, custom CSS may be necessary. */ const Flex = React.forwardRef((props, ref) => <StyledFlex {...props} ref={ref} />); Flex.displayName = 'Flex'; Flex.propTypes = { ...Box.propTypes, }; export default Flex; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { css } from 'styled-components'; import { Transition } from 'react-transition-group'; import { createComponent } from '../utils'; const getTransitionStyle = (state, duration) => { switch (state) { case 'exited': return css` display: none; `; case 'entering': case 'exiting': return css` transition: height ${duration}ms ease-in-out; overflow: hidden; `; default: return css``; } }; const Container = createComponent({ name: 'Collapse', style: ({ duration, height, state }) => css` position: relative; height: ${height}px; ${getTransitionStyle(state, duration)}; `, }); const Trigger = createComponent({ name: 'CollapseTrigger', }); /** Collapse is used to show and hide content. Use a button, anchor, or other clickable elements as triggers. */ export default class Collapse extends Component { static propTypes = { isOpen: PropTypes.bool, duration: PropTypes.number, onEnter: PropTypes.func, onEntering: PropTypes.func, onEntered: PropTypes.func, onExit: PropTypes.func, onExiting: PropTypes.func, onExited: PropTypes.func, }; static defaultProps = { duration: 175, onEnter: () => {}, onEntering: () => {}, onEntered: () => {}, onExit: () => {}, onExiting: () => {}, onExited: () => {}, }; static getDerivedStateFromProps(props, state) { if (props.isOpen !== undefined && props.isOpen !== state.isOpen) { return { ...state, isOpen: props.isOpen, }; } return null; } state = { isOpen: this.props.isOpen || false, height: 0, }; onEnter = (node, isAppearing) => { this.props.onEnter(node, isAppearing); }; onEntering = (node, isAppearing) => { this.setState({ height: node.scrollHeight }); this.props.onEntering(node, isAppearing); }; onEntered = (node, isAppearing) => { this.setState({ height: node.scrollHeight }); this.props.onEntered(node, isAppearing); }; onExit = node => { this.setState({ height: node.scrollHeight }); this.props.onExit(node); }; onExiting = node => { // Taken from: https://github.com/reactstrap/reactstrap/blob/master/src/Collapse.js#L80 const _unused = node.offsetHeight; // eslint-disable-line this.setState({ height: 0 }); this.props.onExiting(node); }; onExited = node => { this.props.onExited(node); }; toggle = () => { this.setState(state => ({ isOpen: !state.isOpen, })); }; renderTrigger() { const { trigger, renderTrigger } = this.props; if (renderTrigger) { return renderTrigger({ toggle: this.toggle }); } else if (trigger) { return <Trigger onClick={this.toggle}>{trigger}</Trigger>; } return null; } render() { const { duration, children, ...props } = this.props; const { height, isOpen } = this.state; return ( <> {this.renderTrigger()} <Transition {...props} in={isOpen} timeout={duration} onEnter={this.onEnter} onEntering={this.onEntering} onEntered={this.onEntered} onExit={this.onExit} onExiting={this.onExiting} onExited={this.onExited}> {state => ( <Container state={state} height={height} duration={duration}> {children} </Container> )} </Transition> </> ); } }
c4638a6be69a3a6371ba57904c31340e6e28a201
[ "JavaScript", "TypeScript" ]
57
JavaScript
guilean/molekule
0da9ea2e30c5b5b33a7912f3ca3acae342436c14
29f7daebd8f422d2a2e90305daa5a2048e1b96b3
refs/heads/master
<repo_name>anacmm/PocUsability<file_sep>/app/view/Mostra.js Ext.define('PocUsability.view.Mostra', { extend: 'Ext.Container', xtype: 'mostraArtigo', config: { title: 'Arquivo Acadêmico', scrollable: true, layout: 'vbox', items: [ { id: 'content', cls: 'x-mostra', tpl: [ '<div class="top">', '<div class="foto" style="background-image:url(resources/images/alunos/{foto}); background-position: center center;"></div>', '<div class="artigo"><span> <b>{titulo}</b> </span> <p> Autor: {autor} <p> Orientador: {orientador}</div>', '<div class="resumo"> {resumo} </div>', '</div>' ].join('') }, { xtype: 'container', layout: { type: 'hbox', pack: 'center', align: 'stretch' }, items: [ { xtype: 'spacer', flex: 1 }, { xtype: 'button', text : 'Download', flex: 1, ui: 'decline', scope: this, handler: function() { Ext.Msg.confirm( 'Confirme', 'Deseja realmete realizar o download do arquivo completo?', function(answer){ if(answer=='yes') { Ext.Msg.alert('Download Concluído', 'Artigo baixado com sucesso!', Ext.emptyFn); } }, this); } }, { xtype: 'spacer', flex: 1 } ] } ], record: null }, updateRecord: function(newRecord) { if (newRecord) { this.down('#content').setData(newRecord.data); } } }); <file_sep>/app/controller/Application.js Ext.define('PocUsability.controller.Application', { extend: 'Ext.app.Controller', config: { refs: { main: 'mainview', tela: null, telas: 'tela', artigos: 'artigos', mostraArtigos: 'mostraArtigo' }, control: { telas: { itemtap: 'onTelaSelect' }, artigos: { itemtap: 'onArtigoSelect' } } }, onTelaSelect: function(list, index, node, record) { this.tela = Ext.create(record.data.tela); this.getMain().push(this.tela); }, onArtigoSelect: function(list, index, node, record) { if (!this.mostraArtigos) { this.mostraArtigos = Ext.create('PocUsability.view.Mostra'); } // Bind the record onto the show tela view this.mostraArtigos.setRecord(record); this.getMain().push(this.mostraArtigos); } }); <file_sep>/app/view/Video.js Ext.define('PocUsability.view.Video', { extend: 'Ext.Video', xtype: 'pocvideo', fullscreen: true, config: { title: 'Vídeo', scrollable: true, maxWidth: '100%', maxHeight: '100%', url: [ 'http://www.youtube.com/watch?v=HnOpPVR3OXg' ], posterUrl: 'resources/images/fatec.jpg' } });<file_sep>/app/model/Artigo.js Ext.define('PocUsability.model.Artigo', { extend: 'Ext.data.Model', config: { fields: [ 'titulo', 'autor', 'orientador', 'foto', 'resumo' ] } }); <file_sep>/app/model/Tela.js Ext.define('PocUsability.model.Tela', { extend: 'Ext.data.Model', config: { fields: [ 'name', 'title', 'descricao', 'icone', 'tela' ] } });
87490b9ff9fbb88d8bfd04a1e3d01801691c80c2
[ "JavaScript" ]
5
JavaScript
anacmm/PocUsability
6c3bc4efd4c9b7cc68680f204e962fd9800f7612
97a36051ecbcc207d86696f2c7e2ae7a23775b53
refs/heads/main
<file_sep>import React from "react"; import styled from "styled-components"; const Button = (props) => { const { _onClick, children, ...rest } = props; return <ButtonEle {...rest} onClick={_onClick }>{children}</ButtonEle>; }; Button.defaultProps = { children: null, bg_color: "#0E693F", width: "100%", margin: "auto", height: "100%", _onClick: () => {}, type: "button", hover_color: "white", border_radius: "0px", }; const ButtonEle = styled.button` border: none; width: ${(props) => props.width}; height: ${(props) => props.height}; margin: ${(props) => props.margin}; background-color: ${(props) => props.bg_color}; color: ${(props) => props.hover_color}; border-radius: ${(props) => props.border_radius}; transition: background-color 0.3s; :hover { cursor: pointer; background-color: ${(props) => props.hover_color}; color: ${(props) => props.bg_color}; border: 1px solid ${(props) => props.bg_color}; } `; export default Button; <file_sep>import React from "react"; import Calendar from "../components/Calendar"; import Slider from "../components/Slider"; import Review from "../components/Review"; import { Button, Grid, Input, Text } from "../elements"; import styled from "styled-components"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faArrowCircleUp } from "@fortawesome/free-solid-svg-icons"; import theme from "../shared/theme"; const Main = (props) => { const handleUp = () => { window.scrollTo({ top: 0, left: 0, behavior: "smooth" }); }; return ( <React.Fragment> <Grid width="800px"> <Grid padding="10px 0 10px 0" width="800px"> <Slider /> </Grid> <Calendar /> <Grid> <Review /> </Grid> </Grid> <UpDiv onClick={handleUp}> <FontAwesomeIcon icon={faArrowCircleUp} size="4x" /> </UpDiv> </React.Fragment> ); }; const UpDiv = styled.div` color: ${theme.bgColor}; position: sticky; width: 64px; background-color: ${theme.fontColor}; height: 64px; bottom: 50px; left: 2%; border-radius: 50%; transition: background-color 0.3s; :hover { cursor: pointer; background-color: ${theme.bgColor}; color: ${theme.fontColor}; } `; export default Main; <file_sep>import React, { useState } from "react"; import { format } from "date-fns"; import { enGB } from "date-fns/locale"; import { DateRangePickerCalendar, START_DATE } from "react-nice-dates"; import "react-nice-dates/build/style.css"; import { Button, Text, Grid } from "../elements"; import SearchRoom from "./SearchRoom"; import theme from "../shared/theme"; import CountCustomer from "./CountCustomer"; import { useDispatch, useSelector } from "react-redux"; import RoomTypeSelector from "./RoomTypeSelector"; import { actionGetOneRoom } from "../redux/modules/room"; const Calendar = () => { const [startDate, setStartDate] = useState(); const [endDate, setEndDate] = useState(); const [focus, setFocus] = useState(START_DATE); const dispatch = useDispatch(); //각각 토글 const [toggleCalender, settoggleCalender] = useState(false); const [toggleCheckPerson, settoggleCheckPerson] = useState(false); const [toggleSearch, setSearch] = useState(false); //인원 const adult = useSelector((state) => state.calendar.result.adult); const child = useSelector((state) => state.calendar.result.children); const roomType = useSelector((state) => state.calendar.result.roomType); //고른 방의 타입 추후 아이디값과 비교하여 전달 const calendarToggle = () => { if (toggleSearch) { window.alert("조회하기 버튼을 다시 눌러주세요."); return; } settoggleCalender((prev) => !prev); }; const personToggle = () => { if (toggleSearch) { window.alert("조회하기 버튼을 다시 눌러주세요."); return; } settoggleCheckPerson((prev) => !prev); }; const searchToogle = () => { if (!startDate || !endDate || !adult || !roomType) { window.alert("선택사항을 모두 선택해 주세요"); return; } if (startDate < new Date()) { window.alert("오늘 날짜 이상을 설정해 주세요"); return; } if (toggleCalender) { settoggleCalender((prev) => !prev); } if (toggleCheckPerson) { settoggleCheckPerson((prev) => !prev); } dispatch(actionGetOneRoom()); setSearch((prev) => !prev); }; const handleFocusChange = (newFocus) => { setFocus(newFocus || START_DATE); }; return ( <> <Grid is_flex margin="0 auto 10px auto" width="800px" height="70px" bg={theme.gridBgColor} border_radius={theme.borderRadius} > <Grid _onClick={calendarToggle} border_radius={theme.borderRadius} bg={theme.innerBoxColor} is_flex width="450px" > <Text margin="0 0 0 30px" color={theme.fontColor} bold size="16px"> Reservation : </Text> <Grid is_flex bg={theme.bgColor} height="50px" width="130px" border_radius={theme.borderRadius} > <Text color={theme.fontColor} bold size="15px"> {startDate ? format(startDate, "yyyy-MM-dd", { locale: enGB }) : ""} </Text> </Grid> <Grid is_flex bg={theme.bgColor} height="50px" width="130px" border_radius={theme.borderRadius} > <Text color={theme.fontColor} bold size="15px"> {endDate ? format(endDate, " yyyy-MM-dd", { locale: enGB }) : ""} </Text> </Grid> </Grid> <Button bg_color={theme.innerBoxColor} width="120px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} _onClick={calendarToggle} margin="0 0 0 10px" > <Text size="17px" bold color="white"> 날짜선택 </Text> </Button> <Button bg_color={theme.innerBoxColor} width="120px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} _onClick={personToggle} margin="0 10px" > <Text color="white" bold size="17px"> 상세선택 </Text> </Button> <Button bg_color={theme.innerBoxColor} width="120px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} _onClick={searchToogle} > <Text size="17px" bold color="white"> 조회하기 </Text> </Button> </Grid> {toggleCheckPerson && ( <> {/* 인원추가 창 */} <CountCustomer /> {/* 상세선택 창 */} <RoomTypeSelector /> </> )} {/* 캘린더 */} {toggleCalender && ( <Grid margin="auto" width="800px" bg="rgba(153, 153 ,153 ,0.4)" border_radius="20px" > <DateRangePickerCalendar startDate={startDate} endDate={endDate} focus={focus} onStartDateChange={setStartDate} onEndDateChange={setEndDate} onFocusChange={handleFocusChange} locale={enGB} /> </Grid> )} {toggleSearch && ( <Grid width="800px" margin="0 auto 10px auto"> <SearchRoom startDate={startDate} endDate={endDate} adult={adult} child={child} roomType={roomType} /> </Grid> )} </> ); }; export default Calendar; <file_sep>import React from "react"; import { history } from "../redux/configStore"; import { Button, Grid, Image, Text } from "../elements"; import theme from "../shared/theme"; import { useSelector, useDispatch } from "react-redux"; import { deleteReview, deleteReviewDB} from "../redux/modules/review"; import reviewImg from '../img/review_img.jpeg' import moment from "moment"; const CardDetail = (props) => { const dispatch = useDispatch(); const user_name = useSelector((state) => state.user.user_info.nickname) //props const {title, _id, content, date, userId, nickname, user_profile, image_url} = props const insert_d = moment(date).format("dddd MMM Do YY"); //deleteBtn const deleteBtn = () => { let result = window.confirm("정말 삭제하시겠어요?"); result ? dispatch(deleteReviewDB(_id)) : history.push("/"); }; //editBtn const editBtn = () => { history.push(`/review/${_id}`); }; return ( <Grid width="800px" height="530px" bg={theme.gridBgColor} border_radius={theme.borderRadius} is_flex > {/** 이미지 */} <Grid width="480px" height="450px" margin="0 10px 0 20px"> <Image src={reviewImg} border_radius={theme.borderRadius} /> </Grid> {/**제목, 내용 */} <Grid width="240px" height="445px" bg={theme.innerBoxColor} border_radius={theme.borderRadius} > <Grid width="90%" height="5%" align="right" padding="7% 0px 0px 0px"> <Text color={"white"} size="17px" bold> {insert_d} </Text> </Grid> <Grid is_flex width="200px" height="250px"> <Text size="20px" bold color={theme.fontColor} lineHeight="30px"> {content} </Text> </Grid> {user_name === nickname && ( <Grid width="200px" height="70px"> <Grid is_flex> <Button key={_id} border_radius={theme.borderRadius} height="40px" hover_color={theme.hoverColor} _onClick={editBtn} > <Text size="20px" bold color={theme.fontColor}> 수정하기 </Text> </Button> </Grid> <Grid is_flex> <Button border_radius={theme.borderRadius} height="40px" hover_color={theme.hoverColor} _onClick={deleteBtn} > <Text size="20px" bold color={theme.fontColor}> 삭제하기 </Text> </Button> </Grid> </Grid> )} </Grid> </Grid> ); }; CardDetail.defaultProps = { //나중에 user_profile: "https://abs.twimg.com/sticky/default_profile_images/default_profile_400x400.png", image_url: "https://ak-d.tripcdn.com/images/022621200084a4yua0A11_R_600_400_R5_D.jpg_.webp", //db _id: "60ec33bc4a02d368fdf9170c", title: "좋아요", content: "please....?????", date: "Mon Jul 12 2021", userId: { _id: "60ec30cbff7f286051745a60", }, nickname: "garden1" } export default CardDetail; <file_sep>import React from "react"; import { useHistory } from "react-router-dom"; import { Button, Grid, Text } from "../elements"; import theme from "../shared/theme"; import ReviewCard from "./ReviewCard"; import { useSelector, useDispatch} from 'react-redux'; import { getReview, getReviewDB } from '../redux/modules/review'; import styled from "styled-components"; const Review = () => { const history = useHistory(); const is_login = useSelector((state) => state.user.is_login); const handleOnReview = () => { if(!is_login) { let result = window.confirm('로그인이 필요해요! 로그인 페이지로 이동할까요?') result ? history.push('/login') : history.push('/'); } if(is_login) { history.push("/review"); } }; const dispatch = useDispatch(); const review_list = useSelector((state)=>state.review.list) React.useEffect(() => { dispatch(getReviewDB()) },[]) return ( <Grid margin="10px auto 10px auto" width="800px"> <Grid margin="10px auto 10px auto" height="70px" border_radius={theme.borderRadius} > {/* 클릭하면 글 쓰기 페이지*/} <GoReviewWrite onClick={handleOnReview} > <Text size="20px" bold={true} color={theme.fontColor}> ✔ 호텔 후기 작성하러 가기 ✔ </Text> </GoReviewWrite> </Grid> {review_list.map((r, idx) => { return <ReviewCard key={r.id} {...r}/> })} </Grid> ); }; const GoReviewWrite = styled.button` border-radius: 20px; background-color: #1f2e3b; width:50%; border: none; height:100%; display: block; margin:auto; :hover { background-color: rgba(52, 118, 88, 0.5) ; } `; export default Review; <file_sep>import { createSlice } from "@reduxjs/toolkit"; import axios from "axios"; import { getCookie } from "../../shared/cookie"; const initialState = { list: [], room: { _id: "60e9448c4e03c013b8c05810", name: "디럭스룸", image: "https://sbti.kosmes.or.kr/images/content/img_SHSTI040M0_01_01.jpg", price: 3000000, }, }; const room = createSlice({ name: "room", initialState, reducers: { setRooms: (state, action) => { state.list = [...action.payload]; }, setRoom: (state, action) => { state.room = action.payload; }, }, }); //{ autherization : `Bearer ${token}` } const instance = axios.create({ baseURL: "http://3.35.173.0:3000", headers: { authorization: `Bearer ${getCookie("token")}` }, }); export const actionGetRooms = () => async (dispatch, getState, { history }) => { try { const data = await instance.get("/api/room"); const room_list = data.data.rooms; dispatch(setRooms(room_list)); } catch (error) { window.alert(error.message); } }; export const actionGetOneRoom = () => async (dispatch, getState, { history }) => { const room_id = getState().calendar.result.room_id; try { const get_room = await instance.get(`/api/room/${room_id}`); const room = { _id: get_room.data.room._id, name: get_room.data.room.name, image: get_room.data.room.image, price: get_room.data.room.price, }; if (get_room.data.message !== "success") { window.alert(get_room.data.message); } dispatch(setRoom(room)); } catch (error) { window.alert(error.message); } }; export const { setRooms, setRoom } = room.actions; export default room; <file_sep>import { createSlice } from "@reduxjs/toolkit"; const room_id = { Deluxe: "60e9448c4e03c013b8c05810", Suite: "60e9449c4e03c013b8c05812", Superior: "60e944a84e03c013b8c05814", "On-dol": "60e944b94e03c013b8c05816", Single: "60e944c54e03c013b8c05818", }; const initialState = { result: { adult: 0, children: 0, roomType: null, room_id: "", }, }; const calendar = createSlice({ name: "calendar", initialState, reducers: { actionAddAdult: (state, action) => { state.result.adult += 1; }, actionDelAdult: (state, action) => { state.result.adult -= 1; }, actionAddChild: (state, action) => { state.result.children += 1; }, actionDelChild: (state, action) => { state.result.children -= 1; }, actionTypeSelector: (state, action) => { state.result.roomType = action.payload; state.result.room_id = room_id[action.payload]; }, }, }); export const { actionAddAdult, actionDelAdult, actionAddChild, actionDelChild, actionTypeSelector, } = calendar.actions; export default calendar; <file_sep>import { createStore, combineReducers, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import { createBrowserHistory } from "history"; import { connectRouter } from "connected-react-router"; // module import calendar from "./modules/calendar"; import review from "./modules/review"; import user from "./modules/user"; import room from "./modules/room"; import book from "./modules/book"; // base url http://172.16.58.3:3000/ //히스토리 객체 만들기 export const history = createBrowserHistory(); //루트 리듀서 - (수정) //combineReducers({ bucket, a, b... }); const rootReducer = combineReducers({ book: book.reducer, user: user.reducer, room: room.reducer, calendar: calendar.reducer, review: review.reducer, //만든 히스토리를 리듀서에 넣어주기(히스토리와 라우터가 연결됨) router: connectRouter(history), }); //미들웨어 준비 > 히스토리를 이용해서 미들웨어 const middlewares = [thunk.withExtraArgument({ history: history })]; // 현재 환경 const env = process.env.NODE_ENV; // 개발환경- 로거 if (env === "development") { //require : 패키지 가지고 올 때 개발 환경에서만 필요한 패키지이기 때문에 불필요한 프로젝트 크기 확장을 막아줌 const { logger } = require("redux-logger"); middlewares.push(logger); } //redux devTools 설정 const composeEnhancers = typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize... }) : compose; //미들웨어 묶기 const enhancer = composeEnhancers(applyMiddleware(...middlewares)); let store = (initialStore) => createStore(rootReducer, enhancer); export default store(); <file_sep>import Text from './Text' import Button from './Button' import Grid from './Grid' import Image from './Image' import Input from './Input' export { Text, Button, Grid, Image, Input }<file_sep># 🧚🏻‍♀️항해99 미니프로젝트 14조 - 프론트(김나영, 이원교) 와이어프레임 : https://www.figma.com/file/O4IB0kbXsRz8xi6oZrjNLI/Untitled?node-id=0%3A1 ## 🙌🏻member ### view #### 나영 - 로그인 & 회원가입 / 리뷰 작성(+수정) / 선택 예약 확인 / 마이페이지 #### 원교 - 메인(룸타입 이미지 슬라이드 / 일정 선택 캘린더 / 리뷰 목록) ### function #### 나영 - 리뷰게시판 CRUD / 로그인 상태에서만 리뷰 Create 가능 / 내가 쓴 리뷰에서만 Update,Delete 가능 / 마이페이지 - 현재 예약 Road #### 원교 - 로그인&회원가입(토큰,쿠키 사용) / 선택 예약 확인 페이지 - 메인 페이지에서 선택한 예약 일정, 인원, 룸타입 확인 후 예약 Create / 마이페이지 - 현재 예약 Delete ## ✍🏻 프로젝트 소스 @최소단위 엘리먼트 - Grid - Text - Button - 로그인/회원가입/커뮤니티/예약 확인 - Image - 슬라이드 - Input (type : date) - 예약 일정 선택 ** - (ttl) index.js @ 컴포넌트 - RoomTimeChk - ReviewCard - Review - Detail - Write - Calendar - SearchRoom - Book_Calender - CardDetail - CountCustomer - RoomTypeSelector - Slider @shared - Thema - Header - App - cookie - Permit <file_sep>import React from 'react'; import { Grid, Button, Input, Text, Image } from "../elements"; import Book_list from './Book_list'; import {actionUserBookInfo} from '../redux/modules/book'; import {useDispatch, useSelector} from 'react-redux'; const Book_Detail = (props) => { const dispatch = useDispatch(); React.useEffect(() => { dispatch(actionUserBookInfo()) },[]) const book_list = useSelector((state) => state.book.user_book_info) return ( <React.Fragment> <Grid> {/* 예약 타이틀 */} <Grid height="5%"> <Text color={'white'} bold size="30px">다가오는 예약</Text> </Grid> {book_list.map((b,idx) => { return ( <Grid height="auto" margin="3% 0px"> <Book_list key={b.id} {...b}/> </Grid> ) })} </Grid> </React.Fragment> ); } export default Book_Detail;<file_sep>import React from "react"; import styled from "styled-components"; import theme from "./theme"; import { Button, Grid, Text } from "../elements"; import { useHistory } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { actionLogOut } from "../redux/modules/user"; const Header = (props) => { const is_login = useSelector((state) => state.user.is_login); const dispatch = useDispatch(); const history = useHistory(); const handleClickLogin = () => { history.push("/login"); }; const handleClickRegister = () => { history.push("/register"); }; const GoMyPage = () => { history.push("/mypage"); }; const handleLogout = () => { dispatch(actionLogOut()); }; return ( <Grid is_flex={true} height="120px" bg="rgba(52, 118, 88, 0.5)"> <DivForFlex /> <Grid is_flex={true}> <A href="/"> <Text color="ivory" size="50px" bold={true}> Hotel Fourteen </Text> </A> </Grid> {!is_login && ( <ButtonDiv> <Button width="130px" height="35px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} margin="0 15px" _onClick={handleClickLogin} > <Text color="ivory" size="17px"> 로그인 </Text> </Button> <Button width="130px" height="35px" border_radius="18px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} margin="" _onClick={handleClickRegister} > <Text color="ivory" size="17px"> 회원가입 </Text> </Button> </ButtonDiv> )} {is_login && ( <ButtonDiv> <Button width="130px" height="35px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} margin="0 15px" _onClick={GoMyPage} > <Text color="ivory" size="17px"> 마이페이지 </Text> </Button> <Button width="130px" height="35px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} margin="" _onClick={handleLogout} > <Text color="ivory" size="17px"> 로그아웃 </Text> </Button> </ButtonDiv> )} </Grid> ); }; const DivForFlex = styled.div` width: 100%; `; const ButtonDiv = styled.div` width: 100%; height: 100%; display: flex; align-items: flex-end; justify-content: center; padding-bottom: 30px; `; const A = styled.a` text-decoration: none; `; export default Header; <file_sep>import React from "react"; import styled from "styled-components"; import { Text } from "../elements"; const Input = (props) => { const { width, padding, bg, name, height, border, size, margin, label, value, placeholder, _onChange, type, need_value, multiline, border_radius, color, multiline_noValue, } = props; const styles = { padding: padding, width: width, margin: margin, height: height, border: border, size: size, bg: bg, border_radius, color, }; if (need_value) { return ( <React.Fragment> <Text>{label}</Text> <InputBox {...styles} placeholder={placeholder} type={type} onChange={_onChange} value={value} /> </React.Fragment> ); } if (multiline) { return ( <React.Fragment> <TextArea rows={17} {...styles} placeholder={placeholder} type={type} onChange={_onChange} value={value} /> </React.Fragment> ); } if (multiline_noValue) { return ( <React.Fragment> <TextArea rows={17} {...styles} placeholder={placeholder} type={type} onChange={_onChange} /> </React.Fragment> ); } return ( <React.Fragment> <Text>{label}</Text> <InputBox {...styles} placeholder={placeholder} type={type} name={name} onChange={_onChange} required /> </React.Fragment> ); }; Input.defaultProps = { width: "100%", padding: false, height: "100%", border: false, size: "14px", margin: false, label: "", value: "", placeholder: "", _onChange: () => {}, type: "text", need_value: false, multiline: false, name: "", bg: null, border_radius: "", color: "", multiline_noValue:"", }; const InputBox = styled.input` border: none; width: ${(props) => props.width}; height: ${(props) => props.height}; padding: ${(props) => props.padding}; border: ${(props) => props.border}; font-size: ${(props) => props.size}; margin: ${(props) => props.margin}; background-color: ${(props) => props.bg}; border-radius: ${(props) => props.border_radius}; border: none; color: ${(props) => props.color}; //css 만들면 focus 조절 `; const TextArea = styled.textarea` width: ${(props) => props.width}; height: ${(props) => props.height}; resize: none; padding: ${(props) => props.padding}; border: ${(props) => props.border}; font-size: ${(props) => props.size}; margin: ${(props) => props.margin}; background-color: ${(props) => props.bg}; border-radius: ${(props) => props.border_radius}; border: none; color: ${(props) => props.color}; //css 만들면 focus 조절 `; export default Input; <file_sep>import React from "react"; import { Helmet } from "react-helmet-async"; const MetaScript = () => { return ( <Helmet> <title>Hotel Fourteen</title> <meta property="og:title" content="Hotel Fourteen" /> <meta property="og:description" content="국내 유일의 6성급 호텔." /> <meta property="og:image" content="../img/review_img.jpeg" /> </Helmet> ); }; export default MetaScript; <file_sep>import React, { useState } from "react"; import { Button, Grid, Image, Text } from "../elements"; import theme from "../shared/theme"; import CardDetail from "./CardDetail"; import profile_img from '../img/favicon4.PNG' const ReviewCard = (props) => { const [detail_toggle, setToggle] = useState(false); const handleToggleChange = () => { setToggle((prev) => !prev); console.log(detail_toggle); }; //props const {title, _id, content, date, userId, nickname, user_profile, image_url} = props return ( <> <Grid width="800px" margin="0 0 10px 0" is_flex height="70px" bg={theme.innerBoxColor} border_radius={theme.borderRadius} > <Grid padding="0 20px 0 20px" is_flex> <Grid is_flex> <Image width="50px" height="50px" src={user_profile} border_radius="50%" /> <Grid width="auto" padding="3.5% 0px 3.5% 2%"> <Text color={'white'} size="16px">{nickname}</Text> </Grid> <Grid width="300px" is_flex> <Text size="15px" color={theme.fontColor} bold> {title} </Text> </Grid> <Grid is_flex height="50px" width="300px"> <Button bg_color={theme.hoverColor} border_radius={theme.borderRadius} hover_color={theme.bgColor} _onClick={handleToggleChange} > <Text color={theme.fontColor} size="20px"> 상세보기 </Text> </Button> </Grid> </Grid> </Grid> </Grid> {detail_toggle && ( <CardDetail {...props} /> )} </> ); }; ReviewCard.defaultProps = { //나중에 user_profile: profile_img, image_url:"https://lh3.googleusercontent.com/proxy/-r05vLKRnd5jp9TZLDaB_RVMizXrL3YwmF1oeRf5CI17-_koilXwJLsLPxAzruFd3mPi0GRRNiDOEUVTmWt2DdltIoYF6-fQvlPqvdVLMSzVcMKULykNDz1V8XQSfkCEfQ", //db _id: "60ec33bc4a02d368fdf9170c", title: "좋아요", content: "please....?????", date: "Mon Jul 12 2021 21:21:16 GMT+0900 (Korean Standard Time)", userId: { _id: "60ec30cbff7f286051745a60", }, nickname: "garden1", } export default ReviewCard; <file_sep>import React from "react"; import { useDispatch, useSelector } from "react-redux"; import { Button, Grid, Text } from "../elements"; import { actionTypeSelector } from "../redux/modules/calendar"; import theme from "../shared/theme"; const RoomTypeSelector = () => { const roomType = useSelector((state) => state.calendar.result.roomType); const dispatch = useDispatch(); const selectDeluxe = () => { dispatch(actionTypeSelector("Deluxe")); }; const selectSuite = () => { dispatch(actionTypeSelector("Suite")); }; const selectSuperior = () => { dispatch(actionTypeSelector("Superior")); }; const selectOn_dol = () => { dispatch(actionTypeSelector("On-dol")); }; const selectSingle = () => { dispatch(actionTypeSelector("Single")); }; return ( <Grid is_flex={true} margin="0 auto 10px auto" width="800px" height="70px" bg={theme.gridBgColor} border_radius={theme.borderRadius} > <Button width="130px" height="70px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} _onClick={selectDeluxe} > <Text size="20px" bold={true} color="white"> Deluxe </Text> </Button> <Button width="130px" height="70px" border_radius={theme.borderRadius} hover_color={theme.hoverColor} _onClick={selectSuite} > <Text size="20px" bold={true} color="white"> Suite </Text> </Button> <Button width="130px" height="70px" border_radius="20px" hover_color="rgba(52, 118, 88, 0.5)" _onClick={selectSuperior} > <Text size="20px" bold={true} color="white"> Superior </Text> </Button> <Button width="130px" height="70px" border_radius="20px" hover_color="rgba(52, 118, 88, 0.5)" _onClick={selectOn_dol} > <Text size="20px" bold={true} color="white"> On-dol </Text> </Button> <Button width="130px" height="70px" border_radius="20px" hover_color="rgba(52, 118, 88, 0.5)" _onClick={selectSingle} > <Text size="20px" bold={true} color="white"> Single </Text> </Button> <Grid border_radius="20px" bg="rgba(255,255,255, 0.8)" is_flex={true} width="130px" > <Text size="20px" bold={true} color="#0E693F"> {roomType ? `✔ ${roomType}` : "선택사항"} </Text> </Grid> </Grid> ); }; export default RoomTypeSelector; <file_sep>import React from "react"; import styled from "styled-components"; import { Button, Grid, Input, Text } from "../elements"; import * as Yup from "yup"; import { useFormik } from "formik"; import theme from "../shared/theme"; import { useDispatch } from "react-redux"; import { actionSignupForDb } from "../redux/modules/user"; //박스 배경 색 #1f2e3b //회원가입 버튼 색 #376a48 const SignUp = (props) => { const dispatch = useDispatch(); const formik = useFormik({ initialValues: { userId: "", userName: "", pwd: "", pwdCheck: "", }, validationSchema: Yup.object({ userId: Yup.string() .email("이메일 형식이 아닙니다.") .required("아이디를 입력해주세요!"), userName: Yup.string().required("이름을 입력해주세요."), pwd: Yup.string() .min(4, "비밀번호는 4자리 이상이여야 합니다.") .matches(/[a-zA-Z]/, "패스워드에는 반드시 영문을 포함해야합니다.") .required("패스워드를 입력해주세요."), pwdCheck: Yup.string() .min(4, "비밀번호는 4자리 이상이여야 합니다.") .required("패스워드를 재입력해주세요") .oneOf([Yup.ref("pwd"), null], "비밀번호가 일치하지 않습니다."), }), onSubmit: (values) => { // dispatch 자리 dispatch(actionSignupForDb(values)); }, }); //input 입력값 확인을 위한 함수 // const [id, setId] = React.useState(""); // const [user_name, setUserName] = React.useState(""); // const [pw, setPw] = React.useState(""); // const [pw_chk, setPwChk] = React.useState(""); // const input_ID = (e) => { // setId(e.target.value) // } // const input_UserName = (e) => { // setUserName(e.target.value) // } // const input_Pw = (e) => { // setPw(e.target.value) // } // const input_PwChk = (e) => { // setPwChk(e.target.value) // } // //회원가입 버튼 // const registerBtn = () => { // console.log(id, user_name, pw, pw_chk) // } return ( //회원가입 레이아웃 //inputboxs <Grid bg={"#1f2e3b"} width="800px" height="100%" margin="7% auto" border_radius={theme.borderRadius} > {/* register글씨 */} <Box> <Text color={theme.fontColor} size="60px" bold> Register </Text> </Box> {/* //action="" accept-charset="utf-8" method="post" */} <FromBox name="registerForm" onSubmit={formik.handleSubmit}> {/* 아이디 input */} <Grid width="400px" height="80px" padding="3% 0px"> <Text bold color={theme.fontColor} size="20px"> 이메일 </Text> <Input padding="0px 1%;" placeholder="이메일을 입력해주세요." // _onChange={input_ID} id="userId" name="userId" type="userId" _onChange={formik.handleChange} value={formik.values.userId} height="40px" border_radius="15px" margin="10px 0 10px 0" /> {/* 닉네임 input */} {formik.touched.userId && formik.errors.userId ? ( <HelperMsg>{formik.errors.userId}</HelperMsg> ) : null} </Grid> <Grid width="400px" height="80px" padding="3% 0px"> <Text bold color={theme.fontColor} size="20px"> 닉네임 </Text> <Input padding="0px 1%;" placeholder="닉네임을 입력해주세요." // _onChange={input_UserName} id="userName" name="userName" type="userName" _onChange={formik.handleChange} value={formik.values.userName} height="40px" border_radius="15px" margin="10px 0 10px 0" /> {formik.touched.userName && formik.errors.userName ? ( <HelperMsg>{formik.errors.userName}</HelperMsg> ) : null} </Grid> {/* 비밀번호 input */} <Grid width="400px" height="80px" padding="3% 0px"> <Text bold color={theme.fontColor} size="20px"> 비밀번호486 </Text> <Input padding="0px 1%;" placeholder="비밀번호를 입력해주세요." // _onChange={input_Pw} id="pwd" name="pwd" type="password" _onChange={formik.handleChange} value={formik.values.pwd} height="40px" border_radius="15px" margin="10px 0 10px 0" /> {formik.touched.pwd && formik.errors.pwd ? ( <HelperMsg>{formik.errors.pwd}</HelperMsg> ) : null} </Grid> {/* 비밀번호 확인 input */} <Grid width="400px" height="80px" padding="3% 0px"> <Text bold color={theme.fontColor} size="20px"> 비밀번호 확인 </Text> <Input padding="0px 1%;" placeholder="비밀번호를 확인해주세요." // _onChange={input_PwChk} id="pwdCheck" name="pwdCheck" type="password" _onChange={formik.handleChange} value={formik.values.pwdCheck} height="40px" border_radius="15px" margin="10px 0 10px 0" /> {formik.touched.pwdCheck && formik.errors.pwdCheck ? ( <HelperMsg>{formik.errors.pwdCheck}</HelperMsg> ) : null} </Grid> {/* 회원가입 버튼 */} <Grid width="150px" height="70px" padding="5% 0px 3% 0px"> <InputBtn type="submit" value="회원가입" /> {/* <Button bg_color={"#376a48"} _onClick={registerBtn}>회원가입</Button> */} </Grid> </FromBox> </Grid> ); }; const Box = styled.div` width: 100%; height: 10%; padding: auto; text-align: center; padding-top: 3%; `; const FromBox = styled.form` width: 70%; height: 100%; margin: 2% auto; `; const InputBtn = styled.input` width: 100%; height: 40px; border-radius: 30px; font-weight: 700; border: none; color: white; background-color: #376a48; margin: auto; align-content: center; `; const HelperMsg = styled.div` text-decoration: underline; font-size: 15px; font-weight: 600; color: ${theme.warningColor}; `; export default SignUp; <file_sep>import React from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import Book_Calender from "../components/Book_Calendar"; import { Grid, Button, Input, Text } from "../elements"; import theme from "../shared/theme"; //오로라 // import book_Video from '../video/pexels-nicolas-becker-5600929.mp4' //폭죽 import book_Video from "../video/video (1).mp4"; import { format } from "date-fns"; import { enGB } from "date-fns/locale"; import { actionBookingforDb } from "../redux/modules/book"; const Book = (props) => { //현재 이메일 const user_name = useSelector((state) => state.user.user_info.nickname); const book_info = useSelector((state) => state.book.book_info); const dispatch = useDispatch(); const day_arr = ["일", "월", "화", "수", "목", "금", "토"]; const startDate = `${format(book_info.startDate, "yyyy년 MM월 dd일", { locale: enGB, })} (${day_arr[new Date(book_info.startDate).getDay()]}) `; const endDate = `${format(book_info.endDate, "yyyy년 MM월 dd일", { locale: enGB, })} (${day_arr[new Date(book_info.endDate).getDay()]}) `; const handleReservation = () => { dispatch(actionBookingforDb()); }; return ( <React.Fragment> {/* 글쓰기 상자 */} <Grid is_flex bg={theme.gridBgColor} width="70%" height="100vh" margin="2% auto" padding="5% 3% 0px 6%" border_radius={theme.borderRadius} > {/* flex 좌측 */} <Grid> {/* 호텔 이미지 = 선택한 이미지 자동으로 불러오기 가능할까? */} <Book_vid controls autoPlay loop muted> <source src={book_Video} type="video/mp4" /> </Book_vid> {/* <Image src="https://mblogthumb-phinf.pstatic.net/MjAxNjEyMjFfNjUg/MDAxNDgyMjg1MjA1MDEx.j_Ec0Ee48Q7hnCBiO8i9f-G251y7VgSuE-kjY_-JkGUg.sx5FORfY7C7W3KQLfPRMsi8EbjaSXDm9FefuUQPZnG8g.JPEG.chalet_swiss/image_251768691482284708664.jpg?type=w800" width="100%" height="400px" /> */} </Grid> {/* flex 우측 - textarea */} <Grid> {/* 예약 확인 - 유저 네임 받기*/} <Grid bg={theme.innerBoxColor} height="30%" width="80%" align="center" padding="5% 0px" border_radius={theme.borderRadius} > <Text size="25px" color="white" bold> {user_name}, 예약을 확인해주세요! </Text> {/* 체크인-아웃 > 사이드로 해야해서 플렉스*/} <Grid is_flex margin="5% 0px 0px 0px" height="auto"> <Grid> <Title>Check-In</Title> <Title>이후 오후 3:00</Title> </Grid> <Grid> <Title>Check-Out</Title> <Title>이전 오전 12:00</Title> </Grid> </Grid> <Grid height="auto" margin="7% 0px 4% 0px"> {/* 데이터로 넘어온 날짜값 */} <Title> {startDate} - {endDate} </Title> {/* 데이터로 넘어온 인원 수 */} <Title> 숙박 인원 : 성인 {book_info.adult}명, 소아 {book_info.child} 명 </Title> </Grid> <hr /> <Grid is_flex height="auto" margin="6% 0px 0px 0px"> <Grid> <Text color="white" size="18px" bold> 합계 </Text> </Grid> {/* 데이터로 넘어온 가격 */} <Grid> <Text color="white" size="18px" bold> {book_info.price.toLocaleString()}원 </Text> </Grid> </Grid> </Grid> {/* 캘린더 */} <Grid height="auto" margin="5% 0px 0px 0px"> <Book_Calender /> </Grid> {/* 예약 하기 버튼 */} <ReserveBtn onClick={handleReservation}>예약하기</ReserveBtn> </Grid> </Grid> </React.Fragment> ); }; const Title = styled.p` color: white; margin-top: 4%; `; const Book_vid = styled.video` width: 100%; height: 90%; object-fit: fill; border-radius: 20px; `; const ReserveBtn = styled.button` width: 150px; height: 50px; border-radius: 30px; background-color: rgba(31, 46, 59); margin: 5% auto; border: none; color: white; display: block; font-size: 15px; font-weight: bold; `; export default Book; <file_sep>// //1. 우선적으로 필요한 액션 addPost, getPost // //2. 다음 순위 updatePost, deletePost // //import import { createSlice } from "@reduxjs/toolkit"; import axios from "axios"; import { getCookie } from "../../shared/cookie"; // //axios const instance = axios.create({ baseURL: "http://3.35.173.0:3000", headers: { authorization: `Bearer ${getCookie("token")}` }, }); export const addReviewDB = (title, content) => { return function (dispatch, getState, { history }) { instance .post("/api/review", { title: title, content: content }) .then((res) => { console.log(res); window.alert("리뷰 작성을 완료하였어요!"); dispatch(addReview(title, content)); history.push("/"); }) .catch((err) => { window.alert("리뷰 작성에 오류가 있어요! 관리자에게 문의해주세요."); console.log(err); }); }; }; export const getReviewDB = () => { return function (dispatch, getState, { history }) { instance .get("/api/review") .then((res) => { let content_list = res.data.reviews; dispatch(getReview(content_list)); }) .catch((err) => { window.alert("페이지에 오류가 있어요! 관리자에게 문의해주세요."); console.log(err); }); }; }; export const deleteReviewDB = (reviewId) => { return function (dispatch, getState, { history }) { instance .delete(`/api/review/${reviewId}`) .then((res) => { console.log(res); window.alert("리뷰가 삭제되었습니다!"); dispatch(deleteReview(reviewId)); history.replace("/"); }) .catch((err) => { window.alert("앗! 리뷰 삭제에 오류가 있어요! 관리자에게 문의해주세요"); console.log("err"); }); }; }; export const updateReviewDB = (title, content, reviewId) => { return function (dispatch, getState, { history }) { instance .put(`/api/review/${reviewId}`, { title: title, content: content }) .then((res) => { console.log(res); window.alert("수정이 완료되었어요!"); history.replace("/"); }) .catch((err) => { window.alert("리뷰 수정에 오류가 있어요! 관리자에게 문의해주세요."); console.log(err); }); }; }; const initialState = { list: [], }; //리덕스 const review = createSlice({ name: "review", initialState, reducers: { addReview: (state, action) => { const title = action.payload.title; const content = action.payload.content; state.list.push({ title, content }); }, getReview: (state, action) => { state.list = action.payload; }, deleteReview: (state, action) => { let idx = state.list.findIndex((r) => r._id === action.payload); if (idx !== -1) { state.list.splice(idx, 1); } }, updateReview: (state, action) => {}, }, }); export const { addReview, getReview, deleteReview, updateReview } = review.actions; export default review;
67cf3e07cc68b79671c7671ae154794f8f55b1aa
[ "JavaScript", "Markdown" ]
19
JavaScript
skdud4659/HotelFourteen_FE
8ab9229b98a3b16727c9b546889df15e17502d1f
1dec01de3098d259dc08aadbec0e2ea0d79b4875
refs/heads/master
<repo_name>azhabinsky/mentor_digital_angularjs_test<file_sep>/src/js/app.module.js (function() { 'use strict'; angular .module('app', [ 'ngRoute', 'ngAnimate', 'ui.utils.masks', 'app.contacts' ]) .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.html5Mode(true); $routeProvider.otherwise({redirectTo: '/'}); }]) .run(['$rootScope', '$route', function($rootScope, $route) { $rootScope.$on('$routeChangeSuccess', function() { document.title = $route.current.title; }); }]); })(); <file_sep>/src/js/services/data.service.js (function() { 'use strict'; angular .module('app') .factory('dataservice', ['$http', '$location', 'exception', function($http, $location, exception) { var service = { getContacts: getContacts }; return service; function getContacts() { return $http.get('/api/contacts') .then(getContactsComplete) .catch(getContactsFailed); function getContactsComplete(data, status, headers, config) { return data.data; } function getContactsFailed(e) { $location.url('/'); return exception.catcher('XHR Failed for getContacts')(e); } } }]); })(); <file_sep>/README.md Installation //development tools installation: 1. npm install //related libs installation: 2. bower install The project uses GulpJS task-runner. To run app for development (without minifyed assets) use this command: gulp build-dev To run app for production (with minifyed assets) use this command: gulp build-prod <file_sep>/src/server/routes/index.js module.exports = function(app) { var api = '/api/'; var data = '/../data/'; var jsonfileservice = require('../utils/jsonfileservice')(); var four0four = require('../utils/404')(); app.get(api + 'contacts', getContacts); app.get(api + '*', four0four.notFoundMiddleware); function getContacts(req, res, next) { var msg = 'contacts not found. '; try { var json = jsonfileservice.getJsonFromFile(data + 'contacts.json'); if (json) { res.send(json); } else { four0four.send404(req, req, msg); } } catch (ex) { four0four.send404(req, res, msg + ex.message); } } }; <file_sep>/gulpfile.js var args = require('yargs').argv; var browserSync = require('browser-sync'); var config = require('./gulp.config')(); var del = require('del'); var gulp = require('gulp'); var path = require('path'); var port = process.env.PORT || config.defaultPort; var $ = require('gulp-load-plugins')({lazy: true}); var _ = require('lodash'); var runSequence = require('run-sequence'); gulp.task('help', $.taskListing); gulp.task('default', ['help']); gulp.task('vet', function() { log('Analyzing source with JSHint and JSCS'); return gulp .src(config.js.all) .pipe($.if(args.verbose, $.print())) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish', {verbose: true})) .pipe($.jshint.reporter('fail')) .pipe($.jscs()); }); gulp.task('js', function() { runSequence('js-app', 'js-libs'); }); gulp.task('js-app', function() { log('Processing app.js'); var files = [].concat( config.js.app, config.temp + config.templateCache.file ); return gulp .src(files) .pipe($.plumber()) .pipe($.concat('app.js')) .pipe(gulp.dest(config.build.dev + 'js')) .pipe($.uglify()) .pipe(gulp.dest(config.build.prod + 'js')); }); gulp.task('js-libs', function() { log('Processing JS libraries'); return gulp .src(config.js.libs) .pipe($.plumber()) .pipe($.concat('libs.js')) .pipe(gulp.dest(config.build.dev + 'js')) .pipe($.uglify()) .pipe(gulp.dest(config.build.prod + 'js')); }); gulp.task('clean-js', function() { log('Cleaning JS'); var files = [].concat( config.build.dev + 'js/*.*', config.build.prod + 'js/*.*' ); return clean(files); }); gulp.task('clean-custom-js', function() { log('Cleaning app.js'); var files = [].concat( config.build.dev + 'js/app.js', config.build.prod + 'js/app.js' ); return clean(files); }); gulp.task('clean-libs-js', function() { log('Cleaning libs.js'); var files = [].concat( config.build.dev + 'js/libs.js', config.build.prod + 'js/libs.js' ); return clean(files); }); gulp.task('styles', function() { runSequence('styles-custom', 'styles-libs'); }); gulp.task('styles-custom', function() { log('Compiling app Less --> CSS'); return gulp .src(config.css.custom) .pipe($.plumber()) .pipe($.less()) .pipe($.autoprefixer({browsers: ['last 2 versions', '> 5%']})) .pipe(gulp.dest(config.build.dev + 'styles')) .pipe($.cssmin()) .pipe(gulp.dest(config.build.prod + 'styles')); }); gulp.task('styles-libs', function() { log('Compiling libraries CSS'); return gulp .src(config.css.libs) .pipe($.plumber()) .pipe($.concat('libs.css')) .pipe(gulp.dest(config.build.dev + 'styles')) .pipe($.cssmin()) .pipe(gulp.dest(config.build.prod + 'styles')); }); gulp.task('clean-styles', function() { log('Cleaning styles'); var files = [].concat( config.build.dev + 'styles/*.*', config.build.prod + 'styles/*.*' ); return clean(files); }); gulp.task('clean-custom-styles', function() { log('Cleaning styles.css'); var files = [].concat( config.build.dev + 'styles/styles.css', config.build.prod + 'styles/styles.css' ); return clean(files); }); gulp.task('clean-libs-styles', function() { log('Cleaning libs.css'); var files = [].concat( config.build.dev + 'styles/libs.css', config.build.prod + 'styles/libs.css' ); return clean(files); }); gulp.task('fonts', function() { log('Copying fonts'); return gulp .src(config.fonts) .pipe(gulp.dest(config.build.dev + 'fonts')) .pipe(gulp.dest(config.build.prod + 'fonts')); }); gulp.task('clean-fonts', function() { return function() { clean(config.build.dev + 'fonts/**/*.*'); clean(config.build.prod + 'fonts/**/*.*'); }; }); gulp.task('images', function() { log('Compressing and copying images'); return gulp .src(config.images) .pipe($.imagemin({optimizationLevel: 4})) .pipe(gulp.dest(config.build.dev + 'images')) .pipe(gulp.dest(config.build.prod + 'images')); }); gulp.task('favicon', function() { log('Copying favicon'); return gulp .src(config.favicon) .pipe(gulp.dest(config.build.dev)) .pipe(gulp.dest(config.build.prod)); }); gulp.task('clean-images', function() { log('Cleaning images'); return function() { clean(config.build.dev + 'favicon.*'); clean(config.build.dev + 'images/**/*.*'); clean(config.build.prod + 'favicon.*'); clean(config.build.prod + 'images/**/*.*'); }; }); gulp.task('templates', function() { log('Creating an AngularJS $templateCache'); return gulp .src(config.html.templates) .pipe($.if(args.verbose, $.bytediff.start())) .pipe($.htmlmin({collapseWhitespace: true})) .pipe($.if(args.verbose, $.bytediff.stop(bytediffFormatter))) .pipe($.angularTemplatecache( config.templateCache.file, config.templateCache.options )) .pipe(gulp.dest(config.temp)); }); gulp.task('clean-temp', function() { var delconfig = [].concat(config.temp); log('Cleaning: ' + $.util.colors.blue(delconfig)); return del(delconfig); }); gulp.task('html', function() { log('Copying html-files'); return gulp .src(config.html.pages) .pipe(gulp.dest(config.build.dev)) .pipe($.htmlmin({collapseWhitespace: true})) .pipe(gulp.dest(config.build.prod)); }); gulp.task('clean-html', function() { var files = [].concat( config.build.dev + '**/*.html', config.build.prod + '**/*.html' ); return clean(files); }); gulp.task('build', function() { log('Building everything'); runSequence('clean', 'vet', 'templates', 'js-libs', 'js-app', 'styles-libs', 'styles-custom', 'fonts', 'images', 'favicon', 'html'); }); gulp.task('build-dev', function() { log('Building dev'); runSequence('clean', 'vet', 'templates', 'js-libs', 'js-app', 'styles-libs', 'styles-custom', 'fonts', 'images', 'favicon', 'html', 'serve-dev'); }); gulp.task('build-prod', function() { log('Building prod'); runSequence('clean', 'vet', 'templates', 'js-libs', 'js-app', 'styles-libs', 'styles-custom', 'fonts', 'images', 'favicon', 'html', 'serve-prod'); }); gulp.task('clean', function() { var delconfig = [].concat('./build', config.temp); log('Cleaning: ' + $.util.colors.blue(delconfig)); return del(delconfig); }); gulp.task('serve-dev', function() { var msg = { title: 'Build successfully complete', subtitle: 'Deployed to "dev" folder', message: 'Running "dev" server' }; log(msg); notify(msg); serve(true /*isDev*/); }); gulp.task('serve-prod', function() { var msg = { title: 'Build successfully complete', subtitle: 'Deployed to "dev" folder', message: 'Running "dev" server' }; log(msg); notify(msg); serve(false /*isDev*/); }); gulp.task('browserSyncReload', browserSync.reload); function serve(isDev) { var debug = args.debug || args.debugBrk; var debugMode = args.debug ? '--debug' : args.debugBrk ? '--debug-brk' : ''; var nodeOptions = getNodeOptions(isDev); if (debug) { runNodeInspector(); nodeOptions.nodeArgs = [debugMode + '=5858']; } if (args.verbose) { console.log(nodeOptions); } return $.nodemon(nodeOptions) .on('restart', function(ev) { log('*** nodemon restarted'); log('files changed:\n' + ev); setTimeout(function() { browserSync.notify('reloading now ...'); browserSync.reload({stream: false}); }, config.browserReloadDelay); }) .on('start', function() { log('*** nodemon started'); startBrowserSync(isDev); }) .on('crash', function() { log('*** nodemon crashed: script crashed for some reason'); }) .on('exit', function() { log('*** nodemon exited cleanly'); }); } function getNodeOptions(isDev) { return { script: config.nodeServer, delayTime: 1, env: { 'PORT': port, 'NODE_ENV': isDev ? 'dev' : 'prod' }, watch: [config.server] }; } function runNodeInspector() { log('Running node-inspector.'); log('Browse to http://localhost:8080/debug?port=5858'); var exec = require('child_process').exec; exec('node-inspector'); } function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; } function formatPercent(num, precision) { return (num * 100).toFixed(precision); } /** * Start BrowserSync * --nosync will avoid browserSync */ function startBrowserSync(isDev) { if (args.nosync || browserSync.active) { return; } log('Starting BrowserSync on port ' + port); gulp.watch([config.js.app], ['js-app']).on('change', changeEvent); gulp.watch([config.css.custom], ['styles-custom']).on('change', changeEvent); gulp.watch([config.html.pages], ['html']).on('all', changeEvent); gulp.watch([config.html.templates], ['templates', 'js-app']).on('all', changeEvent); gulp.watch([config.images], ['images']).on('all', changeEvent); gulp.watch([config.fonts], ['fonts']).on('all', changeEvent); var options = { proxy: 'localhost:' + port, port: 3000, files: isDev ? [ config.src + '**/*.*', '!' + config.css.custom, '!' + config.css.libs ] : [], ghostMode: { // these are the defaults t,f,t,t clicks: true, location: false, forms: true, scroll: true }, injectChanges: true, logFileChanges: true, logLevel: 'debug', logPrefix: 'gulp-patterns', notify: true, reloadDelay: 0 //1000 }; browserSync(options); } function clean(path) { log('Cleaning: ' + $.util.colors.blue(path)); return del(path); } function log(msg) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { $.util.log($.util.colors.blue(msg[item])); } } } else { $.util.log($.util.colors.blue(msg)); } } function notify(options) { var notifier = require('node-notifier'); var notifyOptions = { sound: 'Bottle', contentImage: path.join(__dirname, 'gulp.png'), icon: path.join(__dirname, 'gulp.png') }; _.assign(notifyOptions, options); notifier.notify(notifyOptions); } function changeEvent(event) { var srcPattern = new RegExp('/.*(?=/' + config.src + ')/'); log('File ' + event.path.replace(srcPattern, '') + ' ' + event.type); } <file_sep>/src/js/controllers/contacts.controller.js (function() { 'use strict'; angular .module('app.contacts') .controller('ContactsController', ['$scope', 'dataservice', function($scope, dataservice) { $scope.addContact = { data: {}, reset: function() { angular.forEach($scope.addContact.data, function(value, key) { $scope.addContact.data[key] = ''; }); $scope.newContactForm.$setPristine(); }, add: function() { $scope.contacts.list.push(angular.copy($scope.addContact.data)); $scope.addContact.reset(); } }; $scope.contacts = { list: [], columns: { firstName: {title: '<NAME>', isSortable: true}, lastName: {title: '<NAME>', isSortable: true}, email: {title: 'Email', isSortable: true}, phone: {title: 'Phone', isSortable: false} }, sortType: 'firstName', sortReverse: false, changeSorting: function(k) { $scope.contacts.sortType = k; $scope.contacts.sortReverse = !$scope.contacts.sortReverse; } }; $scope.getContacts = function() { dataservice.getContacts() .then(function(data) { $scope.contacts.list = angular.copy(data); }); }; $scope.getContacts(); }]); })();
f20e60134ee810eb818196f94fe446f78d667310
[ "JavaScript", "Markdown" ]
6
JavaScript
azhabinsky/mentor_digital_angularjs_test
f7e4288539267c45e10a46142646d89c5eedec15
4c8f5ef559051f22beb991d4618bb367bceac51a
refs/heads/master
<file_sep>practice1122 ============ My Practice Repository<file_sep><?php echo 'Hello I am 1.php file inside practice1122 folder first commit second time modified commit from <EMAIL>'; ?>
87227f42556798669bcc7b35fe61593b2be1d5a2
[ "Markdown", "PHP" ]
2
Markdown
sachin422/practice1122
fd29125f7169cd55abde3b8080f456916cf72523
a4197f4fa2d0b3386725755705971aaae57c29de
refs/heads/master
<repo_name>Requilence/nuvi-interview<file_sep>/README.md NUVI INTERVIEW CODE PROJECT =========== You can override default settings with some environment variables: - **NUVI_LIST_LINK** - URL to directory listing - **NUVI_POOL_DOWNLOADS** - the number of maximum parallel downloads - **NUVI_POOL_PROCESSING** - the number of maximum parallel data processing (unzip + redis) In addition to **NEWS_XML** Redis list my solution additionally uses: - Redis hash **NEWS_XML_KEY** to store inserted XMLs hash sums(in this case MD5 of the content obtained from the filename) - Redis hash **NEWS_ZIP_URL** to store downloaded and processed URLs The application is idempotent. It can be restarted and it will skip already downloaded&processed files. It also checks XML hash sum before pushing to **NEWS_XML_KEY** because the provided files source contains a lot of duplicate XML's. ### Requirements Go 1.5+, Redis 2.0.0+ <file_sep>/main.go package main import ( "net/http" "io/ioutil" "regexp" "strings" "io" "fmt" "archive/zip" "os" "path/filepath" "gopkg.in/redis.v4" "gopkg.in/cheggaaa/pb.v1" "sync/atomic" "sync" "strconv" ) const DefaultLink = "http://bitly.com/nuvi-plz" const DefaultParallelDownloads = 10 const DefaultParallelProcessing = 10 type DownloadedFile struct { URL string LocalPath string } var HTTPListingRE = regexp.MustCompile(`(?i)<tr><td>.*?href="([^"]*)`) var client *redis.Client var bar *pb.ProgressBar var stat = struct { Total uint64 Skipped uint64 Downloaded uint64 Unzipped uint64 XMLS uint64 Inserted uint64 Duplicates uint64 }{} var processingWait sync.WaitGroup func unzip(zipPath string) (string, error) { dest := filepath.Dir(zipPath) + "/" + filepath.Base(zipPath) + "_unzip" r, err := zip.OpenReader(zipPath) if err != nil { return "", err } defer func() { if err := r.Close(); err != nil { panic(err) } }() os.MkdirAll(dest, 0755) extractAndWriteFile := func(f *zip.File) error { rc, err := f.Open() if err != nil { return err } defer func() { if err := rc.Close(); err != nil { panic(err) } }() path := filepath.Join(dest, f.Name) if f.FileInfo().IsDir() { os.MkdirAll(path, f.Mode()) } else { os.MkdirAll(filepath.Dir(path), f.Mode()) f, err := os.OpenFile(path, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, f.Mode()) if err != nil { return err } defer func() { if err := f.Close(); err != nil { panic(err) } }() _, err = io.Copy(f, rc) if err != nil { return err } } return nil } for _, f := range r.File { err := extractAndWriteFile(f) if err != nil { return "", err } } return dest, nil } func downloadPool(filesToDownload<-chan string, filesToProcess chan <- DownloadedFile) { for fileURL := range filesToDownload { path, err := downloadAndGetPath(fileURL) if err != nil { processingWait.Done() fmt.Println(err) } else { atomic.AddUint64(&stat.Downloaded, 1) filesToProcess <- DownloadedFile{fileURL, path} } } } func processingPool(filesToProcess<-chan DownloadedFile) { for filePath := range filesToProcess { err := processFile(filePath) if err != nil { fmt.Println(err) } } } func downloadAndGetPath(fileURL string) (string, error) { response, err := http.Get(fileURL) if err != nil { return "", err } defer response.Body.Close() file, err := ioutil.TempFile("", "") if err != nil { return "", err } _, err = io.Copy(file, response.Body) if err != nil { return "", err } file.Close() return file.Name(), nil } func listHTTPDirFiles(dirURL string) ([]string, error) { req, err := http.NewRequest("GET", dirURL, nil) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { return nil, err } trs := HTTPListingRE.FindAllStringSubmatch(string(body), -1) var urls []string respLocation := resp.Request.URL.String() if !strings.HasSuffix(respLocation, "/") { respLocation = respLocation + "/" } if err != nil { return nil, err } for _, tr := range trs { if !strings.HasPrefix(tr[1], "/") && !strings.HasPrefix(tr[1], ".") { urls = append(urls, resp.Request.URL.String() + tr[1]) } } return urls, nil } func processFile(file DownloadedFile) error { unzippedDir, err := unzip(file.LocalPath) if err != nil { return err } os.Remove(file.LocalPath) atomic.AddUint64(&stat.Unzipped, 1) files, _ := ioutil.ReadDir(unzippedDir) for _, fileInfo := range files { atomic.AddUint64(&stat.XMLS, 1) b, err := ioutil.ReadFile(unzippedDir + "/" + fileInfo.Name()) if err != nil { return (err) } // hash := string(uint64ToBytes(xxhash.Checksum64(b))) // file name of file is MD5 of its content fparts := strings.Split(fileInfo.Name(), ".") hash := fparts[0] os.Remove(unzippedDir + "/" + fileInfo.Name()) if client.HExists("NEWS_XML_KEY", hash).Val() { atomic.AddUint64(&stat.Duplicates, 1) continue } err = client.RPush("NEWS_XML", b).Err() if err != nil { return err } atomic.AddUint64(&stat.Inserted, 1) client.HSet("NEWS_XML_KEY", hash, "") } client.HSet("NEWS_ZIP_URL", file.URL, "") os.RemoveAll(unzippedDir) bar.Increment() processingWait.Done() return nil } func main() { client = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 1, }) _, err := client.Ping().Result() if err != nil { panic("REDIS ERROR: " + err.Error()) } link := os.Getenv("NUVI_LIST_LINK") if link == "" { link = DefaultLink } parallelDownloads, _ := strconv.Atoi(os.Getenv("NUVI_POOL_DOWNLOADS")) if parallelDownloads == 0 { parallelDownloads = DefaultParallelDownloads } parallelProcessing, _ := strconv.Atoi(os.Getenv("NUVI_POOL_PROCESSING")) if parallelProcessing == 0 { parallelProcessing = DefaultParallelProcessing } urls, err := listHTTPDirFiles(link) if err != nil { fmt.Println(err) } filesToDownload := make(chan string, len(urls)) filesToProcess := make(chan DownloadedFile, len(urls)) bar = pb.New(len(urls)).SetMaxWidth(100) bar.Start() for i := 0; i < parallelDownloads; i++ { go downloadPool(filesToDownload, filesToProcess) } for i := 0; i < parallelProcessing; i++ { go processingPool(filesToProcess) } for _, url := range urls { stat.Total++ if !client.HExists("NEWS_ZIP_URL", url).Val() { processingWait.Add(1) filesToDownload <- url } else { stat.Skipped++ bar.Increment() } } close(filesToDownload) processingWait.Wait() bar.Finish() fmt.Printf("%+v\n", stat) }
5232048bb8ac68d358982616690e24f5537cb804
[ "Markdown", "Go" ]
2
Markdown
Requilence/nuvi-interview
8863d59e4d60ac8f2aeae6609ee5f8ee7f96ee42
ee7ea01b77f159dd049899fa062ca44e329b9182
refs/heads/master
<file_sep>class WaterCupsController < ApplicationController def index watercups = WaterCup.all render json: watercups end def show watercup = WaterCup.find_by_id(params[:id]) render json: watercup end def new watercup = WaterCup.new end def create watercup = WaterCup.new(amount: params["amount"], user_id: params["user_id"]) watercup.save render json: watercup end def update watercup = WaterCup.find_by(id: params[:id]) watercup.update(amount: params["amount"]) render json: watercup end def destroy watercup = WaterCup.find_by(id: params[:id]) watercup.delete render json: watercup end end def watercup_params params.require(:watercup).permit(:amount,) end<file_sep># create_table "users", force: :cascade do |t| # t.string "name" # t.integer "age" # t.string "gender" # t.integer "watergoal" # t.datetime "created_at", precision: 6, null: false # t.datetime "updated_at", precision: 6, null: false # end # create_table "water_cups", force: :cascade do |t| # t.integer "amount" # t.integer "user_id" # t.datetime "created_at", precision: 6, null: false # t.datetime "updated_at", precision: 6, null: false # end user1 = User.create(name: "name1", age: "1", gender: "male", watergoal: "8") water1 = WaterCup.create(amount: "2", user_id: 1) water2 = WaterCup.create(amount: "1", user_id: 1) water3 = WaterCup.create(amount: "1", user_id: 1) water4 = WaterCup.create(amount: "1", user_id: 1) puts 'seeds done'<file_sep>class UsersController < ApplicationController def index users = User.all render json: users end def show user = User.find_by_id(params[:id]) render json: user end def new user = User.new end def create user = User.new(user_params) user.save render json: user end def update user = User.find_by(id: params[:id]) user.update(name: params["name"], age: params["age"], gender: params["gender"], watergoal: params["watergoal"]) render json: user end end private def user_params params.require(:user).permit(:name, :age, :gender, :watergoal) end
84674e73dc762df4ce87791b0bd25c0419078d2d
[ "Ruby" ]
3
Ruby
candacecodes/hydr8-backend
c0988217ac2690d34ad9bbdd4ab64b04b757d9d1
b495cf7d07f096f88ba977423154a2724da7a598
refs/heads/master
<repo_name>WolfieZero/scotch-school-getting-started-with-angular-2<file_sep>/README.md # Angular 2 Following the course [**Getting Started with Angular 2+**](https://school.scotch.io/getting-started-with-angular-2) ## Structural Directive ```javascript *ngFor="let user of users" *ngIf="users" ``` ## Putting Info Into a Component ```javascript @Input() ``` ## Bindings ### Property Binding - `[]` Data flows INTO it one-way ```javascript [class.active]="user === activeUser" ``` ### Event Binding - `()` Data flows OUT OF it one-way ```javascript (Click)="selectUser(user)" ``` ### Two-Way Data Binding - "The Banana in a Box" ```javascript [(ngModel)]="activeUser.name" ``` ## Links [Style Guide](https://angular.io/docs/ts/latest/guide/style-guide.html) <file_sep>/ng2-start/app/app.component.ts import { Component } from '@angular/core'; import { User } from './shared/models/User'; // Refereces are absolute due to these files not being built into the // dist folder. So they should always refence those exact files. @Component({ selector: 'app', templateUrl: './app/app.component.html', styleUrls: [ './app/app.component.css' ] }) export class AppComponent { message: string = 'Hello!'; users: User[] = [ { id: 1, name: 'Roxie', username: 'roxiechinchilla' }, { id: 2, name: 'Enni', username: 'ennithelappy' }, ]; activeUser: User; selectUser(user) { this.activeUser = user; } onUserCreated(event) { this.users.push(event.user); } }
44a1db08515b3023de7be922418c2d56522e424d
[ "Markdown", "TypeScript" ]
2
Markdown
WolfieZero/scotch-school-getting-started-with-angular-2
47a2d1d2679cca425ac174225dd6dcedb1137ef2
dc8a849a8fc3a684f777c8d68a9705f4435e510f
refs/heads/master
<file_sep>#!/bin/sh echo "<KEY>" <file_sep>#include "internal.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ Internal::Internal () : mode (SEARCH), unsat (false), iterating (false), localsearching (false), preprocessing (false), force_saved_phase (false), termination_forced (false), searching_lucky_phases (false), stable (false), reported (false), rephased (0), vsize (0), max_var (0), level (0), vals (0), marks (0), frozentab (0), i2e (0), scinc (1.0), scores (this), stab (0), vtab (0), ltab (0), ftab (0), btab (0), otab (0), ptab (0), ntab (0), ntab2 (0), big (0), wtab (0), conflict (0), ignore (0), propagated (0), propagated2 (0), best_assigned (0), target_assigned (0), no_conflict_until (0), proof (0), checker (0), tracer (0), opts (this), #ifndef QUIET profiles (this), force_phase_messages (false), #endif arena (this), prefix ("c "), internal (this), external (0) { control.push_back (Level (0, 0)); binary_subsuming.redundant = false; binary_subsuming.size = 2; } Internal::~Internal () { for (const auto & c : clauses) delete_clause (c); if (proof) delete proof; if (tracer) delete tracer; if (checker) delete checker; if (vtab) DELETE_ONLY (vtab, Var, vsize); if (ltab) DELETE_ONLY (ltab, Link, vsize); if (ftab) DELETE_ONLY (ftab, Flags, vsize); if (btab) DELETE_ONLY (btab, long, vsize); if (stab) DELETE_ONLY (stab, double, vsize); if (ptab) DELETE_ONLY (ptab, int, 2*vsize); if (big) RELEASE_DELETE (big, Bins, 2*vsize); if (vals) { vals -= vsize; DELETE_ONLY (vals, signed_char, 2*vsize); } if (marks) DELETE_ONLY (marks, signed_char, vsize); if (phases.saved) DELETE_ONLY (phases.saved, Phase, vsize); if (phases.target) DELETE_ONLY (phases.target, Phase, vsize); if (phases.best) DELETE_ONLY (phases.best, Phase, vsize); if (phases.prev) DELETE_ONLY (phases.prev, Phase, vsize); if (phases.min) DELETE_ONLY (phases.min, Phase, vsize); if (i2e) DELETE_ONLY (i2e, int, vsize); if (frozentab) DELETE_ONLY (frozentab, unsigned, vsize); if (otab) reset_occs (); if (ntab) reset_noccs (); if (wtab) reset_watches (); } /*------------------------------------------------------------------------*/ void Internal::enlarge_vals (size_t new_vsize) { signed_char * new_vals; NEW_ZERO (new_vals, signed_char, 2*new_vsize); new_vals += new_vsize; if (vals) memcpy (new_vals - max_var, vals - max_var, 2*max_var + 1); vals -= vsize; DELETE_ONLY (vals, signed_char, 2*vsize); vals = new_vals; } void Internal::enlarge (int new_max_var) { assert (!level); size_t new_vsize = vsize ? 2*vsize : 1 + (size_t) new_max_var; while (new_vsize <= (size_t) new_max_var) new_vsize *= 2; LOG ("enlarge internal size from %ld to new size %ld", vsize, new_vsize); // Ordered in the size of allocated memory (larger block first). assert (!vsize || !otab); if (!vsize || wtab) ENLARGE_ZERO (wtab, Watches, 2*vsize, 2*new_vsize); ENLARGE_ONLY (vtab, Var, vsize, new_vsize); ENLARGE_ONLY (ltab, Link, vsize, new_vsize); ENLARGE_ZERO (btab, long, vsize, new_vsize); ENLARGE_ZERO (stab, double, vsize, new_vsize); ENLARGE_ONLY (ptab, int, 2*vsize, 2*new_vsize); ENLARGE_ONLY (i2e, int, vsize, new_vsize); enlarge_vals (new_vsize); ENLARGE_ZERO (frozentab, unsigned, vsize, new_vsize); ENLARGE_ONLY (phases.saved, Phase, vsize, new_vsize); ENLARGE_ZERO (phases.target, Phase, vsize, new_vsize); ENLARGE_ZERO (phases.best, Phase, vsize, new_vsize); ENLARGE_ZERO (phases.prev, Phase, vsize, new_vsize); ENLARGE_ZERO (phases.min, Phase, vsize, new_vsize); ENLARGE_ZERO (marks, signed_char, vsize, new_vsize); ENLARGE_ONLY (ftab, Flags, vsize, new_vsize); vsize = new_vsize; } void Internal::init (int new_max_var) { if (new_max_var <= max_var) return; if (level) backtrack (); LOG ("initializing %d internal variables from %d to %d", new_max_var - max_var, max_var + 1, new_max_var); if ((size_t) new_max_var >= vsize) enlarge (new_max_var); signed_char val = opts.phase ? 1 : -1; for (int i = max_var + 1; i <= new_max_var; i++) phases.saved[i] = val; #ifndef NDEBUG for (int i = -new_max_var; i < -max_var; i++) assert (!vals[i]); for (int i = max_var + 1; i <= new_max_var; i++) assert (!vals[i]); for (int i = max_var + 1; i <= new_max_var; i++) assert (!frozentab[i]); for (int i = max_var + 1; i <= new_max_var; i++) assert (!marks[i]); for (int i = max_var + 1; i <= new_max_var; i++) assert (!btab[i]); #endif for (int i = 2*(max_var + 1); i <= 2*new_max_var+1; i++) ptab[i] = -1; for (int i = max_var + 1; i <= new_max_var; i++) ftab[i].init (); assert (!btab[0]); int old_max_var = max_var; max_var = new_max_var; init_queue (old_max_var, new_max_var); init_scores (old_max_var, new_max_var); int initialized = new_max_var - old_max_var; stats.vars += initialized; stats.unused += initialized; stats.inactive += initialized; LOG ("finished initializing %d internal variables", initialized); } void Internal::add_original_lit (int lit) { assert (abs (lit) <= max_var); if (lit) { original.push_back (lit); } else { if (proof) proof->add_original_clause (original); add_new_original_clause (); original.clear (); } } /*------------------------------------------------------------------------*/ // This is the main CDCL loop with interleaved inprocessing. int Internal::cdcl_loop_with_inprocessing () { int res = 0; START (search); if (stable) { START (stable); report ('['); } else { START (unstable); report ('{'); } while (!res) { if (unsat) res = 20; else if (!propagate ()) analyze (); // propagate and analyze else if (iterating) iterate (); // report learned unit else if (satisfied ()) res = 10; // found model else if (terminating ()) break; // limit hit or sync abort else if (restarting ()) restart (); // restart by backtracking else if (rephasing ()) rephase (); // reset variable phases else if (reducing ()) reduce (); // collect useless clauses else if (probing ()) probe (); // failed literal probing else if (subsuming ()) subsume (); // subsumption algorithm else if (eliminating ()) elim (); // variable elimination else if (compacting ()) compact (); // collect variables else res = decide (); // next decision } if (stable) { STOP (stable); report (']'); } else { STOP (unstable); report ('}'); } STOP (search); return res; } /*------------------------------------------------------------------------*/ void Internal::init_limits () { const bool incremental = lim.initialized; if (incremental) LOG ("reinitializing limits incrementally"); else LOG ("initializing limits and increments"); const char * mode = 0; if (incremental) mode = "keeping"; else { last.reduce.conflicts = -1; lim.reduce = stats.conflicts + opts.reduceint; mode = "initial"; } (void) mode; LOG ("%s reduce limit %ld after %ld conflicts", mode, lim.reduce, lim.reduce - stats.conflicts); if (incremental) mode = "keeping"; else { lim.flush = opts.flushint; inc.flush = opts.flushint; mode = "initial"; } (void) mode; LOG ("%s flush limit %ld interval %ld", mode, lim.flush, inc.flush); if (incremental) mode = "keeping"; else { lim.subsume = stats.conflicts + scale (opts.subsumeint); mode = "initial"; } (void) mode; LOG ("%s subsume limit %ld after %ld conflicts", mode, lim.subsume, lim.subsume - stats.conflicts); if (incremental) mode = "keeping"; else { last.elim.marked = -1; lim.elim = stats.conflicts + scale (opts.elimint); mode = "initial"; } (void) mode; LOG ("%s elim limit %ld after %ld conflicts", mode, lim.elim, lim.elim - stats.conflicts); lim.elimbound = opts.elimboundmin; LOG ("elimination bound %ld", lim.elimbound); if (incremental) mode = "keeping"; else { lim.probe = stats.conflicts + opts.probeint; mode = "initial"; } (void) mode; LOG ("%s probe limit %ld after %ld conflicts", mode, lim.probe, lim.probe - stats.conflicts); if (!incremental) { last.ternary.marked = -1; lim.compact = stats.conflicts + opts.compactint; LOG ("initial compact limit %ld increment %ld", lim.compact, lim.compact - stats.conflicts); } lim.rephase = stats.conflicts + opts.rephaseint; lim.rephased[0] = lim.rephased[1] = 0; LOG ("new rephase limit %ld after %ld conflicts", lim.rephase, lim.rephase - stats.conflicts); lim.restart = stats.conflicts + opts.restartint; LOG ("new restart limit %ld increment %ld", lim.restart, lim.restart - stats.conflicts); reported = false; lim.report = 0; if (!incremental) { stable = opts.stabilize && opts.stabilizeonly; if (stable) LOG ("starting in always forced stable phase"); else LOG ("starting in default non-stable phase"); init_averages (); } else if (opts.stabilize && opts.stabilizeonly) { LOG ("keeping always forced stable phase"); assert (stable); } else if (stable) { LOG ("switching back to default non-stable phase"); stable = false; swap_averages (); } else LOG ("keeping non-stable phase"); inc.stabilize = opts.stabilizeint; lim.stabilize = stats.conflicts + inc.stabilize; LOG ("new stabilize limit %ld after %ld conflicts", lim.stabilize, inc.stabilize); if (opts.stabilize && opts.reluctant) { LOG ("new restart reluctant doubling sequence period %d", opts.reluctant); reluctant.enable (opts.reluctant, opts.reluctantmax); } else reluctant.disable (); if (inc.conflicts < 0) { lim.conflicts = -1; LOG ("no limit on conflicts"); } else { lim.conflicts = stats.conflicts + inc.conflicts; LOG ("conflict limit after %ld conflicts at %ld conflicts", inc.conflicts, lim.conflicts); } if (inc.decisions < 0) { lim.decisions = -1; LOG ("no limit on decisions"); } else { lim.decisions = stats.decisions + inc.decisions; LOG ("conflict limit after %ld decisions at %ld decisions", inc.decisions, lim.decisions); } if (inc.preprocessing <= 0) { lim.preprocessing = 0; LOG ("no preprocessing"); } else { lim.preprocessing = inc.preprocessing; LOG ("limiting to %d preprocessing rounds", lim.preprocessing); } if (inc.localsearch <= 0) { lim.localsearch = 0; LOG ("no local search"); } else { lim.localsearch = inc.localsearch; LOG ("limiting to %d local search rounds", lim.localsearch); } lim.initialized = true; } /*------------------------------------------------------------------------*/ bool Internal::preprocess_round (int round) { (void) round; if (unsat) return false; if (!max_var) return false; START (preprocess); struct { int vars; long clauses; } before, after; before.vars = active (); before.clauses = stats.current.irredundant; stats.preprocessings++; assert (!preprocessing); preprocessing = true; PHASE ("preprocessing", stats.preprocessings, "starting round %d with %d variables and %ld clauses", round, before.vars, before.clauses); int old_elimbound = lim.elimbound; if (opts.probe) probe (false); if (opts.elim) elim (false); after.vars = active (); after.clauses = stats.current.irredundant; assert (preprocessing); preprocessing = false; PHASE ("preprocessing", stats.preprocessings, "finished round %d with %d variables and %ld clauses", round, after.vars, after.clauses); STOP (preprocess); report ('P'); if (unsat) return false; if (after.vars < before.vars) return true; if (old_elimbound < lim.elimbound) return true; return false; } int Internal::preprocess () { if (opts.simplify) for (int i = 0; i < lim.preprocessing; i++) if (!preprocess_round (i)) break; if (unsat) return 20; return 0; } /*------------------------------------------------------------------------*/ int Internal::try_to_satisfy_formula_by_saved_phases () { LOG ("satisfying formula by saved phases"); assert (!level); assert (!force_saved_phase); assert (propagated == trail.size ()); force_saved_phase = true; int res = 0; while (!res) { if (satisfied ()) { LOG ("formula indeed satisfied by saved phases"); res = 10; } else if (decide ()) { LOG ("inconsistent assumptions with redundant clauses and phases"); res = 20; } else if (!propagate ()) { LOG ("saved phases do not satisfy redundant clauses"); assert (level > 0); backtrack (); conflict = 0; // ignore conflict assert (!res); break; } } assert (force_saved_phase); force_saved_phase = false; return res; } /*------------------------------------------------------------------------*/ void Internal::produce_failed_assumptions () { LOG ("producing failed assumptions"); assert (!level); assert (!assumptions.empty ()); while (!unsat) { assert (!satisfied ()); if (decide ()) break; while (!unsat && !propagate ()) analyze (); } if (unsat) LOG ("formula is actually unsatisfiable unconditionally"); else LOG ("assumptions indeed failing"); } /*------------------------------------------------------------------------*/ int Internal::local_search_round (int round) { assert (round > 0); if (unsat) return false; if (!max_var) return false; START_OUTER_WALK (); assert (!localsearching); localsearching = true; // Determine propagation limit quadratically scaled with rounds. // long limit = opts.walkmineff; limit *= round; if (LONG_MAX / round > limit) limit *= round; else limit = LONG_MAX; int res = walk_round (limit, true); assert (localsearching); localsearching = false; STOP_OUTER_WALK (); report ('L'); return res; } int Internal::local_search () { if (unsat) return 0; if (!max_var) return 0; if (!opts.walk) return 0; int res = 0; for (int i = 1; !res && i <= lim.localsearch; i++) res = local_search_round (i); if (res == 10) { LOG ("local search determined formula to be satisfiable"); assert (!stats.walk.minimum); res = try_to_satisfy_formula_by_saved_phases (); } else if (res == 20) { LOG ("local search determined assumptions to be inconsistent"); assert (!assumptions.empty ()); produce_failed_assumptions (); } return res; } /*------------------------------------------------------------------------*/ int Internal::solve () { assert (clause.empty ()); START (solve); if (level) backtrack (); int res = 0; if (unsat) { LOG ("already inconsistent"); res = 20; } else if (!propagate ()) { LOG ("root level propagation produces conflict"); learn_empty_clause (); res = 20; } else { init_limits (); if (!opts.restoreall && external->tainted.empty ()) { LOG ("no tainted literals and nothing to restore"); report ('*'); } else { report ('+'); external->restore_clauses (); internal->report ('r'); if (!unsat && !propagate ()) { LOG ("root level propagation after restore produces conflict"); learn_empty_clause (); res = 20; } } if (!res) res = preprocess (); if (!res) res = local_search (); if (!res) res = lucky_phases (); if (!res) { if (terminating ()) res = 0; else res = cdcl_loop_with_inprocessing (); } } if (termination_forced) { termination_forced = false; LOG ("reset forced termination"); } if (res == 10) report ('1'); else if (res == 20) report ('0'); else report ('?'); STOP (solve); return res; } /*------------------------------------------------------------------------*/ void Internal::print_stats () { stats.print (this); if (checker) checker->print_stats (); } /*------------------------------------------------------------------------*/ // Only useful for debugging purposes. void Internal::dump (Clause * c) { for (const auto & lit : *c) printf ("%d ", lit); printf ("0\n"); } void Internal::dump () { long m = assumptions.size (); for (int idx = 1; idx <= max_var; idx++) if (fixed (idx)) m++; for (const auto & c : clauses) if (!c->garbage) m++; printf ("p cnf %d %ld\n", max_var, m); for (int idx = 1; idx <= max_var; idx++) { const int tmp = fixed (idx); if (tmp) printf ("%d 0\n", tmp < 0 ? -idx : idx); } for (const auto & c : clauses) if (!c->garbage) dump (c); for (const auto & lit : assumptions) printf ("%d 0\n", lit); fflush (stdout); } /*------------------------------------------------------------------------*/ bool Internal::traverse_clauses (ClauseIterator & it) { vector<int> eclause; if (unsat) return it.clause (eclause); for (const auto & c : clauses) { if (c->garbage) continue; if (c->redundant) continue; bool satisfied = false; for (const auto & ilit : *c) { const int tmp = fixed (ilit); if (tmp > 0) { satisfied = true; break; } if (tmp < 0) continue; const int elit = externalize (ilit); eclause.push_back (elit); } if (!satisfied && !it.clause (eclause)) return false; eclause.clear (); } return true; } } <file_sep>#include "internal.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ // Binary implication graph lists. void Internal::init_bins () { assert (!big); NEW_ZERO (big, Bins, 2*vsize); } void Internal::reset_bins () { assert (big); RELEASE_DELETE (big, Bins, 2*vsize); big = 0; } } <file_sep>#include "internal.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ // Compacting removes holes generated by inactive variables (fixed, // eliminated, substituted or pure) by mapping active variables indices down // to a contiguous interval of indices. /*------------------------------------------------------------------------*/ bool Internal::compacting () { if (level) return false; if (!opts.simplify) return false; if (!opts.compact) return false; if (stats.conflicts < lim.compact) return false; int inactive = max_var - active (); assert (inactive >= 0); if (!inactive) return false; if (inactive < opts.compactmin) return false; return inactive >= (1e-3 * opts.compactlim) * max_var; } /*------------------------------------------------------------------------*/ // Map old internal literal 'SRC' to new internal literal 'DST'. This would // be trivially just a look-up into the 'map' created in 'compact' (caring // about signedness of 'SRC' though), except that fixed variables have all // to be mapped to the first fixed variable 'first_fixed', which makes it // more tricky. // #define MAP_LIT(SRC,DST) \ do { \ int OLD = (SRC); \ assert (OLD), assert (abs (OLD) <= max_var); \ int RES = map[abs (OLD)]; \ if (!RES) { \ assert (!level); \ assert (vals_not_mapped_yet); \ const int TMP = val (OLD); \ if (TMP) { \ assert (first_fixed); \ RES = map_first_fixed; \ if (TMP != first_fixed_val) RES = -RES; \ } \ } else if ((OLD) < 0) RES = -RES; \ assert (abs (RES) <= new_max_var); \ (DST) = RES; \ } while (0) // Map the positive variable indices in array 'NAME' of element type 'TYPE'. // #define MAP_ARRAY_ONLY(TYPE,NAME) \ do { \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ assert (0 < DST), assert (DST <= SRC); \ assert (DST > 0); \ NAME[DST] = NAME[SRC]; \ } \ SHRINK_ONLY (NAME, TYPE, vsize, new_vsize); \ PRINT ("mapped '" # NAME "'"); \ } while (0) // Same as 'MAP_ARRAY_ONLY' but two sided (positive and negative literal). // // We need two versions here, one for arrays of 'std::vector' which need // proper initialization and release operations and then another one which // does not initialize anything. // // This is the first version for arrays containing objects with destructor // (e.g., in our case only 'std::vector'). // #define RELEASE_MAP2_ARRAY(TYPE,NAME) \ do { \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ assert (0 < DST), assert (DST <= SRC); \ NAME[2*DST] = NAME[2*SRC]; \ NAME[2*DST+1] = NAME[2*SRC+1]; \ } \ RELEASE_SHRINK (NAME, TYPE, 2*vsize, 2*new_vsize); \ PRINT ("mapped '" # NAME "' (after release)"); \ } while (0) // This is second version for arrays containing objects which do not have a // destructor (such as 'noccs2'). The only difference to the previous // 'RELEASE_MAP2_ARRAY' is to use 'SHRINK_ONLY' without 'RELEASE_SHRINK'. // #define MAP2_ARRAY_ONLY(TYPE,NAME) \ do { \ for (int SRC = 1; SRC <= max_var; SRC++) { \ const int DST = map[SRC]; \ if (!DST) continue; \ assert (0 < DST), assert (DST <= SRC); \ NAME[2*DST] = NAME[2*SRC]; \ NAME[2*DST+1] = NAME[2*SRC+1]; \ } \ SHRINK_ONLY (NAME, TYPE, 2*vsize, 2*new_vsize); \ PRINT ("mapped '" # NAME "' (no release)"); \ } while (0) // Map a 'vector<int>' of literals, flush inactive literals, resize and // shrink it to fit its new size after flushing. // #define MAP_FLUSH_AND_SHRINK_INT_VECTOR(V) \ do { \ const auto end = V.end (); \ auto j = V.begin (), i = j; \ for (; i != end; i++) { \ const int SRC = *i; \ int DST = map[abs (SRC)]; \ assert (abs (DST) <= abs (SRC)); \ if (!DST) continue; \ if (SRC < 0) DST = -DST; \ *j++ = DST; \ } \ V.resize (j - V.begin ()); \ shrink_vector (V); \ PRINT ("mapped '" # V "'"); \ } while (0) /*------------------------------------------------------------------------*/ #ifndef QUIET #ifdef LOGGING #define PRINTVERBOSEGUARD !opts.log #else #define PRINTVERBOSEGUARD true #endif #define PRINT(MSG) \ do { \ if (opts.quiet) break; \ if (PRINTVERBOSEGUARD && opts.verbose < 2) break; \ print_prefix (); \ printf ("[compact-%ld] %s %.0f MB\n", stats.compacts, \ (MSG), current_resident_set_size ()/(double)(1<<20) ); \ fflush (stdout); \ } while (0) #else #define PRINT(MSG) do { } while (0) #endif /*------------------------------------------------------------------------*/ void Internal::compact () { PRINT ("BEFORE"); START (compact); assert (active () < max_var); stats.compacts++; assert (!level); assert (!unsat); assert (!conflict); assert (clause.empty ()); assert (levels.empty ()); assert (analyzed.empty ()); assert (minimized.empty ()); assert (control.size () == 1); assert (propagated == trail.size ()); garbage_collection (); /*----------------------------------------------------------------------*/ // We produce a compacting garbage collector like map of old 'src' to // new 'dst' variables. Inactive variables are just skipped except for // fixed ones which will be mapped to the first fixed variable (in the // appropriate phase). This avoids to handle the case 'fixed value' // separately as it is done in Lingeling, where fixed variables are // mapped to the internal variable '1'. // int * map, new_max_var = 0, first_fixed = 0, map_first_fixed = 0; NEW_ZERO (map, int, max_var + 1); for (int src = 1; src <= max_var; src++) { const Flags & f = flags (src); if (f.active ()) map[src] = ++new_max_var; else if (f.fixed () && !first_fixed) map[first_fixed = src] = map_first_fixed = ++new_max_var; } #ifndef NDEBUG bool vals_not_mapped_yet = true; // for testing & debugging #endif const int first_fixed_val = first_fixed ? val (first_fixed) : 0; if (first_fixed) LOG ("found first fixed %d", sign (first_fixed_val)*first_fixed); else LOG ("no variable fixed"); const size_t new_vsize = new_max_var + 1; // Adjust to fit 'new_max_var'. PRINT ("generated 'map'"); if (!assumptions.empty ()) { assert (!external->assumptions.empty ()); LOG ("temporarily reset internal assumptions"); reset_assumptions (); } /*----------------------------------------------------------------------*/ // In this first part we only map stuff without reallocation. /*----------------------------------------------------------------------*/ // Flush the external indices. This has to occur before we map 'vals'. // for (int eidx = 1; eidx <= external->max_var; eidx++) { int src = external->e2i[eidx], dst; if (!src) continue; MAP_LIT (src, dst); LOG ("compact %ld maps external %d to internal %d from internal %d", stats.compacts, eidx, dst, src); external->e2i[eidx] = dst; } PRINT ("mapped 'i2e'"); // Map the literals in all clauses. // for (const auto & c : clauses) { assert (!c->garbage); for (auto & src : *c) { assert (!val (src)); int dst; MAP_LIT (src, dst); assert (dst || c->garbage); src = dst; } } PRINT ("mapped 'clauses'"); // Map the blocking literals in all watches. // if (watches ()) for (int idx = 1; idx <= max_var; idx++) for (int sign = -1; sign <= 1; sign += 2) for (auto & w : watches (sign*idx)) MAP_LIT (w.blit, w.blit); PRINT ("mapped 'blits'"); // We first flush inactive variables and map the links in the queue. This // has to be done before we map the actual links data structure 'ltab'. { int prev = 0, mapped_prev = 0, next; for (int idx = queue.first; idx; idx = next) { Link * l = ltab + idx; next = l->next; if (idx == first_fixed) continue; const int dst = map[idx]; if (!dst) continue; assert (active (idx)); if (prev) ltab[prev].next = dst; else queue.first = dst; l->prev = mapped_prev; mapped_prev = dst; prev = idx; } if (prev) ltab[prev].next = 0; else queue.first = 0; queue.unassigned = queue.last = mapped_prev; } PRINT ("mapped 'queue'"); /*----------------------------------------------------------------------*/ // In the second part we map, flush and shrink arrays. /*----------------------------------------------------------------------*/ MAP_FLUSH_AND_SHRINK_INT_VECTOR (trail); propagated = trail.size (); if (first_fixed) { assert (trail.size () == 1); var (first_fixed).trail = 0; // before mapping 'vtab' } else assert (trail.empty ()); if (!probes.empty ()) MAP_FLUSH_AND_SHRINK_INT_VECTOR (probes); /*----------------------------------------------------------------------*/ // In the third part we map stuff and also reallocate memory. /*----------------------------------------------------------------------*/ // Now we continue in reverse order of allocated bytes, e.g., see // 'Internal::enlarge' which reallocates in order of allocated bytes. MAP_ARRAY_ONLY (Flags, ftab); MAP_ARRAY_ONLY (signed_char, marks); MAP_ARRAY_ONLY (Phase, phases.saved); MAP_ARRAY_ONLY (Phase, phases.target); MAP_ARRAY_ONLY (Phase, phases.best); MAP_ARRAY_ONLY (Phase, phases.prev); MAP_ARRAY_ONLY (Phase, phases.min); // Special code for 'frozentab'. // { unsigned * new_frozentab; NEW_ZERO (new_frozentab, unsigned, new_vsize); for (int src = 1; src <= max_var; src++) new_frozentab[map[src]] += frozentab[src]; // accumulate! DELETE_ONLY (frozentab, unsigned, vsize); frozentab = new_frozentab; } PRINT ("mapped 'frozentab'"); if (!external->assumptions.empty ()) { for (const auto & elit : external->assumptions) { assert (elit); assert (elit != INT_MIN); int eidx = abs (elit); assert (eidx <= external->max_var); int ilit = external->e2i[eidx]; assert (ilit); // Because we froze all!!! if (elit < 0) ilit = -ilit; assume (ilit); } PHASE ("compact", stats.compacts, "reassumed %zd external assumptions", external->assumptions.size ()); } // Special case for 'val' as for 'val' we trade branch less code for // memory and always allocated an [-maxvar,...,maxvar] array. { #ifndef NDEBUG vals_not_mapped_yet = false; // for testing & debugging #endif signed_char * new_vals; NEW_ONLY (new_vals, signed_char, 2*new_vsize); new_vals += new_vsize; for (int src = -max_var; src <= -1; src++) new_vals[-map[-src]] = vals[src]; for (int src = 1; src <= max_var; src++) new_vals[map[src]] = vals[src]; new_vals[0] = 0; vals -= vsize; DELETE_ONLY (vals, signed_char, 2*vsize); vals = new_vals; } PRINT ("mapped 'vals'"); MAP_ARRAY_ONLY (int, i2e); MAP2_ARRAY_ONLY (int, ptab); MAP_ARRAY_ONLY (long, btab); MAP_ARRAY_ONLY (Link, ltab); MAP_ARRAY_ONLY (Var, vtab); if (ntab) MAP2_ARRAY_ONLY (long, ntab); if (ntab2) MAP_ARRAY_ONLY (long, ntab2); if (wtab) RELEASE_MAP2_ARRAY (Watches, wtab); if (otab) RELEASE_MAP2_ARRAY (Occs, otab); if (big) RELEASE_MAP2_ARRAY (Bins, big); /*----------------------------------------------------------------------*/ // In the fourth part we map the binary heap for scores. /*----------------------------------------------------------------------*/ // The simplest way to map a binary heap is to get all elements from the // heap and reinsert them. This could be slightly improved in terms of // speed if we add a 'flush (int * map)' function to 'Heap', but that is // pretty complicated and would require that the 'Heap' knows that mapped // elements with 'zero' destination should be flushed. vector<int> saved; assert (saved.empty ()); if (!scores.empty ()) { while (!scores.empty ()) { const int src = scores.front (); scores.pop_front (); const int dst = map [src]; if (dst && src != first_fixed) saved.push_back (dst); } scores.erase (); } MAP_ARRAY_ONLY (double, stab); if (!saved.empty ()) { for (const auto & idx : saved) scores.push_back (idx); scores.shrink (); } PRINT ("mapped 'scores'"); /*----------------------------------------------------------------------*/ DELETE_ONLY (map, int, max_var); PHASE ("compact", stats.compacts, "reducing internal variables from %d to %d", max_var, new_max_var); /*----------------------------------------------------------------------*/ // Need to adjust the target and best assigned counters too. size_t new_target_assigned = 0, new_best_assigned = 0; for (int idx = 1; idx <= new_max_var; idx++) { if (phases.target[idx]) new_target_assigned++; if (phases.best[idx]) new_best_assigned++; } LOG ("reset target assigned from %zd to %zd", target_assigned, new_target_assigned); LOG ("reset best assigned from %zd to %zd", best_assigned, new_best_assigned); target_assigned = new_target_assigned; best_assigned = new_best_assigned; no_conflict_until = 0; INIT_EMA (averages.current.trail.fast, opts.ematrailfast); INIT_EMA (averages.current.trail.slow, opts.ematrailslow); /*----------------------------------------------------------------------*/ max_var = new_max_var; vsize = new_vsize; stats.unused = 0; stats.inactive = stats.now.fixed = first_fixed ? 1 : 0; stats.now.substituted = stats.now.eliminated = stats.now.pure = 0; check_var_stats (); long delta = opts.compactint * (stats.compacts + 1); lim.compact = stats.conflicts + delta; PHASE ("compact", stats.compacts, "new compact limit %ld after %ld conflicts", lim.compact, delta); report ('/'); STOP (compact); PRINT ("AFTER"); } } <file_sep>#include "internal.hpp" namespace CaDiCaL { void Internal::copy_phases (Phase * & dst) { assert (sizeof (Phase) == 1); memcpy (dst, vals, max_var + 1); } void Internal::clear_phases (Phase * & dst) { assert (sizeof (Phase) == 1); memset (dst, 0, max_var + 1); } } <file_sep>#ifndef _phases_hpp_INCLUDED #define _phases_hpp_INCLUDED namespace CaDiCaL { typedef signed char Phase; struct Phases { Phase * saved; // The actual saved phase. Phase * target; // The current target phase. Phase * best; // The current largest trail phase. Phase * prev; // Previous during local search. Phase * min; // The current minimum unsatisfied phase. Phases () : saved (0), target (0), best (0), prev (0), min (0) { } }; } #endif <file_sep>#include "internal.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ // Occurrence lists. void Internal::init_occs () { assert (!otab); NEW_ZERO (otab, Occs, 2*vsize); LOG ("initialized occurrence lists"); } void Internal::reset_occs () { assert (otab); RELEASE_DELETE (otab, Occs, 2*vsize); LOG ("reset occurrence lists"); otab = 0; } /*------------------------------------------------------------------------*/ // One-sided occurrence counter (each literal has its own counter). void Internal::init_noccs () { assert (!ntab); NEW_ZERO (ntab, long, 2*vsize); LOG ("initialized two-sided occurrence counters"); } void Internal::reset_noccs () { assert (ntab); DELETE_ONLY (ntab, long, 2*vsize); LOG ("reset two-sided occurrence counters"); ntab = 0; } }
ec7b9b7103681e2383f5f24ba92ff9804cc68a44
[ "C++", "Shell" ]
7
Shell
jamesbornholt/cadical
d60a22bd3c25d243b7928c16acf5968af017896e
21c04364941f50eb3f85ad389986ad083fdd15b9
refs/heads/master
<repo_name>cjvaughn/CEMRACS_MFG<file_sep>/main.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jul 24 09:24:22 2017 @author: christy """ import numpy as np import math import copy def b(i,j,X,Y,Z,X_initial_probs): num_initial=len(X[0]) Y_mean=0 for k in range(len(Y[i])): num_per_initial=len(Y[i])/num_initial index=int(math.floor(k/num_per_initial)) Y_mean+=Y[i][k]*X_initial_probs[index]/num_per_initial return -rho*Y_mean def b_example_72(i,j,X,Y,Z,X_initial_probs): return rho*math.cos(Y[i][j]) def f(i,j,X,Y,Z): return a*Y[i][j] def g(x): return x def g_example_72(x): return math.sin(x) def solver_bar(X,Y_terminal,X_initial_probs,Y_old): num_initial=len(X[0]) Y=[] Z=[] for i in range(num_t_fine): row2=np.zeros((num_initial*2**i)) row3=np.zeros((num_initial*2**i)) Y.append(row2) Z.append(row3) for j in range(len(Y[num_t_fine-1])): Y[num_t_fine-1][j]=Y_terminal[j] for k in range(J): if k>0: Y_old=Y if use_example_72: #evaluate at T # for j in range(num_initial*2**(num_t_fine-1)): # Y[num_t_fine-1][j]=math.sin(X[num_t_fine-1][j]) for n in range(num_t_fine-1): i=num_t_fine-2-n for j in range(num_initial*2**i): Y[i][j]=(Y[i+1][2*j]+Y[i+1][2*j+1])/2.0 else: for n in range(num_t_fine-1): i=num_t_fine-2-n for j in range(num_initial*2**i): #Y[i][j]=(Y[i+1][2*j]+Y[i+1][2*j+1]+delta_t_fine*f(i+1,2*j,X,Y,Z)+delta_t_fine*f(i+1,2*j+1,X,Y,Z))/2.0 Y[i][j]=(Y[i+1][2*j]+Y[i+1][2*j+1])/2.0+delta_t_fine*f(i,j,X,Y_old,Z) Z[i][j]=delta_W/delta_t_fine*(Y[i+1][2*j]-Y[i+1][2*j+1])/2.0 for i in range(num_t_fine-1): for j in range(num_initial*2**i): if use_example_72: X[i+1][2*j]=X[i][j]+delta_t_fine*b_example_72(i,j,X,Y,Z,X_initial_probs)+sigma*delta_W X[i+1][2*j+1]=X[i][j]+delta_t_fine*b_example_72(i,j,X,Y,Z,X_initial_probs)-sigma*delta_W else: X[i+1][2*j]=X[i][j]+delta_t_fine*b(i,j,X,Y,Z,X_initial_probs)+sigma*delta_W X[i+1][2*j+1]=X[i][j]+delta_t_fine*b(i,j,X,Y,Z,X_initial_probs)-sigma*delta_W return [X,Y,Z] def solver(level,xi_vals,xi_probs): #print('Executing solver[level] for level=',level) num_initial=len(xi_vals) if level==num_t_coarse-1: #print('break condition') Y_terminal=np.zeros((num_initial)) for i in range(num_initial): if use_example_72: Y_terminal[i]=g_example_72(xi_vals[i]) else: Y_terminal[i]=g(xi_vals[i]) return Y_terminal X=[] for i in range(num_t_fine): X.append([]) for k in range(num_initial): row1=xi_vals[k]*np.ones((2**i)) X[i]=np.concatenate((X[i],row1)) X_terminal_probs=[] for k in range(num_initial): row4=xi_probs[k]*(0.5)**(num_t_fine-1)*np.ones((2**(num_t_fine-1))) X_terminal_probs=np.concatenate((X_terminal_probs,row4)) Y_terminal=np.zeros(num_initial*(2**(num_t_fine-1))) num_initial=len(X[0]) Y=[] for i in range(num_t_fine): row2=np.zeros((num_initial*2**i)) Y.append(row2) X=(solver_bar(X,Y_terminal,xi_probs,Y))[0] for j in range(J): X_terminal=X[num_t_fine-1] #figure out how to break from loop if j==1 and level==num_t_coarse-2: Y_terminal=solver(level+1,X_terminal,X_terminal_probs) else: Y_terminal=solver(level+1,X_terminal,X_terminal_probs) [X,Y,Z]=solver_bar(X,Y_terminal,xi_probs,Y) #printing Y[0] for each iteration to observe bifurcation if level==0: print('Iteration ',j) print(Y[0]) Y_initial=Y[0] if level==0: return [Y_initial,X,Y,Z] return Y_initial if __name__ == '__main__': global J J=5 T=1.0 global num_t_coarse num_t_coarse=2 global delta_t_coarse delta_t_coarse=T/(num_t_coarse-1) global num_t_fine num_t_fine=3 global delta_t_fine delta_t_fine=delta_t_coarse/(num_t_fine-1) global sigma sigma=1 global delta_W delta_W=math.sqrt(delta_t_fine) global rho rho=0.1 global a a=0.25 global use_example_72 use_example_72=False x_0=[2.0] x_0_probs=[1.0] [Y_initial,X,Y,Z]=solver(0,x_0,x_0_probs) Y_0=0 m_0=0 for k in range(len(x_0)): Y_0+=Y_initial[k]*x_0_probs[k] m_0+=x_0[k]*x_0_probs[k] true_Y_0=m_0*math.exp(a*T)/(1+rho/a*(math.exp(a*T)-1.0)) print('True Answer: Y_0=') print(true_Y_0) print('Our Answer: Y_0=') print(Y_0) print('Log Num Time Steps') print(math.log(num_t_fine-1)) print('Log Difference') print(math.log(abs(true_Y_0-Y_0)))
add5dd1529762910d5edb0fbf4afa22ddf688ba8
[ "Python" ]
1
Python
cjvaughn/CEMRACS_MFG
c76f74e62935dc3b03191b50a52960e50edc0616
f183a123f05758d98abb3e86abc62bba186432a5
refs/heads/master
<file_sep>########################################################################################################## # # pwrRasch: Statistical Power Simulation for Testing the Rasch Model # # Internal function: Vectorized computation of Three-Way ANOVA for balanced design # # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # ########################################################################################################## aov.rasch.sim.vec <- function(data) { group <- data$group person <- data$person item <- data$item response <- data[, grep("response", colnames(data)):ncol(data)] a <- length(unique(group)) b <- length(unique(person)) c <- length(unique(item)) ### SS.T <- (1/(a*b/a*c))*colSums(response)^2 SS.A <- colSums(rowsum(response, group)^2)*(1/(b/a*c)) SS.B <- colSums(rowsum(response, person)^2)*(1/c) SS.C <- colSums(rowsum(response, item)^2)*(1/(a*b/a)) ### SS.interm. <- rbind(rowsum(response[group == 1,], item[group == 1]), rowsum(response[group == 2,], item[group == 2])) SS.BC <- colSums(SS.interm.) SS.AC <- colSums(SS.interm.^2)*(1/(b/a)) ### F.AC <- ((SS.AC - SS.A - SS.C + SS.T)/(c - 1)) / ((SS.BC - SS.B - SS.AC + SS.A)/(a*(b/a - 1)*(c - 1))) p.AC <- pf(F.AC, c - 1, a*(b/a - 1)*(c - 1), lower.tail = FALSE) ### return(p.AC) }<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/pwrRasch.R \docType{package} \name{pwrRasch} \alias{pwrRasch} \alias{pwrRasch-package} \title{Statistical Power Simulation for Testing the Rasch Model} \description{ Statistical power simulation for testing the Rasch Model based on a three-way analysis of variance design with mixed classification. } \author{ <NAME> [aut,cre] \email{<EMAIL>}, <NAME> [aut] \email{<EMAIL>}, <NAME> [ctb] Maintainer: <NAME> <<EMAIL>> } \references{ <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. <NAME>. (2008). An efficient MCMC algorithm to sample binary matrices with fixed marginals. \emph{Psychometrika, 73}(4), 705-728. <NAME>., <NAME>., & <NAME>. (2007). The Rasch sampler. \emph{Journal of Statistical Software, 20}(4), 1-14. } \seealso{ \link{aov.rasch}, \link{pwr.rasch} } <file_sep>#' Simulation to Estimate Statistical Power of a Rasch Model Test #' #' This function conducts a simulation to estimate statistical power #' of a Rasch model test for user-specified item and person parameters. #' #' The F-test in a three-way analysis of variance design \eqn{(A \succ \mathbf{B}) x C}{}(A > \strong{B}) x C #' with mixed classification (fixed factor A = subgroup, random factor B = testee, #' and fixed factor C = items) is used to simulate statistical power of a #' Rasch model test. This approach using a F-distributed statistic, where #' the sample size directly affects the degree of freedom enables determination #' of the sample size according to a given type I and type II risk, and according #' to a certain effect of model misfit which is of practical relevance. #' Note, that this approach works as long as there exists no main effect of #' A (subgroup). Otherwise an artificially high type I risk of the A x C interaction #' F-test results - that is, the approach works as long as no statistically significant #' main effect of A occurs. #' #' @param b Either a vector or an integer indicating the number of observations in each group. #' @param ipar Item parameters in both groups specified in a list. #' @param ppar Person parameters specified by a distribution for each group. #' @param runs Number of simulation runs. #' @param H0 If \code{TRUE}, null hypothesis condition is simulated. #' @param sig.level Nominal significance level. #' @param method Simulation method: for-loop or vectorized. #' @param output If \code{TRUE}, output is shown. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @references #' <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model #' calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. #' #' <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. #' \emph{Educational Research and Evaluation, 17}, 321-333. #' #' @return Returns a list with following entries: #' #' \tabular{ll}{ #' \code{b} \tab number of observations in each group \cr #' \code{ipar} \tab item parameters in both subgroups \cr #' \code{c} \tab number of items \cr #' \code{ppar} \tab distribution of person parameters \cr #' \code{runs} \tab number of simulation runs \cr #' \code{sig.level} \tab nominal significance level \cr #' \code{H0.AC.p} \tab \emph{p}-values of the interaction A x C in the null hypothesis condition (if \code{H0 = TRUE}) \cr #' \code{H1.AC.p} \tab \emph{p}-values of the interaction A x C in the alternative hypothesis condition \cr #' \code{power} \tab estimated statistical power \cr #' \code{type1} \tab estimated significance level \cr #' } #' #' @seealso #' \code{\link{aov.rasch}} #' #' @export #' #' @examples #' \dontrun{ #' #' # item parameters #' ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) #' # model differential item function (DIF) #' ipar2[10] <- ipar1[11] #' ipar2[11] <- ipar1[10] #' # simulation for b = 200 #' pwr.rasch(200, ipar = list(ipar1, ipar2)) #' #' # simulation for b = 100, 200, 300, 400, 500 #' pwr.rasch(seq(100, 500, by = 100), ipar = list(ipar1, ipar2)) #' #' # simulation for b = 100, 200, 300, 400, 500 #' # uniform distribution [-3, 3] of person parameters #' pwr.rasch(200, ipar = list(ipar1, ipar2), ppar = list("runif(b, -3, 3)", "runif(b, -3, 3)")) #' } pwr.rasch <- function(b, ipar = list(), ppar = list("rnorm(b, mean = 0, sd = 1.5)", "rnorm(b, mean = 0, sd = 1.5)"), runs = 1000, H0 = TRUE, sig.level = 0.05, method = c("loop", "vectorized"), output = TRUE) { #--------------------------------------------------------------------------------------------------------# # Input Check l.call <- match.call() # sum of item parameters = 0 if (all(round(unlist(lapply(ipar, sum)), 3) != 0)) { stop("Item pararameters are not normalized to sum-0") } # number of items if (length(unique(unlist(lapply(ipar, length)))) != 1) { stop("Different number of items specified in both groups") } #--------------------------------------------------------------------------------------------------------# cat("--------------------------------------------------------\n") cat(" Call: "); print(l.call) cat(" Time: ", time <- paste(Sys.time()), "\n") cat(" R: ", R.version$version.string, "\n") cat(" Package:", pkg.version<- paste0("pwrRasch version ", packageDescription("pwrRasch")$Version, " (", packageDescription("pwrRasch")$Date, ")"), "\n") cat("--------------------------------------------------------\n") if (length(b) == 1) { simres <- pwr.rasch.internal(b = b, ipar = ipar, ppar = ppar, runs = runs, H0 = H0, sig.level = sig.level, method = method, output = output) } else { # length(b) > 1 j <- 1 simres <- NULL for (i in b) { if (i == b[1]) { simres[[j]] <- pwr.rasch.internal(b = i, ipar = ipar, ppar = ppar, runs = runs, H0 = H0, sig.level = sig.level, method = method, output = FALSE) j <- j + 1 } else { simres[[j]] <- pwr.rasch.internal(b = i, ipar = ipar, ppar = ppar, runs = runs, H0 = H0, sig.level = sig.level, method = method, output = FALSE) j <- j + 1 } } } #------------------------------------------------------------------------------------------------------# # Output if (length(b) == 1) { if (output == TRUE) { c <- unique(unlist(lapply(ipar, length))) if (H0 == TRUE) { cat("\n Statistical Power Simulation for the Rasch model \n\n", " b (number of persons in each group): ", b, "\n", " c (number of items): ", c, "\n", " simulation runs: ", runs, "\n\n", " Estimated statistical power: ", formatC(simres$power, format = "f", digits = 3), "\n", " Nominal significance level: ", sig.level, "\n", " Empirical significance level:", formatC(simres$type1, format = "f", digits = 3), "\n") } else { cat("\n Statistical Power Simulation for the Rasch model \n\n", " b (numer of persons in each group): ", b, "\n", " c (numer of items): ", c, "\n", " simulation runs: ", runs, "\n\n", " Estimated statistical power: ", formatC(simres$power, format = "f", digits = 3), "\n", " Nominal significance level: ", sig.level, "\n") } cat("--------------------------------------------------------\n") } #------------------------------------------------------------------------------------------------------# # Warnings if (H0 == TRUE) { # Warning: Nominal vs. empirical significane level if (round(sum(simres$H0.AC.p < sig.level) / runs, 3) < (sig.level - sig.level / 100 * 20) | round(sum(simres$H0.AC.p < sig.level) / runs, 3) > (sig.level + sig.level / 100 * 20)) { warning("F-test does not hold its type-I-risk with 20%-robusteness, i.e, results may not be trustworthy.") } } } else { # length(b) > 1 if (output == TRUE) { cat("\n Statistical Power Simulation for the Rasch model \n\n", " b (numer of persons in each group): ", paste(b, collapse = ", "), "\n", " c (numer of items): ", unique(unlist(lapply(ipar, length))), "\n", " simulation runs: ", runs, "\n\n", " Estimated statistical power: \n") for (i in 1:length(simres)) { cat(paste0(" b = ", formatC(b[i], digits = max(nchar(b)) - 1, format = "d"), ":"), formatC(simres[[i]][["power"]], format = "f", digits = 3), "\n") } cat("\n Nominal significance level: ", sig.level, "\n") if (H0 == TRUE) { cat("\n Empirical significance level: \n") for (i in 1:length(simres)) { cat(paste0(" b = ", formatC(b[i], digits = max(nchar(b)) - 1, format = "d"), ":"), formatC(simres[[i]][["type1"]], format = "f", digits = 3), "\n") } } cat("------------------------------------------------------\n") } #------------------------------------------------------------------------------------------------------# # Warnings if (H0 == TRUE) { # Warning: Nominal vs. empirical significane level sig.level.act <- unlist(lapply(simres, function(x) sum(x$H0.AC.p < sig.level) / runs)) if (any(sig.level.act < (sig.level - sig.level / 100 * 20)) | any(sig.level.act > (sig.level + sig.level / 100 * 20))) { warning("F-test does not hold its type-I-risk with 20%-robusteness, i.e, results may not be trustworthy.") } } } class(simres) <- "pwrrasch" return(invisible(simres)) } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/pwrRasch.R \docType{data} \name{aid_st2} \alias{aid_st2} \title{Sample of test data from subtest 2 of the Adaptive Intelligence Diagnosticum (AID3; Kubinger \& Holocher-Ertl, 2014)} \format{A data frame with 300 rows and 28 variables: \itemize{ \item ID: ID variable of each testee \item age_in_month: the age of the testperson in month \item sex: gender of the testee \item country: country of the testee \item stage: stage of the data collection \item it1...it18: items of the subtest 2 }} \usage{ aid_st2 } \description{ A dataset containing the test data of 300 childen (drawn randomly from the original dataset). The variables are as follows: } \keyword{datasets} <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/plot.pwrrasch.R \name{plot.pwrrasch} \alias{plot.pwrrasch} \title{Plot Statistical Power Curve} \usage{ \method{plot}{pwrrasch}(x, plot.sig.level = TRUE, type = c("b", "b"), pch = c(19, 17), lty = c(1, 3), lwd = c(1, 1), legend = "topleft", bty = "o", ...) } \arguments{ \item{x}{\code{pwrrasch} object.} \item{plot.sig.level}{If \code{TRUE}, nominal significance level is plotted.} \item{type}{Vector indicating type of plot for the statistica power curve and the type 1 risk curve.} \item{pch}{Vector indicating plotting symbol for the statistical power curve and the type 1 risk curve.} \item{lty}{Vector indicating line type for the statistical power curve and the type 1 risk curve.} \item{lwd}{Vector indicating line width for the statistical power curve and the type 1 risk curve.} \item{legend}{Location of the legend. If \code{FALSE}, legend is omitted.} \item{bty}{Type of box to be drawn around the legend.} \item{...}{Additional arguments affecting the summary produced.} } \description{ Generic \code{plot} function for the \code{pwrrasch} object, which plots the statistical power curve relating statistical power to sample size } \details{ Graphical parameters are: \itemize{ \item{\code{type}} The following values are possible: \code{"p"} for points, \code{"l"} for lines, \code{"b"} for both point and lines \item{\code{pch}} see \link[graphics]{points} \item{\code{lty}} Line types can be specified as an integer (\code{0} = blank, \code{1} = solid, \code{2} = dashed, \code{3} = dotted, \code{4} = dotdash, \code{5} = longdash, \code{6} = twodash) \item{\code{lwd}} Positive numbers indicating line widths \item{\code{legend}} Either the x and y coordinates to be used to position the legend or keyword from the list \code{"bottomright"}, \code{"bottom"}, \code{"bottomleft"}, \code{"left"}, \code{"topleft"}, \code{"top"}, \code{"topright"}, \code{"right"} and \code{"center"} \item{\code{bty}} Allowed values are "o" (draw box around legend) and "n" (do not draw box around legend). } } \examples{ \dontrun{ # item parameters ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) # model differential item function (DIF) ipar2[10] <- ipar1[11] ipar2[11] <- ipar1[10] # simulation for b = 100, 200, 300, 400, 500 simres <- pwr.rasch(seq(100, 500, by = 100), ipar = list(ipar1, ipar2)) plot(simres) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } \references{ <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. } <file_sep>########################################################################################################## # # pwrRasch: Statistical Power Simulation for Testing the Rasch Model # # Internal function: ANOVA balanced # # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # ########################################################################################################## aov.rasch.balanced <- function(data, group = "group", person = "person", item = "item", response = "response", output = TRUE) { eval(parse(text = paste0(group, " <- data$", group))) eval(parse(text = paste0(person, " <- data$", person))) eval(parse(text = paste0(item, " <- data$", item))) eval(parse(text = paste0(response, " <- data$", response))) a <- length(unique(group)) b <- length(unique(person)) c <- length(unique(item)) ### SS.T <- (1/(a*b/a*c))*sum(response)^2 SS.A <- sum(rowsum(response, group)^2)*(1/(b/a*c)) - SS.T SS.B <- sum(rowsum(response, person)^2)*(1/c) - SS.T - SS.A SS.C <- sum(rowsum(response, item)^2)*(1/(a*b/a)) - SS.T SS.interm. <- c(rowsum(response[group == 1], item[group == 1]),rowsum(response[group == 2], item[group == 2])) SS.AC <- sum(SS.interm.^2)*(1/(b/a)) - SS.A - SS.C - SS.T SS.BC <- sum(SS.interm.) - SS.T - SS.B - SS.C - SS.AC - SS.A ### df.B <- a*(b/a - 1) df.C <- c - 1 df.BC <- df.B*df.C ### MS.A <- SS.A MS.B <- SS.B / df.B MS.C <- SS.C / df.C MS.BC <- SS.BC / df.BC MS.AC <- SS.AC / df.C ### F.A <- MS.A / MS.B F.B <- MS.B / MS.BC F.C <- MS.C / MS.BC F.AC <- MS.AC / MS.BC ### p.A <- pf(F.A, 1, df.B, lower.tail = FALSE) p.B <- pf(F.B, df.B, df.BC, lower.tail = FALSE) p.C <- pf(F.C, df.C, df.BC, lower.tail = FALSE) p.AC <- pf(F.AC, df.C, df.B*df.C, lower.tail = FALSE) #------------------------------------------------------------------------------------------------------# # Output if (output == TRUE) { cat("Three-way analysis of variance with mixed classification \n\n") printCoefmat(matrix(c(df.C, SS.AC, MS.AC, F.AC, p.AC), ncol = 5, dimnames = list("group:item", c("DF", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"))), has.Pvalue = TRUE, cs.ind = 0) # Warning: Statistically significant Main Effect A if (p.A < .05) { warning(paste0("Main effect A (group) is statistically significant, ", "F(1, ", df.B, ") = ", formatC(F.A, format = "f", digits = 3), ", p = ", formatC(p.A, format = "f", digits = 3), ", i.e. results may not be trustworthy.")) } } #------------------------------------------------------------------------------------------------------# # Return restab <- matrix(c(1, SS.A, MS.A, F.A, p.A, df.B, SS.B, MS.B, F.B, p.B, df.C, SS.C, MS.C, F.C, p.C, df.C, SS.AC, MS.AC, F.AC, p.AC, df.BC, SS.BC, MS.BC, NA, NA), ncol = 5, byrow = TRUE, dimnames = list(c("group", "person(group)", "item", "group:item", "Residuals"), c("DF", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"))) return(invisible(restab)) }<file_sep>########################################################################################################## # # pwrRasch: Statistical Power Simulation for Testing the Rasch Model # # Internal function: ANOVA unbalanced # # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # ########################################################################################################## aov.rasch.unbalanced <- function(data, group = "group", person = "person", item = "item", response = "response", output = TRUE) { eval(parse(text = paste0("data$", group, " <- as.factor(data$", group, ")"))) eval(parse(text = paste0("data$", person, " <- as.factor(data$", person, ")"))) eval(parse(text = paste0("data$", item, " <- as.factor(data$", item, ")"))) formula <- paste(response, "~", paste(group, item, paste(group, item, sep = ":"), paste0("Error(", person, " + ", person, ":", item,")"),sep = " + ")) data.aov <- summary(aov(eval(parse(text = formula)), data = data)) #------------------------------------------------------------------------------------------------------# # Output if (output == TRUE) { cat("Three-way analysis of variance with mixed classification \n\n") print(unclass(data.aov[[2]])[[1]][2, ]) if (data.aov[[1]][[1]][1, "Pr(>F)"] < .05) { warning(paste0("Main effect A (group) is statistically significant, F(1, ", data.aov[[1]][[1]][2, "Df"], ") = ", formatC(data.aov[[1]][[1]][1, "F value"], format = "f", digits = 3), ", p = ", formatC(data.aov[[1]][[1]][1, "Pr(>F)"], format = "f", digits = 3), ", i.e. results may not be trustworthy.")) } } #------------------------------------------------------------------------------------------------------# # Return F.B <- data.aov[[1]][[1]][2, "Mean Sq"] / data.aov[[2]][[1]][3, "Mean Sq"] p.B <- pf(F.B, data.aov[[1]][[1]][2, "Df"], data.aov[[2]][[1]][3, "Df"], lower.tail = FALSE) restab <- matrix(unlist(c(data.aov[[1]][[1]][1, ], data.aov[[1]][[1]][2, 1:3], F.B, p.B, data.aov[[2]][[1]][1, ], data.aov[[2]][[1]][2, ], data.aov[[2]][[1]][3, ])), ncol = 5, byrow = TRUE, dimnames = list(c("group", "person(group)", "item", "group:item", "Residuals"), c("DF", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"))) return(invisible(restab)) }<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/simul.rasch.R \name{simul.rasch} \alias{simul.rasch} \title{Simulate data according to the Rasch model} \usage{ simul.rasch(persons, items, sum0 = TRUE) } \arguments{ \item{persons}{Either a vector of specified person parameters or an integer indicating the number of persons.} \item{items}{Either a vector of specified item parameters or an integer indicating the number of items.} \item{sum0}{If \code{TRUE}, specified item parameters need to be normalized to sum-0.} } \value{ Returns a 0-1 matrix according to the Rasch model. } \description{ This function simulates data according to the Rasch model based on user-specified item and person parameters. } \details{ If persons is an integer value, the corresponding parameter vector is drawn from N(0, 1.5). If items is an integer value, the corresponding parameter vector is equally spaced between [-3, 3]. Note that item parameters need to be normalized to sum-0. This precondition can be overruled using argument \code{sum0 = FALSE}. } \examples{ \dontrun{ # simulate Rasch model based data # 100 persons, 20 items, # person parameter drawn from a normal distribution: N(0,1.5) # item parameters equally spaced between [-3, 3] simul.rasch(100, items = 20) # simulate Rasch model based data # 100 persons, 17 items # person parameter drawn from a uniform distribution: U[-4, 4] # item parameters: [-4.0, -3.5, -3.0, ... , 3.0, 3.5, 4.0] simul.rasch(runif(100, -4, 4), items = seq(-4, 4, by = 0.5)) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } \references{ <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. } \seealso{ \code{\link{aov.rasch}}, \code{\link{pwr.rasch}} } <file_sep>#' Plot Statistical Power Curve #' #' Generic \code{plot} function for the \code{pwrrasch} object, which #' plots the statistical power curve relating statistical power to sample size #' #' @details Graphical parameters are: #' \itemize{ #' \item{\code{type}} The following values are possible: \code{"p"} for points, #' \code{"l"} for lines, \code{"b"} for both point and lines #' \item{\code{pch}} see \link[graphics]{points} #' \item{\code{lty}} Line types can be specified as an integer (\code{0} = blank, \code{1} = solid, #' \code{2} = dashed, \code{3} = dotted, \code{4} = dotdash, \code{5} = longdash, #' \code{6} = twodash) #' \item{\code{lwd}} Positive numbers indicating line widths #' \item{\code{legend}} Either the x and y coordinates to be used to position the legend or #' keyword from the list \code{"bottomright"}, \code{"bottom"}, \code{"bottomleft"}, #' \code{"left"}, \code{"topleft"}, \code{"top"}, \code{"topright"}, \code{"right"} #' and \code{"center"} #' \item{\code{bty}} Allowed values are "o" (draw box around legend) and "n" (do not draw box around legend). #' } #' #' @param x \code{pwrrasch} object. #' @param plot.sig.level If \code{TRUE}, nominal significance level is plotted. #' @param type Vector indicating type of plot for the statistica power curve #' and the type 1 risk curve. #' @param pch Vector indicating plotting symbol for the statistical power curve #' and the type 1 risk curve. #' @param lty Vector indicating line type for the statistical power curve #' and the type 1 risk curve. #' @param lwd Vector indicating line width for the statistical power curve #' and the type 1 risk curve. #' @param legend Location of the legend. If \code{FALSE}, legend is omitted. #' @param bty Type of box to be drawn around the legend. #' @param ... Additional arguments affecting the summary produced. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @references #' <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model #' calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. #' #' <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. #' \emph{Educational Research and Evaluation, 17}, 321-333. #' #' @export #' #' @examples #' \dontrun{ #' #' # item parameters #' ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) #' # model differential item function (DIF) #' ipar2[10] <- ipar1[11] #' ipar2[11] <- ipar1[10] #' # simulation for b = 100, 200, 300, 400, 500 #' simres <- pwr.rasch(seq(100, 500, by = 100), ipar = list(ipar1, ipar2)) #' plot(simres) #' } plot.pwrrasch <- function(x, plot.sig.level = TRUE, type = c("b", "b"), pch = c(19, 17), lty = c(1, 3), lwd = c(1, 1), legend = "topleft", bty = "o", ...) { #--------------------------------------------------------------------------------------------------------# # Input Check if (length(x[[1]]) == 1) { stop("Object pwrrasch contains result of only one b.") } #--------------------------------------------------------------------------------------------------------# b <- unlist(lapply(x, function(x) x$b)) pwr <- unlist(lapply(x, function(x) x$power)) type1 <- unlist(lapply(x, function(x) x$type1)) sig.level <- unique(unlist(lapply(x, function(x) x$sig.level))) ### plot(b, pwr, type = type[1], lty = lty[1], pch = pch[1], lwd = lwd[1], xlab = "", ylab = "", ylim = c(0, 1), axes = FALSE) axis(1, at = b) axis(2, at = seq(0, 1, by = 0.1)) mtext("b (number of persons in each group)", side = 1, line = 2.25) mtext("Estimated statistical power", side = 2, line = 2.25) box() ### for (i in 1:length(b)) { lines(c(b[i], b[i]), c(0, pwr[i]), lty = 2, col = "gray70") lines(c(b[i], 0), c(pwr[i], pwr[i]), lty = 2, col = "gray70") } points(b, pwr, pch = pch[1], type = type[1]) ### if (!is.null(type1) & plot.sig.level == TRUE) { lines(c(0, max(b)), c(sig.level, sig.level), col = "red2") points(b, type1, type = type[2], lty = lty[2], pch = pch[2], lwd = lwd[2]) if (legend[1] != FALSE) { if (length(legend) == 1) { legend(legend, c("statistical power", "type 1 error risk"), pch = pch, lty = lty, lwd = lwd, cex = 0.9, bty = bty) } else { legend(legend[1], legend[2], c("statistical power", "type 1 error risk"), pch = pch, lty = lty, lwd = lwd, cex = 0.9, bty = bty) } } } else { if (legend[1] != FALSE) { if (length(legend) == 1) { legend(legend, "statistical power", pch = pch[1], lty = lty[1], lwd = lwd[1], cex = 0.9, bty = bty) } else { legend(legend[1], legend[2], "statistical power", pch = pch[1], lty = lty[1], lwd = lwd[1], cex = 0.9, bty = bty) } } } }<file_sep>#' Simulate data according to the Rasch model #' #' This function simulates data according to the Rasch model #' based on user-specified item and person parameters. #' #' If persons is an integer value, the corresponding parameter vector #' is drawn from N(0, 1.5). If items is an integer value, the corresponding parameter vector #' is equally spaced between [-3, 3]. Note that item parameters need to be normalized to sum-0. #' This precondition can be overruled using argument \code{sum0 = FALSE}. #' #' @param persons Either a vector of specified person parameters or an integer indicating the number of persons. #' @param items Either a vector of specified item parameters or an integer indicating the number of items. #' @param sum0 If \code{TRUE}, specified item parameters need to be normalized to sum-0. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @seealso #' \code{\link{aov.rasch}}, \code{\link{pwr.rasch}} #' #' @references #' <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model #' calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. #' #' <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. #' \emph{Educational Research and Evaluation, 17}, 321-333. #' #' @return #' Returns a 0-1 matrix according to the Rasch model. #' #' @export #' #' @examples #' \dontrun{ #' #' # simulate Rasch model based data #' # 100 persons, 20 items, #' # person parameter drawn from a normal distribution: N(0,1.5) #' # item parameters equally spaced between [-3, 3] #' simul.rasch(100, items = 20) #' #' # simulate Rasch model based data #' # 100 persons, 17 items #' # person parameter drawn from a uniform distribution: U[-4, 4] #' # item parameters: [-4.0, -3.5, -3.0, ... , 3.0, 3.5, 4.0] #' simul.rasch(runif(100, -4, 4), items = seq(-4, 4, by = 0.5)) #' } simul.rasch <- function(persons, items, sum0 = TRUE) { #------------------------------------------------------------------------------------------------------# # Input Check # sum of item parameters = 0 if (length(items) == 1) { if (sum0 == TRUE & round(sum(seq(-3, 3, length.out = items)), digits = 3) != 0) { stop("Item pararameters are not normalized to sum-0") } } else { if (sum0 == TRUE & sum(round(items, digits = 3)) != 0) { stop("Item pararameters are not normalized to sum-0") } } #------------------------------------------------------------------------------------------------------# # item parameters if (length(items) == 1) { diff <- seq(-3, 3, length.out = items) n.items <- items } else { diff <- items n.items <- length(items) } # person parameters if (length(persons) == 1) { ability <- rnorm(persons, sd = 1.5) n.persons <- persons } else { ability <- persons n.persons <- length(persons) } fsmat <- outer(ability, diff, "-") psolve <- exp(fsmat) / (1 + exp(fsmat)) resmat <- (matrix(runif(n.items * n.persons), n.persons, n.items) < psolve) * 1 return(resmat) }<file_sep>#' @importFrom utils packageDescription #' .onAttach <- function(libname, pkgname){ desc <- packageDescription("pwrRasch") d1 <- desc$Version nk <- paste0(rep(" ", 20 - nchar(d1))) packageStartupMessage("|----------------------------------------------------------|\n", paste0("| ", desc$Package, " ", d1," (",desc$Date,")"), nk, " |\n" , "| Statistical Power Simulation for Testing the Rasch Model |\n" , "|----------------------------------------------------------|" ) } version <- function(pkg = "pwrRasch") { lib <- dirname(system.file(package = pkg)) desc <- packageDescription(pkg) return(paste(desc$Package, desc$Version, desc$Date,lib)) } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/summary.pwrrasch.R \name{summary.pwrrasch} \alias{summary.pwrrasch} \title{Object Summary} \usage{ \method{summary}{pwrrasch}(object, ...) } \arguments{ \item{object}{\code{pwrrasch} object} \item{...}{Additional arguments affecting the summary produced.} } \description{ Generic \code{summary} function for the \code{pwrrasch} object } \examples{ \dontrun{ # item parameters ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) # model differential item function (DIF) ipar2[9] <- ipar1[12] ipar2[12] <- ipar1[9] # simulation for b = 100 simres <- pwr.rasch(100, ipar = list(ipar1, ipar2)) summary(simres) # item parameters ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) # model differential item function (DIF) ipar2[10] <- ipar1[11] ipar2[11] <- ipar1[10] # simulation for b = 100, 200, 300, 400, 500 simres <- pwr.rasch(seq(100, 500, by = 100), ipar = list(ipar1, ipar2)) summary(simres) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/itemtable.R \name{itemtable} \alias{itemtable} \title{Summary of DIF items} \usage{ itemtable(object, all = FALSE, digits = 2) } \arguments{ \item{object}{\code{pwrrasch} object} \item{all}{If \code{TRUE}, all items are included in the table.} \item{digits}{Integer indicating the number of decimal places.} } \description{ This function builds a table of DIF items specified in the \code{pwrrasch} object } \examples{ \dontrun{ # item parameters ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) # model differential item function (DIF) ipar2[10] <- ipar1[11] ipar2[11] <- ipar1[10] # simulation for b = 100 simres <- pwr.rasch(100, ipar = list(ipar1, ipar2)) itemtable(simres) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } <file_sep>########################################################################################################## # # pwrRasch: Statistical Power Simulation for Testing the Rasch Model # # Internal function: Simulation # # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # ########################################################################################################## pwr.rasch.internal <- function(b = b, ipar = ipar, ppar = ppar, runs = runs, H0 = H0, sig.level = sig.level, method = method, output = output) { #-----------------------------------------------------------------------------------------------------# # Numer of observations b and number of items c # b (number of observation per group) if (length(eval(parse(text = ppar[[1]]))) != length(eval(parse(text = ppar[[2]])))) { stop("Different numbers of persons specified in both groups") } # c (number of items) c <- unique(unlist(lapply(ipar, length))) #-----------------------------------------------------------------------------------------------------# # Simulation method <- ifelse(all(c("loop", "vectorized") %in% method), "vectorized", method) if (!method %in% c("loop", "vectorized")) { stop(paste0("Option \"", method, "\" for argument method unknown, use \"loop\" or \"vectorized\"")) } gc() ### for-loop if (method == "loop") { x <- switch(as.character(nchar(format(runs, scientific = FALSE))), "1" = 9, "2" = 7, "3" = 5, "4" = 3, "5" = 1, "6" = 1, "7" = 1, "8" = 1, "9" = 1, "10" = 1) group <- c(rep(0, times = b), rep(1, times = b)) # H0 condition if (H0 == TRUE) { cat(paste0(" Conducting H0 simulation... ", t1 <- Sys.time(), "\n")) H0.AC.p <- NULL for (i in 1:runs) { cat("\r", paste0(" run ", formatC(i, digits = nchar(runs) - 1, format = "d", flag = 0)," of ",runs,"...")) # Simulate 0/1 data dat <- rbind(simul.rasch(eval(parse(text = ppar[[1]])), ipar[[1]]), simul.rasch(eval(parse(text = ppar[[2]])), ipar[[1]])) # Three-way analysis of variance with mixed classification H0.AC.p <- c(H0.AC.p, aov.rasch.sim(data = reshape.rasch(dat, group = group))) } cat(paste0(" finished", paste(rep(" ", times = x), collapse = ""), Sys.time(),"\n")) } # H1 condition H1.AC.p <- NULL cat(paste0(" Conducting H1 simulation... ", if (H0 == FALSE) t1 <- Sys.time() else Sys.time(), "\n")) for (i in 1:runs) { cat("\r", paste0(" run ", formatC(i, digits = nchar(runs) - 1, format = "d", flag = 0)," of ", runs,"...")) # Simulate 0/1 data dat <- rbind(simul.rasch(eval(parse(text = ppar[[1]])), ipar[[1]]), simul.rasch(eval(parse(text = ppar[[2]])), ipar[[2]])) # Three-way analysis of variance with mixed classification H1.AC.p <- c(H1.AC.p, aov.rasch.sim(data = reshape.rasch(dat, group = group))) } cat(paste0(" finished", paste(rep(" ", times = x), collapse = ""), t2 <- Sys.time(),"\n")) } ### Vectorized computing if (method == "vectorized") { group <- c(rep(0, times = b), rep(1, times = b)) # H0 condition if (H0 == TRUE) { cat(paste0(" Conducting H0 simulation... ", t1 <- Sys.time(), "\n")) dat.mx <- rbind(simul.rasch(eval(parse(text = ppar[[1]])), ipar[[1]]), simul.rasch(eval(parse(text = ppar[[2]])), ipar[[1]])) dat.mx <- reshape.rasch(dat.mx, group = group) dat.mx1 <- simul.rasch(eval(parse(text = sub("b", "(runs-1)*b", ppar[[1]]))), ipar[[1]]) dat.mx2 <- simul.rasch(eval(parse(text = sub("b", "(runs-1)*b", ppar[[2]]))), ipar[[1]]) ### dat.mx1 <- array(dat.mx1, dim = c(b, runs - 1, ncol(dat.mx1))) dat.mx1 <- aperm(dat.mx1, c(1, 3, 2)) dat.mx1 <- matrix(dat.mx1, nrow = b*ncol(dat.mx1)) dat.mx2 <- array(dat.mx2, dim = c(b, runs - 1, ncol(dat.mx2))) dat.mx2 <- aperm(dat.mx2, c(1, 3, 2)) dat.mx2 <- matrix(dat.mx2, nrow = b*ncol(dat.mx2)) dat.mx <- cbind(dat.mx, rbind(dat.mx1, dat.mx2)) ### H0.AC.p <- unname(aov.rasch.sim.vec(data = dat.mx)) } # H1 condition cat(paste0(" Conducting H1 simulation... ", if (H0 == FALSE) t1 <- Sys.time() else Sys.time(), "\n")) dat.mx <- rbind(simul.rasch(eval(parse(text = ppar[[1]])), ipar[[1]]), simul.rasch(eval(parse(text = ppar[[2]])), ipar[[2]])) dat.mx <- reshape.rasch(dat.mx, group = group) dat.mx1 <- simul.rasch(eval(parse(text = sub("b", "(runs-1)*b", ppar[[1]]))), ipar[[1]]) dat.mx2 <- simul.rasch(eval(parse(text = sub("b", "(runs-1)*b", ppar[[2]]))), ipar[[2]]) ### dat.mx1 <- array(dat.mx1, dim = c(b, runs - 1, ncol(dat.mx1))) dat.mx1 <- aperm(dat.mx1, c(1, 3, 2)) dat.mx1 <- matrix(dat.mx1, nrow = b*ncol(dat.mx1)) dat.mx2 <- array(dat.mx2, dim = c(b, runs - 1, ncol(dat.mx2))) dat.mx2 <- aperm(dat.mx2, c(1, 3, 2)) dat.mx2 <- matrix(dat.mx2, nrow = b*ncol(dat.mx2)) dat.mx <- cbind(dat.mx, rbind(dat.mx1, dat.mx2)) ### H1.AC.p <- unname(aov.rasch.sim.vec(data = dat.mx)) } if (method != "loop") cat(paste0(" Finished simulation... ", t2 <- Sys.time(), "\n")) cat("--------------------------------------------------------\n") print(round(t2 - t1, digits = 2)) if (H0 == TRUE) { return(list(b = b, ipar = ipar, c = c, ppar = ppar, runs = runs, sig.level = sig.level, H0.AC.p = H0.AC.p, H1.AC.p = H1.AC.p, power = sum(H1.AC.p < sig.level) / runs, type1 = sum(H0.AC.p < sig.level) / runs)) } else { return(list(b = b, ipar = ipar, c = c, ppar = ppar, runs = runs, sig.level = sig.level, H1.AC.p = H1.AC.p, power = sum(H1.AC.p < sig.level) / runs)) } }<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/summary.aovrasch.R \name{summary.aovrasch} \alias{summary.aovrasch} \title{Object Summary} \usage{ \method{summary}{aovrasch}(object, ...) } \arguments{ \item{object}{\code{aovrasch} object} \item{...}{Additional arguments affecting the summary produced.} } \description{ Generic \code{summary} function for the \code{aovrasch} object } \examples{ \dontrun{ # simulate Rasch model based data # 100 persons, 20 items, dat <- simul.rasch(100, items = seq(-3, 3, length.out = 20)) # reshape simulated data into 'long' format with balanced assignment # of examinees into two subgroups. dat.long <- reshape.rasch(dat, group = rep(0:1, each = nrow(dat) / 2)) # apply three-way analysis of variance with mixed classification for testing the Rasch model. res <- aov.rasch(dat.long) summary(res) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } <file_sep>#' Summary of DIF items #' #' This function builds a table of DIF items specified in the \code{pwrrasch} object #' #' @param object \code{pwrrasch} object #' @param all If \code{TRUE}, all items are included in the table. #' @param digits Integer indicating the number of decimal places. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @export #' #' @examples #' \dontrun{ #' #' # item parameters #' ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) #' # model differential item function (DIF) #' ipar2[10] <- ipar1[11] #' ipar2[11] <- ipar1[10] #' # simulation for b = 100 #' simres <- pwr.rasch(100, ipar = list(ipar1, ipar2)) #' itemtable(simres) #' } itemtable <- function(object, all = FALSE, digits = 2) { if (length(object[[1]]) == 1) { ipar1 <- object$ipar[[1]] ipar2 <- object$ipar[[2]] min.items <- round(min(c(ipar1, ipar2)), digits = digits) max.items <- round(max(c(ipar1, ipar2)), digits = digits) n.DIF <- sum((ipar1 - ipar2) != 0) } else { object <- object[[1]] ipar1 <- object$ipar[[1]] ipar2 <- object$ipar[[2]] min.items <- round(min(c(ipar1, ipar2)), digits = digits) max.items <- round(max(c(ipar1, ipar2)), digits = digits) n.DIF <- sum((ipar1 - ipar2) != 0) } #------------------------------------------------------------------------------------------------------# if (all == FALSE) { pos <- which((ipar1 - ipar2) != 0) ipar1 <- ipar1[pos] ipar2 <- ipar2[pos] } else { pos <- 1:length(ipar1) } if (length(pos) != 0) { itemtab <- data.frame(cbind(rbind(ipar1, ipar2, abs(ipar1 - ipar2)), c(sum(ipar1), sum(ipar2), sum(abs(ipar1 - ipar2))))) row.names(itemtab) <- c("ipar1", "ipar2", "DIF") names(itemtab) <- c(paste0("Pos", pos), "SUM") } else { itemtab <- NULL } #------------------------------------------------------------------------------------------------------# # Output cat("\nSummary of DIF items specified in the pwrrasch object\n\n", " item parameters: ", paste0("[", min.items, ", ", max.items, "]\n"), " n items: ", object$c, "\n", " n DIF items: ", n.DIF, "\n\n") if (length(pos) != 0) { printCoefmat(itemtab, digits = digits, has.Pvalue = FALSE) cat("\n") } else { cat("No DIF items specified.\n") } #------------------------------------------------------------------------------------------------------# return(invisible(itemtab)) }<file_sep>#' Statistical Power Simulation for Testing the Rasch Model #' #' Statistical power simulation for testing the Rasch Model #' based on a three-way analysis of variance design with mixed classification. #' #' @docType package #' @name pwrRasch #' #' @importFrom graphics plot legend points axis box lines mtext #' @importFrom stats pf printCoefmat rnorm runif aov #' #' @author #' <NAME> [aut,cre] \email{<EMAIL>}, #' <NAME> [aut] \email{<EMAIL>}, #' <NAME> [ctb] #' #' Maintainer: <NAME> <<EMAIL>> #' #' @seealso \link{aov.rasch}, \link{pwr.rasch} #' #' @references #' <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. #' #' <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. #' #' <NAME>. (2008). An efficient MCMC algorithm to sample binary matrices with fixed marginals. \emph{Psychometrika, 73}(4), 705-728. #' #' <NAME>., <NAME>., & <NAME>. (2007). The Rasch sampler. \emph{Journal of Statistical Software, 20}(4), 1-14. #' NULL #' Sample of test data from subtest 2 of the Adaptive Intelligence Diagnosticum (AID3; Kubinger \& Holocher-Ertl, 2014) #' #' A dataset containing the test data of 300 childen (drawn randomly from the original dataset). #' The variables are as follows: #' #' @format A data frame with 300 rows and 28 variables: #' \itemize{ #' \item ID: ID variable of each testee #' \item age_in_month: the age of the testperson in month #' \item sex: gender of the testee #' \item country: country of the testee #' \item stage: stage of the data collection #' \item it1...it18: items of the subtest 2 #' } "aid_st2" <file_sep>#' Object Summary #' #' Generic \code{summary} function for the \code{aovrasch} object #' #' @param object \code{aovrasch} object #' @param ... Additional arguments affecting the summary produced. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @importFrom stats printCoefmat #' #' @export #' #' @examples #' \dontrun{ #' #' # simulate Rasch model based data #' # 100 persons, 20 items, #' dat <- simul.rasch(100, items = seq(-3, 3, length.out = 20)) #' # reshape simulated data into 'long' format with balanced assignment #' # of examinees into two subgroups. #' dat.long <- reshape.rasch(dat, group = rep(0:1, each = nrow(dat) / 2)) #' # apply three-way analysis of variance with mixed classification for testing the Rasch model. #' res <- aov.rasch(dat.long) #' summary(res) #' } summary.aovrasch <- function(object, ...) { cat("\nThree-way analysis of variance with mixed classification \n\n") printCoefmat(object[4, , drop = FALSE], has.Pvalue = TRUE, cs.ind = 0) cat("\n") # Warning: Statistically significant Main Effect A if (object[1, "Pr(>F)"] < .05) { warning(paste0("Main effect A (group) is statistically significant, ", "F(1, ", object[2, "DF"], ") = ", formatC(object[1, "F value"], format = "f", digits = 3), ", p = ", formatC(object[1, "Pr(>F)"], format = "f", digits = 3), ", i.e. results may not be trustworthy.")) } }<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/pwr.rasch.R \name{pwr.rasch} \alias{pwr.rasch} \title{Simulation to Estimate Statistical Power of a Rasch Model Test} \usage{ pwr.rasch(b, ipar = list(), ppar = list("rnorm(b, mean = 0, sd = 1.5)", "rnorm(b, mean = 0, sd = 1.5)"), runs = 1000, H0 = TRUE, sig.level = 0.05, method = c("loop", "vectorized"), output = TRUE) } \arguments{ \item{b}{Either a vector or an integer indicating the number of observations in each group.} \item{ipar}{Item parameters in both groups specified in a list.} \item{ppar}{Person parameters specified by a distribution for each group.} \item{runs}{Number of simulation runs.} \item{H0}{If \code{TRUE}, null hypothesis condition is simulated.} \item{sig.level}{Nominal significance level.} \item{method}{Simulation method: for-loop or vectorized.} \item{output}{If \code{TRUE}, output is shown.} } \value{ Returns a list with following entries: \tabular{ll}{ \code{b} \tab number of observations in each group \cr \code{ipar} \tab item parameters in both subgroups \cr \code{c} \tab number of items \cr \code{ppar} \tab distribution of person parameters \cr \code{runs} \tab number of simulation runs \cr \code{sig.level} \tab nominal significance level \cr \code{H0.AC.p} \tab \emph{p}-values of the interaction A x C in the null hypothesis condition (if \code{H0 = TRUE}) \cr \code{H1.AC.p} \tab \emph{p}-values of the interaction A x C in the alternative hypothesis condition \cr \code{power} \tab estimated statistical power \cr \code{type1} \tab estimated significance level \cr } } \description{ This function conducts a simulation to estimate statistical power of a Rasch model test for user-specified item and person parameters. } \details{ The F-test in a three-way analysis of variance design \eqn{(A \succ \mathbf{B}) x C}{}(A > \strong{B}) x C with mixed classification (fixed factor A = subgroup, random factor B = testee, and fixed factor C = items) is used to simulate statistical power of a Rasch model test. This approach using a F-distributed statistic, where the sample size directly affects the degree of freedom enables determination of the sample size according to a given type I and type II risk, and according to a certain effect of model misfit which is of practical relevance. Note, that this approach works as long as there exists no main effect of A (subgroup). Otherwise an artificially high type I risk of the A x C interaction F-test results - that is, the approach works as long as no statistically significant main effect of A occurs. } \examples{ \dontrun{ # item parameters ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) # model differential item function (DIF) ipar2[10] <- ipar1[11] ipar2[11] <- ipar1[10] # simulation for b = 200 pwr.rasch(200, ipar = list(ipar1, ipar2)) # simulation for b = 100, 200, 300, 400, 500 pwr.rasch(seq(100, 500, by = 100), ipar = list(ipar1, ipar2)) # simulation for b = 100, 200, 300, 400, 500 # uniform distribution [-3, 3] of person parameters pwr.rasch(200, ipar = list(ipar1, ipar2), ppar = list("runif(b, -3, 3)", "runif(b, -3, 3)")) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } \references{ <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. } \seealso{ \code{\link{aov.rasch}} } <file_sep>#' Three-Way Analysis of Variance with Mixed Classification for Testing the Rasch Model #' #' This function applies the three-way analysis of variance with mixed classification #' for testing the Rasch model. #' #' The F-test in a three-way analysis of variance design (A > \strong{B}) x C with mixed classification #' (fixed factor A = subgroup, random factor B = testees, and fixed factor C = items) is used #' to test the Rasch model. Rasch model fitting means that there is no interaction A x C. #' A statistically significant interaction A x C indicates differential item functioning (DIF) #' of the items with respect of the two groups of testees Note, if a main effect of A (subgroup) #' exists, an artificially high type I risk of the A x C interaction F-test results - that is, #' the approach works as long as no statistically significant main effect of A occurs. #' Note that in case of unbalanced groups computation can take a long time. #' #' @param data A data frame in which the variables specified in the model will be found. #' Note that data needs to be in 'long' format. #' @param group Column name of the data frame containing the grouping variable. #' @param person Column name of the data frame containing the person number variable. #' @param item Column name of the data frame containing the item number variable. #' @param response Column name of the data frame containing the response variable. #' @param output If \code{TRUE}, an output will be shown on the console. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @references #' <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model #' calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. #' #' <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. #' \emph{Educational Research and Evaluation, 17}, 321-333. #' #' @return #' Returns an ANOVA table #' #' @seealso #' \code{\link{reshape.rasch}}, \code{\link{pwr.rasch}} #' #' @export #' #' @examples #' \dontrun{ #' #' # simulate Rasch model based data #' # 100 persons, 20 items, #' dat <- simul.rasch(100, items = seq(-3, 3, length.out = 20)) #' # reshape simulated data into 'long' format with balanced assignment #' # of testees into two subgroups #' dat.long <- reshape.rasch(dat, group = rep(0:1, each = nrow(dat) / 2)) #' # apply three-way analysis of variance with mixed classification for testing the Rasch model #' aov.rasch(dat.long) #' #' # extract variable names of items #' vnames <- grep("it", names(aid_st2), value = TRUE) #' # reshape aid subtest 2 data into 'long' format with split criterium sex #' aid_long.sex <- reshape.rasch(aid_st2[, vnames], group = aid_st2[, "sex"]) #' # apply three-way analysis of variance with mixed classification for testing the Rasch model #' aov.rasch(aid_long.sex) #' } aov.rasch <- function(data, group = "group", person = "person", item = "item", response = "response", output = TRUE) { data.test <- data[!is.na(data$response), ] if (eval(parse(text = paste0("length(unique(table(data$", group, "))) == 1 &", "all(tapply(data.test$", person, ", data.test$", item, ", function(x) all(table(x) == 1))) & ", "length(unique(tapply(data.test$", item, ", data.test$", person, ", function(x) sum(table(x) == 1)))) == 1")))) { restab <- aov.rasch.balanced(data, group = group, person = person, item = item, response = response, output = output) } else { restab <- aov.rasch.unbalanced(data, group = group, person = person, item = item, response = response, output = TRUE) } class(restab) <- "aovrasch" return(invisible(restab)) }<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/aov.rasch.R \name{aov.rasch} \alias{aov.rasch} \title{Three-Way Analysis of Variance with Mixed Classification for Testing the Rasch Model} \usage{ aov.rasch(data, group = "group", person = "person", item = "item", response = "response", output = TRUE) } \arguments{ \item{data}{A data frame in which the variables specified in the model will be found. Note that data needs to be in 'long' format.} \item{group}{Column name of the data frame containing the grouping variable.} \item{person}{Column name of the data frame containing the person number variable.} \item{item}{Column name of the data frame containing the item number variable.} \item{response}{Column name of the data frame containing the response variable.} \item{output}{If \code{TRUE}, an output will be shown on the console.} } \value{ Returns an ANOVA table } \description{ This function applies the three-way analysis of variance with mixed classification for testing the Rasch model. } \details{ The F-test in a three-way analysis of variance design (A > \strong{B}) x C with mixed classification (fixed factor A = subgroup, random factor B = testees, and fixed factor C = items) is used to test the Rasch model. Rasch model fitting means that there is no interaction A x C. A statistically significant interaction A x C indicates differential item functioning (DIF) of the items with respect of the two groups of testees Note, if a main effect of A (subgroup) exists, an artificially high type I risk of the A x C interaction F-test results - that is, the approach works as long as no statistically significant main effect of A occurs. Note that in case of unbalanced groups computation can take a long time. } \examples{ \dontrun{ # simulate Rasch model based data # 100 persons, 20 items, dat <- simul.rasch(100, items = seq(-3, 3, length.out = 20)) # reshape simulated data into 'long' format with balanced assignment # of testees into two subgroups dat.long <- reshape.rasch(dat, group = rep(0:1, each = nrow(dat) / 2)) # apply three-way analysis of variance with mixed classification for testing the Rasch model aov.rasch(dat.long) # extract variable names of items vnames <- grep("it", names(aid_st2), value = TRUE) # reshape aid subtest 2 data into 'long' format with split criterium sex aid_long.sex <- reshape.rasch(aid_st2[, vnames], group = aid_st2[, "sex"]) # apply three-way analysis of variance with mixed classification for testing the Rasch model aov.rasch(aid_long.sex) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } \references{ <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. } \seealso{ \code{\link{reshape.rasch}}, \code{\link{pwr.rasch}} } <file_sep>#' Reshape data frame in wide format into a long format #' #' This function reshapes a matrix from 'wide' into a 'long' format. This is necessary for #' the three-way analysis of variance with mixed classification for testing the Rasch model. #' #' In order to apply the three-way analysis of variance with mixed classification for #' testing the Rasch model, data need to be in 'long' format. That is, Rasch model #' data design is interpreted as a analysis of variance design (A > \strong{B}) x C, #' where items are levels of a fixed factor C and the testees are levels of a random #' factor B, nested within a fixed factor A of different subgroups. #' #' @param data Matrix or data frame in 'wide' format. #' @param group Vector which assigns each person to a certain subgroup (external split criterion). #' Note, that this function is restricted to A = 2 subgroups. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @export #' #' @seealso #' \code{\link{aov.rasch}} #' #' @references #' <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model #' calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. #' #' <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. #' \emph{Educational Research and Evaluation, 17}, 321-333. #' #' @return #' Returns a data frame with following entries: #' \tabular{ll}{ #' \code{group} \tab fixed factor A (subgroup) \cr #' \code{person} \tab random factor B (testees) \cr #' \code{item} \tab fixed factor C (items) \cr #' \code{response} \tab dependent variable, 0 (item not solved) and 1 (item solved) \cr #' } #' #' @examples #' \dontrun{ #' #' # simulate Rasch model based data #' # 100 persons, 20 items, #' dat <- simul.rasch(100, items = seq(-3, 3, length.out = 20)) #' # reshape simulated data into 'long' format with balanced assignment #' # of testees into two subgroups. #' dat.long <- reshape.rasch(dat, group = rep(0:1, each = nrow(dat) / 2)) #' head(dat.long) #' #' # extract variable names of items #' vnames <- grep("it", names(aid_st2), value = TRUE) #' # reshape aid subtest 2 data into 'long' format with split criterium sex #' aid_long.sex <- reshape.rasch(aid_st2[, vnames], group = aid_st2[, "sex"]) #' } reshape.rasch <- function(data, group) { #--------------------------------------------------------------------------------------------------------# # Input Check # A = 2 subgroups if (length(unique(group)) != 2) { stop("Subgroups A != 2 (external split criterion) specified") } # length of split criterion if (length(group) != nrow(data)) { stop("Length of A (external split criterion) does not match the number of observations in the data") } #--------------------------------------------------------------------------------------------------------# resp1 <- data[which(group == unique(group)[1]), ] resp2 <- data[which(group == unique(group)[2]), ] b1 <- nrow(resp1) b2 <- nrow(resp2) c <- ncol(data) data.long <- data.frame(group = c(rep(1, times = b1*c), rep(2, times = b2*c)), person = c(rep(1:b1, times = c, each = 1), rep((b1 + 1):(b1 + b2), times = c, each = 1)), item = c(rep(1:c, each = b1), rep(1:c, each = b2)), response = unlist(c(resp1, resp2))) return(data.long) }<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/reshape.rasch.R \name{reshape.rasch} \alias{reshape.rasch} \title{Reshape data frame in wide format into a long format} \usage{ reshape.rasch(data, group) } \arguments{ \item{data}{Matrix or data frame in 'wide' format.} \item{group}{Vector which assigns each person to a certain subgroup (external split criterion). Note, that this function is restricted to A = 2 subgroups.} } \value{ Returns a data frame with following entries: \tabular{ll}{ \code{group} \tab fixed factor A (subgroup) \cr \code{person} \tab random factor B (testees) \cr \code{item} \tab fixed factor C (items) \cr \code{response} \tab dependent variable, 0 (item not solved) and 1 (item solved) \cr } } \description{ This function reshapes a matrix from 'wide' into a 'long' format. This is necessary for the three-way analysis of variance with mixed classification for testing the Rasch model. } \details{ In order to apply the three-way analysis of variance with mixed classification for testing the Rasch model, data need to be in 'long' format. That is, Rasch model data design is interpreted as a analysis of variance design (A > \strong{B}) x C, where items are levels of a fixed factor C and the testees are levels of a random factor B, nested within a fixed factor A of different subgroups. } \examples{ \dontrun{ # simulate Rasch model based data # 100 persons, 20 items, dat <- simul.rasch(100, items = seq(-3, 3, length.out = 20)) # reshape simulated data into 'long' format with balanced assignment # of testees into two subgroups. dat.long <- reshape.rasch(dat, group = rep(0:1, each = nrow(dat) / 2)) head(dat.long) # extract variable names of items vnames <- grep("it", names(aid_st2), value = TRUE) # reshape aid subtest 2 data into 'long' format with split criterium sex aid_long.sex <- reshape.rasch(aid_st2[, vnames], group = aid_st2[, "sex"]) } } \author{ <NAME> \email{<EMAIL>}, <NAME> \email{<EMAIL>} } \references{ <NAME>., <NAME>., & <NAME>. (2009). On designing data-sampling for Rasch model calibrating an achievement test. \emph{Psychology Science Quarterly, 51}, 370-384. <NAME>., <NAME>., & <NAME>. (2011). A new approach for testing the Rasch model. \emph{Educational Research and Evaluation, 17}, 321-333. } \seealso{ \code{\link{aov.rasch}} } <file_sep>########################################################################################################## # # pwrRasch: Statistical Power Simulation for Testing the Rasch Model # # Internal function: Computation of Three-Way ANOVA for balanced design # # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # ########################################################################################################## aov.rasch.sim <- function(data) { group <- data$group person <- data$person item <- data$item response <- data$response a <- length(unique(group)) b <- length(unique(person)) c <- length(unique(item)) ### SS.T <- (1/(a*b/a*c))*sum(response)^2 SS.A <- sum(rowsum(response, group)^2)*(1/(b/a*c)) SS.B <- sum(rowsum(response, person)^2)*(1/c) SS.C <- sum(rowsum(response, item)^2)*(1/(a*b/a)) ### SS.interm. <- c(rowsum(response[group == 1], item[group == 1]), rowsum(response[group == 2], item[group == 2])) SS.BC <- sum(SS.interm.) SS.AC <- sum(SS.interm.^2)*(1/(b/a)) ### F.AC <- ((SS.AC - SS.A - SS.C + SS.T)/(c - 1)) / ((SS.BC - SS.B - SS.AC + SS.A)/(a*(b/a - 1)*(c - 1))) p.AC <- pf(F.AC, c - 1, a*(b/a - 1)*(c - 1), lower.tail = FALSE) return(p.AC) }<file_sep>#' Object Summary #' #' Generic \code{summary} function for the \code{pwrrasch} object #' #' @param object \code{pwrrasch} object #' @param ... Additional arguments affecting the summary produced. #' #' @author #' <NAME> \email{<EMAIL>}, #' <NAME> \email{<EMAIL>} #' #' @export #' #' @examples #' \dontrun{ #' #' # item parameters #' ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) #' # model differential item function (DIF) #' ipar2[9] <- ipar1[12] #' ipar2[12] <- ipar1[9] #' # simulation for b = 100 #' simres <- pwr.rasch(100, ipar = list(ipar1, ipar2)) #' summary(simres) #' #' # item parameters #' ipar2 <- ipar1 <- seq(-3, 3, length.out = 20) #' # model differential item function (DIF) #' ipar2[10] <- ipar1[11] #' ipar2[11] <- ipar1[10] #' # simulation for b = 100, 200, 300, 400, 500 #' simres <- pwr.rasch(seq(100, 500, by = 100), ipar = list(ipar1, ipar2)) #' summary(simres) #' } summary.pwrrasch <- function(object, ...) { if (length(object[[1]]) == 1) { if ("type1" %in% names(object)) { with(object, { cat("\n Statistical Power Simulation for the Rasch model \n\n", " b (number of persons in each group): ", b, "\n", " c (number of items): ", c, "\n", " simulation runs: ", runs, "\n\n", " Estimated statistical power: ", formatC(sum(H1.AC.p < sig.level) / runs, format = "f", digits = 3), "\n", " Nominal significance level: ", sig.level, "\n", " Empirical significance level:", formatC(sum(H0.AC.p < sig.level) / runs, format = "f", digits = 3), "\n\n") }) } else { with(object, { cat("\n Statistical Power Simulation for the Rasch model \n\n", " b (numer of persons in each group): ", b, "\n", " c (numer of items): ", c, "\n", " simulation runs: ", runs, "\n\n", " Estimated statistical power: ", formatC(sum(H1.AC.p < sig.level) / runs, format = "f", digits = 3), "\n", " Nominal significance level: ", sig.level, "\n\n") }) } #--------------------------------------------------------------------------------------------------------# # length(object) > 1 } else { b <- unlist(lapply(object, function(x) x$b)) c <- unique(unlist(lapply(object, function(x) x$c))) runs <- unique(unlist(lapply(object, function(x) x$runs))) pwr <- unlist(lapply(object, function(x) x$power)) type1 <- unlist(lapply(object, function(x) x$type1)) ### cat("\n Statistical Power Simulation for the Rasch model \n\n", " b (numer of persons in each group): ", paste(b, collapse = ", "), "\n", " c (numer of items): ", c, "\n", " simulation runs: ", runs, "\n\n", " Estimated statistical power: \n") for (i in 1:length(object)) { cat(paste0(" b = ", formatC(object[[i]]$b, digits = max(nchar(object[[i]]$b)) - 1, format = "d"), ":"), formatC(object[[i]]$power, format = "f", digits = 3) , "\n") } ### if (!is.null(type1)) { cat("\n Empirical significance level: \n") for (i in 1:length(object)) { cat(paste0(" b = ", formatC(object[[i]]$b, digits = max(nchar(object[[i]]$b)) - 1, format = "d"), ":"), formatC(object[[i]]$type1, format = "f", digits = 3) , "\n") } } cat("\n") } }
a0dc66f69473837992dbc7ed3f99c6ac37cf2f94
[ "R" ]
25
R
cran/pwrRasch
cbd51fcaad970764df2e8f003bf2622280669226
845f9678da59078e6724e8bde0d249d36e9f97e8
refs/heads/master
<file_sep># Mailbox This is an iOS app that runs through sample screens from the Mailbox UI Time Spent - 12 hours spent in total Completed User Stories: On dragging the message left... * [x] Required: Initially, the revealed background color should be gray. * [x] Required: As the reschedule icon is revealed, it should start semi-transparent and become fully opaque. If released at this point, the message should return to its initial position. * [x] Required: After 60 pts, the later icon should start moving with the translation and the background should change to yellow. * [x] Required: Upon release, the message should continue to reveal the yellow background. When the animation it complete, it should show the reschedule options. * [x] Required: After 260 pts, the icon should change to the list icon and the background color should change to brown. * [x] Required: Upon release, the message should continue to reveal the brown background. When the animation it complete, it should show the list options. * [x] Required: User can tap to dismissing the reschedule or list options. After the reschedule or list options are dismissed, you should see the message finish the hide animation. On dragging the message right... * [x] Required: Initially, the revealed background color should be gray. * [x] Required: As the archive icon is revealed, it should start semi-transparent and become fully opaque. If released at this point, the message should return to its initial position. * [x] Required: After 60 pts, the archive icon should start moving with the translation and the background should change to green. * [x] Required: Upon release, the message should continue to reveal the green background. When the animation it complete, it should hide the message. * [x] Required: After 260 pts, the icon should change to the delete icon and the background color should change to red. * [x] Required: Upon release, the message should continue to reveal the red background. When the animation it complete, it should hide the message. * [x] Optional: Panning from the edge should reveal the menu * [x] Optional: If the menu is being revealed when the user lifts their finger, it should continue revealing. * [x] Optional: If the menu is being hidden when the user lifts their finger, it should continue hiding. Walkthrough of all User Stories: ![Video Walkthrough](Mailbox Walkthrough.gif) GIF created with [LiceCap](http://www.cockos.com/licecap/). <file_sep>// // mailboxViewController.swift // Mailbox // // Created by Claw on 9/30/15. // Copyright © 2015 Claw. All rights reserved. // import UIKit class mailboxViewController: UIViewController { @IBOutlet weak var primaryMailView: UIView! @IBOutlet weak var mailScrollView: UIScrollView! @IBOutlet weak var singleMessageUIView: UIImageView! @IBOutlet weak var latericonUIImageView: UIImageView! @IBOutlet weak var rescheduleImageView: UIImageView! @IBOutlet weak var listImageView: UIImageView! @IBOutlet weak var listiconImageView: UIImageView! @IBOutlet weak var archiveiconImageView: UIImageView! @IBOutlet weak var mailfeedImageView: UIImageView! @IBOutlet weak var msgcontainerVIew: UIView! @IBOutlet weak var deleteiconImageView: UIImageView! @IBOutlet weak var menuImageView: UIImageView! var initialMsgCenter: CGPoint! var msgOriginalCenter: CGPoint! var initialcontainerCenter: CGPoint! var initialmailfeedCenter: CGPoint! var initialLaterCenter: CGPoint! var laterOriginalCenter: CGPoint! var initialarchiveCenter: CGPoint! var archiveOriginalCenter: CGPoint! var initiallistCenter: CGPoint! var initialdeleteCenter: CGPoint! var deleteOriginalCenter: CGPoint! var menuOriginalCenter:CGPoint! var initialprimarymailCenter: CGPoint! var primarymailOriginalCenter:CGPoint! override func viewDidLoad() { super.viewDidLoad() mailScrollView.contentSize = CGSize(width: 375, height: 1400) menuImageView.alpha = 1 //setup the pan gesture recognizer let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "onCustomPan:") singleMessageUIView.addGestureRecognizer(panGestureRecognizer) //setup the list tap gesture recognizer let listtapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onListTap:") listtapGestureRecognizer.numberOfTapsRequired = 1; listImageView.userInteractionEnabled = true listImageView.addGestureRecognizer(listtapGestureRecognizer) //setup the reschedule tap gesture recognizer let reschedtapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onReschedTap:") reschedtapGestureRecognizer.numberOfTapsRequired = 1; rescheduleImageView.userInteractionEnabled = true rescheduleImageView.addGestureRecognizer(reschedtapGestureRecognizer) //setup the menu tap gesture recognizer let menutapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onMenuTap:") menutapGestureRecognizer.numberOfTapsRequired = 1; menuImageView.userInteractionEnabled = true menuImageView.addGestureRecognizer(menutapGestureRecognizer) //set initial values for msg and later icon initialMsgCenter = singleMessageUIView.center initialLaterCenter = latericonUIImageView.center initialcontainerCenter = msgcontainerVIew.center initialmailfeedCenter = mailfeedImageView.center initiallistCenter = listiconImageView.center initialarchiveCenter = archiveiconImageView.center initialdeleteCenter = deleteiconImageView.center initialprimarymailCenter = primaryMailView.center //Add Screen Edge Gesture Recgonizer var edgeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: "onEdgePan:") edgeGesture.edges = UIRectEdge.Left primaryMailView.addGestureRecognizer(edgeGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func onEdgePan(panGestureRecognizer: UIPanGestureRecognizer) { print("Panning the edge!") let point = panGestureRecognizer.locationInView(view) let velocity = panGestureRecognizer.velocityInView(view) let translation = panGestureRecognizer.translationInView(view) if panGestureRecognizer.state == UIGestureRecognizerState.Began { primarymailOriginalCenter = primaryMailView.center } else if panGestureRecognizer.state == UIGestureRecognizerState.Changed{ primaryMailView.center.x = primarymailOriginalCenter.x + translation.x } else if panGestureRecognizer.state == UIGestureRecognizerState.Ended { if velocity.x > 0 { UIView.animateWithDuration(0.5, animations:{ self.primaryMailView.center.x = self.initialprimarymailCenter.x + 375 }) } else if velocity.x < 0 { UIView.animateWithDuration(0.5, animations:{ self.primaryMailView.center.x = self.initialprimarymailCenter.x }) } } } func onCustomPan(panGestureRecognizer: UIPanGestureRecognizer) { let point = panGestureRecognizer.locationInView(view) let velocity = panGestureRecognizer.velocityInView(view) let translation = panGestureRecognizer.translationInView(view) if panGestureRecognizer.state == UIGestureRecognizerState.Began { iconlocationReset() msgOriginalCenter = singleMessageUIView.center laterOriginalCenter = latericonUIImageView.center archiveOriginalCenter = archiveiconImageView.center deleteOriginalCenter = deleteiconImageView.center if velocity.x < 0 { latericonUIImageView.alpha = 0.25 } if velocity.x > 0 { archiveiconImageView.alpha = 0.25 } } else if panGestureRecognizer.state == UIGestureRecognizerState.Changed { // move the message and show that we tracked it singleMessageUIView.center = CGPoint(x: msgOriginalCenter.x + translation.x, y: msgOriginalCenter.y) // check to see if message is between 0 and 60 pixels to the left if (singleMessageUIView.center.x < initialMsgCenter.x) && (singleMessageUIView.center.x > initialMsgCenter.x - 60){ UIView.animateWithDuration(0.5, animations:{ self.latericonUIImageView.alpha = 1 }) } // check to see if message is being dragged to the left between 60 and 260 pixels else if (singleMessageUIView.center.x < initialMsgCenter.x - 61) && (singleMessageUIView.center.x > initialMsgCenter.x - 260){ UIView.animateWithDuration(0.5, animations:{ self.msgcontainerVIew.backgroundColor = .yellowColor() }) self.latericonUIImageView.center.x = laterOriginalCenter.x + translation.x + 60 } // check to see if message is being dragged to the left more than 260 pixels else if (singleMessageUIView.center.x < initialMsgCenter.x - 261){ UIView.animateWithDuration(0.3, animations:{ self.msgcontainerVIew.backgroundColor = .brownColor() }) self.listiconImageView.alpha = 1 self.latericonUIImageView.alpha = 0 self.listiconImageView.center.x = self.laterOriginalCenter.x + translation.x + 60 } else if (singleMessageUIView.center.x > initialMsgCenter.x) && (singleMessageUIView.center.x < initialMsgCenter.x + 60){ UIView.animateWithDuration(0.5, animations:{ self.archiveiconImageView.alpha = 1 }) } // check to see if message is being dragged to the right between 60 and 260 pixels else if (singleMessageUIView.center.x > initialMsgCenter.x + 61) && (singleMessageUIView.center.x < initialMsgCenter.x + 260){ UIView.animateWithDuration(0.5, animations:{ self.msgcontainerVIew.backgroundColor = .greenColor() }) self.archiveiconImageView.center.x = archiveOriginalCenter.x + translation.x - 60 } // check to see if message is being dragged to the right more than 260 pixels else if (singleMessageUIView.center.x > initialMsgCenter.x + 261){ UIView.animateWithDuration(0.3, animations:{ self.msgcontainerVIew.backgroundColor = .redColor() }) self.archiveiconImageView.alpha = 0 self.deleteiconImageView.center.x = self.archiveOriginalCenter.x + translation.x - 60 self.deleteiconImageView.alpha = 1 } } else if panGestureRecognizer.state == UIGestureRecognizerState.Ended { // check to see if message was moved left or right more than 60 pixels if ((singleMessageUIView.center.x > initialMsgCenter.x - 60) && (singleMessageUIView.center.x < initialMsgCenter.x)) || ((singleMessageUIView.center.x < initialMsgCenter.x + 60) && (singleMessageUIView.center.x > initialMsgCenter.x)){ //snap the message back UIView.animateWithDuration(0.4, animations: { self.singleMessageUIView.center.x = self.initialMsgCenter.x self.msgcontainerVIew.backgroundColor = .grayColor() }) } // check to see ended between 61 and 260 pixels to the left else if (singleMessageUIView.center.x < initialMsgCenter.x - 61) && (singleMessageUIView.center.x > initialMsgCenter.x - 260){ //show reschedule image UIView.animateWithDuration(0.5, animations:{ self.rescheduleImageView.alpha = 1 }) // check to see ended more than 260 pixels to the left } else if (singleMessageUIView.center.x < initialMsgCenter.x - 261) { //show list image UIView.animateWithDuration(0.5, animations:{ self.listImageView.alpha = 1 }) } else if (singleMessageUIView.center.x > initialMsgCenter.x + 61){ //complete the animation to the right swiperightReset() } // check to see ended more than 260 pixels to the left } } func onMenuTap(menutapGestureRecognizer: UITapGestureRecognizer){ print("tapped on menu") UIView.animateWithDuration(0.5, animations:{ self.primaryMailView.center.x = self.initialprimarymailCenter.x }) } func onListTap(listtapGestureRecognizer: UITapGestureRecognizer) { swipeleftReset() } func onReschedTap(reschedtapGestureRecognizer: UITapGestureRecognizer) { swipeleftReset() } func swipeleftReset (){ // set the icons and the lists to hide self.archiveiconImageView.alpha = 0 self.listiconImageView.alpha = 0 self.latericonUIImageView.alpha = 0 self.rescheduleImageView.alpha = 0 self.listImageView.alpha = 0 self.deleteiconImageView.alpha = 0 // move the message all the way left UIView.animateWithDuration(0.4, animations: { self.singleMessageUIView.center.x = self.initialMsgCenter.x - 375 }) delay(0.3){ self.movefeedup() } } func swiperightReset (){ // set the icons and the lists to hide self.archiveiconImageView.alpha = 0 self.listiconImageView.alpha = 0 self.latericonUIImageView.alpha = 0 self.rescheduleImageView.alpha = 0 self.listImageView.alpha = 0 self.deleteiconImageView.alpha = 0 // move the message all the way right UIView.animateWithDuration(0.4, animations: { self.singleMessageUIView.center.x = self.initialMsgCenter.x + 375 }) delay(0.3){ self.movefeedup() } } func movefeedup (){ // hide the container and then move the mailfeed up UIView.animateWithDuration(0.4, animations: { self.msgcontainerVIew.alpha = 0 self.mailfeedImageView.center.y = self.initialmailfeedCenter.y - 90 }) delay (1){ // move container into correct position and then move the feed back down self.singleMessageUIView.center = self.initialMsgCenter self.msgcontainerVIew.alpha = 1 self.mailfeedImageView.center.y = self.initialmailfeedCenter.y } } func iconlocationReset (){ latericonUIImageView.center = initialLaterCenter listiconImageView.center = initiallistCenter archiveiconImageView.center = initialarchiveCenter self.latericonUIImageView.alpha = 0 self.archiveiconImageView.alpha = 0 self.msgcontainerVIew.backgroundColor = .grayColor() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
6e7cf41a6e2549eb24cac51d85cd2821f0a89105
[ "Markdown", "Swift" ]
2
Markdown
chrislawcodes/Mailbox
ac6c615a2678f14c9d09c6ba7c518c9b3e7055f1
6b3dd69b3fc05d3800d66b22a81b281da54544e4
refs/heads/main
<file_sep>import requests import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) # Unlike the Spotify API we only need the Access token (Key) GENIUS_KEY = os.getenv('GENIUS_KEY') # We get the lyrics by passing in the song name and artist name. def get_lyrics(song_name, artist_name): # We use the search API URL = 'https://api.genius.com/search' headers = {'Authorization': 'Bearer ' + GENIUS_KEY} data = {'q': song_name + ' ' + artist_name} response = requests.get(URL, data=data, headers=headers) response = response.json() # Set these equal to None if no lyrics are found. remote_song_info = None lyric_url = None for i in response['response']['hits']: if artist_name.lower() in i['result']['primary_artist']['name'].lower(): remote_song_info = i break if remote_song_info: lyric_url = remote_song_info['result']['url'] return lyric_url<file_sep># Project 1 ## Purpose / Objective In this project, we'll deploy a simple “music discovery” web app that shows song(s) from your favorite artist(s) and link(s) to the music and lyrics. This data will be dynamically generated using third-party APIs from Spotify and Genius. ### Final Product: https://floating-island-45726.herokuapp.com/ ## Steps to Deploy ### Clone the repository 1. On `https://github.com/new`, create a new personal repository. Name it whatever you want. 2. In terminal, in your home directory, clone the repo: `https://github.com/NJIT-CS490-SP21/project1-as3627.git`. 3. `cd` into the repository that is created and you should see all the files. 4. Then, connect this cloned repo to your new personal repo made in Step 1: `git remote set-url origin https://www.github.com/{your-username}/{repo-name}` (be sure to change your username and repo-name and remove the curly braces) 5. Run `git push origin main` to push the local repo to remote. You should now see this same code in your personal repo. ### Sign up for a Spotify Developer Account 1. You can sign up for a free Spotify Developer account on their website here: [https://developer.spotify.com/](https://developer.spotify.com/). 2. Once you make an account, head on over to the Dashboard and hit `Create an App`. Fill out the information on there. 3. After you finish filling in the information for creating the app, make note of the `Client ID` and `Client Secret`, we'll need them later. 4. Spotify is used to gather song data. ### Sign up for a Genius API Account 1. You can sign up for a free Genius account on this link here: [https://genius.com/signup_or_login](https://genius.com/signup_or_login). 2. Once you make an account, head over to [https://genius.com/api-clients](https://genius.com/api-clients) and hit `New API Client` and fill in the information. 3. Once you fill in the information hit `Generate Access Token` and make note of this Access Token, we'll need it later. 4. Genius is used to gather song lyrics. ### Sign up for a Heroku Account 1. You can sign up for a free Heroku account on their website here: [https://signup.heroku.com/login](https://signup.heroku.com/login). 2. Heroku is used to host the web app. ### Install Requirements (if you don't already have them) Note: if for some reason these commands don't work, put `sudo` in front of each command and then try running it. 1. `pip install python-dotenv` 2. `pip install requests` 3. `pip install Flask` 4. `npm install -g heroku` (Note this one might take a while to install, don't worry) ### Setup 1. Create a `.env` file in your project directory. 2. Add the Spotify `Client ID` and `Client Secret` variables inside the `.env` file, with the lines: `export CLIENT_ID = '{YOUR_ID}'` and `export CLIENT_SECRET = '{YOUR_SECRET}'`. 3. Add the Genius `Access Token` variable in the `.env` file, with the lines: `export GENIUS_KEY = '{YOUR KEY}'`. 4. Inside `app.py` add your favorite artists' Artist IDs inside the `ids` list beginning on line 18. To find out how to get Artist IDs, check this link out: [https://support.tunecore.com/hc/en-us/articles/360040325651-How-to-Find-my-Spotify-Artist-ID](https://support.tunecore.com/hc/en-us/articles/360040325651-How-to-Find-my-Spotify-Artist-ID) ### Running the Application 1. Run command in terminal with `python app.py` 2. Preview the web page in browser `'/'` ### Deploy to Heroku 1. If you don't have this file already, create `Procfile` and write `web: python app.py` on the first line. This is used to deploy the app on Heroku. 2. If you don't have this file already, create `requirements.txt` and write `Flask`, `requests`, and `python-dotenv`. Make sure each is separated with a newline. If you use more packages, make sure to include them here. 3. Make sure to have all your files commited with git by this point. 4. Login to your Heroku account with `heroku login -i`. 5. Create a Heroku app with the command: `heroku create`. This will create a new URL and associated host for you. 6. Push your code to Heroku with the command: `git push heroku main`. This pushes your code to Heroku's remote repository. 7. Once that's done, visit [https://dashboard.heroku.com/apps](https://dashboard.heroku.com/apps). Click on the app that you made, and then hit settings. Inside settings, click on `Reveal Config Vars`. 8. Add all three variables that you had in the `.env` file: `CLIENT_ID`, `CLIENT_SECRET`, and `GENIUS_KEY` and the associated key. (Note you don't need to include quotation marks with the keys) 9. Run `heroku open` or refresh the URL if you have it open, and the web app should be running. ## Technical Issues Faced: 1. Initially with the Spotify API, there were some songs that did not have any preview. In these cases I would still be attempting to put something into the audio player, which would be giving me errors. I actually thought it was an audio player error in the beginning, which made me go to [w3schools.com/html/html5_audio.asp](w3schools.com/html/html5_audio.asp) to check how audio players worked again. After seeing I didn't make any mistakes with the audio player, I went back to the `json` in the python file. After running the code a few times, I found that for these songs, had `None` for their preivew url. I realized I was passing the value of `None` instead of a URL, so I modified my HTML with Flask python tags `{% if song_preview == None %}`. Now in my code, I made it so that the audio player only comes up if a song preview link was provided. 2. Some songs had multiple artists. Initially I was pulling only the first artist of the song, since I didn't really know how to get the rest. After going through the lecture 4 demo again, I decided to change how the code worked. Since for that demo, we passed a list and the length of the list, I decided to do the same for the artist names. Before I could do anything, I went back to the Spotify api. I had to look back at the `json` and see where the artist names were being stored again. After I found that, I made a loop in the spotify file, and then appended every artist name into a list. After that I also took the length of the list and returned both the list and length with the rest of the variables. 3. When I used the Genius API, there were some cases where I could not return a lyrics page. For some reason, it would be throwing an error for me and not returning `None`, as the case was for the Spotify API when there wasn't a song preview. I thought I was messing up with my usage of the API, so I decided to look up a tutorial on how to use the Genius API. I actually found a link to help: [https://dev.to/willamesoares/how-to-integrate-spotify-and-genius-api-to-easily-crawl-song-lyrics-with-python-4o62](https://dev.to/willamesoares/how-to-integrate-spotify-and-genius-api-to-easily-crawl-song-lyrics-with-python-4o62) which actually goes over a similar project. In this project's case, I followed along with the code structure and I noticed that they initially set the link to be `None`, and if there was a lyric page found, they would set the varible to the link. In the cases where no link was found, it would automatically return `None`. Which ended up solving my issue. This site also helped me clean up my code for API usage. ## Current Known (or Potential) Issues: 1. If the api crashes, or hit its limit for the day, the app will most likely return an error message or crash. This issue has not occured (yet), but is possible. If this occurs, I advise waiting some time before using the app again. I have not been able to fix this potential issue yet. ## Additional Features I'd like to Implement: 1. If I had more time to work on it, I would like to add a search bar so the user can search for an artist themselves. Similar to how we did HW8, I would be using Javascript with `@app.route("/search/<user_text>")` in Flask. I would most likely use an html button along with a text box to send the arguments to the back end. I would then create a new method under the search route, and make use of the Spotify Search API for searching the inputted artist's URI, and then using the top-tracks API to pick a random song. The only issue is that I had a hard time working with the JS part, especially with parsing the `json` and changing the html. It would take me a long time to add this feature, and givin the due date is soon, I decided against adding it. If given more time I would have implemented it. ## Extra Features I Implemented: 1. I got tired of having to hit `CTRL + R` every time to refresh the page, so I created a refresh button on the page itself. I looked up how to make a refresh button in html and found this site: [https://www.htmlgoodies.com/tutorials/getting_started/article.php/3479551/reloading-the-page.htm](https://www.htmlgoodies.com/tutorials/getting_started/article.php/3479551/reloading-the-page.htm) that taught me how to do it. Clicking on the 🔄 emoji will refresh the page. 2. I added a `Play on Spotify!` feature as well. With the API's `json` it also returned a link for the song itself on Spotify. I thought it would be a good idea to include this link so the user can play the song right away on their Spotify. <file_sep>import os import random from flask import Flask, render_template from spoti import get_info from genius import get_lyrics app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route('/') def hello_world(): """ Returns root endpoint HTML """ # These can be swapped out for any artist URI. # The ones in this list are (in order): <NAME>, <NAME>, Sia, The Weeknd, <NAME> ids = ['66CXWjxzNUsdJxJ2JdwvnR', '6M2wZ9GZgrQXHCFfjv46we', '5WUlDfRSoLAfcVSX1WnrxN', '1Xyo4u8uXC1ZmMpatF05PJ', '0du5cEVh5yTK9QJze8zA0C'] idx = random.randint(0, len(ids) - 1) # Pass the random index through to get info for a randomly chosen artist. info = get_info(ids[idx]) lyrics = get_lyrics(info[0], info[1][0]) total_artists = len(info[1]) # Pass every variable we need to the front end. return render_template( "index.html", song_name=info[0], artist_name=info[1], total_artists=total_artists, song_img=info[2], song_preview=info[3], spotify_url=info[4], lyrics_link = lyrics, ) # Runs the app app.run( host=os.getenv('IP', '0.0.0.0'), port=int(os.getenv('PORT', 8080)), debug=True ) <file_sep>import requests import os import random from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) AUTH_URL = 'https://accounts.spotify.com/api/token' CLIENT_ID = os.getenv('CLIENT_ID') CLIENT_SECRET = os.getenv('CLIENT_SECRET') # This method aquires the credential token from the Client ID and Secret def get_token(): auth_response = requests.post(AUTH_URL, { 'grant_type': 'client_credentials', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, }) # convert the response to JSON auth_response_data = auth_response.json() # save the access token access_token = auth_response_data['access_token'] return access_token # get_info calls get_token and makes the API call with the artist ID provided def get_info(artist_id): access_token = get_token() headers = { 'Authorization': 'Bearer {TOKEN}'.format(TOKEN=access_token) } URL = 'https://api.spotify.com/v1/artists/{id}/top-tracks'.format(id=artist_id) data = requests.get(URL + "?market=US", headers = headers) data = data.json() # We chose a random song from the artist's top tracks rand = random.randint(0, len(data['tracks']) - 1) song_name = data['tracks'][rand]['name'] # Handling multiple artists for one song artist_name = [] total = len(data['tracks'][rand]['artists']) for i in range(total): artist_name.append(data['tracks'][rand]['artists'][i]['name']) song_img = data['tracks'][rand]['album']['images'][0]['url'] song_preview = data['tracks'][rand]['preview_url'] spotify_url = data['tracks'][rand]['external_urls']['spotify'] info = [song_name, artist_name, song_img, song_preview, spotify_url] # Returns a list containing all the info. return info
e58044d7f1a463f09a355b8cce4fd06db470c842
[ "Markdown", "Python" ]
4
Python
NJIT-CS490-SP21/project1-as3627
9a5ab5123c0007b494d122e3b42be30d4f2aafee
c899a516c0f549af9600c321b1687cd63cd51a13
refs/heads/master
<repo_name>miki1099/ZIPcompressor<file_sep>/src/FileManager.java import javax.swing.*; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FileManager { public static List<File> getFiles(){ JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setMultiSelectionEnabled(true); chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); int tmp = chooser.showDialog(chooser.getRootPane(), "Add to archive"); if(tmp == JFileChooser.APPROVE_OPTION){ List<File> files = Arrays.asList(chooser.getSelectedFiles()); return files; } else{ return List.of(); } } public static List<File> addWithoutDuplicate(List<File> inp, List<File> out){ for(File file : inp){ if(!out.contains(file)){ out.add(file); } } return out; } public static List<String> getFileNames(List<File> files) { List<String> names = new ArrayList<>(); for(File file : files){ names.add(file.getName()); } return names; } }
ca216ffbb7f07b5597ca7b8839b751c68f56b01c
[ "Java" ]
1
Java
miki1099/ZIPcompressor
eaa40b537cfc9f8358e8c44445e6c65f34da0aac
746db1aea3237cbfd4c314ed9d966ea242361598
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class CardsListing : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { [SerializeField] private TMP_Text _name = null; [SerializeField] private TMP_Text _cost = null; [SerializeField] private CollectionCard cardPrefab = null; public CardBase card; private CollectionCard collectionCard; public void SetCardInfo(CardBase NewCard) { this.card = NewCard; Image image = GetComponent<Image>(); image.color = (NewCard is SpellCard)? Color.red : Color.blue; _name.text = NewCard.Name; _cost.text = NewCard.Cost.ToString(); this.card = NewCard; GameObject cardObject = Instantiate(cardPrefab.gameObject, transform); GameObject ListObj = GameObject.Find("ListCards"); cardObject.transform.parent = ListObj.transform; collectionCard = cardObject.GetComponent<CollectionCard>(); card = NewCard; cardObject.SetActive(false); } public void on_click_card() { DeckCardList dc = Object.FindObjectOfType<DeckCardList>(); dc.AddCard(card); } public void OnPointerEnter(PointerEventData eventData) { collectionCard.card = card; collectionCard.transform.localScale = new Vector3(4000,4000,4000); collectionCard.transform.localPosition = new Vector3(1150, 0, -50); collectionCard.gameObject.SetActive(true); } public void OnPointerExit(PointerEventData data) { collectionCard.gameObject.SetActive(false); } } <file_sep>using Photon.Pun; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class JoinRoom : MonoBehaviourPunCallbacks { [SerializeField] private TMP_Text _name = null; [SerializeField] private TMP_Text _errorMsg = null; [SerializeField] private GameObject roomCanvas = null; public void on_click_join_room() { PhotonNetwork.JoinRoom(_name.text); } public override void OnJoinedRoom() { roomCanvas.SetActive(true); } public override void OnJoinRoomFailed(short returnCode, string message) { _errorMsg.gameObject.SetActive(true); _errorMsg.text = message; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class buttonReplace : MonoBehaviour { [SerializeField] private GameObject replaceCross = null; [SerializeField] private GameObject card = null; public void OnMouseDown() { replaceCross.SetActive(!replaceCross.activeInHierarchy); DeckDraw.eventReplaceCards.Invoke(card); } } <file_sep>using System.Collections.Generic; using UnityEngine; using System.Linq; [CreateAssetMenu(menuName="Cards/Units/Summoner")] public class SummonerCard : UnitCard { [SerializeField] protected CardBase summon; [SerializeField] protected int number; //Carte d'unité ajoutant des cartes dans la main du joueur au déploiement protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { board.AddUnit(this, target, player); for (int i = 0; i < number; i++){ if(objPlayer.Hand.Count()<10) objPlayer.addCard(summon); } return true; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //Classe gérant le survol d'une cellule par la souris du joueur public class PlayerMouseHover : BoardBehaviour { [SerializeField] private BoardClicker boardClicker = null; [SerializeField] private HoverCell hoverCell = null; [SerializeField] private Color friendlyColor = new Color(); [SerializeField] private Color ennemyColor = new Color(); [SerializeField] private Color hoverColor = new Color(); private void OnEnable() { boardClicker.OnHoverCell += OnHoverCell; boardClicker.OnHoverUnit += OnHoverUnit; boardClicker.OnHoverCard += _ => Clear(); } private void OnDisable() { boardClicker.OnHoverCell -= OnHoverCell; boardClicker.OnHoverUnit -= OnHoverUnit; boardClicker.OnHoverCard -= _ => Clear(); } void OnHoverCell(Cell cell) { Clear(); hoverCell.ShowCells(hoverColor, cell); } void OnHoverUnit(Cell cell, Unit unit) { Clear(); if (unit.Player == PlayersExtension.LocalPlayer()) hoverCell.ShowCells(friendlyColor, cell); else hoverCell.ShowCells(ennemyColor, cell); } void Clear() { hoverCell.HideCells(friendlyColor); hoverCell.HideCells(ennemyColor); hoverCell.HideCells(hoverColor); } } <file_sep>using Photon.Pun; using System.Net.Http; using TMPro; using UnityEngine; public class changeUsername : MonoBehaviourPunCallbacks { [SerializeField] private TMP_InputField username = null; [SerializeField] private Canvas MenuCanvas = null; private void Start() { if (PlayerPrefs.HasKey("username")) { username.text = PlayerPrefs.GetString("username"); } } public void On_Click_Change_Username() { PlayerPrefs.SetString("username", username.text.Replace("\u200b", "")); PhotonNetwork.NickName = PlayerPrefs.GetString("username"); MenuCanvas.gameObject.SetActive(true); gameObject.SetActive(false); Connect(); } private void Connect() { var client = new HttpClient(); var response = client.PostAsync("http://games.strange-nebula.com:3000/u/" + PlayerPrefs.GetString("username"), null).Result; var responseString = response.Content.ReadAsStringAsync().Result; } } <file_sep>- Les tests d'acceptation de la story fonctionnent. - Issues testées fonctionnellement. - Les anciens tests, nouveaux tests et build passent. <file_sep>using UnityEngine; using TMPro; //Classe permettant l'affichage des Hammercoins des joueurs public class InfoGold : BoardBehaviour { [System.Serializable] public enum LocalOrRemote { Local, Remote }; [SerializeField] private LocalOrRemote role = LocalOrRemote.Local; [SerializeField] public TMP_Text text = null; private void Update() { if (role == LocalOrRemote.Local) text.text = manager.LocalPlayer.CurrentGold.ToString() + " / " + manager.LocalPlayer.Gold.ToString(); else if (role == LocalOrRemote.Remote) text.text = manager.RemotePlayer.CurrentGold.ToString() + " / " + manager.RemotePlayer.Gold.ToString(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using Photon.Pun; //Affichage du texte de victoire ou de défaite public class WinText : BoardBehaviour { [SerializeField] public TMP_Text text; public void OnWin(GameState state) { string txt = ""; if (PlayersExtension.LocalPlayer() == state.Winner()){ txt = "You win !"; } else { txt = "You loose !"; } text.text = "Game finished !\n"+txt; } }<file_sep>using UnityEngine; //Classe représentant une carte de jeu [System.Serializable] public abstract class CardBase : ScriptableObject{ #if UNITY_EDITOR [SerializeField] public string resourcePath; #else [SerializeField] protected string resourcePath; #endif protected Sprite image = null; [SerializeField] protected new string name = ""; [SerializeField, TextArea] protected string description = ""; [SerializeField] protected int cost = 1; [SerializeField] public CastMask castMask = 0; [SerializeField] public ParticleSystem particleSystem; ParticleSystem ParticleSystem => particleSystem; public string ResourcePath => resourcePath; public int Cost => cost; public string Description => description; public Sprite Image => image; public string Name => name; public bool Use(Board board, Cell target, PlayerRole player, Player objPlayer) { if (CardCast.CanCast(castMask, board, target)) { return CardEffect(board, target, player, objPlayer); } return false; } protected abstract bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer); } //Classe représentant une carte de sort //chaque archétype de sort hérite de cette classe est redéfinis le CardEffect public abstract class SpellCard : CardBase {}<file_sep>- Description, critères d'acceptation, tests d'acceptation. - Un set d'issues github pour chaque tâche à réaliser pour que la story soit fonctionnelle. <file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; public class BoardUnitPool : BoardBehaviour { private Dictionary<int, BoardUnit> boardUnits; private void Start() { boardUnits = new Dictionary<int, BoardUnit>(); } private void Update() { foreach (var unit in board.Units) { if (!boardUnits.ContainsKey(unit.Id)) { boardUnits.Add(unit.Id, CreateBoardUnit(unit)); } } } private BoardUnit CreateBoardUnit(Unit unit) { GameObject go = Instantiate(unit.Card.Model, board.LocalPosition(unit), Quaternion.identity, transform); go.GetComponentsInChildren<Collider>().ToList().ForEach(x => x.enabled = false); BoardUnit boardUnit; if (!go.transform.TryGetComponent(out boardUnit)) { boardUnit = go.AddComponent<BoardUnit>(); } boardUnit.unitId = unit.Id; manager.History.Add(new AtqAction(manager.CurrentPlayer.Role, manager.Turn, unit.Id)); manager.History.Add(new MovementAction(manager.CurrentPlayer.Role, manager.Turn, unit.Id, new Vector2Int(0,0))); return boardUnit; } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Linq; using TMPro; public class CardsListingMenu : MonoBehaviour { [SerializeField] private CardsListing _cardsListing = null; [SerializeField] private Transform _content = null; [SerializeField] private TMP_InputField field = null; [SerializeField] private Toggle unitToggle = null; [SerializeField] private Toggle spellToggle = null; private Dictionary<string,CardsListing> cardsToDisplay = new Dictionary<string, CardsListing>(); private List<CardBase> listCards = new List<CardBase>(); void Start() { HashSet<CardBase> cards = new HashSet<CardBase>(); int mostExpensive = 0; foreach (UnitCard card in Resources.LoadAll("Cards/Unit", typeof(UnitCard))) { if(card.Cost > mostExpensive) { mostExpensive = card.Cost; } cards.Add(card); } foreach (SpellCard card in Resources.LoadAll("Cards/Spell", typeof(SpellCard))) { if(card.Cost > mostExpensive) { mostExpensive = card.Cost; } cards.Add(card); } Sort(cards, mostExpensive); foreach(CardBase card in listCards) { cardsToDisplay[card.Name] = Instantiate(_cardsListing, _content); cardsToDisplay[card.Name].SetCardInfo(card); } valueChanged(); } private void Sort(HashSet<CardBase> cards, int mostExpensive) { List<CardBase> toRemove; for(int i=0; i<=mostExpensive; i++) { toRemove = new List<CardBase>(); foreach(CardBase card in cards) { if(card.Cost == i) { listCards.Add(card); toRemove.Add(card); } } foreach(CardBase card in toRemove) { cards.Remove(card); } } } public void valueChanged() { foreach(CardBase cb in listCards) { if (cardsToDisplay[cb.Name] != null) Destroy(cardsToDisplay[cb.Name].gameObject); } foreach(CardBase cb in listCards) { if(cb.Name.ToLower().Contains(field.text.ToLower()) && ((cb is UnitCard && unitToggle.isOn) || (cb is SpellCard && spellToggle.isOn))) { cardsToDisplay[cb.Name] = Instantiate(_cardsListing, _content); cardsToDisplay[cb.Name].SetCardInfo(cb); } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class DeckListingMenu : MonoBehaviour { [SerializeField] private DeckListing _deckListing = null; [SerializeField] private Transform _content = null; public Dictionary<string,DeckListing> ListDecks = new Dictionary<string, DeckListing>(); private Deck selectedDeck = null; private void OnEnable() { FetchServer(); } public void setDeck(Deck NewDeck){ foreach(string name in ListDecks.Keys){ if (name == NewDeck.Name){ ListDecks[name].Deck = NewDeck; } } } public void RemoveDeck(Deck deck) { Destroy(ListDecks[deck.Name].gameObject); ListDecks.Remove(deck.Name); selectedDeck = null; } public void ClickDeck(Deck deck) { if(selectedDeck != null) { ListDecks[selectedDeck.Name].SetBgColor(new Color(130/255f, 130/255f, 130/255f)); } selectedDeck = deck; ListDecks[selectedDeck.Name].SetBgColor(new Color(65/255f, 200/255f, 65/255f)); } public void on_click_create_deck(TMP_InputField field) { string name = field.text; if(name != "") { DeckListing listing = null; if(!ListDecks.ContainsKey(name)) { listing = Instantiate(_deckListing, _content); } if(listing != null || ListDecks.ContainsKey(name)) { ListDecks[name] = (listing!=null) ? listing : ListDecks[name]; ListDecks[name].SetDeckInfo(new Deck(name)); } } } public void FetchServer() { string user = PlayerPrefs.GetString("username"); foreach (var deckName in AccessDatabase.GetDecksOf(user)) { var deck = AccessDatabase.GetDeck(user, deckName); if (!ListDecks.ContainsKey(deck.Name)){ DeckListing listing = Instantiate(_deckListing, _content); ListDecks[deck.Name] = listing; ListDecks[deck.Name].SetDeckInfo(deck); } } } } <file_sep>using TMPro; using UnityEngine; using DG.Tweening; public class CollectionCard : BoardBehaviour { // [SerializeField, Range(1f, 2f)] private float scaleUp = 1.5f; // [SerializeField, Range(0f, 1f)] private float offsetY = 0.2f; // [SerializeField, Range(0f, 1f)] private float offsetZ = 0.2f; //[SerializeField] private Transform OverCard = null; public CardBase card = null; [SerializeField] private Transform unitModel = null; [SerializeField] private Transform spellModel = null; [SerializeField] private TMP_Text costText = null; [SerializeField] private TMP_Text nameText = null; [SerializeField] private TMP_Text descriptionText = null; [SerializeField] private TMP_Text RANGEorCACText = null; // [SerializeField] private SpriteRenderer image = null; [SerializeField] private TMP_Text attackText = null; [SerializeField] private TMP_Text healthText = null; public BoardPlayer player { get; set; } private void Update() { if (card != null) { costText.text = card.Cost.ToString(); nameText.text = card.Name; descriptionText.text = card.Description; //image.sprite = card.Image; if ((card.GetType().IsAssignableFrom(typeof(UnitCard)) || card.GetType().IsSubclassOf(typeof(UnitCard)))) { unitModel.gameObject.SetActive(true); spellModel.gameObject.SetActive(false); RANGEorCACText.text = (((UnitCard) card).Range) ? "Range" : "Melee"; attackText.text = ((UnitCard) card).Attack.ToString(); healthText.text = ((UnitCard) card).Health.ToString(); } else { unitModel.gameObject.SetActive(false); spellModel.gameObject.SetActive(true); RANGEorCACText.text = ""; attackText.text = ""; healthText.text = ""; } } else { unitModel.gameObject.SetActive(false); spellModel.gameObject.SetActive(false); costText.text = ""; nameText.text = ""; descriptionText.text = ""; //image.sprite = null; RANGEorCACText.text = ""; attackText.text = ""; healthText.text = ""; } } private void OnMouseEnter() { transform.localScale = new Vector3 (3000,3000,3000); transform.localPosition -= new Vector3(0,0,30) ; } private void OnMouseExit() { transform.localScale = new Vector3(1500,1500,1500); transform.localPosition += new Vector3(0,0,30) ; } private void OnMouseDown() { DeckCardList dc = Object.FindObjectOfType<DeckCardList>(); dc.DeleteCard(this); } } <file_sep>using UnityEngine; using TMPro; using Photon.Pun; public class BoardUnit : BoardBehaviour { public int unitId; private Unit unit => board.GetUnit(unitId, true); private new Renderer renderer; private void Start() { SyncPosition(); renderer = GetComponent<Renderer>(); } private void Update() { SyncPosition(); DisableIfNeeded(); } private void SyncPosition() { if (unit != null) { transform.position = boardManager.transform.TransformPoint(board.LocalPosition(unit)); transform.localScale = Vector3.one * unit.Card.ModelScale; } } private void DisableIfNeeded() { if (unit.Dead || unit == null) gameObject.SetActive(false); } }<file_sep>using UnityEngine; //Classe représentant une carte d'unité //chaque archétype d'unité hérite de cette classe est redéfinis le CardEffect [CreateAssetMenu(menuName="Cards/Units/Default")] public class UnitCard : CardBase { [SerializeField] private GameObject model = null; [SerializeField] public int health = 1; [SerializeField] public int attack = 1; [SerializeField] private int movement = 5; [SerializeField] private UnitMoveMask movementMask = UnitMoveMask.NeutralCells; [SerializeField] private UnitMoveMask atqMask = UnitMoveMask.NeutralCells; [SerializeField] protected bool range = false; [SerializeField] protected float modelScale = 1f; public GameObject Model => model; public int Health => health; public int Attack => attack; public int Movement => movement; public UnitMoveMask MovementMask => movementMask; public UnitMoveMask AtqMask => atqMask; public bool Range => range; public float ModelScale => modelScale; protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { board.AddUnit(this, target, player); return true; } }<file_sep>using Photon.Pun; using Photon.Realtime; using System.Collections; using System.Collections.Generic; using UnityEngine; public class refreshList : MonoBehaviour { public void OnEnable() { on_click_refresh_list(); } public void on_click_refresh_list() { PhotonNetwork.JoinLobby(TypedLobby.Default); } } <file_sep>using Photon.Pun; using Photon.Realtime; using System.Collections; using System.Collections.Generic; using UnityEngine; public class testConnect : MonoBehaviourPunCallbacks { // Start is called before the first frame update void Start() { if (PlayerPrefs.HasKey("username")) { PhotonNetwork.NickName = PlayerPrefs.GetString("username"); } PhotonNetwork.ConnectUsingSettings(); } public override void OnConnectedToMaster() { print(PhotonNetwork.LocalPlayer.NickName); PhotonNetwork.JoinLobby(TypedLobby.Default); } } <file_sep>using Photon.Pun; using UnityEngine; using ExitGames.Client.Photon; //Classe permettant de faire le lien entre le joueur d'un point de vu réseau //et leur objet Player respectif public enum PlayerRole { PlayerOne = 0, PlayerTwo = 1, Spectator = 2 } public static class PlayersExtension { public static PlayerRole Other(this PlayerRole player) { switch(player) { case PlayerRole.PlayerOne: return PlayerRole.PlayerTwo; case PlayerRole.PlayerTwo: return PlayerRole.PlayerOne; default: return PlayerRole.Spectator; } } public static PlayerRole RandomPlayer() { int value = Random.Range(0, 2); if (value == 0) { return PlayerRole.PlayerOne; } else { return PlayerRole.PlayerTwo; } } public static void RegisterLocalPlayer(PlayerRole role, Deck deck) { Hashtable hash = new Hashtable { { "role", role }, { "deck", deck }}; LocalPhotonPlayer().SetCustomProperties(hash); } public static Deck GetDeckLocalPlayer() { if (PhotonNetwork.InRoom) { return (Deck) LocalPhotonPlayer().CustomProperties["deck"]; } return null; } public static Deck GetDeckRemotePlayer() { if (PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom.PlayerCount > 1) { return (Deck) RemotePhotonPlayer().CustomProperties["deck"]; } return null; } public static PlayerRole LocalPlayer() { if (PhotonNetwork.InRoom) { return (PlayerRole) LocalPhotonPlayer().CustomProperties["role"]; } return PlayerRole.PlayerOne; } public static PlayerRole RemotePlayer() { if (PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom.PlayerCount > 1) { return (PlayerRole) RemotePhotonPlayer().CustomProperties["role"]; } return PlayerRole.PlayerTwo; } public static int LocalPlayerIndex() { return (int) LocalPlayer(); } public static int RemotePlayerIndex() { return (int) RemotePlayer(); } public static Photon.Realtime.Player LocalPhotonPlayer() { return PhotonNetwork.LocalPlayer; } public static Photon.Realtime.Player RemotePhotonPlayer() { return PhotonNetwork.LocalPlayer.GetNext(); } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using Photon.Pun; using Photon.Realtime; using UnityEngine.UI; public class CreateRoom : MonoBehaviourPunCallbacks { [SerializeField] private TMP_InputField _roomField = null; [SerializeField] private TMP_Text ErrorName = null; private bool IsPrivate = false; [SerializeField] private GameObject _roomCanvas = null; [SerializeField] private TMP_Dropdown _dropDown = null; [SerializeField] private TMP_Text _selectedGameMode = null; //_selectedGameMode.text pour avoir le mode sélectionné private GameModes mode; public override void OnEnable() { _dropDown.ClearOptions(); base.OnEnable(); _roomField.text = PhotonNetwork.NickName + "'s Game"; FillDropDown(); } private void FillDropDown() { _dropDown.AddOptions(new List<string>(Enum.GetNames(typeof(GameModes)))); } public void CreateRoom_button() { string name = _roomField.text; if (name.Length > 0 && PhotonNetwork.IsConnected) { if (Enum.TryParse<GameModes>(_selectedGameMode.text, out mode)) { RoomOptions RoomOptions = new RoomOptions(); RoomOptions.MaxPlayers = 2; RoomOptions.IsVisible = !IsPrivate; PhotonNetwork.CreateRoom(name, RoomOptions, TypedLobby.Default); } } return; } public override void OnCreatedRoom() { PhotonNetwork.CurrentRoom.SetCustomProperties( new ExitGames.Client.Photon.Hashtable { {"GameMode", (int) mode}} ); } public void on_click_change_private() { IsPrivate = !IsPrivate; } public override void OnCreateRoomFailed(short returnCode, string message) { ErrorName.gameObject.SetActive(true); ErrorName.text = message; } public override void OnJoinedRoom() { _roomCanvas.SetActive(true); } public override void OnJoinRoomFailed(short returnCode, string message) { ErrorName.gameObject.SetActive(true); ErrorName.text = message; } } <file_sep>using Photon.Pun; using Photon.Realtime; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class RoomListing : MonoBehaviour { [SerializeField] private TMP_Text _name = null; [SerializeField] private TMP_Text _CountPlayers = null; [SerializeField] private TMP_Text _gameFull = null; public RoomInfo RoomInfo { get; private set; } public void SetRoomInfo(RoomInfo roomInfo) { RoomInfo = roomInfo; _name.text = roomInfo.Name; _CountPlayers.text = RoomInfo.PlayerCount.ToString() + "/2"; _gameFull.gameObject.SetActive(RoomInfo.PlayerCount == 2); } public void on_click_join_room() { PhotonNetwork.JoinRoom(RoomInfo.Name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using TMPro; using System; using UnityEngine.UI; using UnityEngine.Events; public class DeckDraw : MonoBehaviour { [SerializeField] private Hand hand = null; [SerializeField] private GameObject _unitCard = null; [SerializeField] private GameObject _spellCard = null; [SerializeField] private GameObject UnitDeck = null; [SerializeField] private GameObject SpellDeck = null; [SerializeField] private GameObject validate = null; [SerializeField] private BoardPlayer BoardPlayer = null; [SerializeField] private ParticleSystem DiscardParticleUnit = null; [SerializeField] private ParticleSystem DiscardParticleSpell = null; private Button ValidateButton; private List<CardBase> listCardMulligan = new List<CardBase>(); private List<GameObject> cardsMulligan = new List<GameObject>(); private List<int> toReplace = new List<int>(); private class CardEvent : UnityEvent<GameObject> { } public static UnityEvent<GameObject> eventReplaceCards; public void Start() { if (eventReplaceCards == null) eventReplaceCards = new CardEvent(); eventReplaceCards.AddListener(UpdateReplace); } public void UpdateReplace(GameObject card) { int cardNb = 0; if (cardsMulligan.Count == 3) cardNb = Mathf.RoundToInt(card.transform.localPosition.x * 50f / 9 + 2); else cardNb = Mathf.RoundToInt(card.transform.localPosition.x * 50f / 9 + 5f/2); if(toReplace.Contains(cardNb)) { toReplace.Remove(cardNb); } else { toReplace.Add(cardNb); } } public void Mulligan(Tuple<List<UnitCard>, List<SpellCard>> tuple) { StartCoroutine(MulliganCoroutine(tuple)); } private IEnumerator MulliganCoroutine(Tuple<List<UnitCard>, List<SpellCard>> v) { ValidateButton = validate.GetComponentInChildren<Button>(true); validate.SetActive(true); float x = (v.Item2.Count == 1) ? 0 : -0.5f ; Sequence DrawSequence = DOTween.Sequence(); foreach(UnitCard unit in v.Item1) { yield return new WaitForSecondsRealtime(1f); GameObject U = Instantiate(_unitCard, UnitDeck.transform); cardsMulligan.Add(U); listCardMulligan.Add(unit); U.transform.localScale = Vector3.one; U.transform.localPosition = new Vector3(0, 0, 0); U.transform.eulerAngles = new Vector3(180, 90, 0); U.SetActive(true); DrawSequence = DOTween.Sequence(); U.transform.SetParent(hand.gameObject.transform); float posX = x * 0.18f - 0.18f; DrawSequence.Append(U.transform.DOLocalMove(new Vector3(posX, 0.3f, 0), 0.4f)); DrawSequence.Join(U.transform.DOLocalRotate(new Vector3(-90, 0, 0), 0.5f)); DrawSequence.Join(U.transform.DOScale(Vector3.one * 2, 0.4f)); TMP_Text[] texts = U.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = unit.Name; texts[1].text = unit.Description; texts[2].text = unit.Cost.ToString(); texts[3].text = ((UnitCard)unit).Attack.ToString(); texts[4].text = ((UnitCard)unit).Health.ToString(); texts[5].text = (((UnitCard)unit).Range) ? "Range" : "Melee"; U.GetComponentInChildren<Canvas>().GetComponentInChildren<Collider>(true).gameObject.SetActive(true); x++; } foreach (SpellCard spell in v.Item2) { yield return new WaitForSecondsRealtime(1f); GameObject S = Instantiate(_spellCard, SpellDeck.transform); cardsMulligan.Add(S); listCardMulligan.Add(spell); S.transform.localScale = Vector3.one; S.transform.localPosition = new Vector3(0, 0, 0); S.transform.eulerAngles = new Vector3(180, 90, 0); S.SetActive(true); DrawSequence = DOTween.Sequence(); S.transform.SetParent(hand.gameObject.transform); float posX = x * 0.18f - 0.18f; DrawSequence.Append(S.transform.DOLocalMove(new Vector3(posX, 0.3f, 0), 0.4f)); DrawSequence.Join(S.transform.DOLocalRotate(new Vector3(-90, 0, 0), 0.5f)); DrawSequence.Join(S.transform.DOScale(Vector3.one * 2, 0.4f)); TMP_Text[] texts = S.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = spell.Name; texts[1].text = spell.Description; texts[2].text = spell.Cost.ToString(); S.GetComponentInChildren<Canvas>().GetComponentInChildren<Collider>(true).gameObject.SetActive(true); x++; } ValidateButton.gameObject.SetActive(true); } public void Draw(CardBase card = null) { Sequence DrawSequence = DOTween.Sequence(); if (BoardPlayer.manager.CurrentPlayer.Hand.Count > 10) { DrawSequence = DOTween.Sequence(); if ((card.GetType().IsAssignableFrom(typeof(UnitCard)) || card.GetType().IsSubclassOf(typeof(UnitCard)) )) { _unitCard.transform.SetParent(UnitDeck.transform); _unitCard.transform.localScale = Vector3.one; _unitCard.transform.localPosition = new Vector3(0, 0, 0); _unitCard.transform.eulerAngles = new Vector3(180, 90, 0); _unitCard.SetActive(true); DrawSequence = DOTween.Sequence(); _unitCard.transform.SetParent(hand.gameObject.transform); DrawSequence.Append(_unitCard.transform.DOLocalMove(new Vector3(0, 0.2f, 0), 0.4f)); DrawSequence.Join(_unitCard.transform.DOLocalRotate(new Vector3(-90, 0, 0), 0.5f)); DrawSequence.Join(_unitCard.transform.DOScale(Vector3.one * 2, 0.4f)); if (card) { TMP_Text[] texts = _unitCard.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = card.Name; texts[1].text = card.Description; texts[2].text = card.Cost.ToString(); texts[3].text = ((UnitCard)card).Attack.ToString(); texts[4].text = ((UnitCard)card).Health.ToString(); texts[5].text = (((UnitCard)card).Range) ? "Range" : "Melee"; } StartCoroutine(DiscardUnit()); DOTween.Play(DrawSequence); } else { _spellCard.transform.SetParent(SpellDeck.transform); _spellCard.transform.localScale = Vector3.one; _spellCard.transform.localPosition = new Vector3(0, 0, 0); _spellCard.transform.eulerAngles = new Vector3(180, 90, 0); _spellCard.SetActive(true); DrawSequence = DOTween.Sequence(); _spellCard.transform.SetParent(hand.gameObject.transform); DrawSequence.Append(_spellCard.transform.DOLocalMove(new Vector3(0, 0.2f, 0), 0.4f)); DrawSequence.Join(_spellCard.transform.DOLocalRotate(new Vector3(-90, 0, 0), 0.5f)); DrawSequence.Join(_spellCard.transform.DOScale(Vector3.one * 2, 0.4f)); if (card) { TMP_Text[] texts = _spellCard.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = card.Name; texts[1].text = card.Description; texts[2].text = card.Cost.ToString(); } StartCoroutine(DiscardSpell()); DOTween.Play(DrawSequence); } } else { float x = 0; if ((card.GetType().IsAssignableFrom(typeof(UnitCard)) || card.GetType().IsSubclassOf(typeof(UnitCard)))) { _unitCard.transform.SetParent(UnitDeck.transform); _unitCard.transform.localScale = Vector3.one; _unitCard.transform.localPosition = new Vector3(0, 0, 0); _unitCard.transform.eulerAngles = new Vector3(180, 90, 0); _unitCard.SetActive(true); DrawSequence = DOTween.Sequence(); _unitCard.transform.SetParent(hand.gameObject.transform); DrawSequence.Append(_unitCard.transform.DOLocalMove(new Vector3(0, 0.2f, 0), 0.4f)); DrawSequence.Join(_unitCard.transform.DOLocalRotate(new Vector3(-90, 0, 0), 0.5f)); DrawSequence.Join(_unitCard.transform.DOScale(Vector3.one * 2, 0.4f)); if (card) { TMP_Text[] texts = _unitCard.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = card.Name; texts[1].text = card.Description; texts[2].text = card.Cost.ToString(); texts[3].text = ((UnitCard)card).Attack.ToString(); texts[4].text = ((UnitCard)card).Health.ToString(); texts[5].text = (((UnitCard)card).Range) ? "Range" : "Melee"; } StartCoroutine(wait()); DrawSequence.AppendInterval(1); if (hand.player != null) { x = (hand.player.Hand.Count - 0.5f - hand.player.Hand.Count / 2f) * hand.Spacing; } DrawSequence.Append(_unitCard.transform.DOLocalMove(new Vector3(x, 0.2f, 0f), 0.2f)); DrawSequence.Append(_unitCard.transform.DOLocalMove(new Vector3(x, 0f, 0f), 0.2f)); DrawSequence.Join(_unitCard.transform.DOLocalRotate(new Vector3(-90f, 0, 0), 0.2f)); DrawSequence.Join(_unitCard.transform.DOScale(Vector3.one, 0.2f)); DOTween.Play(DrawSequence); } else { _spellCard.transform.SetParent(SpellDeck.transform); _spellCard.transform.localScale = Vector3.one; _spellCard.transform.localPosition = new Vector3(0, 0, 0); _spellCard.transform.eulerAngles = new Vector3(180, 90, 0); _spellCard.SetActive(true); DrawSequence = DOTween.Sequence(); _spellCard.transform.SetParent(hand.gameObject.transform); DrawSequence.Append(_spellCard.transform.DOLocalMove(new Vector3(0, 0.2f, 0), 0.4f)); DrawSequence.Join(_spellCard.transform.DOLocalRotate(new Vector3(-90, 0, 0), 0.5f)); DrawSequence.Join(_spellCard.transform.DOScale(Vector3.one * 2, 0.4f)); if (card) { TMP_Text[] texts = _spellCard.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = card.Name; texts[1].text = card.Description; texts[2].text = card.Cost.ToString(); } StartCoroutine(wait()); DrawSequence.AppendInterval(1); if (hand.player != null) { x = (hand.player.Hand.Count - 0.5f - hand.player.Hand.Count / 2f) * hand.Spacing; } DrawSequence.Append(_spellCard.transform.DOLocalMove(new Vector3(x, 0.2f, 0f), 0.2f)); DrawSequence.Append(_spellCard.transform.DOLocalMove(new Vector3(x, 0f, 0f), 0.2f)); DrawSequence.Join(_spellCard.transform.DOLocalRotate(new Vector3(-90f, 0, 0), 0.2f)); DrawSequence.Join(_spellCard.transform.DOScale(Vector3.one, 0.2f)); DOTween.Play(DrawSequence); } } } IEnumerator wait() { yield return new WaitForSecondsRealtime(1.9f); hand.UpdateHand(); _unitCard.SetActive(false); _spellCard.SetActive(false); } IEnumerator DiscardSpell() { yield return new WaitForSecondsRealtime(1.0f); DiscardParticleSpell.transform.localScale = Vector3.one * 0.2f; DiscardParticleSpell.Play(); yield return new WaitForSecondsRealtime(0.5f); _unitCard.SetActive(false); _spellCard.SetActive(false); } IEnumerator DiscardUnit() { yield return new WaitForSecondsRealtime(1.0f); DiscardParticleUnit.transform.localScale = Vector3.one * 0.2f; DiscardParticleUnit.Play(); yield return new WaitForSecondsRealtime(0.5f); _unitCard.SetActive(false); _spellCard.SetActive(false); } public void Validate() { StartCoroutine(UpdateTextReplace()); } private IEnumerator UpdateTextReplace() { float x = (listCardMulligan.Count == 3) ? 0 : -0.9f; Sequence ReplaceSequence = DOTween.Sequence(); ValidateButton.gameObject.SetActive(false); List<CardBase> toAddCard = new List<CardBase>(); List<CardBase> toRemoveCard = new List<CardBase>(); foreach(GameObject c in cardsMulligan) { c.GetComponentInChildren<Canvas>().GetComponentInChildren<Collider>(true).gameObject.SetActive(false); } toReplace.Sort(); foreach (int i in toReplace) { ReplaceSequence = DOTween.Sequence(); float posX = i * 0.18f - 0.18f; if ((listCardMulligan[i - 1].GetType().IsAssignableFrom(typeof(UnitCard)) || listCardMulligan[i - 1].GetType().IsSubclassOf(typeof(UnitCard)))) { UnitCard unitReplace = BoardPlayer.manager.CurrentPlayer.Deck.DrawUnit(); GameObject U = cardsMulligan[i - 1]; toAddCard.Add(unitReplace); Vector3 pos = U.transform.localPosition; ReplaceSequence.Append(U.transform.DOLocalMove(new Vector3(0.439f, 0.2018478f, 0.1763173f), 0.4f)); ReplaceSequence.Join(U.transform.DOLocalRotate(new Vector3(209.874f, 92.881f, 84.231f), 0.4f)); ReplaceSequence.Join(U.transform.DOScale(Vector3.one, 0.4f)); ReplaceSequence.Append(U.transform.DOLocalMove(pos, 0.4f)); ReplaceSequence.Join(U.transform.DOLocalRotate(new Vector3(-90f, 0f, 0f), 0.4f)); ReplaceSequence.Join(U.transform.DOScale(Vector3.one * 2, 0.4f)); yield return new WaitForSecondsRealtime(0.5f); TMP_Text[] texts = U.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = unitReplace.Name; texts[1].text = unitReplace.Description; texts[2].text = unitReplace.Cost.ToString(); texts[3].text = unitReplace.Attack.ToString(); texts[4].text = unitReplace.Health.ToString(); texts[5].text = (unitReplace.Range) ? "Range" : "Melee"; DOTween.Play(ReplaceSequence); } else { SpellCard spellReplace = BoardPlayer.manager.CurrentPlayer.Deck.DrawSpell(); toAddCard.Add(spellReplace); GameObject S = cardsMulligan[i - 1]; Vector3 pos = S.transform.localPosition; ReplaceSequence.Append(S.transform.DOLocalMove(new Vector3(0.393f, 0.1185548f, 0.1763173f), 0.4f)); ReplaceSequence.Join(S.transform.DOLocalRotate(new Vector3(-29.874f, -87.119f, 264.231f), 0.4f)); ReplaceSequence.Join(S.transform.DOScale(Vector3.one, 0.4f)); ReplaceSequence.Append(S.transform.DOLocalMove(pos, 0.4f)); ReplaceSequence.Join(S.transform.DOLocalRotate(new Vector3(-90f, 0f, 0f), 0.4f)); ReplaceSequence.Join(S.transform.DOScale(Vector3.one * 2, 0.4f)); yield return new WaitForSecondsRealtime(0.5f); TMP_Text[] texts = S.GetComponentInChildren<Canvas>().GetComponentsInChildren<TMP_Text>(); texts[0].text = spellReplace.Name; texts[1].text = spellReplace.Description; texts[2].text = spellReplace.Cost.ToString(); DOTween.Play(ReplaceSequence); } BoardPlayer.manager.CurrentPlayer.Deck.AddCard(listCardMulligan[i - 1]); toRemoveCard.Add(listCardMulligan[i - 1]); } foreach(CardBase r in toRemoveCard) { listCardMulligan.Remove(r); } foreach(CardBase a in toAddCard) { listCardMulligan.Add(a); } yield return new WaitForSecondsRealtime(2f); foreach (CardBase card in listCardMulligan) { BoardPlayer.manager.CurrentPlayer.addCard(card); } validate.gameObject.SetActive(false); foreach (GameObject c in cardsMulligan) { Destroy(c); } hand.UpdateHand(); } } <file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Rendering; [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer), typeof(MeshCollider))] public class BoardMesh : BoardBehaviour { private MeshFilter meshFilter; private MeshRenderer meshRenderer; private MeshCollider meshCollider; private Mesh mesh; private Dictionary<int, int> cellCenterIndices; public override void OnResetBoard(BoardManager boardManager) { base.OnResetBoard(boardManager); Start(); } private void Start() { mesh = new Mesh(); mesh.MarkDynamic(); mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; cellCenterIndices = new Dictionary<int, int>(); meshFilter = gameObject.GetComponent<MeshFilter>(); meshRenderer = gameObject.GetComponent<MeshRenderer>(); meshCollider = gameObject.GetComponent<MeshCollider>(); GenerateMesh(); meshFilter.mesh = mesh; meshCollider.sharedMesh = mesh; } private void GenerateMesh() { List<Vector3> vertices = new List<Vector3>(); List<Vector2> uv = new List<Vector2>(); List<List<int>> triangles = new List<List<int>>(); for (int i = 0; i < 4; i++) triangles.Add(new List<int>()); List<List<Cell>> cellGroups = new List<List<Cell>>(); foreach (var cell in board.Cells()) { GenerateHexagonTop(cell, vertices, uv, triangles); } foreach (var cell in board.Cells()) { foreach(var neighbor in board.Neighbors(cell)) { if (cellCenterIndices.ContainsKey(board.CellIndex(neighbor.position.x, neighbor.position.y))) { GenerateHexagonSide(cell, neighbor, vertices, uv, triangles); } } } mesh.subMeshCount = triangles.Count; mesh.vertices = vertices.ToArray(); mesh.uv = uv.ToArray(); for (int i = 0; i < triangles.Count; i++) mesh.SetTriangles(triangles[i], i); mesh.RecalculateNormals(); mesh.MarkModified(); } public void UpdateMesh(List<Cell> changedCells) { Vector3[] vertices = mesh.vertices; List<List<int>> triangles = new List<List<int>>(); for (int i = 0; i < mesh.subMeshCount; i++) { triangles.Add(mesh.GetTriangles(i).ToList()); } foreach (var cell in changedCells) { UpdateCell(cell, vertices, triangles); } mesh.vertices = vertices; for (int i = 0; i < mesh.subMeshCount; i++) { mesh.SetTriangles(triangles[i], i); } mesh.RecalculateNormals(); mesh.MarkModified(); meshCollider.sharedMesh = mesh; } private int[] GetCellVertIndices(Cell cell) { int index = board.CellIndex(cell.position.x, cell.position.y); int c = cellCenterIndices[index]; return new int[] { c, c+1, c+2, c+3, c+4, c+5, c+6, c+7, c+8, c+9, c+10, c+11, c+12, c+13, c+14, c+15, c+16, c+17, c+18, }; } private void UpdateCell(Cell cell, Vector3[] vertices, List<List<int>> triangles) { int[] verts = GetCellVertIndices(cell); for (int i = 0; i < verts.Length; i++) { vertices[verts[i]].y = cell.Height; } int oldSubMesh = triangles.FindIndex(sm => sm.Any(t => t == verts[0])); int firstTriangle = triangles[oldSubMesh].FindIndex(t => t == verts[0]); triangles[oldSubMesh].RemoveRange(firstTriangle, 18); int newSubMesh = CellSubMesh(cell); GenerateHexagonTopTriangles(verts[0], newSubMesh, triangles); } private void GenerateHexagonTop(Cell cell, List<Vector3> vertices, List<Vector2> uv, List<List<int>> triangles) { int nverts = vertices.Count; int subMesh = CellSubMesh(cell); Vector3 pos = board.CellToLocal(cell.position); cellCenterIndices[board.CellIndex(cell.position.x, cell.position.y)] = vertices.Count; vertices.Add(pos); vertices.Add(pos + new Vector3(-0.5f, 0, -Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(0.5f, 0, -Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(1f, 0, 0)); vertices.Add(pos + new Vector3(0.5f, 0, Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(-0.5f, 0, Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(-1f, 0, 0)); vertices.Add(pos + new Vector3(-0.5f, 0, -Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(0.5f, 0, -Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(0.5f, 0, -Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(1f, 0, 0)); vertices.Add(pos + new Vector3(1f, 0, 0)); vertices.Add(pos + new Vector3(0.5f, 0, Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(0.5f, 0, Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(-0.5f, 0, Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(-0.5f, 0, Mathf.Sqrt(3f)/2f)); vertices.Add(pos + new Vector3(-1f, 0, 0)); vertices.Add(pos + new Vector3(-1f, 0, 0)); vertices.Add(pos + new Vector3(-0.5f, 0, -Mathf.Sqrt(3f)/2f)); uv.Add(new Vector2(0.5f, 0.5f)); uv.Add(new Vector2(0.25f, 0)); uv.Add(new Vector2(0.75f, 0)); uv.Add(new Vector2(1, 0.5f)); uv.Add(new Vector2(0.75f, 1)); uv.Add(new Vector2(0.25f, 1)); uv.Add(new Vector2(0, 0.5f)); uv.Add(new Vector2(0, 0)); uv.Add(new Vector2(1, 0)); uv.Add(new Vector2(0, 0)); uv.Add(new Vector2(1, 0)); uv.Add(new Vector2(0, 0)); uv.Add(new Vector2(1, 0)); uv.Add(new Vector2(0, 1)); uv.Add(new Vector2(1, 1)); uv.Add(new Vector2(0, 1)); uv.Add(new Vector2(1, 1)); uv.Add(new Vector2(0, 1)); uv.Add(new Vector2(1, 1)); GenerateHexagonTopTriangles(nverts, subMesh, triangles); } private void GenerateHexagonTopTriangles(int center, int subMesh, List<List<int>> triangles) { triangles[subMesh].Add(center); triangles[subMesh].Add(center+2); triangles[subMesh].Add(center+1); triangles[subMesh].Add(center); triangles[subMesh].Add(center+3); triangles[subMesh].Add(center+2); triangles[subMesh].Add(center); triangles[subMesh].Add(center+4); triangles[subMesh].Add(center+3); triangles[subMesh].Add(center); triangles[subMesh].Add(center+5); triangles[subMesh].Add(center+4); triangles[subMesh].Add(center); triangles[subMesh].Add(center+6); triangles[subMesh].Add(center+5); triangles[subMesh].Add(center); triangles[subMesh].Add(center+1); triangles[subMesh].Add(center+6); } private void GenerateHexagonSide(Cell cell, Cell neighbor, List<Vector3> vertices, List<Vector2> uv, List<List<int>> triangles) { int subMesh = SideSubMesh(cell, neighbor); Vector3 middle = (board.CellToLocal(cell.position) + board.CellToLocal(neighbor.position)) / 2f; Vector3 offset = board.CellToLocal(cell.position) - board.CellToLocal(neighbor.position); offset.y = 0; Vector3 right = Vector3.Cross(offset, Vector3.up).normalized * 0.5f; float height = cell.Height - neighbor.Height; Vector3 a = middle - right; Vector3 b = middle + right; int[] cellVerts = GetCellVertIndices(cell).Skip(7).ToArray(); int[] neighborVerts = GetCellVertIndices(neighbor).Skip(7).ToArray(); var vertsCell = vertices.GetRange(cellVerts[0], 12); var vertsNeighbor = vertices.GetRange(neighborVerts[0], 12); var la = vertsCell.OrderBy(v => (v-a).sqrMagnitude).ToArray(); var lc = vertsNeighbor.OrderBy(v => (v-a).sqrMagnitude).ToArray(); int ia = (vertsCell.IndexOf(la[0]))%12; int ib = (ia+11)%12; int ic = (ia+5)%12; int id = (ic+1)%12; int na = cellVerts[ia]; int nb = cellVerts[ib]; int nc = neighborVerts[ic]; int nd = neighborVerts[id]; triangles[subMesh].Add(nb); triangles[subMesh].Add(na); triangles[subMesh].Add(nc); triangles[subMesh].Add(nd); triangles[subMesh].Add(nb); triangles[subMesh].Add(nc); } private int CellSubMesh(Cell cell) { if (cell.cellType == Cell.CellType.Water) return 0; else if (cell.cellType == Cell.CellType.Field) return 1; else return 2; } private int SideSubMesh(Cell high, Cell low) { return 3; } } <file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; //Masque de déplacement permettant de définir des règles de déplacement complexes [System.Serializable, System.Flags ] public enum UnitMoveMask { PathFinding = 1 << 0, FlyBy = 1 << 1, OnWater = 1 << 2, OnField = 1 << 3, OnMountain = 1 << 4, NormalCells = 1 << 5, SpecialCells = 1 << 6, AllyCells = 1 << 7, EnnemyCells = 1 << 8, NeutralCells = 1 << 9, AnyTerrain = OnWater | OnField | OnMountain, AnyCellOwner = AllyCells | EnnemyCells | NeutralCells, } public static class UnitMovement { public static IEnumerable<Cell> AvailableCells(UnitMoveMask value, Board board, Cell origin, int maxDistance) { if (Check(value, UnitMoveMask.PathFinding)) { foreach (var cell in PathFinding.CellsInReach(board, origin, maxDistance, value)) { yield return cell; } } else if (Check(value, UnitMoveMask.FlyBy)) { foreach (var cell in board.Disc(origin, maxDistance)) { if (CheckCell(value, board, cell)) yield return cell; } } } public static bool CanMove(UnitMoveMask value, Board board, Cell origin, Cell target, int maxDistance, out List<Cell> path) { if (Check(value, UnitMoveMask.PathFinding)) { return PathFinding.ComputePath(board, origin, target, maxDistance, value, out path); } else if (Check(value, UnitMoveMask.FlyBy) && CheckCell(value, board, target)) { if (target.Distance(origin) <= maxDistance*2) { path = new List<Cell> {origin, target}; return true; } } path = null; return false; } private static bool Check(UnitMoveMask value, UnitMoveMask mask) { return (value & mask) != 0; } public static bool CheckCell(UnitMoveMask value, Board board, Cell cell) { return TestTerrain(value, board, cell) && TestUnits(value, board, cell); } private static bool TestTerrain(UnitMoveMask value, Board board, Cell cell) { return value == UnitMoveMask.AnyTerrain || Check(value, UnitMoveMask.OnWater) && cell.cellType == Cell.CellType.Water || Check(value, UnitMoveMask.OnField) && cell.cellType == Cell.CellType.Field || Check(value, UnitMoveMask.OnMountain) && cell.cellType == Cell.CellType.Mountain; } private static bool TestUnits(UnitMoveMask value, Board board, Cell cell) { var unit = board.GetUnit(cell); return unit == null || unit.Dead; } } <file_sep>using ExitGames.Client.Photon; using Photon.Pun; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; using System.Collections; using UnityEngine.UI; using TMPro; using PHashTable = ExitGames.Client.Photon.Hashtable; using DG.Tweening; //Classe s'occupant de la synchronization des joueurs lors d'une partie en réseau public class BoardManager : MonoBehaviourPunCallbacks, IPunObservable { public Board board => manager.Board; public GameManager Manager => manager; public GameObject ValidateButton => validateButton; [SerializeField] private Vector2Int boardSize = new Vector2Int(50, 50); [SerializeField] private float perlinNoiseScale = 0.0f; [SerializeField] private Vector3 perlinNoiseOffset = Vector3.zero; [SerializeField] private Transform EndTurnButton = null; [SerializeField] private TMP_Text TimerText = null; [SerializeField] private BoardCardDraw[] draws = null; [SerializeField] private Hand _hand = null; [SerializeField] public TMP_Text scoreText1 = null; [SerializeField] public TMP_Text scoreText2 = null; [SerializeField] public TMP_Text infoWin = null; [SerializeField] public GameObject YourTurnButton = null; [SerializeField] private BoardPlayer BoardPlayer = null; [SerializeField] private GameObject validateButton = null; [SerializeField] private GameObject DrawUI = null; public Hand Hand { get { return _hand; } } public UnityEvent onReset; [SerializeField] private GameManager manager; private Coroutine _timer = null; private bool startOfTurn = false; private bool startOfEnnemyTurn; private void Awake() { PhotonPeer.RegisterType(typeof(GameManager), (byte) 'G', GameManager.Serialize, GameManager.Deserialize); Reset(NewGame()); SubmitManager(); } private void Start() { startOfTurn = manager.MyTurn(); startOfEnnemyTurn = !startOfTurn; } private IEnumerator waitForWin(){ WinText text = infoWin.GetComponent<WinText>(); text.OnWin(Manager.GameState); SubmitManager(); yield return new WaitForSecondsRealtime(1f); PhotonNetwork.LeaveRoom(); } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) SubmitManager(); if (manager.GameState.Finished() && PhotonNetwork.IsConnectedAndReady) { StartCoroutine(waitForWin()); } if (manager.MyTurn() && startOfTurn) { startOfTurn = false; StartOfTurn(); } if (!manager.MyTurn() && startOfEnnemyTurn) { startOfEnnemyTurn = false; StartOfEnnemyTurn(); } UpdateScore(manager.GetScore(PlayersExtension.LocalPlayer()), manager.GetScore(PlayerRole.Spectator),1); } public void UpdateScore(int localscore, int maxscore,int score){ if(score == 1) { scoreText1.text = "My Score\n" + localscore.ToString()+ " / " + maxscore.ToString(); } else { scoreText2.text = "Ennemy Score\n" + localscore.ToString() + " / " + maxscore.ToString(); } } private void StartOfTurn() { StartCoroutine(YourTurn()); startOfEnnemyTurn = true; if (_timer != null) { StopCoroutine(_timer); } _timer = StartCoroutine(Timer()); EndTurnButton.gameObject.GetComponent<BoxCollider>().enabled = true; EndTurnButton.DORotate(new Vector3(90, 0, 180), 0.2f); DOTween.Play(EndTurnButton); if (draws != null) { foreach(var d in draws) { d.AllowDraw(); } } } IEnumerator YourTurn(){ if (manager.Turn == 1) { BoardPlayer.Mulligan(); yield return new WaitUntil(() => validateButton.activeInHierarchy); yield return new WaitWhile(() => validateButton.activeInHierarchy); } yield return new WaitUntil(() => DrawUI.activeInHierarchy); yield return new WaitWhile(() => DrawUI.activeInHierarchy); YourTurnButton.SetActive(true); yield return new WaitForSecondsRealtime(2f); YourTurnButton.SetActive(false); } private void StartOfEnnemyTurn() { startOfTurn = true; if (_timer != null) { StopCoroutine(_timer); } _timer = StartCoroutine(Timer()); EndTurnButton.gameObject.GetComponent<BoxCollider>().enabled = (PhotonNetwork.IsConnected) ? false : true; EndTurnButton.DORotate(new Vector3(-90, 0, 180), 0.2f); DOTween.Play(EndTurnButton); } private IEnumerator Timer() { TimerText.enabled = false; if (manager.Turn == 1) { yield return new WaitUntil(() => validateButton.activeInHierarchy); yield return new WaitWhile(() => validateButton.activeInHierarchy); } yield return new WaitUntil(() => DrawUI.activeInHierarchy); yield return new WaitWhile(() => DrawUI.activeInHierarchy); for (int i=60; i > 0; i--) { TimerText.text = i.ToString(); TimerText.enabled = (i <= 15 && manager.MyTurn()); yield return new WaitForSecondsRealtime(1f); } if (manager.MyTurn() || !PhotonNetwork.IsConnected) { NextTurn(); } } public void SubmitManager() { if (PhotonNetwork.IsConnected) photonView.RPC("Reset", RpcTarget.All, manager); } public static Photon.Realtime.Player RemotePhotonPlayer => PhotonNetwork.PlayerListOthers[0]; public static Photon.Realtime.Player LocalPhotonPlayer => PhotonNetwork.LocalPlayer; private GameManager NewGame() { GameModes mode = GameModes.DestroyTheBase; if (PhotonNetwork.InRoom) { mode = (GameModes) PhotonNetwork.CurrentRoom.CustomProperties["GameMode"]; } GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = boardSize; setup.noiseScale = perlinNoiseScale; setup.noiseOffset = perlinNoiseOffset; setup.gameMode = mode; Deck deck1 = null; Deck deck2 = null; if (PhotonNetwork.IsConnected) { deck2 = PlayersExtension.GetDeckLocalPlayer(); deck1 = PlayersExtension.GetDeckRemotePlayer(); } else { UnitCard c1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); UnitCard c2 = Resources.Load<UnitCard>("Cards/Unit/Eagle"); UnitCard c3 = Resources.Load<UnitCard>("Cards/Unit/Dragon"); SpellCard c4 = Resources.Load<SpellCard>("Cards/Spell/Fireball"); deck1 = new Deck( new UnitCard[] { c1, c1, c2, c2, c3, c3, c2, c3, c3}, new SpellCard[] { c4, c4, c4, c4, c4 } ); deck2 = new Deck(new UnitCard[] { c1, c1, c2, c2, c3, c3, c2, c3, c3 }, new SpellCard[] { c4, c4, c4, c4, c4 }); } GameManager manager = new GameManager(setup, deck1, deck2); return manager; } [PunRPC] public void Reset(GameManager manager) { this.manager = manager; onReset.Invoke(); } public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { // Debug.Log("Game manager synced"); } public override void OnLeftRoom() { SceneManager.LoadScene("Rooms"); PhotonNetwork.JoinLobby(); } public override void OnPlayerLeftRoom(Photon.Realtime.Player otherPlayer) { SceneManager.LoadScene("Rooms"); PhotonNetwork.JoinLobby(); } public void NextTurn(){ if (manager.MyTurn() || !PhotonNetwork.IsConnected){ manager.IncreaseTurn(); manager.ResetGold(); manager.NextTurn(); SubmitManager(); } } }<file_sep>using Photon.Pun; using System.Collections.Generic; using System.Linq; using UnityEngine; //Classe représentant le plateau de jeu hexagonale [System.Serializable] public class Board { [SerializeField] private Cell[] cells = null; [SerializeField] private List<Unit> units = null; public List<Unit> AllUnits => units; public List<Unit> Units => units.Where(u => u.Dead == false).ToList(); public Vector2Int size; public Board() { size = new Vector2Int(50, 50); units = new List<Unit>(); ResetGrid(); } public Board(Vector2Int size) { this.size = size; units = new List<Unit>(); ResetGrid(); } public Board(int width, int height) { this.size = new Vector2Int(width, height); units = new List<Unit>(); ResetGrid(); } //Permet d'obtenir la cell à l'index x y donné public int CellIndex(int x, int y) { return x % size.x + y * size.x; } private void ResetGrid() { cells = new Cell[size.x * size.y]; for (int x = 0; x < size.x; x++) { for (int y = 0; y < size.y; y++) { Cell cell = new Cell(new Vector2Int(x, y)); cells[CellIndex(x, y)] = cell; } } } public IEnumerable<Cell> Cells(bool ignoreTypeNone = true) { foreach (var cell in cells) if (cell.cellType != Cell.CellType.None || !ignoreTypeNone) yield return cell; } public bool HasCell(Vector2Int cellPosition) { return HasCell(cellPosition.x, cellPosition.y); } public bool HasCell(int x, int y) { return 0 <= x && x < size.x && 0 <= y && y < size.y && GetCell(x, y).cellType != Cell.CellType.None; } //Retourne la cellule pour la position demandée public Cell GetCell(Vector2Int cellPosition) { return GetCell(cellPosition.x, cellPosition.y); } public Cell GetCell(int x, int y) { return cells[CellIndex(x, y)]; } //Permet d'obtenir les coordonnées dans l'espace de la cellule donnée public Vector3 CellToLocal(Vector2Int cell) { return CellToLocal(cell.x, cell.y); } public Vector3 CellToLocal(int x, int y) { float locx = x - size.x / 2f; float locy = y - size.y / 2f; Vector3 pos = new Vector3(locx * 3f / 2f, 0, locx * Mathf.Sqrt(3)/2f + locy * Mathf.Sqrt(3)); if (HasCell(x, y)) pos += GetCell(x, y).Height * Vector3.up; return pos; } //Permet d'obtenir la cellule présente aux coordonnées dans l'espace données public Vector2Int LocalToCell(Vector3 point) { return new Vector2Int(Mathf.RoundToInt(point.x * 2f / 3f), Mathf.RoundToInt(point.x / -3f + Mathf.Sqrt(3f)/3f * point.z)) + size / 2; } //Permet d'obtenir l'unité présente sur la cellule donnée //null si aucune cellule n'est présente public Unit GetUnit(Cell cell, bool dead = false) { IEnumerable<Unit> e = units.Where(u => u.position == cell.position && (dead || !u.Dead)); if (e.Count() > 0) { return e.Last(); } else { return null; } } public Unit GetUnit(int unitId, bool dead = false) { IEnumerable<Unit> e = units.Where(u => u.Id == unitId && (dead || !u.Dead)); if (e.Count() > 0) { return e.Last(); } else { return null; } } //Permet d'obtenir la cellule sur laquelle se trouve l'unité public Cell GetCell(Unit unit) { return GetCell(unit.position); } public Vector3 LocalPosition(Unit unit) => CellToLocal(unit.position); public Vector3 LocalPosition(Cell cell) => CellToLocal(cell.position); //Permet d'obtenir une liste de cellules voisines pour la position ou la cellule donnée public IEnumerable<Cell> Neighbors(Vector2Int pos, bool addDummy=false) { int[] dx = new int[] {1,1,0,-1,-1,0}; int[] dy = new int[] {0,-1,-1,0,1,1}; for (int i = 0; i < 6; i++) { if (addDummy || HasCell(pos.x+dx[i], pos.y+dy[i])) { if (addDummy) yield return new Cell(new Vector2Int(pos.x+dx[i], pos.y+dy[i]), Cell.CellType.None); else yield return GetCell(pos.x+dx[i], pos.y+dy[i]); } } } public IEnumerable<Cell> Neighbors(Cell cell, bool addDummy=false) { return Neighbors(cell.position, addDummy); } //Permet d'obtenir une liste de cellules en anneau autour d'une cellule pour une distance donnée public IEnumerable<Cell> Ring(Cell cell, int distance) { if (distance == 0){ yield return cell; } else { Vector2Int pos = cell.position + new Vector2Int(-distance, distance); for (int i = 0; i < 6; i++) { for (int j = 0; j < distance; j++) { if (HasCell(pos)) yield return GetCell(pos); pos = Neighbors(pos, true).ElementAt(i).position; } } } } //Permet d'obtenir une liste de toutes les cellules autour d'une cellule pour une distance donnée public IEnumerable<Cell> Disc(Cell cell, int distance) { for (int d=0; d<distance; d++) foreach(var c in Ring(cell, d)) yield return c; } //Retourne la liste des unités appartenant au player donnée public IEnumerable<Unit> PlayerUnits(PlayerRole player) { foreach(var unit in units) { if (unit.Player == player) yield return unit; } } //Permet d'ajouter une unité sur une cellule du plateau public void AddUnit(UnitCard card, Cell target, PlayerRole owner) { units.Add(new Unit(card, target.position, units.Count, owner)); } }<file_sep>using UnityEngine; using System.Linq; using NUnit.Framework; public abstract class MonoBehaviourBaseTest { protected GameObject subject; [SetUp] public virtual void SetUp(){ subject = new GameObject("Subject"); } [TearDown] public virtual void TearDown(){ Object.FindObjectsOfType<GameObject>().ToList().ForEach(go => Object.Destroy(go)); } } <file_sep>using UnityEngine; public interface IGameObject : IObject { void SetActive(bool value); } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //Classe s'occupant du zoom/dézoom sur le plateau ainsi que le déplacement en X Y par le joueur. public class MoveBoard : MonoBehaviour { [SerializeField] private float maxZoom = 0.03f; [SerializeField] private float minZoom = 0.013f; private float CurrentZoom = 0; [SerializeField] private float Sensitivity = 0.002f; //[SerializeField] private float distance = -0.1f; [SerializeField] private float decalage = 0.05f; [SerializeField] private float magni = 0.2f; Vector3 p = Vector3.zero; Vector3 s = Vector3.zero; bool buttonDown = false; private void Start() { CurrentZoom = transform.localScale.x; } void FixedUpdate() { transform.localScale = Vector3.one * Mathf.Clamp((CurrentZoom + (Input.mouseScrollDelta.y * Time.deltaTime * Sensitivity)), minZoom, maxZoom); CurrentZoom = transform.localScale.x; magni = ((CurrentZoom * 450f) / 17f) - 117f / 340f; decalage = ((CurrentZoom * -1f) / 17f) + 18359375f/6640625000f; } private void OnMouseOver() { if (Input.GetMouseButtonDown(1)) { p = Input.mousePosition; s = Vector3.zero; buttonDown = true; } if (Input.GetMouseButton(1) && buttonDown) { s = Input.mousePosition; Vector3 normal = Vector3.Normalize(s - p); normal = new Vector3(normal.x,0,normal.y); transform.position = Vector3.ClampMagnitude(((s - p).magnitude * normal * decalage),magni)-new Vector3(0,0.1f,0); } if (Input.GetMouseButtonUp(1)) { buttonDown = false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoardPlayer : BoardBehaviour { public Player player { get; private set; } [SerializeField] private DeckDraw deckdraw = null; public override void OnResetBoard(BoardManager boardManager) { base.OnResetBoard(boardManager); Start(); } private void Start() { player = manager.CurrentPlayer; } public void Mulligan() { deckdraw.Mulligan(manager.CurrentPlayer.DrawMulligan(manager.PlayerTurn)); } public void DrawUnit() { deckdraw.Draw(manager.CurrentPlayer.DrawUnit()); } public void DrawSpell() { deckdraw.Draw(manager.CurrentPlayer.DrawSpell()); } }<file_sep>using System.Collections.Generic; using System.Linq; public static class PathFinding { public static bool ComputePath(Board board, Cell origin, Cell destination, int maxDistance, UnitMoveMask moveMask, out List<Cell> path) { if (origin == destination) { path = new List<Cell> { origin, destination }; } var tree = DepthFirstSearch(board, origin, maxDistance, moveMask); if ((tree.ContainsKey(origin) || tree.ContainsValue(origin)) && (tree.ContainsKey(destination) || tree.ContainsValue(destination))) { path = new List<Cell>(); path.Add(destination); while(tree[destination] != origin) { destination = tree[destination]; path.Add(destination); } path.Add(origin); path.Reverse(); return true; } path = null; return false; } public static IEnumerable<Cell> CellsInReach(Board board, Cell center, int maxDistance, UnitMoveMask moveMask) { var tree = DepthFirstSearch(board, center, maxDistance, moveMask); foreach(var cell in tree.Keys) yield return cell; foreach(var cell in tree.Values) if (!tree.ContainsKey(cell)) yield return cell; } private static Dictionary<Cell, Cell> DepthFirstSearch(Board board, Cell center, int maxDistance, UnitMoveMask moveMask) { Dictionary<Cell, Cell> tree = new Dictionary<Cell, Cell>(); Dictionary<Cell, int> distances = new Dictionary<Cell, int>(); distances.Add(center, 0); List<Cell> reachable = new List<Cell>(); foreach(Cell cell in board.Neighbors(center).Where(c => UnitMovement.CheckCell(moveMask, board, c))) { tree[cell] = center; distances.Add(cell, 1); reachable.Add(cell); } while(reachable.Count > 0) { Cell cell = reachable[0]; int distance = distances[cell]; if(distance+1 <= maxDistance) { distance++; foreach(Cell neighbor in board.Neighbors(cell).Where(c => UnitMovement.CheckCell(moveMask, board, c))) { if(!distances.ContainsKey(neighbor) || distances[neighbor] > distance) { distances[neighbor] = distance; tree[neighbor] = cell; reachable.Add(neighbor); } } } reachable.RemoveAt(0); } return tree; } }<file_sep>using System.Collections.Generic; using UnityEngine; using System.Linq; [CreateAssetMenu(menuName="Cards/Units/Aoe deploy")] public class AoeDeployCard : UnitCard { [SerializeField] protected int aoeDmg; [SerializeField] protected int aoeRange; //Carte effectuant des dommage en zone lorsqu'elle est déployée protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { List<Cell> cells = board.Disc(target, aoeRange).ToList(); foreach (Cell cell in cells){ if (board.GetUnit(cell) != null){ board.GetUnit(cell).TakeDamage(aoeDmg); } } board.AddUnit(this, target, player); return true; } }<file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; using System.Text; using UnityEngine.Serialization; //Classe représentant le deck du joueur [System.Serializable] public class Deck { // [SerializeField] private string owner = null; [SerializeField] private string name = null; public string Name => name; [SerializeField, FormerlySerializedAs("units")] private List<string> serializedUnits = null; [SerializeField, FormerlySerializedAs("spells")] private List<string> serializedSpells = null; public List<string> SerializedUnits => serializedUnits; public List<string> SerializedSpells => serializedSpells; public List<UnitCard> units => serializedUnits.Select(c => Resources.Load<UnitCard>(c)).ToList(); public List<SpellCard> spells => serializedSpells.Select(c => Resources.Load<SpellCard>(c)).ToList(); //private int MAX = 10; public Deck(string name) { this.name = name; serializedUnits = new List<string>(); serializedSpells = new List<string>(); } public Deck(string name, string[] unitResources, string[] spellResources) { this.name = name; this.serializedUnits = new List<string>(unitResources); this.serializedSpells = new List<string>(spellResources); } public Deck(string name, UnitCard[] units, SpellCard[] spells) { this.name = name; this.serializedUnits = units.Select(u => u.ResourcePath).ToList(); this.serializedSpells = spells.Select(s => s.ResourcePath).ToList(); } public Deck(UnitCard[] units, SpellCard[] spells) { this.name = ""; this.serializedUnits = units.Select(u => u.ResourcePath).ToList(); this.serializedSpells = spells.Select(s => s.ResourcePath).ToList(); } public Deck(Deck original) { this.name = original.name; this.serializedUnits = new List<string>(original.serializedUnits); this.serializedSpells = new List<string>(original.serializedSpells); } public void Shuffle() { serializedUnits = serializedUnits.OrderBy(unit => Random.value).ToList(); serializedSpells = serializedSpells.OrderBy(spell => Random.value).ToList(); } //Pioche une carte du deck Unité et l'ajoute à la main du joueur public UnitCard DrawUnit() { var card = serializedUnits[0]; serializedUnits.RemoveAt(0); return Resources.Load<UnitCard>(card); } //Pioche une carte du deck Sorts et l'ajoute à la main du joueur public SpellCard DrawSpell() { var card = serializedSpells[0]; serializedSpells.RemoveAt(0); return Resources.Load<SpellCard>(card); } //Ajoute une carte au deck public void AddCard(CardBase card) { if (card.GetType().IsAssignableFrom(typeof(UnitCard)) || card.GetType().IsSubclassOf(typeof(UnitCard)) ) { serializedUnits.Add(card.ResourcePath); } else { serializedSpells.Add(card.ResourcePath); } } //Supprime une carte du deck public void RemoveCard(CardBase card) { if (card.GetType().IsAssignableFrom(typeof(UnitCard)) || card.GetType().IsSubclassOf(typeof(UnitCard)) ) { serializedUnits.Remove(card.ResourcePath); } else { serializedSpells.Remove(card.ResourcePath); } } public static byte[] Serialize(object deck) { string json = JsonUtility.ToJson(deck); return Encoding.UTF8.GetBytes(json); } public static object Deserialize(byte[] data) { string json = Encoding.UTF8.GetString(data); return JsonUtility.FromJson<Deck>(json); } }<file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; //Classe s'occupant d'afficher un retour visuel du survol de la souris par l'utilisateur sur le plateau public class HoverCell : BoardBehaviour { private readonly Color transparent = new Color(0,0,0,0); [SerializeField] private Sprite sprite = null; [SerializeField] private float offset = 0.01f; private Dictionary<Vector2Int, SpriteRenderer> instances; private Dictionary<Color, List<Vector2Int>> colorToPos; private List<Color> stack; private void Start() { instances = new Dictionary<Vector2Int, SpriteRenderer>(); colorToPos = new Dictionary<Color, List<Vector2Int>>(); stack = new List<Color>(); foreach(Cell cell in board.Cells()) { GameObject go = new GameObject(string.Format("Cell ({0}, {1})", cell.position.x, cell.position.y), typeof(SpriteRenderer)); go.transform.parent = transform; go.transform.localPosition = board.LocalPosition(cell) + Vector3.up * offset; go.transform.localRotation = Quaternion.Euler(90, 0, 0); go.transform.localScale = Vector3.one; instances[cell.position] = go.GetComponent<SpriteRenderer>(); instances[cell.position].sprite = sprite; instances[cell.position].enabled = false; } } private void Update() { foreach (var kv in colorToPos) { foreach (var pos in kv.Value) { instances[pos].transform.localPosition = board.CellToLocal(pos) + Vector3.up * offset; instances[pos].color = kv.Key; instances[pos].enabled = true; } } } public void ShowCells(Color color, params Cell[] cells) { ShowCells(color, new List<Cell>(cells)); } public void ShowCells(Color color, IEnumerable<Cell> cells) { if (!stack.Contains(color)) stack.Add(color); if (!colorToPos.ContainsKey(color)) { colorToPos.Add(color, new List<Vector2Int>()); } foreach (var cell in cells) { if (instances.ContainsKey(cell.position)) { instances[cell.position].color = color; instances[cell.position].enabled = true; if (!colorToPos[color].Contains(cell.position)) colorToPos[color].Add(cell.position); } } } public void HideCells(Color color) { if (colorToPos.ContainsKey(color)) { foreach (var pos in colorToPos[color]) { instances[pos].enabled = false; } colorToPos.Remove(color); } } } <file_sep>using System.Collections; using UnityEngine; using UnityEngine.UI; //Classe s'occupant de la pioche du deck par le joueur lors du jeu public class BoardCardDraw : MonoBehaviour { public enum Draw { Unit, Spell } [SerializeField] private BoardPlayer player = null; [SerializeField] private Draw draw = Draw.Spell; [SerializeField] private BoardCardDraw[] others = null; [SerializeField] private GameObject drawUI = null; [SerializeField] private BoardManager BoardManager = null; [SerializeField] private GameObject DeckSpell = null; [SerializeField] private GameObject DeckUnit = null; private bool canDraw = false; public void AllowDraw() { StartCoroutine(AllowDrawCo()); } IEnumerator AllowDrawCo() { if (BoardManager.Manager.Turn == 1) { yield return new WaitUntil(() => BoardManager.ValidateButton.activeInHierarchy); yield return new WaitWhile(() => BoardManager.ValidateButton.activeInHierarchy); } canDraw = true; drawUI.SetActive(true); if (others != null) { foreach(var o in others) { o.canDraw = true; } } } public void DrawAtStartOfTurn() { if (BoardManager.Manager.Turn != 1 || !BoardManager.ValidateButton.activeInHierarchy) { if (canDraw) { if (draw == Draw.Unit) { player.DrawUnit(); } else { player.DrawSpell(); } canDraw = false; drawUI.SetActive(false); if (draw == Draw.Unit) { if (BoardManager.Manager.CurrentPlayer.Deck.units.Count == 0) { DeckUnit.SetActive(false); drawUI.GetComponentsInChildren<Button>(true)[1].gameObject.SetActive(false); } } else { if (BoardManager.Manager.CurrentPlayer.Deck.spells.Count == 0) { DeckSpell.SetActive(false); drawUI.GetComponentsInChildren<Button>(true)[0].gameObject.SetActive(false); } } if (others != null) { foreach(var o in others) { o.canDraw = false; } } } } } }<file_sep>using TMPro; using UnityEngine; using DG.Tweening; using System; //Classe représentant l'objet carte dans la main du joueur lors d'une partie public class GameCard : BoardBehaviour { [SerializeField, Range(1f, 2f)] private float scaleUp = 1.5f; [SerializeField, Range(0f, 1f)] private float offsetY = 0.2f; [SerializeField, Range(0f, 1f)] private float offsetZ = 0.2f; [SerializeField] private Transform OverCard = null; public CardBase card = null; [SerializeField] private Transform unitModel = null; [SerializeField] private Transform spellModel = null; [SerializeField] private TMP_Text costText = null; [SerializeField] private TMP_Text nameText = null; [SerializeField] private TMP_Text descriptionText = null; [SerializeField] private TMP_Text RANGEorCACText = null; // [SerializeField] private SpriteRenderer image = null; [SerializeField] private TMP_Text attackText = null; [SerializeField] private TMP_Text healthText = null; public BoardPlayer player { get; set; } private void Update() { if (card != null) { costText.text = card.Cost.ToString(); nameText.text = card.Name; descriptionText.text = card.Description; //image.sprite = card.Image; if (card.GetType().IsAssignableFrom(typeof(UnitCard)) || card.GetType().IsSubclassOf(typeof(UnitCard))) { unitModel.gameObject.SetActive(true); spellModel.gameObject.SetActive(false); RANGEorCACText.text = (((UnitCard) card).Range) ? "Range" : "Melee"; attackText.text = ((UnitCard) card).Attack.ToString(); healthText.text = ((UnitCard) card).Health.ToString(); } else { unitModel.gameObject.SetActive(false); spellModel.gameObject.SetActive(true); RANGEorCACText.text = ""; attackText.text = ""; healthText.text = ""; } } else { unitModel.gameObject.SetActive(false); spellModel.gameObject.SetActive(false); costText.text = ""; nameText.text = ""; descriptionText.text = ""; //image.sprite = null; RANGEorCACText.text = ""; attackText.text = ""; healthText.text = ""; } } //Utilise la carte sur la cellule donnée, et la retire de la main du joueur public bool Use(Cell cell) { ParticleSystem partic = card.particleSystem; if (card.Use(board, cell, manager.PlayerTurn, manager.LocalPlayer)) { PlayEffect(partic, cell); manager.LocalPlayer.UseCard(card); boardManager.Hand.UpdateHand(); boardManager.SubmitManager(); return true; } return false; } //Joue l'effet de particule sur la cellule donnée de la carte private void PlayEffect(ParticleSystem particle, Cell cell){ ParticleSystem particleEff = GameObject.Instantiate(particle); particleEff.transform.parent = boardManager.transform; particleEff.transform.localPosition = board.CellToLocal(cell.position); particleEff.transform.localScale = new Vector3(0.005f,0.005f,0.005f); } //Grossis la carte lorsque l'on passe la souris dessus private void OnMouseEnter() { transform.DOScale(Vector3.one * scaleUp, 0.1f); transform.DOLocalMoveY(offsetY, 0.1f); transform.DOLocalMoveZ(-offsetZ, 0.1f); if(Int16.Parse(costText.text) <= manager.LocalPlayer.CurrentGold) OverCard.gameObject.SetActive(true); DOTween.Play(transform); } //Remet la carte à sa taille normale lorsque la souris quitte celle-ci private void OnMouseExit() { transform.DOScale(Vector3.one,0.2f); transform.DOLocalMoveY(0, 0.1f); transform.DOLocalMoveZ(0, 0.1f); OverCard.gameObject.SetActive(false); DOTween.Play(transform); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using ExitGames.Client.Photon; using Photon.Pun; public class RoomDeckListMenu : MonoBehaviour { [SerializeField] private RoomDeckListing _roomDeckListing = null; [SerializeField] private Transform _content = null; [SerializeField] private DeckListingMenu _deckListingMenu = null; [SerializeField] private GameObject button = null; private Deck selectedDeck = null; private bool display = false; private Dictionary<Deck,RoomDeckListing> ListDecks = new Dictionary<Deck, RoomDeckListing>(); private void Awake() { PhotonPeer.RegisterType(typeof(Deck), (byte) 'D', Deck.Serialize, Deck.Deserialize); } private void Update() { if(gameObject.activeSelf && !display) { DisplayDecks(); display = true; } else if (!gameObject.activeSelf) { display = false; } } private void DisplayDecks() { _deckListingMenu.FetchServer(); foreach (DeckListing deckListing in _deckListingMenu.ListDecks.Values) { Deck deck = deckListing.Deck; RoomDeckListing listing = Instantiate(_roomDeckListing, _content); listing.SetDeckInfo(deck); ListDecks[deck] = listing; ListDecks[deck].SetDeckInfo(deck); if(selectedDeck == null) { selectedDeck = deck; ListDecks[selectedDeck].SetBgColor(new Color(200/255f, 125/255f, 65/255f)); } } } public void SetSelectedDeck(Deck deck) { ListDecks[selectedDeck].SetBgColor(new Color(100/255f, 100/255f, 100/255f)); button.SetActive(true); selectedDeck = deck; ListDecks[selectedDeck].SetBgColor(new Color(65/255f, 200/255f, 65/255f)); } public void on_click_confirm_deck() { if (PhotonNetwork.IsConnectedAndReady) { if (PhotonNetwork.LocalPlayer.ActorNumber == PhotonNetwork.PlayerList[0].ActorNumber) { PlayersExtension.RegisterLocalPlayer(PlayerRole.PlayerOne, selectedDeck); } else { PlayersExtension.RegisterLocalPlayer(PlayerRole.PlayerTwo, selectedDeck); } gameObject.SetActive(false); } } } <file_sep>using Photon.Pun; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class ReadyRPC : MonoBehaviourPun, Photon.Pun.IPunObservable { [SerializeField] private PhotonView readyView = null; [SerializeField] private TMP_Text Text = null; public bool Ready; public void ChangeText(string Text) { readyView.RPC("ChangeText_RPC", RpcTarget.All, Text); } [PunRPC] void ChangeText_RPC(string text) { if (text=="Not Ready") { Text.color = Color.red; } else { Text.color = Color.green; } Text.text = text; Ready = !Ready; } public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { throw new System.NotImplementedException(); } } <file_sep>using System.Collections; using System.Linq; using UnityEngine; using TMPro; //Classe permettant l'utilisation de cartes, et les contraintes qui y sont liés public class UseCard : BoardBehaviour { [SerializeField] private BoardClicker boardClicker = null; [SerializeField] private HoverCell hoverCell = null; // [SerializeField] private float growDuration = 0.2f; // [SerializeField] private float growAmount = 1.5f; [SerializeField] private int cardCost = 0; [SerializeField] private TMP_Text atqText; [SerializeField] private TMP_Text healText; private GameCard card; private void OnEnable() { boardClicker.OnClickCard += OnClickCard; boardClicker.OnClickCell += OnClickCell; boardClicker.OnClickUnit += (c, u) => OnClickCell(c); } private void OnDisable() { boardClicker.OnClickCard -= OnClickCard; boardClicker.OnClickCell -= OnClickCell; boardClicker.OnClickUnit -= (c, u) => OnClickCell(c); } void OnClickCard(GameCard card) { if (manager.MyTurn()) { if (manager.CurrentPlayer.CurrentGold >= card.card.Cost) { this.card = card; this.cardCost = card.card.Cost; hoverCell.HideCells(Color.green); hoverCell.ShowCells(Color.green, board.Cells().Where(cell => CardCast.CanCast(card.card.castMask, board, cell)) ); } } } private void DisplayAtq(int dmg, Unit unit){ atqText.gameObject.SetActive(true); Vector3 pos = board.LocalPosition(unit); pos.z -= 11f; pos.y += 2; pos.x -= 1.5f; atqText.transform.localPosition = pos; if (unit.Health-dmg <=0){ atqText.text = "KO"; } else { atqText.text = "-"+dmg; } StartCoroutine(waitDmg()); } private void DisplayHeal(int dmg, Unit unit){ healText.gameObject.SetActive(true); Vector3 pos = board.LocalPosition(unit); pos.z -= 11f; pos.y += 2; pos.x -= 1.5f; healText.transform.localPosition = pos; healText.text = "+"+dmg; StartCoroutine(waitDmg()); } private IEnumerator waitDmg(){ yield return new WaitForSecondsRealtime(2f); atqText.gameObject.SetActive(false); healText.gameObject.SetActive(false); } private void DisplayDmg(Cell cell){ if (card.card.GetType().IsAssignableFrom(typeof(DamageSpell)) && board.GetUnit(cell) != null ){ DamageSpell ds = (DamageSpell)this.card.card; if (ds.Damage > 0) { DisplayAtq(ds.Damage , board.GetUnit(cell)); } else { int heal = ds.Damage*-1; DisplayHeal(heal , board.GetUnit(cell)); } } } void OnClickCell(Cell cell) { if (this.card != null && manager.MyTurn()) { if (manager.CurrentPlayer.CurrentGold >= this.card.card.Cost) { DisplayDmg(cell); if (card.Use(cell)) { manager.CurrentPlayer.SetCurrentGold(manager.CurrentPlayer.CurrentGold - this.cardCost); this.card = null; this.cardCost = 0; } } } hoverCell.HideCells(Color.green); card = null; } } <file_sep>using System.Collections; using UnityEngine.TestTools; using NUnit.Framework; [TestFixture] public class GameCardTests : MonoBehaviourBaseTest { [UnityTest] public bool GameCardUpdate_Test(){ Board board = new Board(); Cell cell = board.GetCell(1,1); GameCard gc = subject.AddComponent<GameCard>(); CardBase a = gc.card; return true; } } <file_sep>using System.Text; using UnityEngine; using Photon.Pun; using System.Collections.Generic; //Game manager s'occupant de la gestion des tours des joueurs lors d'une partie [System.Serializable] public class GameManager { [System.Serializable] public struct Setup { public Vector2Int boardSize; public Vector3 noiseOffset; public float noiseScale; public GameModes gameMode; } [SerializeField] private Board board; [SerializeField] private List<Player> players; [SerializeField] private int turn; [SerializeField] private int midturn; [SerializeField] private PlayerRole playerTurn; [SerializeField] private Setup setup; [SerializeField] private GameHistory history; public Board Board => board; public Player LocalPlayer => players[PlayersExtension.LocalPlayerIndex()]; public Player RemotePlayer => players[PlayersExtension.RemotePlayerIndex()]; public Player CurrentPlayer => players[(int)playerTurn]; public GameHistory History => history; public PlayerRole PlayerTurn => playerTurn; public int Turn => turn; public GameMode GameMode => setup.gameMode.GameMode(); public GameState GameState => GameMode.CurrentGameState(this); public void ResetBoard() { board = new Board(setup.boardSize); Cell center = board.GetCell(setup.boardSize.x/2, setup.boardSize.y/2); int radius = Mathf.FloorToInt(setup.boardSize.magnitude)/2; foreach(var cell in board.Cells()) { var pos = board.CellToLocal(cell.position) * setup.noiseScale + setup.noiseOffset; if (center.Distance(cell) < radius) { var height = Mathf.PerlinNoise(pos.x, pos.z); if (height < 0.33f) cell.cellType = Cell.CellType.Water; else if (height < 0.66f) cell.cellType = Cell.CellType.Field; else cell.cellType = Cell.CellType.Mountain; } else { cell.cellType = Cell.CellType.None; } } } public GameManager(Setup setup, Deck playerOneDeck, Deck playerTwoDeck) { history = new GameHistory(); this.setup = setup; ResetBoard(); turn = 1; midturn = 0; playerTurn = 0; players = new List<Player> { new Player(playerOneDeck, PlayerRole.PlayerOne), new Player(playerTwoDeck, PlayerRole.PlayerTwo) }; } public int GetScore(PlayerRole player){ return GameMode.GetScore(player, this); } //Indique si c'est le tour du joueur donnée ou non public bool CanPlay(PlayerRole player) { return player == playerTurn; } public void NextTurn() { playerTurn = playerTurn.Other(); } public Player GetPlayer(PlayerRole role) { return players[(int)role]; } public static byte[] Serialize(object manager) { string json = JsonUtility.ToJson(manager); return Encoding.UTF8.GetBytes(json); } public static object Deserialize(byte[] data) { string json = Encoding.UTF8.GetString(data); return JsonUtility.FromJson<GameManager>(json); } public bool MyTurn(){ return playerTurn == PlayersExtension.LocalPlayer(); } //Augmente le compteur de tour, et augmente les Hammercoin quand les deux joueurs ont joués leur tour public void IncreaseTurn(){ if (midturn == 1){ midturn = 0; turn++; IncreaseGold(); } else { midturn = 1; } } //Augmente les Hammercoins maximum de chaque joueur public void IncreaseGold(){ foreach (Player p in players){ p.SetGold(turn); } } //Remet à 0 les Hammercoins des joueurs public void ResetGold(){ foreach (Player p in players){ p.SetCurrentGold(p.Gold); } } }<file_sep>using UnityEngine; using UnityEditor; [CustomEditor(typeof(BoardManager))] public class BoardManagerEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); if (GUILayout.Button("onReset.Invoke()")) ((BoardManager)target).onReset.Invoke(); if (GUILayout.Button("SubmitManager()")) ((BoardManager)target).SubmitManager(); } }<file_sep>using System.Collections.Generic; using UnityEngine; using System.Linq; //Historique permettant de garder une trace des différentes actions des joueurs lors de leur tour //Cela permet par exemple d'empécher une unité d'être déplacée 2 fois dans le même tour [System.Serializable] public class GameAction { [SerializeField] protected PlayerRole player; [SerializeField] protected int turn; public PlayerRole Player => player; public int Turn => turn; public GameAction(PlayerRole player, int turn) { this.player = player; this.turn = turn; } } public class MovementAction : GameAction { [SerializeField] private int unitId; [SerializeField] private Vector2Int[] path; public int UnitId => unitId; public Vector2Int[] Path => path; public Vector2Int Origin => path[0]; public Vector2Int Destination => path[path.Length-1]; public MovementAction(PlayerRole player, int turn, int unitId, params Vector2Int[] path) : base(player, turn) { this.unitId = unitId; this.path = path; } } public class AtqAction : GameAction { [SerializeField] private int unitId; public int UnitId => unitId; public AtqAction(PlayerRole player, int turn, int unitId) : base(player, turn) { this.unitId = unitId; } } public class CardPlayAction : GameAction { [SerializeField] protected Vector2Int[] targetPositions; [SerializeField] protected string cardResourcePath; public Vector2Int[] TargetPositions => targetPositions; public string CardResourcePath => cardResourcePath; public CardBase Card => Resources.Load<CardBase>(cardResourcePath); public CardPlayAction(PlayerRole player, int turn, string cardResourcePath, params Vector2Int[] targetPositions) : base(player, turn) { this.cardResourcePath = cardResourcePath; this.targetPositions = targetPositions; } } public class SpellCastAction : CardPlayAction { public SpellCard SpellCard => Resources.Load<SpellCard>(cardResourcePath); public SpellCastAction(PlayerRole player, int turn, string cardResourcePath, params Vector2Int[] targetPositions) : base(player, turn, cardResourcePath, targetPositions) {} } public class UnitDeployAction : CardPlayAction { public UnitCard UnitCard => Resources.Load<UnitCard>(cardResourcePath); public UnitDeployAction(PlayerRole player, int turn, string cardResourcePath, params Vector2Int[] targetPositions) : base(player, turn, cardResourcePath, targetPositions) {} } [System.Serializable] public class GameHistory { public delegate bool GameHistoryFilter(GameAction action); public delegate bool GameHistoryFilter<T>(T action) where T : GameAction; public delegate int GameHistoryOrdering(GameAction action); public delegate int GameHistoryOrdering<T>(T action) where T : GameAction; private List<GameAction> history; public GameHistory() { history = new List<GameAction>(); } public List<GameAction> Find(GameHistoryFilter filter){ return history.Where(action => filter(action)).ToList(); } public List<GameAction> Find(GameHistoryFilter filter, GameHistoryOrdering ordering, bool reverseOrder = false) { return Find(filter).OrderBy(action => (reverseOrder ? -1 : 1) * ordering(action)).ToList(); } public List<T> Find<T>(GameHistoryFilter<T> filter) where T : GameAction { return history.OfType<T>().Where(action => filter(action)).ToList(); } public List<T> Find<T>(GameHistoryFilter<T> filter, GameHistoryOrdering<T> ordering, bool reverseOrder = false) where T : GameAction { return Find<T>(filter).OrderBy(action => (reverseOrder ? -1 : 1) * ordering(action)).ToList(); } public void Add(GameAction action){ history.Add(action); } } <file_sep># Risks Niveaux de probabilité & d'importance possibles : - Bas : :confused: - Medium : :dizzy_face: - Critique : :rotating_light: ## Écriture d'un risque: Le template: - **Parce que** (optionnel si la raison est évidente): La raison - **Si** : La condition d'apparition du risque - **Alors**: La conséquence ---------------------------------------------------------------- ## Sprint 1 ### Risk #1 **Si** nous n'arrivons pas à faire fonctionner le réseau local **Alors** notre solution finale ne sera pas jouable **Parce que** notre jeu en dépend. Probabilité : :dizzy_face: Importance : :rotating_light: Actions : Se former sur l'utilisation de communication réseau sous Unity (Photon, Mirror). ### Risk #2 **Si** nous n'arrivons pas à bien nous former à Unity **Alors** nous n'avancerons pas suffisament rapidement dans le développement de notre projet **Parce que** notre jeu utilise Unity. Probabilité : :confused: Importance : :rotating_light: Actions : Se former sur l'utilisation de Unity. ---------------------------------------------------------------- ## Sprint 2 ### Risk #1 **Si** nous ne pensons pas assez a l'équilibrage des cartes **Alors** le jeu risquera d'être déséquilibré. Probabilité : :confused: Importance : :confused: Actions : Tester et faire jouer d'autres personnes afin d'estimer quelles cartes sont trop fortes et quelles cartes sont trop faibles. ### Risk #2 **Si** nous ne pensons faisons mal le design de notre interface en jeu **Alors** le jeu risquera d'être peu agréable à jouer. Probabilité : :confused: Importance : :dizzy_face: Actions : Faire jouer d'autres personnes et leur demander des retours. ---------------------------------------------------------------- ## Sprint 3 ### Risk #1 **Si** nous ne mettons pas de nouveau mode de jeu **Alors** le jeu perdra en complexité et diversité. Probabilité : :confused: Importance : :dizzy_face: Actions : Tester et faire jouer d'autres personnes en leur faisant jouer plusieurs parties avec différents mode de jeu et demander des retours. ### Risk #2 **Si** nous ne créons pas plus de cartes avec des effets plus complexes **Alors** le jeu perdra en complexité et diversité. Probabilité : :confused: Importance : :dizzy_face: Actions : Tester et faire jouer d'autres personnes en leur faisant jouer plusieurs parties avec différents decks de cartes et demander des retours. <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System; //Bouton de fin de tour public class EndTurnButton : MonoBehaviour { [SerializeField] private BoardManager BoardManager = null; public void OnMouseDown() { if (BoardManager.Manager.Turn != 1 || !BoardManager.ValidateButton.activeInHierarchy) { BoardManager.NextTurn(); } } } <file_sep>public interface ITakeDamage { void TakeDamage(int amount); int Health { get; } }<file_sep>using System.Linq; using System.Collections.Generic; using UnityEngine; //Objet représentant une cellule composant le plateau (Board) [System.Serializable] public class Cell { public enum CellState { Free, Occupied, Blocked } public enum CellType { Water, Field, Mountain, None } public CellType cellType; public readonly Vector2Int position; public Cell() { this.position = new Vector2Int(); this.cellType = CellType.Field; } public Cell(Vector2Int position, CellType cellType = CellType.Field) { this.position = position; this.cellType = cellType; } public float Height { get { switch (cellType) { case CellType.Water: return 1; case CellType.Field: return 2; case CellType.Mountain: return 3; default: return 0; } }} //Permet d'obtenir la distance entre deux cellules public float Distance(Cell other) { return Mathf.Abs(position.x - other.position.x) + Mathf.Abs(position.y - other.position.y) + Mathf.Abs(position.x + position.y - other.position.x - other.position.y); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using TMPro; public class DeckCardList : MonoBehaviour { [SerializeField] private CollectionCard cardPrefab = null; [SerializeField] private TMP_Text UnitCountText = null; [SerializeField] private TMP_Text SpellCountText = null; [SerializeField] private TMP_Text saveMessage = null; [SerializeField] private TMP_Text DeckName = null; public CollectionCard[] CardUnit { get; private set; } public CollectionCard[] CardSpell { get; private set; } private Deck currentDeck = null; private int MAX = 10; private float spacing = 210f; private int unitCount = 0; private int spellCount = 0; private Vector3 size = new Vector3(1700,1700,1700); void Start() { CardUnit = new CollectionCard[MAX]; CardSpell = new CollectionCard[MAX]; for (int i = 0; i < CardUnit.Length; i++) { GameObject cardObject = Instantiate(cardPrefab.gameObject, transform); CardUnit[i] = cardObject.GetComponent<CollectionCard>(); cardObject.SetActive(false); } for (int i = 0; i < CardSpell.Length; i++) { GameObject cardObject = Instantiate(cardPrefab.gameObject, transform); CardSpell[i] = cardObject.GetComponent<CollectionCard>(); cardObject.SetActive(false); } } void Reset(){ foreach(CollectionCard card in CardUnit){ Destroy(card.gameObject); } foreach(CollectionCard card in CardSpell){ Destroy(card.gameObject); } currentDeck = null; } bool IsNotTriplicate(CardBase cb){ int cpt = 0; if ( (cb.GetType().IsAssignableFrom(typeof(UnitCard)) || cb.GetType().IsSubclassOf(typeof(UnitCard)) )){ for (int i = 0; i < currentDeck.units.Count(); i++){ if (currentDeck.units[i].Name == cb.Name){cpt++;} } } else if (!cb.GetType().IsAssignableFrom(typeof(UnitCard))){ for (int i = 0; i < currentDeck.spells.Count(); i++){ if (currentDeck.spells[i].Name == cb.Name){cpt++;} } } if (cpt < 2){ return true; } saveMessage.gameObject.SetActive(true); saveMessage.color = new Color(250/255f, 34/255f, 48/255f, 1); saveMessage.text = "Two copies of the same card maximum!"; return false; } bool IsValidDeck(){ if(currentDeck.spells.Count() == MAX && currentDeck.units.Count() == MAX){ return true; } else { saveMessage.gameObject.SetActive(true); saveMessage.color = new Color(250/255f, 34/255f, 48/255f, 1); saveMessage.text = "Your deck must have 10 units & spells to be saved!"; return false; } } void TextUpdate(){ saveMessage.gameObject.SetActive(false); } public void Save(){ TextUpdate(); if (IsValidDeck()){ DeckListingMenu dlm = Object.FindObjectOfType<DeckListingMenu>(); dlm.setDeck(currentDeck); saveMessage.gameObject.SetActive(true); saveMessage.color = new Color(27/255f, 140/255f, 30/255f, 1); saveMessage.text = "Deck saved!"; AccessDatabase.SaveDeck(PlayerPrefs.GetString("username"), currentDeck); } } public void Delete() { TextUpdate(); DeckListingMenu dlm = Object.FindObjectOfType<DeckListingMenu>(); if (currentDeck != null && dlm.ListDecks.Count > 1) { saveMessage.gameObject.SetActive(true); saveMessage.color = new Color(27/255f, 140/255f, 30/255f, 1); saveMessage.text = "Deck deleted"; AccessDatabase.DeleteDeck(PlayerPrefs.GetString("username"), currentDeck); dlm.RemoveDeck(currentDeck); currentDeck = null; UnitCountText.text = ""; SpellCountText.text = ""; DeckName.text = ""; Reset(); Start(); } else { saveMessage.gameObject.SetActive(true); saveMessage.color = new Color(250/255f, 34/255f, 48/255f, 1); if (currentDeck == null) { saveMessage.text = "No deck selected."; } else { saveMessage.text = "You must have at least one deck."; } } } public void AddCard(CardBase cb){ TextUpdate(); if (currentDeck != null){ if ( (cb.GetType().IsAssignableFrom(typeof(UnitCard)) || cb.GetType().IsSubclassOf(typeof(UnitCard)) ) && currentDeck.units.Count() < MAX && IsNotTriplicate(cb)){ for (int i = 0; i < CardUnit.Count(); i++){ if(CardUnit[i].gameObject.activeSelf == false){ CardUnit[i].card = cb; CardUnit[i].gameObject.SetActive(true); CardUnit[i].transform.localScale = size; currentDeck.AddCard(cb); unitCount++; break; } } } else if (!cb.GetType().IsAssignableFrom(typeof(UnitCard)) && currentDeck.spells.Count() < MAX && IsNotTriplicate(cb)){ for (int i = 0; i < CardSpell.Count(); i++){ if(CardSpell[i].gameObject.activeSelf == false){ CardSpell[i].card = cb; CardSpell[i].gameObject.SetActive(true); currentDeck.AddCard(cb); spellCount++; break; } } } } DisplayCount(); } public void DeleteCard(CollectionCard cc){ TextUpdate(); currentDeck.RemoveCard(cc.card); cc.gameObject.SetActive(false); cc.transform.localScale = size; cc.transform.localPosition += new Vector3(0,0,30) ; if (cc.card.GetType().IsAssignableFrom(typeof(UnitCard)) || cc.card.GetType().IsSubclassOf(typeof(UnitCard))){ unitCount--; } else {spellCount--;} DisplayCount(); } void DisplayCount(){ UnitCountText.text = unitCount+"/"+MAX; SpellCountText.text = spellCount+"/"+MAX; } public void LoadDeck(Deck deck){ Reset(); Start(); DeckName.text = deck.Name; currentDeck = deck; List<UnitCard> lu = deck.units; List<SpellCard> ls = deck.spells; unitCount = lu.Count(); spellCount = ls.Count(); DisplayCount(); for (int i = 0; i<MAX; i++){ if (lu.Count > i){ CardUnit[i].card = lu[i]; CardUnit[i].gameObject.SetActive(true); } Vector3 pos = CardUnit[i].transform.localPosition; Vector3 scale = size; CardUnit[i].transform.localScale = scale; if (i > 4){ pos.x = (-375)+((i-5) * spacing); pos.z = -20; pos.y = 115; } else { pos.x = (-490)+(i * spacing); pos.z = -10; pos.y = 265; } CardUnit[i].transform.localPosition = pos; } for (int i = 0; i<MAX; i++){ if (ls.Count > i){ CardSpell[i].card = ls[i]; CardSpell[i].gameObject.SetActive(true); } Vector3 pos = CardSpell[i].transform.localPosition; Vector3 scale = size; CardSpell[i].transform.localScale = scale; if (i > 4){ pos.x = (-375)+((i-5) * spacing); pos.z = -20; pos.y = -295; } else { pos.x = (-490)+(i * spacing); pos.z = -10; pos.y = -145; } CardSpell[i].transform.localPosition = pos; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //Classe gérant le clique du joueur sur le plateau afin de récupéré la cellule ou l'unité cliqué [RequireComponent(typeof(Collider))] public class BoardClicker : BoardBehaviour { [SerializeField] private Camera Camera = null; public delegate void OnClickCardAction(GameCard card); public delegate void OnClickCellAction(Cell cell); public delegate void OnClickUnitAction(Cell cell, Unit unit); public event OnClickCardAction OnHoverCard; public event OnClickCardAction OnClickCard; public event OnClickCellAction OnHoverCell; public event OnClickCellAction OnClickCell; public event OnClickUnitAction OnHoverUnit; public event OnClickUnitAction OnClickUnit; void Update() { if (Raycast(out var hit)) { if (HoverCard(hit, out var card)) { if (Input.GetMouseButtonDown(0)) OnClickCard?.Invoke(card); else OnHoverCard?.Invoke(card); } else if (HoverCell(hit, out var cell)) { Unit unit = board.GetUnit(cell); if (unit != null && !unit.Dead) { if (Input.GetMouseButtonDown(0)) OnClickUnit?.Invoke(cell, unit); else OnHoverUnit?.Invoke(cell, unit); } else { if (Input.GetMouseButtonDown(0)) OnClickCell?.Invoke(cell); else OnHoverCell?.Invoke(cell); } } } } private bool HoverCell(RaycastHit hit, out Cell cell) { if (hit.transform == boardManager.transform) { Vector2Int cellPos = board.LocalToCell(transform.InverseTransformPoint(hit.point)); if (board.HasCell(cellPos)) { cell = board.GetCell(cellPos); if (cell != null && cell.cellType != Cell.CellType.None) return true; } } cell = null; return false; } private bool HoverCard(RaycastHit hit, out GameCard card) { card = hit.transform.GetComponent<GameCard>(); return card != null; } private bool Raycast(out RaycastHit hit) { Ray ray = Camera.ScreenPointToRay(Input.mousePosition); return Physics.Raycast(ray, out hit); } }<file_sep>using UnityEngine; [CreateAssetMenu(menuName="Cards/Spells/Buff")] public class BuffSpell : SpellCard { [SerializeField] private int atq = 0; [SerializeField] private int movement = 0; [SerializeField] private int range = 0; //Carte de sort augmentant certaines statistiques de sa cible protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { Unit unit = board.GetUnit(target); if (unit != null){ if (unit.Card.ResourcePath.Contains("Specials/")) return false; unit.attack = unit.attack + atq; unit.movement = unit.movement + movement; unit.rangeAtq = unit.rangeAtq + range; return true; } return false; } }<file_sep>using System.Collections.Generic; using UnityEngine; using System.Linq; [CreateAssetMenu(menuName="Cards/Units/Eater")] public class EaterCard : UnitCard { [SerializeField] protected int killRange; //Carte d'unité qui détruit les unités alliés proche lors du déploiement pour prendre leurs statistiques de vie et d'attaque protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { base.CardEffect(board, target, player, objPlayer); Unit spawned = board.GetUnit(target); int cptAtq = 0; int cptHp = 0; List<Cell> cells = board.Disc(target, killRange).ToList(); var mask = CastMask.AnyTerrain | CastMask.AnyPosition | CastMask.AnyCellOwner; mask &= ~CastMask.SpecialCells; foreach (Cell cell in cells){ Unit currentUnit = board.GetUnit(cell); if (currentUnit != null && currentUnit != spawned && currentUnit.Player == player && !currentUnit.Card.ResourcePath.Contains("Specials/")){ cptAtq += currentUnit.Attack; cptHp += currentUnit.Health; currentUnit.TakeDamage(999); } } Debug.Log(cptAtq); spawned.attack += cptAtq; spawned.TakeDamage(-cptHp); return true; } }<file_sep>using UnityEngine; using System.Collections.Generic; using System.Linq; [CreateAssetMenu(menuName="Cards/Spells/Terrain")] public class ChangeTerrainSpell : SpellCard { [SerializeField] private Cell.CellType terrain = Cell.CellType.None; [SerializeField] private int range = 0; //Carte de sort modifiant une ou plusieurs cellule du terrain de jeu protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { List<Cell> cells = board.Disc(target, range).ToList(); foreach(Cell cell in cells){ if(board.GetUnit(cell) == null) cell.cellType = terrain; } return true; } }<file_sep>using UnityEngine; [CreateAssetMenu(menuName="Cards/Spells/Unspawn Unit")] public class UnspawnUnitSpell : SpellCard { [SerializeField] private bool destroyUnit = true; [SerializeField] private int amount = 1; protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { Unit unit = board.GetUnit(target); if (unit != null && !unit.Card.ResourcePath.Contains("Specials/")) { if (destroyUnit) { unit.TakeDamage(unit.Health); } for(int i=0; i<amount; i++) { objPlayer.addCard(unit.Card); } return true; } return false; } }<file_sep>using Photon.Pun; using Photon.Realtime; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; public class CurrentRoom : MonoBehaviourPunCallbacks { [SerializeField] private TMP_Text _OtherPlayer = null; [SerializeField] private TMP_Text Text_Timer = null; private Coroutine _timer=null; private Coroutine _dots = null; [SerializeField] private RawImage StrangeNebula = null; [SerializeField] private TMP_Text ThreeDots = null; [SerializeField] private GameObject ChooseDeck = null; //[SerializeField] //private GameObject Waiting = null; public override void OnEnable() { base.OnEnable(); _dots = StartCoroutine(Dots()); if (PhotonNetwork.CurrentRoom.PlayerCount == 2) { foreach (KeyValuePair<int, Photon.Realtime.Player> player in PhotonNetwork.CurrentRoom.Players) { if(player.Value.NickName != PhotonNetwork.NickName) _OtherPlayer.text = ""; ThreeDots.gameObject.SetActive(false); } } } public override void OnPlayerEnteredRoom(Photon.Realtime.Player newPlayer) { foreach (KeyValuePair<int, Photon.Realtime.Player> player in PhotonNetwork.CurrentRoom.Players) { if (player.Value.NickName != PhotonNetwork.NickName) _OtherPlayer.text = ""; ThreeDots.gameObject.SetActive(false); } } public override void OnPlayerLeftRoom(Photon.Realtime.Player otherPlayer) { _OtherPlayer.text = "Waiting for player"; ThreeDots.gameObject.SetActive(true); } public void FixedUpdate() { if (PhotonNetwork.CurrentRoom.PlayerCount >= 2 && _timer==null) { Text_Timer.gameObject.SetActive(true); _timer = StartCoroutine(Timer()); ChooseDeck.SetActive(true); StrangeNebula.gameObject.SetActive(false); } if (PhotonNetwork.CurrentRoom.PlayerCount < 2 && _timer != null) { StopCoroutine(_timer); _timer = null; Text_Timer.text = "5"; Text_Timer.gameObject.SetActive(false); ChooseDeck.SetActive(false); StrangeNebula.gameObject.SetActive(true); } StrangeNebula.transform.Rotate(new Vector3(0, 0, -2)); } private IEnumerator Timer() { for(int i=10; i >= 0; i--) { Text_Timer.text = i.ToString(); yield return new WaitForSecondsRealtime(1f); } PhotonNetwork.LoadLevel("GameScene"); } private IEnumerator Dots() { while (true) { if(ThreeDots.text.Equals("...")) { ThreeDots.text = ""; } else { ThreeDots.text = ThreeDots.text + "."; } yield return new WaitForSecondsRealtime(0.7f); } } } <file_sep>using UnityEngine; using UnityEditor; public class UpdateCardResourcePath { [MenuItem("Tools/Update cards")] private static void UpdateCards() { foreach(var card in Resources.LoadAll<CardBase>("")) { string path = AssetDatabase.GetAssetPath(card); path = path.Replace("Assets/Resources/", ""); path = path.Replace(".asset", ""); card.resourcePath = path; EditorUtility.SetDirty(card); } } }<file_sep>using System.Linq; using UnityEngine; //Mode de jeu Point public class Point : GameMode { [SerializeField] private int p1 = 0; [SerializeField] private int p2 = 0; [SerializeField] private int ScoreToWin = 3; public override GameState CurrentGameState(GameManager gameManager) { countDeath(gameManager); if (p1 >= ScoreToWin) { return GameState.WinPlayerTwo; } else if (p2 >= ScoreToWin) { return GameState.WinPlayerOne; } else return GameState.NotFinished; } public override int GetScore(PlayerRole player, GameManager gameManager){ countDeath(gameManager); if (player==PlayerRole.PlayerOne){ return p2; } if (player == PlayerRole.PlayerTwo){ return p1; } return ScoreToWin; } private void countDeath(GameManager gameManager){ p1 = gameManager.Board.AllUnits.Where(u=>u.Dead && u.Player == PlayerRole.PlayerOne).Select(u => u.Cost).Sum(); p2 = gameManager.Board.AllUnits.Where(u=>u.Dead && u.Player == PlayerRole.PlayerTwo).Select(u => u.Cost).Sum(); } } <file_sep>using UnityEngine; public class BoardBehaviour : MonoBehaviour { public BoardManager boardManager {get; private set; } public Board board => boardManager?.board; public GameManager manager => boardManager?.Manager; protected virtual void Awake() { boardManager = FindObjectOfType<BoardManager>(); } public virtual void OnResetBoard(BoardManager boardManager) { this.boardManager = boardManager; } }<file_sep>public enum GameState { NotFinished = 0, Draw = 1, WinPlayerOne = 2, WinPlayerTwo = 4, Finished = WinPlayerOne | WinPlayerTwo | Draw } //Classe gérant les modes de jeu, permettant de définir quel joueur gagne et quel joueur perd la partie public static class GameStateExtension { public static bool Finished(this GameState state) { return (int)(state & GameState.Finished) != 0; } public static PlayerRole Winner(this GameState state) { if ((state & GameState.WinPlayerOne) != 0) return PlayerRole.PlayerOne; else if ((state & GameState.WinPlayerTwo) != 0) return PlayerRole.PlayerTwo; else return PlayerRole.Spectator; } } [System.Serializable] public enum GameModes { // KillToWin, Point, DestroyTheBase } public static class GameModesExtension { public static GameMode GameMode(this GameModes mode) { switch(mode) { // case GameModes.KillToWin: return new KillToWin(); case GameModes.Point: return new Point(); case GameModes.DestroyTheBase: return new DestroyTheBase(); default: return null; } } } [System.Serializable] public abstract class GameMode { public abstract GameState CurrentGameState(GameManager gameManager); public abstract int GetScore(PlayerRole player, GameManager gameManager); }<file_sep>## Hammercraft Version 0.0.2 ## Author : <NAME>, <NAME>, <NAME>, <NAME> ## Getting started To install the project on your machine just download the .zip for your OS on the release page. Just unzip it on a fresh folder and you're good to go. ## The game Hammercraft is a game that mix together both cards and board games where players can use cards to summon units on the board or play spell cards to interact with the units on the boards. ## The project This project is being made for a school project "projet innovation" at the Polytech Nice-Sophia Engineer School. ## Thanks Thanks to <NAME>, <NAME>, <NAME> for organising this project. And finally, thanks to <NAME> our sponsor who helped us throughout the duration of the project. <file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; using TMPro; using System.Collections; //Classe s'occupant du déplacement et de l'attaque des unités sur le plateau public class MoveUnit : BoardBehaviour { [SerializeField] private BoardClicker boardClicker = null; [SerializeField] private HoverCell hoverCell = null; [SerializeField] private Color color = Color.white; [SerializeField] private Color pathColor = Color.white; [SerializeField] private TMP_Text infoUnits = null; [SerializeField] private TMP_Text atqText; [SerializeField] private TMP_Text counterText; private Cell origin; private Unit unit; private Unit infoUnit; private Cell hover; private void Update() { if(unit != null){ if (unit.Health <= 0){ Deselect(); } } if(infoUnit != null){ SetInfo(); } } private void SetInfo(){ string move; string atq; if(infoUnit.Health <= 0){infoUnits.gameObject.SetActive(false);} else {infoUnits.gameObject.SetActive(true);} if (CanMove(infoUnit)){move = "Can move";} else { move = "Movement used";} if (CanAtq(infoUnit)){atq = "Can attack";} else { atq = "Attack used";} if (infoUnit.Player == PlayersExtension.LocalPlayer()){infoUnits.color = Color.cyan;} else {infoUnits.color = Color.red;} if (infoUnit.Card.ResourcePath.Contains("Specials/")){ infoUnits.text = infoUnit.Card.Name+"\nHP: "+infoUnit.Health; } else { infoUnits.text = infoUnit.Card.Name+"\nHP: "+infoUnit.Health+"\nATQ: "+infoUnit.Attack+"\n"+move+"\n"+atq; } } private bool CanMove(Unit unit) { return manager.History.Find<MovementAction>(action => { return action.Turn == manager.Turn && action.UnitId == unit.Id; }).Count == 0; } private bool CanAtq(Unit unit) { return manager.History.Find<AtqAction>(action => { return action.Turn == manager.Turn && action.UnitId == unit.Id; }).Count == 0; } private void OnEnable() { boardClicker.OnHoverUnit += OnInfoUnit; boardClicker.OnClickUnit += OnSelectUnit; boardClicker.OnClickCell += OnSelectCell; boardClicker.OnHoverCell += OnHoverCell; boardClicker.OnClickCard += _ => Deselect(); } private void OnDisable() { boardClicker.OnHoverUnit -= OnInfoUnit; boardClicker.OnClickUnit -= OnSelectUnit; boardClicker.OnClickCell -= OnSelectCell; boardClicker.OnHoverCell -= OnHoverCell; boardClicker.OnClickCard -= _ => Deselect(); } private void OnInfoUnit(Cell HovCell, Unit unit) { this.infoUnit = unit; } private void DisplayAtq(int dmg, Unit unit){ atqText.gameObject.SetActive(true); Vector3 pos = board.LocalPosition(unit); pos.z -= 11f; pos.y += 2; pos.x -= 1.5f; atqText.transform.localPosition = pos; if (unit.Health <=0){ atqText.text = "KO"; } else { atqText.text = "-"+dmg; } StartCoroutine(waitDmg()); } private void DisplayCounterAtq(int dmg, Unit unit){ counterText.gameObject.SetActive(true); Vector3 pos = board.LocalPosition(unit); pos.z -= 11f; pos.y += 2; pos.x -= 1.5f; counterText.transform.localPosition = pos; if (unit.Health <=0){ counterText.text = "KO"; } else { counterText.text = "-"+dmg; } StartCoroutine(waitDmg()); } private IEnumerator waitDmg(){ yield return new WaitForSecondsRealtime(2f); counterText.gameObject.SetActive(false); atqText.gameObject.SetActive(false); } void OnSelectUnit(Cell cell, Unit unit) { if (this.unit != null && cell.Distance(origin) <= this.unit.RangeAtq && this.unit != unit && CanAtq(this.unit)){ this.unit.DealDamage(unit); DisplayAtq(this.unit.Attack, unit); if (unit.RangeAtq>=cell.Distance(origin)){ unit.DealDamage(this.unit); DisplayCounterAtq(unit.Attack, this.unit); } manager.History.Add(new AtqAction(manager.CurrentPlayer.Role, manager.Turn, this.unit.Id)); Deselect(); } else if(!unit.Dead && manager.MyTurn() && unit.Player == manager.PlayerTurn) { this.unit = unit; this.origin = cell; if ((unit.MovementMask & UnitMoveMask.FlyBy) != 0){ hoverCell.ShowCells(color, UnitMovement.AvailableCells(unit.MovementMask, board, cell, unit.Movement+1)); } else { hoverCell.ShowCells(color, UnitMovement.AvailableCells(unit.MovementMask, board, cell, unit.Movement)); } hoverCell.ShowCells(Color.yellow, UnitMovement.AvailableCells(unit.AtqMask, board, cell, (unit.RangeAtq)/2)); } } private void OnSelectCell(Cell cell) { if (origin != null && unit != null && cell.position != unit.position) { if (UnitMovement.CanMove(unit.MovementMask, board, origin, cell, unit.Movement, out var path) && CanMove(unit)) { unit.position = cell.position; manager.History.Add(new MovementAction(manager.CurrentPlayer.Role, manager.Turn, unit.Id, path.Select(c => c.position).ToArray())); boardManager.SubmitManager(); Deselect(); } else { Deselect(); } } } private void OnHoverCell(Cell cell) { if (hover != cell) { hover = cell; hoverCell.HideCells(pathColor); if (unit == null || origin == null) return; if (UnitMovement.CanMove(unit.MovementMask, board, origin, cell, unit.Movement, out var path)) { hoverCell.ShowCells(pathColor, path); } } } private void Deselect() { unit = null; origin = null; hoverCell.HideCells(Color.yellow); hoverCell.HideCells(pathColor); hoverCell.HideCells(color); } } <file_sep>using ExitGames.Client.Photon; using UnityEngine; using Photon.Pun; using UnityEngine.Events; using System; //Classe représentant une unité sur le plateau de jeu [System.Serializable] public class Unit : ITakeDamage, IDealDamage { [SerializeField] private string cardResourcePath; [SerializeField] private int id; [SerializeField] private bool dead; [SerializeField] private int health; [SerializeField] public int attack; [SerializeField] public int movement; [SerializeField] public int cost; [SerializeField] private UnitMoveMask movementMask; [SerializeField] private UnitMoveMask atqMask; [SerializeField] private PlayerRole player; [SerializeField] public int rangeAtq; private UnitCard card; public Vector2Int position; public UnitCard Card { get { if (!card) { card = Resources.Load<UnitCard>(cardResourcePath); } return card; }} public int Id => id; public int Cost => cost; public bool Dead => dead; public int Health => health; public int Attack => attack; public int Movement => movement; public UnitMoveMask MovementMask => movementMask; public UnitMoveMask AtqMask => atqMask; public PlayerRole Player => player; public int RangeAtq => rangeAtq; private BoardUnit boardUnit; /* This should never be used directly when using networking */ public Unit(UnitCard card, Vector2Int position, int id, PlayerRole owner) { this.cardResourcePath = card.ResourcePath; this.health = card.Health; this.attack = card.Attack; this.movement = card.Movement; this.cost = card.Cost; this.position = position; this.dead = false; this.player = owner; this.id = id; this.rangeAtq = (card.Range) ? 6 : 2; this.movementMask = card.MovementMask; this.atqMask = card.AtqMask; } public void TakeDamage(int amount) { health = Mathf.Max(0, health - amount); if (health <= 0) { Die(); } } public void DealDamage(ITakeDamage target) { target.TakeDamage(attack); } private void Die() { dead = true; } }<file_sep>using UnityEngine; using System; using System.Net.Http; public static class AccessDatabase { const string protocol = "http"; const string host = "games.strange-nebula.com"; const string port = "3000"; private class RemoteDeckList { public string[] decks = null; } private class RemoteDeck { public string owner; public string name; public string[] units; public string[] spells; } public static string[] GetDecksOf(string user) { HttpClient client = new HttpClient(); var url = GetUrl($"/u/{user}"); var res = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result; var list = JsonUtility.FromJson<RemoteDeckList>(res); return list.decks; } public static Deck GetDeck(string user, string name) { HttpClient client = new HttpClient(); var url = GetUrl($"/u/{user}/{name}"); var res = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result; var deck = JsonUtility.FromJson<RemoteDeck>(res); return new Deck(deck.name, deck.units, deck.spells); } public static void SaveDeck(string user, Deck deck) { HttpClient client = new HttpClient(); var url = GetUrl($"/u/{user}/{deck.Name}"); var remoteDeck = new RemoteDeck() { owner = user, name = deck.Name, units = deck.SerializedUnits.ToArray(), spells = deck.SerializedSpells.ToArray() }; var json = JsonUtility.ToJson(remoteDeck); var content = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(json)); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var res = client.PostAsync(url, content).Result; } public static void DeleteDeck(string user, Deck deck) { HttpClient client = new HttpClient(); var url = GetUrl($"/u/{user}/{deck.Name}"); var res = client.DeleteAsync(url); } private static Uri GetUrl(string path) { return new Uri($"{protocol}://{host}:{port}{path}"); } }<file_sep>using UnityEngine; using NUnit.Framework; public class GameManagerTest { [Test] public void Serialize() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); byte[] serialized = GameManager.Serialize(manager); //Debug.Log(System.Text.Encoding.UTF8.GetString(serialized)); //Assert.That(manager, Is.EqualTo(GameManager.Deserialize(serialized))); } [Test] public void CanPlay() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); byte[] serialized = GameManager.Serialize(manager); Assert.True(manager.CanPlay(0)); } [Test] public void CantPlay() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); byte[] serialized = GameManager.Serialize(manager); Assert.False(manager.CanPlay((PlayerRole)1)); } [Test] public void NextTurn() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); byte[] serialized = GameManager.Serialize(manager); manager.NextTurn(); Assert.False(manager.CanPlay(0)); } [Test] public void GetPlayer() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( "coucou", new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); byte[] serialized = GameManager.Serialize(manager); Player p = new Player(deck, 0); Assert.That(manager.GetPlayer(0).Deck.Name, Is.EqualTo(p.Deck.Name)); } [Test] public void MyTurn() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( "coucou", new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); byte[] serialized = GameManager.Serialize(manager); Assert.That(manager.MyTurn()); } [Test] public void IncreaseTurn() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( "coucou", new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); manager.IncreaseTurn(); Assert.That(manager.GetPlayer(0).Gold == 1); } [Test] public void IncreaseGold() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( "coucou", new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); manager.IncreaseTurn(); manager.IncreaseTurn(); manager.IncreaseGold(); Assert.That(manager.GetPlayer(0).Gold > 1); } [Test] public void CurrentGold() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( "coucou", new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); manager.IncreaseTurn(); manager.IncreaseTurn(); manager.IncreaseGold(); manager.GetPlayer(0).SetCurrentGold(1); Assert.That(manager.GetPlayer(0).CurrentGold == 1); } [Test] public void ResetGold() { GameManager.Setup setup = new GameManager.Setup(); setup.boardSize = new Vector2Int(10,10); setup.gameMode = GameModes.Point; Deck deck = new Deck( "coucou", new UnitCard[] { UnitCard.CreateInstance<UnitCard>(), UnitCard.CreateInstance<UnitCard>() }, new SpellCard[] { SpellCard.CreateInstance<DamageSpell>(), SpellCard.CreateInstance<DamageSpell>() } ); GameManager manager = new GameManager(setup, deck, deck); manager.IncreaseTurn(); manager.IncreaseTurn(); manager.IncreaseGold(); manager.GetPlayer(0).SetCurrentGold(1); manager.ResetGold(); Assert.That(manager.GetPlayer(0).CurrentGold > 1); } }<file_sep>using System.Linq; using UnityEngine; //Masque de déploiement permettant de définir des règles de déploiement complexes [System.Serializable, System.Flags] public enum CastMask { EmptyCell = 1 << 0, OnUnit = 1 << 1, NearUnit = 1 << 2, OnWater = 1 << 3, OnField = 1 << 4, OnMountain = 1 << 5, NormalCells = 1 << 6, SpecialCells = 1 << 7, AllyCells = 1 << 8, EnnemyCells = 1 << 9, NeutralCells = 1 << 10, AnyPosition = EmptyCell | OnUnit | NearUnit, AnyTerrain = OnWater | OnField | OnMountain, AnyCellOwner = AllyCells | EnnemyCells | NeutralCells, } public static class CardCast { public static bool CanCast(CastMask value, Board board, Cell target) { return TestTerrainCondition(value, board, target) && TestOwnerCondition(value, board, target) && TestUnitCondition(value, board, target); } private static bool TestUnitCondition(CastMask value, Board board, Cell target) { var unit = board.GetUnit(target); return value == CastMask.AnyPosition || Check(value, CastMask.EmptyCell) && (unit == null || unit.Dead) || Check(value, CastMask.OnUnit) && unit != null && !unit.Dead || Check(value, CastMask.NearUnit) && board.Neighbors(target).Any(cell => board.GetUnit(cell) != null && board.GetUnit(cell).Dead == false); } private static bool TestTerrainCondition(CastMask value, Board board, Cell target) { return value == CastMask.AnyTerrain || Check(value, CastMask.OnWater) && target.cellType == Cell.CellType.Water || Check(value, CastMask.OnField) && target.cellType == Cell.CellType.Field || Check(value, CastMask.OnMountain) && target.cellType == Cell.CellType.Mountain; } private static bool TestOwnerCondition(CastMask value, Board board, Cell target) { return value == CastMask.AnyCellOwner || Check(value, CastMask.NeutralCells) || Check(value, CastMask.AllyCells) || Check(value, CastMask.EnnemyCells); } private static bool Check(CastMask value, CastMask mask) { return (value & mask) != 0; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using NUnit.Framework; using System.Linq; public class BoardTest { [Test] public void BoardCreation_Test() { Board board = new Board(); Assert.That(board.size, Is.EqualTo(new Vector2Int(50,50))); } [Test] public void BoardCreationParam1_Test() { Board board = new Board(new Vector2Int(20,20)); Assert.That(board.size, Is.EqualTo(new Vector2Int(20,20))); } [Test] public void BoardCreationParam2_Test() { Board board = new Board(10,10); Assert.That(board.size, Is.EqualTo(new Vector2Int(10,10))); } [Test] public void HasCell1True_Test() { Board board = new Board(10,10); Assert.True(board.HasCell(new Vector2Int(1,1))); } [Test] public void HasCell1False_Test() { Board board = new Board(10,10); Assert.False(board.HasCell(new Vector2Int(11,13))); } [Test] public void HasCell2True_Test() { Board board = new Board(10,10); Assert.True(board.HasCell(1,1)); } [Test] public void HasCell2False_Test() { Board board = new Board(10,10); Assert.False(board.HasCell(11,13)); } [Test] public void GetCell1_Test() { Board board = new Board(10,10); Assert.True((board.GetCell(1,1)).GetType() == typeof(Cell)); } [Test] public void GetCell2_Test() { Board board = new Board(10,10); Assert.True((board.GetCell(new Vector2Int(2,2))).GetType() == typeof(Cell)); } [Test] public void CellToLocal1_Test() { Board board = new Board(10,10); Vector3 v = new Vector3 (0,2,0); Assert.That(board.CellToLocal(new Vector2Int(5,5)), Is.EqualTo(v)); } [Test] public void CellToLocal2_Test() { Board board = new Board(10,10); Vector3 v = new Vector3 (0,2,0); Assert.That(board.CellToLocal(5,5), Is.EqualTo(v)); } [Test] public void LocalToCell_Test() { Board board = new Board(10,10); Vector2Int v = new Vector2Int (5,5); Vector3 vEx = new Vector3 (0,2,0); Assert.That(board.LocalToCell(vEx), Is.EqualTo(v)); } [Test] public void AddUnitCard_Test() { Board board = new Board(10,10); Vector3 v = new Vector3 (0,2,0); UnitCard c1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); Cell cell = board.GetCell(new Vector2Int(2,2)); Unit u = new Unit(c1, cell.position, 1, 0); board.AddUnit(c1, cell, 0); Assert.That(board.Units[0].Card, Is.EqualTo(u.Card)); } [Test] public void AddUnitPosition_Test() { Board board = new Board(10,10); Vector3 v = new Vector3 (0,2,0); UnitCard c1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); Cell cell = board.GetCell(new Vector2Int(2,2)); Unit u = new Unit(c1, cell.position, 1, 0); board.AddUnit(c1, cell, 0); Assert.That(board.Units[0].position, Is.EqualTo(cell.position)); } } <file_sep>using UnityEngine; [CreateAssetMenu(menuName="Cards/Spells/Damage")] public class DamageSpell : SpellCard { [SerializeField] private int damage = 0; [SerializeField] private bool canHitSpecials = true; public int Damage => damage; public bool CanHitSpecials => canHitSpecials; //Carte de sort réduisant les points de vie de l'unité ciblée protected override bool CardEffect(Board board, Cell target, PlayerRole player, Player objPlayer) { Unit unit = board.GetUnit(target); if (unit != null && (!unit.Card.ResourcePath.Contains("Specials/") || unit.Card.ResourcePath.Contains("Specials/") && CanHitSpecials)) { unit.TakeDamage(damage); return true; } return false; } }<file_sep>using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class DeckListing : MonoBehaviour, IPointerDownHandler { [SerializeField] private TMP_Text _name = null; [SerializeField] private Image image = null; public Deck Deck {get; set;} public void SetDeckInfo(Deck deck) { Deck = deck; _name.text = deck.Name; } public void OnPointerDown(PointerEventData eventData) { DeckCardList dc = Object.FindObjectOfType<DeckCardList>(); dc.LoadDeck(Deck); DeckListingMenu dlm = Object.FindObjectOfType<DeckListingMenu>(); dlm.ClickDeck(Deck); } public void SetBgColor(Color color) { image.color = color; } } <file_sep>using System.Linq; using UnityEngine; //Mode de jeu DestroyTheBase public class DestroyTheBase : GameMode { public override GameState CurrentGameState(GameManager gameManager) { Unit b1 = GetBase(PlayerRole.PlayerOne, gameManager); Unit b2 = GetBase(PlayerRole.PlayerTwo, gameManager); if (b1 == null) { AddBase(PlayerRole.PlayerOne, gameManager); b1 = GetBase(PlayerRole.PlayerOne, gameManager); } if (b2 == null) { AddBase(PlayerRole.PlayerTwo, gameManager); b2 = GetBase(PlayerRole.PlayerTwo, gameManager); } if (b1.Dead && b2.Dead) return GameState.Draw; else if (b1.Dead) return GameState.WinPlayerTwo; else if (b2.Dead) return GameState.WinPlayerOne; else return GameState.NotFinished; } public override int GetScore(PlayerRole player, GameManager gameManager) { if (player == PlayerRole.Spectator) { return Resources.Load<UnitCard>("Cards/Specials/PlayerBaseP1").Health; } var unit = GetBase(player, gameManager); if (unit != null) return unit.Health; else return 1; } private Unit GetBase(PlayerRole player, GameManager gameManager) { var unit = gameManager.Board.GetUnit(gameManager.Board.GetCell(GetBasePosition(player, gameManager)), true); return unit; } private void AddBase(PlayerRole player, GameManager gameManager) { UnitCard card; if (player == PlayerRole.PlayerOne) card = Resources.Load<UnitCard>("Cards/Specials/PlayerBaseP1"); else card = Resources.Load<UnitCard>("Cards/Specials/PlayerBaseP2"); Cell cell = gameManager.Board.GetCell(GetBasePosition(player, gameManager)); gameManager.Board.AddUnit(card, cell, player); } private Vector2Int GetBasePosition(PlayerRole player ,GameManager gameManager) { if (player == PlayerRole.PlayerOne) { return new Vector2Int(23, 20); } else { return new Vector2Int(29, 28); } } }<file_sep>using System.Collections.Generic; using UnityEngine; //Classe s'occupant des différents reliefs possibles du plateau public class BoardProps : BoardBehaviour { [SerializeField, Range(0, 1)] private float spawnRate = 0.0f; [SerializeField] private List<GameObject> waterProps = null; [SerializeField] private List<GameObject> fieldProps = null; [SerializeField] private List<GameObject> mountainProps = null; private void Start() { AddProps(); } private void AddProps() { foreach(var cell in board.Cells()) { if (Random.value > spawnRate) { if (cell.cellType == Cell.CellType.Water) SpawnProp(waterProps, cell); if (cell.cellType == Cell.CellType.Field) SpawnProp(fieldProps, cell); if (cell.cellType == Cell.CellType.Mountain) SpawnProp(mountainProps, cell); } } } private void SpawnProp(List<GameObject> pool, Cell cell) { GameObject prop = pool[Random.Range(0, pool.Count)]; Instantiate(prop, transform.TransformPoint(board.CellToLocal(cell.position)), Quaternion.Euler(transform.TransformDirection(new Vector3(0, Random.Range(0f, 360f), 0))), transform); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using Photon.Pun; //Classe affichant le nom des joueurs sur le plateau public class InfoPlayer : BoardBehaviour { [SerializeField] public TMP_Text text; [SerializeField] public TMP_Text text2; private void Update() { if (PhotonNetwork.IsConnectedAndReady) text.text = BoardManager.RemotePhotonPlayer.NickName; text2.text = BoardManager.LocalPhotonPlayer.NickName; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using NUnit.Framework; using System.Linq; public class CellTest : MonoBehaviour { public enum CellType {Water, Field, Mountain, None}; [Test] public void Neighbors_Test() { Board board = new Board(10,10); Cell cell = board.GetCell(4,4); Cell cellN = board.GetCell(4,3); List<Cell> got = board.Neighbors(cell).ToList(); Assert.True(got.Contains(cellN)); } [Test] public void HeightWater_Test() { Cell cell = new Cell(); cell.cellType = (Cell.CellType)CellType.Water; float res = cell.Height; Assert.True(res == 1); } [Test] public void HeightMountain_Test() { Cell cell = new Cell(); cell.cellType = (Cell.CellType)CellType.Mountain; float res = cell.Height; Assert.True(res == 3); } [Test] public void LocalPosition_Test() { Board board = new Board(10,10); Cell cell = board.GetCell(5,5); Assert.That(board.LocalPosition(cell), Is.EqualTo(new Vector3(0,2,0))); } [Test] public void Distance_Test() { Board board = new Board(10,10); Cell cell = board.GetCell(5,5); Cell cellN = board.GetCell(5,4); Assert.That(cell.Distance(cellN), Is.EqualTo(2f)); } [Test] public void Ring_Test() { Board board = new Board(10,10); Cell cell = board.GetCell(5,5); Cell cellN = board.GetCell(5,4); Assert.True(board.Ring(cell, 1).Contains(cellN)); } [Test] public void NotRing_Test() { Board board = new Board(10,10); Cell cell = board.GetCell(5,5); Cell cellN = board.GetCell(5,3); Assert.False(board.Ring(cell, 1).Contains(cellN)); } [Test] public void Disc_Test() { Board board = new Board(10,10); Cell cell = board.GetCell(5,5); Cell cellN = board.GetCell(5,4); Assert.True(board.Disc(cell, 3).Contains(cellN)); } } <file_sep>public interface IDealDamage { void DealDamage(ITakeDamage target); }<file_sep>using System; using System.Collections.Generic; using System.Linq; using UnityEngine; //Classe représentant un joueur [System.Serializable] public class Player { [SerializeField] private Deck originalDeck = null; [SerializeField] private Deck deck = null; public Deck OriginalDeck => originalDeck; public Deck Deck => deck; [SerializeField] private List<string> serializedHand = null; [SerializeField] private PlayerRole role; [SerializeField] private int gold = 0; [SerializeField] private int currentGold = 0; public List<CardBase> Hand => serializedHand.Select(c => Resources.Load<CardBase>(c)).ToList(); public PlayerRole Role => role; public int Gold => gold; public int CurrentGold => currentGold; public Player(Deck deck, PlayerRole role) { this.role = role; originalDeck = deck; this.gold = 1; this.currentGold = gold; this.deck = new Deck(deck); this.Deck.Shuffle(); serializedHand = new List<string>(); } public void SetGold(int newgold){ this.gold = newgold; } public void SetCurrentGold(int newgold){ currentGold = newgold; } //Pioche une carte de son deck et l'ajoute à sa main public UnitCard DrawUnit() { UnitCard t = Deck.DrawUnit(); if (serializedHand.Count < 10) serializedHand.Add(t.ResourcePath); return t; } //Ajoute une carte à sa main, si celle-ci ne contient pas déjà 10 cartes public void addCard(CardBase card){ if (serializedHand.Count < 10) serializedHand.Add(card.ResourcePath); } public Tuple<List<UnitCard>,List<SpellCard>> DrawMulligan(PlayerRole playerRole) { List<UnitCard> U = new List<UnitCard>(); List<SpellCard> S = new List<SpellCard>(); U.Add(Deck.DrawUnit()); U.Add(Deck.DrawUnit()); S.Add(Deck.DrawSpell()); if (playerRole.Equals(PlayerRole.PlayerTwo)) { S.Add(Deck.DrawSpell()); } return Tuple.Create(U,S); } //Pioche une carte de son deck et l'ajoute à sa main public SpellCard DrawSpell() { SpellCard t = Deck.DrawSpell(); if (serializedHand.Count < 10) serializedHand.Add(t.ResourcePath); return t; } //Supprime une carte de la main du joueur public void UseCard(CardBase card) { serializedHand.Remove(card.ResourcePath); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using NUnit.Framework; public class PlayerTest : MonoBehaviour { [Test] public void PlayerDrawUnitCompare_Test(){ UnitCard u = ScriptableObject.CreateInstance<UnitCard>(); SpellCard s = ScriptableObject.CreateInstance<DamageSpell>(); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Player p = new Player(deck, 0); Assert.That(p.OriginalDeck.DrawUnit(), Is.EqualTo(p.Deck.DrawUnit())); } [Test] public void PlayerDrawSpellCompare_Test(){ UnitCard u = ScriptableObject.CreateInstance<UnitCard>(); SpellCard s = ScriptableObject.CreateInstance<DamageSpell>(); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Player p = new Player(deck, 0); Assert.That(p.OriginalDeck.DrawSpell(), Is.EqualTo(p.Deck.DrawSpell())); } /*[Test] public void PlayerUseCardSpell_Test(){ UnitCard u = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Player p = new Player(deck, 0); SpellCard a = p.DrawSpell(); p.UseCard(a); Assert.That(p.Hand.Count, Is.EqualTo(0)); } [Test] public void PlayerUseCardUnit_Test(){ UnitCard u = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Player p = new Player(deck, 0); UnitCard a = p.DrawUnit(); p.UseCard(a); Assert.True(p.Hand.Count == 0); } [Test] public void PlayerDrawSpell_Test(){ UnitCard u = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Player p = new Player(deck, 0); SpellCard a = p.DrawSpell(); Assert.True(p.Hand.Count == 1); } [Test] public void PlayerDrawUnit_Test(){ UnitCard u = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Player p = new Player(deck, 0); UnitCard a = p.DrawUnit(); Assert.True(p.Hand.Count == 1); }*/ } <file_sep>using System.Collections.Generic; using UnityEngine; //Classe représentant la main du joueur public class Hand : BoardBehaviour { [SerializeField] private float spacing = 0.1f; [SerializeField] private GameCard cardPrefab = null; // [SerializeField] private PlayerRole role = PlayerRole.PlayerOne; public Player player { get; private set; } public GameCard[] Cards { get; private set; } public float Spacing { get { return spacing; } } private void Start() { Cards = new GameCard[10]; for (int i = 0; i < Cards.Length; i++) { GameObject cardObject = Instantiate(cardPrefab.gameObject, transform); Cards[i] = cardObject.GetComponent<GameCard>(); cardObject.SetActive(false); } } private void Update() { UpdateHand(); } public void UpdateHand() { player = manager.LocalPlayer; for (int i = 0; i < Cards.Length; i++) { if (i < player.Hand.Count) { Cards[i].card = player.Hand[i]; if (Cards[i] != null) { Cards[i].gameObject.SetActive(true); Vector3 pos = Cards[i].transform.localPosition; pos.x = ((float) i - ((float) player.Hand.Count / 2f)) * spacing; Cards[i].transform.localPosition = pos; } } else { Cards[i].card = null; Cards[i].gameObject.SetActive(false); } } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using NUnit.Framework; public class DeckTest : MonoBehaviour { [Test] public void Shuffle_Test(){ UnitCard u = new UnitCard(); SpellCard s = new DamageSpell(); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new DamageSpell[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); deck.Shuffle(); Assert.True(us[0] == u); } [Test] public void DrawUnit_Test(){ UnitCard u = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Assert.That(deck.DrawUnit().resourcePath, Is.EqualTo(u.resourcePath)); } [Test] public void DrawSpell_Test(){ UnitCard u = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] us = new UnitCard[1]; SpellCard[] ss = new SpellCard[1]; us[0] = u; ss[0] = s; Deck deck = new Deck(us, ss); Assert.That(deck.DrawSpell().resourcePath, Is.EqualTo(s.resourcePath)); } [Test] public void AddCardUnit_Test(){ UnitCard u1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s1 = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] u = new UnitCard[] {u1}; SpellCard[] s = new SpellCard[] {s1}; Deck deck = new Deck(u, s); UnitCard u2 = Resources.Load<UnitCard>("Cards/Unit/Pro"); deck.AddCard(u2); Assert.True(deck.units.Count == 2); } [Test] public void AddCardSpell_Test(){ UnitCard u1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s1 = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] u = new UnitCard[] {u1}; SpellCard[] s = new SpellCard[] {s1}; Deck deck = new Deck(u, s); SpellCard s2 = Resources.Load<SpellCard>("Cards/Spell/Heal"); deck.AddCard(s2); Assert.True(deck.spells.Count == 2); } [Test] public void RemoveCardUnit_Test(){ UnitCard u1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s1 = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] u = new UnitCard[] {u1}; SpellCard[] s = new SpellCard[] {s1}; Deck deck = new Deck(u, s); deck.RemoveCard(u1); Assert.True(deck.units.Count == 0); } [Test] public void RemoveCardSpell_Test(){ UnitCard u1 = Resources.Load<UnitCard>("Cards/Unit/Noob"); SpellCard s1 = Resources.Load<SpellCard>("Cards/Spell/Fireball"); UnitCard[] u = new UnitCard[] {u1}; SpellCard[] s = new SpellCard[] {s1}; Deck deck = new Deck(u, s); deck.RemoveCard(s1); Assert.True(deck.spells.Count == 0); } } <file_sep>using Photon.Pun; using Photon.Realtime; using System.Collections; using System.Collections.Generic; using UnityEngine; public class RoomListingsMenu : MonoBehaviourPunCallbacks { [SerializeField] private RoomListing _roomListing = null; [SerializeField] private Transform _content = null; private Dictionary<string,RoomListing> ListGames = new Dictionary<string, RoomListing>(); public override void OnRoomListUpdate(List<RoomInfo> roomList) { foreach(RoomInfo info in roomList) { if (info.RemovedFromList) { Destroy(ListGames[info.Name].gameObject); ListGames.Remove(info.Name); } else { RoomListing listing = null; if (!ListGames.ContainsKey(info.Name)){ listing = Instantiate(_roomListing, _content); } if (listing != null || ListGames.ContainsKey(info.Name)) { ListGames[info.Name] = (listing!=null) ? listing : ListGames[info.Name]; ListGames[info.Name].SetRoomInfo(info); } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; public class RoomDeckListing : MonoBehaviour { [SerializeField] private TMP_Text _name = null; [SerializeField] private Image image = null; public Deck Deck {get; set;} public void SetDeckInfo(Deck deck) { Deck = deck; _name.text = deck.Name; } public void on_click_deck() { RoomDeckListMenu deckList = Object.FindObjectOfType<RoomDeckListMenu>(); deckList.SetSelectedDeck(Deck); } public void SetBgColor(Color color) { image.color = color; } }
dbe91ebb4e943123993e543953b1d55e52b4e10e
[ "Markdown", "C#" ]
79
C#
PNS-PS7and8/pns-innov1920-pns-innov1920-n
08600ce7aa9b2751885239f2d95a3f4bd956a318
d28bc1370a1cf87a92ce69becdf12a19c3b2e32e
refs/heads/master
<repo_name>L3tum/php-uring-server<file_sep>/src/HttpResponseBuilder.php <?php namespace Uring; use Amp\Http\Rfc7230; use Psr\Http\Message\ResponseInterface; class HttpResponseBuilder { public static function getResponse(ResponseInterface $response): string { // HTTP/1.1 404 NOT FOUND\r\nServer: Custom\r\n\r\nBODY $body = $response->getBody()?->__toString(); $headerLine = Rfc7230::formatHeaders($response->getHeaders()); if (!$response->hasHeader('content-length')) { $bodyLength = strlen($body); $headerLine .= "Content-Length: $bodyLength\r\n"; } if (!$response->hasHeader('server')) { $headerLine .= "Server: PHP-Uring\r\n"; } return "HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}\r\n$headerLine\r\n{$body}"; } } <file_sep>/src/ServerSocket.php <?php namespace Uring; class ServerSocket extends Socket { public function __construct( int $socketFileDescriptor, public readonly SocketAddress $socketAddress ) { parent::__construct($socketFileDescriptor); } } <file_sep>/src/Socket.php <?php namespace Uring; use Uring\Internals\FFI; class Socket { public const COMMON_BUFFER_LENGTH = 8192; public function __construct( public readonly int $socketFileDescriptor ) { } public function closeSocket(): void { FFI::libc()->close($this->socketFileDescriptor); } } <file_sep>/src/SocketServer.php <?php namespace Uring; use Closure; use RuntimeException; use Uring\Exceptions\UringException; use Uring\States\InputOutputState; abstract class SocketServer { /** * @var array<int, ServerSocket> */ protected array $listeningSockets = []; protected UringFFI $uring; protected bool $stopped = false; protected Closure $onAccept; protected int $queueDepth; /** * @var array<array-key, array{address: string, port: int, domain: int}> */ protected array $wantedSockets = []; final public function addListeningSocket(string $address, int $port, int $domain = STREAM_PF_INET): void { $this->wantedSockets[] = ['address' => $address, 'port' => $port, 'domain' => $domain]; } protected function initializeBackend(int $queueDepth, ?int $masterFd = null): void { if (!isset($this->uring)) { $this->queueDepth = $queueDepth; $this->uring = new UringFFI($queueDepth, Socket::COMMON_BUFFER_LENGTH); $this->uring->initializeQueue($masterFd); } } public function run(int $queueDepth = 1024): void { if (count($this->wantedSockets) === 0 && count($this->listeningSockets) === 0) { // TODO throw new RuntimeException("Need some sockets man"); } if (!isset($this->onAccept)) { throw new RuntimeException("No accept callback man"); } $this->initializeBackend($queueDepth); $this->launchHousekeeper(-1); $this->startListeningSocketsAsync(); while (!$this->stopped) { if ($this->hasRunningClients()) { $this->uring->conditionalSubmit(); $states = $this->uring->peekBatch(); } else { $states = $this->uring->submitAndWait(); } $this->handleUringStates($states); $this->uring->freeRequestStates($states); } } abstract protected function startListeningSocketsAsync(): void; final public function setOnAccept(Closure $callback): void { $this->onAccept = $callback; } protected function hasRunningClients(): bool { return false; } abstract protected function launchHousekeeper(int $referenceFd): void; abstract protected function doHousekeeping(): void; protected function handleHousekeeper(int $referenceFd): void { while (!$this->stopped) { try { $this->timeoutAndWait($referenceFd, $this->getHousekeepingInterval()); } catch (UringException) { // Intentionally left blank } $this->doHousekeeping(); } } protected function getHousekeepingInterval(): float { return 10.0; } /** * @param InputOutputState[] $states */ abstract protected function handleUringStates(array $states): void; /** * @throws UringException * @internal */ abstract public function readAndWait(int $fileDescriptor, int $bufferLength): string; /** * @throws UringException * @internal */ abstract public function writeAndWait(int $fileDescriptor, string &$buffer): void; /** * @throws UringException * @internal */ abstract public function closeAndWait(int $fileDescriptor): void; /** * @throws UringException * @internal */ abstract public function timeoutAndWait(int $fileDescriptor, float $timeoutInSeconds): void; /** * Returns the created filedescriptor * @throws UringException * @internal */ abstract public function createSocketAndWait(int $domain): int; public function stop(): void { if ($this->stopped) { return; } $this->stopped = true; echo PHP_EOL . "DIE DIE DIE" . PHP_EOL; if (isset($this->uring)) { $this->uring->stop(); } foreach ($this->listeningSockets as $socket) { $socket->closeSocket(); } } } <file_sep>/src/HttpRequestParser.php <?php namespace Uring; use Amp\Http\Rfc7230; use Psr\Http\Message\RequestInterface; use RuntimeException; class HttpRequestParser { public static function getRequest(string &$buffer): RequestInterface { $requestParts = explode("\r\n", $buffer, 2); if (count($requestParts) < 2) { throw new RuntimeException("Malformed request $buffer"); } $requestLine =& $requestParts[0]; $requestBody =& $requestParts[1]; if (mb_strlen($requestLine) > 256) { throw new RuntimeException("Request-Line too long"); } if (preg_match("/^([A-Z]+) ([^ ]+) HTTP\/(1|1\.0|1\.1|2|2\.0)$/", $requestLine, $matches) === 1) { $method =& $matches[1]; $requestUri =& $matches[2]; $version =& $matches[3]; self::verifyHttpMethod($method); } else { throw new RuntimeException("Invalid Request-Line"); } unset($requestLine); $requestParts = explode("\r\n\r\n", $requestBody, 2); $headers = Rfc7230::parseHeaders($requestParts[0] . "\r\n"); $rawBody =& $requestParts[1]; if (isset($headers['host'])) { $requestUri = $headers['host'][0] . $requestUri; } return new \Nyholm\Psr7\Request($method, $requestUri, $headers, $rawBody, $version); } public static function verifyHttpMethod(string &$method): void { match ($method) { 'HEAD', 'GET' => null, default => throw new RuntimeException("Unsupported HTTP Method $method") }; } } <file_sep>/src/ClientSocket.php <?php namespace Uring; use Uring\Exceptions\UringException; class ClientSocket extends Socket { public function __construct( protected readonly SocketServer $server, int $socketFileDescriptor, public readonly SocketAddress $serverAddress, public readonly SocketAddress $clientAddress ) { parent::__construct($socketFileDescriptor); } /** * @throws UringException */ public function read(int $length): string { return $this->server->readAndWait($this->socketFileDescriptor, $length); } /** * @throws UringException */ public function write(string $buffer): void { $this->server->writeAndWait($this->socketFileDescriptor, $buffer); } } <file_sep>/src/FiberServer.php <?php namespace Uring; use Exception; use FFI; use Fiber; use FiberError; use Throwable; use Uring\Exceptions\BadFileDescriptorException; use Uring\Exceptions\InvalidArgumentException; use Uring\Exceptions\MissingWaiterException; use Uring\States\AcceptState; use Uring\States\CancelState; use Uring\States\CloseState; use Uring\States\CreateSocketState; use Uring\States\ReadState; use Uring\States\ShutdownState; use Uring\States\StatesState; use Uring\States\TimeoutState; use Uring\States\WriteState; class FiberServer extends SocketServer { /** * @var array<int, Fiber> */ protected array $runningClients = []; /** @var array<class-string, array<int, Fiber>> */ protected array $waiters = []; public function __construct() { foreach (StatesState::STATES as $state) { $this->waiters[$state] = []; } } private static function finalizer(FiberServer $that, int $socket): void { foreach (StatesState::STATES as $state) { unset($that->waiters[$state][$socket]); } try { $that->closeAndWait($socket); } catch (Exception|Throwable $e) { echo "Got exception in finalizer for socket $socket: " . $e::class . " " . $e->getMessage() . PHP_EOL; } finally { Internals\FFI::libc()->close($socket); unset($that->runningClients[$socket]); foreach (StatesState::STATES as $state) { unset($that->waiters[$state][$socket]); } echo "Closed socket $socket" . PHP_EOL; } } /** * @inheritDoc */ protected function handleUringStates(array $states): void { $index = count($states); try { foreach ($states as $index => $state) { $fiber = $this->waiters[$state::class][$state->fileDescriptor] ?? null; match ($fiber !== null) { true => match (isset($state->exception)) { true => $fiber->throw($state->exception), false => match ($state::class) { AcceptState::class => throw new BadFileDescriptorException("File descriptor for $state->fileDescriptor is already running!"), ReadState::class => match ($state->bufferWritten >= 0) { true => $fiber->resume(FFI::string($state->buffer, $state->bufferWritten)), false => $fiber->throw(new InvalidArgumentException("Buffer for read was -1")) }, WriteState::class => $fiber->resume($state->bufferWritten), CreateSocketState::class => $fiber->resume($state->createdFileDescriptor), default => $fiber->resume() } }, false => match ($state::class) { AcceptState::class => ( $this->runningClients[$state->fileDescriptor] = $fiber = new Fiber($this->onAccept)) && $fiber->start(new ClientSocket($this, $state->fileDescriptor, $this->listeningSockets[$state->serverSocket]->socketAddress, SocketAddress::fromCData($state->clientAddress)) ), default => match (isset($this->runningClients[$state->fileDescriptor])) { false => null, true => match ($this->runningClients[$state->fileDescriptor]->isTerminated()) { true => null, false => throw new MissingWaiterException("Got Event without listener on fd $state->fileDescriptor " . $state::class) } } } }; if (($fiber = $this->runningClients[$state->fileDescriptor] ?? null) !== null && $fiber->isTerminated()) { $this->launchFinalizer($state->fileDescriptor); } // throw new MissingWaiterException("Got Event without listener on fd $state->fileDescriptor " . $state::class) } } catch (Exception|Throwable $e) { $fiber = $this->runningClients[$state->fileDescriptor] ?? null; if ($e instanceof FiberError) { $status = "None"; if ($fiber === null) { $status = "None"; } elseif ($fiber->isTerminated()) { $status = "Terminated"; } elseif ($fiber->isSuspended()) { $status = "Suspended"; } elseif ($fiber->isRunning()) { $status = "Running"; } elseif (!$fiber->isStarted()) { $status = "Not Started Yet"; } echo "FiberError " . $e->getMessage() . " on Fiber $state->fileDescriptor with state " . $state::class . " in status $status" . PHP_EOL; } else { // TODO: Log echo "Got Exception " . $e::class . " " . $e->getMessage() . " For State " . $state::class . " with fd $state->fileDescriptor" . PHP_EOL; echo $e->getTraceAsString() . PHP_EOL; // FFI::libc()->close($state->fileDescriptor); } } finally { if (count($states) > $index + 2) { echo "Running handleUringStates again because $index + 2 is less than " . count($states) . PHP_EOL; $this->handleUringStates(array_slice($states, $index + 1)); } } } protected function startListeningSocketsAsync(): void { foreach ($this->wantedSockets as $wantedSocket) { $fiber = new Fiber(function (array $wantedSocket) { $socketFd = $this->uring->flags->supportsCreateSocket ? $this->createSocketAndWait($wantedSocket['domain']) : SocketFFI::createSocket($wantedSocket['domain']); SocketFFI::enableReusableAddress($socketFd); $sockAddr = SocketFFI::createSocketAddress($wantedSocket['address'], $wantedSocket['port'], $wantedSocket['domain']); SocketFFI::bindSocketAddressToSocket($socketFd, $sockAddr); SocketFFI::testListen($socketFd); $this->listeningSockets[$socketFd] = new ServerSocket($socketFd, $sockAddr); $this->uring->acceptRequests($socketFd); }); $fiber->start($wantedSocket); } $this->wantedSockets = []; } protected function launchHousekeeper(int $referenceFd): void { $this->runningClients[$referenceFd] = $fiber = new Fiber(fn() => $this->handleHousekeeper($referenceFd)); $fiber->start(); } protected function doHousekeeping(): void { foreach ($this->runningClients as $socket => $fiber) { if ($fiber !== null && $fiber->isTerminated()) { $this->launchFinalizer($socket); } } } private function launchFinalizer(int $socket): void { $that = $this; $this->runningClients[$socket] = $fiber = new Fiber(static fn($that, $socket) => self::finalizer($that, $socket)); $fiber->start($that, $socket); } /** * @inheritDoc */ public function readAndWait(int $fileDescriptor, int $bufferLength): string { $this->uring->readRequest($fileDescriptor, $bufferLength); $this->waiters[ReadState::class][$fileDescriptor] =& $this->runningClients[$fileDescriptor]; $buffer = Fiber::suspend(); unset($this->waiters[ReadState::class][$fileDescriptor]); return $buffer; } /** * @inheritDoc */ public function writeAndWait(int $fileDescriptor, string &$buffer): void { $this->uring->writeRequest($fileDescriptor, $buffer); $this->waiters[WriteState::class][$fileDescriptor] =& $this->runningClients[$fileDescriptor]; Fiber::suspend(); unset($this->waiters[WriteState::class][$fileDescriptor]); } /** * @inheritDoc */ public function closeAndWait(int $fileDescriptor): void { if ($this->uring->flags->supportsCancelFd) { $this->uring->cancelRequests($fileDescriptor); $this->waiters[CancelState::class][$fileDescriptor] =& $this->runningClients[$fileDescriptor]; Fiber::suspend(); unset($this->waiters[CancelState::class][$fileDescriptor]); } if ($this->uring->flags->supportsShutdown) { $this->uring->shutdownRequest($fileDescriptor, STREAM_SHUT_WR); $this->waiters[ShutdownState::class][$fileDescriptor] =& $this->runningClients[$fileDescriptor]; Fiber::suspend(); $this->uring->shutdownRequest($fileDescriptor, STREAM_SHUT_RD); Fiber::suspend(); unset($this->waiters[ShutdownState::class][$fileDescriptor]); } $this->uring->closeRequest($fileDescriptor); $this->waiters[CloseState::class][$fileDescriptor] =& $this->runningClients[$fileDescriptor]; Fiber::suspend(); unset($this->waiters[CloseState::class][$fileDescriptor]); } /** * @inheritDoc */ public function timeoutAndWait(int $fileDescriptor, float $timeoutInSeconds): void { $this->uring->timeoutRequest($fileDescriptor, $timeoutInSeconds); $this->waiters[TimeoutState::class][$fileDescriptor] =& $this->runningClients[$fileDescriptor]; Fiber::suspend(); unset($this->waiters[TimeoutState::class][$fileDescriptor]); } /** * @inheritDoc */ public function createSocketAndWait(int $domain): int { $fakeFd = $this->uring->createSocketRequest(STREAM_PF_INET, SOCK_STREAM, 0); $this->waiters[CreateSocketState::class][$fakeFd] = Fiber::getCurrent(); $createdFd = Fiber::suspend(); unset($this->waiters[CreateSocketState::class][$fakeFd]); return $createdFd; } }
f5f46f46fc3a6f067c53f040b10174b7048933df
[ "PHP" ]
7
PHP
L3tum/php-uring-server
13098b9fa95e34bc4e049c00869a3db2df234f16
5a0fc7298306a52ec5d5a8b0daead70b47369a2c
refs/heads/main
<repo_name>iankloo/course_site_demo<file_sep>/README.md # Course Website Concept Demo This site is a shell that could be used as the main web resource for a course. [Link to running site](https://iankloo.github.io/course_site_demo) ![](site_demo.png) ### Design principles: 1. Aesthetically pleasing and professional appearance - Communication is more than just providing access to information - If folder-based structures (Blackboard, Teams, etc.) are "good enough", why do all of the websites we visit frequently not just have a folder structure? - Folder-based course sites communicate to students that we are doing the minimum for class prep (even when that isn't true). 2. Reduces number of clicks for students to get to content - All course material for each lesson should be available in one place. - It shouldn't take long for students to access multiple lessons (e.g., when studying for a test) 3. All course resources available and their locations obvious - Course resources like the syllabus and instructor information should be up-front and easy to access 4. Open source and platform agnostic - Using for-profit software means we depend on external developers to make products that work for us - Shifting between platforms can be difficult - Open source tools are prevalent and well-maintained in the academic space 5. Incorporates version control - Tracking changes to the course website becomes the process of tracking changes to the course. This is a huge asset for knowledge management. - Github and Gitlab can serve as the repository of the site code as well as the (free) hosting solution ### Limitations: 1. No user engagement (e.g., discussions, turning things in) on the site - this is a one-way street - This resource is a platform for sharing material with students, you'll want to use something like Teams or Slack for communication and something more secure for collecting work. 2. Moderate learning curve to get started managing a site ## How to: ### Install - Install blogdown: ``` install.packages('blogdown') ``` - Clone git repo - Open the R project in the repo called `course_site.Rproj` - Run `blogdown::hugo_build()` and then `blogdown::run_site()` to get things up and running - Note: linked files won't work locally unless you go to `config.yaml` and comment out `baseurl:...`. Just make sure you uncomment before pushing updates to the server. - At this point you probably want to start your own Git repo so you can work on your own site. My preferred workflow for this is: 1. Create an empty repo (if on github, just click through it) 2. Clone that empty repo onto your machine 3. Copy and paste all of the `course_site` files into your repo ### Adding content - Add lectures by adding folders in `content/post/` - Probably easiest to copy existing lectures and modifying - Need an `index.Rmd` file here to create the lecture page - Include links to slides, lesson resources, etc. - When linking to things from the lectures, put the content in `static/` somewhere. - You can see several examples in the two lectures that show how to write the links correctly - Presentations can be done any way you want. This example project shows sites made using [xaringan](https://github.com/yihui/xaringan) slides. You could just as easily build slides in powerpoint and export as PDF. You'd just store them in `static/` like any other file and make a reference in the lecture. - Videos shown in this example are embedded links to Vimeo. You can get these linke by clicking "embed" on a Vimeo video and copying the string. I left a video folder if you want to upload videos locally. - Modify `config.yaml` to add new items to the top menu bar. The syntax is easy to copy. These can be external links or link to internal pages that are hosted in `content/`. ### Building site - To test out what you added, run `blogdown::hugo_build()` and `blogdown::run_site()`. This starts a server on your computer to give you a preview of what the site will look like with your changes. ### Deploying site - If everything looks good, uncomment the `baseurl:...` part of `config.yaml` and push everything to the server. - If you are using git, that would look like: ``` git add --all git commit -m 'new content' git push ``` <file_sep>/docs/presentations/lecture_1.Rmd --- title: "Course Introduction" author: "<NAME>" date: "2019-08-19" objectives: 'Understand the goals, objectives, organization, and administrative requirements for SE375; Check that course level requirements are met (R installed, textbook on hand); Review basic concepts of statistics; Review confidence intervals' type: 'presentation' links: CLT visualization: address: 'https://gallery.shinyapps.io/CLT_mean/' icon: 'share-alt' Interpreting CIs: address: 'https://rpsychologist.com/d3/CI/' icon: 'share-alt' output: xaringan::moon_reader: css: ["default", "www/se_template.css"] nature: highlightStyle: github highlightLines: true countIncrementalSlides: false --- class: gray ## About me - I'm from Pittsburgh, so go Pens and Steelers (in that order) <img src = 'www/img/iankloo_timeline.png' style = 'width:100%'> --- class: gray ## About me - I've got twins...so life is busy <center> <img src = 'www/img/babies.JPG' style = 'width:60%;'> </center> --- class: gray ## About me - DoD projects - Counter-threat finance (seized a bunch of money) - Support to OSINT analysts (wrote apps to find data people willingly give away) - Support to special operations (...) - Side projects - NHL live in-game win probability - Predicting wins in DOTA 2 (eSports analytics) - What am I doing here? - Teaching you! - Doing some research to help with the DoD projects mentioned above --- class: gray ## Course Material - Course Website (slides, schedule) - <a href = 'https://se375.dse-apps.com'>se375.dse-apps.com</a> - MS Teams (discussion, quizzes) - Applied Statistics and Probability for Engineers, Montgomery, 7th Edition - ONLINE ONLY - SE375 Reference Handbook - R and Rstudio --- class: gray ## Lectures - Lectures are for you! - I will try to present material in a way that you don't get in your textbook to give you another way to look at things - I'll hit theory as quickly as possible and get to an example problem - You'll see some code, but this won't be a "coding class" - My style can (and probably will) change to meet the needs of this specific group - I'll need your feedback! --- class: gray ## Class Basics <strong>Rules</strong> - Respect others: be on time, ready to learn (HW, Appropriate Materials, No Phones) - No food, no drink (except approved containers - <strong>not</strong> Starbucks with a lid), no tobacco - Coats and backpacks in the hallway - If you need to leave early or miss a class, let me know via email - I cannot excuse you from missing class - I just record what happens - It is your responsibility to reschedule WPR's 48 hours before they are given - Primary means of communication are Teams and email - AI - as often as you need, specific questions, come prepared - Disputing grades - I make mistakes, so please correct me if you think you were graded incorrectly - <strong>Make all requests for grade disputes in writing</strong> --- class: gray ## Tips to Succeed in SE375 - <strong>Remember (or relearn) what you did in MA206</strong> - Classes are starting to build on each other - you have to retain knowledge! - Prep before class - Coming to lectures and participating alone is not enough to succeed for most - Re-write my code, don't copy/paste - This helps with retention - There isn't much code in this class - Communicate with me early and often if you have any problems <strong>I'm not interested in you "getting by" in this class. My job is to teach you statistics. You will get a good grade if you learn statistics...and a bad one if you don't.</strong> --- class: gray ## Documentation Requirements Source Document: DSE Policy Memo 1-3 "Academic Documentation Policy" - Graded submissions require cover sheet/electronic acknowledgement - In-line documentation as necessary - Common knowledge includes: - All DSE textbooks, course materials, anything on blackboard, discussions in class, discussions with your instructor - <strong>No need to document common knowledge</strong> - <strong>This does NOT equate to good scholarship, but will save you from an honor violation</strong> - Assistance and collaboration - Properly, specifically documented assistance IAW and DAW Appendix A (p.21) - Collaboration is working together on a common project - Best practices - When in doubt, document - Actively document sources while you're working - it's way to hard to go back and remember - Citation style: APA --- class: gray ## Assistance <strong>Assistance Includes:</strong> - Getting a verbal answer from another person about a specific point of confusion - Having someone show you his/her solution so you know how to proceed on your own - Having someone show you where the errors are in your own solution - Having someone help you fix errors in your own solution - Using previous semester's assignments in order to derive your own answer - Having someone explain to you exactly what to type - Using other electronic and non-electronic resources (e.g., websites) <strong>This all needs to be specifically documented</strong> --- class: gray ## Assistance .pull-left[ <strong>Good Assistance</strong> - You are doing the typing - The person giving assistance is both present and knowledgeable - The person giving assistance is successfully helping you understand the material ] .pull-right[ <strong>Bad Assistance</strong> - Electronic copying - Retyping someone else's solution with that person not present to explain the solution - Reproducing someone else's solution without understanding the content - Receiving an electronic file of someone else's work ] --- class: gray ## Last Word on Honor Issues - The honor system is cadet-run - It is my responsibility to put anything that may be an honor issue to the honor system - I don't decide if someone is guilty of an honor violation - In my experience, the main issue is assistance - if you tell a different story in your assistance citation than another cadet, someone is wrong...and that may be an honor violation <strong>In this class especially, it is very obvious if you copy someone's answer --- class: gray ## Course Structure Topic | Lessons ------------- | ------------- Block 1: MA206 Review | 1-3 Block 1: Extending Hypothesis Testing & Regression | 4-11 Block 2: ANOVA | 12-20 Block 3: DOE | 21-34 Block 4: SQC | 35-39 --- class: gray ## Graded Events Event | Lesson | Points ------------- | ------------- | ------------- Problem Set 1 | 4 | 50 Review Test | 6 | 75 Problem Set 2 | 12 | 75 Problem Set 3 | 19 | 75 WPR | 20 | 200 Problem Set 4 | 29 | 75 Project | 30 - 35 | 150 Problem Set 5 | 39 | 50 TEE | 40 | 200 Instructor Points | | 50 --- class: gray ## Instructor Points - There will be a reading quiz that you need to take before the start of (almost) every class - I will post each quiz at least 24 hours before they are due and will blast a message on Teams - make sure your notifications are set accordingly - I will drop your lowest 3 quizzes - <strong>You are responsible for quizzes even if you aren't in class</strong> - That's it! I'm not holding you hostage with instructor points. - If you don't participate in class, you will likely do poorly. Trying to give/takeaway instructor points based on class participation or other intangibles introduces too much bias --- class: gray ## "Homework" - The syllabus has recommended homework problems for each class - I am NOT collecting these - I recommend using these to check on your own learning, and as potential AI problems - I will publish complete solutions (not just answers) for all of them, as we go --- class: gray ## Course Project STATAPULT! <center> <img src = 'www/img/statapult.png'> </center> --- class: gray ## Review of Major Statistical Concepts - If you failed or did poorly in MA206, this course will be very difficult - come see me early - If you don't know the basics, learn them quick - Ex) you can't tell me what a P-value and a Z-score are, competently, by the first test, you will likely fail the class - My goal is for everyone to pass this class, but <strong>I won't pass someone who doesn't know statistics</strong>...that defeats the purpose of all of this - If you can't do the level of statistics taught in this course, you should not be a systems engineer (not the end of the world) - This class will be easier for those with aptitude, but anyone admitted to West Point can pass this class if they put in the work --- class: gray ## Why Should You Care? - The foundation of machine learning and artificial intelligence is statistics - Even if you don't want to be a practitioner, you need to know how this works to be a leader - <strong>"Leaderology" is not sufficient in technical fields anymore</strong> - Logically thinking about the world requires statistics - PhD's in statistics are doctorates in philosophy - this is a way to think - Most people don't understand statistics well enough to apply it. As an engineer, you can't get by without it! - Statistics is heavily tested on the Fundamentals of Engineering Exam (FEE) --- class: gray ## Confidence Intervals - Need average age of cows at USMA, but birthdays are PII...how can we estimate it? - We could just ask everyone... 1. Would take forever 2. Maybe someone won't answer the survey - We could ask a small number and estimate the mean of the <font color='blue'>population</font> based on the mean of the <font color='red'>sample</font> - The <font color='red'>sample mean ( $\overline{x}$ )</font> will not exactly estimate <font color='blue'>population mean ( $\mu$ ) </font>, so we need to report a <strong>confidence interval</strong> --- class: gray ## Confidence Intervals - General formula: $$\text{point estimate } \pm \text{ statistic }_\frac{\alpha}{2} * \text{standard error}$$ - Point estimate = <font color='red'> $\overline{x}$ </font> - Statistic: 1. If $n \geq 30$, use a z-statistic 2. If $n < 30$, use a t-statistic - Standard Error: 1. If you have <font color='blue'> $\sigma$ </font>, use $\frac{\sigma}{\sqrt{n}}$ 2. If you only have <font color='red'> $S$ </font>, use $\frac{S}{\sqrt{n}}$ - Intuition: - Bigger standard error, bigger confidence interval - Smaller $n$, bigger confidence interval - Smaller $\alpha$ bigger confidence interval --- class: gray ## Key Concept: Central Limit Theorem - We can use z- and t-statistics because of the CLT - No matter what your data looks like, - Take a bunch of samples and calculate the means - The distribution of these means (sampling distribution) will approach a normal distribution! - So...if we take a sample and calculate the mean, we can use the normal distribution to say something about the population mean - <a href = https://gallery.shinyapps.io/CLT_mean/>Demo</a> --- class: gray ## Confidence Intervals - Using a z table (if $n \geq 30$ --> uses a normal distribution) <center> <img src = 'www/img/z_table.png' style = 'height: 450px'> </center> --- class: gray ## Confidence Intervals - Using a t table (if $n < 30$ --> uses a modified, more conservative, distribution that is similar to the normal distribution) <center> <img src = 'www/img/t_table.png' style = 'height: 450px'> </center> --- class: gray ## Confidence Intervals - Interpreting CI's - Ex) 95% CI - If we repeatedly take samples of the population and calculate the mean, the population mean will fall within our calculated CI 95% of the time - OK to interpret in plain language as "there is a 95% chance the population mean is within this range" - What we can't say: - How close the population and sample means likely are - Anything meaningful about the population or sample distributions other than the means of both - This helps: https://rpsychologist.com/d3/CI/ --- class: gray ## Confidence Intervals: Practice Problem - Want to know the age of the average cow at USMA, but don't have time to ask everyone - You asked 50 cadets and got the following information: - Mean: 20 - Standard Deviation (of sample): 3 - Use this information to create and interpret a 95% confidence interval to say something about the mean of all USMA cows --- class: gray ## Confidence Intervals: Practice Problem <center> <img src = 'www/img/CI_practice_problem_board_solution.png' style = 'height: 465px'> </center> --- class: gray ## Confidence Intervals: Practice Problem - Coded Solution ```{r, echo = TRUE} z_stat <- qnorm(.025, lower.tail = FALSE) st_error <- 3 / (sqrt(50)) upper <- 20 + (z_stat * st_error) lower <- 20 - (z_stat * st_error) upper lower ``` - With 95% confidence, we state the mean age of cows is between `r upper` and `r lower` - There is a 5% chance the true mean age is not within our CI <file_sep>/static/presentations/www/data/interactionFunction.R treatmentCombos <- function(vec, out = NULL, leaveOutBase = TRUE){ if(length(vec) > 0){ if(is.null(out)){ combo <- vec[1] newVec <- vec[-1] treatmentCombos(newVec, out = combo) } else{ doneTmp <- out combo <- append(out, vec[1]) combo <- append(combo, unlist(lapply(doneTmp, FUN = function(d) paste(d, vec[1], sep = '')))) newVec <- vec[-1] treatmentCombos(newVec, out = combo) } } else{ if(leaveOutBase){ return(out) } else{ return(c('(1)',out)) } } } buildTreatments <- function(myFactors){ lfactors <- tolower(myFactors) n <- 1:(length(lfactors)) treatment <- treatmentCombos(lfactors) #treatments <- data.frame(treatment = unlist(lapply(n, FUN = function(d) apply(combn(lfactors, d), 2, FUN = function(f) paste(f, collapse = '')))), stringsAsFactors = FALSE) tmp <- lapply(lfactors, function(d) unlist(lapply(treatment, FUN = function(e) ifelse(d %in% unlist(strsplit(e, "")), 1, -1)))) tmpDF <- data.frame(do.call(cbind, tmp)) colnames(tmpDF) <- toupper(myFactors) out <- cbind(treatment, tmpDF) tmpNull <- out[1,] tmpNull[,] <- -1 tmpNull$treatment <- '(1)' out <- rbind(tmpNull, out) return(out) } makeInteractionGrid <- function(myData, nonFactorCols = c('treatment')){ cols <- colnames(myData) cols <- cols[!cols %in% nonFactorCols] n <- 2:(length(cols)) interNames <- unlist(lapply(n, FUN = function(d) apply(combn(cols, d), 2, FUN = function(f) paste(f, collapse = '')))) for(i in interNames){ myData[,i] <- apply(myData[, unlist(strsplit(i,''))], 1, FUN = prod) } return(myData) } getEffects <- function(myData, obsColName = 'obs', nonFactorCols = c('treatment'), stErrorEst = NULL, keep = NULL, fractional = NULL){ cols <- colnames(myData) cols <- cols[!cols %in% c(obsColName, nonFactorCols)] lens <- unlist(lapply(cols, FUN = function(d) length(unlist(strsplit(d, ''))))) numMainEffects <- sum(lens[lens == 1]) effectVec <- unlist(lapply(cols, FUN = function(d) sum(myData[,d] * myData[,obsColName]) * (1 / (2^(numMainEffects-1))))) effectDF <- data.frame(term = cols, effect = effectVec, stringsAsFactors = FALSE) if(is.null(fractional) == FALSE){ effectDF$effect <- effectDF$effect*(1/fractional) } effectDF$coefficient <- effectDF$effect/2 effectDF <- rbind(data.frame(term = 'Constant', effect = NA, coefficient = mean(myData[,obsColName])), effectDF) if(is.null(keep) == FALSE) stErrorEst <- cols[!cols %in% keep] if(is.null(stErrorEst) == FALSE){ anovaTable <- data.frame(term = effectDF$term[effectDF$term != 'Constant'], stringsAsFactors = FALSE) anovaTable <- cbind(anovaTable, data.frame(SS = unlist(lapply(cols, FUN = function(d) (sum(myData[,d] * myData[,obsColName])^2) / (2^numMainEffects) )))) anovaTable$DF <- 1 anovaTable <- rbind(anovaTable, data.frame(term = 'Error', SS = sum(anovaTable$SS[anovaTable$term %in% stErrorEst]), DF = length(stErrorEst))) anovaTable <- anovaTable[!anovaTable$term %in% stErrorEst,] anovaTable$MS <- anovaTable$SS / anovaTable$DF anovaTable$F <- anovaTable$MS / anovaTable$MS[anovaTable$term == 'Error'] anovaTable$F[anovaTable$term == 'Error'] <- NA anovaTable$P <- NA anovaTable$P <- mapply(FUN = function(x,y) pf(abs(x), df1 = y, df2 = anovaTable$DF[anovaTable$term == 'Error'], lower.tail = FALSE), anovaTable$F, anovaTable$DF) effectDF$SE <- sqrt(anovaTable$MS[anovaTable$term == 'Error'] * (1/(2^numMainEffects))) if(is.null(fractional) == FALSE){ effectDF$SE <- effectDF$SE*(1/fractional) } effectDF$t <- effectDF$coefficient / effectDF$SE effectDF$P <- pt(abs(effectDF$t), df = nrow(myData) - (nrow(effectDF)-1), lower.tail = FALSE) * 2 if(is.null(fractional) == FALSE){ effectDF$P <- pt(abs(effectDF$t), df = (nrow(myData)*(1/fractional)) - ((nrow(effectDF)*(1/fractional))-1), lower.tail = FALSE) * 2 } effectDF <- effectDF[!effectDF$term %in% stErrorEst,] return(list(effects = effectDF, anova = anovaTable)) } else { return(effectDF) } }<file_sep>/docs/presentations/lecture_12.Rmd --- title: "ANOVA - Completely Randomized Design" author: "<NAME>" date: "2019-09-18" objectives: 'Understand the concept of ANOVA and Completely Randomized Designs; Understand the statistical model of ANOVA; Use the F-test and be able to read an F-table' homework: '13.2.1' type: 'presentation' output: xaringan::moon_reader: css: ["default", "www/se_template.css"] nature: highlightStyle: github highlightLines: true countIncrementalSlides: false --- ```{r, echo = FALSE} knitr::opts_chunk$set(fig.align = 'center', warning = FALSE, message = FALSE) ``` ## Where we are - Block 1: Hypothesis testing and regression - <strong>Block 2: Analysis of Variance (ANOVA) - WPR</strong> - Block 3: Design of Experiments (DOE) - Block 4: Statistical Quality Control (SQC) --- ## Analysis of Variance - Analysis of variance (ANOVA) is "a method of decomposing total variability in a set of observations...into component sums of squares that are associated with specific defined sources of variation" (Montgomery, p. 787) - In this lesson, we will use ANOVA to test for treatment effects in experiments - Ex) (Book example, p. 541) Does increasing the % of hardwood in a paper bag make it stronger? --- ## ANOVA Terminology - Factor = the thing that is changed in your experiment (the independent variable) - Ex1) The % of hardwood - Treatments = the levels of the factor - Ex1) 5%, 10%, 15%, 20% (4 levels) - Replicates = observations - Ex1) Observed tensile strength --- ## ANOVA and Randomization - We will be discussing ANOVA in the context of an experiment - Randomization is critical! - Observations must be taken in a random order - Treatments must also be applied as uniformly as possible (no bias) - We call experiments that meet these requirements Completely Randomized Design (CRD) --- ## How ANOVA Works - We often look at data like this: ```{r, echo = FALSE} df <- data.frame(concentration = c(5,5,5,5,5,5,10,10,10,10,10,10,15,15,15,15,15,15,20,20,20,20,20,20), observation = c(7,8,15,11,9,10,12,17,13,18,19,15,14,18,19,17,16,18,19,25,22,23,18,20)) df$concentration <- factor(df$concentration) df ``` --- ## How ANOVA Works - But we could also look at it like this: ```{r, echo = FALSE} library(magrittr) library(kableExtra) mat <- matrix(df$observation, ncol = 6) colnames(mat) <- 1:6 rownames(mat) <- c('5%' ,'10%','15%','20%') knitr::kable(mat, format = 'html', booktabs = T) %>% kable_styling(latex_options = c('hold_position')) %>% add_header_above(c('Concentration', 'Observations' = 6)) ``` --- ## How ANOVA Works - Or, like this: ```{r, echo = FALSE, fig.height = 6} library(ggplot2) ggplot(df) + geom_density(aes(x = observation)) + facet_grid(~concentration) + theme_minimal() ``` --- ## How ANOVA Works - Or, like this: ```{r, echo = FALSE, fig.height = 6} library(ggplot2) ggplot(df) + geom_boxplot(aes(x = concentration, y = observation)) + theme_minimal() ``` --- ## ANOVA - We want to test if the treatment has an effect... - We can think of this as a linear model: $$Y_{ij}=\mu+\tau_{i}+\epsilon_{ij}$$ - Where each treatment (i) has observations (j) --- ## ANOVA Assumptions - Observations are independent (addressed via randomization during experiment) - Residuals ($ \epsilon $) are NID - Residual plots - Shapiro-Wilk test `shapiro.test()` - Treatment groups have equal variance (homoscedasticity) - Bartlett test `bartlett.test()` --- ## ANOVA - If we want to test if the treatment has an effect, our hypothesis test is: $$H_{0}: \tau_{1}=\tau_{2}=...=\tau_{a}=0$$ $$H_{a}: \tau_{i}\neq0 \text{ for at least one }i$$ --- ## ANOVA - To test this hypothesis, we need a statistical test: F-test - The F-statistic is calculated by comparing 2 different kinds of variation in your data: - Variation caused by the treatment = $SS_{\text{Treatments}}$ - Variation caused by the error term = $SS_{E}$ $$F_{0} = \frac{\frac{SS_{\text{Treatments}}}{(a-1)}}{\frac{SS_{E}}{a(n-1)}}$$ - If $F_{0}$ is large, much of the variation in your data is caused by the treatment - Reject the null hypothesis, concluding your treatment has some effect --- ## ANOVA <center> <img src = 'www/img/anova_formulas.png' style = 'height: 500px'> </center> --- ## ANOVA: F-Statistic - We will use a new statistic to compare our test statistic to: F-statistic - Recall, our test statistic is the ratio of 2 variances - The F-statistic is a distribution created by dividing two variances - It tells us how likely (or unlikely) it is that we would see our calculated $F_{0}$ under the null hypothesis --- ## ANOVA: F-Statistic - Using the F-table requires calculation of the degrees of freedom: - df for Numerator = df for $SS_{\text{Treatments}}$ = $a-1$ - df for Denominator = df for $SS_{E}$ = $a(n-1)$ --- ## ANOVA: F-Statistic - F-table for $\alpha = 0.01$ <center> <img src = 'www/img/p_750.png'> </center> --- ## ANOVA Example - Use ANOVA to test if increasing the concentration of hardwood has an effect on the strength of paper bags - Use $\alpha = 0.01$ ```{r, echo = FALSE} knitr::kable(mat, format = 'html', booktabs = T) %>% kable_styling(latex_options = c('hold_position')) %>% add_header_above(c('Concentration', 'Observations' = 6)) ``` --- ## ANOVA Example $$H_{0}: \tau_{1}=\tau_{2}=...=\tau_{a}=0$$ - Or, the null hypothesis is that increasing the concentration of hardwood has no effect on the strength of a paper bag $$H_{a}: \tau_{i}\neq0 \text{ for at least one }i$$ - Or, the alternative hypothesis is that increasing the concentration of hardwood has some effect on the strength of a paper bag --- ## ANOVA Example - Calculate $SS_{\text{T}}$ $SS_{\text{T}} = 7^2 + 8^2 + ... + 20^2 - \frac{383^2}{24}$ ```{r} SSt <- sum(df$observation^2) - (sum(df$observation)^2)/nrow(df) SSt ``` --- ## ANOVA Example - Calculate $SS_{\text{Treatments}}$ $SS_{\text{Treatments}} = \frac{60^2+94^2+102^2+127^2}{6} - \frac{383^2}{24}$ ```{r} SStreatments <- (sum(df$observation[df$concentration == 5])^2 + sum(df$observation[df$concentration == 10])^2 + sum(df$observation[df$concentration == 15])^2 + sum(df$observation[df$concentration == 20])^2) / 6 - (sum(df$observation)^2)/nrow(df) SStreatments ``` --- ## ANOVA Example - Calculate $SS_{E}$ $SS_{E} = SS_{\text{T}} - SS_{\text{Treatments}} = 512.96 - 382.79 = 130.17$ ```{r} SSe <- SSt - SStreatments SSe ``` --- ## ANOVA Example - Calculate $F_{0}$ $F_{0} = \frac{\frac{SS_{\text{Treatments}}}{(a-1)}}{\frac{SS_{E}}{a(n-1)}}=\frac{\frac{382.79}{4-1}}{\frac{130.17}{4(6-1)}}$ ```{r} a <- 4 n <- 6 F0 <- (SStreatments/(a-1))/(SSe/(a*(n-1))) F0 ``` --- ## ANOVA Example <center> <img src = 'www/img/p_750_example.png'> </center> --- ## ANOVA Example - Conclusion: our calculated our calculated test statistic is larger than the $F_{\alpha}$ (19.60 > 4.94), so we can reject the null hypothesis, concluding that the concentration of hardwood has an effect on the strength of plastic bags. <center> <img src = 'www/img/anova_table.png'> </center> --- ## ANOVA Example - In R: ```{r} anova_model <- aov(observation ~ concentration, df) summary(anova_model) ``` --- ## ANOVA Example - Checking assumptions: ```{r} bartlett.test(observation ~ concentration, df) ``` - We fail to reject the null hypothesis that the variances of the samples are the same, concluding that it is plausible that the sample variances are, in fact, equal. This satisfies our homoscedasticity assumption --- ## ANOVA Example ```{r} shapiro.test(anova_model$residuals) ``` ```{r, fig.height = 3} plot(anova_model, which = 1) ``` - Residuals appear to be NID <file_sep>/static/presentations/www/data/baseball_exercise.R #---Baseball Exercise #-1) read in the data #-2) Use ggpairs() to figure out if any regressors are collinear #-3) Create a model to predict wins using runs scored, runs agianst, on-base percentage, sluggin percentage, and batting average #-4) Use the variance inflation factor to test for multicollinearity #-5) Print your model's summary and analyze the significance of the coefficients, the model utility test, and the R^2 value #-6) Check your residual assumptions #-7) Remove and regressors that might be causing multicollinarity problems and rebuild your model #-8) Analyze your new model (hint, you should be down to 4 regressors at this point) #-9) Check your new model's assumptions #-10) Remove any insignificant regressors from your model and rebuild #-11) Check the final model's assumptions #-12) Check for outliers using standardized residuals #-13) Check for influential points using Cook's Distance #-14) How is your final model? Would you use it? <file_sep>/content/about.md --- date: "2016-05-05T21:48:51-07:00" title: About --- ## The Course: SE375 Statistics for Engineers This course is an integral part of the Systems Engineering major that emphasizes both the statistical analyses of data and a statistical methodology important to systems analysis and design. The over-arching course goal is to develop cadets into critical consumers and providers of statistical information as it relates to the techniques, activities, and modeling applications that typify systems engineering concerns.. The course builds on the core probability and statistics course and introduces statistics applications fundamental to the design and analysis of simulations and engineering systems. Specific topics include point and interval estimation, parametric and non-parametric tests of hypotheses, analysis of variance, linear regression, and survey design of experiments, specifically analysis of power and determination of sample size. The course emphasizes the importance of knowing and understanding the assumptions associated with the use of inferential statistics as well as the usefulness of statistical software packages. The basic principles learned in this course will facilitate data analysis in support of Army acquisition and system redesign decision-making. Ethical implications in the analysis and presentation of experimental results, as well as interactions with decision makers, are addressed. ## Instructor Team <img style="float: left; margin-right: 20px; width: 250px" src="/images/kloo.jpg"> <NAME> earned a Bachelor’s of Business Administration from The College of William and Mary in 2011 and a Master’s in Policy Analytics from Carnegie Mellon University in 2014. Following his graduate studies, Ian became a Presidential Management Fellow which allowed him to work on data science projects throughout the DoD enterprise and the Federal Bureau of Investigation. Ian’s research focuses on applying emerging analytic methodologies to problems in the intelligence and special operations communities. Ian and his wife Nora are parents to one year old twins. <file_sep>/content/post/2021-05-20-lecture-12/index.Rmd --- title: "Lecture 12" category: "Module 2" author: "<NAME>" date: 2021-05-20 description: "Beginning of the ANOVA block." --- This lesson will transition us from the review block to a completely new topic: Analysis of Variance (ANOVA). ### Course Objectives: - Understand the concept of ANOVA and Completely Randomized Designs - Understand the statistical model of ANOVA - Use the F-test and be able to read an F-table ### [Slides](/presentations/lecture_12.html) ### [Notebook (HTML)](lesson_12.html) <h3><a href = 'lesson_12.ipynb' download>Notebook (Jupyter)</a> <file_sep>/content/post/2021-05-17-lecture-1/index.Rmd --- title: "Lecture 1" category: "Module 1" author: "<NAME>" date: 2021-05-17 description: "An overview of the course." --- The first lecture for SE375 will cover introductions, a review of the syllabus, and an overview of the course. ### Course Objectives: - Understand the goals, objectives, organization, and administrative requirements for SE375 - Check that course level requirements are met (R installed, textbook on hand) - Review basic concepts of statistics - Review confidence intervals ### [Slides](/presentations/lecture_1.html) <div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/448353267?badge=0&amp;autopause=0&amp;player_id=0&amp;app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="Welcome to SE375"></iframe></div><script src="https://player.vimeo.com/api/player.js"></script> <file_sep>/static/presentations/www/data/aliasFunction.R library(data.table) source(file = "interactionFunction.R") TC <- treatmentCombos(vec = c("a", "b", "c", "d", "e", "f", "g")) df <- buildTreatments(myFactors = c("A", "B", "C", "D", "E", "F", "G")) df <- makeInteractionGrid(myData = df) tcs <- c("def", "afg", "beg", "abd", "cdg", "ace", "bcf", "abcdefg", "abcg", "bcde", "acdf", "cefg", "abef", "bdfg", "adeg", "(1)") # add the remaining treatment combinations design_tcs <- match(tcs, df$treatment) # this returns the row numbers of the TCs z <- list() # create an empty list to fill in the loop below # The loop below returns the column name (effect) for all columns that are all +1s for the subsetted design matrix for (i in seq_along(2:length(colnames(df)))) { z[i-1] <- ifelse(identical(df[ design_tcs , i ] , rep(1, 2^(7-3))), colnames(df[i]), NA) } def_rel <- unlist(z[!is.na(z)]) def_rel ali <- function(dr, e) { ifelse(e %in% unlist(strsplit(dr, split = "")), paste(unlist(strsplit(dr, split = ""))[!(unlist(strsplit(dr, split = "")) %in% e)],collapse=""), paste0(dr, e)) } # "A" %in% unlist(strsplit("ABCG", split = "")) # unlist(strsplit("ABCG", split = ""))[!(unlist(strsplit("ABCG", split = "")) %in% "A")] # paste0("ABCG", "F") ali("ABCG","A") #drops "A" # ali(dr= "ABCG", e="F") # adds "F" aliases <- function(dr, e) { lapply(dr, ali, e) } z <- lapply(colnames(df[2:8]), aliases, dr=def_rel) #takes each main effect and finds the alias from each defining relation z <- rbindlist(z) rownames(z) <- colnames(df[2:8]) z <file_sep>/content/stats_concepts.md --- date: "2016-05-05T21:48:51-07:00" title: Stats Concepts --- MA206 (which is a pre-requisite to this course) covers a large variety of statistical concepts. The resources here are meant to reenforce those concepts that are especially important for SE370. These resources are here to help you develop your foundation. ## Hypothesis Testing <div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/448350048?badge=0&amp;autopause=0&amp;player_id=0&amp;app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="hypothesis_testing_R"></iframe></div><script src="https://player.vimeo.com/api/player.js"></script> ## Linear Regression <div style="padding:75% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/552583153?badge=0&amp;autopause=0&amp;player_id=0&amp;app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="linear_regression_part_1.mp4"></iframe></div><script src="https://player.vimeo.com/api/player.js"></script> <file_sep>/docs/presentations/www/data/tsVis.Rmd --- title: "Special Topic: Time Series Visualization" author: "<NAME>" date: "December 2019" output: rmarkdown::html_document: theme: lumen --- ## Intro As an analyst, you will come across time series data - probably often. Knowing some tricks for munging (cleaning/working with) and visualizing time series data will serve you well. This tutorial will cover the general topics you need to know to be able to work with and visualize time series data. All code will be explained to give you a good understanding of what we are actually doing. ## Data The data for this tutorial comes from NOAA (National Oceanic and Atmospheric Administration). It contains daily snowfall totals for Central Park. Reading in the data: ```{r} library(data.table) snow <- fread('~/Downloads/noaa_snow_ny.csv') head(snow) ``` We have a column for name (which we can disregard), a column for date, and a column with the amount of snow that fell that day (in inches). For now, let's drop the name column, rename the other columns to lowercase, and move forward: ```{r} snow <- snow[,c('DATE','SNOW')] colnames(snow) <- c('date','snow') head(snow) ``` ## Dates in R: A huge pain Aside from a few specialized software packages built for time series analysis, most scripting languages require some finesse to get dates working correctly. Here is a quick run-down of how to work with dates in R. Let's look at the date column of the snow data: ```{r} head(snow) ``` Those look like dates, but they aren't: ```{r} class(snow$date) ``` R thinks of these dates as characters. This is a defense mechanism that R employs to make sure you can read in data of any type. R doesn't assume your data is actually a date unless you specifically tell it to. This should be familiar - Excel does the same thing. Fortunately, just like Excel, R has a date class that you can convert to: ```{r} snow$newDate <- as.Date(snow$date) head(snow) ``` As you can see, the data doesn't look different, but R now knows that we want to treat the dates as dates. Why does this matter? Here's an example: ```{r, error = TRUE} max(snow$date) - min(snow$date) max(snow$newDate) - min(snow$newDate) ``` The first attempt fails because R doesn't know how to subtract characters from each other. R does, however, know how to subtract dates. This is just a small example to show you that formatting your data as a date is very important when working with time series data. Let's rename our columns so that we only have one date column that contains properly formatted data: ```{r} snow$date <- as.Date(snow$date) snow$newDate <- NULL head(snow) ``` ## Time Series Data Structures Time series data often arrives in a data frame with a row for each observation. While the data looks clean, we need to take a closer look: ```{r} snow[1:10,] ``` This data set only contains data when there is snow on a given day. The days that don't have snow are simply left out of the data. If you attempt to visualize this data, you might get something like this: ```{r} barplot(snow$snow, names = snow$date) ``` This is definitely a representation of our data, but it is very misleading. The x axis is supposed to represent dates, but it is only showing the dates where there was snow. If we just want a visualization, we can solve the problem by using ggplot: ```{r, warning = FALSE, message = FALSE} library(ggplot2) ggplot(data = snow, aes(x = date, y = snow)) + geom_bar(stat = 'identity') ``` This is a much more realistic representation of our data. It only snows a few days a year in NY - this is clear from looking at this visualization. In the above example, ggplot recognizes that there are holes in your data that you want to display. Some packages are not so friendly, and you don't want to leave things up to chance, so you will want to reformat your time series data to include gaps. The easiest way to do this is with a `tidyr` function called `complete()`: ```{r, warning = FALSE, message = FALSE} library(tidyr) snow <- complete(snow, date = seq.Date(min(date), max(date), by="day")) snow$snow[is.na(snow$snow)] <- 0 print(snow) ``` OK, now our data represents a full daily time series. ## Moving between time steps (aggregation) In R, we like to work with data frames because they are almost universally accepted by various functions and are familiar/easy to comprehend. When working with time series data, it can be useful to use another data type called `xts` (extended time series). This data type is slightly less intuitive and easy to grasp, but has some very useful properties. We can take our data frame and create a new object using `xts`: ```{r, warning = FALSE, message = FALSE} library(xts) ts <- xts(snow$snow, order.by=snow$date) head(ts) ``` This doesn't look too different from our data frame, but R now considers this to be a different class: ```{r} class(ts) ``` These time series objects are very useful for a number of reasons. One typical operation you will want to do with time series data is to aggregate the data to different time steps. This can a big pain without using `xts`. In `xts`, we can use the `apply.xxx` family of functions: ```{r, warning = FALSE, message = FALSE} monthly <- apply.monthly(ts, sum) head(monthly) ``` Now we have data that is aggregated to the month scale. And similarly, we can translate to the annual scale: ```{r, warning = FALSE, message = FALSE} annual <- apply.yearly(ts, sum) head(annual) ``` That might seem somewhat easy to do without `xts`, but consider moving to a weekly scale: ```{r, warning = FALSE, message = FALSE} weekly <- apply.weekly(ts, sum) head(weekly) ``` This aggregation would have been very difficult without `xts`. Finally, you can easily translate back from a time series object to a data frame using: ```{r, warning = FALSE, message = FALSE} annualDF <- fortify.zoo(annual) colnames(annualDF) <- c('date','snow') head(annualDF) ``` Moving between time steps easily is critical to good time series analysis. It is easy to miss a trend if you are in the wrong scale. For example, temperature in NY is seasonal, but it is only seasonal by month. If you look at average annual temperatures, there is (almost) no trend in the data. With weather, this is obvious because we live with weather every day. However, you may not understand your data this well in practice. The best idea is to try a few different aggregations when working with time series data to see if you can find anything interesting. ## Decomposition Another popular method for dealing with time series data is decomposition. The idea is to split out the seasonal oscillation in data, leaving you with a "true" trend line. The easiest way to do this in R is to convert to a `ts` object and use the `decompose()` function: ```{r} monthlyDF <- fortify.zoo(monthly) colnames(monthlyDF) <- c('date','snow') mo_ts <- ts(monthlyDF$snow, frequency = 12) decomp <- decompose(mo_ts) plot(decomp) ``` The trend appears to show some change over time, but it doesn't look like we are systematically getting more or less snow over time. ## Visualization Why are we using bar charts? Because we're using discrete time steps (as opposed to continuous time). You will often see data visualized like this: ```{r, warning = FALSE, message = FALSE} library(lubridate) df <- annualDF[1:(nrow(annualDF)-1),] df$year <- year(df$date) ggplot(data = df, aes(x = year, y = snow)) + geom_line() + geom_point() + scale_x_continuous(breaks = df$year) + ylim(0,60) ``` This is a common, but bad representation of our data. The problem is that we are using a continuous line to represent a discrete event. For example, this plot suggests that it snowed about 5 inches between June and August of 2000...this is obviously not true. Things like this are easy to see when it comes to snowfall, but could potentially be a big problem when you don't fully understand your data. This might seem like a weird thing to mention since you see data like this all the time, but you should be thinking hard about the way that you are representing data. I will argue that this is a much better interpretation of the data: ```{r} ggplot(data = df, aes(x = year, y = snow)) + geom_bar(stat = 'identity') + scale_x_continuous(breaks = df$year) + ylim(0,60) ``` Adding some finishing touches: ```{r} ggplot(data = df, aes(x = year, y = snow)) + geom_bar(stat = 'identity') + scale_x_continuous(breaks = df$year) + ylim(0,60) + theme_minimal(base_size = 12) + ggtitle('Annual Snowfall in Central Park') + theme(axis.text.x = element_text(angle=45, hjust = 1), panel.grid.minor.x = element_blank(), plot.title = element_text(hjust = 0.5)) + ylab('Total Snowfall (in)') + xlab('Year') ``` ### Interactive Plots Interactive plots can be useful in presentations and applications. You can easily make your `ggplots` interactive with `plotly` using `ggplotly()`: ```{r, warning = FALSE, message = FALSE} library(plotly) g <- ggplot(data = df, aes(x = year, y = snow)) + geom_bar(stat = 'identity') + scale_x_continuous(breaks = df$year) + ylim(0,60) + theme_minimal(base_size = 12) + ggtitle('Annual Snowfall in Central Park') + theme(axis.text.x = element_text(angle=45, hjust = 1), panel.grid.minor.x = element_blank(), plot.title = element_text(hjust = 0.5)) + ylab('Total Snowfall (in)') + xlab('Year') ggplotly(g) ``` You can also use packages like `c3`: ```{r, warning = FALSE, message = FALSE} library(c3) df %>% c3(x = 'year', y = 'snow') %>% c3_bar() %>% grid('y') ``` Or `highcharter` (note, this `highcharts` requires a license for commercial use): ```{r, warning = FALSE, message = FALSE} library(highcharter) hchart(df, 'column', hcaes(x = 'year', y = 'snow')) ``` <file_sep>/docs/presentations/www/code/lab_shell.Rmd --- title: "DOE Lab" date: "November 2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` An article in Biotechnology Progress (December 2002, Vol. 18(6), pp. 1170-1175) presented a \(\ 2^{7-3} \) fractional factorial design to evaluate factors promoting astaxanthin production. As described in Algal Research (Volume 18, September 2016, Pages 175-190), "astaxanthin is considered the most powerful antioxidant in nature, serving the role of a highly efficient scavenger of free radicals build up within the human body. Astaxanthin is a substance that protects the skin against UV-induced photo-oxidation and it is used for anti-tumor therapies and prevention - treatment of neural damage interrelated with age-related macular degeneration, Alzheimer and Parkinson diseases. Furthermore, it is considered as a natural superfood destined to enhance athletic performance by increasing stamina and reducing the time of muscle recovery." [source: https://www.sciencedirect.com/science/article/pii/S2211926416301965] The data are from the fractional factorial experiment are shown in the following table. ```{r, echo=FALSE, fig.cap="**14-92 Data**", out.width = '70%'} knitr::include_graphics("14_92_data.png") ``` The factors and levels in this experiment are shown here: ```{r, echo=FALSE, fig.cap="**14-92 Factors**", out.width = '40%'} knitr::include_graphics("14_92_factors.png") ``` We would like to anaylze the results of this experiment, but we don't know which defining relations were used in the experimental design. As a result, we also don't know which effects are aliased, which is needed in order to analyze the results of the experiment. Make sure that interactionFunction.R is stored in the same folder as this file, then run the chunk below to generate the full design matrix. ```{r} source(file = "interactionFunction.R") TC <- treatmentCombos(vec = c("a", "b", "c", "d", "e", "f", "g")) df <- buildTreatments(myFactors = c("A", "B", "C", "D", "E", "F", "G")) df <- makeInteractionGrid(myData = df) ``` If we assume that the principal fraction of the full design matrix was used to select the fractional factorial design, we can identify the effect contrast columns that are all positive, thereby identifying the complete defining relation. With the complete defining relation, we can then identify the alias structure. Create a character vector of the treatment combinations at which observations were made in the experiment. For instance, the first treatment combination is "def". Then use the match() function to return the index of all rows of the complete design matrix for these treatment combinations. ```{r} tcs <- c("def", ) # add the remaining treatment combinations design_tcs <- match(tcs, df$treatment) # this returns the row numbers of the TCs ``` Now identify the columns that are all +1's for the rows identified above, since these will be our complete defining relation. ```{r} z <- list() # create an empty list to fill in the loop below # The loop below returns the column name (effect) for all columns that are all +1s for the subsetted design matrix for (i in seq_along(2:length(colnames(df)))) { z[i-1] <- ifelse(identical(df[ design_tcs , i ] , rep(1, 2^(7-3))), colnames(df[i]), NA) } def_rel <- unlist(z[!is.na(z)]) def_rel ``` ### (a) Using the defining relations, identify the alias structure for all main and two-factor effects. (No need to include terms beyond two-factor interaction effects). Now subset the full design matrix by the observed treatment combinations and add in columns for the two response variables observed in the experiment. ```{r} df1 <- df[ design_tcs , c(1:8)] df1$weight <- c(4.2,4.4,7.8,14.9,25.3,26.7,23.9,21.9,24.3,20.5,10.8,20.8,13.5,10.3,23,12.1) df1$cellular <- c(10.8,24.9,27.3,36.3,112.6,159.3,145.2,234.2,72.1,112.2,22.5,149.7,140.1,47.3,153.2,35.2) df1 ``` ###(b) Estimate the main and two-factor interaction effects using regression. Recall that there are two response variables (you need two models) ```{r} # Regression models and output ``` ```{r} # Magnitude of effects and aliases on weight: effects1 <- ``` ```{r} # Magnitude of effects and aliases on cellular content: effects2 <- ``` ###(c) Plot the effect estimates on a normal probability scale and interpret the results. ```{r} df1 <- qqnorm(effects1, ylim = c(-10,15)) qqline( effects1 ) text( df1$x, df1$y, names(effects1), pos=1 ) df1 <- qqnorm(effects2, ylim = c(-40,70)) qqline( effects2 ) text( df1$x, df1$y, names(effects2), pos=1 ) ```
3edeeb22e4bf03d13f9aa2d50339c16346cf3a31
[ "Markdown", "R", "RMarkdown" ]
12
Markdown
iankloo/course_site_demo
ebd380c60fc2af93797a629d6165a64ad4e239dd
70ca4ca3ef2217275c37a237afc9a767bf4e9877
refs/heads/master
<file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2015, 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; var log4js = require("log4js"), async = require("async"), nconf = require('nconf'), _ = require('underscore'), request = require("request"), tiamUtil = require("../util/tiam-util"), pipelineUtil = require("../util/pipeline-util") ; var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "lib.event.pipeline" ; var successColor = "#00B198"; var failedColor = "#f04e36"; var abortedColor = "#f18f27"; module.exports = function(requestId, event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + "] "; var pipelineId; if (event.pipeline) { pipelineId = event.pipeline.id; } var stageName; if (event.stage) { stageName = event.stage.name; } logger.info(logPrefix + "[" + requestId + "]Pipeline " + pipelineId + " - Event " + event.event + " : " + stageName); if (event.event == "stageStarted") { createMessageForStageStarted(event, toolchainCredentials, callback); } else if (event.event == "stageCompleted") { createMessageForStageCompleted(event, toolchainCredentials, callback); } else if (event.event == "jobStarted") { createMessageForJobStarted(event, toolchainCredentials, callback); } else if (event.event == "jobCompleted") { createMessageForJobCompleted(event, toolchainCredentials, callback); } else { // Default ! logger.info(logPrefix + "Slack Message Structure created for Pipeline " + pipelineId + " - Event " + event.event + " : " + stageName); callback(null, {username: "Pipeline", text: JSON.stringify(event)}); } } function formatDurationWords(duration) { var durationString = ""; // DurationFormatUtils.formatDurationWords(duration, true, true); var x = Math.floor(duration / 1000); var seconds = x % 60 x = Math.floor(x/60); var minutes = x % 60 x = Math.floor(x/60); var hours = x % 24 x = Math.floor(x/24); var days = x if (days > 0) { durationString += days; if (days > 1) { durationString += " days"; } else { durationString += " day"; } } if (hours > 0) { durationString += " "; durationString += hours; if (hours > 1) { durationString += " hours"; } else { durationString += " hour"; } } if (minutes > 0) { durationString += " "; durationString += minutes; if (minutes > 1) { durationString += " minutes"; } else { durationString += " minute"; } } if (seconds > 0) { durationString += " "; durationString += seconds; if (seconds > 1) { durationString += " seconds"; } else { durationString += " second"; } } if (durationString.length == 0) { durationString = "0 second"; } return durationString; } function getJobExecutionUrl(dashboard_url, pipeline, stage, job, jobExecution) { if (dashboard_url) { var url = dashboard_url + "/"; url += stage.id; url += "/"; url += job.id; if (jobExecution) { url += "/"; url += jobExecution.jobExecutionId; } return url; } else { var url = "http://undefined/pipelines" url += "/" + pipeline.id; url += "/"; url += stage.id; url += "/"; url += job.id; if (jobExecution) { url += "/"; url += jobExecution.jobExecutionId; } return url; } } function getPreTextForStage(dashboard_url, event, statusText) { var executionUrl = ""; if (!_.isEmpty(event.execution.jobExecutions)) { // Just use the first jobExecution to compute the URL var jobExecution = event.execution.jobExecutions[0]; var job = _.findWhere(event.stage.jobs, {"id": jobExecution.jobId}); if (!_.isUndefined(job) && _.isString(jobExecution.jobId) && (jobExecution.jobId.length > 0)) { executionUrl = getJobExecutionUrl(dashboard_url, event.pipeline, event.stage, job, jobExecution); } } var pretext = "Stage *'" + event.stage.name + "'* #" + event.execution.number + " has _*<" + executionUrl + "|" + statusText + ">*_"; return pretext; } function getStringForInput(pipelineInfo, event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".getStringForInput] "; var dashboard_url = pipelineInfo.dashboard_url, api_url = pipelineInfo.api_url ; if (api_url && !_.isEmpty(event.execution.inputs)) { async.map(event.execution.inputs, function(input, asyncCallback) { pipelineUtil.getPipelineStageInput(api_url, event.pipeline.id, event.execution.stageId, input.inputId, toolchainCredentials, function(err, stageInput) { logger.debug(logPrefix + JSON.stringify(stageInput)); if (err) { // log error for stage input retrieval logger.error(logPrefix + "Error while searching for stageInput of stage " + event.execution.stageId + " in pipeline " + event.pipeline.id + ":" + err.toString()); return asyncCallback(); } if (stageInput && stageInput.type == "scm" && stageInput.scmSource.type == "GitHub") { // We only deal with GitHub scm here // url contains .git at the end - remove it to compute the url according to the branch var scmUrl = stageInput.scmSource.url; if (scmUrl.endsWith(".git")) { scmUrl = scmUrl.substring(0, scmUrl.length - 4); } var inputString = "_*<" + scmUrl + "/tree/" + stageInput.scmSource.branch + "|"; inputString += stageInput.scmSource.url + " [" + stageInput.scmSource.branch + "]>*_"; return asyncCallback(null, inputString); } if (stageInput && stageInput.type == "job") { // The input here is the output of another job/stage // retrieve the job name and use the revision id pipelineUtil.getPipelineStageJob(api_url, event.pipeline.id, stageInput.stageId, stageInput.jobId, toolchainCredentials, function(err, job) { if (err) { logger.error(logPrefix + "Error while searching for stage information for stage " + stageInput.stageId + " in pipeline " + event.pipeline.id + ":" + err.toString()); return asyncCallback(); } // <dashboard_url>/<stageId>/<jobId>/<input.revision>/artifacts var inputString = "_*<" + dashboard_url + "/" + stageInput.stageId + "/" + stageInput.jobId + "/" + input.revisionId + "/artifacts |"; inputString += job.componentName + " " + input.revisionId + ">*_"; return asyncCallback(null, inputString); }); } else { // log no stage input logger.debug(logPrefix + "No stageInput processable found for stageInput of stage " + event.execution.stageId + " in pipeline " + event.pipeline.id); return asyncCallback(); } }); }, function(err, results) { if (err) { logger.error(logPrefix + "Error while creating string for stage inputs:" + err.toString()); return callback(err); } var result = ""; _.each(results, function(input, index) { if (input) { if (result.length > 0) { result += ", "; } result += input; } }); callback(null, result); }); } else { callback(); } } function getRequestor(event, toolchainCredentials, callback) { var requestedBy = event.execution.requestedBy; if (requestedBy) { if (requestedBy == null || requestedBy == "") { callback(null, "pipeline"); } else { // Use the user_info in the event for the requestor information if (event.user_info) { callback(null, event.user_info.user_name); } else { callback(null, requestedBy); } } } else { callback(null, "pipeline"); } } function createMessageForStageStarted(event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".createMessageForStageStarted] "; async.auto({ pipelineInfo: function(asyncCallback) { pipelineUtil.getPipelineInfo(event.pipeline.id, toolchainCredentials, asyncCallback); }, inputString: ["pipelineInfo", function(asyncCallback, r) { getStringForInput(r.pipelineInfo, event, toolchainCredentials, asyncCallback); }], requestedBy: function(asyncCallback) { getRequestor(event, toolchainCredentials, asyncCallback); } }, function(err, results) { if (err) { callback(err); } else { var message = {}; message.username = "Pipeline '" + results.pipelineInfo.label + "'"; message.icon_url = nconf.get("icons:pipeline"); // Pretext & statusColor var statusColor; var statusText = "STARTED"; var pretext = getPreTextForStage(results.pipelineInfo.dashboard_url, event, "STARTED"); var inputString = results.inputString; if (inputString && inputString.length > 0) { inputString = "\nInput: " + inputString; } var startedString = ""; if (event.execution.createdAt != null) { startedString += "\nStarted: " + new Date(event.execution.createdAt).toUTCString(); } var text = "Triggered by _*" + results.requestedBy + "*_" + inputString + startedString; var attachment = {}; attachment.fallback = "Stage '" + event.stage.name + "' #" + event.execution.number + " " + statusText; attachment.pretext = pretext; //attachment.color = statusColor; attachment.text = text; attachment.mrkdwn_in = ["pretext", "text"]; // attachment needs to be stringify in order to be processed message.attachments = JSON.stringify([attachment]); callback(null, message); } }); } function createMessageForStageCompleted(event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".createMessageForStageCompleted] "; async.auto({ pipelineInfo: function(asyncCallback) { pipelineUtil.getPipelineInfo(event.pipeline.id, toolchainCredentials, asyncCallback); }, inputString: ["pipelineInfo", function(asyncCallback, r) { getStringForInput(r.pipelineInfo, event, toolchainCredentials, asyncCallback); }], requestedBy: function(asyncCallback) { getRequestor(event, toolchainCredentials, asyncCallback); } }, function(err, results) { if (err) { callback(err); } else { var message = {}; message.username = "Pipeline '" + results.pipelineInfo.label + "'"; message.icon_url = nconf.get("icons:pipeline"); // Pretext & statusColor var statusColor; var statusText; if (event.execution.successful) { statusText = "PASSED"; statusColor = successColor; } else { statusText = "FAILED"; statusColor = failedColor; } var pretext = getPreTextForStage(results.pipelineInfo.dashboard_url, event, statusText); var inputString = results.inputString; if (inputString && inputString.length > 0) { inputString = "\nInput: " + inputString; } var startedString = ""; if (event.execution.createdAt != null) { startedString += "\nStarted: " + new Date(event.execution.createdAt).toUTCString(); } var durationString = ""; if (event.execution.createdAt != null && event.execution.completedAt != null) { var duration = event.execution.completedAt - event.execution.createdAt; durationString = "\nDuration: " + formatDurationWords(duration); } var jobStatuses = ""; if (!event.execution.successful) { if (!_.isEmpty(event.execution.jobExecutions)) { _.map(event.execution.jobExecutions, function(jobExecution) { var job = _.findWhere(event.stage.jobs, {"id": jobExecution.jobId}); if (!_.isUndefined(job) && _.isString(jobExecution.jobId) && (jobExecution.jobId.length > 0)) { var jobName = job.componentName; var jobStatusText; if (_.isUndefined(jobExecution.successful) || _.isNull(jobExecution.successful)) { jobStatusText ="not completed"; } else if (jobExecution.successful) { jobStatusText = "passed"; } else { jobStatusText = "failed"; } var jobExecutionUrl = getJobExecutionUrl(results.pipelineInfo.dashboard_url, event.pipeline, event.stage, job, jobExecution); jobStatuses += "\nJob *'" + jobName + "'* has _*<" + jobExecutionUrl + "|" + jobStatusText + ">*_"; } }) } } var text = "Triggered by _*" + results.requestedBy + "*_" + inputString + startedString + durationString + jobStatuses; var attachment = {}; attachment.fallback = "Stage '" + event.stage.name + "' #" + event.execution.number + " " + statusText; attachment.pretext = pretext; attachment.color = statusColor; attachment.text = text; //attachment.author_name = "pipeline"; //attachment.author_icon = "pipeline icon" attachment.mrkdwn_in = ["pretext", "text"]; // attachment needs to be stringify in order to be processed message.attachments = JSON.stringify([attachment]); callback(null, message); } }); } function createMessageForJobStarted(event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".createMessageForJobStarted] "; async.parallel({ pipelineInfo: function(asyncCallback) { pipelineUtil.getPipelineInfo(event.pipeline.id, toolchainCredentials, asyncCallback); }, requestedBy: function(asyncCallback) { getRequestor(event, toolchainCredentials, asyncCallback); } }, function(err, results) { if (err) { callback(err); } else { var message = {}; message.username = "Pipeline '" + results.pipelineInfo.label + "'"; message.icon_url = nconf.get("icons:pipeline"); var job = event.job; var jobExecution = _.findWhere(event.execution.jobExecutions, {"jobId": job.id}); var preStatusText = " has "; var statusText; if (jobExecution) { if (jobExecution.status == "OK") { statusText = "STARTED"; } if (jobExecution.status == "FAILED") { statusText = "FAILED"; } else if (jobExecution.status == "CONFIGURING") { preStatusText = " has been " statusText = "CONFIGURED"; } else if (jobExecution.status == "QUEUED") { preStatusText = " has been " statusText = "QUEUED"; } else { statusText = jobExecution.status; } } var executionUrl = getJobExecutionUrl(results.pipelineInfo.dashboard_url, event.pipeline, event.stage, event.job, jobExecution); var pretext = "Job *'" + event.job.componentName + "'* in Stage *'" + event.stage.name + "'* #" + event.execution.number + preStatusText + "_*<" + executionUrl + "|" + statusText + ">*_"; // No start time for jobStarted event var text = "Triggered by _*" + results.requestedBy + "*_"; var attachment = {}; attachment.fallback = "Job '" + event.job.componentName + "' in Stage '" + event.stage.name + "' #" + event.execution.number + " " + statusText; attachment.pretext = pretext; attachment.text = text; attachment.mrkdwn_in = ["pretext", "text"]; // attachment needs to be stringify in order to be processed message.attachments = JSON.stringify([attachment]); callback(null, message); } }); } function createMessageForJobCompleted(event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".createMessageForJobCompleted] "; async.parallel({ pipelineInfo: function(asyncCallback) { pipelineUtil.getPipelineInfo(event.pipeline.id, toolchainCredentials, asyncCallback); }, requestedBy: function(asyncCallback) { getRequestor(event, toolchainCredentials, asyncCallback); } }, function(err, results) { if (err) { callback(err); } else { var message = {}; message.username = "Pipeline '" + results.pipelineInfo.label + "'"; message.icon_url = nconf.get("icons:pipeline"); var job = event.job; var jobExecution = _.findWhere(event.execution.jobExecutions, {"jobId": job.id}); var statusText; var statusColor; if (jobExecution) { if (jobExecution.successful) { statusText = "PASSED"; statusColor = successColor; } else { statusText = "FAILED"; statusColor = failedColor; } if (jobExecution.status == "ABORTED") { statusText = "ABORTED"; statusColor = abortedColor; } } var executionUrl = getJobExecutionUrl(results.pipelineInfo.dashboard_url, event.pipeline, event.stage, event.job, jobExecution); var pretext = "Job *'" + event.job.componentName + "'* in Stage *'" + event.stage.name + "'* #" + event.execution.number + " has _*<" + executionUrl + "|" + statusText + ">*_"; var startedString = ""; var durationString = ""; if (jobExecution) { if (jobExecution.startTime != null) { startedString += "\nStarted: " + new Date(jobExecution.startTime).toUTCString(); } if (jobExecution.duration != null) { durationString = "\nDuration: " + formatDurationWords(jobExecution.duration); } } var text = "Triggered by _*" + results.requestedBy + "*_" + startedString + durationString; var attachment = {}; attachment.fallback = "Job '" + event.job.componentName + "' in Stage '" + event.stage.name + "' #" + event.execution.number + " " + statusText; attachment.color = statusColor; attachment.pretext = pretext; attachment.text = text; attachment.mrkdwn_in = ["pretext", "text"]; // attachment needs to be stringify in order to be processed message.attachments = JSON.stringify([attachment]); callback(null, message); } }); }<file_sep>#!/bin/bash set +x git clone "https://$IDS_USER:$IDS_PASS@github.ibm.com/org-ids/otc-system-test" set -x otc-system-test/scripts/systemTests.sh -c otc-slack-broker -p $TEST_PASSWORD ys1-int <file_sep>#!/bin/bash ############################################################################### # Licensed Materials - Property of IBM # (c) Copyright IBM Corporation 2015, 2015. All Rights Reserved. # # Note to U.S. Government Users Restricted Rights: # Use, duplication or disclosure restricted by GSA ADP Schedule # Contract with IBM Corp. ############################################################################### usage () { cat <<'USAGE' SYNOPSIS -------- export UCD_COMPONENT=... export UCD_USERNAME=... export UCD_PASSWORD=... echo "<a commit sh>-$(date +%Y%m%d%H%M%Z)" > .pipeline_build_id pipeline.publish.sh ENVIRONMENT VARIABLES --------------------- Most options are specified as environment variables: UCD_COMPONENT The component in UCD to publish a version to. UCD_USERNAME The username to use when publishing to UCD. UCD_PASSWORD The password to use when publishing to UCD. FILES ----- .pipeline_build_id The contents of this file will contain the name of the pipeline build. This file is required in order for a version to be published, and should contain a Git commit id, followed by a dash (-) followed by a timestamp (with timezone). DESCRIPTION ----------- Publishes the contents of the working directory to the UCD_COMPONENT component in the https://ucdeploy.swg-devops.com UCD server. The name of the version will be TIPS ---- This script is intended to be run as part of a Pipeline. If it's not, make sure to specify all of the environment variables in the usage above. USAGE } SCRIPT_NAME=$(basename "$0") UCD_SERVER_URL=https://ucdeploy.swg-devops.com UCD_CLIENT_URL=https://ucdeploy.swg-devops.com/tools/udclient.zip TMPDIR=/tmp/pipeline.publish.$$ main () { echo "OTC-SLACK-BROKER-$BUILD_NUMBER-$(date +%Y%m%d%H%M%Z)" > .pipeline_build_id cat .pipeline_build_id if ! [ -s .pipeline_build_id ]; then usage >&2 echo ".pipeline_build_id: Pipeline build id file not found or empty" >&2 return 1 fi if ! [ "$UCD_USERNAME" ]; then usage >&2 echo "Required environment variable, UCD_USERNAME is not specified" >&2 return 1 fi if ! [ "$UCD_PASSWORD" ]; then usage >&2 echo "Required environment variable, UCD_PASSWORD is not specified" >&2 return 1 fi if ! [ "$UCD_COMPONENT" ]; then usage >&2 echo "Required environment variable, UCD_COMPONENT is not specified" >&2 return 1 fi echo "- Fetching the UCD client" if ! curl "$UCD_CLIENT_URL" > "$TMPDIR/udclient.zip"; then echo "$UCD_CLIENT_URL: Could not fetch the UCD client." >&2 return 1 fi echo "- Installing the UCD client" if ! unzip -d "$TMPDIR/udclient" "$TMPDIR/udclient.zip"; then echo "$TMPDIR/udclient.zip: Could not expand the UCD client to a temporary location, $TMPDIR/udclient" return 1 fi UCD=$TMPDIR/udclient/udclient/udclient # Just as a sanity check, silently try running UCD. If there were any # problems, let the user know by running it again; not silently. # if ! "$UCD" >/dev/null 2>&1; then "$UCD" echo "$UCD: Could not run UCD" >&2 return 1 fi VERSION_NAME=$(<.pipeline_build_id) echo "- Creating a new version in UCD, $VERSION_NAME" if ! "$UCD" \ -weburl "$UCD_SERVER_URL" \ -username "$UCD_USERNAME" \ -password "$<PASSWORD>" \ createVersion \ -component "$UCD_COMPONENT" \ -name "$VERSION_NAME" then echo "$VERSION_NAME: Could not create a new version in the UCD component, $UCD_COMPONENT" >&2 return 1 fi echo "- Importing sources into verion $VERSION_NAME of $UCD_COMPONENT" if ! "$UCD" \ -weburl "$UCD_SERVER_URL" \ -username "$UCD_USERNAME" \ -password "$<PASSWORD>" \ addVersionFiles \ -component "$UCD_COMPONENT" \ -version "$VERSION_NAME" \ -saveExecuteBits true \ -base "$PWD" then echo "$VERSION_NAME: Could not import sources into a version of UCD component, $UCD_COMPONENT" >&2 return 1 fi # All done. echo "- All done." } if ! mkdir -p "$TMPDIR"; then echo "$TMPDIR: Could not create a temporary directory" >&2 exit 1 fi main "$@" RESULT=$? rm -rf "$TMPDIR" exit "$RESULT" <file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; var log4js = require("log4js"), nanoDocUpdater = require("nano-doc-updater"), nconf = require("nconf"), request = require("request"), _ = require("underscore"), Slack = require("slack-node") ; var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "lib.client.slack-client"; module.exports.getSlackUser = getSlackUser; module.exports.getOrCreateSlackChannel = getOrCreateSlackChannel; module.exports.postMessage = postMessage; module.exports.updateChannelTopicAndPurpose = updateChannelTopicAndPurpose; module.exports.validateChannelName = validateChannelName; var slack_url = nconf.get("services:slack_api"); if (slack_url) { // ensure final / is there if (slack_url.charAt(slack_url.length - 1) != '/') { slack_url += "/"; } } else { slack_url = "https://slack.com/api/"; } function slackAPI(slack, method, options, callback, retry) { var logPrefix = "[" + logBasePath + ".slackAPI] "; slack.api(method, options, function (err, response) { if (retry && retry == 3/*retry 3 times max*/) { // give up and return error if any return callback(err, response); } if (err && err.status == 'fail' /*workaround for https://github.com/nodejs/node/issues/4161*/) { // wait 1s and retry retry = retry ? retry+1 : 1; logger.warning(logPrefix + "err.status == 'fail', retrying #" + retry); sleep(1); slackAPI(slack, method, options, callback, retry); } else { callback(err, response); } }); } function sleep(s) { var e = new Date().getTime() + (s * 1000); while (new Date().getTime() <= e) { ; } } function getSlackLibrary(slack_api_token) { var slack = new Slack(slack_api_token); if (slack_url) { slack.url = slack_url; } return slack; } function getSlackUser(slack_api_token, callback) { var logPrefix = "[" + logBasePath + ".getSlackChannel] "; var slack = getSlackLibrary(slack_api_token); slackAPI(slack, "auth.test", function (err, response) { if (err) { callback(err); } else { if (response.ok) { delete response.ok; callback(null, response); } else { callback(response.error); } } }); } function getOrCreateSlackChannel(slack_api_token, user, channel_id, channel_name, channel_topic, channel_purpose, callback) { var logPrefix = "[" + logBasePath + ".getOrCreateSlackChannel] "; if(!channel_id && !channel_name) { logger.error(logPrefix + "parameters' channel information (id or name) not provided"); return callback({ description:"channel information (id or name) not provided"}); } var slack = getSlackLibrary(slack_api_token); if (channel_id) { logger.debug(logPrefix + "Using Slack channel " + channel_id + ""); slackAPI(slack, "channels.info", {channel: channel_id}, function (err, response) { if (err) { return callback(err); } if (response.ok) { var channel = response.channel; if (response.channel.is_archived) { return unarchiveChannel(slack, channel, callback); } else { return callback(null, channel); } } if (response.error == "channel_not_found"){ // Let's see if it is a private channel slackAPI(slack, "groups.info", {channel: channel_id}, function (err, response) { if (err) { return callback(err); } if (response.ok) { var group = response.group; if (group.is_archived) { return unarchiveGroup(slack, group, callback); } else { return callback(null, group); } } else { return callback(response.error); } }); } else { callback(response.error); } }); } else { // Let's try to create a new channel given the channel_name and topic logger.debug(logPrefix + "Trying to create channel'" + channel_name + "'"); slackAPI(slack, "channels.create", {name: channel_name}, function (err, response) { if (err) { callback(err); } else if (response.ok) { var slack_channel = response.channel; slack_channel.newly_created = true; logger.debug(logPrefix + "Slack channel '" + slack_channel.name + "' created - " + slack_channel.id); // Workaround to have a topic and purpose indicating that this has been created by us // Those topic will be update/changed when binding the service with a toolchain if (!channel_topic) { channel_topic = "Notifications from Bluemix DevOps Services"; } if (!channel_purpose) { channel_purpose = "Notifications from Bluemix DevOps Services"; } if (channel_topic) { logger.debug(logPrefix + "Setting topic for newly created slack channel " + slack_channel.id + " to " + channel_topic); slackAPI(slack, "channels.setTopic", {channel: slack_channel.id, topic: channel_topic}, function(err, response){ if (err) { callback(err); } else if (response.ok) { if (channel_purpose) { logger.debug(logPrefix + "Setting purpose for for newly created slack channel " + slack_channel.id + " to " + channel_purpose); slackAPI(slack, "channels.setPurpose",{channel: slack_channel.id, purpose: channel_purpose}, function(err, response) { if(err) { callback(err); } else if(response.ok){ callback(null, slack_channel); } else { callback(response.error); } }); } else { callback(null, slack_channel); } } else { callback(response.error); } }) } else { callback(null, slack_channel); } } else if (response.error == "name_taken"){ // Channel name is already existing so try to reuse it ! var checked_channel_name = validateChannelName(channel_name); logger.debug(logPrefix + "Creation failed. Searching for Slack channel '" + checked_channel_name + "' [initial channel name='" + channel_name + "']"); slackAPI(slack, "channels.list", function(err, response) { if (err) { return callback(err); } if (response.ok) { var slack_channel = _.findWhere(response.channels, {name: checked_channel_name}); if (!slack_channel) { // Not found in public channel, let's search in private channel (ie groups) slackAPI(slack, "groups.list", function(err, response) { if (err) { return callback(err); } if (response.ok) { var group = _.findWhere(response.groups, {name: checked_channel_name}); if (group) { if (group.is_archived) { return unarchiveGroup(slack, group, callback) } else { return callback(null, group); } } } // Nothing found logger.error(logPrefix + "Slack channel with name '" + checked_channel_name + "' exists but is not accessible or found in channel list (either private or public)."); callback("Slack channel with name '" + checked_channel_name + "' exists but is not accessible or found in channel list (either private or public)."); }); } else { logger.debug(logPrefix + "Slack channel found ! " + JSON.stringify(slack_channel)); if (slack_channel.is_archived) { return unarchiveChannel(slack, slack_channel, callback); } else { return callback(null, slack_channel); } } } else { callback(response.error); } }); } else { callback(response.error); } }); } } function updateChannelTopicAndPurpose(slack_api_token, channel_id, channel_topic, channel_purpose, callback) { var logPrefix = "[" + logBasePath + ".updateChannelTopicAndPurpose] "; //console.log("slack_api_token:" + slack_api_token); var slack = getSlackLibrary(slack_api_token); logger.debug(logPrefix + "Setting topic for slack channel " + channel_id + " to " + channel_topic); slackAPI(slack, "channels.setTopic", {channel: channel_id, topic: channel_topic}, function(err, response){ if (err) { callback(err); } else if (response.ok) { if (channel_purpose) { logger.debug(logPrefix + "Setting purpose for slack channel " + channel_id + " to " + channel_purpose); slackAPI(slack, "channels.setPurpose",{channel: channel_id, purpose: channel_purpose}, function(err, response) { if(err) { callback(err); } else if(response.ok){ callback(); } else { callback(response.error); } }); } else { callback(); } } else { callback(response.error); } }); } function postMessage(slack_api_token, message, callback) { var slack = getSlackLibrary(slack_api_token); slackAPI(slack, "chat.postMessage", message, function (err, response) { if (err) { callback(err); } else { if (response.ok) { delete response.ok; callback(null, response); } else { callback(response.error); } } }); } function validateChannelName(channel_name) { if (channel_name) { // Channel name must be 21 characters or less var result = channel_name.substring(0, 21); // Channel names can only contain numbers, hyphens, and underscores // whitespace replaced by - result = result.replace(/ /g, "-"); // Channel names can only contain lowercase letters result = result.toLowerCase(); // Leading # are removed result = result.replace(/^#+/, ""); // Non letter, number, hyphen or underscore replaced by an underscore result = result.replace(/[^A-Za-z0-9_\-]/g, "_"); // Multiple - or _ are replaced by a single on result = result.replace(/-+/g, "-"); result = result.replace(/_+/g, "_"); return result; } else { return ""; } } function unarchiveChannel(slack, channel, callback) { var logPrefix = "[" + logBasePath + ".unarchiveChannel] "; logger.debug(logPrefix + "Unarchiving channel " + channel.id + ""); slackAPI(slack, "channels.unarchive", {channel: channel.id}, function (err, response) { if (err) { return callback(err); } if (response.ok) { channel.is_archived = false; return callback(null, channel); } else { return callback(response.error); } }); } function unarchiveGroup(slack, group, callback) { var logPrefix = "[" + logBasePath + ".unarchiveGroup] "; logger.debug(logPrefix + "Unarchiving group " + group.id + ""); slackAPI(slack, "groups.unarchive", {channel: group.id}, function (err, response) { if (err) { return callback(err); } if (response.ok) { group.is_archived = false; return callback(null, group); } else { return callback(response.error); } }); } <file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2015, 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; var nconf = require("nconf"), log4js = require("log4js"), request = require("request"), lruCache = require('lru-cache') ; var tiamUrl = nconf.get("TIAM_URL"); var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "lib.util.tiam-util" ; /** To determine the max size, we assume that we want to take up a maximum of 64MB for the running node app and convert KB to MB, so 64 * 1024 = 65,536. **/ var options = { max: 65536, length: function(n) { // String are 2 bytes in memory // and keys are between 120 to 250 chars // return length in approx. kb return ((2 * n.length) + 500)/1024; } }; var cache = lruCache(options); exports.getCredentials = getCredentials; exports.introspectCredentials = introspectCredentials; var getCredentialsUrl = tiamUrl + '/service/manage/credentials'; function getCredentials(authorizationCredentials, options, callback) { var logPrefix = "[" + logBasePath + ".getCredentials] "; var cacheKey = "get:" + authorizationCredentials; var url = getCredentialsUrl; if (options) { if (options.target) { url = url + '?target=' + options.target; cacheKey = cacheKey + ":" + options.target; } if (options.toolchain) { if (options.target) { url = url + '&'; } else { url = url + '?'; } url = url + 'toolchain=' + options.toolchain; cacheKey = cacheKey + ":" + options.toolchain; } } if (!options || options.refresh != true) { logger.debug(logPrefix + "Looking in cache for TIAM credentials"); var credentials = cache.get(cacheKey); if (credentials) { logger.debug(logPrefix + "Using cached TIAM credentials"); return callback(null, credentials); } } // Create a new credentials using TIAM Service var options = { url: url, headers: { Authorization: 'Basic ' + authorizationCredentials }, json: true }; request.post(options, function(error, res, body) { if (error) { logger.error(logPrefix + "Error while calling to TIAM service."); return callback(500); } switch (res.statusCode) { case 201: // Set the credentials in the cache undefinitively cache.set(cacheKey, body.target_credentials); logger.info(logPrefix + "Set new TIAM credentials in cache - cache length is approx. " + cache.length + " kb with " + cache.itemCount + " cached item(s)"); return callback(null, body.target_credentials); case 401: logger.debug(logPrefix + "Returning 401"); return callback(401); case 500: logger.debug(logPrefix + "Returning 500"); return callback(500); default: logger.error(logPrefix + 'Introspect basic credentials failed due to an internal ' + 'server error. Status code:' + res.statusCode + ', Error: ' + body.error); return callback(body.error, 500); } }); } var introspectCredentialsUrl = tiamUrl + '/service/manage/introspect?credentials='; // Cache userData for 1 hour var maxAge = 1000* 60 * 60; function introspectCredentials(authorizationCredentials, credentials, options, callback) { var logPrefix = "[" + logBasePath + ".introspectCredentials] "; logger.debug(logPrefix + "Introspect credentials at " + introspectCredentialsUrl + credentials); var cacheKey = "introspect:" + authorizationCredentials + ":" + credentials; if (!options || options.refresh != true) { var userData = cache.get(cacheKey); if (userData) { logger.debug(logPrefix + "Using cached userData for given credentials"); return callback(null, userData); } } // Introspect credentials to obtain userData using TIAM Service var options = { url: introspectCredentialsUrl + credentials, headers: { Authorization: 'Basic ' + authorizationCredentials }, json: true }; request.get(options, function(error, res, body) { if (error) { logger.error(logPrefix + "Error while calling to TIAM service."); return callback(500); } switch (res.statusCode) { case 200: // Set the userData for 1 hour cache.set(cacheKey, body, maxAge); logger.info(logPrefix + "Set UserData in cache - cache length is approx. " + cache.length + " kb with " + cache.itemCount + " cached item(s)"); return callback(null, body); case 400: logger.error(logPrefix + 'Introspect basic credentials failed. Status code:' + res.statusCode + ', Error: ' + body.error); return callback(400, body.error); case 401: logger.debug(logPrefix + 'Introspect basic credentials failed. Status code:' + res.statusCode + ', Error: ' + body.error); return callback(401, body.error); case 500: logger.error(logPrefix + 'Introspect basic credentials failed. Status code:' + res.statusCode + ', Error: ' + body.error); return callback(500, body.error); default: logger.error(logPrefix + 'Introspect basic credentials failed due to an internal ' + 'server error. Status code:' + res.statusCode + ', Error: ' + body.error); return callback(500, body.error); } }); } <file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2015, 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; /******************* Begin Synchronous App Configuration **********************/ //configure nconf and logging early var log4js = require("log4js"), nconf = require("nconf"), util = require('util') ; //Configuration for nconf populateNconfSync(); //Configuration for logging log4js.configure("./config/log4js.json", { reloadSecs: 30 }); var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "index"; // check if log level has not been overridden var level = nconf.get("LOG4J_LEVEL"); if (level && level.length > 0) logger.setLevel(level); /******************** End Synchronous App Configuration ***********************/ /************* Begin Application Performance Monitoring config ****************/ // Turn on newRelic if requested. require('newrelic') should be as // close as possible to first line of program // (at least before express) if (nconf.get('ENABLE_NEW_RELIC')) { require('newrelic'); logger.info('New Relic enabled'); } /*************** End Application Performance Monitoring config ****************/ /******************* Add middleware and start up server ***********************/ var app = require('./app.js'); app.configureMiddleware(function(err) { if (err) { util.log('Could not start server: ' + JSON.stringify(err)); } else { var httpServer = app.server.listen(nconf.get('PORT'), function(err) { util.log('Listening on port ' + nconf.get('PORT')); }); // If SIGTERM is emitted then gracefully shutdown // https://docs.cloudfoundry.org/devguide/deploy-apps/prepare-to-deploy.html#moving-apps process.on('SIGTERM', function () { logger.warn('Exiting because of SIGTERM signal'); httpServer.close(function (err) { // No new connections will be accepted // however existing connections (because of keep-alive may continue) // https://github.com/nodejs/node/issues/2642 // force an hard-stop util.log("Server now closed - Exit process"); // process.exit(0); }); }); } }); /**************************** Server listening ********************************/ function populateNconfSync() { /* Load up configuration. - ENVVARs override... - Whatever's in the VCAP_SERVICES envvar (parsed as json) which overrides... - config/${NODE_ENV}.json which overrides... - config/dev.json. */ nconf.env("__"); var overrides = {}; if (process.env.VCAP_SERVICES) overrides._vcap_services = JSON.parse(process.env.VCAP_SERVICES); if (process.env.VCAP_APPLICATION) overrides._vcap_application = JSON.parse(process.env.VCAP_APPLICATION); if (Object.getOwnPropertyNames(nconf.overrides).length !== 0) { nconf.overrides(overrides); } if (process.env.NODE_ENV) nconf.file("node_env", "config/" + process.env.NODE_ENV + ".json"); nconf.file("default", "config/dev.json"); } <file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2015, 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; var express = require("express"), log4js = require("log4js"), nconf = require("nconf"), r = express.Router(), request = require("request"), _ = require("underscore"), slackClient = require("../client/slack-client"), tiamUtil = require("../util/tiam-util") ; var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "lib.event.event"; r .post("/accept", incomingEventFromLMS, getServiceInstance, checkCredentials, processEvent) ; module.exports = r; var catalog = { "pipeline": require("./pipeline"), "toolchain": require("./toolchain") } var defaultTranslator = translate; function incomingEventFromLMS(req, res, next) { var logPrefix = "[" + logBasePath + ".incomingEventFromLMS] "; var source = req.body.service_id, serviceInstanceId = req.body.instance_id, toolchainId = req.body.toolchain_id ; var incomingEvent = {}; incomingEvent.source = source; incomingEvent.serviceInstanceId = serviceInstanceId; incomingEvent.toolchainId = toolchainId; incomingEvent.payload = req.body.payload; req.incomingEvent = incomingEvent; logger.debug(logPrefix + "Incoming event from LMS: " + JSON.stringify(incomingEvent.payload)); next(); } function getServiceInstance(req, res, next) { var logPrefix = "[" + logBasePath + ".getServiceInstance] "; var source = req.incomingEvent.source; var serviceInstanceId = req.incomingEvent.serviceInstanceId; var toolchainId = req.incomingEvent.toolchainId; if (!source || !serviceInstanceId || !toolchainId) { return res.status(400).json({ "description": "Error: no service_id, instance_id or toolchain_id for the incoming event."}); } logger.debug(logPrefix + "Looking for service instance record"); // Find the serviceInstance record var db = req.servicesDb; db.get(serviceInstanceId, null, function(err, body) { if(err && err.statusCode !== 404) { logger.error(logPrefix + "Retrieving the service instance with" + " ID: " + serviceInstanceId + " failed with the following" + " error: " + err.toString()); return res.status(500).json({ "description": err.toString() }); } else if(err && err.statusCode === 404) { logger.info(logPrefix + "Service instance with" + " ID: " + serviceInstanceId + " not found"); return res.status(400).json({"description": "no service instance found for id " + serviceInstanceId}); } else { req.serviceInstance = body; next(); } }); } function checkCredentials(req, res, next) { var logPrefix = "[" + logBasePath + ".checkCredentials] "; // Find toolchain credentials var toolchainId = req.incomingEvent.toolchainId; var toolchain_id = _.findWhere(req.serviceInstance.toolchain_ids, {id: toolchainId}); if (toolchain_id) { logger.debug(logPrefix + "Toolchain id and credentials found"); req.toolchainCredentials = toolchain_id.credentials; } // Introspect credentials if basic authorization var authHeader = req.header('Authorization'); if (authHeader) { // Split header and grab values from it. var authHeaderParts = authHeader.split(/\s+/); var authPrefix = String(authHeaderParts[0]).toLowerCase(); var authValue = authHeaderParts[1]; if (authPrefix === "basic") { logger.debug(logPrefix + "Basic auth - Introspect credentials given toolchain credentials"); // introspect credentials according to toolchain credentials if (!req.toolchainCredentials) { return res.status(401).json({ message: 'No toolchainCredentials found'}); } return tiamUtil.introspectCredentials(req.toolchainCredentials, authValue, null, function(err, description) { if (err) { logger.debug(logPrefix + "Basic auth - error while introspect credentials:" + err.toString()); return res.status(err).json({ "description" : description}); } else { logger.debug(logPrefix + "Basic auth - credentials introspected"); next(); } }); } } return res.status(401).json({ message: 'An invalid authorization header was passed in'}); } function processEvent(req, res, next) { var logPrefix = "[" + logBasePath + ".processEvent] "; var source = req.incomingEvent.source; var serviceInstanceId = req.incomingEvent.serviceInstanceId; var toolchainId = req.incomingEvent.toolchainId; var payload = req.incomingEvent.payload; var authorization = req.header("Authorization"); var serviceInstance = req.serviceInstance; var toolchainCredentials = req.toolchainCredentials; // According to :source value, we will route to the appropriate event to slack message translator // If the :source is not known, warning in the log and generic message in the channel // The output of // retrieve the channel var message; var translator = catalog[source]; if (!translator) { logger.warn(logPrefix + "No event to slack message translator found for " + source + ".\nContent:" + JSON.stringify(req.body)); res.status(204).json({}); } else { // Add an internal correlator just to check/ensure/debug the message ordered (ie pipeline) var requestId = req.header("vcap_request_id"); if (!requestId) { requestId = new Date().getTime(); } logger.info(logPrefix + "[" + requestId + "]Event about to be processed - from '" + source + "' in toolchain '" + toolchainId + "' for Slack service instance id:" + serviceInstanceId); logger.debug(logPrefix + "[" + requestId + "] Event payload: " + JSON.stringify(payload)); translator(requestId, payload, toolchainCredentials, function (error, message) { if (error) { res.status(500).json({ "description" : error}); } else if (message) { // Find the api_token out of the serviceInstance record var api_token = serviceInstance.parameters.api_token; // Find the channel_id out of the serviceInstance record instance_id parameters // and add it to the message object message.channel = serviceInstance.instance_id; var channelName = serviceInstance.parameters.label; if (!channelName) { channelName = message.channel; } logger.debug(logPrefix + "[" + requestId + "] Posting Slack Message to channel '" + channelName + "' for Event - from '" + source + "' in toolchain '" + toolchainId + "' for Slack service instance id:" + serviceInstanceId); slackClient.postMessage(api_token, message, function(err, response) { if (err) { res.status(500).json({ "description" : err.toString() }); return; } else if (response.error) { res.status(400).json({ "description" : "Error - " + response.error}); return; } else { logger.debug(logPrefix + "[" + requestId + "] Slack Message to channel '" + channelName + "' sent for Event - from '" + source + "' in toolchain '" + toolchainId + "' for Slack service instance id:" + serviceInstanceId); res.status(204).json({}); return; } }); } else { // No message out of the event ! res.status(204).json({}); } }); } } function translate(requestId, event, authorization, callback) { var message = {}; message.username = "Unknow Event"; message.text = JSON.stringify(event); callback(null, message); } <file_sep>#!/bin/sh usage () { cat <<USAGE NAME $(basename $0) - Prepares the environment for an OpenToolchain Component's install. SYNOPSIS export JML_FILE=\${p:localPath}/sl-tools/VMconfigs/\${p:configFile} export IAAS_LOCATION=\${p:localPath}/sl-tools/bin/iaas $(basename $0) ENVIRONMENT VARIABLES JML_FILE The location of a JML configuration file. If this is run from within a UCD component process, consider: \${p:localPath}/sl-tools/VMconfigs/\${p:configFile} IAAS_LOCATION The location of the iaas utility for reading JML values and running internal provisioning APIs. If this is run from within a UCD component process, consider: \${p:localPath}/sl-tools/bin/iaas USAGE } iaas_get () { iaas_get_key=$1; shift if ! "$IAAS_LOCATION" -j -c "$JML_FILE" get-env-param -f -p "$iaas_get_key"; then echo "$iaas_get_key: Could not fetch JML property" >&2 return 1 fi } if [ "$JML_FILE" ]; then echo "JML_FILE=$JML_FILE" else echo "JML_FILE: Expected envvar not specified!" >&2 usage >&2 exit 1 fi if [ "$IAAS_LOCATION" ]; then echo "IAAS_LOCATION=$IAAS_LOCATION" else echo "IAAS_LOCATION: Expected envvar not specified!" >&2 usage >&2 exit 1 fi set -x # Configure the deploy script # export CF_APP="otc-slack-broker" export DOMAIN=$(iaas_get bluemix_env_domain) export ENV=$(iaas_get bluemix_env_name) export ROUTE="otc-slack-broker" export TEST_URL_PATH="/status" # Configure the actual app # export CF_SERVICES="otc-db:$CLOUDANT_SERVICE_NAME:$CLOUDANT_SERVICE_PLAN" export app_url="https://$ROUTE.$DOMAIN" export app_BUILD_NUMBER="$(<.pipeline_build_id)" export app_LOG4J_LEVEL="$SERVICE_LOG_LEVEL" export app_SECGRP="$DATA_LABELING" # Configuration for logmet export app_log4js_logmet_enabled="true" export app_log4js_logmet_component="otc-slack-broker" export app_log4js_logmet_logging_token="$(iaas_get otc_logging_token)" export app_log4js_logmet_space_id="$(iaas_get otc_logging_space_id)" export app_log4js_logmet_logging_host="$(iaas_get otc_logging_logstash_host)" export app_log4js_logmet_logging_port="$(iaas_get otc_logging_logstash_port)" # Configuration for qradar syslog appender export app_log4js_syslog_appender_enabled=false qradar_host="$(iaas_get qradar_isie_ip)" if [ "$qradar_host" -a "$qradar_host" != 1.1.1.1 ]; then export app_log4js_syslog_appender_enabled=true export app_log4js_syslog_appender_useUdpSyslog=true export app_log4js_syslog_appender_host="$qradar_host" export app_log4js_syslog_appender_port="$(iaas_get otc_qradar_udp_port)" export app_log4js_syslog_appender_product="otc-slack-broker" fi # Configuration to connect to the otc-status app export app_otc_status="https://otc-status.$DOMAIN" # Environment variables dedicated to slack broker defined using export app_<variable> export app_TIAM_CLIENT_ID=slack export app_TIAM_URL="https://devops-api.$DOMAIN/v1/identity" export app_icons__github=https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png export app_icons__pipeline=https://devops.ng.bluemix.net/images/pipeline.png export app_icons__toolchain=https://devops.ng.bluemix.net/images/toolchain-32.png export app_services__otc_api=https://otc-api.$DOMAIN/api/v1 export app_services__otc_ui=https://dev-console.$DOMAIN/devops export app_services__slack_api=https://slack.com/api export app_ENABLE_NEW_RELIC="$ENABLE_NEW_RELIC" export app_NEW_RELIC_APP_NAME="$CF_APP-$ENV" export app_NEW_RELIC_LICENSE_KEY="$NEW_RELIC_LICENSE_KEY" export app_OTC_API_BROKER_SECRET="$(iaas_get OTC_API_SLACK_BROKER_CREDENTIALS)" chmod u+x "$(dirname "$0")/../otc-cf-deploy/deploy" "$_" "$@" <file_sep>#!/bin/bash bash otc-deploy/cf-apps/common/pipeline.test.setup.sh export BUILD_NUMBER=$(<.pipeline_build_id) export OTC_API_BROKER_SECRET=$_DEPLOY_OTC_API_BROKER_SECRET export url=$_DEPLOY_url node test/tapeSlack.js | node_modules/.bin/tap-xunit > test/tapeSlack.xml if grep -B 1 -A 5 "<failure>" ./test/*.xml; then echo "Test Failure detected. Exiting." exit 1 fi <file_sep>#!/bin/bash -x export CF_APP=otc-slack-broker #jml variables expected to be defined for environment ADMIN_USER="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_cf_username)" ADMIN_PASSWORD="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_cf_password)" DOMAIN="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p bluemix_env_domain)" export CF_ENV=$(echo "$DOMAIN" | sed -n "s/^\([^\.]*\)\..*/\1/p") TMP="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_org)" if [ $? -eq 0 ]; then CF_ORG="$TMP" else CF_ORG=BluemixDevOpsORG fi TMP="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_space)" if [ $? -eq 0 ]; then CF_SPACE="$TMP" else CF_SPACE=dev fi #logmet export LOGGING_ORG="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_logging_org)" export LOGGING_SPACE="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_logging_space)" export LOGGING_HOST="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_logging_logstash_host)" export LOGGING_PORT="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_logging_logstash_port)" export LOGGING_TOKEN="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_logging_token)" export LOGGING_SPACE_GUID="$($IAAS_LOCATION -j -c $JML_FILE get-env-param -f -p otc_logging_space_id)" #be sure we are logged into proper api cf api https://api.$DOMAIN cf login -u "$ADMIN_USER" -p "$ADMIN_PASSWORD" -o "$CF_ORG" -s "$CF_SPACE" #replace domain with dedicated $DOMAIN cat manifest.mf | sed -e 's/stage1.ng.bluemix.net/$DOMAIN/g' #deploy the app first chmod 755 .jobs/* .jobs/deploy #environment variables required for running slack broker cf set-env otc-slack-broker-blue ENABLE_NEW_RELIC true cf set-env otc-slack-broker-blue LOG4J_LEVEL DEBUG cf set-env otc-slack-broker-blue NEW_RELIC_APP_NAME otc-slack-broker-ys1 cf set-env otc-slack-broker-blue NEW_RELIC_LICENSE_KEY <KEY> cf set-env otc-slack-broker-blue OTC_API_BROKER_SECRET <KEY> cf set-env otc-slack-broker-blue SECGRP GRP3DEVS cf set-env otc-slack-broker-blue TIAM_CLIENT_ID slack cf set-env otc-slack-broker-blue TIAM_URL https://devops-api.$CF_ENV.bluemix.net/v1/identity cf set-env otc-slack-broker-blue _vcap_services__cloudantNoSQLDB__0__credentials__url https://bmdevops-ys1-us-south:mnfsd764jndhflITDYmegl83m@bmdevops-ys1-us-south.cloudant.com cf set-env otc-slack-broker-blue icons__github https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png cf set-env otc-slack-broker-blue icons__pipeline http://blade-resources.mybluemix.net/pipeline.png cf set-env otc-slack-broker-blue icons__toolchain http://blade-resources.mybluemix.net/toolchain-32.png cf set-env otc-slack-broker-blue log4js_logmet_component otc-slack-broker cf set-env otc-slack-broker-blue log4js_logmet_enabled true cf set-env otc-slack-broker-blue log4js_logmet_logging_host $LOGGING_HOST cf set-env otc-slack-broker-blue log4js_logmet_logging_port $LOGGING_PORT cf set-env otc-slack-broker-blue log4js_logmet_logging_token $LOGGING_TOKEN cf set-env otc-slack-broker-blue log4js_logmet_space_id $LOGGING_SPACE_GUID cf set-env otc-slack-broker-blue services__otc_api https://otc-api.$CF_ENV.bluemix.net/api/v1 cf set-env otc-slack-broker-blue services__otc_ui https://dev-console.$CF_ENV.bluemix.net/devops cf set-env otc-slack-broker-blue services__slack_api https://slack.com/api cf set-env otc-slack-broker-blue url https://otc-slack-broker.$DOMAIN cf restage otc-slack-broker-blue exit $RC <file_sep>############################################################################### # Licensed Materials - Property of IBM # (c) Copyright IBM Corporation 2015, 2015. All Rights Reserved. # # Note to U.S. Government Users Restricted Rights: # Use, duplication or disclosure restricted by GSA ADP Schedule # Contract with IBM Corp. ############################################################################### #!/bin/bash -x # Install 32-bit runtime to run 32-bit executables on 64-bit unix sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get -y install libc6:i386 libncurses5:i386 libstdc++6:i386 mkdir archive # copy all message files (except translations) into archive, following the same folder structure find . -type f | egrep -i "/[^_]+\.properties$" | xargs -i cp --parents {} archive find . -type f | egrep -i "/.+_en\.json$" | xargs -i cp --parents {} archive # Recursively check all .properties files chmod u+x otc-deploy/tools/chkpli.exe ./otc-deploy/tools/chkpli.exe "archive/*.properties" -OS -S <file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2015, 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; var async = require("async"), checkOtcApiAuth = require("./check-otc-api-auth"), express = require("express"), i18n = require('i18n'), log4js = require("log4js"), msgs = require('../../nls/msgs.properties'), nanoDocUpdater = require("nano-doc-updater"), nconf = require("nconf"), request = require("request"), tiamUtil = require("../util/tiam-util"), toolchainTranslator = require("../event/toolchain"), toolchainUtil = require("../util/toolchain-util"), slackClient = require("../client/slack-client"), _ = require("underscore") ; var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "lib.middleware.service_instances"; var r = express.Router(); r .use(checkOtcApiAuth) .put("/:sid", createOrUpdateServiceInstance) .put("/:sid/toolchains/:tid", bindServiceInstanceToToolchain) .patch("/:sid", patchServiceInstance) .delete("/:sid", unbindServiceInstance) .delete("/:sid/toolchains", unbindServiceInstanceFromAllToolchains) .delete("/:sid/toolchains/:tid", unbindServiceInstanceFromToolchain) ; module.exports = r; /** * Checks if the service instance already exists. If one does, * and the parameters (i.e. list title) needs an update, then the value * is updated. If the parameters are not updated, a check is done to * update the remaining parameters, e.g. toolchains associated with * the service instance. Otherwise, no instance exists so * a list is created along with an instance. * * Note: If a list title is changed outside the instance in the * service itself, then the parameters and title can be out of sync. **/ function createOrUpdateServiceInstance (req, res) { var logPrefix = "[" + logBasePath + ".createOrUpdateServiceInstance] "; var db = req.servicesDb, serviceInstanceId = req.params.sid, parametersData = req.body.parameters, organizationId = req.body.organization_guid, serviceCredentials = req.body.service_credentials; logger.info(logPrefix + "Provisionning the service instance with ID: " + serviceInstanceId + " using parameters:" + JSON.stringify(parametersData)); // req.body (from external request) is not the same as body (response from Cloudant dB). if(!req.body.service_id) { return res.status(400).json({ "description": msgs.get('error.required_parameter', ['service_id'], req)}); } if(!organizationId) { return res.status(400).json({ "description": msgs.get('error.required_parameter', ['organization_guid'], req)}); } db.get(serviceInstanceId, null, function(err, body) { if(err && err.statusCode !== 404) { logger.error(logPrefix + "Retrieving the service instance with" + " ID: " + serviceInstanceId + " failed with the following" + " error: " + err.toString()); res.status(500).json({ "description": err.toString() }); return; } else if(err && err.statusCode === 404) { /** * The service instance does not exist, create * one **/ if(!serviceCredentials) { return res.status(400).json({ "description": msgs.get('error.required_parameter', ['service_credentials'], req)}); } return createOrUpdateServiceInstance_(res, req, db, serviceInstanceId, organizationId, serviceCredentials, parametersData) } else { /** * The service instance exists but the parameters needs an update. **/ if(!serviceCredentials) { // ensure serviceCredentials is there serviceCredentials = body.service_credentials; } return createOrUpdateServiceInstance_(res, req, db, serviceInstanceId, organizationId, serviceCredentials, parametersData) } }); } function createOrUpdateServiceInstance_(res, req, db, serviceInstanceId, organizationId, serviceCredentials, parametersData) { var logPrefix = "[" + logBasePath + ".createOrUpdateServiceInstance_] "; var api_token; var channel_id; var channel_name; var channel_topic; var channel_purpose; if (parametersData) { api_token = parametersData.api_token; channel_id = parametersData.channel_id; channel_name = parametersData.channel_name; channel_topic = parametersData.channel_topic; channel_purpose = parametersData.channel_purpose; } var parameters = {}; if (api_token) { slackClient.getSlackUser(api_token, function (err, user) { if (err) { logger.info(logPrefix + "Error getting slack user : " + err.toString() + " - " + JSON.stringify(user)); if (err == "not_authed" || err == "invalid_auth" || err == "account_inactive") { return res.status(400).json({ "description": msgs.get('error.api_token_invalid', [err], req) }); } else { return res.status(500).json({ "description": msgs.get('error.unable_to_authenticate', [err], req) }); } } parameters.api_token = api_token; slackClient.getOrCreateSlackChannel(api_token, user, channel_id, channel_name, channel_topic, channel_purpose, function (err, channel) { if (err) { logger.error(logPrefix + "Error getting or creating slack channel : " + err.toString()); return res.status(400).json({ "description": msgs.get('error.unable_to_find_or_create_channel', [err.toString()], req) }); } else { var dashboardUrl = user.url + "messages/" + channel.name; parameters.channel_name = channel.name; parameters.label = "#" + channel.name; return doServiceUpdate(res, req, db, serviceInstanceId, serviceCredentials, parameters, channel.id, organizationId, dashboardUrl, channel.newly_created); } }); }); } else { return res.status(400).json({ "description": msgs.get('error.no_api_token', req) }); } } /** * Handles updating the service instance with the new properties. **/ function doServiceUpdate (res, req, db, serviceInstanceId, serviceCredentials, parametersData, instanceId, organizationId, dashboardUrl, channel_newly_created) { var logPrefix = "[" + logBasePath + ".doServiceUpdate] "; if (channel_newly_created) { } else { channel_newly_created = false; } return nanoDocUpdater() .db(db) .id(serviceInstanceId) .existingDoc(null) .newDoc(_.extend( { type: "service_instance", parameters: parametersData, instance_id: instanceId, dashboard_url: dashboardUrl, organization_guid: organizationId, service_credentials: serviceCredentials, channel_newly_created: channel_newly_created }, { toolchain_ids: [] } )) .shouldUpdate(function (published, proposed) { return published.type !== proposed.type || published.parameters != proposed.parameters || published.instance_id !== proposed.instance_id || published.dashboard_url !== proposed.dashboard_url || published.channel_newly_created !== proposed.channel_newly_created || published.service_credentials !== proposed.service_credentials || published.organization_guid !== proposed.organization_guid; }) .update(function (err) { if (err) { logger.error(logPrefix + "Updating the service instance with" + " ID: " + serviceInstanceId + " and parameters: " + parametersData + " failed with the following error: " + err.toString()); if(err.statusCode === 404) { return res.status(404).json({ "description": err.toString() }); } return res.status(500).json({ "description": err.toString() }); } logger.debug(logPrefix + "Updating the service instance with" + " ID: " + serviceInstanceId + " and parameters: " + JSON.stringify(parametersData) + " done"); return res.json({ instance_id: instanceId, dashboard_url: dashboardUrl, parameters: parametersData, organization_guid: organizationId }); } ); } function patchServiceInstance(req, res /*, next*/) { var logPrefix = "[" + logBasePath + ".patchServiceInstance] "; var db = req.servicesDb, serviceInstanceId = req.params.sid, parametersData = req.body.parameters ; logger.info(logPrefix + "Patching the service instance with ID: " + serviceInstanceId + " using parameters:" + JSON.stringify(parametersData)); var patchParameters = {}; // What can be patched for Slack ? // dashboard_url (read only) // parameters.label (read-only) // parameters.api_token (writable) if (parametersData.api_token) { patchParameters.api_token = parametersData.api_token; } // parameters.channel_id (writable) if (parametersData.channel_id) { patchParameters.channel_id = parametersData.channel_id; } // parameters.channel_name (writable) if (parametersData.channel_name) { patchParameters.channel_name = parametersData.channel_name; } // parameters.channel_topic (writable?) if (parametersData.channel_topic) { patchParameters.channel_topic = parametersData.channel_topic; } // parameters.channel_purpose (writable?) if (parametersData.channel_purpose) { patchParameters.channel_purpose = parametersData.channel_purpose; } db.get(serviceInstanceId, null, function(err, body) { if (err && err.statusCode === 404) { logger.error(logPrefix + "Service instance with" + " ID: " + serviceInstanceId + " was not found"); return res.status(404).json({ "description": err.toString() }); } else if (err) { logger.error(logPrefix + "Retrieving the service instance with" + " ID: " + serviceInstanceId + " failed with the following" + " error: " + err.toString()); return res.status(500).json({ "description": err.toString() }); } var organizationId; if (req.body.organization_guid) { // New organization organizationId =req.body.organization_guid; } else { organizationId= body.organization_guid } // previous channel was created ? var channel_newly_created = body.channel_newly_created; // New api_token ? var api_token = body.parameters.api_token; if (patchParameters.api_token && patchParameters.api_token != body.parameters.api_token) { api_token = patchParameters.api_token; } var parameters = {}; slackClient.getSlackUser(api_token, function (err, user) { if (err) { logger.info(logPrefix + "Error getting slack user : " + err.toString() + " - " + JSON.stringify(user)); if (err == "not_authed" || err == "invalid_auth" || err == "account_inactive") { return res.status(400).json({ "description": msgs.get('error.api_token_invalid', [err], req) }); } else { return res.status(500).json({ "description": msgs.get('error.unable_to_authenticate', [err], req) }); } } parameters.api_token = api_token; var channel_id; var channel_name; var channel_topic; var channel_purpose; if (patchParameters.channel_name && patchParameters.channel_name != body.parameters.channel_name) { // New channel name channel_name = patchParameters.channel_name; if (patchParameters.channel_topic) { channel_topic = patchParameters.channel_topic; } if (patchParameters.channel_purpose) { channel_purpose = patchParameters.channel_purpose; } // As this is a new channel name, forget about the previous status channel_newly_created = false; } else { // New channel id if (patchParameters.channel_id && patchParameters.channel_id != body.instance_id) { // new channel id channel_id = patchParameters.channel_id; // As this is a new channel, forget about the previous status channel_newly_created = false; } else { channel_id = body.instance_id; } } slackClient.getOrCreateSlackChannel(api_token, user, channel_id, channel_name, channel_topic, channel_purpose, function (err, channel) { if (err) { logger.error(logPrefix + "Error getting or creating slack channel : " + JSON.stringify(err)); return res.status(err && err.status == 'fail' ? 500 : 400).json({ "description": msgs.get('error.unable_to_find_or_create_channel', [JSON.stringify(err)], req) }); } else { var dashboardUrl = user.url + "messages/" + channel.name; parameters.channel_name = channel.name; parameters.label = "#" + channel.name; if (channel.newly_created) { if (body.toolchain_ids && body.toolchain_ids.length > 0) { // Use the "first" toolchain binded in order to set topic and purpose var id = body.toolchain_ids[0].id; var creds = body.toolchain_ids[0].credentials; changeChannelTopicAndPurpose(api_token, channel.id, id, creds); } } return nanoDocUpdater() .db(db) .id(serviceInstanceId) .existingDoc(null) .newDoc(_.extend(body, { instance_id: channel.id, dashboard_url: dashboardUrl, organization_guid: organizationId, parameters: parameters, channel_newly_created : channel.newly_created })) .shouldCreate(false) .shouldUpdate(function (published, proposed) { var shouldUpdate = published.instance_id !== proposed.instance_id || published.dashboard_url != proposed.dashboard_url || published.organization_guid != proposed.organization_guid || published.parameters != proposed.parameters || published.channel_newly_created != proposed.channel_newly_created ; return shouldUpdate; }) .merge(function (exist, proposed) { var merged = exist; merged.instance_id = proposed.instance_id; merged.dashboard_url = proposed.dashboard_url; merged.parameters.api_token = proposed.parameters.api_token; merged.parameters.channel_name = proposed.parameters.channel_name; merged.parameters.label = proposed.parameters.label; merged.organization_guid = proposed.organization_guid; merged.channel_newly_created = proposed.channel_newly_created; return merged; }) .update(function (err) { if (err) { logger.error(logPrefix + "Patching the service instance with" + " ID: " + serviceInstanceId + " and parameters: " + parametersData + " failed with the following error: " + err.toString()); if(err.statusCode === 404) { return res.status(404).json({ "description": err.toString() }); } return res.status(500).json({ "description": err.toString() }); } else { return res.json({ instance_id: channel.id, dashboard_url: dashboardUrl, parameters: parameters, organization_guid: organizationId }); } }); } }); }); }); } /* Assumption: A service instance may only be bound to one toolchain at a time. If this is not the case, we should replace toolchain_id in docs with toolchain_ids and do a merge (adding the toolchain_id to the list) instead of clobbering the whole doc here. */ function bindServiceInstanceToToolchain (req, res/*, next*/) { var logPrefix = "[" + logBasePath + ".bindServiceInstanceToToolchain] "; var db = req.servicesDb, serviceInstanceId = req.params.sid, toolchainId = req.params.tid, toolchainCredentials = req.body.toolchain_credentials; logger.info(logPrefix + "Binding the service instance with" + " ID: " + serviceInstanceId + " to toolchain ID: " + toolchainId); if (!toolchainCredentials) { return res.status(400).json({ "description": msgs.get('error.required_parameter', ['toolchain_credentials'], req) }); } var updatedDocument; return nanoDocUpdater() .db(db) .id(serviceInstanceId) .existingDoc(null) .newDoc(null) .shouldCreate(false) .shouldUpdate(function (published) { // only update if no binding for a given toolchain var result = _.find(published.toolchain_ids, function(obj) { if (obj.id === toolchainId) { return true; } }); return result == undefined; }) .merge(function (published) { published.toolchain_ids.push({id: toolchainId, credentials: toolchainCredentials}); updatedDocument = published; return published; }) .update(function (err, doc) { if (err) { logger.error(logPrefix + "Binding the service instance with" + " ID: " + serviceInstanceId + " to toolchain ID: " + toolchainId + " failed with the following error: " + err.toString()); if(err.statusCode === 404) { return res.status(404).json({ "description": err.toString() }); } return res.status(500).json({ "description": err }); } if (!doc) { // no doc were updated and neither created so the document for the service was not found return res.status(404).json({ "description": "service instance not found" }); } // Change the topic and purpose if the channel was created by the Slack Broker if (updatedDocument.channel_newly_created) { changeChannelTopicAndPurpose(updatedDocument.parameters.api_token, updatedDocument.instance_id, toolchainId, toolchainCredentials); } logger.info(logPrefix + "Binding the service instance with" + " ID: " + serviceInstanceId + " to toolchain ID: " + toolchainId + " done"); return res.status(204).json({}); }); } /** * Removes the service instance and the list from the service. **/ function unbindServiceInstance (req, res/*, next*/) { var logPrefix = "[" + logBasePath + ".unbindServiceInstance] "; var db = req.servicesDb, serviceInstanceId = req.params.sid; logger.info(logPrefix + "Unbinding the service instance with" + " ID: " + serviceInstanceId); /** * Find out the id of the list to remove. **/ db.get(serviceInstanceId, null, function(err, body) { /** * An error occurred during the request, or the service * instance does not exist. **/ if(err) { logger.error(logPrefix + "Retrieving the service instance with" + " ID: " + serviceInstanceId + " failed with the following" + " error: " + err.toString()); if(err.statusCode === 404) { return res.status(404).json({ "description": err.toString() }); } res.status(500).json({ "description": err.toString() }); return; } else { return nanoDocUpdater() .db(db) .id(serviceInstanceId) .existingDoc(null) .shouldCreate(false) .shouldUpdate(function (published) { return !published._deleted; }) .merge(function (published) { delete published.service_credentials; published.toolchain_ids = []; return _.extend({ _deleted: true }, published); }) .update(function (err) { if (err) { logger.error(logPrefix + "Removing the service instance with ID: " + serviceInstanceId + " failed with the following error: " + err.toString()); if(err.statusCode === 404) { return res.status(404).json({ "description": err.toString() }); } return res.status(500).json({ "description": "Could not delete service instance: " + err.toString() }); } return res.status(204).json({}); }); } }); } function unbindServiceInstanceFromToolchain (req, res/*, next*/) { var logPrefix = "[" + logBasePath + ".unbindServiceInstanceFromToolchain] "; var db = req.servicesDb, serviceInstanceId = req.params.sid, toolchainId = req.params.tid ; logger.info(logPrefix + "Unbinding the service instance with" + " ID: " + serviceInstanceId + " from toolchain ID: " + toolchainId); var toolchainCredentials; return nanoDocUpdater() .db(db) .id(serviceInstanceId) .existingDoc(null) .newDoc(null) .shouldCreate(false) .shouldUpdate(function (published) { var result = _.find(published.toolchain_ids, function(obj) { if (obj.id === toolchainId) { return true; } }); return result !== undefined; }) .merge(function (published) { published.toolchain_ids = _.reject(published.toolchain_ids, function(obj) { if (obj.id === toolchainId) { toolchainCredentials = obj.credentials; return true; } }); return published; }) .update(function (err, doc) { if (err) { logger.error(logPrefix + "Unbinding the service instance with" + " ID: " + serviceInstanceId + " from toolchain ID: " + toolchainId + " failed with the following error: " + err.toString()); if(err.statusCode === 404) { return res.status(404).json({ "description": err.toString() }); } return res.status(500).json({ "description": "Could not unbind service instance: " + err.toString() }); } if (!doc) { // no doc were updated and neither created so the document for the service was not found return res.status(404).json({ "description": "service instance not found" }); } // Force a message to Slack channel // This is because LMS will not be see this service instance bound // to the toolchain and thus not send any event related var unbindPayload = { "toolchain_guid": toolchainId, "event": "unbind", "services": [{ "uuid": serviceInstanceId, "service_id": "slack", "dashboard_url": doc.dashboard_url, "parameters" : doc.parameters }], }; if (req.body && req.body.user_info) { unbindPayload.user_info = req.body.user_info; } toolchainTranslator("", unbindPayload, toolchainCredentials, function (error, message) { if (error) { logger.error(logPrefix + "[" + requestId + "] Create Slack Message failed with error:" + err.toString()); return; } if (message) { // Find the api_token out of the serviceInstance record var api_token = doc.parameters.api_token; // Find the channel_id out of the serviceInstance record instance_id parameters // and add it to the message object message.channel = doc.instance_id; var channelName = doc.parameters.label; if (!channelName) { channelName = message.channel; } return slackClient.postMessage(api_token, message, function(err, response) { if (err) { logger.error(logPrefix + "Slack Message to channel '" + channelName + "' sent with error:" + err.toString()); return; } else if (response.error) { logger.error(logPrefix + "Slack Message to channel '" + channelName + "' sent with error:" + response.error); return; } else { logger.debug(logPrefix + "Slack Message to channel '" + channelName + "' sent for unbind event in toolchain '" + toolchainId + "' for Slack service instance id:" + serviceInstanceId); return; } }); } else { // No message out of the event ! logger.error(logPrefix + "[" + requestId + "] Create Slack Message failed"); } }); return res.status(204).json({}); }); } function unbindServiceInstanceFromAllToolchains (req, res/*, next*/) { return res.status(501).json({"description": "Unimplemented"}); } function changeChannelTopicAndPurpose(api_token, channel_id, toolchainId, toolchainCredentials) { var logPrefix = "[" + logBasePath + ".changeChannelTopicAndPurpose] "; // Find the toolchain information using otc-api var otc_api_url = nconf.get("services:otc_api"); toolchainUtil.getToolchainName(toolchainId, toolchainCredentials, function(error, toolchainName) { if (error) { logger.error(logPrefix + "Error while getting toolchain name for toolchain " + toolchainId + ":" + error); } else { var toolchain_ui_url = nconf.get("services:otc_ui") + "/toolchains/" + toolchainId; var topic = "Notifications from DevOps Services Toolchain *" + toolchainName + "* (" + toolchain_ui_url + ")"; var purpose = "This channel was created to handle notifications from DevOps Services Toolchain *" + toolchainName + "* (" + toolchain_ui_url + ")"; // Update the topic and purpose using slack helper slackClient.updateChannelTopicAndPurpose(api_token, channel_id, topic, purpose, function(err) { if (err) { logger.error(logPrefix + "Error while setting topic and purpose for channel " + channel_id + " - " + err); } }); } }); } <file_sep>#!/bin/bash set +x # install dependencies (node 4.2.x, npm 3.5.2) npmPath=$(which npm) if [[ $? = 0 ]]; then npmPath=$(dirname "$npmPath") else echo "No npm, something must seriously be wrong." exit 1 fi npm install -g npm@3.5.2 # Set up path for dependencies. export PATH="$npmPath":/opt/IBM/node-v4.2/bin:"$PATH" npm -v set +x git clone "https://$IDS_USER:$IDS_PASS@github.ibm.com/org-ids/otc-deploy" git clone --branch "v1.0.6" "https://$IDS_USER:$IDS_PASS@github.ibm.com/org-ids/otc-cf-deploy" set -x bash otc-deploy/cf-apps/common/pipeline.build.sh <file_sep>#!/bin/bash "otc-deploy/cf-apps/otc-x-broker/pipeline.deploy.test.sh" <file_sep># IBM Bluemix DevOps Services - Slack broker This component is an implementation of OpenToolChain Service Broker that allows to integrate Slack in a toolchain. The Slack Broker main responsibity is to create the Slack messages out of the events coming from OTC. It is written using Node.js. Link to [IBM Garage Method and Slack Tool (Culture)](https://www.ibm.com/devops/method/content/culture/tool_slack) and [IBM Bluemix Toolchain tutorial](https://www.ibm.com/devops/method/tutorials/tutorial_toolchain_flow) Link to [Bluemix Public IDS Experiment](https://new-console.ng.bluemix.net/dashboard/devops). This is one of hundreds of [IBM Open Source projects at GitHub](http://ibm.github.io). # License [The MIT License (MIT)](LICENSE.txt) # Contributing Contributions are welcome via Pull Requests. Please submit your very first Pull Request against the [Developer's Certificate of Origin](DCO.txt), adding a line like the following to the end of the file... using your name and email address of course! Signed-off-by: <NAME> <<EMAIL>> # Usage Local Usage ----------- # Create a local config file from the provided template cp config/local-dev.json.template config/local-dev.json # Edit config/local-dev.json and update the following: - Replace CLOUDANT_URL with your Cloudant URL: https://<cloudant id>:<cloudant pw>@<cloudant id>.cloudant.com - Provide values for TIAM* properties: Contact Simon H for Stage1 values. - Update services: Use the services and icons URLs according to your environment (services:* and icons:*) # Tell the broker to use your local config export NODE_ENV=local-dev # Install the module dependencies npm install # Start the node app npm start # Create a test configuration from the provided template cp config/testUtils.json.template config/testUtils.json # Edit config/testUtils.json and update the following: - slack_domain and slack_token (corresponding to the configuration for test user) - test_tiam_id and test_tiam_secret (TIAM properties required to invoke the broker API) # To run the tests, run: npm test Dependencies ------------ The Slack Broker has the following dependencies: - Cloudant - Slack (usage of [Slack Web API](https://api.slack.com/web) thru [slack-node](https://www.npmjs.com/package/slack-node) module) - TIAM Logging ------- Logging for the Slack Broker is handled using log4js. To configure the logging levels and output location, modify the config/log4js.json file. The `request` filter will output Express requests. The `otc-slack-broker` filter indicates any logging for this component. Note: Environment variable LOG4J_LEVEL can be set to change the logging level for otc-slack-broker filter at runtime <include if applicable> # API Refer to the [swagger](https://otc-slack-broker.ng.bluemix.net/swagger/) for more information on the implemented endpoints. <file_sep>#!/bin/bash bash otc-deploy/cf-apps/common/pipeline.test.setup.sh export BUILD_NUMBER=$(<.pipeline_build_id) export NOCK_MODE=true # export DEBUG=nock.* # install dependencies (node 4.2.x, npm 3.5.2) npmPath=$(which npm) if [[ $? = 0 ]]; then npmPath=$(dirname "$npmPath") else echo "No npm, something must seriously be wrong." exit 1 fi npm install -g npm@3.5.2 # Set up path for dependencies. export PATH=$npmPath:/opt/IBM/node-v4.2/bin:$PATH # Install dev-dependencies. npm install node --version node test/tapeSlack.js | node_modules/.bin/tap-xunit > test/tapeSlack.xml if grep -B 1 -A 5 "<failure>" ./test/*.xml; then echo "Test Failure detected. Exiting." exit 1 fi <file_sep>/** * Licensed Materials - Property of IBM * (c) Copyright IBM Corporation 2015, 2016. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. */ "use strict"; var log4js = require("log4js"), nconf = require('nconf'), async = require("async"), _ = require('underscore'), tiamUtil = require("../util/tiam-util"), toolchainUtil = require("../util/toolchain-util") ; var logger = log4js.getLogger("otc-slack-broker"), logBasePath = "lib.event.toolchain" ; var otc_ui_url = nconf.get("services:otc_ui"); module.exports = function(requestId, event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + "]"; logger.info(logPrefix + "[" + requestId + "] Toolchain - " + event.toolchain_guid + " - Event " + event.event); if (event.event == "bind") { createMessageForBindOrUnbind(event, toolchainCredentials, callback); } else if (event.event == "unbind") { createMessageForBindOrUnbind(event, toolchainCredentials, callback); } else if (event.event == "provision") { createMessageForProvision(event, toolchainCredentials, callback); } else { // Default var message = {}; message.username = "Open Tool Chain"; message.icon_url = nconf.get("icons:toolchain"); message.text = "Event Payload received:" + JSON.stringify(event); callback(null, message); } } function createMessageForBindOrUnbind(event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".createMessageForBindOrUnbind]"; async.parallel({ toolchainName: function(asyncCallback) { toolchainUtil.getToolchainName(event.toolchain_guid, toolchainCredentials, asyncCallback); }, userName: function(asyncCallback) { if (event.user_info) { asyncCallback(null, event.user_info.user_name); } else { asyncCallback(); } } }, function(err, results) { if (err) { callback(err); } else { var message = {}; message.username = "Toolchain '" + results.toolchainName + "'"; message.icon_url = nconf.get("icons:toolchain"); message.text = ""; async.eachSeries(event.services, function(service, eachCallback) { var toolchain_binding_status; if (service.toolchain_binding && service.toolchain_binding.status) { toolchain_binding_status = service.toolchain_binding.status; } // The bind event should only inform Slack users for configured or error state (either for service status or toolchain_binding status) if (event.event=="bind") { if (service.status && service.status.state != "configured" && service.status.state != "error") { return eachCallback(null); } if (toolchain_binding_status.state != "configured" && toolchain_binding_status.state != "error") { return eachCallback(null); } } toolchainUtil.getServiceName(service.service_id, toolchainCredentials, function(err, serviceName) { if (err) { eachCallback(err) } else { var text = "Service " + serviceName; // We should use the label of service if any if (service.parameters && service.parameters.label) { var label = service.parameters.label; var dashboard_url; if (event.event!="unbind") { dashboard_url = service.dashboard_url; } if (dashboard_url) { text += " *<" + makeUIAbsoluteURL(dashboard_url) + "|'" + label + "'>*"; } else { text += " *'"; text += label; text += "'*" } } if (event.event=="bind") { // Define the sentence according to toolchain binding status state if (toolchain_binding_status.state == "new") { text += " is *about to be bound* to"; } else if (toolchain_binding_status.state == "configuring") { text += " is *being bound* to"; } else { // Default text += " has been *bound* to"; } } else { text += " has been *unbound* from"; } text += " toolchain *<"; text += nconf.get("services:otc_ui") + "/toolchains/" + event.toolchain_guid; text += "|'" + results.toolchainName + "'>*"; if (results.userName) { text += " by " + results.userName; } if (event.event=="bind" && service.status) { text += " and is *"; if (service.status.state == "error") { text += "in error"; } else { text += service.status.state; } text +="*"; } text += "\n"; message.text += text; eachCallback(null); } }); }, function(err) { if (err) { callback(err); } else { // Message has to be sent only if there is some text content if (message.text.length > 0) { callback(null, message); } else { callback(null, null); } } }); } }); } function createMessageForProvision(event, toolchainCredentials, callback) { var logPrefix = "[" + logBasePath + ".createMessageForBindOrUnbind]"; async.parallel({ toolchainName: function(asyncCallback) { toolchainUtil.getToolchainName(event.toolchain_guid, toolchainCredentials, asyncCallback); }, userName: function(asyncCallback) { if (event.user_info) { asyncCallback(null, event.user_info.user_name); } else { asyncCallback(); } } }, function(err, results) { if (err) { callback(err); } else { var message = {}; message.username = "Toolchain '" + results.toolchainName + "'"; message.icon_url = nconf.get("icons:toolchain"); message.text = ""; async.eachSeries(event.services, function(service, eachCallback) { // The provision event should only inform Slack users for configured or error service state // and with toolchain_binding status == configured // => This means an update to a service configuration if (service.status && service.status.state != "configured" && service.status.state != "error") { return eachCallback(null); } var toolchain_binding_status; if (service.toolchain_binding && service.toolchain_binding.status) { toolchain_binding_status = service.toolchain_binding.status; } if (toolchain_binding_status.state != "configured") { // This is not an update to the service's configuration return eachCallback(null); } toolchainUtil.getServiceName(service.service_id, toolchainCredentials, function(err, serviceName) { if (err) { eachCallback(err) } else { var text = "Service " + serviceName; // We should use the label of service if any if (service.parameters && service.parameters.label) { var label = service.parameters.label; var dashboard_url = service.dashboard_url; if (dashboard_url) { text += " *<" + makeUIAbsoluteURL(dashboard_url) + "|'" + label + "'>*"; } else { text += " *'"; text += label; text += "'*"; } } text += " in toolchain *<"; text += nconf.get("services:otc_ui") + "/toolchains/" + event.toolchain_guid; text += "|'" + results.toolchainName + "'>*"; if (service.status) { if (service.status.state == "new") { text += " is about to be *provisioned*"; } else if (service.status.state == "configuring") { text += " is *configuring*"; } else if (service.status.state == "configured") { text += " has been *configured*"; } else if (service.status.state == "error") { text += " is in *error*"; } else { text += " has been *provisioned*"; } } else { text += " has been *updated*" } if (results.userName) { text += " by " + results.userName; } text += "\n"; message.text += text; eachCallback(null); } }); }, function(err) { if (err) { callback(err); } else { // Message has to be sent only if there is some text content if (message.text.length > 0) { callback(null, message); } else { callback(null, null); } } }); } }); } function makeUIAbsoluteURL(url) { if (url && !url.startsWith('http')) { // see https://hub.jazz.net/ccm09/web/projects/idsorg%20%7C%20One%20Ring%20Track%20and%20Plan#action=com.ibm.team.workitem.viewWorkItem&id=58417 // make it an absolute url var lastSlash = otc_ui_url.lastIndexOf('/'); if (lastSlash != -1) { var env_url = otc_ui_url.substring(0, lastSlash); return env_url + url; } } return url; }
72bdf454ead0bee3d498ce8889a7d95d5a079f0a
[ "JavaScript", "Markdown", "Shell" ]
17
JavaScript
IBM/otc-slack-broker
8464957b2fdf28f2c9026f5e765b338293df14d7
a6d05fba469e16f4fdfdb0fd0994af534728e80b
refs/heads/master
<repo_name>jgreef/Colors<file_sep>/board.cpp #include "board.h" Board::Board() : gen(8), e2(time(NULL)), dist(0, 1) { board = (int*)malloc(sizeof(int) * CELL_WIDTH * CELL_HEIGHT); board_buffer = (int*)malloc(sizeof(int) * CELL_WIDTH * CELL_HEIGHT); board_float = (double*)malloc(sizeof(double) * CELL_WIDTH * CELL_HEIGHT); board_buffer_float = (double*)malloc(sizeof(double) * CELL_WIDTH * CELL_HEIGHT); born = (double*)malloc(sizeof(double) * 18); stay_alive = (born+9); r_i = R_I; r_a = R_A; alpha_n = ALPHA_N; alpha_m = ALPHA_M; b1 = B1; b2 = B2; d1 = D1; d2 = D2; density = 50; num_gliders = 4; changing_background = true; pause = false; set_rules_to_life(); update_algorithm = 0; } Board::~Board() { free(board); free(board_buffer); free(born); free(stay_alive); } //randomly initializes the board with density percent alive //cells void Board::init_board() { for(int i = 0; i < CELL_WIDTH; i++) { for(int j = 0; j < CELL_HEIGHT; j++) { board[j*CELL_WIDTH+i] = (rand()%100 < density ? 1 : -1); } } } //puts num_gliders/4 dots of side length density/10 in each of the //four quadrants. There is vertical and horizontal symmetry void Board::init_quadrants() { clear_board(); int x, y; for(int i = 0; i < num_gliders / 4; i++) { x = rand() % (CELL_WIDTH/2 - density/10); y = rand() % (CELL_HEIGHT/2 - density/10); //u++ <=> u = u + 1 for(int u = 0; u < density/10; u++) { for(int v = 0; v < density/10; v++) { //top left board[(y+u)*CELL_WIDTH+(x+v)] = 1; //top right quadrant board[(y+u)*CELL_WIDTH+(CELL_WIDTH-x-v)] = 1; //bottom left board[(CELL_HEIGHT-y-u)*CELL_WIDTH+(x+v)] = 1; //bottom right board[(CELL_HEIGHT-y-u)*CELL_WIDTH+(CELL_WIDTH-x-v)] = 1; } } } } //clears the board and draws a dot in the center with side length density/10 void Board::init_center_dot() { clear_board(); int s = density/10; for(int i = (CELL_WIDTH - s)/2; i < (CELL_WIDTH + s)/2; i++ ) { for(int j = (CELL_HEIGHT - s)/2; j < (CELL_HEIGHT + s)/2; j++ ) { board[j*CELL_WIDTH+i] = 1; } } } void Board::init_smooth_life() { for(int i = 0; i < CELL_WIDTH; i++) { for(int j = 0; j < CELL_HEIGHT; j++) { board_float[j*CELL_WIDTH+i] = (rand()%100 < density ? 1 : 0); board[j*CELL_WIDTH+i] = 0; } } } //this function clears the board then makes num_glider gliders in random //locations and orientations. Makes sure to keep them away from the edge so //we don't get seg faults void Board::init_gliders() { clear_board(); for(int i = 0; i < num_gliders; i++) { make_glider(rand()%(CELL_WIDTH-10)+5, rand()%(CELL_HEIGHT-10)+5, rand()%4); } } void Board::init_square_shell() { clear_board(); int center_x = CELL_WIDTH/2; int center_y = CELL_HEIGHT/2; int side_length = rand() %(CELL_HEIGHT/2 -1) + 1; for(int i = center_x - side_length; i < center_x + side_length; i++) { for(int j = center_y - side_length; j < center_y + side_length; j++) { board[j*CELL_WIDTH+i] = 1; } } side_length--; for(int i = center_x - side_length; i < center_x + side_length; i++) { for(int j = center_y - side_length; j < center_y + side_length; j++) { board[j*CELL_WIDTH+i] = changing_background ? -1:0; } } } void Board::init_circle_shell() { clear_board(); int r = rand() % (CELL_HEIGHT/2 -1) + 1; int center_x = CELL_WIDTH/2; int center_y = CELL_HEIGHT/2; int* circle_coords = (int*)malloc(sizeof(int) * r * r * 4 * 2); get_circle(center_x, center_y, r, circle_coords); int index = 0; int i, j; while(circle_coords[index] != -1) { i = circle_coords[index]; index++; j = circle_coords[index]; index++; board[j*CELL_WIDTH+i] = 1; } r--; index = 0; get_circle(center_x, center_y, r, circle_coords); while(circle_coords[index] != -1) { i = circle_coords[index]; index++; j = circle_coords[index]; index++; board[j*CELL_WIDTH+i] = changing_background ? -1:0; } free(circle_coords); } void Board::init_triangle_shell() { clear_board(); int mag = 20 + rand() % 50;// rand() % (CELL_HEIGHT/8 -1) + 1; int* coords = (int*)malloc(2* sizeof(int) *CELL_HEIGHT * CELL_WIDTH); get_polygon(CELL_WIDTH/2, CELL_HEIGHT/2, mag, num_gliders, 0, coords); int index = 0; int i, j; while(coords[index] != -1) { i = coords[index]; index++; j = coords[index]; index++; board[j*CELL_WIDTH+i] = 1; } return; } //this function creates a glider on board at x,y in one of 4 orientations. //it just manually sets each required alive cell. Assumes that all cells are //dead in the required area. Doesn't account for the edge of the board void Board::make_glider(int x, int y, int orientation) { if(orientation == 0) { board[(y+0)*CELL_WIDTH+(x+1)]=1; board[(y+1)*CELL_WIDTH+(x+2)]=1; board[(y+2)*CELL_WIDTH+(x+0)]=1; board[(y+2)*CELL_WIDTH+(x+1)]=1; board[(y+2)*CELL_WIDTH+(x+2)]=1; } else if(orientation == 1) { board[(y+0)*CELL_WIDTH+(x+1)]=1; board[(y+0)*CELL_WIDTH+(x+2)]=1; board[(y+1)*CELL_WIDTH+(x+0)]=1; board[(y+1)*CELL_WIDTH+(x+2)]=1; board[(y+2)*CELL_WIDTH+(x+2)]=1; } else if(orientation == 2) { board[(y+0)*CELL_WIDTH+(x+1)]=1; board[(y+0)*CELL_WIDTH+(x+2)]=1; board[(y+0)*CELL_WIDTH+(x+0)]=1; board[(y+1)*CELL_WIDTH+(x+0)]=1; board[(y+2)*CELL_WIDTH+(x+1)]=1; } else if(orientation == 3) { board[(y+0)*CELL_WIDTH+(x+0)]=1; board[(y+1)*CELL_WIDTH+(x+0)]=1; board[(y+1)*CELL_WIDTH+(x+2)]=1; board[(y+2)*CELL_WIDTH+(x+0)]=1; board[(y+2)*CELL_WIDTH+(x+1)]=1; } } void Board::init_circle() { int r = rand()%30+3; int* circle_coords = (int*)malloc(sizeof(int) * r * r * 4 * 2); get_circle(rand()%CELL_WIDTH, rand()%CELL_HEIGHT-10, r, circle_coords); int index = 0; int i, j; while(circle_coords[index] != -1) { i = circle_coords[index]; index++; j = circle_coords[index]; index++; board[j*CELL_WIDTH+i] = 1; } free(circle_coords); } void Board::init_triangle() { int mag = rand()%30+10; int* coords = (int*)malloc(2* sizeof(int) *CELL_HEIGHT * CELL_WIDTH); get_mathy_triangle2(CELL_WIDTH/2, CELL_HEIGHT/2, mag, coords); int index = 0; int i, j; while(coords[index] != -1) { i = coords[index]; index++; j = coords[index]; index++; board[j*CELL_WIDTH+i] = 1; } free(coords); } //clears the board. If changing_background is true sets everything to -1 //so it will age, otherwise sets it to 0 so it won't void Board::clear_board() { for(int i = 0; i < CELL_WIDTH; i++) { for(int j = 0; j < CELL_HEIGHT; j++) { board[j*CELL_WIDTH+i]= changing_background ? -1:0 ; } } } //this function updates the board according to the ruleset void Board::update_board() { switch(update_algorithm) { case 0: update_board_normal(); break; case 1: update_board_smooth(); break; } //free our old board free(board); //put the buffer into the spotlight board = board_buffer; //and get a new buffer board_buffer = (int*)malloc(sizeof(int) * CELL_WIDTH * CELL_HEIGHT); } void Board::update_board_smooth() { double n, m, r, rr; int *points = (int*) malloc(sizeof(int) * r_a * r_a * 4 * 2); int x, y, test_x, test_y, num_m, num_n; double r_a_2 = r_a*r_a; double r_i_2 = r_i*r_i; //squares (m)inus b double r_a_2_m_b = (r_a-0.5)*(r_a-0.5); double r_i_2_m_b = (r_i-0.5)*(r_i-0.5); //squares (p)lus b double r_a_2_p_b = (r_a+0.5)*(r_a+0.5); double r_i_2_p_b = (r_i+0.5)*(r_i+0.5); //iterate over every cell for(int j = 0; j < CELL_HEIGHT; j++) { for(int i = 0; i < CELL_WIDTH; i++) { /*get_circle(i, j, r_i, points); x = 0; y = 1; n = 0; num_n = 0; while(points[x] != -1) { n += board_float[points[y]*CELL_WIDTH+points[x]]; num_n++; x += 2; y += 2; } get_circle(i, j, r_a, points); x = 0; y = 1; m = 0; num_m = 0; while(points[x] != -1) { m += board_float[points[y]*CELL_WIDTH+points[x]]; num_m++; x += 2; y += 2; }*/ n = 0; m = 0; num_n = 0; num_m = 0; for(y = -r_a; y <= r_a; y++) { test_y = j + y; if(test_y < 0) test_y += CELL_HEIGHT; else if(test_y >= CELL_HEIGHT) test_y -= CELL_HEIGHT; for(x = -r_a; x <= r_a; x++) { test_x = i + x; if(test_x < 0) test_x += CELL_WIDTH; else if(test_x >= CELL_WIDTH) test_x -= CELL_WIDTH; //int yspan = r*sin(acos(-i/r)); //for(int j = -yspan; j <= yspan; j++) { rr = x*x + y*y; r = sqrt(rr); if(rr <= r_i_2_m_b) { n += board_float[test_y*CELL_WIDTH+test_x]; } else if(rr <= r_i_2_p_b) { n += (r_i+0.5-r)*board_float[test_y*CELL_WIDTH+test_x]; } if(rr <= r_a_2_m_b && rr >= r_i_2_p_b) { m += board_float[test_y*CELL_WIDTH+test_x]; } else if(rr <= r_a_2_p_b && rr >= r_a_2_m_b) { m += (r_a+0.5-r)*board_float[test_y*CELL_WIDTH+test_x]; } else if(rr <= r_i_2_p_b && rr >= r_i_2_m_b) { m += (r_a+0.5-r)*board_float[test_y*CELL_WIDTH+test_x]; } } } //std::cout << "n " << n << std::endl; //std::cout << "m " << m << std::endl; //m = m - n; //num_m = num_m - num_n; n = n / (r_i_2 * PI); m = m / (PI * (r_a_2 - r_i_2)); //n = n / num_n; //m = m / num_m; double new_val = s(n, m); board_buffer_float[j*CELL_WIDTH+i] = new_val; if(new_val < 0.01 && board_float[j*CELL_WIDTH+i] < 0.01) { board_buffer[j*CELL_WIDTH + i]--; } else if (new_val >= 0.01 && board_float[j*CELL_WIDTH+i] >= 0.01) { board_buffer[j*CELL_WIDTH + i]++; } else { board_buffer[j*CELL_WIDTH + i] = 0; } } } free(points); //free our old board free(board_float); //put the buffer into the spotlight board_float = board_buffer_float; //and get a new buffer board_buffer_float = (double*)malloc(sizeof(double) * CELL_WIDTH * CELL_HEIGHT); } double Board::s1(double x, double a, double alpha) { double to_return = 1/(1 + exp(((a-x) * 4)/alpha)); return to_return; } double Board::s2(double x, double a, double b) { double to_return = s1(x, a, alpha_n) * (1 - s1(x, b, alpha_n)); return to_return; } double Board::sm(double x, double y, double m) { double to_return = x * (1 - s1(m, 0.5, alpha_m)) + y * s1(m, 0.5, alpha_m); return to_return; } double Board::s(double n, double m) { double to_return = s2(n, sm(b1, d1, m), sm(b2, d2, m)); return to_return; } void Board::update_board_normal() { //if we're paused, just update the colors if(pause) { update_colors(); return; } //if a cell is positive it's alive, if it's negative or 0 then it's dead. //the actual value is how many generations it has been alive. //if the value is 0 then that dead cell is not supposed to age //this is how the non-changing background is implemented //iterate over every cell for(int j = 0; j < CELL_HEIGHT; j++) { for(int i = 0; i < CELL_WIDTH; i++) { //get how many alive neighbors it has int neighbors = get_num_alive_neighbors(i, j); //if dead if(board[j*CELL_WIDTH+i] <= 0) { //if supposed to be born if(born[neighbors] >= dist(e2)) // then make it alive with an age of 1 board_buffer[j*CELL_WIDTH+i] = 1; //if its still dead //and it's aging else if(board[j*CELL_WIDTH+i] < 0) //then age it board_buffer[j*CELL_WIDTH+i] = board[j*CELL_WIDTH+i] - 1; else //keep it dead board_buffer[j*CELL_WIDTH+i] = 0; } //if alive else { //and it's supposed to stay alive, and it's not older than the max age if(stay_alive[neighbors] >= dist(e2)) //then age it board_buffer[j*CELL_WIDTH+i] = board[j*CELL_WIDTH+i] + 1; else //otherwise kill it board_buffer[j*CELL_WIDTH+i] = -1; } } } } //this gets the number of alive neighbors, wraps around edges so our real shape //is a donut int Board::get_num_alive_neighbors(int x, int y) { int count = 0; int check_x, check_y; //iterate over the 3x3 square around x,y for(int j = y-1; j <= y+1; j++) { for(int i = x-1; i <= x+1; i++) { check_x = i; check_y = j; //if we're on x,y skip it if(j==y && i==x) continue; //if we're past any edges, wrap around to the other side if(j < 0) check_y = CELL_HEIGHT-1; if(j >= CELL_HEIGHT) check_y = 0; if(i < 0) check_x = CELL_WIDTH-1; if(i >= CELL_WIDTH) check_x = 0; //and check the coordinate, if it's alive increase count if(board[check_y*CELL_WIDTH+check_x] > 0) count++; } } return count; } //this function just updates the colors without updating the board void Board::update_colors() { //iterate over the whole board for(int j = 0; j < CELL_HEIGHT; j++) { for(int i = 0; i < CELL_WIDTH; i++) { //increase age if alive if(board[j*CELL_WIDTH+i] > 0) board_buffer[j*CELL_WIDTH+i] = board[j*CELL_WIDTH+i] + 1; //and increase age if dead and supposed to change else if(board[j*CELL_WIDTH+i] < 0) board_buffer[j*CELL_WIDTH+i] = board[j*CELL_WIDTH+i] - 1; } } } void Board::set_rules_to_life() { //initial rules for the automata is game of life //int life_born[9] = {0,1,1,1,1,0,0,1,0}; //int life_stay_alive[9] = {0,1,1,0,0,1,1,1,1}; //copier //int life_born[9] = {0,1,0,1,0,1,0,1,0}; //int life_stay_alive[9] = {0,1,0,1,0,1,0,1,0}; //vote int life_born[9] = {0,0,0,0,1,0,1,1,1}; int life_stay_alive[9] = {0,0,0,1,0,1,1,1,1}; //float life_born[9] = {-.0224982,-0.0439246,0.16508,-0.381114,0.0156361,0.254988,0.354988,0.2501,0.31466}; //float life_stay_alive[9] = {1,1,1,1,1,1,1,1,1}; free(born); born = (double*)malloc(sizeof(double) * 18); stay_alive = (born + 9); for(int i = 0; i < 9; i++) { born[i] = life_born[i]; stay_alive[i] = life_stay_alive[i]; } } // 0 1 1 1 1 0 0 1 0 // 1 1 1 0 0 1 1 1 1c int* Board::get_board() { return board; } double* Board::get_board_float() { return board_float; } void Board::randomize_rules() { for(int i = 0; i < 9; i++) { born[i] = (rand()%100>20 ? 1 : 0); stay_alive[i] = (rand()%100>20 ? 1 : 0); } } void Board::randomize_rules_non_deterministic() { std::normal_distribution<> ndist(0.0, 0.3); for(int i = 0; i < 9; i++) { born[i] = (rand()%100>20 ? ndist(e2) : 0); stay_alive[i] = (rand()%100>10 ? 1 : 0); } } void Board::randomize_rules_smooth() { std::normal_distribution<> ndist(0.01, 1.0); r_a = (ndist(e2)+1) * 15; r_i = r_a / ((ndist(e2) + 0.5)*3); alpha_n = ndist(e2)/5; alpha_m = ndist(e2)/5; b1 = ndist(e2)/2 * 0.1; b2 = b1 + ndist(e2)/3; d1 = ndist(e2)/2 * 0.1; d2 = b1 + ndist(e2)/3; } void Board::set_density(int new_density) { density = new_density; } void Board::set_update_algorithm(int new_algorithm) { update_algorithm = new_algorithm; } void Board::modify_gliders(int factor) { num_gliders += factor; if(num_gliders < 2) num_gliders = 2; } void Board::toggle_changing_background() { changing_background = !changing_background; } void Board::toggle_pause() { pause = !pause; } void Board::rules_pretty() { gen.add_seed(born); born = gen.generate_one_mean(); stay_alive = (born + 9); init_center_dot(); } void Board::rules_not_pretty() { free(born); born = gen.generate_one_mean(); stay_alive = (born + 9); init_center_dot(); } void Board::rules_pretty_float() { gen.add_seed(born); born = gen.generate_one_mean_float(); stay_alive = (born + 9); init_center_dot(); } void Board::rules_not_pretty_float() { free(born); born = gen.generate_one_mean_float(); stay_alive = (born + 9); init_center_dot(); } void Board::get_mathy_triangle2(int center_x, int center_y, int mag, int* points) { int index = 0; std::uniform_real_distribution<> udist(-PI, PI); std::uniform_real_distribution<> udist2(0.45*PI, 0.65*PI); float theta = udist(e2); float v1[2] = {std::sin(theta), std::cos(theta)}; theta = theta + udist2(e2); float v2[2] = {std::sin(theta), std::cos(theta)}; float v3[2] = {-1*(v1[0]+v2[0]), -1*(v1[1]+v2[1])}; float norm_factor = v3[0]*v3[0] + v3[1]*v3[1]; v3[0] = v3[0] / norm_factor; v3[1] = v3[1] / norm_factor; for(int i = 0; i < CELL_WIDTH; i++) { for(int j = 0; j < CELL_HEIGHT; j++) { float x = i-center_x; float y = j-center_y; bool inside = true; inside = inside && (x*v1[0] + y*v1[1]) < mag; inside = inside && (x*v2[0] + y*v2[1]) < mag; inside = inside && (x*v3[0] + y*v3[1]) < mag; if(inside) { points[index] = i; index++; points[index] = j; index++; } } } points[index] = -1; } void Board::get_polygon(int center_x, int center_y, int mag, int dim, float irreg, int* points) { int index = 0; std::uniform_real_distribution<> udist(-PI, PI); std::uniform_real_distribution<> udist2((1-irreg)* 2*PI/dim, (1+irreg)*2*PI/dim); float **v = (float**)malloc(sizeof(float*)*dim); float x_sum = 0, y_sum = 0; float theta = udist(e2); int k; for(k = 0; k < dim - 1; k++) { theta += udist2(e2); v[k] = (float*)malloc(sizeof(float) * 2); v[k][0] = std::cos(theta); v[k][1] = std::sin(theta); x_sum += v[k][0]; y_sum += v[k][1]; } v[k] = (float*)malloc(sizeof(float) * 2); v[k][0] = -1*x_sum; v[k][1] = -1*y_sum; float norm_factor = v[k][0]*v[k][0] + v[k][1]*v[k][1]; v[k][0] = v[k][0] / norm_factor; v[k][1] = v[k][1] / norm_factor; for(int i = 0; i < CELL_WIDTH; i++) { for(int j = 0; j < CELL_HEIGHT; j++) { float x = i-center_x; float y = j-center_y; bool inside1 = true; bool inside2 = false; for(int k = 0; k < dim; k++) { inside1 = inside1 && (x*v[k][0] + y*v[k][1]) < mag; inside2 = inside2 || (x*v[k][0] + y*v[k][1]) > mag - 5; } if(inside1 && inside2) { points[index] = i; index++; points[index] = j; index++; } /*if(inside2) { points2[index] = i; index++; points2[index] = j; index++; }*/ } } points[index] = -1; } void Board::get_circle(int x, int y, int r, int* points) { int index = 0; int test_x, test_y; int rsquared = r*r; for(int i = -r; i <= r; i++) { test_x = i + x; if(test_x < 0) test_x += CELL_WIDTH; else if(test_x >= CELL_WIDTH) test_x -= CELL_WIDTH; //int yspan = r*sin(acos(-i/r)); //for(int j = -yspan; j <= yspan; j++) { for(int j = -r; j <= r; j++) { test_y = j + y; if(test_y < 0) test_y += CELL_HEIGHT; else if(test_y >= CELL_HEIGHT) test_y -= CELL_HEIGHT; if(i * i + j * j <= rsquared) { points[index] = test_x; index++; points[index] = test_y; index++; } } } points[index] = -1; } void Board::print_rules() { for(int i = 0; i < 9; i++) { std::cout << born[i] << " "; } std::cout << std::endl; for(int i = 0; i < 9; i++) { std::cout << stay_alive[i] << " "; } std::cout << std::endl; std::cout << std::endl; } <file_sep>/Genetics/src/RuleGenerator.cpp #include "RuleGenerator.h" RuleGenerator::RuleGenerator() { } RuleGenerator::~RuleGenerator() { //dtor } int* RuleGenerator::generate_one_mean() { double probabilities[18]; int *to_return = (int*) malloc(sizeof(int) * 18); for(int i = 0; i < 18; i++) { probabilities[i] = 0; } for(std::deque<int*>::iterator it = seeds.begin(); it != seeds.end(); it++) { for(int k = 0; k < 18; k++) { probabilities[k] += (*it)[k]; } } for(int i = 0; i < 18; i++) { probabilities[i] = probabilities[i] / seeds.size(); } for(int i = 0; i < 18; i++) { to_return[i] = probabilities[i] >= (random_double() - 0.1) ? 1 : 0; } return to_return; } void RuleGenerator::add_seed(int* seed) { seeds.push_back(seed); } void RuleGenerator::print_seeds() { for(std::deque<int*>::iterator it = seeds.begin(); it != seeds.end(); it++) { print_array(*it); } } void RuleGenerator::print_array(int *to_print) { std::cout << "[ "; for(int i = 0; i < 18; i++) { std::cout << to_print[i] << " "; } std::cout << "]" << std::endl; return; } double RuleGenerator::random_double() { double f = (double)rand() / RAND_MAX; return f; } <file_sep>/main.cpp // // main.m // Colors // // #include <iostream> #include <time.h> #include <SDL2/SDL.h> #include "board.h" #include "screen.h" #include "RuleGenerator.h" //this function checks if there is user input and reacts accordingly //returns whether the program should keep running, //false if it should quit, true if it should continue bool do_user_input(Board *board, Screen *screen) { static SDL_Event events; while(SDL_PollEvent(&events)) { switch(events.type) { case SDL_QUIT: return false; break; case SDL_KEYDOWN: switch(events.key.keysym.sym) { case SDLK_q: return false; break; //increases the number of gliders by 1 case SDLK_UP: board->modify_gliders(1); break; //decreases the number of gliders to generate by 1 case SDLK_DOWN: board->modify_gliders(-1); break; //increases the number of gliders by 4 case SDLK_RIGHT: board->modify_gliders(4); break; //decreases the number of gliders to generate by 4 case SDLK_LEFT: board->modify_gliders(-4); break; //creates num_gliders gliders in random positions on the board case SDLK_g: board->init_gliders(); break; //randomizes the whole board case SDLK_SPACE: board->init_board(); break; //clears the board case SDLK_z: board->clear_board(); break; //adds a circle to the board case SDLK_o: board->init_circle(); break; //randomizes the cellular automata ruleset case SDLK_d: board->randomize_rules(); screen->reset_colors(); break; case SDLK_j: board->randomize_rules_smooth(); board->init_smooth_life(); break; //randomizes the cellular automata ruleset with nondeterministic behavior case SDLK_r: board->randomize_rules_non_deterministic(); screen->reset_colors(); break; //changes rules to life case SDLK_l: board->set_rules_to_life(); screen->reset_colors(); break; //draws num_gliders/4 dots of side length density/10 symmetrically in each quadrant case SDLK_w: board->init_circle_shell(); break; case SDLK_t: board->init_triangle_shell(); break; case SDLK_e: board->init_quadrants(); break; //toggles between black and white and colors case SDLK_c: screen->flip_draw_colors(); break; //randomize colors case SDLK_x: screen->reset_colors(); break; //makes a center square of side length density/10 case SDLK_a: board->init_center_dot(); break; case SDLK_s: board->init_square_shell(); break; //toggles between having the background case SDLK_v: board->toggle_changing_background(); break; case SDLK_k: board->init_smooth_life(); break; //set board to normal automata case SDLK_n: board->set_update_algorithm(0); screen->flip_draw_smooth(); break; //set board to smooth automata case SDLK_m: board->set_update_algorithm(1); board->init_smooth_life(); screen->flip_draw_smooth(); break; case SDLK_p: board->print_rules(); break; // this changes the density of live cells that random scenes // are generated with-> The integer is the percent alive cells case SDLK_0: board->set_density(0); break; case SDLK_1: board->set_density(10); break; case SDLK_2: board->set_density(20); break; case SDLK_3: board->set_density(30); break; case SDLK_4: board->set_density(40); break; case SDLK_5: board->set_density(50); break; case SDLK_6: board->set_density(60); break; case SDLK_7: board->set_density(70); break; case SDLK_8: board->set_density(80); break; case SDLK_9: board->set_density(90); break; case SDLK_LSHIFT: board->toggle_pause(); break; // these change how fast the colors cycle, higher divisor means slower case SDLK_F1: screen->set_color_speed_divisor(1); break; case SDLK_F2: screen->set_color_speed_divisor(2); break; case SDLK_F3: screen->set_color_speed_divisor(4); break; case SDLK_F4: screen->set_color_speed_divisor(7); break; case SDLK_F5: screen->set_color_speed_divisor(11); break; case SDLK_F6: screen->set_color_speed_divisor(16); break; case SDLK_F7: screen->set_color_speed_divisor(22); break; case SDLK_F8: screen->set_color_speed_divisor(29); break; case SDLK_F9: screen->set_color_speed_divisor(37); break; case SDLK_F10: screen->set_color_speed_divisor(46); break; case SDLK_F11: screen->set_color_speed_divisor(56); break; case SDLK_F12: screen->set_color_speed_divisor(67); break; case SDLK_EQUALS: board->rules_pretty(); screen->reset_colors(); break; case SDLK_MINUS: board->rules_not_pretty(); screen->reset_colors(); break; case SDLK_LEFTBRACKET: board->rules_not_pretty_float(); screen->reset_colors(); break; case SDLK_RIGHTBRACKET: board->rules_pretty_float(); screen->reset_colors(); break; } } } return true; } void teststuff() { RuleGenerator gen(20); double *seed = (double*) malloc(18*sizeof(double)); for(int i = 0; i < 18; i++) { seed[i] = 1; } gen.print_array(seed); gen.add_seed(seed); seed = gen.generate_one_mean_float(); gen.print_array(seed); return; } int main(int argc, char * arg[]) { srand (time(NULL)); //teststuff(); //return 0; Board board; //return 0; Screen screen(&board); board.init_board(); board.set_update_algorithm(0); board.init_board(); bool running = true; while(running) { //translate board to pixels screen.draw_board(); //and draw it screen.update_window(); board.update_board(); running = do_user_input(&board, &screen); } //return (this deconstructs screen and board and thus cleans up everything) return 0; } <file_sep>/README.md # Colors Milestones: 1) Clean up/rewrite code from colors prototype to allow easier additions 2) Implement genetic selection algorithm a) add a way to save cellular automata rulesets b) create an algorithm to combine parent rulesets into children i) create infrastructure to preset children to user and have them pick which become parents c) tune above to make it prettier 3) Implement music sync a) get input from microphone or system sounds b) FFT the raw data c) figure out how to apply it to the cells to make the whole thing prettier Measurements of success 1) Is it prettier than before? 2) Did I learn about genetic algorithms? 3) Did I learn about FFT? <file_sep>/Genetics/include/RuleGenerator.h #ifndef RULEGENERATOR_H #define RULEGENERATOR_H #include <algorithm> // std::random_shuffle #include <deque> // std::vector #include <ctime> // std::time #include <cstdlib> // std::rand, std::srand #include <iostream> class RuleGenerator { public: RuleGenerator(); virtual ~RuleGenerator(); int* generate_one_mean(); void add_seed(int* seed); void print_seeds(); protected: private: std::deque<int*> seeds; void print_array(int *to_print); double random_double(); }; #endif // RULEGENERATOR_H <file_sep>/RuleGenerator.cpp #include "RuleGenerator.h" RuleGenerator::RuleGenerator(unsigned int new_max_seeds) { max_seeds = new_max_seeds; } RuleGenerator::~RuleGenerator() { //dtor } double* RuleGenerator::generate_one_mean() { double probabilities[18]; double *to_return = (double*) malloc(sizeof(double) * 18); for(int i = 0; i < 18; i++) { probabilities[i] = 0; } for(std::deque<double*>::iterator it = seeds.begin(); it != seeds.end(); it++) { for(int k = 0; k < 18; k++) { probabilities[k] += (*it)[k]; } } for(int i = 0; i < 18; i++) { probabilities[i] = probabilities[i] / seeds.size(); } for(int i = 0; i < 18; i++) { to_return[i] = probabilities[i] >= (random_double() - 0.1) ? 1 : 0; } return to_return; } double* RuleGenerator::generate_one_mean_float() { double probabilities[18]; double *to_return = (double*) malloc(sizeof(double) * 18); for(int i = 0; i < 18; i++) { probabilities[i] = 0; } for(std::deque<double*>::iterator it = seeds.begin(); it != seeds.end(); it++) { for(int k = 0; k < 18; k++) { probabilities[k] += (*it)[k]; } } for(int i = 0; i < 18; i++) { probabilities[i] = probabilities[i] / seeds.size(); } int i; for(i = 0; i < 9; i++) { to_return[i] = probabilities[i] + ((random_double() < 0.5) ? -0.1 : 0.1); } for(; i < 18; i++) { to_return[i] = probabilities[i] >= (random_double() - 0.1) ? 1 : 0; } return to_return; } void RuleGenerator::add_seed(double* seed) { seeds.push_back(seed); if(seeds.size() > max_seeds) { free(seeds.front()); seeds.pop_front(); } } void RuleGenerator::print_seeds() { for(std::deque<double*>::iterator it = seeds.begin(); it != seeds.end(); it++) { print_array(*it); } } void RuleGenerator::print_array(double *to_print) { std::cout << "[ "; for(int i = 0; i < 18; i++) { std::cout << to_print[i] << " "; } std::cout << "]" << std::endl; return; } double RuleGenerator::random_double() { double f = (double)rand() / RAND_MAX; return f; } <file_sep>/RuleGenerator.h #ifndef RULEGENERATOR_H #define RULEGENERATOR_H #include <algorithm> // std::random_shuffle #include <deque> // std::deque #include <ctime> // std::time #include <cstdlib> // std::rand, std::srand #include <iostream> class RuleGenerator { public: RuleGenerator(unsigned int new_max_seeds); virtual ~RuleGenerator(); double* generate_one_mean(); double* generate_one_mean_float(); void add_seed(double* seed); void print_seeds(); void print_array(double *to_print); protected: private: unsigned int max_seeds; std::deque<double*> seeds; double random_double(); }; #endif // RULEGENERATOR_H <file_sep>/info.h #ifndef INFO_H_INCLUDED #define INFO_H_INCLUDED //define the size of your screen #define SCREEN_HEIGHT 1080 #define SCREEN_WIDTH 1920 //the size of each cell #define PIXELS_PER_CELL 2 //and how many cells are in it #define CELL_HEIGHT SCREEN_HEIGHT/PIXELS_PER_CELL #define CELL_WIDTH SCREEN_WIDTH/PIXELS_PER_CELL #endif // INFO_H_INCLUDED <file_sep>/Genetics/main.cpp #include <iostream> #include <fstream> #include <string> #include "RuleGenerator.h" using namespace std; void print_array(int *to_print) { cout << "[ "; for(int i = 0; i < 18; i++) { cout << to_print[i] << " "; } cout << "]" << endl; return; } void load_file(string filename, RuleGenerator *gen) { ifstream seed_file; seed_file.open(filename.c_str()); string line; if (seed_file.is_open()) { while (getline(seed_file, line)) { int *next_seed = (int*) malloc(sizeof(int) * 18); for(std::string::size_type i = 0; i < line.size(); ++i) { next_seed[i] = (line[i] == '1') ? 1 : 0; } print_array(next_seed); gen->add_seed(next_seed); } seed_file.close(); } } int main() { RuleGenerator gen; srand (time(NULL)); string seed_filename; cout << "type filename" << endl; cin >> seed_filename; if(seed_filename == "a") seed_filename = "test_seeds1.txt"; load_file(seed_filename, &gen); cout << "loaded seeds are: " << endl; gen.print_seeds(); cout << "generated seeds are: " << endl; for(int i = 0; i < 20; i++) { int *test = gen.generate_one_mean(); print_array(test); free(test); } return 0; } <file_sep>/board.h #ifndef BOARD_H_INCLUDED #define BOARD_H_INCLUDED #include <stdlib.h> #include <random> #include <time.h> #include <math.h> #include <iostream> #include <algorithm> #include "info.h" #include "RuleGenerator.h" #define SMOOTH_MAX RAND_MAX #define R_I 7 #define R_A 21 #define ALPHA_N 0.028 #define ALPHA_M 0.147 #define B1 0.2 #define B2 0.365 #define D1 0.30 #define D2 0.549 #define PI 3.14159265359 class Board { private: int *board; int *board_buffer; double *board_float; double *board_buffer_float; double *born; double *stay_alive; double *smooth_rules; int density; int num_gliders; int update_algorithm; bool changing_background; bool pause; RuleGenerator gen; double r_i; double r_a; double alpha_n; double alpha_m; double b1; double b2; double d1; double d2; std::mt19937 e2; std::uniform_real_distribution<double> dist; void get_circle(int x, int y, int r, int* points); void get_polygon(int x, int y, int mag, int dim, float irreg, int* points); void get_mathy_triangle2(int x, int y, int mag, int* points); void update_board_normal(); void update_board_smooth(); double s1(double x, double a, double alpha); double s2(double x, double a, double b); double sm(double x, double y, double m); double s(double n, double m); public: Board(); ~Board(); void init_board(); void init_quadrants(); void init_center_dot(); void init_gliders(); void init_circle(); void init_triangle(); void init_smooth_life(); void init_square_shell(); void init_circle_shell(); void init_triangle_shell(); void make_glider(int x, int y, int orientation); void clear_board(); void update_board(); int get_num_alive_neighbors(int x, int y); void update_colors(); int* get_board(); double *get_board_float(); void set_rules_to_life(); void randomize_rules(); void randomize_rules_non_deterministic(); void randomize_rules_smooth(); void set_density(int new_density); void set_update_algorithm(int new_algorithm); void modify_gliders(int factor); void toggle_changing_background(); void toggle_pause(); void rules_pretty(); void rules_not_pretty(); void rules_pretty_float(); void rules_not_pretty_float(); void print_rules(); }; #endif // BOARD_H_INCLUDED
09620c12685acb74c8b015ac40d84e1dd7ea295e
[ "Markdown", "C", "C++" ]
10
C++
jgreef/Colors
9426fc33f58bbde3a8cbd488d91c0b0be23b5261
c5a00cfe17afbf6a3561b7337fe5f7faed4d78e4
refs/heads/master
<file_sep>#include <cstdio> #include <iostream> using namespace std; //class simple way... /* class C1{ int i = 0; public: void setvalue(int value){i = value;} int getvalue(){return i;} }; */ //class proper way... class C1{ int i = 0; public: void setvalue(int value); int getvalue(); }; void C1::setvalue(int value){ i = value; } int C1::getvalue(){ return i; } // can change this to a call by reference with (int & i) //void func(int i){ int func(int i){ //int answer = i*i; return i*i; } int main() { int i = 47; // class then object // C1 o1; o1.setvalue(i); printf("this is the value %d\n", o1.getvalue()); //int x = 7; //int y = 42; //int *ip = &x; //printf("the value of x is %d\n", x); //printf("the value of y is %d\n", y); //printf("the value of *ip is %d\n", *ip); //int ans = func(x); //printf("the result of the func is %d\n", ans); return 0; } <file_sep>#include <iostream> using namespace std; /* int main() { try{ int moms_age = 50; int sons_age = 45; if (sons_age > moms_age){ throw 99; } } catch(int x){ cout << "son cannot be older than mom, ERROR NUMBER: " << x << endl; } cout << "done" << endl; } */ int main() { try{ int num1; cout << "enter the first number: " << endl; cin >> num1; int num2; cout << "enter the second number: " << endl; cin >> num2; if (num2 ==0){ throw 0; } cout << num1/num2 << endl; }catch(int x){ cout << "cant do it!" << endl; } }<file_sep>#include <iostream> using namespace std; int main(){ cout << "just a test.. so eat a dick.. and again " << endl; return 0; }<file_sep>// // testing.cpp // // // Created by <NAME> on 10/27/19. // #include "testing.hpp" int main(){ puts("just trying"); return 0; } <file_sep>#include <iostream> using namespace std; int main() { //declaring variable int a; int b; int sum; cout << "enter a number hoss! \n"; //takes info from user and inputs it into computer cin >> a; cout << "enter another number \n"; cin >> b; sum = a + b; cout << "the answer is: " << sum << endl; return 0; } <file_sep>// // testing.hpp // // // Created by <NAME> on 10/27/19. // #ifndef testing_hpp #define testing_hpp #include <stdio.h> #endif /* testing_hpp */ <file_sep>#include <fstream> #include <iostream> #include <vector> #include <sstream> #include <string> using namespace std; int main(){ ifstream infile; infile.open("list.txt"); if (infile.fail()){ cerr << "ooooops" << endl; exit(1); } string item; int count =0; // read file until the end // while (!infile.eof()){ infile >> item; count ++; } infile.close() return 0; }<file_sep>#include <cstddef> #include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; int main(){ int bertha[2][3] = {{1,2,3}, {7,8,9}}; int doug[2][3] = {{1,5,3}, {7,6,9}}; for (int row=0; row<2; row++){ for (int col=0; col<3; col++){ cout << " bertha: " << bertha[row][col] << " __ " << " doug: " << doug[row][col] << endl; } cout << endl; } } <file_sep>#include <iostream> using namespace std; // this is called prototyping a function // just add this at the top if you have written the function below void print_something(); int main() { // >,< <=, >=, ==, != if(3 == 3){ cout << "cats and dogs" << endl; } print_something(); } // this is making a new function // need to declare return type first!!! // void will return whatever.. void print_something(){ cout << "ooo i am txt on the screen" << endl; } <file_sep>#include <iostream> using namespace std; int main() { cout << "this is the end... 4 u so dont even try" << endl; cout << "you are a slimy dick " << endl; return 0; } <file_sep>#include <iostream> using namespace std; int main() { //addition int x = 4+5; cout << x << endl; // subtraction int y = 5-4; cout << y << endl; // multiplication int z = 4*2; cout << z << endl; // division int a = 81 / 3; cout << a << endl; // to get the remainder use 'modulis' --> % return 0; } <file_sep># cpp `g++ -o <name_of_output> name_of_cpp_file.cpp` <file_sep> // these are the includes, which is basically like 'import' in python // 'pre-processor directive' #include <cstdio> //this stands for standard library using namespace std; // all programs enter thru the main () function int main() { // this is a read only variable, it can NEVER be changed by the progrmam // the variable with ALWAYS remain 7 const int i = 7; // keep in mind you have to declare the TYPE of the variable int x = 12; // here is an example of a pointer int *ip = &x; // this is example of a reference int &y = x; // to declare y as a new int will change what is in memory, // which was being pointed to by x AND y, so now the memory will // change what x was pointing at y = 42; // a reference is NOT a variable, it is just a reference to memory !! // // use 'const' if you never want a variable to change puts("hello people"); printf("the value of *ip is %d\n", *ip); printf("the value of x is %d\n", x); printf("the value of y is %d\n", y); // array // string char s[] = "just something"; printf("string is: %s\n", s); // null terminated string char t[] = { 'S','T', 'O', 'P', 0 }; printf("this is the null string: %s\n", t); // for loop over the null terminated string we made for(int i =0; t[i] !=0; ++i) { printf("the char is: %c\n", t[i]); } // conditional value is either 0 (false) or 1(non-zero) (true) return 0; } <file_sep>#include <fstream> #include <iostream> #include <vector> #include <sstream> #include <string> using namespace std; //std::ifstream input("HXB2_prrt.fa"); int main(){ ifstream hxb2; hxb2.open("HXB2_prrt.fa"); string header; string sequence; string line; vector<pair<string, string> > sequences; while( getline (hxb2, line)) { //cout << "line in the file: " << line << endl; if (line.rfind(">",0)==0) { if (!sequence.empty()){ sequences.push_back(make_pair(header,sequence)); } header = line; sequence.clear(); } else { sequence += line; } } if (!sequence.empty()){ sequences.push_back(make_pair(header,sequence)); } hxb2.close(); vector<string> dogs; for (auto const& i: sequences) { // this is where we will encrypt the second item to make a vector //cout << i.first << endl << i.second << endl; dogs.push_back(i.second); } for (auto const& i: dogs) { // this is where we will encrypt the second item to make a vector //cout << i.first << endl << i.second << endl; cout << "within dog: " << i << endl; } // this way works, lets try a new way // /* // check for error if (input.fail()){ cerr << " oooooops " << endl; exit(1); } string item; int count = 0; while(!input.eof()){ input >> item; cout << item << endl; count++; } */ return 0; } <file_sep> #include <iostream> #include <list> #include <vector> using namespace std; int main() { int dogs[10] = {1,2,3,4,5,6,7,8,9,10}; int cats[10] = {1,2,13,4,15,6,7,8,9,20}; std::vector<int> my_list; //cout << dogs[3] << endl; for(int x = 0; x<= 9; x++){ //cout << "position:" << x+1 << " " << dogs[x] << " -------- " << cats[x] << endl; if (dogs[x] != cats[x]){ //cout << dogs[x] << " -------- " << cats[x] << endl; my_list.push_back(1); } } cout << "the total number of differences is: --> " << my_list.size() << endl; return 0; }
7dcbd18824fa365ad8db1c65158335c79b7c54ca
[ "Markdown", "C++" ]
15
C++
jzehr/cpp
e5672e0440e254ea7b18b964d9551062fef0d622
b31b42e58f9197a0da8e9f7ce3fa6ec04662dade
refs/heads/master
<file_sep>import React from 'react'; import Settings from './settings'; import Introduction from './introduction'; import aStarSolver from '../util/a_star_solver'; import $ from 'jquery'; class App extends React.Component { constructor() { super(); this.state = { startDrag: false, endDrag: false, wallDrag: false, solving: false, solved: false }; this.createGrid = this.createGrid.bind(this); this.resetMaze = this.resetMaze.bind(this); this.randomWalls = this.randomWalls.bind(this); this.solve = this.solve.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleMouseOver = this.handleMouseOver.bind(this); } componentWillMount() { this.createGrid(); } componentDidMount() { document.addEventListener('mouseup', () => { this.setState({ startDrag: false, endDrag: false, wallDrag: false }); }); } createGrid() { if (this.state.solving) return; let grid = initialGrid(); let height = grid.length; let width = grid[0].length; let startPos = [ Math.floor(height * 0.5), Math.floor(width * (1/10)) ]; let endPos = [ Math.floor(height * 0.5), Math.floor(width * (9/10)) ]; grid[startPos[0]][startPos[1]].className = 'start'; grid[endPos[0]][endPos[1]].className = 'end'; this.setState({ grid: grid, startPos: startPos, endPos: endPos, solved: false }); } resetMaze() { let grid = this.state.grid; let startPos = this.state.startPos; let endPos = this.state.endPos; for (let i = 0; i < grid.length; i++) { let row = grid[i]; for (let j = 0; j < row.length; j++) { if (i === startPos[0] && j === startPos[1]) continue; if (i === endPos[0] && j === endPos[1]) continue; grid[i][j].className = 'empty'; } } this.setState({ grid: grid, solved: false }); } randomWalls() { let grid = this.state.grid; let startPos = this.state.startPos; let endPos = this.state.endPos; for (let i = 0; i < grid.length; i++) { let row = grid[i]; for (let j = 0; j < row.length; j++) { if (i === startPos[0] && j === startPos[1]) continue; if (i === endPos[0] && j === endPos[1]) continue; let option = Math.random() < 0.3 ? 'wall' : 'empty'; grid[i][j].className = option; } } this.setState({ grid: grid, solved: false }); } solve() { this.setState({ solving: true }); let grid = cloneGrid(this.state.grid); let steps = []; let recordStep = step => steps.push(step); // part of animation feature aStarSolver(grid, this.state.startPos, this.state.endPos, recordStep); this.setState({ grid: grid, solving: false, solved: true }); } // Animation is too slow. Remove this feature until it looks cleaner animateSteps(grid, steps) { let i = 0; let max = steps.length; this.interval = setInterval(() => { if (i < max) { let node = steps[i]; let pos = node.pos.join(','); document.getElementById(pos).className = node.className; i++; } else { this.setState({ grid: grid, solving: false }); clearInterval(this.interval); } }, 1); } handleMouseDown(e) { e.preventDefault(); if (this.state.solving) return; let type = e.target.className; let grid = this.state.grid; switch (type) { case 'start': return this.setState({ startDrag: true, endDrag: false }); case 'end': return this.setState({ startDrag: false, endDrag: true }); case 'empty': let emptyPos = this.grabPos(e); grid[emptyPos[0]][emptyPos[1]].className = 'wall'; return this.setState({ grid: grid, wallDrag: true }); case 'wall': let wallPos = this.grabPos(e); grid[wallPos[0]][wallPos[1]].className = 'empty'; return this.setState({ grid: grid }); default: return; } } grabPos(e) { return e.target.dataset.value.split(',').map(i => parseInt(i)); } handleMouseOver(e) { e.preventDefault(); if (this.state.solving) return; let pos = this.grabPos(e); let grid = this.state.grid; let node = grid[pos[0]][pos[1]]; if (this.state.startDrag) { let startPos = this.state.startPos; grid[startPos[0]][startPos[1]].className = 'empty'; node.className = 'start'; return this.setState({ grid: grid, startPos: pos }); } else if (this.state.endDrag) { let endPos = this.state.endPos; grid[endPos[0]][endPos[1]].className = 'empty'; node.className = 'end'; return this.setState({ grid: grid, endPos: pos }); } else if (this.state.wallDrag ) { if (node.className === 'start' || node.className === 'end') return; node.className = 'wall'; return this.setState({ grid: grid }); } } render() { let grid = this.state.grid; let table = []; for (let i = 0; i < grid.length; i++) { let nodes = []; for (let j = 0; j < grid[i].length; j++) { let node = grid[i][j]; nodes.push( <td className={node.className} id={node.pos} key={node.pos} data-value={node.pos} onMouseDown={this.handleMouseDown} onMouseOver={this.handleMouseOver} /> ); } table.push(<tr key={i}>{nodes}</tr>); } return( <div className='container'> <Introduction/> <div className='grid'> <table> <tbody> {table} </tbody> </table> </div> <Settings resetMaze={this.resetMaze} randomWalls={this.randomWalls} solve={this.solve} solved={this.state.solved} solving={this.state.solving} /> </div> ); } } const cloneGrid = grid => { let clone = []; for (let i = 0; i < grid.length; i++) { let row = []; for (let j = 0; j < grid[i].length; j++) { let node = Object.assign({}, grid[i][j]); row.push(node); } clone.push(row); } return clone; }; const windowHeight = $(window).height(); const windowWidth = $(window).width(); const intialHeight = windowHeight * 0.85 / 20; const intialWidth = windowWidth / 20; const initialGrid = () => { let grid = []; for (let i = 0; i < intialHeight; i++) { let row = []; for (let j = 0; j < intialWidth; j++) { let node = { className: 'empty', pos: [i,j] }; row.push(node); } grid.push(row); } return grid; }; const clearGrid = (grid, [names]) => { let clearedGrid = grid.map(row => { return row.map(node => { let name = node.className; node.className = names.includes(name) ? 'empty' : name; return node; }); }); return clearedGrid; }; export default App; <file_sep>import React from 'react'; import $ from 'jquery'; require('jquery-ui-bundle'); class Introduction extends React.Component { constructor() { super(); } componentDidMount() { let $instructions = $('#instructions'); $instructions.draggable(); $instructions.css({'position': 'fixed'}); $('#hide-instructions').click(() => $instructions.hide()); } render() { return ( <div id='instructions' className='draggable'> <header> <h1>A* Algorithm Visualizer <span id='hide-instructions'>hide</span> </h1> </header> <p> <span style={{textDecoration: 'underline'}}>Instructions:</span><br/> 1. Click within the white grid and drag mouse to create obstacles.<br/> 2. Drag the <span className='green'>green</span> node to set a start position.<br/> 3. Drag the <span className='red'>red</span> node to a set an end position.<br/> 4. Use the right hand-panel to clear the grid, create a random maze, or solve. </p> </div> ); } } export default Introduction; <file_sep># A* Algorithm Visualizer #### Try it out at [http://www.marcmoy.io/AStarVisualizer/](http://www.marcmoy.io/AStarVisualizer/) ![preview](preview.gif) ### Background The A* Algorithm utilizes heuristic and movement values to determine the shortest path from a start node to an end node. Nodes from an open list and a closed list are compared to a 'current' node as that node travels across the grid until the end node is found. As the current node travels across the grid, parent nodes are assigned to keep track of the path leading to the end node. Using recursion, that path is then traced back from the start node to the end node, resulting in the shortest path.
c4e3693da04147098d7cddde0e3ebea75f222cd3
[ "JavaScript", "Markdown" ]
3
JavaScript
marcmoy/AStarVisualizer
61741f5e7484dbb0e25530dca5ec7478c04e0644
55b7f15e5772e2399f506e1b5d917e9033443e66
refs/heads/master
<file_sep>#!/bin/bash format_disks(){ if [[ -z $parts ]]; then get_partitions let partcount=$(echo $parts | wc -w) let partcount+=1 fi # Generate whiptail menu command for partition formatting partmenu="whiptail --menu --noitem \"Pick a partition to format\" 15 40 $partcount" for x in $parts; do partmenu="$partmenu \"$x\" \"\"" done partmenu="$partmenu \"done\" \"\"" # Ask user for formatting preferences until done or cancel are selected partmenuchoice=$(eval $partmenu 3>&1 1>&2 2>&3) while [[ $partmenuchoice != "done" && $partmenuchoice != "" ]]; do fs=$(whiptail --menu --noitem "How would you like to format $partmenuchoice?" 13 45 5 "ext2" "" "ext3" "" "ext4" "" "vfat" "" "xfs" "" "btrfs" "" 3>&1 1>&2 2>&3) if [[ $fs != "" ]]; then eval "mkfs.$fs $partmenuchoice" fi partmenuchoice=$(eval $partmenu 3>&1 1>&2 2>&3) done } setup_swap(){ if [[ -z $parts ]]; then get_partitions let partcount=$(echo $parts | wc -w) let partcount+=1 fi # Generate swap menu command swapmenu="whiptail --menu --noitem \"Pick a partition to use as swap\" 15 35 $partcount" for x in $parts; do swapmenu="$swapmenu \"$x\" \"\"" done swapmenu="$swapmenu \"no swap\" \"\"" # Format swap partition if present swapmenuchoice=$(eval $swapmenu 3>&1 1>&2 2>&3) if [[ $swapmenuchoice != "done" && $swapmenuchoice != "" ]]; then mkswap $swapmenuchoice swapon $swapmenuchoice fi } mount_partitions(){ if [[ -z $parts ]]; then get_partitions let partcount=$(echo $parts | wc -w) let partcount+=1 fi # Generate partition mounting menu mountmenu="whiptail --menu --noitem \"Pick a partition to mount\" 15 40 $partcount" for x in $parts; do mountmenu="$mountmenu \"$x\" \"\"" done mountmenu="$mountmenu \"done\" \"\"" # Mount disk partitions mountmenuchoice=$(eval $mountmenu 3>&1 1>&2 2>&3) while [[ $mountmenuchoice != "done" && $mountmenuchoice != "" ]]; do location=$(whiptail --inputbox "Where would you like to mount $mountmenuchoice?" 10 45 3>&1 1>&2 2>&3) if [[ $location != "" ]]; then if [ ${location:0:4} == "/mnt" ]; then if [ ! -d $location]; then mkdir $location fi mount $mountmenuchoice $location else if [ ! -d "/mnt/$location" ]; then mkdir /mnt/$location fi mount $mountmenuchoice /mnt/$location fi fi mountmenuchoice=$(eval $mountmenu 3>&1 1>&2 2>&3) done } set_hostname(){ hostname=$(whiptail --inputbox "Please enter a hostname for the new system" 10 46 3>&1 1>&2 2>&3) echo $hostname > /mnt/etc/hostname } setup_network(){ wifi=$(whiptail --yesno "Are you going to use wifi?" 7 31 3>&1 1>&2 2>&3) if [[ $wifi == "yes" ]]; then arch-chroot /mnt pacman -S wpa_supplicant iw dialog fi dhcp=$(whiptail --yesno "Would you like to use DHCP?" 7 31 3>&1 1>&2 2>&3) if [[ $dhcp == "yes" ]]; then arch-chroot /mnt systemctl enable dhcpcd fi } set_timezone(){ # construct command string for time region timemenu="whiptail --menu \"Select a region\" 25 50 15" for region in $(ls /usr/share/zoneinfo | xargs); do if [[ -d /usr/share/zoneinfo/$region ]]; then timemenu="$timemenu \"$region\" \"\"" fi done region=$(eval $timemenu 3>&1 1>&2 2>&3) # if user did not cancel construct command string for time zone if [[ $region != "" ]]; then submenu="whiptail --menu \"Select a timezone\" 25 50 15" for zone in $(ls /usr/share/zoneinfo/$region | xargs); do submenu="$submenu \"$zone\" \"\"" done zone=$(eval $submenu 3>&1 1>&2 2>&3) # if user did not cancel set timezone if [[ $zone != "" ]]; then # if this is a directory there is a subzone if [[ -d /usr/share/zoneinfo/$region/$zone ]]; then subzonemenu="whiptail --menu \"Select a subzone\" 25 50 15" for subzone in $(ls /usr/share/zoneinfo/$region/$zone/ | xargs); do subzonemenu="$subzonemenu \"$subzone\" \"\"" done subzone=$(eval $subzonemenu 3>&1 1>&2 2>&3) if [[ $subzone != "" ]]; then ln -sf /usr/share/zoneinfo/$region/$zone/$subzone /etc/localtime fi fi else # there is no subzone arch-chroot /mnt ln -sf /usr/share/zoneinfo/$region/$zone /etc/localtime fi fi } set_locale(){ localemenu="whiptail --menu --noitem \"Please select the locale you want to use\" 25 50 15" for line in $(seq 24 484); do localemenu="$localemenu \"$(head -n $line /mnt/etc/locale.gen | tail -n 1 | sed "s/#//")\" \"\"" done locale=$(eval $localemenu 3>&1 1>&2 2>&3 | cut -d " " -f 1) if [[ $locale != "" ]]; then # get line number in /etc/locale.gen line=$(grep -n $locale /mnt/etc/locale.gen | cut -d : -f 1 | tail -n 1) # uncomment said line sed -i"" "$line s/#//" /mnt/etc/locale.gen arch-chroot /mnt locale-gen echo "LANG=$(grep -e "^[^#]" /mnt/etc/locale.gen | awk '{print $1}')" > /mnt/etc/locale.conf fi } # TODO: fix the cancel logic so that blank entries dont cancel but button presses do # Try to use exit status as a way to check if the cancel button is pressed "$?" set_root_passwd(){ pass1=" " pass2=" " while [[ $pass1 != $pass2 && ! -z $pass1 && ! -z $pass2 ]]; do pass1=$(whiptail --passwordbox "Enter the password you wish to use for root" 10 50 3>&1 1>&2 2>&3) pass2=$(whiptail --passwordbox "Enter the password again" 10 50 3>&1 1>&2 2>&3) if [[ $pass1 != $pass2 && ! -z $pass1 && ! -z $pass2 ]]; then whiptail --msgbox "Passwords do not match please try again" 10 50 elif [[ $pass1 == "" && $pass2 == "" ]]; then whiptail --msgbox "Password cannot be blank please try again" 10 50 pass1=" " pass2=" " elif [[ $pass1 == $pass2 ]]; then echo "echo \"root:$pass1\" | chpasswd" > /mnt/changeroot.sh arch-chroot /mnt chmod +x changeroot.sh arch-chroot /mnt ./changeroot.sh arch-chroot /mnt rm changeroot.sh fi done } # TODO: update password flow control to satisfy same problems as set_root_passwd add_user(){ user=$(whiptail --inputbox "Enter a new username" 10 50 3>&1 1>&2 2>&3) if [[ $user != "" ]]; then groups=$(whiptail --inputbox "Enter any secondary groups you would like the new user to be in, seperated by comma" 15 50 3>&1 1>&2 2>&3) if [[ $groups != "" ]]; then arch-chroot /mnt useradd -m -G $groups $user else arch-chroot /mnt useradd -m $user fi pass1="<PASSWORD>" pass2="<PASSWORD>" while [[ $pass1 != $pass2 || $pass1 == "" ]]; do pass1=$(whiptail --passwordbox "Please enter a password for user $user" 10 50 3>&1 1>&2 2>&3) pass2=$(whiptail --passwordbox "Please enter again" 10 50 3>&1 1>&2 2>&3) if [[ $pass1 != $pass2 ]]; then whiptail --msgbox "Passwords do no match please try again" 10 50 elif [[ $pass1 == "" ]]; then whiptail --msgbox "Password cannot be blank please try again" 10 50 else echo "echo \"$user:$pass1\" | chpasswd" > /mnt/changepass.sh arch-chroot /mnt chmod +x changepass.sh arch-chroot /mnt ./changepass.sh arch-chroot /mnt rm changepass.sh fi done fi } # TODO: test UEFI install install_bootloader(){ bootmenu="whiptail --menu --notags \"Select the bootloader you wish to use\" 10 50 3 \ \"syslinux\" \"Syslinux\" \ \"grub\" \"GRUB\" \ \"uefi\" \"bootctl(UEFI)\" " bootchoice=$(eval $bootmenu 3>&1 1>&2 2>&3) if [[ $bootchoice != "" ]]; then if [[ $bootchoice == "syslinux" ]]; then arch-chroot /mnt pacman -S syslinux arch-chroot /mnt syslinux-install_update -i -a -m whiptail --msgbox "Please confirm that the syslinux installation chose the correct root partition" vim /mnt/boot/syslinux/syslinux.cfg elif [[ $bootchoice == "grub" ]]; then arch-chroot /mnt pacman -S grub for disk in $(ls /dev | grep -e "^sd.$" | xargs); do diskmenu="$diskmenu \"/dev/$disk\" \"\"" done diskmenu="whiptail --menu --noitem \"Please select the disk on which you want to install GRUB\" 15 50 5" disk=$(eval $diskmenu 3>&1 1>&2 2>&3) if [[ $disk != "" ]]; then arch-chroot /mnt grub-install --target=i386-pc --recheck --debug $disk arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg fi elif [[ $bootchoice == "uefi" ]]; then arch-chroot /mnt bootctl install echo "title Arch Linux" >> /mnt/boot/loader/entries/arch.conf echo "linux /vmlinuz-linux" >> /mnt/boot/loader/entries/arch.conf echo "initrd /initramfs-linux.img" >> /mnt/boot/loader/entries/arch.conf echo "options root=/dev/sda2 rw" >> /mnt/boot/loader/entries/arch.conf # this may not be correct echo "timeout 3" >> /mnt/boot/loader/loader.conf echo "default arch" >> /mnt/boot/loader/loader.conf fi fi } install_drivers(){ drivermenu="whiptail --menu --notags \"Select your video driver\" 15 50 7 \ \"xf86-video-ati\" \"ati\" \ \"xf86-video-intel\" \"intel\" \ \"xf86-video-nouveau\" \"nouveau\" \ \"nvidia\" \"nvidia\" \ \"nvidia-340xx\" \"nvidia-340xx\" \ \"nvidia-304xx\" \"nvidia-304xx\" \ \"virtualbox-guest-utils\" \"virtualbox\" \ " driver=$(eval $drivermenu 3>&1 1>&2 2>&3) if [[ $driver != "" ]]; then arch-chroot /mnt pacman -S $driver fi } install_desktop(){ demenu="whiptail --menu --notags \"Select the DE you wish to install\" 17 50 9 \ \"cinnamon\" \"Cinnamon\" \ \"enlightenment\" \"Enlightenment\" \ \"gnome\" \"Gnome\" \ \"kdebase-workspace\" \"KDE 4\" \ \"plasma\" \"KDE 5 Plasma\" \ \"lxde\" \"LXDE\" \ \"lxqt\" \"LXQt\" \ \"mate\" \"MATE\" \ \"xfce4\" \"Xfce\" \ " wmmenu="whiptail --menu --notags \"Select the WM you wish to install\" 21 50 13 \ \"blackbox\" \"Blackbox\" \ \"fluxbox\" \"Fluxbox\" \ \"openbox\" \"Openbox\" \"fvwm\" \"FVWM\" \ \"icewm\" \"iceWM\" \ \"jwm\" \"JWM\" \ \"windowmaker\" \"Window Maker\" \ \"bspwm\" \"Bspwm\" \ \"herbstluftwm\" \"Herbstluftwm\" \ \"awesome\" \"Awesome\" \ \"dwm\" \"dwm\" \ \"i3\" \"i3\" \ \"xmonad\" \"xmonad\" \ " DEorWM=$(whiptail --menu --notags "Would you like to install a DE or a WM?" 10 43 2 "de" "Desktop Environment" "wm" "Window Manager" 3>&1 1>&2 2>&3) if [[ $DEorWM != "" ]]; then if [[ $DEorWM == "de" ]]; then menuchoice=$(eval $demenu 3>&1 1>&2 2>&3) elif [[ $DEorWM == "wm" ]]; then menuchoice=$(eval $wmmenu 3>&1 1>&2 2>&3) fi fi if [[ $menuchoice != "" ]]; then arch-chroot /mnt pacman -S xorg-server xorg-server-utils xorg-xinit xorg-twm xorg-xclock xterm arch-chroot /mnt pacman -S $menuchoice fi } install_helper(){ whiptail --msgbox "Note: Installation of an AUR helper requires installation of the base-devel package" 15 50 helpermenu="whiptail --menu --notags \"Select a AUR helper to install\" 15 50 5 \ \"aura\" \"Aura\" \ \"autoaur\" \"Autoaur\" \ \"cower\" \"Cower\" \ \"packer\" \"Packer\" \ \"yaourt\" \"Yaourt\" \ " helper=$(eval $helpermenu 3>&1 1>&2 2>&3) if [[ $helper != "" ]]; then mkdir /mnt/home/build cp helper-install.sh /mnt/home/build arch-chroot /mnt /home/build/helper-install.sh $helper fi } get_partitions(){ # Obtain list of disk partitions parts=$(fdisk -l | grep -e "^/dev/" | awk '{print $1}'); } # Create string of command for main menu mainmenu="whiptail --menu --notags \"Arch Install Scripts\" 25 50 16 \ \"part\" \"Partition Disk(s)\" \ \"format\" \"Format Partitions\" \ \"swap\" \"Setup Swap\" \ \"mount\" \"Mount Paritions\" \ \"base\" \"Install Base System\" \ \"hostname\" \"Set Hostname\" \ \"network\" \"Networking Tools\" \"time\" \"Set Timezone\" \ \"locale\" \"Set Locale\" \ \"root\" \"Set Root Password\" \ \"users\" \"Add User(s)\" \ \"boot\" \"Install Bootloader\" \ \"drivers\" \"Install Graphics Drivers\" \ \"desktop\" \"Install Desktop Environment\" \ \"helper\" \"Install AUR Helper\" \"done\" \"Make Initial RAM Image and Exit Script\" \ " mainmenuchoice="default" while [[ $mainmenuchoice != "done" && $mainmenuchoice != "" ]]; do mainmenuchoice=$(eval $mainmenu 3>&1 1>&2 2>&3) case $mainmenuchoice in "part") cfdisk;; "format") format_disks;; "swap") setup_swap;; "mount") mount_partitions;; "base") pacstrap /mnt base sudo genfstab -p /mnt >> /mnt/etc/fstab;; "hostname") set_hostname;; "network") setup_network;; "time") set_timezone;; "locale") set_locale;; "root") set_root_passwd;; "users") add_user;; "boot") install_bootloader;; "drivers") install_drivers;; "desktop") install_desktop;; "helper") install_helper;; "done") arch-chroot /mnt mkinitcpio -p linux;; esac done <file_sep>#!/bin/bash pacman -S base-devel wget chown nobody:nobody /home/build chmod g+ws /home/build cd /home/build sed -i "85s/#//g" /etc/sudoers usermod -G wheel nobody sudo -u nobody wget https://aur.archlinux.org/cgit/aur.git/snapshot/"$1".tar.gz sudo -u nobody tar xzf "$1".tar.gz cd $1 sudo -u nobody makepkg -s --noconfirm pacman -U *.tar.xz sed -i "85s/^/#/g" /etc/sudoers <file_sep># arch-install-scripts A work in progress ### Things that are done: - Configuration of disk - Installation of base system - Basic settings like hostname/locale/timezone - User config - Display driver installation - DE/WM installation ### Things that are not done: - Bootloader installation(needs UEFI support) - Static network configuration(Only DHCP right now) ## Screenshot ![arch-install-scripts](https://cloud.githubusercontent.com/assets/6550505/26070927/602b3d3c-3974-11e7-8d81-9163ba6980bf.png)
26e5fa53ecdf69391488c28b56d73469ed0d5471
[ "Markdown", "Shell" ]
3
Shell
nelson-sean/arch-install-scripts
6600bba2f83e3178d58c61a04e5bf6723cb0d8d8
234a5383578a86eba883bc77a7cb2f75f7a87b50
refs/heads/master
<file_sep>import java.io.FileNotFoundException; import java.util.Scanner; import java.io.PrintWriter; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Random; import java.math.BigInteger; import java.math.BigDecimal; import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class LCG { int numGenerated; public static void main(String[] args) { Scanner reader = new Scanner(System.in); // Reading from System.in System.out.println("Choose a random function:"); System.out.println("1 - Standard Rand Function"); System.out.println("2 - LGC"); System.out.println("3 - LGC(RANDU)"); int functionNum = reader.nextInt(); System.out.println("\nHow many numbers should be generated? (10,000 Reccomended)"); int numsGenerated = reader.nextInt(); System.out.println("\nThe seed used will be: 123456789"); long seed = 123456789; if(functionNum==1){ rand(numsGenerated,seed); }else if(functionNum==2 || functionNum==3){ lcgTest(numsGenerated,seed,functionNum); }else{ System.out.println("Please Enter a number 1-3"); System.exit(0); } System.out.println("\nChoose a test to run:"); System.out.println("1 - Kolmogorov-Smirnov Test"); System.out.println("2 - Chi-Square Test"); System.out.println("3 - Runs Test"); System.out.println("4 - Autocorrelations Test"); int testNum = reader.nextInt(); if(testNum==1){//Kolmogorov-Smirnov ks(); }else if(testNum == 2){//Chi-Square chiSquare(); }else if(testNum == 3){//Runs runs(numsGenerated); }else if(testNum == 4){//Autocorrelations System.out.println("Enter an l value:"); int l = reader.nextInt(); ac(numsGenerated,l); }else{ System.out.println("Please enter number 1-4"); System.exit(0); } } public static void rand(int n,long seed){ try (PrintWriter writer = new PrintWriter("randoms.txt")) { Random rnd = new Random(seed); for(int i=0; i<n; i++){ writer.println(rnd.nextDouble()); } writer.close(); } catch (FileNotFoundException ex) { Logger.getLogger(LCG.class.getName()).log(Level.SEVERE, null, ex); } } public static void lcgTest(int n,long seed,int function){ BigInteger a; BigInteger c; BigInteger m; BigInteger x; BigDecimal result; BigDecimal max;//Number to divide by to get all answers < 1 if(function==2){//LCG x = new BigInteger(Long.toString(seed)); a = new BigInteger("101427"); c = new BigInteger ("321"); m = new BigInteger("65536"); max = new BigDecimal("65536"); }else{//RANDU x = new BigInteger(Long.toString(seed)); a = new BigInteger("65539"); c = new BigInteger("0"); m = new BigInteger("2147483648"); max = new BigDecimal("2147483648");//Number to divide by to get all answers < 1 } //run lcg test try (PrintWriter writer = new PrintWriter("randoms.txt")) { for(int i=0; i<n; i++){ result = new BigDecimal(x.toString()); result = result.divide(max); writer.println(result); x = ((a.multiply(x)).add(c)).mod(m); } writer.close(); } catch (FileNotFoundException ex) { Logger.getLogger(LCG.class.getName()).log(Level.SEVERE, null, ex); } { } } private static void ks() { File file = new File("randoms.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; boolean eighty = false, ninty = false, nintyFive = false; int i = 0; double dPlus = 0; double dMinus = 0; double temp; double D; double N = 100; ArrayList<Double> data = new ArrayList<>(); while ((line = br.readLine()) != null && i<N) {//add to arraylist to sort data.add(Double.parseDouble(line)); i++; } Collections.sort(data); for(i=0; i<N; i++){ temp = (double)(i+1)/N-data.get(i); if(temp>dPlus){ dPlus = temp; } temp = (double)data.get(i)-i/N; if(temp>dMinus){ dMinus = temp; } } D = Math.max(dPlus, dMinus); System.out.println("D value: "+D); if(D<(1.07/Math.sqrt(N))){ eighty = true; } if(D<(1.22/Math.sqrt(N))){ ninty = true; } if(D<(1.36/Math.sqrt(N))){ nintyFive = true; } results(eighty,ninty,nintyFive); } catch (IOException ex) { Logger.getLogger(LCG.class.getName()).log(Level.SEVERE, null, ex); } } private static void chiSquare() { int[] y = new int[10];//actual double c = 0; int e;//expected File file = new File("randoms.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; int rounded; int total = 0; boolean eighty = false, ninty = false, nintyFive = false; while ((line = br.readLine()) != null) { rounded = Integer.parseInt(line.substring(2,3));//round down to the hundreths place y[rounded]++;//count the number in each division total++; } e = total/10; for(int i=0;i<10;i++){ c += Math.pow((y[i] - e),2)/e;//calculate C value } System.out.println("c value: " + c); //Using 9 as degrees of freedom (10 cells) if(c<14.648){ eighty = true; } if(c<16.919){ ninty = true; } if(c<19.023){ nintyFive = true; } results(eighty,ninty,nintyFive); } catch (IOException ex) { Logger.getLogger(LCG.class.getName()).log(Level.SEVERE, null, ex); } } private static void runs(int N) { double expVar; double expMu; double Z; double cur = 0; double last; int runs = 1; boolean positive = true; File file = new File("randoms.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; boolean eighty = false, ninty = false, nintyFive = false; while ((line = br.readLine()) != null) { last = cur; cur = Double.parseDouble(line); if((cur>last&&!positive)||(cur<last&&positive)){//end of run runs++; positive = !positive;//change run } } expMu =(double)(2*N-1)/3; expVar =(double)(16*N-29)/90; Z = (runs-expMu)/expVar; System.out.println("Z value: " + Z); if(Z>-1.29&&Z<1.29){ eighty = true; } if(Z>-1.65&&Z<1.65){ ninty = true; } if(Z>=-1.96&&Z<1.96){ nintyFive = true; } results(eighty,ninty,nintyFive); } catch (IOException ex) { Logger.getLogger(LCG.class.getName()).log(Level.SEVERE, null, ex); } } private static void ac(int N,int l) { int i = 0;//starting point double M; int index = 0; double prev; double next = 0; double sum = 0; double rho; double sigma; double Z; M = (int)Math.floor((N-i)/l-1); System.out.println("Using " + i + " as i"); File file = new File("randoms.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; boolean eighty = false, ninty = false, nintyFive = false; while ((line = br.readLine()) != null) { if(index%l==0){ prev = next; next = Double.parseDouble(line); sum += prev*next; } index++; } rho = 1/(M+1)*sum-.25; sigma = Math.sqrt(13*M+7)/(12*(M+1)); Z = rho/sigma; System.out.println("Z value: " + Z); if(Z>-1.29&&Z<1.29){ eighty = true; } if(Z>-1.65&&Z<1.65){ ninty = true; } if(Z>=-1.96&&Z<1.96){ nintyFive = true; } results(eighty,ninty,nintyFive); } catch (IOException ex) { Logger.getLogger(LCG.class.getName()).log(Level.SEVERE, null, ex); } } private static void results(boolean eighty, boolean ninty, boolean nintyFive){ if(nintyFive){ System.out.println("Significance at 95%"); } if(ninty){ System.out.println("Significance at 90%"); } if(eighty){ System.out.println("Significance at 80%"); } if(!eighty&&!ninty&&!nintyFive){ System.out.println("No Signifcance at 80%, 90%, or 95%"); } } }
e41f2e31e2b361cdac617e37ab332824bbc41feb
[ "Java" ]
1
Java
mikeoles/Simulation
cb95a3d2838058f7593b6fd8ddd02d1da38193c8
e19faf4257432f6206494e428ee3877970a22422
refs/heads/master
<repo_name>mrshaq/JSONWebToken<file_sep>/JSONWebToken.podspec Pod::Spec.new do |s| s.name = 'JSONWebToken' s.version = '1.1' s.summary = 'Swift lib for decoding, validating, signing and verifying JWT' s.homepage = "https://github.com/mrshaq/JSONWebToken" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Kreactive' => 'https://github.com/kreactive' } s.source = { :git => "https://github.com/mrshaq/JSONWebToken.git" } s.ios.deployment_target = '9.0' s.requires_arc = true s.framework = 'Security' s.source_files = "JSONWebToken/*.{swift,h,m}" s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.0', } end
70d7fcd50ef425576a629497098d682d3efc61a8
[ "Ruby" ]
1
Ruby
mrshaq/JSONWebToken
744056e008fa7e592e91f38129368c95c81d8acd
fa03fb4a210d5d7479440e90fcd5a515030f56ba
refs/heads/main
<file_sep>//========== Tableau citations Coluche ============== //=============================================== let startQuoteColuche = [ "La différence qu'il y a entre les oiseaux et les hommes politiques, ", "Certains ont l'air honnête, ", "Les portes de l'avenir, ", "De tous ceux qui n'ont à rien à dire, ", "Des fois, ", "Le plus dur pour les hommes politiques, ", "C'est pas compliqué en politique, ", "Dans l'administration on ne doit pas dormir, ", "Un crédit à long terme, ", "C'est pas vraiment ma faut si y'en qui ont faim, "]; let middleQuoteColuche = [ "c'est que de temps en temps, ", "mais quand ils te serrent la main, ", "sont ouvertes à ceux, ", "les plus agréables, ", "on a plus de contacts avec un chien pauvre, ", "c'est d'avoir la mémoire qu'il faut, ", "il suffit d'avoir une bonne conscience, ", "au burau le matin sinon, ", "ça veut dire que moins tu peux payer, ", "mais ça le devriendrait, "]; let endQuoteColuche = [ "les oiseaux s'arrêtent de voler !", "tu as intérêt à recompter tes doigts.", "qui savent les pousser.", "sont ceux qui se taisent.", "qu'avec un homme riche.", "pour se souvenir de ce qu'il ne faut pas dire.", "et pour ça il faut avoir une mauvaise mémoire.", "on ne sait plus quoi faire l'après midi.", "plus tu payes.", "si on y changeait rien."]; //========== Tableau citations Oscar wilde ============== //=============================================== let startQuoteOscarwilde = [ "Il est beaucoup plus intelligent, ", "Aujourd'hui les gens, ", "La sagesse, ", "J'adore parler de rien, ", "La logique, ", "La musique, ", "L'expérience, ", "Les folies, ", "Le meilleur moyen, ", "La beauté, "]; let middleQuoteOscarwilde = [ "de dire des choses absurdes, ", "connaissent le prix de tout, ", "c'est d'avoir des rêves suffisamment grands, ", "c'est le seul domaine, ", "est le dernier refuge, ", "met l'ême en harmonie, ", "est le nom que chacun, ", "sont les seules choses, ", "de résister à la tentation, ", "est dans les yeux, "]; let endQuoteOscarwilde = [ "que d'en écouter.", "et la valeur de rien.", "pour ne pas les perdre de vue lorsqu'on les poursuit.", "où j'ai de vagues connaissances.", "des gens sans imagination.", "avec tout ce qui existe.", "donne à ses erreurs.", "que l'on ne regrette jamais.", "de résister à la tentation.", "de celui qui regarde."]; // Instanciation des deux classes let colucheQuote = new Quote(startQuoteColuche, middleQuoteColuche, endQuoteColuche); let oscarwildeQuote = new Quote(startQuoteOscarwilde, middleQuoteOscarwilde, endQuoteOscarwilde); let generate = new Generate(colucheQuote, oscarwildeQuote);
8c92a30e7a3e60086b701f8997e7509e2b818a2a
[ "JavaScript" ]
1
JavaScript
rachidagit/copiep5
42bf05f72083d92323091cbe518aeb70f91f326d
71b211e7dc2f12e989dc4c65bd68ab815adb38b4
refs/heads/master
<file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-body', templateUrl: './body.component.html' }) export class BodyComponent { // Variable mostrar de tipo booleano mostrar = false; // Objeto al cual accedemos desde el body frase: any = { mensaje: 'Una gran responsabilidad', autor: 'Parker' }; // ngFor: personajes = ['Batman', 'SuperMan', 'Acuaman']; } <file_sep>// Importamos esta librería para indicar que este es un componente y pueda importarse desde otros import { Component } from '@angular/core'; /* Decorador donde específicamos el nombre/etiqueta con el que se llamará el componente desde cualquier archivo "html", además especificamos la plantilla html que usará, si existe también se especifica el archivo de estilos (css) */ @Component({ selector: 'app-header', templateUrl: './header.component.html' }) // Nombre del componente que podremos importar export class HeaderComponent{ }
59159584992ebf53c47cd5b27bec59e786390cf2
[ "TypeScript" ]
2
TypeScript
RudyCancax/ngIf-ngFor
659d54becf5aa0dc2830facefcd8dac1ab4820cb
0d789abfefd3400f0805f36435cfd8854ba1fe07
refs/heads/master
<file_sep>package org.mediacloud.cliff.test; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import org.junit.Test; import org.mediacloud.cliff.ParseManager; import org.mediacloud.cliff.extractor.EntityExtractor; public class ParseManagerTest { @SuppressWarnings("rawtypes") @Test public void testCountry() { HashMap response = ParseManager.parseFromText("This is about India the country.", false); HashMap results = (HashMap) response.get("results"); assertEquals( ((ArrayList)((HashMap) results.get("places")).get("mentions")).size(),1 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("states")).size(),0 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("cities")).size(),0 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("countries")).size(),1 ); assertEquals( ((ArrayList) results.get("people")).size(),0 ); assertEquals( ((ArrayList) results.get("organizations")).size(),0 ); } @SuppressWarnings("rawtypes") @Test public void testCity() { HashMap response = ParseManager.parseFromText("This is focus Brooklyn the city.", false); HashMap results = (HashMap) response.get("results"); assertEquals( ((ArrayList)((HashMap) results.get("places")).get("mentions")).size(),1 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("states")).size(),1 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("cities")).size(),1 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("countries")).size(),1 ); assertEquals( ((ArrayList) results.get("people")).size(),0 ); assertEquals( ((ArrayList) results.get("organizations")).size(),0 ); } @SuppressWarnings("rawtypes") @Test public void testState() { HashMap response = ParseManager.parseFromText("This is focus New York the state.", false); HashMap results = (HashMap) response.get("results"); assertEquals( ((ArrayList)((HashMap) results.get("places")).get("mentions")).size(),1 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("states")).size(),1 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("cities")).size(),0 ); assertEquals( ((ArrayList)((HashMap)((HashMap) results.get("places")).get("focus")).get("countries")).size(),1 ); assertEquals( ((ArrayList) results.get("people")).size(),0 ); assertEquals( ((ArrayList) results.get("organizations")).size(),0 ); } } <file_sep>package org.mediacloud.cliff.people.disambiguation; import java.util.List; import org.mediacloud.cliff.DisambiguationStrategy; import org.mediacloud.cliff.extractor.PersonOccurrence; import org.mediacloud.cliff.people.ResolvedPerson; /** * Wrapper around disambiguation strategies, so we can try and compare different ones * * @author rahulb */ public interface PersonDisambiguationStrategy extends DisambiguationStrategy { /** * For each candidate list, select the best candidate. * * @param allPossibilities * Set of candidates to sort through. * @return Set of the best candidate choices. */ public abstract List<ResolvedPerson> select(List<PersonOccurrence> allPossibilities); public abstract void logStats(); }<file_sep>package org.mediacloud.cliff.places.focus; import java.util.List; import com.bericotech.clavin.resolver.ResolvedLocation; /** * Wrapper around the concept of looking at a list of places and deciding which country a * document is "about". This exists so we can try and compare different strategies. * @author rahulb */ public interface FocusStrategy { public abstract List<FocusLocation> selectCountries( List<ResolvedLocation> resolvedLocations); public abstract List<FocusLocation> selectStates( List<ResolvedLocation> resolvedLocations); public abstract List<FocusLocation> selectCities( List<ResolvedLocation> resolvedLocations); }<file_sep>package org.mediacloud.cliff.util; import com.neovisionaries.i18n.CountryCode; /** * Helpers to work with ISO3166 country codes and ids. * * @author rahulb */ public class ISO3166Utils { public static String alpha3toAlpha2(String alpha3) throws UnknownCountryException { if(alpha3.length()==0) return " "; CountryCode countryCode = CountryCode.getByCode(alpha3); if(null==countryCode){ throw new UnknownCountryException("Can't find country "+alpha3, alpha3); } return countryCode.getAlpha2(); } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>CLIFF</artifactId> <groupId>org.mediacloud</groupId> <version>2.6.1</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mitie</artifactId> <dependencies> <dependency> <groupId>org.mediacloud</groupId> <artifactId>common</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>edu.mit.ll.mitie</groupId> <artifactId>mitie</artifactId> <version>0.4</version> </dependency> <dependency> <groupId>org.kohsuke.metainf-services</groupId> <artifactId>metainf-services</artifactId> <version>1.8</version> <optional>true</optional> </dependency> </dependencies> </project> <file_sep>package org.mediacloud.cliff.places.disambiguation; import java.util.ArrayList; import java.util.List; import com.bericotech.clavin.gazetteer.CountryCode; import com.bericotech.clavin.gazetteer.FeatureClass; import com.bericotech.clavin.resolver.ResolvedLocation; public class LargeAreasPass extends GenericPass { @Override protected List<List<ResolvedLocation>> disambiguate( List<List<ResolvedLocation>> possibilitiesToDo, List<ResolvedLocation> bestCandidates) { List<List<ResolvedLocation>> possibilitiesToRemove = new ArrayList<List<ResolvedLocation>>(); for (List<ResolvedLocation> candidates : possibilitiesToDo) { boolean foundOne = false; for (ResolvedLocation candidate : candidates) { if (!foundOne && isExactMatch(candidate) && candidate.getGeoname().getPrimaryCountryCode() == CountryCode.NULL && candidate.getGeoname().getFeatureClass() == FeatureClass.L) { bestCandidates.add(candidate); possibilitiesToRemove.add(candidates); foundOne = true; } } } return possibilitiesToRemove; } @Override public String getDescription() { return "Pick large areas"; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>CLIFF</artifactId> <groupId>org.mediacloud</groupId> <version>2.6.1</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>stanford-entity-extractor</artifactId> <dependencies> <dependency> <groupId>org.mediacloud</groupId> <artifactId>common</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>edu.stanford.nlp</groupId> <artifactId>stanford-corenlp</artifactId> <version>3.9.2</version> </dependency> <dependency> <groupId>org.kohsuke.metainf-services</groupId> <artifactId>metainf-services</artifactId> <version>1.8</version> <optional>true</optional> </dependency> </dependencies> </project><file_sep>package org.mediacloud.cliff.places.focus; import com.bericotech.clavin.gazetteer.CountryCode; import com.bericotech.clavin.gazetteer.GeoName; public class FocusLocation { private int score; private GeoName geoName; public FocusLocation(GeoName geoName, int score){ this.geoName = geoName; this.score = score; } public int getScore() { return score; } public GeoName getGeoName() { return geoName; } public CountryCode getPrimaryCountryCode(){ return geoName.getPrimaryCountryCode(); } } <file_sep>package org.mediacloud.cliff.places.disambiguation; import java.util.ArrayList; import java.util.List; import com.bericotech.clavin.gazetteer.FeatureClass; import com.bericotech.clavin.resolver.ResolvedLocation; public class TopColocationsPass extends GenericPass { @Override protected List<List<ResolvedLocation>> disambiguate( List<List<ResolvedLocation>> possibilitiesToDo, List<ResolvedLocation> bestCandidates) { List<List<ResolvedLocation>> possibilitiesToRemove = new ArrayList<List<ResolvedLocation>>(); possibilitiesToRemove.clear(); for( List<ResolvedLocation> candidates: possibilitiesToDo){ boolean foundOne = false; for( ResolvedLocation candidate: candidates) { if(!foundOne && (candidate.getGeoname().getFeatureClass()==FeatureClass.A || candidate.getGeoname().getFeatureClass()==FeatureClass.P) && inSameCountry(candidate,bestCandidates)){ bestCandidates.add(candidate); possibilitiesToRemove.add(candidates); foundOne = true; } } } return possibilitiesToRemove; } @Override public String getDescription() { return "Pick the top Admin Region or Populated Place remaining that is in a country we found already"; } } <file_sep>package org.mediacloud.cliff.places.disambiguation; import java.util.List; import org.mediacloud.cliff.DisambiguationStrategy; import org.mediacloud.cliff.places.CliffLocationResolver; import com.bericotech.clavin.resolver.ResolvedLocation; /** * Wrapper around disambiguation strategies, so we can try and compare different ones * * @author rahulb */ public interface LocationDisambiguationStrategy extends DisambiguationStrategy { /** * For each candidate list, select the best candidate. * * @param allPossibilities * Set of candidate lists to sort through. * @return Set of the best candidate choices. */ public abstract List<ResolvedLocation> select( CliffLocationResolver resolver, List<List<ResolvedLocation>> allPossibilities); public abstract void logStats(); }<file_sep>package org.mediacloud.cliff.places.disambiguation; import java.util.ArrayList; import java.util.List; import com.bericotech.clavin.resolver.ResolvedLocation; public class TopPreferringColocatedPass extends GenericPass { @Override protected List<List<ResolvedLocation>> disambiguate( List<List<ResolvedLocation>> possibilitiesToDo, List<ResolvedLocation> bestCandidates) { List<List<ResolvedLocation>> possibilitiesToRemove = new ArrayList<List<ResolvedLocation>>(); for( List<ResolvedLocation> candidates: possibilitiesToDo){ boolean foundOne = false; // check for one in the same country for( ResolvedLocation candidate: candidates) { if(!foundOne && inSameCountry(candidate,bestCandidates) ){ bestCandidates.add(candidate); possibilitiesToRemove.add(candidates); foundOne = true; } } // still nothing? pick the first city if(!foundOne){ for( ResolvedLocation candidate: candidates) { if(!foundOne && isCity(candidate) ){ bestCandidates.add(candidate); possibilitiesToRemove.add(candidates); foundOne = true; } } } // just pick SOMETHING! if(!foundOne){ ResolvedLocation candidate = candidates.get(0); logResolvedLocationInfo(candidate); bestCandidates.add(candidate); possibilitiesToRemove.add(candidates); } } return possibilitiesToRemove; } @Override public String getDescription() { return "Pick the top result, preferrring ones in the a country found already (last ditch effort)"; } } <file_sep>package org.mediacloud.cliff.test.places.disambiguation; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import org.mediacloud.cliff.ParseManager; import org.mediacloud.cliff.test.util.TestPlaces; import com.bericotech.clavin.resolver.ResolvedLocation; public class DelawarePlaceTest { @Test public void testDelawareState() throws Exception{ List<ResolvedLocation> results = ParseManager.extractAndResolve("This is about Delaware the state.").getResolvedLocations(); assertEquals("Found "+results.size()+" places, should have been 1!",1,results.size()); assertEquals(TestPlaces.STATE_DELAWARE,results.get(0).getGeoname().getGeonameID()); } @Test /** * Problem case reported by <NAME> */ public void test10kReportMention() throws Exception{ List<ResolvedLocation> results = ParseManager.extractAndResolve("We have holdings in Wilmington,(DE|Delaware)").getResolvedLocations(); assertEquals("Found "+results.size()+" places, should have been 2!",2,results.size()); assertEquals(TestPlaces.STATE_DELAWARE,results.get(0).getGeoname().getGeonameID()); assertEquals(TestPlaces.CITY_WILMINGTON_DELAWARE,results.get(1).getGeoname().getGeonameID()); } } <file_sep>package org.mediacloud.cliff.test.util; import static org.junit.Assert.assertTrue; import java.io.File; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; import org.apache.commons.io.FileUtils; import org.mediacloud.cliff.ParseManager; import org.mediacloud.cliff.places.focus.FocusLocation; import org.mediacloud.cliff.test.places.CodedArticle; import org.slf4j.Logger; import com.bericotech.clavin.gazetteer.CountryCode; import com.bericotech.clavin.resolver.ResolvedLocation; import com.bericotech.clavin.util.TextUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class TestUtils { private static Gson gson = new Gson(); public static String NYT_JSON_PATH = "src/test/resources/sample-docs/nyt.json"; public static String HUFFPO_JSON_PATH = "src/test/resources/sample-docs/huffpo.json"; public static String BBC_JSON_PATH = "src/test/resources/sample-docs/bbc.json"; public static void verifyPlacesInFile(String pathToFile, int[] places, Logger logger) throws Exception{ TestUtils.verifyPlacesInFile(pathToFile, places, false,logger); } public static void verifyPlacesInFile(String pathToFile, int[] places, boolean andNoOthers, Logger logger) throws Exception{ verifyPlacesInFile(pathToFile, places, andNoOthers, logger, false); } public static void verifyPlacesInFile(String pathToFile, int[] places, boolean andNoOthers, Logger logger, boolean replaceDemonyms) throws Exception{ logger.info("Looking for "+Arrays.toString(places)+" in "+pathToFile); File inputFile = new File(pathToFile); String inputString = TextUtils.fileToString(inputFile); List<ResolvedLocation> results = ParseManager.extractAndResolve(inputString,replaceDemonyms).getResolvedLocations(); for(ResolvedLocation resolvedLocation: results){ logger.info(" "+resolvedLocation.toString()); } for(int placeId: places){ assertTrue("Didn't find "+placeId+" in list of places ("+places.length+" places found)",TestUtils.resultsContainsPlaceId(results, placeId)); } if(andNoOthers){ for(ResolvedLocation resolvedLocation: results){ assertTrue("Found a place that we weren't supposed to! "+resolvedLocation,intArrayContains(places,resolvedLocation.getGeoname().getGeonameID())); } } } public static boolean intArrayContains(int[] array, int key) { for (final int i : array) { if (i == key) { return true; } } return false; } public static boolean resultsContainsPlaceId(List<ResolvedLocation> results, int placeId){ if(placeId==0) return true; for(ResolvedLocation location: results){ if(location.getGeoname().getGeonameID()==placeId){ return true; } } return false; } public static boolean isCountryCodeInResolvedLocations(String countryAlpha2, List<ResolvedLocation> results){ if(countryAlpha2.length()==0) return true; for(ResolvedLocation location: results){ if(location.getGeoname().getPrimaryCountryCode().toString().equals(countryAlpha2)){ return true; } } return false; } public static boolean isCountryCodeInList(String countryAlpha2, List<CountryCode> countryCodes){ if(countryAlpha2.length()==0) return true; for(CountryCode location: countryCodes){ if(location.toString().equals(countryAlpha2)){ return true; } } return false; } public static boolean isCountryCodeInAboutnessLocationList(String countryAlpha2, List<FocusLocation> countryCodes){ if(countryAlpha2.length()==0) return true; for(FocusLocation location: countryCodes){ if(location.getPrimaryCountryCode().name().equals(countryAlpha2)){ return true; } } return false; } public static List<CodedArticle> loadExamplesFromFile(String filename) throws Exception { Type listType = new TypeToken<List<CodedArticle>>() {}.getType(); String json = FileUtils.readFileToString(new File(filename)); List<CodedArticle> articles = gson.fromJson(json, listType); return articles; } } <file_sep>package org.mediacloud.cliff.test.places.focus; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import org.mediacloud.cliff.ParseManager; import org.mediacloud.cliff.extractor.ExtractedEntities; import org.mediacloud.cliff.places.CountryGeoNameLookup; import org.mediacloud.cliff.places.focus.FocusLocation; import org.mediacloud.cliff.places.focus.FocusStrategy; import org.mediacloud.cliff.test.reuters.RegionSubstitutionMap; import org.mediacloud.cliff.test.reuters.ReutersCorpusDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bericotech.clavin.gazetteer.CountryCode; import com.bericotech.clavin.gazetteer.GeoName; /** * Load some of the Reuters corpus and check against their geographic tagging. This prints out * accuracy percentages, so it isn't a unit test per-say, because there isn't a magic threshold. * We just want to know how we're doing in comparison. * * @author rahulb */ public class ReutersFocusChecker { private static final Logger logger = LoggerFactory.getLogger(ReutersFocusChecker.class); public static final String REGIONS_FILE = "reuters_region_codes.txt"; private static String BASE_DIR = "data/reuters/"; private int articlesWithLocations = 0; private int focusArticlesWeGotRight = 0; private int mentionsArticlesWeGotRight = 0; private RegionSubstitutionMap substitutions; public ReutersFocusChecker() throws Exception { substitutions = new RegionSubstitutionMap(REGIONS_FILE); } public void check() throws IOException{ FileVisitor<Path> fileProcessor = new ProcessFile(); Files.walkFileTree(Paths.get(BASE_DIR), fileProcessor); double success = (double)mentionsArticlesWeGotRight/(double)articlesWithLocations; double focusSuccess = (double)focusArticlesWeGotRight/(double)articlesWithLocations; logger.info("Checked "+articlesWithLocations+" Articles - Base success rate: "+success); logger.info("Checked "+articlesWithLocations+" Articles - Aboutness success rate: "+focusSuccess); } private final class ProcessFile extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path aFile, BasicFileAttributes aAttrs) throws IOException { logger.info("--------------------------------------------------------------------------------"); if( aFile.getFileName().toString().endsWith(".xml") ) { ReutersCorpusDocument doc; try { doc = ReutersCorpusDocument.fromFile(aFile.toString(),substitutions); if(doc.hasCodedCountries()){ ExtractedEntities entities = ParseManager.extractAndResolve(doc.getCompiledText()); logger.info("Checking file "+aFile); articlesWithLocations++; List<GeoName> countriesTheyCoded = new ArrayList<GeoName>(); for(CountryCode countryCode:doc.getCountryCodeObjects()){ countriesTheyCoded.add( CountryGeoNameLookup.lookup(countryCode.name()) ); } logger.info(doc.getId()+": "+countriesTheyCoded); List<GeoName> ourMentionedCountries = entities.getUniqueCountryGeoNames(); // check to make sure we found all the countries they coded if(ourMentionedCountries.size()>0){ boolean allMatched = true; for(GeoName countryTheyCoded:countriesTheyCoded){ if(!ourMentionedCountries.contains(countryTheyCoded)){ allMatched = false; } } if(allMatched){ mentionsArticlesWeGotRight++; } else { logger.warn(doc.getId()+": mentions "+ourMentionedCountries+" they coded "+countriesTheyCoded); } } //also have a measure for making sure the main "about" country is included in their list of countries FocusStrategy focus = ParseManager.getFocusStrategy(); List<FocusLocation> ourAboutnessCountries = focus.selectCountries(entities.getResolvedLocations()); List<GeoName> ourAboutnessGeoNames = new ArrayList<GeoName>(); for(FocusLocation aboutLocation: ourAboutnessCountries){ ourAboutnessGeoNames.add(aboutLocation.getGeoName()); } if(ourAboutnessGeoNames.size()>0){ boolean allMatched = true; for(GeoName focusGeoName:ourAboutnessGeoNames){ if(!countriesTheyCoded.contains(focusGeoName)){ allMatched = false; } } if(allMatched){ focusArticlesWeGotRight++; } else { logger.warn(doc.getId()+": about "+ourAboutnessGeoNames+" they found "+countriesTheyCoded); } } } } catch (Exception e) { logger.info("skipping it becuase "+e.toString()); } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path aDir, BasicFileAttributes aAttrs) throws IOException { logger.info("Processing directory:" + aDir); return FileVisitResult.CONTINUE; } } public static void main(String[] args) throws Exception { long startTime = System.currentTimeMillis(); logger.info("Starting ReutersFocusChecker"); ReutersFocusChecker checker = new ReutersFocusChecker(); checker.check(); ParseManager.logStats(); long endTime = System.currentTimeMillis(); long elapsedMillis = endTime - startTime; logger.info("Done with ReutersFocusChecker ("+elapsedMillis+" milliseconds)"); } } <file_sep>package org.mediacloud.cliff.test.gdelt; import org.mediacloud.cliff.util.ISO3166Utils; import org.mediacloud.cliff.util.UnknownCountryException; import com.bericotech.clavin.gazetteer.CountryCode; public class GdeltActor { private String countryCode; public GdeltActor(String cc) throws UnknownCountryException{ this.countryCode = ISO3166Utils.alpha3toAlpha2(cc); } public CountryCode getCountryCodeObj(){ return CountryCode.valueOf(this.countryCode); } public String getCountryCode() { return countryCode; } @Override public String toString(){ return this.getCountryCodeObj().toString(); } } <file_sep>package org.mediacloud.cliff.test.stanford; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; import org.junit.Test; import org.mediacloud.cliff.CliffConfig; import org.mediacloud.cliff.extractor.EntityExtractor; import org.mediacloud.cliff.extractor.ExtractedEntities; import org.mediacloud.cliff.extractor.OrganizationOccurrence; import org.mediacloud.cliff.extractor.PersonOccurrence; import org.mediacloud.cliff.stanford.StanfordNamedEntityExtractor; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import com.bericotech.clavin.extractor.LocationOccurrence; public class StanfordNamedEntityExtractorTest { public final static Logger logger = LoggerFactory.getLogger(StanfordNamedEntityExtractorTest.class); public void testOrgSpanish() { CliffConfig config = CliffConfig.getInstance(); EntityExtractor extractor = new StanfordNamedEntityExtractor(); try { extractor.initialize(config); ExtractedEntities entities = extractor.extractEntities("Instituciones clave: Instituto del Niño y Adolescente del Uruguay (INAU), Administración Nacional de Educación Pública (ANEP), Educación Privada, Universidades, Ministerio de Educación y Cultura (MEC), Centros de formación militar.", false, EntityExtractor.SPANISH); List<PersonOccurrence> people = entities.getPeople(); List<LocationOccurrence> places = entities.getLocations(); List<OrganizationOccurrence> orgs = entities.getOrganizations(); assertEquals( 8, orgs.size() ); assertEquals( 0, places.size() ); assertEquals( 0, people.size() ); assertEquals( "Ministerio de Educación y Cultura", orgs.get(5).text); } catch (ClassCastException | ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testPersonSpanish() { CliffConfig config = CliffConfig.getInstance(); EntityExtractor extractor = new StanfordNamedEntityExtractor(); try { extractor.initialize(config); ExtractedEntities entities = extractor.extractEntities("<NAME> toma las calles del mundo.", false, EntityExtractor.SPANISH); List<PersonOccurrence> people = entities.getPeople(); List<LocationOccurrence> places = entities.getLocations(); List<OrganizationOccurrence> orgs = entities.getOrganizations(); assertEquals( 0, orgs.size() ); assertEquals( 0, places.size() ); assertEquals( 1, people.size() ); assertEquals( "<NAME>", people.get(0).text); } catch (ClassCastException | ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testCountrySpanish() { CliffConfig config = CliffConfig.getInstance(); EntityExtractor extractor = new StanfordNamedEntityExtractor(); try { extractor.initialize(config); ExtractedEntities entities = extractor.extractEntities("Esto es sobre la ciudad de Berlin.", false, EntityExtractor.SPANISH); List<PersonOccurrence> people = entities.getPeople(); List<LocationOccurrence> places = entities.getLocations(); List<OrganizationOccurrence> orgs = entities.getOrganizations(); assertEquals( 0, orgs.size() ); assertEquals( 0, people.size() ); assertEquals( 1, places.size() ); assertEquals( "Berlin", places.get(0).getText()); } catch (ClassCastException | ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>CLIFF: Extract Named Entities and Geoparse the News =================================================== CLIFF is a lightweight server to allow HTTP requests to the Stanford Named Entity Recognizer and a modified [CLAVIN 2.1.0 geoparser](http://clavin.bericotechnologies.com). It allows you to submit unstructured text over HTTP and a receive in reply JSON results with information about organizations mentioned, locations mentioned, people mentioned, and countries the text is "about". The geoparsing is tuned to identify cities, states and countries. # Installing You can try CLIFF out on our public website: http://cliff.mediacloud.org. We don't host a public installation of CLIFF for you to use. If you want to install and use CLIFF quickly, try [our Docker config](https://github.com/mitmedialab/cliff-docker). If you want to access CLIFF's results from Python, use our [`mediacloud-cliff Python client API library](https://pypi.org/project/mediacloud-cliff/): ``` pip install mediacloud-cliff ``` # Using To test it out, hit this url in a browser and you should get some JSON back: ``` http://localhost:8080/cliff-2.6.1/parse/text?q=This is some text about New York City, and maybe about Accra as well, and maybe Boston as well. ``` Of course, when you use this in a script you should do an HTTP POST, not a GET! ## Public API Endpoints ### /parse/text The reason CLIFF exists! This parses some text and returns the entities mentioned (people, places and organizations). |Parameter|Default|Notes| |----------|----------|----------| |q|(required)|Raw text of a news story that you want to parse| |replaceAllDemonyms|false|"true" if you want to count things like "Chinese" as a mention of the country China| Example Query: `http://localhost:8080/CLIFF-2.1.1/parse/text?q=Some%20clever%20text%20mentioning%20places%20like%20New%20Delhi,%20and%20people%20like%20Einstein.%20Perhaps%20also%20we%20want%20mention%20an%20organization%20like%20the%20United%20Nations?` Response: ```json { "results": { "organizations": [ { "count": 1, "name": "United Nations" } ], "places": { "focus": { "cities": [ { "id": 1261481, "lon": 77.22445, "name": "New Delhi", "score": 1, "countryGeoNameId": "1269750", "countryCode": "IN", "featureCode": "PPLC", "featureClass": "P", "stateCode": "07", "lat": 28.63576, "stateGeoNameId": "1273293", "population": 317797 } ], "states": [ { "id": 1273293, "lon": 77.1, "name": "National Capital Territory of Delhi", "score": 1, "countryGeoNameId": "1269750", "countryCode": "IN", "featureCode": "ADM1", "featureClass": "A", "stateCode": "07", "lat": 28.6667, "stateGeoNameId": "1273293", "population": 16787941 } ], "countries": [ { "id": 1269750, "lon": 79, "name": "Republic of India", "score": 1, "countryGeoNameId": "1269750", "countryCode": "IN", "featureCode": "PCLI", "featureClass": "A", "stateCode": "00", "lat": 22, "stateGeoNameId": "", "population": 1173108018 } ] }, "mentions": [ { "id": 1261481, "lon": 77.22445, "source": { "charIndex": 40, "string": "New Delhi" }, "name": "<NAME>", "countryGeoNameId": "1269750", "countryCode": "IN", "featureCode": "PPLC", "featureClass": "P", "stateCode": "07", "confidence": 1, "lat": 28.63576, "stateGeoNameId": "1273293", "population": 317797 } ] }, "people": [ { "count": 1, "name": "Einstein" } ] }, "status": "ok", "milliseconds": 4004, "version": "2.6.1" } ``` ### /geonames A convenience method to help you lookup places by their geonames ids. |Parameter|Default|Notes| |----------|----------|----------| |id|(required)|The unique id that identifies a place in the [geonames.org](geonames.org) database| Example Query: `http://localhost:8080/cliff-2.6.1/geonames?id=4930956` Response: ```json { "results": { "id": 4930956, "lon": -71.05977, "name": "Boston", "countryGeoNameId": "6252001", "countryCode": "US", "featureCode": "PPLA", "featureClass": "P", "parent": { "id": 4952349, "lon": -71.06575, "name": "Suffolk County", "countryGeoNameId": "6252001", "countryCode": "US", "featureCode": "ADM2", "featureClass": "A", "parent": { "id": 6254926, "lon": -71.10832, "name": "Massachusetts", "countryGeoNameId": "6252001", "countryCode": "US", "featureCode": "ADM1", "featureClass": "A", "parent": { "id": 6252001, "lon": -98.5, "name": "United States", "countryGeoNameId": "6252001", "countryCode": "US", "featureCode": "PCLI", "featureClass": "A", "stateCode": "00", "lat": 39.76, "stateGeoNameId": "", "population": 310232863 }, "stateCode": "MA", "lat": 42.36565, "stateGeoNameId": "6254926", "population": 6433422 }, "stateCode": "MA", "lat": 42.3555, "stateGeoNameId": "6254926", "population": 722023 }, "stateCode": "MA", "lat": 42.35843, "stateGeoNameId": "6254926", "population": 617594 }, "status": "ok", "version": "2.6.1" } ``` ### /extract A convenience method to help you get the raw text of the story from a URL. This uses the [boilerpipe](https://code.google.com/p/boilerpipe/) library. |Parameter|Default|Notes| |----------|----------|----------| |url|(required)|The url of a news story to extract the text of| Example Query: `http://localhost:8080/cliff-2.6.1/extract?url=http://www.theonion.com/articles/woman-thinks-she-can-just-waltz-back-into-work-aft,38349/` Response: ```json { "results": { "text": "Business\nPresented by\nWoman Thinks She Can Just Waltz Back Into Work After Maternity Leave Without Bringing Baby To Office\nClose\nVol 51 Issue 13 \u00b7 Local \u00b7 Workplace \u00b7 Parents \u00b7 Kids \u00b7 After Birth\nKENWOOD, OH\u2014Saying she has a lot of nerve to try and pull something like this, employees of insurance agency Boland & Sons told reporters Wednesday that coworker <NAME> seems to believe she can just waltz back into work after her maternity leave without once bringing her baby into the office. \u201cI don\u2019t know where she gets off thinking she doesn\u2019t need to come in here with that baby strapped around her in a bjorn,\u201d said <NAME>, adding that Nelson is out of her goddamn mind if she seriously believes showing off a few measly pictures of the newborn on her cell phone is an adequate substitute for bringing him around to meet everyone in their department. \u201cShe\u2019s been back for three weeks already, so the grace period is over. She needs to come in with that baby in a stroller, roll it by my desk, and say \u2018Somebody wants to say hello,\u2019 or, frankly, she might as well never show her face here again. Seriously, every single person here better get a chance to lean in and smile at that baby, and God help her if she shows up the rest of this week empty-handed.\u201d Sheldrick reportedly expressed equal astonishment that Nelson\u2019s husband thinks he can get away with not once arriving with the infant to pick up his wife from work.\nShare This Story:\nSign-up For The Onion's Newsletter\nGive your spam filter something to do.\nDaily Headlines\nThe Onion is not intended for readers under 18 years of age.\n\u00a9 Copyright 2015 Onion Inc. All rights reserved\n", "title": "Woman Thinks She Can Just Waltz Back Into Work After Maternity Leave Without Bringing Baby To Office - The Onion - America's Finest News Source", "url": "http:\/\/www.theonion.com\/articles\/woman-thinks-she-can-just-waltz-back-into-work-aft,38349\/" }, "status": "ok", "milliseconds": 625, "version": "2.6.1" } ``` ## Options You can configure how CLIFF runs by editing environment variables. * `INDEX_PATH` - controls where CLIFF will look for the geonames index (defaults to `/etc/cliff2/IndexDirectory` for reverse compatability) # Developing You need maven and java (1.8). We develop in Eclipse Kepler: Java EE. ## Eclipse & Java on Mac You might need to update your version of the JRE for developing on Mac. If so, you can do: ``` brew update brew cask install Java ``` ## Install CLAVIN You need to download and install the latest version of CLAVIN in order to build the Geonames Gazetteer Index for geoparsing. The idea is that you build all that, and then create a symlink at `/etc/cliff2/IndexDirectory` to the CLAVIN index you just built. Instead of building the CLAVIN geonames index yourself, consider downloading a prebuilt one from [`mediacloud-clavin-build-geonames-index` repository's releases page](https://github.com/berkmancenter/mediacloud-clavin-build-geonames-index/releases). To build, run `mvn` in the top level directory. You can do `mvn package -DskipTests` and then you will get a .war file in `webapp/target/`. ## Tomcat Setup CLIFF is setup to be run inside a Java servlet container (ie. Tomcat 8). For development we use the [Maven Tomcat plugin](http://tomcat.apache.org/maven-plugin.html). To deploy, add this to your `%TOMCAT_PATH%/conf/tomcat-users.xml` file: ```xml <role rolename="manager"/> <role rolename="manager-gui"/> <role rolename="manager-script"/> <user username="cliff" password="<PASSWORD>" roles="manager,manager-gui,manager-script"/> ``` Also add this to your `~/.m2/settings.xml`: ```xml <servers> <server> <id>CliffTomcatServer</id> <username>cliff</username> <password><PASSWORD>> </server> </servers> ``` That lets the Maven Tomcat plugin upload the WAR it builds over the website control panel. ## Building and Deploying to Tomcat First make sure tomcat is running (ie. `catalina run`). Now run `mvn tomcat7:deploy -DskipTests` to deploy the app, or `mvn tomcat7:redeploy -DskipTests` to redeploy once you've already got the app deployed. ## Pluggable Entity Extraction CLIFF leverages a pluggable entity extractor(s) via a java SPI system. This works by discovering which providers implement the EntityExtractor interface on the classpath. To work, the jar containing the entity extractor must exist in the classpath of the CLIFF Webapp. By default, this project utilizes a maven profile which will select the stanford-ner model by default. However, the Stanford NER leverages a GNU / Commercial License. ### Running the MITIE NER Download and compile the MITIE NER package for your system following the instructions at [MITIE](https://github.com/mit-nlp/MITIE). As MITIE is not published to a maven repo, prior to compiling CLIFF you must install MITIE via mvn such as `mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file -Dfile=$PWD/javamitie.jar -DgroupId=edu.mit.ll.mitie -DartifactId=mitie -Dversion=0.4 -Dpackaging=jar` Once compiled, the MITIE binary library must also be on your tomcat / java's `java.libray.path`. You can either set this on your system to the folder of the MITIE binary or copy the MITIE binary to `$JAVA_HOME/jre/lib/`. MITIE requires a model which is a fairly large download. Follow the instructions on the MITIE site to retrieve this and point `cliff.properties` at the location you choose to store this in your deployment. The final step is during your build, you must disable the stanford-ner maven profile and activate the mitie profile. For example `mvn -P mitie,\!stanford-ner clean install`, `mvn -P mitie,\!stanford-ner tomcat7:run`. Cliff will then use MITIE instead of Stanford NER. ## Using your own NER To use your own NER, create a mvn module modeled after the MITIE example. You must modify the webapp/pom.xml for a correct profile which includes the MITIE NER sub-module and includes the transitive depenencies of your NER system. Then make sure you install any modules you need for your NER system and can activate the module as described in the MITIE section. ## Testing We have a number of unit tests that can be run with `mvn test`. ## Releasing To build a release: 1. first update the version numbers in all the `pom.xml` files (`pom.xml`, `webapp/pom.xml`, `common/pom.xml`, `stanford-entity-extractor/pom.xml` ) 2. also update the version number in `org.mediacloud.cliff.ParseManager` 3. to create the WAR file, run `mvn package` 4. update the examples in `README.md` 5. tag the release with the version number `vX.Y.Z` 6. author a new release for that tag on GitHub, write a description of the changes, and upload the .war ## Deploying on Ubuntu We run our servers on Ubuntu - here's some tips for deploying to that type of server: 1. First make sure you have java7: `sudo apt-get install openjdk-7-jdk` 2. First install tomcat7: `sudo apt-get install tomcat7`. 3. Point tomcat at the correct java: open `/etc/default/tomcat7` then uncomment and change the `JAVA_HOME` var to `/usr/lib/jvm/java-7-openjdk-amd64` 4. Increase tomcat's memory: open `/etc/default/tomcat7` and change the `JAVA_OPTS` var to inclue something like `-Xmx4024m` 5. Put your war in the right place: on Ubuntu this is `/var/lib/tomcat7/webapps/` <file_sep>package org.mediacloud.cliff.test; import com.bericotech.clavin.extractor.LocationOccurrence; import edu.mit.ll.mitie.NamedEntityExtractor; import org.kohsuke.MetaInfServices; import org.mediacloud.cliff.CliffConfig; import org.mediacloud.cliff.extractor.*; import org.mediacloud.cliff.places.substitutions.Blacklist; import org.mediacloud.cliff.places.substitutions.CustomSubstitutionMap; import org.mediacloud.cliff.places.substitutions.WikipediaDemonymMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.mit.ll.mitie.*; import java.io.IOException; import java.util.Map; /** * Created with IntelliJ IDEA. * User: aaslinger * Date: 7/23/15 * Time: 11:12 AM * <p/> * Developed By OpenWhere, Inc. */ @MetaInfServices(EntityExtractor.class) public class MitieEntityExtractor implements EntityExtractor { public final static Logger logger = LoggerFactory.getLogger(MitieEntityExtractor.class); @Override public String getName() { return "MITIE"; } public static final String CUSTOM_SUBSTITUTION_FILE = "custom-substitutions.csv"; public static final String LOCATION_BLACKLIST_FILE = "location-blacklist.txt"; public static final String PERSON_TO_PLACE_FILE = "person-to-place-replacements.csv"; // the actual named entity recognizer (NER) object private NamedEntityExtractor namedEntityRecognizer; private WikipediaDemonymMap demonyms; private CustomSubstitutionMap customSubstitutions; private CustomSubstitutionMap personToPlaceSubstitutions; private Blacklist locationBlacklist; public void initialize(CliffConfig config) throws ClassCastException, IOException, ClassNotFoundException{ String model = config.getPropertyByName("mer.mitiePath"); if(model == null){ logger.error("No MITIE model configured at {}", model); } namedEntityRecognizer = new NamedEntityExtractor(model); demonyms = new WikipediaDemonymMap(); customSubstitutions = new CustomSubstitutionMap(CUSTOM_SUBSTITUTION_FILE); locationBlacklist = new Blacklist(LOCATION_BLACKLIST_FILE); personToPlaceSubstitutions = new CustomSubstitutionMap(PERSON_TO_PLACE_FILE,false); } // // /** // * Get extracted locations from a plain-text body. // * // * @param textToParse Text content to perform extraction on. // * @param manuallyReplaceDemonyms Can slow down performance quite a bit // * @return All the entities mentioned // */ // @Override public ExtractedEntities extractEntities(String textToParse, boolean manuallyReplaceDemonyms) { ExtractedEntities entities = new ExtractedEntities(); if (textToParse==null || textToParse.length()==0){ logger.warn("input to extractEntities was null or zero!"); return entities; } String text = textToParse; if(manuallyReplaceDemonyms){ // this is a noticeable performance hit logger.debug("Replacing all demonyms by hand"); text = demonyms.replaceAll(textToParse); } global g = new global(); StringVector words = g.tokenize(text); StringVector possibleTags = namedEntityRecognizer.getPossibleNerTags(); EntityMentionVector extractedEntities = namedEntityRecognizer.extractEntities(words); if (extractedEntities != null) { assignExtractedEntities(entities, text, words, possibleTags, extractedEntities); } return entities; } private void assignExtractedEntities(ExtractedEntities entities, String text, StringVector words, StringVector possibleTags, EntityMentionVector extractedEntities) { for (int i=0; i < extractedEntities.size(); i++){ EntityMention extractedEntity = extractedEntities.get(i); String entityName = getEntityString(words, extractedEntity); String tag = possibleTags.get(extractedEntity.getTag()); int position = text.indexOf(entityName); switch(tag){ case "PERSON": if(personToPlaceSubstitutions.contains(entityName)){ entities.addLocation( getLocationOccurrence(personToPlaceSubstitutions.getSubstitution(entityName), position) ); logger.debug("Changed person "+entityName+" to a place"); } else { PersonOccurrence person = new PersonOccurrence(entityName, position); entities.addPerson( person ); } break; case "LOCATION": if(!locationBlacklist.contains(entityName)){ entities.addLocation( getLocationOccurrence(entityName, position) ); } else { logger.debug("Ignored blacklisted location "+entityName); } break; case "ORGANIZATION": OrganizationOccurrence organization = new OrganizationOccurrence(entityName, position); entities.addOrganization( organization ); break; default: logger.error("Unknown NER type :"+ tag); } } } /** * Get extracted locations from a plain-text body. * * @param sentences Text content to perform extraction on. * @param manuallyReplaceDemonyms Can slow down performance quite a bit * @return All the entities mentioned */ @Override public ExtractedEntities extractEntitiesFromSentences(Map[] sentences, boolean manuallyReplaceDemonyms) { ExtractedEntities entities = new ExtractedEntities(); if (sentences.length==0){ logger.warn("input to extractEntities was null or zero!"); return entities; } if(manuallyReplaceDemonyms){ // this is a noticeable performance hit logger.debug("Replacing all demonyms by hand"); } StringVector possibleTags = namedEntityRecognizer.getPossibleNerTags(); for(Map s:sentences){ String storySentencesId = s.get("story_sentences_id").toString(); String text = s.get("sentence").toString(); if(manuallyReplaceDemonyms){ // this is a noticeable performance hit text = demonyms.replaceAll(text); } StringVector words = global.tokenize(text); EntityMentionVector extractedEntities = namedEntityRecognizer.extractEntities(words); if (extractedEntities != null) { assignExtractedEntities(entities, text, words, possibleTags, extractedEntities); } } return entities; } private String getEntityString(StringVector words, EntityMention ent){ StringBuilder builder = new StringBuilder(); for(int i = ent.getStart(); i < ent.getEnd(); i++){ builder.append(words.get(i)); if(i + 1 < ent.getEnd()){ builder.append(" "); } } return builder.toString(); } private LocationOccurrence getLocationOccurrence(String entityName, int position){ String fixedName = entityName; if (demonyms.contains(entityName)) { fixedName = demonyms.getSubstitution(entityName); logger.debug("Demonym substitution: "+entityName+" to "+fixedName); } else if(customSubstitutions.contains(entityName)) { fixedName = customSubstitutions.getSubstitution(entityName); logger.debug("Custom substitution: "+entityName+" to "+fixedName); } return new LocationOccurrence(fixedName, position); } } <file_sep>package org.mediacloud.cliff.test.places.disambiguation; import org.junit.Test; import org.mediacloud.cliff.test.util.TestPlaces; import org.mediacloud.cliff.test.util.TestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ColomboPlaceTest { private static final Logger logger = LoggerFactory.getLogger(ColomboPlaceTest.class); @Test public void testColombo() throws Exception { TestUtils.verifyPlacesInFile("src/test/resources/sample-docs/autralia-sri-lanka.txt", new int[] {TestPlaces.COUNTRY_AUSTRALIA,TestPlaces.CITY_CAIRNS, TestPlaces.CITY_COLOMBO_SRI_LANKA}, false, logger ); } } <file_sep>package org.mediacloud.cliff.places.focus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.mediacloud.cliff.places.Adm1GeoNameLookup; import org.mediacloud.cliff.places.CountryGeoNameLookup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bericotech.clavin.gazetteer.CountryCode; import com.bericotech.clavin.gazetteer.GeoName; import com.bericotech.clavin.resolver.ResolvedLocation; /** * Once we have selected the candidates, we need to pick what country the document is "about". This * is the most naive "Aboutness" strategy; it just picks the most mentioned country. * * @author rahulb */ public class FrequencyOfMentionFocusStrategy implements FocusStrategy { private static final Logger logger = LoggerFactory.getLogger(FrequencyOfMentionFocusStrategy.class); @Override public List<FocusLocation> selectCountries(List<ResolvedLocation> resolvedLocations){ List<FocusLocation> results = new ArrayList<FocusLocation>(); // count country mentions HashMap<CountryCode,Integer> countryCounts = FocusUtils.getCountryCounts(resolvedLocations); if(countryCounts.size()==0){ return results; } // find the most mentioned CountryCode primaryCountry = null; for(CountryCode countryCode: countryCounts.keySet()){ if( (primaryCountry==null) || (countryCounts.get(countryCode) > countryCounts.get(primaryCountry)) ){ primaryCountry = countryCode; } } logger.info("Found primary country "+primaryCountry); // return results if(primaryCountry!=null) { results.add( new FocusLocation( CountryGeoNameLookup.lookup( primaryCountry.name()),countryCounts.get(primaryCountry) ) ); for(CountryCode countryCode: countryCounts.keySet()){ if( countryCode != primaryCountry && countryCounts.get(countryCode) == countryCounts.get(primaryCountry) ){ results.add( new FocusLocation( CountryGeoNameLookup.lookup( countryCode.name()),countryCounts.get(countryCode) ) ); } } } return results; } @Override public List<FocusLocation> selectStates(List<ResolvedLocation> resolvedLocations){ List<FocusLocation> results = new ArrayList<FocusLocation>(); // count state mentions HashMap<String,Integer> stateCounts = FocusUtils.getStateCounts(resolvedLocations); if(stateCounts.size()==0){ return results; } // find the most mentioned String primaryState = null; int highestCount = 0; for(String stateCode: stateCounts.keySet()){ int count = stateCounts.get(stateCode); if( (primaryState==null) || count > highestCount ){ highestCount = count; primaryState = stateCode; } } logger.info("Found primary state "+primaryState.toString()); // return results if(primaryState!=null) { int primaryStateCount = stateCounts.get(primaryState); results.add( new FocusLocation( Adm1GeoNameLookup.lookup(primaryState), primaryStateCount ) ); for(String stateCode: stateCounts.keySet()){ int count = stateCounts.get(stateCode); if( stateCode != primaryState && count == primaryStateCount ){ results.add( new FocusLocation( Adm1GeoNameLookup.lookup(stateCode), count ) ); } } } return results; } @Override public List<FocusLocation> selectCities(List<ResolvedLocation> resolvedLocations){ List<FocusLocation> results = new ArrayList<FocusLocation>(); // count state mentions HashMap<GeoName,Integer> cityCounts = FocusUtils.getCityCounts(resolvedLocations); if(cityCounts.size()==0){ return results; } // find the most mentioned GeoName primaryCity = null; int highestCount = 0; for(GeoName geoname: cityCounts.keySet()){ int count = cityCounts.get(geoname); if( (primaryCity==null) || count > highestCount ){ highestCount = count; primaryCity = geoname; } } logger.info("Found primary city "+primaryCity.toString()); // return results if(primaryCity!=null) { int primaryCityCount = cityCounts.get(primaryCity); results.add( new FocusLocation( primaryCity, primaryCityCount ) ); for(GeoName city: cityCounts.keySet()){ int count = cityCounts.get(city); if( (city != primaryCity && count == primaryCityCount ) || ((city != primaryCity && count > 1)) ){ results.add( new FocusLocation( city, count ) ); } } } return results; } } <file_sep>package org.mediacloud.cliff; public interface DisambiguationStrategy { } <file_sep>package org.mediacloud.cliff.test.places.disambiguation; import org.junit.Test; import org.mediacloud.cliff.test.util.TestPlaces; import org.mediacloud.cliff.test.util.TestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UnitedKingdomPlaceTest { private static final Logger logger = LoggerFactory.getLogger(UnitedKingdomPlaceTest.class); @Test public void testUkExample() throws Exception { TestUtils.verifyPlacesInFile("src/test/resources/sample-docs/uk-story.txt", new int[] {TestPlaces.COUNTRY_UK}, logger ); } } <file_sep>package org.mediacloud.cliff.places.disambiguation; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bericotech.clavin.resolver.ResolvedLocation; public class ExactColocationsPass extends GenericPass { private static final Logger logger = LoggerFactory.getLogger(ExactColocationsPass.class); @Override protected List<List<ResolvedLocation>> disambiguate( List<List<ResolvedLocation>> possibilitiesToDo, List<ResolvedLocation> bestCandidates) { List<List<ResolvedLocation>> possibilitiesToRemove = new ArrayList<List<ResolvedLocation>>(); possibilitiesToRemove.clear(); if(bestCandidates.size() == 0){ return possibilitiesToRemove; } for( List<ResolvedLocation> candidates: possibilitiesToDo){ ResolvedLocation candidateToPick = null; List<ResolvedLocation> colocatedExactCityCandidates = inSameCountry(candidates, bestCandidates,true,true,true); logger.debug(" Found "+colocatedExactCityCandidates.size()+" colocations"); if(colocatedExactCityCandidates.size()==1){ candidateToPick = colocatedExactCityCandidates.get(0); }else if (colocatedExactCityCandidates.size()>1){ List<ResolvedLocation> shareCountryAndAdm1 = inSameCountryAndAdm1(colocatedExactCityCandidates,bestCandidates); if(shareCountryAndAdm1.size()>0){ candidateToPick = shareCountryAndAdm1.get(0); } else { candidateToPick = colocatedExactCityCandidates.get(0); } } if(candidateToPick!=null){ logger.debug(" "+candidateToPick.getGeoname().getGeonameID()+" "+candidateToPick.getGeoname().getName() + " is in "+candidateToPick.getGeoname().getPrimaryCountryCode()); bestCandidates.add(candidateToPick); possibilitiesToRemove.add(candidates); } } return possibilitiesToRemove; } /** * * @param colocatedExactCityCandidates * @param alreadyPicked * @return */ private List<ResolvedLocation> inSameCountryAndAdm1( List<ResolvedLocation> candidates, List<ResolvedLocation> alreadyPicked) { List<ResolvedLocation> colocations = new ArrayList<ResolvedLocation>(); for(ResolvedLocation pickedLocation:alreadyPicked){ for(ResolvedLocation candidate:candidates){ if(isSameCountryAndAdm1(candidate, pickedLocation)){ colocations.add(candidate); } } } return colocations; } private boolean isSameCountryAndAdm1(ResolvedLocation place1, ResolvedLocation place2) { return place1.getGeoname().getAdmin1Code().equals(place2.getGeoname().getAdmin1Code()); } @Override public String getDescription() { return "Looking for top populated city exact match in same countries/states as best results so far"; } }<file_sep>package org.mediacloud.cliff.places; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.mediacloud.cliff.ParseManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bericotech.clavin.gazetteer.CountryCode; import com.bericotech.clavin.gazetteer.GeoName; /** * If you have a country code (iso3166-alpha2) and ADM1 code this returns the GeoName object for it. */ public class Adm1GeoNameLookup extends AbstractGeoNameLookup { public final static Logger logger = LoggerFactory.getLogger(Adm1GeoNameLookup.class); public static final String RESOURCE_NAME = "admin1CodesASCII.txt"; private static Adm1GeoNameLookup instance; public Adm1GeoNameLookup() throws IOException { super(); } public static String getKey(String countryCode, String ADM1){ return countryCode+"."+ADM1; } public static String getKey(CountryCode countryCode, String ADM1){ return getKey(countryCode.name(),ADM1); } public GeoName get(String countryCode, String ADM1){ return this.get(getKey(countryCode,ADM1)); } @Override public void parse() { try { CliffLocationResolver resolver = (CliffLocationResolver) ParseManager.getResolver(); BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME))); String line = null; while ((line = br.readLine()) != null) { if(line.trim().length()==0){ continue; } if (line.charAt(0)=='#') { continue; } String[] columns = line.trim().split("\t"); String key = columns[0]; String name = columns[1]; int geonameId = Integer.parseInt(columns[3]); try { this.put(key, resolver.getByGeoNameId(geonameId)); } catch (UnknownGeoNameIdException e) { logger.error("Uknown geoNameId "+geonameId+" for "+name); } } logger.info("Loaded "+this.size()+" countries"); } catch(Exception e){ logger.error("Unable to load location resolver"); logger.error(e.toString()); } } private static Adm1GeoNameLookup getInstance() throws IOException{ if(instance==null){ instance = new Adm1GeoNameLookup(); } return instance; } public static GeoName lookup(String countryCodeDotAdm1Code){ try{ Adm1GeoNameLookup lookup = getInstance(); GeoName geoName = lookup.get(countryCodeDotAdm1Code); logger.debug("Found '"+countryCodeDotAdm1Code+"': "+geoName); return geoName; } catch (IOException ioe){ logger.error("Couldn't lookup state ADM1 geoname!"); logger.error(ioe.toString()); } return null; } public static boolean isValid(String countryCodeDotAdm1Code){ boolean valid = false; try{ Adm1GeoNameLookup lookup = getInstance(); valid = lookup.contains(countryCodeDotAdm1Code); } catch (IOException ioe){ logger.error("Couldn't lookup state ADM1 geoname!"); logger.error(ioe.toString()); } return valid; } public static GeoName lookup(String countryCode, String adm1Code){ return lookup( getKey(countryCode, adm1Code) ); } }<file_sep>package org.mediacloud.cliff.test.gdelt; import java.net.URL; public class GdeltEvent { private String id; private GdeltActor actor1; private GdeltActor actor2; private URL sourceUrl; public GdeltEvent(String id, GdeltActor a1, GdeltActor a2, URL url){ this.id = id; this.actor1 = a1; this.actor2 = a2; this.sourceUrl = url; } public String getId(){ return id; } public GdeltActor getActor1() { return actor1; } public GdeltActor getActor2() { return actor2; } public URL getSourceUrl() { return sourceUrl; } @Override public String toString(){ return id+": "+actor1+" & "+actor2+" ("+sourceUrl+")"; } } <file_sep>package org.mediacloud.cliff.test.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileSystemCache { private static final Logger logger = LoggerFactory.getLogger(FileSystemCache.class); private File tempDir; public FileSystemCache(String cacheName){ tempDir = new File(System.getProperty("java.io.tmpdir"),cacheName); if(!tempDir.exists()){ tempDir.mkdir(); logger.info("Created cache at "+tempDir.getAbsolutePath()); } else { logger.info("Existing cache at "+tempDir.getAbsolutePath()); } } public boolean put(String rawKey, String value){ try { FileWriter fw = new FileWriter(getFile(rawKey).getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(value); bw.close(); logger.debug("Cached "+rawKey+" to "+getFile(rawKey).getAbsolutePath()); return true; } catch (IOException e) { logger.error("Couldn't write to file "+e.toString()); } return false; } public String get(String rawKey){ if(!contains(rawKey)) return null; byte[] encoded; try { encoded = Files.readAllBytes(Paths.get(getFile(rawKey).getAbsolutePath())); return new String(encoded, StandardCharsets.UTF_8); } catch (IOException e) { logger.error("Couldn't read file "+getFile(rawKey).getAbsolutePath()); } return null; } private File getFile(String rawKey){ String key = md5(rawKey); return new File(tempDir.getAbsolutePath(),key); } public boolean contains(String rawKey){ return getFile(rawKey).exists(); } public void delete(String rawKey){ if(contains(rawKey)) getFile(rawKey).delete(); } public static String md5(String rawKey) { try { MessageDigest m = MessageDigest.getInstance("MD5"); byte[] data = rawKey.getBytes(); m.update(data,0,data.length); BigInteger i = new BigInteger(1,m.digest()); return String.format("%1$032X", i); } catch (NoSuchAlgorithmException nsae){ logger.error("Dan't find MD5 algorithm :-("); } return ""; } public static void main(String[] args) throws Exception { FileSystemCache cache = new FileSystemCache("test-cache"); String key = "testing123"; String value = "this is some content"; cache.delete(key); cache.put(key,value); String results = cache.get(key); org.junit.Assert.assertEquals(value, results); } } <file_sep>package org.mediacloud.cliff.test.places.disambiguation; import static org.junit.Assert.assertEquals; import java.io.File; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.mediacloud.cliff.ParseManager; import org.mediacloud.cliff.extractor.ExtractedEntities; import org.mediacloud.cliff.test.util.TestPlaces; import org.mediacloud.cliff.util.MuckUtils; import com.bericotech.clavin.resolver.ResolvedLocation; public class FranceNLPPlaceTest { @Test public void testFranceFromNlp() throws Exception{ String fileName = "story307385477.json"; File file = new File("src/test/resources/sample-muck-json/"+fileName); String json = FileUtils.readFileToString(file); ExtractedEntities entities = MuckUtils.entitiesFromNlpJsonString(json); assertEquals("Wrong number of location occurrences", 5, entities.getLocations().size()); assertEquals("Wrong number of people occurrences", 18, entities.getPeople().size()); assertEquals("Wrong number of organization occurrences", 8, entities.getOrganizations().size()); entities = ParseManager.getParserInstance().resolve(entities); List<ResolvedLocation> results = entities.getResolvedLocations(); assertEquals("Found "+results.size()+" places, should have been 5!",5,results.size()); assertEquals(TestPlaces.COUNTRY_IRELAND,results.get(0).getGeoname().getGeonameID()); assertEquals(TestPlaces.COUNTRY_FRANCE,results.get(1).getGeoname().getGeonameID()); } }
0dfe6271e26c461bdc4d64c6daad9df2484e833b
[ "Markdown", "Java", "Maven POM" ]
27
Java
praetr/CLIFF
52ec5b92fe44bb4d5842a8abea055d7683f9e780
e6b3ce77e84bb676697b13c0ead2633503537f12
refs/heads/main
<repo_name>logos132089/passwall-desktop<file_sep>/src/renderer/api/HTTPClient.js import Axios from 'axios' let baseURL = 'http://localhost:3625' if (process.env.NODE_ENV === 'production') { baseURL = 'https://vault.passwall.io' } const client = Axios.create({ baseURL, headers: { 'Content-Type': 'application/json; charset=utf-8', Accept: 'application/json, text/plain, */*' }, withCredentials: true, }) export default class HTTPClient { static async head(path) { return client.head(path) } static async get(path, params = {}, headers = {}) { return client.get(path, { params, headers }) } static async post(path, data = {}, headers = {}, onUploadProgress) { return client.post(path, data, { headers, onUploadProgress }) } static async put(path, data = {}, headers = {}) { return client.put(path, data, { headers }) } static async delete(path, data = {}, headers = {}) { return client.delete(path, { data, headers }) } static setHeader(key, value) { client.defaults.headers.common[key] = value } static setBaseURL(url) { client.defaults.baseURL = url } } <file_sep>/SECURITY.md # PassWall Desktop Security ## Encryption ### Encrypted Fields **Bank Accounts** bank_name: No bank_code: No account_name: Yes account_number: Yes iban: Yes currency: Yes password: Yes **Credit Cards** card_name: No cardholder_name: Yes type: Yes number: Yes expiry_date: Yes verification_number: Yes **Emails** title: No email: Yes password: Yes **Logins** title: No url: No username: Yes password: Yes **Notes** title: No note: Yes **Servers** title: No url: No ip: Yes username: Yes password: Yes hosting_username: Yes hosting_password: Yes admin_username: Yes admin_password: Yes <file_sep>/src/renderer/i18n/langs/en.js export default { Home: 'Home', MasterPasswordRecoveryMessage: 'We are not able to recover anyone’s master password.', ServerURL: 'Server URL', EMailAddress: 'E-Mail Address', MasterPassword: '<PASSWORD>', AllItems: 'All Items', Categories: 'Categories', Logins: 'Logins', Logout: 'Logout', NewLogin: 'New Login', 'Please fill all the necessary fields': 'Please fill all the necessary fields', PrivateNotes: 'Private Notes', UseThis: 'Use this', CreditCards: 'Credit Cards', Identities: 'Identities', GiveFeedback: 'Give Feedback', 'Search passwords, websites, notes': 'Search passwords, websites, notes', Trash: 'Trash', Share: 'Share', Delete: 'Delete', Login: 'Login', Password: '<PASSWORD>', Address: 'Address', Save: 'Save', Hide: 'Hide', Show: 'Show', ClickToFill: 'Click to fill', Copy: 'Copy', Edit: 'Edit', Username: 'Username', URL: 'URL', 'There is an update available.': 'There is an update available.', 'Search passwords, websites, notes': 'Search passwords, websites, notes', 'There is nothing here, yet...': 'There is nothing here, yet...', ContentHidden: 'This content is hidden', API500ErrorMessage: 'An unexpected error seems to have occured. Or you can contact us if the problem persists.', CheckIfExposed: 'Check if password has been exposed.', AlwaysOnTop: 'Always On Top', } <file_sep>/src/renderer/config.js import Vue from 'vue' import i18n from '@/i18n' import store from '@/store' import router from '@/router' import * as Waiters from '@/utils/waiters' Vue.prototype.$waiters = Waiters import * as Contant from '@/utils/constant' Vue.prototype.$C = Contant import VueClipboard from 'vue-clipboard2' Vue.use(VueClipboard) import VuePerfectScrollbar from 'vue2-perfect-scrollbar' import 'vue2-perfect-scrollbar/dist/vue2-perfect-scrollbar.css' Vue.use(VuePerfectScrollbar) import VeeValidate from 'vee-validate' Vue.use(VeeValidate, { events: 'input|blur' }) import VueDebounce from 'vue-debounce' Vue.use(VueDebounce, { defaultTime: '700ms' }) import VTooltip from 'v-tooltip' Vue.use(VTooltip) import VueWait from 'vue-wait' Vue.use(VueWait) window.wait = new VueWait({ registerComponent: false, registerDirective: false }) // Auto register all components const requireComponent = require.context('./components', true, /\.(vue)$/) requireComponent.keys().forEach(fileName => { const componentConfig = requireComponent(fileName) Vue.component(componentConfig.default.name, componentConfig.default) }) import Notifications from 'vue-notification' Vue.use(Notifications, { duration: 2500 }) Vue.prototype.$notifyError = text => Vue.prototype.$notify({ type: 'error', text }) Vue.prototype.$notifyWarn = text => Vue.prototype.$notify({ type: 'warn', text }) Vue.prototype.$notifySuccess = text => Vue.prototype.$notify({ type: 'success', text }) Vue.prototype.$request = async (callback, waitKey, errorCallback = null) => { try { window.wait.start(waitKey) await callback() } catch (error) { console.log(error) if (error.response) { if (error.response.status === 401 && !router.app._route.meta.auth) { store.dispatch('Logout') return router.push({ name: 'Login' }) } if (errorCallback) { errorCallback(error) } else if (error.response.status >= 500) { Vue.prototype.$notifyError(i18n.t('API500ErrorMessage')) } else if (error.response.data.Message && error.response.status != 401) { Vue.prototype.$notifyError(error.response.data.Message) } } else { Vue.prototype.$notifyError('Network Error !') } } finally { window.wait.end(waitKey) } } <file_sep>/src/renderer/store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) import CryptoUtils from '@/utils/crypto' import AuthService from '@/api/services/Auth' import SystemService from '@/api/services/System' import HTTPClient from '@/api/HTTPClient' import Logins from '@/views/Logins/store' import CreditCards from '@/views/CreditCards/store' import BankAccounts from '@/views/BankAccounts/store' import Emails from '@/views/Emails/store' import Notes from '@/views/Notes/store' import Servers from '@/views/Servers/store' export default new Vuex.Store({ state() { CryptoUtils.encryptKey = localStorage.master_hash CryptoUtils.transmissionKey = localStorage.transmission_key return { transmission_key: localStorage.transmission_key, master_hash: localStorage.master_hash, searchQuery: '', authenticated: false, pro: false, user: {} } }, getters: { hasProPlan(state) { return state.pro }, isAuthenticated(state) { return state.authenticated } }, actions: { async Login({ state }, payload) { payload.master_password = <PASSWORD>Utils.sha<PASSWORD>(payload.master_password) const { data } = await AuthService.Login(payload) state.transmission_key = data.transmission_key state.master_hash = CryptoUtils.pbkdf2Encrypt(data.secret, payload.master_password) CryptoUtils.encryptKey = state.master_hash CryptoUtils.transmissionKey = state.transmission_key state.user = data state.pro = state.user.type == 'pro' state.authenticated = true localStorage.email = payload.email localStorage.server = payload.server if (process.env.NODE_ENV !== 'production') { localStorage.master_hash = state.master_hash localStorage.transmission_key = state.transmission_key } }, Logout({ state }, payload) { const { data } = AuthService.Logout(payload) state.transmission_key = null state.master_hash = null state.user = null state.authenticated = false state.pro = false const lsKeys = Object.keys(localStorage).filter(key => ['email','server'].includes(key) === false) lsKeys.forEach(key => localStorage.removeItem(key)) }, async Import(_, data) { return SystemService.Import(data) }, async Export() { const { data } = SystemService.Export() return data } }, mutations: { onInputSearchQuery(state, event) { state.searchQuery = event.target.value } }, modules: { Logins, CreditCards, BankAccounts, Emails, Notes, Servers } }) <file_sep>/CHANGELOG.md # Changelog PassWall Desktop ## [0.1.4] (04-08-2020) ### Added - First letters of user first and last names - Company logos - Loading state to signin button - Text area component to private notes - Added scroll bar on the detail column - Encryption to json - Import ### Enhanced - Generate password button and "Use This" actions ## [0.1.3] (23-06-2020) ### Added - Servers type ### Fixed - Email password store ## [0.1.2] (03-06-2020) ### Added - Changed the size of stars ### Updated - Updated notification ## [0.1.1] (03-06-2020) ### Added - Keyboard shortcuts like CMD + V etc. - Logout on quitting app <!-- ### Changed ### Removed ### Fixed ### Deprecated ### Security --> ## [0.1.0] (31-05-2020) - First Release <!-- ### Added ### Changed ### Removed ### Fixed ### Deprecated ### Security --><file_sep>/src/renderer/api/services/Auth.js import HTTPClient from '@/api/HTTPClient' export default class AuthService { static async Login(payload) { return HTTPClient.post(`/auth/signin`, payload) } static async Logout(payload) { return HTTPClient.post(`/auth/signout`, payload) } static async Check(payload) { return HTTPClient.post('/auth/check', payload) } static async Refresh(payload) { return HTTPClient.post(`/auth/refresh`, payload) } } <file_sep>/src/renderer/router/auth-check.js import store from '@/store'; export default (to, from, next) => { const isAuthPage = to.matched.some(record => record.meta.auth) const isAuthenticated = store.getters['isAuthenticated'] if (isAuthenticated) { if (isAuthPage) { return next({ name: 'Home' }) } } else { if (!isAuthPage) { return next({ name: 'Login' }) } } next() }<file_sep>/README.md # PassWall Desktop <p align="center"> <img src="https://www.yakuter.com/wp-content/yuklemeler/passwall-cover.png" alt="" width="800" height="450" /> </p> <p align="center"> The <strong>PassWall Desktop</strong> is an Electron Vue application that powers the web vault (https://vault.passwall.io/). </p> ## Build/Run If you want to use this client with official PassWall Server, please first sign up via [PassWall Signup](https://signup.passwall.io) ### Requirements - [Node.js](https://nodejs.org) (Version 12.14.0) - [Electron](https://www.electronjs.org) ### Node Version Passwall desktop uses Node 12.14.0 version. For an easy Node setup, you can install NVM and change Node version easily. ``` bash # install nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash # install desired node version nvm install 12.14.0 # change version nvm use 12.14.0 ``` ### Run the app After installing yarn, you can download dependencies and run the app with the commands below. ``` bash # install dependencies yarn # serve with hot reload at localhost:9080 yarn run dev # build electron application for production yarn run build ``` ### Build From Source Code After installing yarn, you can download dependencies and run the app with the commands below. ``` bash # auto choose platform and architecture yarn build # MacOS x64 (intel) yarn build --mac --x64 # MacOS arm64 (M1) yarn build --mac --arm64 # Linux Debian Package yarn build --linux --x64 # Windows x64 yarn build --win --x64 ```<file_sep>/src/renderer/utils/waiters.js export const Auth = { Login: 'Auth_Login' } export const BankAccounts = { All: 'BankAccounts_All', Create: 'BankAccounts_Create', Update: 'BankAccounts_Update', Delete: 'BankAccounts_Delete', Get: 'BankAccounts_Get' } export const Logins = { All: 'Logins_All', Create: 'Logins_Create', Update: 'Logins_Update', Delete: 'Logins_Delete', Get: 'Logins_Get' } export const CreditCards = { All: 'CreditCards_All', Create: 'CreditCards_Create', Update: 'CreditCards_Update', Delete: 'CreditCards_Delete', Get: 'CreditCards_Get' } export const Emails = { All: 'Emails_All', Create: 'Emails_Create', Update: 'Emails_Update', Delete: 'Emails_Delete', Get: 'Emails_Get' } export const Notes = { All: 'Notes_All', Create: 'Notes_Create', Update: 'Notes_Update', Delete: 'Notes_Delete', Get: 'Notes_Get' } export const Servers = { All: 'Servers_All', Create: 'Servers_Create', Update: 'Servers_Update', Delete: 'Servers_Delete', Get: 'Servers_Get' }
5efc18a6704649f42a906dc9fdc76b6e04fb3c39
[ "JavaScript", "Markdown" ]
10
JavaScript
logos132089/passwall-desktop
cdbe2f4b9bbce424bda28024c4b8e5d75e59ef9f
928c957f5354ce1856444d007b969ec03008c237
refs/heads/master
<file_sep>/** * * @author departamento */ public class Principal { public static void main(String[] args) { //No puedo instanciar la clase Animal porque es abstracta //Animal animal = new Animal(); Perro perro = new Perro(); Gato gato = new Gato(); System.out.println("El perro va a decir hola: "); perro.decirHola(); System.out.println("Ahora va a decir hola el gato:"); gato.decirHola(); System.out.println("Ahora hace ruido el perro: "); perro.hacerRuido(); System.out.println("Y ahora hace ruido el gato"); gato.hacerRuido(); System.out.println("Añadimos cambios al proyecto"); System.out.println("Añadimos el 2do cambio al proyecto"); System.out.println("Añadimos el 3er cambio al proyecto"); } } <file_sep># proyectNetBeans Proyect
5861ab79355e5fb72460db229d56387b2a941e97
[ "Markdown", "Java" ]
2
Java
ErickFernando/proyectNetBeans
a3eb4031d86a646f3c3a478e65016e15d0ce57bb
8baa989cbf6dd14b01e052ea24003d82f9119e10
refs/heads/master
<file_sep>package fr.societegenerale; public class Arrays { public static void main(String[] args) { /** * * Créer un tableau des 10 premieres lettres Parcourir et afficher le tableau de * maniere croissante Changer le premier element par 'j' Changer le dernier * element par 'z' Parcourir et afficher le tableau de maniere decroissante sur * une seule ligne * */ char[] tab = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }; for (int i = 0; i < tab.length; i++) { System.out.println(tab[i]); } tab[0] = 'j'; tab[tab.length - 1] = 'z'; for (int i = tab.length - 1; i >= 0; i--) { System.out.print(tab[i]); } } }<file_sep>package fr.societegenerale; public class Strings { public static void main(String[] args) { String hello = null; System.out.println(hello.length()); } }
9e7255d66dc30a8f9fc254cec189bcbc5b56b87a
[ "Java" ]
2
Java
webyprod/h
8159201becf5b1e099bc5521e372cd64ae78feea
33da7eaf82ce5b3191f0f4369b2f3067be26f8e0
refs/heads/master
<file_sep><?php namespace AppModelBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * User */ class User extends BaseUser { /** * @var integer */ protected $id; /** * @var string */ private $name; /** * @var string */ private $lastname; /** * @var \DateTime */ private $daybirth; /** * @var string */ private $avatar; /** * @var array */ private $settings; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return User */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set lastname * * @param string $lastname * @return User */ public function setLastname($lastname) { $this->lastname = $lastname; return $this; } /** * Get lastname * * @return string */ public function getLastname() { return $this->lastname; } /** * Set daybirth * * @param \DateTime $daybirth * @return User */ public function setDaybirth($daybirth) { $this->daybirth = $daybirth; return $this; } /** * Get daybirth * * @return \DateTime */ public function getDaybirth() { return $this->daybirth; } /** * Set avatar * * @param string $avatar * @return User */ public function setAvatar($avatar) { $this->avatar = $avatar; return $this; } /** * Get avatar * * @return string */ public function getAvatar() { return $this->avatar; } /** * Set settings * * @param array $settings * @return User */ public function setSettings($settings) { $this->settings = $settings; return $this; } /** * Get settings * * @return array */ public function getSettings() { return $this->settings; } } <file_sep><?php namespace AppModelBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * RelUserFolder */ class RelUserFolder { /** * @var integer */ private $id; /** * @var boolean */ private $isOwner; /** * @var \AppModelBundle\Entity\User */ private $user; /** * @var \AppModelBundle\Entity\Folder */ private $folder; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set isOwner * * @param boolean $isOwner * @return RelUserFolder */ public function setIsOwner($isOwner) { $this->isOwner = $isOwner; return $this; } /** * Get isOwner * * @return boolean */ public function getIsOwner() { return $this->isOwner; } /** * Set user * * @param \AppModelBundle\Entity\User $user * @return RelUserFolder */ public function setUser(\AppModelBundle\Entity\User $user = null) { $this->user = $user; return $this; } /** * Get user * * @return \AppModelBundle\Entity\User */ public function getUser() { return $this->user; } /** * Set folder * * @param \AppModelBundle\Entity\Folder $folder * @return RelUserFolder */ public function setFolder(\AppModelBundle\Entity\Folder $folder = null) { $this->folder = $folder; return $this; } /** * Get folder * * @return \AppModelBundle\Entity\Folder */ public function getFolder() { return $this->folder; } } <file_sep>TASK ==== Simple Application for manage your task ### Todos - Write Tests - Translate register page - Translate login page - Translate confirmation page - Translate header section - Translate sidebar section - Translate profile section - Profile with X-Editable Form - Write instrucctions
00391c2d8e0b84a11ef53dec727402624f4ab791
[ "Markdown", "PHP" ]
3
PHP
sebathomson/task
6e205467d876e86fac620dca2c0552012956d899
add5f4f5be067cdbd33afbe70b2a50f5283e1899
refs/heads/master
<repo_name>jarvisc1/simpleboot<file_sep>/README.md simpleboot ========== Easy bootstrap confidence intervals for learners ------------------------------------------------ **simpleboot** is an extremely basic and pared-down R function to provide bootstrap confidence intervals for teaching purposes. I assume little or no R awareness at this stage in an introductory stats course. Following the [GAISE guidelines](http://www.amstat.org/education/gaise/GaiseCollege_Full.pdf), I use bootstrapping and randomisation tests to introduce inference right at the beginning. These are not advanced topics, though they may appear in the later parts of a traditional textbook because they are more recently implemented than asymptotic "shortcut" formulas. Nevertheless, there's nothing new about them. Randomisation goes back to Ronald Fisher between the two world wars, while bootstrapping was mathematically formalised by <NAME> in 1979. Syntax ------ If you have a data frame called Mydata, and you want the CI around the mean of Income: `simpleboot(Mydata$Income , "mean")` This works for any R function that takes a single argument and returns a single value. (but see To-Do List below) In my experience, students will use this for means, medians, standard deviations, etc. So, these are the functions available to you: `simpleboot(Mydata$Income , "mean")` `simpleboot(Mydata$Income , "median")` `simpleboot(Mydata$Income , "sd")` `simpleboot(Mydata$Income , "IQR")` Missing data are ignored, which is to say that I impose the R option na.rm=TRUE. If you don't know what this means, don't worry about it! Also, I added some that are not functions in base R: `simpleboot(Mydata$Income,Mydata$Anxiety,"pearson")` `simpleboot(Mydata$Income,Mydata$Anxiety,"spearman")` `simpleboot(Mydata$Income,"p25")` `simpleboot(Mydata$Income,"p75")` `simpleboot(Mydata$Income,"iqr")` `simpleboot(Mydata$Income,"quantile", probs = 0.2)` `simpleboot(Mydata$Income,Mydata$Anxiety,"meandiff")` `simpleboot(Mydata$Income,Mydata$Anxiety,"mediandiff")` That gives you the Pearson correlation, the Spearman correlation, the 1st and 3rd quartiles, the inter-quartile range (which just duplicates IQR()), the 20th percentile (0.2 quantile), the difference in means and the difference in medians. You might not notice if you use this inside R Commander, but a histogram of the empirical distribution function is drawn in the R window. To-Do List ---------- * Perhaps include some asymptotic formulas too * Then wrap it all up in a Rcmdr plug-in <file_sep>/simpleboot.R simpleboot<-function(x,y=NULL,stat, probs = NULL, reps=1000) { cat("Bootstrapping can go wrong!\n") cat("This simple function will not show you warning messages.\n") cat("Check results closely and be prepared to consult a statistician.\n") if(stat=="max" | stat=="min") { warning("Bootstrap is likely to be incorrect for minima and maxima") } if(stat!="mean" & stat!="median" & stat!="p25" & stat!="p75" & stat!="iqr" & stat!="quantile" & stat!="sd" & stat!="pearson" & stat!="spearman" & stat!="meandiff" & stat!="mediandiff") { warning("Simpleboot is only programmed to work with stat set to one of: mean, median, sd, iqr, p25, p75, quantile, pearson, spearman, meandiff, mediandiff. Other functions might work, but there's no guarantee!") } if(stat == "quantile" & (probs <= 0 | probs > 1)){ stop("Quantile values must be greater than zero and less than one.") } require(boot) if(stat=="p25") { eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) quantile(x[i],probs=0.25,na.rm=TRUE)"),list(stat=stat))))) } else if(stat=="p75") { eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) quantile(x[i],probs=0.75,na.rm=TRUE)"),list(stat=stat))))) } else if(stat=="iqr") { eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) quantile(x[i],probs=0.75,na.rm=TRUE)-quantile(x[i],probs=0.25,na.rm=TRUE)"),list(stat=stat))))) } else if(stat=="quantile" & prob ) { eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) quantile(x[i],probs=",probs,",na.rm=TRUE)"),list(stat=stat))))) } else if(stat=="pearson" | stat=="spearman") { x<-matrix(c(x,y),ncol=2)[(!is.na(x))&(!is.na(y)),] eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) cor(x[i,],use='complete',method='",stat,"')[1,2]"),list(stat=stat))))) } else if(stat=="meandiff"){ eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) mean(x[i])-mean(y[i])"),list(stat=stat))))) } else if(stat=="mediandiff"){ eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) median(x[i])-median(y[i])"),list(stat=stat))))) } else { eval(parse(text=eval(substitute(paste0("p.func<-function(x,i) ",stat,"(x[i],na.rm=TRUE)"),list(stat=stat))))) } bootsy<-boot(x,statistic=p.func,R=reps,stype="i") hist(bootsy$t,breaks=25,main="EDF from bootstrap",xlab=stat) suppressWarnings(return(list(replicates=reps,point.estimate=bootsy$t0,normal.ci=c(boot.ci(bootsy)$normal[2],boot.ci(bootsy)$normal[3]), percent.ci=c(boot.ci(bootsy)$percent[4],boot.ci(bootsy)$percent[5]), bca.ci=c(boot.ci(bootsy)$bca[4],boot.ci(bootsy)$bca[5])))) }
87558dfcddced389d4ca06081b875bac70edf545
[ "Markdown", "R" ]
2
Markdown
jarvisc1/simpleboot
44427b7b53e544b90dd6739a2839347d30d2bca6
fb2310a1b6965473d53f7917f58c3e91f673541f
refs/heads/master
<file_sep># webpack_project web入门实战项目 # 打包命令 npm run bundle # 说明 1. 开发路径在src目录下 2. 运行需要直接双击bundle下面的index.html <file_sep>function HeaderModle() { var mybody = document.getElementById('myBody'); var header = document.createElement('div'); header.innerText = '我是哪个header啊!'; mybody.append(header); } export default HeaderModle<file_sep>import HeaderModle from './header.js' new HeaderModle() import imgurl from './11.jpg' console.log(imgurl, 'imgurl') let img = new Image() img.src = imgurl var mybody = document.getElementById('myBody'); mybody.append(img);
b3e3a1f3a122d450e067e88619678498d060458d
[ "Markdown", "JavaScript" ]
3
Markdown
yuanxin42/webpack_project
fda8551b176b40789623e5993b82b74aea76f74d
4328eb2a98290354c3c1de298bd44b996bfb5acf
refs/heads/main
<repo_name>dmwg/docs<file_sep>/src/internals/components/button.md # Button The `Button` component is used throughout Discord for button inputs. ## Notes `Button` has two unique props for setting some classes: - `color`: sets the (background) color of the button, these classes can be accessed in an object under `Button.Colors` - `size`: sets the size (usually padding) of the button, these classes can be accessed in an object under `Button.Sizes` ## Getting Component You can get the component via it's display name, `DropdownButton`. <br> /mod_specific.webpack.displayname DropdownButton Button ## Usage <br> <code-group> <code-block title="JS" active> ```js React.createElement(Button, { color: Button.Colors.BRAND, size: Button.Sizes.SMALL, className: 'my-button', disabled: false, onClick: () => alert(1) }, 'My Button'); ``` </code-block> <code-block title="JSX"> ```jsx <Button color=Button.Colors.BRAND size=Button.Sizes.SMALL className="my-button" disabled=false onClick=() => alert(1) > My Button </Button> ``` </code-block> </code-group> <file_sep>/src/internals/components/tooltip.md # Tooltip <file_sep>/src/internals/tech/react.md # React [React](https://reactjs.org) is a JavaScript library for building user interfaces. It is component-based, meaning parts are often self-contained. It is also based on a virtual DOM system, so sometimes has similar syntax to HTML. Discord uses React components throughout it's app. An example of this is the button component, used for essentially all buttons throughout the app. Components are usually in their own Webpack module using a display name. Another common was is a Webpack module with several exports, where you can get it by using the display name as a property of the parent object.<file_sep>/src/internals/tech/webpack.md # Webpack [Webpack](https://webpack.js.org) is a one of the most common bundlers in the JavaScript ecosystem. It is used to bundle websites for performance (minifying and splitting code) and transpilation (to make modern code work in older browsers) via projects like [Babel](https://babeljs.io). An API exists in all mods to get Webpack modules from within Discord's code bundle. This is useful as most of their internal functions, React components, etc. are otherwise not useable.<file_sep>/src/theming/mods/goosemod.md # GooseMod GooseMod is an exception to most mods, as it does not have it's own theme format. Instead, it uses "modules", not separating themes and plugins. However, you probably shouldn't make your own anyway, as GM's Store supports porting essentially all themes (ones supporting BD, PC, VZ). To get your theme added to GM's Store (it does not have local themes or plugins), you should [join their Discord](https://goosemod.com/discord) and ask there.<file_sep>/src/.vuepress/md_preproc/mod_specific/webpack/displayname.js module.exports = (_, displayName) => { const split = displayName.split(' '); const variableName = split[1] || split[0]; const realName = split[0]; return `<code-group> <code-block title="GooseMod" active> <code-group> <code-block title="ESM" active> \`\`\`js import { findByDisplayName } from '@goosemod/webpack'; const ${variableName} = findByDisplayName('${realName}'); \`\`\` </code-block> <code-block title="CJS"> \`\`\`js const { findByDisplayName } = require('@goosemod/webpack'); const ${variableName} = findByDisplayName('${realName}'); \`\`\` </code-block> </code-group> </code-block> <code-block title="Powercord (v2)"> \`\`\`js const { getModuleByDisplayName } = require('powercord/webpack'); const ${variableName} = getModuleByDisplayName('${realName}', false); \`\`\` </code-block> <code-block title="BetterDiscord"> \`\`\`js // This uses BD's built-in API, you may be using a library which has it's own Webpack API const { findByDisplayName } = BdApi; const ${variableName} = findByDisplayName('${realName}'); \`\`\` </code-block> <code-block title="Vizality"> \`\`\`js import { getModuleByDisplayName } from '@vizality/webpack'; const ${variableName} = getModuleByDisplayName('${realName}'); \`\`\` </code-block> </code-group>` };<file_sep>/src/theming/mods/betterdiscord.md # BetterDiscord BetterDiscord themes are made as a single CSS file (often referred to as a "theme file"), commonly named using the format `<name>.theme.css`. ## Meta Comment Metadata (information about the theme) is provided to BD via a comment block at the top of the CSS file. ### Example ```css /** * @name Revert Rebrand * @author GooseNest * @donate https://github.com/sponsors/CanadaHonk * @description Reverts Discord's 2021 rebrand (font, colors, reactions, mentions, loading screen, home icon, reply ping color, and more) * @invite neMncS2 * @source https://Goose-Nest.github.io/GT-RevertRebrand/src/RevertRebrand.theme.css * @website https://github.com/Goose-Nest/GT-RevertRebrand * @version 4.2 */ ``` ### Properties - `name`: Name of the theme - `author`: Name of the author(s), sometimes including their Discord discriminator (eg: `Ducko#4698`) - `authorId` (optional): User ID of the author(s) - `version`: Version of the theme, usually using a [Semantic Versioning](https://semver.org)-like format like 1.2.3 - `description`: Description of the theme, usually describing what it does - `invite` (optional): Invite code of the theme's support Discord - `source` (optional): Link to the source of the theme - `website` (optional): Link to a website for the theme - `donate` (optional): Link to a website for donating to the author(s) of the theme<file_sep>/src/index.md --- home: true actionText: Browse Internals → actionLink: /internals/intro/webpack.html --- <file_sep>/src/internals/components/markdown.md # Markdown The `Markdown` component can be used for making [Markdown](https://en.wikipedia.org/wiki/Markdown) text formatted (eg: turning `**text**` into **text**). ## Notes Keep in mind Discord's Markdown implementation is non-standard (mostly by not featuring all Markdown features). Specific non-standard changes in the component: - No links (`[text shown](https://example.com)`) - No tables Additionally, the component *does* support some features not present in normal Discord messages: - Lists (`- example item`) - Headers (`# header`) ## Getting Component You can get the component via it's display name, `Markdown`. <br> /mod_specific.webpack.displayname Markdown ## Usage <br> <code-group> <code-block title="JS" active> ```js const markdownText = '***Wow!*** *Markdown* formatting is **very** __neat__.'; React.createElement(Markdown, { className: 'my-markdown-container' }, markdownText); ``` </code-block> <code-block title="JSX"> ```jsx <Markdown className="my-markdown-container"> ***Wow!*** *Markdown* formatting is **very** __neat__. </Markdown> ``` </code-block> </code-group><file_sep>/README.md # DMWG Docs DMWG Docs
7f3d757db4f4085cd2d4f303bb220e2486910f71
[ "Markdown", "JavaScript" ]
10
Markdown
dmwg/docs
ad321f4299140d2457abb54d373bb1454a193c2f
6f56089ac16a945e3fa016c6dee76f0c37adf9a3
refs/heads/master
<repo_name>BlancoLautaro01/POO2-TP11<file_sep>/src/cuenta/CuentaBancaria.java package cuenta; public abstract class CuentaBancaria { protected HistorialMovimientos historialDeMovimientos; protected Notificador notificador; protected int saldo; public CuentaBancaria(HistorialMovimientos historialDeMovimientos, Notificador notificador, Integer saldo) { super(); this.historialDeMovimientos = historialDeMovimientos; this.notificador = notificador; this.saldo = saldo; } public int getSaldo() { return saldo; } //Esta funcion hace lo mismo en cada hijo, por lo que es mejor definir en ellos la condicion y hacer los pasos aca. (Repeticion de codigo) public void extraer(Integer monto) { if (this.condicion(monto)) { this.saldo = saldo - monto; this.historialDeMovimientos.registrarMovimiento("Extraccion", monto); this.notificador.notificarNuevoSaldoACliente(this); } } public abstract boolean condicion(Integer monto); }
608a30a7b4efb3bcd06e8247b0ae8a52d10c62e1
[ "Java" ]
1
Java
BlancoLautaro01/POO2-TP11
9b456c6b61fb7f42f3e0ac92820af9b002711351
f1559a3df63d405d972e0851569f6bbc94c444ec
refs/heads/master
<file_sep> module.exports = function(Mark, opt) { require('./pipes/basic.js')(Mark); require('./pipes/cheerio.js')(Mark, opt.$); require('./pipes/chalk.js')(Mark, opt.chalk); }; <file_sep>var utils = require('../src/utils'), _ = require('underscore'), promptly = require('promptly'); exports.init = function(program) { program .command('samples [N]') // additional args are passed to quget .description('show samples, or run sample N') .action(function () { program.done = true; action(program); }); }; var samples = [{ label: 'Hacker News titles', cmd : 'http://news.ycombinator.com ".title > a" -l 7 -n' }, { label: 'Hacker News titles and subtext', cmd: 'http://news.ycombinator.com ".title > a, .subtext|pack|after \\n|red" -l 7' }, { label: 'Wikipedia\'s On This Day', cmd: 'http://en.wikipedia.org/wiki/Main_Page "#mp-otd > p:first-of-type, #mp-otd > ul:first-of-type > li|tease 15"' }, { label: 'GitHub trending', cmd: 'https://github.com/trending?since=weekly ".repo-list-name|pack, .repo-list-description|tease 7|after \\n" --limit 10' }, { label: 'Markup filters', cmd: 'https://github.com/adammark/Markup.js "h3:contains(Built-in pipes) ~ p|tease 9" -n --limit 45 ' }, { label: 'Cheerio selectors', cmd: 'https://github.com/fb55/css-select "h2:contains(Supported selectors) ~ ul li|pack|before \\n\\t "' }, { label: 'Beijing Air Twitter feed', cmd: 'https://twitter.com/BeijingAir "#stream-items-id > li div.tweet div.content p" --limit 25' }, { label: 'Custom template 1', cmd: 'https://twitter.com/BeijingAir "#stream-items-id > li div.tweet div.content p" --limit 25 -T "{{parent.children.1|text|red}}"' }, { label: 'Custom template 2', cmd: 'http://news.ycombinator.com ".title > a, .subtext" -l 4 -T "{{if $0}}{{.|choose Title|red}}: {{.|text}}{{/if}} - {{if $1}}{{if $1}}{{.|text|pack|red|after \\n}}{{/if}}"' }, { label: 'Jeopardy!', cmd: 'http://www.j-archive.com/showgame.php?game_id=5137 ".clue_text|bold, .clue div[onmouseover]@onmouseover|regex correct_response.>(.*?)<|gray|before \\n" --sep " / "' }]; function action(program) { var choice = program.args[0], prompt; if (choice) { if (choice > samples.length || parseInt(choice, 10) != choice) { console.log(utils.error('Incorrect sample number.')); } else { runSample(null, choice); return; } } // number the labels _(samples).each(function(s, i){ s.label = (1+i) + '. ' + s.label; }); prompt = '\nChoose a sample to run:\n' + _(samples).pluck('label').join('\n') + '\n\n> '; promptly.choose(prompt, _.range(1, samples.length + 1), runSample); } var runSample = exports.runSample = function runSample(err, choice, silent, callback){ --choice; var sample_cmd = _(samples).pluck('cmd')[choice], label = _(samples).pluck('label')[choice]; runCmd(sample_cmd, label, silent, callback); }; var runCmd = exports.runCmd = function runCmd(sample_cmd, label, silent, callback){ var exec = require('child_process').exec, path = require('path'), cmd = ['node', process.argv[1], sample_cmd, process.argv.slice(4).join(' ') ].join(' '); !silent && console.log('Running: ', utils.info(cmd + '\n'), utils.chalk.bold.magenta(label)); exec(cmd, {} ,callback || function(err, stdout, stderr){ err && console.log(err); console.log(stderr); console.log(stdout); process.exit(); }); }; <file_sep># qsel - web snippets from the command-line [![NPM version](https://img.shields.io/npm/v/qsel.svg)](https://www.npmjs.com/package/qsel) [![Build Status](https://img.shields.io/travis/moos/quget/master.svg)](https://travis-ci.org/moos/quget) ## Introduction qsel (formerly `quget`) brings together the power of [request](https://github.com/request/request), [cheerio](https://github.com/cheeriojs/cheerio), and jQuery-like CSS selectors to the command-line. ```bash $ qsel http://news.ycombinator.com ".title > a" --limit 3 Best things and stuff of 2015 When coding style survives compilation: De-anonymizing programmers from binaries Postgres features and tips ``` ```bash $ qsel http://www.google.com/search?q=the+price+of+gold "td._dmh < tr|yellow" Gold Price Per Ounce$1,075.20$3.90 Gold Price Per Gram$34.57$0.13 Gold Price Per Kilo$34,568.46$125.39 ``` ```bash $ qsel https://github.com/trending?since=monthly ".repo-list-name|pack" --limit 5 apple / swift FreeCodeCamp / FreeCodeCamp MaximAbramchuck / awesome-interviews oneuijs / You-Dont-Need-jQuery phanan / koel ``` ## Installation `npm install -g qsel` ## Usage ```text Usage: qsel [command] [options] <url> [selector] | - Example: qsel http://news.ycombinator.com ".title > a|bold|red" --limit 5 Options: -T, --template <template> template "node: {{name}}, text {{.|text}}" -l, --limit <count> limit query to count matches (-count from bottom) (default: 0) -r, --rand select randomly from matched set (can be combined with --limit) -j, --json full results object as (pretty) JSON -c, --compact when used with --json, outputs compact format -n, --line-number add line numbers to output --request-options <request-options> options for "request" as relaxed JSON, "{foo: bar}" -h, --help output usage information -V, --version output the version number Batch processing options: - , --stdin read <url>(s) from STDIN -o, --outfile <file> file to output to (default: stdout) -q, --quite quite the logging -p, --pause <seconds> pause between batch requests (default: 0.0 secs) --sep <seperator> seperator for multiple matches (default: "\n") --tag <tag> enclose complete result in <tag></tag> Commands: samples [N] show samples, or run sample N help [what] get extra help with: pipes, selector, request-options ``` ## Selectors qsel supports all CSS3, some CSS4 and custom jQuery selectors like `:contains()`. For complete list see [css-selelct](https://github.com/moos/css-select#supported-selectors), or run `qsel help selector`. If no `selector` is given, the complete HTML of the page is returned. ## Attributes In general qsel returns the `text()` of the matched nodes. To select an attribute, add the [x-ray](https://github.com/lapwinglabs/x-ray)-like `@` to the selector (*before the pipes!*). - `selector@<attr-name>` - get an attribute by name, e.g., `selector@href` - `selector@text` - get text content of matched nodes recursively (default) - `selector@html` - get the innerHTML Multiple attributes are supported: `selector@id@class`. ## Filters / Pipes qsel supports [Markup.js](https://github.com/adammark/Markup.js)-type pipes separated by `|`, for example, `selector|upcase`, `selector|pack|tease 7`. For complete list see Markup.js' [built-in pipes](https://github.com/adammark/Markup.js#built-in-pipes). Need some emphasis or color? All [chalk.styles](https://github.com/chalk/chalk#styles) are available as pipes as well: e.g. `selector|red`, `selector|bold|bgBlue`. Additional pipes are defined in (src/pipes/basic.js): - `|after text` - add text after each match - `|before text` - add text before each match - `|quote text` - add text before and after each match - `|tag name` - enclose match in &lt;name&gt; and &lt;/name&gt; - `|incr N` - increment the match value by N (default 1) - `|decr N` - decrement the match value by N (default 1) - `|regex (foo.*)` - match by regex - `|colorize` - apply random chalk style to every line Use `\n` to add a new line, e.g. `selector|after \n\n`. For complete list, run `qsel help pipes`. ## Shell pipe qsel can be forced to read from STDIN, either interactively or in a shell pipe, by providing the single dash option `-`. In this mode, each line of input is read as a url and executed in order. Each line may also contain its own `selector`. If none is given, the `selector` from the CLI is used. ```shell $ qsel http://news.ycombinator.com ".title > a@href" -l 3 | qsel - "title|pack" Page not found | Docker Blog Permission to Fail - <NAME>ler of Keen IO The Amazon Whisperer ``` ## Examples For other examples, run `qsel samples`. (Note: samples are run using Node's `child_process.exec()` which gobbles colors in output streams. To see the colors, run the command directly from the shell.) #### Run samples interactively ```bash $ qsel samples Choose a sample to run: 1. Hacker News titles 2. Hacker News titles and subtext 3. Wikipedia's On This Day 4. GitHub trending 5. Markup filters 6. Cheerio selectors 7. Beijing Air Twitter feed 8. Custom template 1 9. Custom template 2 10. Jeopardy! > ``` #### Run a sample ```bash $ qsel samples 1 Running: qsel http://news.ycombinator.com ".title > a" -l 7 -n Hacker News titles 1. Apple, Google ban location tracking in apps using their contact-tracing system 2. Extremely disillusioned with technology. Please help 3. Stealing your SMS messages with iOS 0day 4. Experts Doubt the Sun Is Burning Coal (1863) 5. I gave away my books and sales increased 6. Iloveyou 7. Backblaze B2 Cloud Storage Now Has S3 Compatible APIs ``` #### Simple ```bash $ qsel http://www.google.com/search?q=the+price+of+gold "td._dmh < tr" --limit 1 Gold Price Per Ounce$1,075.20$3.90 ``` #### With JSON output ```bash $ qsel http://www.google.com/search?q=the+price+of+gold "td._dmh < tr" --limit 1 --json [ { "type": "tag", "name": "tr", "attribs": {}, "children": [ { "type": "tag", "name": "td", "attribs": { "class": "_dmh" }, "children": [ { "data": "Gold Price Per Ounce", "type": "text" } ] }, { "type": "tag", "name": "td", "attribs": { "class": "_dmh" }, "children": [ { "data": "$1,075.20", "type": "text" } ] }, { "type": "tag", "name": "td", "attribs": { "class": "_dmh" }, "children": [ { "data": "$3.90", "type": "text" } ] } ], "selectorIndex": 0 } ] ``` #### With JSON compact ```bash $ qsel http://www.google.com/search?q=the+price+of+gold "td._dmh < tr" --limit 1 --json --compact [{"type":"tag","name":"tr","attribs":{},"children":[{"type":"tag","name":"td","attribs":{"class":"_dmh"},"children":[{"data" :"Gold Price Per Ounce","type":"text"}]},{"type":"tag","name":"td","attribs":{"class":"_dmh"},"children":[{"data":"$1,075.20 ","type":"text"}]},{"type":"tag","name":"td","attribs":{"class":"_dmh"},"children":[{"data":"$3.90","type":"text"}]}],"selec torIndex":0}] ``` #### With line numbers ```bash $ qsel http://www.google.com/search?q=the+price+of+gold "td._dmh < tr" -n 1. Gold Price Per Ounce$1,075.20$3.90 2. Gold Price Per Gram$34.57$0.13 3. Gold Price Per Kilo$34,568.46$125.39 ``` #### Select at random ```text $ qsel "https://www.reddit.com/r/oneliners/top/?sort=top&t=year" "a.title|colorize" --limit 3 --rand "DO NOT TOUCH" must be one of the most terrifying things to read in braille. I can't believe no one has managed to come up with a cure for anorexia yet, honestly, I thought it'd be a piece of. Gravity is one of the most fundamental forces in the universe, but if you remove it, you get gravy. ``` #### Custom template ```text $ qsel http://www.google.com/search?q=the+price+of+gold "td._dmh < tr|yellow" -T "#{{index|incr}} {{ty pe|upcase}} {{name}} has {{children.length}} children: {{.|text}}" #1 TAG tr has 3 children: Gold Price Per Ounce$1,075.20$3.90 #2 TAG tr has 3 children: Gold Price Per Gram$34.57$0.13 #3 TAG tr has 3 children: Gold Price Per Kilo$34,568.46$125.39 ``` See [Markup.js](https://github.com/adammark/Markup.js) for template help. #### Custom HTTP headers Any options for [request](https://github.com/request/request#requestoptions-callback) can be entered in a *relaxed* [jsonic](https://github.com/rjrodger/jsonic) format using `--request-options`. ```bash $ qsel https://api.github.com/users/moos Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes. $ qsel https://api.github.com/users/moos --request-options "headers:{\"User-Agent\":foo}" {"login":"moos","id":233047,"avatar_url":"https://avatars.githubusercontent.com/u/233047?v=3", [snip] ``` #### Define an alias ```bash $ alias def='function _blah(){ qsel https://www.bing.com/search?q=define+$@ "#b_results ol:first-child|bold"; };_blah' $ def foo a term used as a universal substitute for something real, especially when discussing technological ideas and problems ``` ## Package note qsel relies on a [fork of css-select](https://github.com/moos/css-select) which supplies the matched selector index in the list of matched elements. Since css-select is a dependency of cheerio, it ues `npm shrinkwrap` to load the fork. Any updates to cheerio will require manually updating the shrinkwrap json file. Hopefully with upcoming npm 3's flat dependency tree, this shebang can be eliminated. ## Change log - 0.7.1 - Add better logging for batch ops. - 0.7.0 - Add `--tag` option. Write results out incrementally in batch ops. - 0.6.0 - Add `---pause` option for batch operations - 0.5.0 - Renamed package to **qsel** (query selector) - 0.4.1 - Add `|tag foo` pipe. - 0.4.0 - Add `--outfile` and `--quite` options - 0.3.3 - Update cheerio to 0.22.0 compatible with lodash 4.17 - 0.3.2 - Use moos/cheerio to pick up moos/css-select. - 0.3.1 - Add `npm-shrinkwrap.json` back in as it's needed to pick up the right `css-select` for `cheerio` - 0.3.0 - Fix reading multiple URLs from STDIN - 0.2.4 - Early version ## License (The MIT License) <file_sep> module.exports = function(Mark, $) { Mark.pipes.text = function(matches){ return $(matches).text(); }; // NOTE: only returns first match! Mark.pipes.html = function(matches){ return $(matches).html(); }; Mark.pipes.attr = function(matches, name){ // handle special case: if (name === 'html') return Mark.pipes.html(matches); if (name === 'text') return Mark.pipes.text(matches); return $(matches).attr(name) || ''; }; }; <file_sep>#!/usr/bin/env node var program = require('commander'), fs = require('fs'), version = require('../package.json').version, quget = require('../src/quget'); program .usage('[command] [options] <url> [selector] | -\n' + '\n Example: quget http://news.ycombinator.com ".title > a|bold|red" -limit 5') .option('-o, --outfile <file>', 'file to output to (default: stdout)') .option('-q, --quite', 'quite the logging') .option('-T, --template <template>', 'template "node: {{name}}, text {{.|text}}"') .option('-l, --limit <count>', 'limit query to count matches (-count from bottom)', parseInt, 0) .option('-r, --rand', 'select randomly from matched set (can be combined with --limit)') .option('-j, --json', 'full results object as (pretty) JSON') .option('-c, --compact', 'when used with --json, outputs compact format') .option('-n, --line-number', 'add line numbers to output') .option('- , --stdin', 'read <url>(s) from STDIN') .option('-p, --pause <seconds>', 'pause between batch requests', parseFloat, 0) .option('--sep <seperator>', 'seperator for multiple matches', sanitize, '\n') .option('--tag <tag>', 'enclose complete result in <tag></tag>', '') .option('--request-options <request-options>', 'options for "request" as relaxed JSON, "{foo: bar}"') .version(version) ; // samples require('./samples').init(program); // help topic require('./help')(program); // parse program.parse(process.argv); if (program.done) return; if (program.args.length < 1 && !program.stdin) return console.log(program.helpInformation()); //console.log(program.args); function pause() { var secs = program.pause; return new Promise(function(resolve){ setTimeout(resolve, secs * 1000); }); } if (program.stdin) { const getStdin = require('get-stdin-with-tty'); getStdin.tty = true; getStdin().then(function(urls) { // init output write(true); urls.split(/\r?\n/) .filter(function(url) { return !!url.trim(); }) .map(function(url, index, list) { var sep = url.indexOf(' '), // take selector from stdin if given sel = program.args[0]; if (sep > 0) { sel = url.substr(sep + 1).trim() || sel; url = url.substr(0, sep); } return function(){ if (!program.quite) { console.log(`<<< ${1 + index}/${list.length}:`, url); } return quget .run(url, sel, program) .then(function(res){ write(res); // output as we get results }) .catch(function(err) { write(false); // end tag console.error('\nError - aborting.', err); doneErr(); }); }; }) .reduce(function(next, fn) { return next = next.then(fn).then(pause); }, Promise.resolve()) .then(function() { write(false); // end tag done(); }); }); } else { run(program.args[0], program.args[1] || ''); } // run function run(url, selector) { return quget .run(url, selector, program) .then(write) .then(done) .catch(doneErr); } function getTag(init) { if (!program.tag) return ''; return init ? '<' + program.tag + '>' : '</' + program.tag + '>'; } function write(result) { var init = result === true; var end = result === false; var data = !init && !end; if (data && program.compact) { quget.compactJson(result); // compact only writes to stdout } else { result = data ? result : getTag(result); if (program.outfile) { writeFile(result, init); if (data && !program.quite) { console.log(' > written to:', program.outfile); } } else { console.log(result + program.sep); } } } // atomic write file function writeFile(data, init) { var fd = fs.openSync(program.outfile, init ? 'w' : 'as'); fs.writeSync(fd, Buffer.from(data, 'utf-8') + program.sep); fs.closeSync(fd); } function done(code) { process.exit(code || 0); } function doneErr(code) { done(code || -1); } function sanitize(text) { return text .replace(/\\t/g, '\t') .replace(/\\n/g, '\n') } <file_sep>var chalk = require('chalk'); exports.chalk = chalk; exports.error = function error(text){ return chalk.bold.red(text); }; exports.info = function info(text){ return chalk.bold.green(text); }; <file_sep> module.exports = function(Mark) { Mark.pipes.after = function(str, text){ text = sanitize(text); return str + text; }; Mark.pipes.after.help = 'Insert text after (use \\t & \\n for tab and newline): |after Done.\\n'; Mark.pipes.before = function(str, text){ text = sanitize(text); return text + str; }; Mark.pipes.before.help = 'Insert text before: |before Title\\t'; Mark.pipes.quote = function(str, text){ if (text === 'br') text = '\n'; text = sanitize(text); return text + str + text; }; Mark.pipes.quote.help = 'Surround with text: |quote \\n'; Mark.pipes.tag = function(str, text){ text = sanitize(text); return `<${text}>${str}</${text}>`; }; Mark.pipes.tag.help = 'Enclose with <tag />: |tag foo'; Mark.pipes.incr = function(str, count){ count = count || 1; return Number(str) + count; }; Mark.pipes.incr.help = 'Increment by count (default: 1): |incr 2'; Mark.pipes.decr = function(str, count){ count = count || 1; return Number(str) - count; }; Mark.pipes.decr.help = 'Decrement by count (default: 1): |decr'; Mark.pipes.regex = function(str, regex){ regex = new RegExp(regex); return (str.match(regex) || [])[1]; }; Mark.pipes.regex.help = 'Regular expression match: |regex foo(.*?)bar'; // helper function sanitize(text) { return text .replace(/\\t/g, '\t') .replace(/\\n/g, '\n') } }; <file_sep>/*! * quget -- Get web snippets from the command-line. * * @copyright 2016 https://github.com/moos/quget * @license MIT */ var _ = require('underscore'), request = require('request'), utils = require('./utils'); exports.run = function run(url, selector, options) { var req = { url: url }; // add request options, if any if (options.requestOptions) { var jsonic = require('jsonic'); _.extend(req, jsonic(options.requestOptions)); } return new Promise(function (resolve, reject) { // make request request(req, function (err, response, html) { if (err) { console.error(utils.error(err)); return reject(err); } if (!selector) { return resolve(html); } // parse selector(s) var cheerio = require('cheerio'), Mark = require('markup-js'), reSeperator = /\s*,\s*/, reAttr = /@[\w-_]+/g, reFilter = /\s*\|(?!\=)\s*/, removeFilter = function (sel) { return (sel + ' ').slice(0, sel.search(reFilter)); }, selectors = selector.trim().split(reSeperator), selectorStr = selectors.map(removeFilter).join(',').replace(reAttr, ''), coll = [], linenoTmpl = options.lineNumber ? '{{index|incr}}. ' : '', count, $, results, output; Mark.delimiter = /\s+/; // load html & apply selectors $ = cheerio.load(html); results = $(selectorStr); // init filter pipes require('./pipes.js')(Mark, { $ : $, chalk: utils.chalk }); // apply limit count = results.length; if (options.limit && results.length > options.limit) { count = options.limit; } //console.log('count', count, results.length, options.limit) // rand and limit are applied to selector groups if (options.rand || options.limit) { var grouped = _.chain(results) .toArray() .each(function (item, n) { item.index = n; }) .groupBy('selectorIndex') .filter(function (group, n) { return n !== 'undefined'; }) .value(), // group which has min matches minGroup = _(grouped).sortBy('length')[0], indexList; // apply rand if (options.rand) { // if no limit was given, select 1 at random if (options.limit <= 0) count = 1; indexList = _.chain(minGroup) .pluck('index') // sample based on flat results index .sample(count) .sortBy() .value(); } // apply limit else { var start = count < 0 ? count + minGroup.length : 0, stop = count < 0 ? minGroup.length : count; indexList = _.range(start, stop); } results = $(_ .chain(indexList) .map(function (index) { var groupIndex = options.rand ? _(minGroup).findIndex(function (item) { return item.index === index; }) : index; return _(grouped).reduce(function (prev, item) { prev.push(item[groupIndex]); return prev; }, []); }) .flatten() .compact() .value() ); } // handle json if (options.json) { output = toJSON(Array.from(results), options.compact); return resolve(output); } // parse results results.each(function (index) { // 'this' is the matched node var item = this, tmpl = options.template || templatize(selectors[item.selectorIndex]), $n = '$' + item.selectorIndex, str; // useful for {{if $0}}...{{/if}} predicates. $n is the n-th matched selector (0-based) item[ $n ] = item; item.index = index; str = Mark.up(linenoTmpl + tmpl, item); coll.push(str); }); output = coll.join(options.sep); return resolve(output); }); }); // promise }; // helper function exports.compactJson = function(data) { console.log('%j', data); }; // get template token for attribute (@attr), otherwise uses text node function attrize(attr){ var delim = ' '; // should match Mark.delimiter return !attr ? 'text' : 'attr' + delim + attr.replace('@',''); } // generate a template for selection, e.g., 'div a@href|pack' var templatize = _.memoize(function (sel) { var attr = sel.match(/\@([\w-_]+)/g) || [0], pipes = sel.match(/\|.*$/) || '', tmpl = attr.map(attrize).map(function tokenize(token){ return '{{.|' + token + pipes + '}}'; }).join(' '); //console.log(sel, 'template', tmpl) return tmpl; }); function toJSON(data, deep){ var out = []; data.forEach(function(obj){ // clean up delete obj.next; delete obj.prev; delete obj.parent; if (obj.children) obj.children = toJSON(obj.children, true); out.push(obj); }); return deep ? out : JSON.stringify(out, undefined, 2); }
1894d3c94a0059f84a0d1299526da63b6a1d16c7
[ "JavaScript", "Markdown" ]
8
JavaScript
moos/quget
b5f2ecb6a25d6e7f30d07adf66dd71b89352a6bb
f4e46094995dfffbb1cd937b13fa0b82fee1b376