identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/AloisSeckar/SoftMan/blob/master/src/main/java/elrh/softman/logic/LineupPosition.java
Github Open Source
Open Source
Unlicense
null
SoftMan
AloisSeckar
Java
Code
75
204
package elrh.softman.logic; import elrh.softman.db.orm.PlayerInfo; public class LineupPosition { private PlayerInfo player; private Position position; public LineupPosition(PlayerInfo player, Position position) { this.player = player; this.position = position; } public PlayerInfo getPlayer() { return player; } public void setPlayer(PlayerInfo player) { this.player = player; } public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } @Override public String toString() { return player.toString() + " [" + position + "]"; } }
50,485
https://github.com/zhangxuan666/Lxgw/blob/master/resources/views/Home/Sell.blade.php
Github Open Source
Open Source
MIT
2,019
Lxgw
zhangxuan666
Blade
Code
2,010
13,576
@extends('layout.publics') <!--End Header End--> <!--Begin Menu Begin--> <div class="menu_bg"> <div class="menu"> <!--Begin 商品分类详情 Begin--> <div class="nav"> <div class="nav_t">全部商品分类</div> <div class="leftNav none"> <ul> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav1.png" /></span> <span class="fl">进口食品、生鲜</span> </div> <div class="zj"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav2.png" /></span> <span class="fl">食品、饮料、酒</span> </div> <div class="zj" style="top:-40px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力2</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav3.png" /></span> <span class="fl">母婴、玩具、童装</span> </div> <div class="zj" style="top:-80px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力3</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav4.png" /></span> <span class="fl">家居、家庭清洁、纸品</span> </div> <div class="zj" style="top:-120px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力4</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav5.png" /></span> <span class="fl">美妆、个人护理、洗护</span> </div> <div class="zj" style="top:-160px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力5</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav6.png" /></span> <span class="fl">女装、内衣、中老年</span> </div> <div class="zj" style="top:-200px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力6</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav7.png" /></span> <span class="fl">鞋靴、箱包、腕表配饰</span> </div> <div class="zj" style="top:-240px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力7</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav8.png" /></span> <span class="fl">男装、运动</span> </div> <div class="zj" style="top:-280px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力8</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav9.png" /></span> <span class="fl">手机、小家电、电脑</span> </div> <div class="zj" style="top:-320px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力9</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> <li> <div class="fj"> <span class="n_img"><span></span><img src="images/nav10.png" /></span> <span class="fl">礼品、充值</span> </div> <div class="zj" style="top:-360px;"> <div class="zj_l"> <div class="zj_l_c"> <h2>零食 / 糖果 / 巧克力10</h2> <a href="#">坚果</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">巧克力</a>| <a href="#">口香糖</a>|<a href="#">海苔</a>|<a href="#">鱼干</a>|<a href="#">蜜饯</a>|<a href="#">红枣</a>| <a href="#">蜜饯</a>|<a href="#">红枣</a>|<a href="#">牛肉干</a>|<a href="#">蜜饯</a>| </div> </div> <div class="zj_r"> <a href="#"><img src="images/n_img1.jpg" width="236" height="200" /></a> <a href="#"><img src="images/n_img2.jpg" width="236" height="200" /></a> </div> </div> </li> </ul> </div> </div> <!--End 商品分类详情 End--> <ul class="menu_r"> <li><a href="Index.html">首页</a></li> <li><a href="Food.html">美食</a></li> <li><a href="Fresh.html">生鲜</a></li> <li><a href="HomeDecoration.html">家居</a></li> <li><a href="SuitDress.html">女装</a></li> <li><a href="MakeUp.html">美妆</a></li> <li><a href="Digital.html">数码</a></li> <li><a href="GroupBuying.html">团购</a></li> </ul> <div class="m_ad">中秋送好礼!</div> </div> </div> <!--End Menu End--> <div class="i_bg"> <!--Begin Banner Begin--> <div class="n_ban"> <div class="top_slide_wrap"> <ul class="slide_box bxslider"> <li><a href="#" style="background:url(images/n_ban.jpg) no-repeat center top;">banner1</a></li> <li><a href="#" style="background:url(images/n_ban.jpg) no-repeat center top;">banner2</a></li> <li><a href="#" style="background:url(images/n_ban.jpg) no-repeat center top;">banner3</a></li> </ul> <div class="op_btns clearfix"> <a href="#" class="op_btn op_prev"><span></span></a> <a href="#" class="op_btn op_next"><span></span></a> </div> </div> </div> <script type="text/javascript"> //var jq = jQuery.noConflict(); (function(){ $(".bxslider").bxSlider({ auto:true, prevSelector:jq(".top_slide_wrap .op_prev")[0],nextSelector:jq(".top_slide_wrap .op_next")[0] }); })(); </script> <!--End Banner End--> <div class="content mar_10"> <!--Begin 特卖 Begin--> <div class="s_left"> <div class="brand_t">品牌特卖</div> <ul class="sell_brand"> <li> <div class="con"> <div class="simg"><img src="images/sb1.jpg" width="220" height="100" /></div> <div class="ch_bg"> <span class="ch_txt">先领券再消费</span> <a href="#" class="ch_a">查看</a> </div> 09月12日 — 10月20日 </div> <div class="img"><img src="images/tm1.jpg" width="530" height="190" /></div> </li> <li> <div class="con"> <div class="simg"><img src="images/sb2.jpg" width="220" height="100" /></div> <div class="ch_bg"> <span class="ch_txt">先领券再消费</span> <a href="#" class="ch_a">查看</a> </div> 09月12日 — 10月20日 </div> <div class="img"><img src="images/tm2.jpg" width="530" height="190" /></div> </li> <li> <div class="con"> <div class="simg"><img src="images/sb3.jpg" width="220" height="100" /></div> <div class="ch_bg"> <span class="ch_txt">先领券再消费</span> <a href="#" class="ch_a">查看</a> </div> 09月12日 — 10月20日 </div> <div class="img"><img src="images/tm3.jpg" width="530" height="190" /></div> </li> </ul> <div class="brand_t">商品特卖</div> <ul class="p_sell"> <li> <div class="img"><img src="images/t1.jpg" width="160" height="140" /></div> <div class="name">苹果 Iphone 6S</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>5288</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t2.jpg" width="160" height="140" /></div> <div class="name">登机箱拉杆箱</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>288</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t3.jpg" width="160" height="140" /></div> <div class="name">粉色hp笔记本</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>3899</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t4.jpg" width="160" height="140" /></div> <div class="name">diva少女系香水</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>567</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t1.jpg" width="160" height="140" /></div> <div class="name">苹果 Iphone 6S</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>5288</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t2.jpg" width="160" height="140" /></div> <div class="name">登机箱拉杆箱</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>288</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t3.jpg" width="160" height="140" /></div> <div class="name">粉色hp笔记本</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>3899</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t4.jpg" width="160" height="140" /></div> <div class="name">diva少女系香水</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>567</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t1.jpg" width="160" height="140" /></div> <div class="name">苹果 Iphone 6S</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>5288</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t2.jpg" width="160" height="140" /></div> <div class="name">登机箱拉杆箱</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>288</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t3.jpg" width="160" height="140" /></div> <div class="name">粉色hp笔记本</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>3899</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> <li> <div class="img"><img src="images/t4.jpg" width="160" height="140" /></div> <div class="name">diva少女系香水</div> <div class="price"> <table border="0" style="width:100%; color:#888888;" cellspacing="0" cellpadding="0"> <tr style="font-family:'宋体';"> <td width="33%">市场价 </td> <td width="33%">折扣</td> <td width="33%">为您节省</td> </tr> <tr> <td style="text-decoration:line-through;">¥5388</td> <td>8.0</td> <td>¥100</td> </tr> </table> </div> <div class="ch_bg"> <span class="ch_txt">¥<font>567</font></span> <a href="#" class="ch_a">查看</a> </div> <div class="times">倒计时:1200 时 30 分 28 秒</div> </li> </ul> </div> <!--End 特卖 End--> <div class="s_right"> <div class="sell_ban"> <div id="imgPlays"> <ul class="imgs" id="actors"> <li><a href="#"><img src="images/tm_ban.jpg" width="300" height="352" /></a></li> <li><a href="#"><img src="images/tm_ban.jpg" width="300" height="352" /></a></li> <li><a href="#"><img src="images/tm_ban.jpg" width="300" height="352" /></a></li> </ul> <div class="prev_s">上一张</div> <div class="next_s">下一张</div> </div> </div> <div class="sell_hot"> <div class="s_hot_t"> <span class="fl">热销品牌</span> <span class="h_more fr"><a href="#">更多</a></span> </div> <ul> <li><a href="#"><img src="images/hb_1.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_2.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_3.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_4.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_5.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_6.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_7.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_8.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_9.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_10.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_11.jpg" width="160" height="59" /></a></li> <li><a href="#"><img src="images/hb_12.jpg" width="160" height="59" /></a></li> </ul> </div> <div class="sell_tel"> <table border="0" style="width:280px; margin:15px auto;" cellspacing="0" cellpadding="0"> <tr valign="top"> <td width="170"><img src="images/tm_1.png" /></td> <td> 客服在线时间 <br /> 每天09:00 - 18:00 </td> </tr> <tr valign="top"> <td colspan="2" style="padding-left:58px; padding-top:10px;"> <span style="color:#ff4e00; font-size:20px;">400-123-4567</span><br /> 客服热线(免费长途) </td> </tr> </table> </div> <div class="sell_tel"> <table border="0" style="width:280px; margin:15px auto;" cellspacing="0" cellpadding="0"> <tr valign="top"> <td width="170"><img src="images/tm_2.png" /></td> <td> 享受VIP专属特权 </td> </tr> </table> </div> <div class="sell_tel"> <table border="0" style="width:280px; margin:15px auto;" cellspacing="0" cellpadding="0"> <tr valign="top"> <td width="170"><img src="images/tm_3.png" /></td> <td> 客服在线时间<br /> 每天09:00 - 18:00 </td> </tr> </table> </div> </div> </div> <!--Begin Footer Begin --> <div class="b_btm_bg bg_color"> <div class="b_btm"> <table border="0" style="width:210px; height:62px; float:left; margin-left:75px; margin-top:30px;" cellspacing="0" cellpadding="0"> <tr> <td width="72"><img src="images/b1.png" width="62" height="62" /></td> <td><h2>正品保障</h2>正品行货 放心购买</td> </tr> </table> <table border="0" style="width:210px; height:62px; float:left; margin-left:75px; margin-top:30px;" cellspacing="0" cellpadding="0"> <tr> <td width="72"><img src="images/b2.png" width="62" height="62" /></td> <td><h2>满38包邮</h2>满38包邮 免运费</td> </tr> </table> <table border="0" style="width:210px; height:62px; float:left; margin-left:75px; margin-top:30px;" cellspacing="0" cellpadding="0"> <tr> <td width="72"><img src="images/b3.png" width="62" height="62" /></td> <td><h2>天天低价</h2>天天低价 畅选无忧</td> </tr> </table> <table border="0" style="width:210px; height:62px; float:left; margin-left:75px; margin-top:30px;" cellspacing="0" cellpadding="0"> <tr> <td width="72"><img src="images/b4.png" width="62" height="62" /></td> <td><h2>准时送达</h2>收货时间由你做主</td> </tr> </table> </div> </div> <div class="b_nav"> <dl> <dt><a href="#">新手上路</a></dt> <dd><a href="#">售后流程</a></dd> <dd><a href="#">购物流程</a></dd> <dd><a href="#">订购方式</a></dd> <dd><a href="#">隐私声明</a></dd> <dd><a href="#">推荐分享说明</a></dd> </dl> <dl> <dt><a href="#">配送与支付</a></dt> <dd><a href="#">货到付款区域</a></dd> <dd><a href="#">配送支付查询</a></dd> <dd><a href="#">支付方式说明</a></dd> </dl> <dl> <dt><a href="#">会员中心</a></dt> <dd><a href="#">资金管理</a></dd> <dd><a href="#">我的收藏</a></dd> <dd><a href="#">我的订单</a></dd> </dl> <dl> <dt><a href="#">服务保证</a></dt> <dd><a href="#">退换货原则</a></dd> <dd><a href="#">售后服务保证</a></dd> <dd><a href="#">产品质量保证</a></dd> </dl> <dl> <dt><a href="#">联系我们</a></dt> <dd><a href="#">网站故障报告</a></dd> <dd><a href="#">购物咨询</a></dd> <dd><a href="#">投诉与建议</a></dd> </dl> <div class="b_tel_bg"> <a href="#" class="b_sh1">新浪微博</a> <a href="#" class="b_sh2">腾讯微博</a> <p> 服务热线:<br /> <span>400-123-4567</span> </p> </div> <div class="b_er"> <div class="b_er_c"><img src="images/er.gif" width="118" height="118" /></div> <img src="images/ss.png" /> </div> </div> <div class="btmbg"> <div class="btm"> 备案/许可证编号:蜀ICP备12009302号-1-www.dingguagua.com Copyright © 2015-2018 尤洪商城网 All Rights Reserved. 复制必究 , Technical Support: Dgg Group <br /> <img src="images/b_1.gif" width="98" height="33" /><img src="images/b_2.gif" width="98" height="33" /><img src="images/b_3.gif" width="98" height="33" /><img src="images/b_4.gif" width="98" height="33" /><img src="images/b_5.gif" width="98" height="33" /><img src="images/b_6.gif" width="98" height="33" /> </div> </div> <!--End Footer End --> </div> </body> <!--[if IE 6]> <script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script> <![endif]--> </html>
41,351
https://github.com/coder-zyy/WYnews/blob/master/WYnews/WYnews/Classes/Other/Tools/NetworkTools.swift
Github Open Source
Open Source
MIT
2,021
WYnews
coder-zyy
Swift
Code
118
305
// // NetworkTools.swift // WYnews // // Created by coder_zyy on 2018/5/24. // Copyright © 2018年 coder_zyy. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { class func requestData(URLString : String, type : MethodType, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in // 1.校验是否有结果 /* if let result = response.result.value { finishedCallback(result) } else { print(response.result.error) } */ guard let result = response.result.value else { print("erro = ",response.result.error?.localizedDescription as Any) return } if response.result.isFailure { return } finishedCallback(result) } } }
47,411
https://github.com/udoprog/ptscan/blob/master/crates/ptscan/src/bitset.rs
Github Open Source
Open Source
MIT, Apache-2.0, CC-BY-SA-3.0
2,023
ptscan
udoprog
Rust
Code
172
461
//! A simple, stripped down bitset implementation. #[derive(Clone)] #[repr(transparent)] pub struct BitSet { slots: Vec<u64>, } impl BitSet { const BITS_IN_SLOT: usize = std::mem::size_of::<u64>() * 8; /// Construct a new bitset. pub fn new() -> Self { Self { slots: Vec::new() } } /// Test if the given bit is set. pub fn test(&self, index: usize) -> bool { let slot = index / Self::BITS_IN_SLOT; if let Some(slot) = self.slots.get(slot) { let o = index % Self::BITS_IN_SLOT; 1 & (slot >> o) == 1 } else { false } } /// Set the given bit. pub fn set(&mut self, index: usize) { let slot = index / Self::BITS_IN_SLOT; let offset = index % Self::BITS_IN_SLOT; if self.slots.len() < slot { self.slots .extend(std::iter::repeat(0u64).take(slot - self.slots.len())); } self.slots[slot] |= 1u64 << offset; } /// Clear the given bit. pub fn clear(&mut self, index: usize) { let slot = index / Self::BITS_IN_SLOT; let offset = index % Self::BITS_IN_SLOT; // NB: not set. if self.slots.len() < slot { return; } self.slots[slot] &= !(1u64 << offset); } }
40,873
https://github.com/teknoplop/z88dk/blob/master/libsrc/_DEVELOPMENT/adt/wv_priority_queue/c/sccz80/wv_priority_queue_shrink_to_fit.asm
Github Open Source
Open Source
ClArtistic
2,021
z88dk
teknoplop
Assembly
Code
16
122
; int wv_priority_queue_shrink_to_fit(wv_priority_queue_t *q) SECTION code_clib SECTION code_adt_wv_priority_queue PUBLIC wv_priority_queue_shrink_to_fit EXTERN asm_wv_priority_queue_shrink_to_fit defc wv_priority_queue_shrink_to_fit = asm_wv_priority_queue_shrink_to_fit
27,771
https://github.com/chrismcleod17/newsday-roku/blob/master/components/Content/OmnitureHandler.brs
Github Open Source
Open Source
BSD-2-Clause
null
newsday-roku
chrismcleod17
null
Spoken
504
1,505
' ********** Copyright 2016 Roku Corp. All Rights Reserved. ********** ' init(): OmnitureHandler constructor ' Description: sets the execution function for the UriFetcher ' and tells the UriFetcher to run sub init() print "OmnitureHandler.brs - [init]" ' create the message port m.port = createObject("roMessagePort") ' setting callbacks for url request and response m.top.observeField("request", m.port) m.top.mediaInfo = invalid m.top.finished = false ' setting the task thread function m.top.functionName = "go" m.top.control = "RUN" end sub sub go() print "OmnitureHandler.brs - [go]" ' Holds requests by id m.jobsById = {} ' UriFetcher event loop while true msg = wait(0, m.port) mt = type(msg) print "Received event type '"; mt; "'" ' If a request was made if mt = "roSGNodeEvent" if msg.getField()="request" if handleRequest(msg.getData()) <> true then print "Invalid request" else print "Error: unrecognized field '"; msg.getField() ; "'" end if else print "Error: unrecognized event type '"; mt ; "'" end if end while end sub function handleRequest(request as Object) as Boolean print "OmnitureHandler.brs - [handleRequest]" if type(request) = "roAssociativeArray" context = request.context requestType = context.reqtype screen = context.screen dictionary = context.dictionary 'if requestType = "trackAction" or requestType = "trackState" userid = invalid zipcode = invalid accessLevel = invalid 'add constants dictionary["contentSource"] = "app" 'add content levels levels = dictionary["contentHierarchy"].Split(":") for i=1 to 5 contentLevel = "contentLevel" + i.toStr() if(i < 3) levelindex = 2 else levelindex = i-1 end if if levels[levelindex] <> invalid dictionary[contentLevel] = levels[levelindex] else dictionary[contentLevel] = levels[levels.Count() - 1] end if end for dictionary["contentDirectory"] = levels[levels.Count() - 1] ' last level is contentDirectory 'add user info to dictionary sec = CreateObject("roRegistrySection", "UserInfo") if sec.Exists("UserId") userid = sec.Read("UserId") zipcode = sec.Read("Zipcode") req = CreateObject("roUrlTransfer") req.SetMessagePort(m.port) req.SetUrl("https://www.newsday.com/device/accountservices?serviceType=getSiteAccess&userid=" + userid) rsp = req.GetToString() responseJSON = ParseJSON(rsp) if(responseJSON <> invalid and responseJSON.status <> "fail") accessLevel = responseJSON.accessLevel end if else print "No User Info Stored!" end if if userid <> invalid then dictionary["userAccountId"] = userid if zipcode <> invalid then dictionary["userZip"] = zipcode if accessLevel <> invalid then dictionary["userAccessLevel"] = LCase(accessLevel) 'add device info to dictionary deviceinfo = CreateObject("roDeviceInfo") dictionary["ipAddress"] = deviceInfo.GetIPAddrs() dictionary["deviceId"] = deviceInfo.GetDeviceUniqueId() version=deviceInfo.GetVersion() version_major=mid(version,3,1) version_minor=mid(version,5,2) version_build=mid(version,8,5) if version_minor.toint() < 10 then version_minor=mid(version_minor,2) end if userAgent="Roku/DVP-"+version_major+"."+version_minor+" ("+version+")" dictionary["userAgent"] = userAgent dictionary["bundleId"] = "newsday_roku" dictionary["myAppName"] = "newsday roku tv" 'track request if(requestType = "trackAction") ADBMobile().trackAction(screen, dictionary) else if(requestType = "trackState") ADBMobile().trackState(screen, dictionary) else if requestType = "play" print "play requested" ADBMobile().trackAction("video play", dictionary) else if requestType = "finished" print "finished requested" ADBMobile().trackAction("video finished", dictionary) end if 'else ' mediaContextData = {} ' if(m.top.mediaInfo = invalid) ' ' Create a media info object ' mediaInfo = adb_media_init_mediainfo(dictionary["contentTitle"], dictionary["id"], dictionary["length"], dictionary["streamType"]) ' m.top.mediaInfo = mediaInfo ' ' ' Create context data if any ' ' 'mediaContextData["cmk1"] = "cmv1" ' 'mediaContextData[""cmk2""] = "cmv2" ' ' ADBMobile().mediaTrackLoad(mediaInfo,mediaContextData) ' end if ' else if requestType = "33percent" ' print "33 per requested" ' ADBMobile().mediaTrackEvent("33 Percent", m.top.mediaInfo, mediaContextData) ' else if requestType = "66percent" ' print "66 per requested" ' ADBMobile().mediaTrackEvent("66 Percent", m.top.mediaInfo, mediaContextData) ' end if ' end if end if m.top.finished = true return true end function
44,107
https://github.com/ripxfrostbite/RedirectLauncher/blob/master/RedirectLauncherMk2-WPF/Updaters/ClientUpdater.cs
Github Open Source
Open Source
MIT
2,019
RedirectLauncher
ripxfrostbite
C#
Code
949
3,486
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace RedirectLauncherMk2_WPF.Updater { class ClientUpdater { List<ManifestFile> Files = new List<ManifestFile>(); public Queue<ManifestFile> FilesNeedingUpdate = new Queue<ManifestFile>(); private int TargetVersion = 0; private string DefaultPatchDomain = "https://download2.nexon.net/Game/nxl/games/10200/"; private string AltManifestDomain = "http://aurares.potato.moe/patchdata/objects/"; private Game Client; public String lastError; private DirectoryInfo updateDirectory; private DirectoryInfo updateExtractDirectory; private MainWindow LauncherWindow; private string appID = Properties.Settings.Default.AppID; public ClientUpdater(Game Client, MainWindow LauncherWindow) { this.Client = Client; this.LauncherWindow = LauncherWindow; updateDirectory = new DirectoryInfo(System.Environment.CurrentDirectory + "\\rdlauncherMabiUpdaterTemp"); updateExtractDirectory = new DirectoryInfo(updateDirectory.FullName + "\\extracted"); } private void initDirectories() { if (!updateDirectory.Exists) updateDirectory.Create(); if (!updateExtractDirectory.Exists) updateExtractDirectory.Create(); } public async Task<bool> loadManifestForVersion(int Version, string patchDomain, String mainVersionHash, String manifestHashLocation) { if(patchDomain!=null) this.DefaultPatchDomain = patchDomain; return await Task.Run(() => { prepareUpdater(); using (var dl = new WebClient()) { try { if (manifestHashLocation != null) { //Get manifest hash location from NX API dl.DownloadFile(manifestHashLocation, updateDirectory.FullName + "\\manifest.hash"); dl.DownloadFile(DefaultPatchDomain + File.ReadAllText(updateDirectory.FullName + "\\manifest.hash"), updateDirectory.FullName + "\\update.manifest"); } else { //Get manifest hash location from Alt source dl.DownloadFile(AltManifestDomain + Version + "R.manifest.hash", updateDirectory.FullName + "\\manifest.hash"); dl.DownloadFile(AltManifestDomain + File.ReadAllText(updateDirectory.FullName + "\\manifest.hash"), updateDirectory.FullName + "\\update.manifest"); } } catch (WebException e) { if (((HttpWebResponse)e.Response).StatusCode.Equals(HttpStatusCode.NotFound)) { lastError = "It seems that we couldn't get the manifest for version " + Version + " please try later..."; return false; } } } //Got the manifest, process it. MemoryStream ms = new MemoryStream(File.ReadAllBytes(updateDirectory.FullName + "\\update.manifest")); ms.ReadByte(); ms.ReadByte(); DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress); String manifestJson = new StreamReader(df, Encoding.UTF8).ReadToEnd(); File.WriteAllText(updateDirectory + "\\deserialized.json", manifestJson); dynamic json = JsonConvert.DeserializeObject<dynamic>(manifestJson); bool noBase64 = false; try { noBase64 = ((JObject)json).GetValue("NoBase64").ToObject<bool>(); } catch (NullReferenceException) { } foreach (JProperty prop in ((JObject)json.files).Children()) { Files.Add(new ManifestFile(prop.Name, prop.Value["fsize"].ToObject<long>(), prop.Value["mtime"].ToObject<long>(), prop.Value["objects"].ToObject<List<String>>(), prop.Value["objects_fsize"].ToObject<List<String>>(), noBase64)); } if (Files.Count > 0) { Console.WriteLine("Manifest loaded with " + Files.Count + " files"); return true; } else { LauncherWindow.displayAlertDialog("Update Failed!", "Looks like something was weird with the manifest for version " + Version + ", it returned no files! Please try again later..."); return false; } }); } public async Task getInstallDiff(IProgress<int> progress) { await Task.Run(() => { int currentManifestObject = 0; //Check if file is valid foreach (ManifestFile file in Files) { currentManifestObject++; progress.Report(Convert.ToInt32((Convert.ToDouble(currentManifestObject) / Convert.ToDouble(Files.Count)) * 100.0)); string filePath = LauncherWindow.settings.clientInstallDirectory + "\\" + file.name; if (file.fileParts.Count > 0 && file.fileParts[0].Equals("__DIR__")) continue; FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { if (file.fileParts.Count == 1) { using (FileStream stream = fileInfo.OpenRead()) { //Valid hash SHA1Managed sha = new SHA1Managed(); byte[] hash = sha.ComputeHash(stream); string computedHash = BitConverter.ToString(hash).Replace("-", String.Empty).ToLower(); if (file.fileParts[0].Equals(computedHash)) continue; } } else { //Not modified if (fileInfo.Length == file.fileSize && fileInfo.LastWriteTimeUtc.Equals(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(file.buildDate))) continue; } } FilesNeedingUpdate.Enqueue(file); } }); Console.WriteLine("Total files needing download " + FilesNeedingUpdate.Count); } public async Task<bool> startUpdate(IProgress<int> progress, IProgress<String> status) { return await Task.Run(() => { int filesDone = 0; bool failedDownload = false; foreach(var file in FilesNeedingUpdate) { filesDone++; int failCount = 0; String filepath = Path.GetDirectoryName(updateExtractDirectory + "\\" + file.name); if(!Directory.Exists(filepath)) Directory.CreateDirectory(filepath); using (var fileOut = new FileStream(updateExtractDirectory + "\\" + file.name, FileMode.Create, FileAccess.Write)) { foreach (var obj in file.fileParts) { status.Report("Downloading Files (" + filesDone + " of " + FilesNeedingUpdate.Count + ") (" + file.fileParts.IndexOf(obj) + " parts of " + file.fileParts.Count + ")"); progress.Report(Convert.ToInt32((((Convert.ToDouble(file.fileParts.IndexOf(obj))+1.0) / Convert.ToDouble(file.fileParts.Count)) * 100))); failCount = 0; byte[] objGood = null; while (objGood == null && failCount <= 5) { failCount++; objGood = downloadFromServerAsync(progress, obj, file.name, file.filePartsSizes[file.fileParts.IndexOf(obj)]); if (objGood != null) { //Write data to file fileOut.Write(objGood, 0, objGood.Length); } } if (failCount > 5) { failedDownload = true; LauncherWindow.displayAlertDialog("Update Failed!", "A file could not be downloaded correctly, please try again later!"); break; } } fileOut.Flush(); fileOut.Close(); if (failCount > 5) { failedDownload = true; break; } } File.SetLastWriteTime(updateExtractDirectory + "\\" + file.name, new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(file.buildDate)); } if (!failedDownload) { status.Report("Moving updated data to install directory."); //Stage 2 - Commit update and set version int fileTransferred = 0; foreach (DirectoryInfo dir in updateExtractDirectory.GetDirectories("*", SearchOption.AllDirectories)) Directory.CreateDirectory(dir.FullName.Replace(updateExtractDirectory.FullName, Client.settings.clientInstallDirectory + "\\")); FileInfo[] files = updateExtractDirectory.GetFiles("*", SearchOption.AllDirectories); foreach (FileInfo file in files) { file.CopyTo(Path.Combine(Client.settings.clientInstallDirectory, file.FullName.Replace(updateExtractDirectory.FullName + "\\", "")), true); fileTransferred++; progress.Report(Convert.ToInt32(((Convert.ToDouble(fileTransferred) / Convert.ToDouble(files.Length)) * 100))); file.Delete(); } } return !failedDownload; }); } private byte[] downloadFromServerAsync(IProgress<int> progress, String file, String fileName, String expectedSize) { WebClient client = new WebClient(); Console.WriteLine("Downloading file from " + DefaultPatchDomain + appID + "/" + file.Substring(0, 2) + "/" + file); MemoryStream ms = new MemoryStream(client.DownloadData(DefaultPatchDomain + appID + "/" + file.Substring(0, 2) + "/" + file)); MemoryStream msCopy = new MemoryStream(); //Gross work around to the stream going out of position ms.CopyTo(msCopy); ms.Position = 0; msCopy.Position = 0; ms.ReadByte(); ms.ReadByte(); msCopy.ReadByte(); msCopy.ReadByte(); DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress); DeflateStream dfCopy = new DeflateStream(msCopy, CompressionMode.Decompress); //Valid hash SHA1Managed sha = new SHA1Managed(); byte[] hash = sha.ComputeHash(df); string computedHash = BitConverter.ToString(hash).Replace("-", String.Empty).ToLower(); byte[] result = null; if (file.Equals(computedHash)) { Console.WriteLine("File verified! " + file + " = " + computedHash); MemoryStream msOut = new MemoryStream(); var buffer = new byte[4096]; int read; while ((read = dfCopy.Read(buffer, 0, buffer.Length)) > 0) { msOut.Write(buffer, 0, read); } msOut.Flush(); result = msOut.ToArray(); msOut.Close(); } else { Console.WriteLine("File mismatch! " + file + " = " + computedHash); } df.Close(); ms.Close(); return result; } private void prepareUpdater() { if (updateDirectory.Exists == true) { updateDirectory.Delete(true); updateDirectory.Create(); updateExtractDirectory.Create(); } else { updateDirectory.Create(); updateExtractDirectory.Create(); } Files.Clear(); FilesNeedingUpdate.Clear(); } } class ManifestFile { public String name; public long fileSize; public long buildDate; //I think? public List<String> fileParts; public List<String> filePartsSizes; public ManifestFile(String name, long fileSize, long buildDate, List<String> fileParts, List<String> filePartsSizes, bool noBase64) { if (!noBase64) { byte[] data = Convert.FromBase64String(name); this.name = Encoding.Unicode.GetString(data).Substring(1); } else { this.name = name; } this.fileSize = fileSize; this.buildDate = buildDate; this.fileParts = fileParts; this.filePartsSizes = filePartsSizes; } } }
25,584
https://github.com/paulscottrobson/elf-replica/blob/master/Assembler/door.asm
Github Open Source
Open Source
MIT
null
elf-replica
paulscottrobson
Assembly
Code
243
637
; ************************************************************************************************************ ; ************************************************************************************************************ ; ; Door opening ; ; Uses RE,RF ; ************************************************************************************************************ ; ************************************************************************************************************ DoorOpen: plo re ; save door position. plo rf ; ready to mask it at rf ani 4 ; 0 for left, 4 for right. bz __DOLeftMask ldi 081h __DOLeftMask: ; 0 for left $81 for right xri 080h ; now $80 for left $01 for right phi re ; save in re.H ldi Buffer/256 ; finish setting up rf phi rf sex rf __DOMask: ghi re ; get mask and ; and into screen. str rf str rf glo rf ; next line adi 8 plo rf shl bnf __DOMask ; until done half the screen sex r2 ; X points to stack. glo re ; get door position ani 4 ; 0 if left 4 if right bz __DONotRight ldi 7 __DONotRight: ; 0 if left 7 if right str r2 ; save at TOS. glo re ; XOR with door position. xor ; so now D is distance in from edge. xri 3 ; now distance from the middle. shl ; up four positions per depth. shl bz __DONoAdjust ; -1 position smi 1 __DONoAdjust: shl ; multiply by 8 so index into Row shl shl str r2 ; save at R(X) glo re ; get door position adi 15*8 ; put half way down sm ; subtract offset plo rf ldi 0FFh ; put a solid bar there. str rf return br DoorOpen
28,914
https://github.com/PandaWzg/imking-ecology/blob/master/common/models/common/SmsLog.php
Github Open Source
Open Source
Apache-2.0
2,020
imking-ecology
PandaWzg
PHP
Code
269
918
<?php namespace common\models\common; use Yii; use common\behaviors\MerchantBehavior; /** * This is the model class for table "{{%common_sms_log}}". * * @property int $id * @property string $merchant_id 商户id * @property string $member_id 用户id * @property string $mobile 手机号码 * @property string $code 验证码 * @property string $content 内容 * @property int $error_code 报错code * @property string $error_msg 报错信息 * @property string $error_data 报错日志 * @property string $usage 用途 * @property int $used 是否使用[0:未使用;1:已使用] * @property int $use_time 使用时间 * @property int $status 状态(-1:已删除,0:禁用,1:正常) * @property string $created_at 创建时间 * @property string $updated_at 修改时间 */ class SmsLog extends \common\models\base\BaseModel { use MerchantBehavior; const USAGE_LOGIN = 'login'; const USAGE_REGISTER = 'register'; const USAGE_UP_PWD = 'up-pwd'; /** * @var array */ public static $usageExplain = [ self::USAGE_LOGIN => '登录', self::USAGE_REGISTER => '注册', self::USAGE_UP_PWD => '重置密码', ]; /** * {@inheritdoc} */ public static function tableName() { return '{{%common_sms_log}}'; } /** * {@inheritdoc} */ public function rules() { return [ [['merchant_id', 'member_id', 'error_code', 'used', 'mobile', 'code', 'use_time', 'ip', 'status', 'created_at', 'updated_at'], 'integer'], [['error_data'], 'string'], [['usage'], 'string', 'max' => 20], [['content'], 'string', 'max' => 500], [['error_msg'], 'string', 'max' => 200], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'merchant_id' => '商户', 'member_id' => '用户', 'mobile' => '手机号码', 'code' => '验证码', 'content' => '内容', 'error_code' => '状态Code', 'error_msg' => '状态说明', 'error_data' => '具体信息', 'usage' => '用途', 'used' => '是否使用', 'use_time' => '使用时间', 'ip' => 'ip', 'status' => '状态', 'created_at' => '创建时间', 'updated_at' => '修改时间', ]; } /** * @param bool $insert * @return bool */ public function beforeSave($insert) { if ($this->isNewRecord) { $this->ip = ip2long(Yii::$app->request->userIP); } return parent::beforeSave($insert); } }
44,868
https://github.com/stuart-xyz/knative-gcp/blob/master/pkg/reconciler/trigger/trigger_test.go
Github Open Source
Open Source
Apache-2.0
null
knative-gcp
stuart-xyz
Go
Code
1,840
10,145
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package trigger import ( "context" "fmt" "testing" "time" "cloud.google.com/go/pubsub" "cloud.google.com/go/pubsub/pstest" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" clientgotesting "k8s.io/client-go/testing" eventingduckv1beta1 "knative.dev/eventing/pkg/apis/duck/v1beta1" "knative.dev/eventing/pkg/duck" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/client/injection/ducks/duck/v1/addressable" "knative.dev/pkg/client/injection/ducks/duck/v1/source" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" . "knative.dev/pkg/reconciler/testing" "knative.dev/pkg/resolver" brokerv1beta1 "github.com/google/knative-gcp/pkg/apis/broker/v1beta1" "github.com/google/knative-gcp/pkg/apis/configs/dataresidency" "github.com/google/knative-gcp/pkg/client/injection/ducks/duck/v1alpha1/resource" triggerreconciler "github.com/google/knative-gcp/pkg/client/injection/reconciler/broker/v1beta1/trigger" "github.com/google/knative-gcp/pkg/reconciler" . "github.com/google/knative-gcp/pkg/reconciler/testing" ) const ( testNS = "testnamespace" triggerName = "test-trigger" brokerName = "test-broker" testUID = "abc123" testProject = "test-project-id" subscriberURI = "http://example.com/subscriber/" subscriberKind = "Service" subscriberName = "subscriber-name" subscriberGroup = "serving.knative.dev" subscriberVersion = "v1" ) var ( backoffPolicy = eventingduckv1beta1.BackoffPolicyLinear backoffDelay = "PT5S" deadLetterTopicID = "test-dead-letter-topic-id" retry int32 = 3 testKey = fmt.Sprintf("%s/%s", testNS, triggerName) triggerFinalizerUpdatedEvent = Eventf(corev1.EventTypeNormal, "FinalizerUpdate", `Updated "test-trigger" finalizers`) triggerReconciledEvent = Eventf(corev1.EventTypeNormal, "TriggerReconciled", `Trigger reconciled: "testnamespace/test-trigger"`) triggerFinalizedEvent = Eventf(corev1.EventTypeNormal, "TriggerFinalized", `Trigger finalized: "testnamespace/test-trigger"`) topicCreatedEvent = Eventf(corev1.EventTypeNormal, "TopicCreated", `Created PubSub topic "cre-tgr_testnamespace_test-trigger_abc123"`) topicDeletedEvent = Eventf(corev1.EventTypeNormal, "TopicDeleted", `Deleted PubSub topic "cre-tgr_testnamespace_test-trigger_abc123"`) deadLetterTopicCreatedEvent = Eventf(corev1.EventTypeNormal, "TopicCreated", `Created PubSub topic "test-dead-letter-topic-id"`) subscriptionCreatedEvent = Eventf(corev1.EventTypeNormal, "SubscriptionCreated", `Created PubSub subscription "cre-tgr_testnamespace_test-trigger_abc123"`) subscriptionDeletedEvent = Eventf(corev1.EventTypeNormal, "SubscriptionDeleted", `Deleted PubSub subscription "cre-tgr_testnamespace_test-trigger_abc123"`) subscriptionConfigUpdatedEvent = Eventf(corev1.EventTypeNormal, "SubscriptionConfigUpdated", `Updated config for PubSub subscription "cre-tgr_testnamespace_test-trigger_abc123"`) subscriberAPIVersion = fmt.Sprintf("%s/%s", subscriberGroup, subscriberVersion) subscriberGVK = metav1.GroupVersionKind{ Group: subscriberGroup, Version: subscriberVersion, Kind: subscriberKind, } brokerDeliverySpec = &eventingduckv1beta1.DeliverySpec{ BackoffDelay: &backoffDelay, BackoffPolicy: &backoffPolicy, Retry: &retry, DeadLetterSink: &duckv1.Destination{ URI: &apis.URL{ Scheme: "pubsub", Host: deadLetterTopicID, }, }, } brokerDeliverySpecWithoutRetry = &eventingduckv1beta1.DeliverySpec{ BackoffDelay: &backoffDelay, BackoffPolicy: &backoffPolicy, DeadLetterSink: &duckv1.Destination{ URI: &apis.URL{ Scheme: "pubsub", Host: deadLetterTopicID, }, }, } ) func init() { // Add types to scheme _ = brokerv1beta1.AddToScheme(scheme.Scheme) } func TestAllCasesTrigger(t *testing.T) { table := TableTest{ { Name: "bad workqueue key", Key: "too/many/parts", }, { Name: "key not found", Key: testKey, }, { Name: "Trigger with finalizer is being deleted, no topic or sub exists", Key: testKey, Objects: []runtime.Object{ NewTrigger(triggerName, testNS, brokerName, WithTriggerDeletionTimestamp, WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults), }, WantEvents: []string{ triggerFinalizerUpdatedEvent, triggerFinalizedEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchRemoveFinalizers(testNS, triggerName), }, OtherTestData: map[string]interface{}{}, PostConditions: []func(*testing.T, *TableRow){ NoTopicsExist(), NoSubscriptionsExist(), }, }, { // The finalization logic should be skipped since there is no finalizer string. Name: "Trigger without finalizer is being deleted, no topic or sub exists", Key: testKey, Objects: []runtime.Object{ NewTrigger(triggerName, testNS, brokerName, WithTriggerDeletionTimestamp, WithTriggerSetDefaults), }, }, { Name: "Trigger is being deleted, topic and sub exists", Key: testKey, Objects: []runtime.Object{ NewTrigger(triggerName, testNS, brokerName, WithTriggerDeletionTimestamp, WithTriggerUID(testUID), WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults), }, WantEvents: []string{ topicDeletedEvent, subscriptionDeletedEvent, triggerFinalizerUpdatedEvent, triggerFinalizedEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchRemoveFinalizers(testNS, triggerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ TopicAndSub("cre-tgr_testnamespace_test-trigger_abc123", "cre-tgr_testnamespace_test-trigger_abc123"), }, }, PostConditions: []func(*testing.T, *TableRow){ NoTopicsExist(), NoSubscriptionsExist(), }, }, { Name: "Broker not found, Trigger with finalizer should be finalized", Key: testKey, Objects: []runtime.Object{ NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults, WithInitTriggerConditions, ), }, WantEvents: []string{ topicDeletedEvent, subscriptionDeletedEvent, triggerFinalizedEvent, }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ TopicAndSub("cre-tgr_testnamespace_test-trigger_abc123", "cre-tgr_testnamespace_test-trigger_abc123"), }, }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults, WithInitTriggerConditions, WithTriggerBrokerFailed("BrokerDoesNotExist", "Broker test-broker does not exist"), ), }}, }, { Name: "Broker is being deleted, Trigger with finalizer should be finalized", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerDeletionTimestamp, WithBrokerSetDefaults, ), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults, WithInitTriggerConditions, ), }, WantEvents: []string{ topicDeletedEvent, subscriptionDeletedEvent, triggerFinalizedEvent, }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ TopicAndSub("cre-tgr_testnamespace_test-trigger_abc123", "cre-tgr_testnamespace_test-trigger_abc123"), }, }, }, { Name: "Switched to other brokerclass, Trigger with finalizer should be finalized", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass("some-other-brokerclass"), WithBrokerSetDefaults, ), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults, WithInitTriggerConditions, ), }, WantEvents: []string{ topicDeletedEvent, subscriptionDeletedEvent, triggerFinalizedEvent, }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ TopicAndSub("cre-tgr_testnamespace_test-trigger_abc123", "cre-tgr_testnamespace_test-trigger_abc123"), }, }, // This WantStatusUpdates should be deleted once the following TODO is finished. // TODO(https://github.com/knative/pkg/issues/1149) Add a FilterKind to genreconciler so it will // skip a trigger if it's not pointed to a gcp broker and doesn't have googlecloud finalizer string. WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerFinalizers(finalizerName), WithTriggerSetDefaults, WithInitTriggerConditions, WithTriggerTopicReady, WithTriggerSubscriptionReady, ), }}, }, { Name: "Broker is not ready", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerDeliverySpec(brokerDeliverySpec), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerUnknown("Broker/", ""), WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerDependencyReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, topicCreatedEvent, subscriptionCreatedEvent, triggerReconciledEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{}, PostConditions: []func(*testing.T, *TableRow){ OnlyTopics("cre-tgr_testnamespace_test-trigger_abc123"), OnlySubscriptions("cre-tgr_testnamespace_test-trigger_abc123"), SubscriptionHasRetryPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.RetryPolicy{ MaximumBackoff: 5 * time.Second, MinimumBackoff: 5 * time.Second, }), }, }, { Name: "Subsciber doesn't exist", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerSetDefaults), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithInitTriggerConditions, WithTriggerBrokerReady, WithTriggerSubscriberResolvedFailed("Unable to get the Subscriber's URI", `services.serving.knative.dev "subscriber-name" not found`), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, Eventf(corev1.EventTypeWarning, "InternalError", `services.serving.knative.dev "subscriber-name" not found`), }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, WantErr: true, }, { Name: "Trigger created, broker ready, subscriber is addressable", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerDeliverySpec(brokerDeliverySpec), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerReady, WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerDependencyReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, topicCreatedEvent, subscriptionCreatedEvent, triggerReconciledEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ Topic("test-dead-letter-topic-id"), }, }, PostConditions: []func(*testing.T, *TableRow){ OnlyTopics("cre-tgr_testnamespace_test-trigger_abc123", "test-dead-letter-topic-id"), OnlySubscriptions("cre-tgr_testnamespace_test-trigger_abc123"), SubscriptionHasRetryPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.RetryPolicy{ MaximumBackoff: 5 * time.Second, MinimumBackoff: 5 * time.Second, }), SubscriptionHasDeadLetterPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.DeadLetterPolicy{ MaxDeliveryAttempts: 3, DeadLetterTopic: "projects/test-project-id/topics/test-dead-letter-topic-id", }), TopicExistsWithConfig("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.TopicConfig{ Labels: map[string]string{ "name": "test-trigger", "namespace": "testnamespace", "resource": "triggers", }, }), }, }, { Name: "Sub already exists, update config", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerDeliverySpec(brokerDeliverySpec), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerReady, WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerDependencyReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, subscriptionConfigUpdatedEvent, triggerReconciledEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ TopicAndSub("cre-tgr_testnamespace_test-trigger_abc123", "cre-tgr_testnamespace_test-trigger_abc123"), Topic("test-dead-letter-topic-id"), }, }, PostConditions: []func(*testing.T, *TableRow){ OnlyTopics("cre-tgr_testnamespace_test-trigger_abc123", "test-dead-letter-topic-id"), OnlySubscriptions("cre-tgr_testnamespace_test-trigger_abc123"), SubscriptionHasRetryPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.RetryPolicy{ MaximumBackoff: 5 * time.Second, MinimumBackoff: 5 * time.Second, }), SubscriptionHasDeadLetterPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.DeadLetterPolicy{ MaxDeliveryAttempts: 3, DeadLetterTopic: "projects/test-project-id/topics/test-dead-letter-topic-id", }), }, }, { Name: "Check topic config and labels - broker without spec.delivery.retry", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerDeliverySpec(brokerDeliverySpecWithoutRetry), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerReady, WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerDependencyReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, topicCreatedEvent, subscriptionCreatedEvent, triggerReconciledEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ Topic("test-dead-letter-topic-id"), }, "dataResidencyConfigMap": NewDataresidencyConfigMapFromRegions([]string{"us-east1"}), }, PostConditions: []func(*testing.T, *TableRow){ OnlyTopics("cre-tgr_testnamespace_test-trigger_abc123", "test-dead-letter-topic-id"), OnlySubscriptions("cre-tgr_testnamespace_test-trigger_abc123"), SubscriptionHasRetryPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.RetryPolicy{ MaximumBackoff: 5 * time.Second, MinimumBackoff: 5 * time.Second, }), SubscriptionHasDeadLetterPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.DeadLetterPolicy{ DeadLetterTopic: "projects/test-project-id/topics/test-dead-letter-topic-id", }), TopicExistsWithConfig("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.TopicConfig{ MessageStoragePolicy: pubsub.MessageStoragePolicy{ AllowedPersistenceRegions: []string{"us-east1"}, }, Labels: map[string]string{ "name": "test-trigger", "namespace": "testnamespace", "resource": "triggers", }, }), }, }, { Name: "Check topic config and labels", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerDeliverySpec(brokerDeliverySpec), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerReady, WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerDependencyReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, topicCreatedEvent, subscriptionCreatedEvent, triggerReconciledEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ Topic("test-dead-letter-topic-id"), }, "dataResidencyConfigMap": NewDataresidencyConfigMapFromRegions([]string{"us-east1"}), }, PostConditions: []func(*testing.T, *TableRow){ OnlyTopics("cre-tgr_testnamespace_test-trigger_abc123", "test-dead-letter-topic-id"), OnlySubscriptions("cre-tgr_testnamespace_test-trigger_abc123"), SubscriptionHasRetryPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.RetryPolicy{ MaximumBackoff: 5 * time.Second, MinimumBackoff: 5 * time.Second, }), SubscriptionHasDeadLetterPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.DeadLetterPolicy{ MaxDeliveryAttempts: 3, DeadLetterTopic: "projects/test-project-id/topics/test-dead-letter-topic-id", }), TopicExistsWithConfig("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.TopicConfig{ MessageStoragePolicy: pubsub.MessageStoragePolicy{ AllowedPersistenceRegions: []string{"us-east1"}, }, Labels: map[string]string{ "name": "test-trigger", "namespace": "testnamespace", "resource": "triggers", }, }), }, }, { Name: "Trigger created, broker ready, subscriber is addressable, nil pubsub client", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerDeliverySpec(brokerDeliverySpec), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerReady, WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerDependencyReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, topicCreatedEvent, subscriptionCreatedEvent, triggerReconciledEvent, }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ Topic("test-dead-letter-topic-id"), }, // TODO: This should make sure the function is called only once, but currently this case only check the create function // will be called on demand since there is no test that reconcile twice or with both reconcile and delete. "maxPSClientCreateTime": 1, }, PostConditions: []func(*testing.T, *TableRow){ OnlyTopics("cre-tgr_testnamespace_test-trigger_abc123", "test-dead-letter-topic-id"), OnlySubscriptions("cre-tgr_testnamespace_test-trigger_abc123"), SubscriptionHasRetryPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.RetryPolicy{ MaximumBackoff: 5 * time.Second, MinimumBackoff: 5 * time.Second, }), SubscriptionHasDeadLetterPolicy("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.DeadLetterPolicy{ MaxDeliveryAttempts: 3, DeadLetterTopic: "projects/test-project-id/topics/test-dead-letter-topic-id", }), TopicExistsWithConfig("cre-tgr_testnamespace_test-trigger_abc123", &pubsub.TopicConfig{ Labels: map[string]string{ "name": "test-trigger", "namespace": "testnamespace", "resource": "triggers", }, }), }, }, { Name: "Trigger created, broker ready, subscriber is addressable, pubsub client creation fails", Key: testKey, Objects: []runtime.Object{ NewBroker(brokerName, testNS, WithBrokerClass(brokerv1beta1.BrokerClass), WithInitBrokerConditions, WithBrokerReady("url"), WithBrokerDeliverySpec(brokerDeliverySpec), WithBrokerSetDefaults, ), makeSubscriberAddressableAsUnstructured(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerSetDefaults), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(testUID), WithTriggerSubscriberRef(subscriberGVK, subscriberName, testNS), WithTriggerBrokerReady, WithTriggerSubscriptionReady, WithTriggerTopicReady, WithTriggerSubscriberResolvedSucceeded, WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSetDefaults, WithTriggerDependencyUnknown("", ""), WithTriggerTopicUnknown("PubSubClientCreationFailed", "Failed to create Pub/Sub client: Invoke time 0 reaches the max invoke time 0"), WithTriggerSubscriptionUnknown("PubSubClientCreationFailed", "Failed to create Pub/Sub client: Invoke time 0 reaches the max invoke time 0"), ), }}, WantEvents: []string{ triggerFinalizerUpdatedEvent, Eventf(corev1.EventTypeWarning, "InternalError", "Invoke time 0 reaches the max invoke time 0"), }, WantPatches: []clientgotesting.PatchActionImpl{ patchFinalizers(testNS, triggerName, finalizerName), }, OtherTestData: map[string]interface{}{ "pre": []PubsubAction{ Topic("test-dead-letter-topic-id"), }, "maxPSClientCreateTime": 0, }, WantErr: true, }, } table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher, testData map[string]interface{}) controller.Reconciler { srv := pstest.NewServer() // Insert pubsub client for PostConditions and create fixtures psclient, _ := GetTestClientCreateFunc(srv.Addr)(ctx, testProject) savedCreateFn := createPubsubClientFn close := func() { srv.Close() createPubsubClientFn = savedCreateFn } t.Cleanup(close) var drStore *dataresidency.Store if testData != nil { InjectPubsubClient(testData, psclient) if testData["pre"] != nil { fixtures := testData["pre"].([]PubsubAction) for _, f := range fixtures { f(ctx, t, psclient) } } // If we found "dataResidencyConfigMap" in OtherData, we create a store with the configmap if cm, ok := testData["dataResidencyConfigMap"]; ok { drStore = NewDataresidencyTestStore(t, cm.(*corev1.ConfigMap)) } } // If maxPSClientCreateTime is in testData, no pubsub client is passed to reconciler, the reconciler // will create one in demand testPSClient := psclient if maxTime, ok := testData["maxPSClientCreateTime"]; ok { // Overwrite the createPubsubClientFn to one that failed when called more than maxTime times. // maxTime=0 is used to inject error createPubsubClientFn = GetFailedTestClientCreateFunc(srv.Addr, maxTime.(int)) testPSClient = nil } ctx = addressable.WithDuck(ctx) ctx = resource.WithDuck(ctx) ctx = source.WithDuck(ctx) r := &Reconciler{ Base: reconciler.NewBase(ctx, controllerAgentName, cmw), brokerLister: listers.GetBrokerLister(), sourceTracker: duck.NewListableTracker(ctx, source.Get, func(types.NamespacedName) {}, 0), addressableTracker: duck.NewListableTracker(ctx, addressable.Get, func(types.NamespacedName) {}, 0), uriResolver: resolver.NewURIResolver(ctx, func(types.NamespacedName) {}), projectID: testProject, pubsubClient: testPSClient, dataresidencyStore: drStore, } return triggerreconciler.NewReconciler(ctx, r.Logger, r.RunClientSet, listers.GetTriggerLister(), r.Recorder, r, withAgentAndFinalizer(nil)) })) } func makeSubscriberAddressableAsUnstructured() *unstructured.Unstructured { return &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": subscriberAPIVersion, "kind": subscriberKind, "metadata": map[string]interface{}{ "namespace": testNS, "name": subscriberName, }, "status": map[string]interface{}{ "address": map[string]interface{}{ "url": subscriberURI, }, }, }, } } // TODO Move to a util package so all reconciler tests can use. func patchFinalizers(namespace, name, finalizer string) clientgotesting.PatchActionImpl { action := clientgotesting.PatchActionImpl{} action.Name = name action.Namespace = namespace patch := `{"metadata":{"finalizers":["` + finalizer + `"],"resourceVersion":""}}` action.Patch = []byte(patch) return action } // TODO Move to a util package so all reconciler tests can use. func patchRemoveFinalizers(namespace, name string) clientgotesting.PatchActionImpl { action := clientgotesting.PatchActionImpl{} action.Name = name action.Namespace = namespace patch := `{"metadata":{"finalizers":[],"resourceVersion":""}}` action.Patch = []byte(patch) return action }
21,837
https://github.com/costajvsc/dotimer/blob/master/controllers/door-guards/create.php
Github Open Source
Open Source
MIT
null
dotimer
costajvsc
PHP
Code
36
185
<?php include_once('../../database/DoorGuard.php'); include_once('../../database/DoorGuardDAO.php'); $DAO = new DoorGuardDAO(); $door_guard = new DoorGuard(); $door_guard->setIDDoor($_POST['id_door']); $door_guard->setIDEmploye($_POST['id_employe']); $result = $DAO->create($door_guard); session_start(); if($result) $_SESSION["success"] = "Permission was created with successfully"; else $_SESSION["error"] = "Could not create this permission."; header('Location: http://localhost/dotimer/views/doors/guards.php'); ?>
26,559
https://github.com/icaas/xgboost/blob/master/python-package/conv_rst.py
Github Open Source
Open Source
Apache-2.0
null
xgboost
icaas
Python
Code
24
95
# pylint: disable=invalid-name, exec-used """Convert README.md to README.rst for PyPI""" from pypandoc import convert read_md = convert('python-package/README.md', 'rst') with open('python-package/README.rst', 'w') as rst_file: rst_file.write(read_md)
27,597
https://github.com/faraway030/tongfang-unofficial-control-center/blob/master/main.py
Github Open Source
Open Source
MIT
null
tongfang-unofficial-control-center
faraway030
Python
Code
434
1,625
#!/usr/bin/python3 # main.py import sys import argparse, textwrap from handler import DeviceHandler class Controller(DeviceHandler): def __init__(self, vendor_id, product_id): super(Controller, self).__init__(vendor_id, product_id) brightness_map = { 1: 0x08, 2: 0x16, 3: 0x24, 4: 0x32 } def get_rgb(self, color): colors = { "white": "FFFFFF", "red": "FF0000", "blue": "0000C8", "teal": "0064C8", "green": "006400", "yellow": "FFFF66", "orange": "ff2800", "gold": "ff4600", "cyan": "00FFFF", "pink": "FF00C8", "purple": "8800C8", } color = colors[color] r = int(color[:2],16) g = int(color[2:4],16) b = int(color[-2:],16) return [r, g, b] def setup(self, program=0x01, speed=0x05, brightness=0x32, direction=0x00, save=0x01): # Byte Purpose Notes # 0 ??? 0x08 to issue commands? # 1 ??? 0x02 to issue commands? # 2 Program The 'effect' in use # 3 Speed 0x0?: 1,2,3,4,5,6,7,8,9,a (fastest to slowest) # 4 Brightness 0x08, 0x16, 0x24, 0x32 # 5 ??? 0x08 # 6 Direction 0x0?: 0 for None, 1 for right, 2 for left # 7 save changes (00 for no, 01 for yes) ###################################################################### # Programs: # Name Command Colors required # # Static 0x01 4 # Breathing 0x02 7 # Wave 0x03 7 # Rainbow 0x04 0 # Mix 0x13 7 # Flash 0x12 7 self.ctrl_write(0x08, 0x02, program, speed, brightness, 0x08, direction, save) def set_area(self, area, color): self.rgb = self.get_rgb(color) self.ctrl_write(0x14, 0x00, area, self.rgb[0], self.rgb[1], self.rgb[2], 0x00, 0x00) def set_brightness(self, brightness=None): if brightness: self.ctrl_write(0x08, 0x02, 0x01, 0x05, self.brightness_map[brightness], 0x08, 0x00, 0x00) else: self.set_brightness(4) def send_end(self): self.ctrl_write(0x14, 0x00, 0x05, 0x00, 0x00, 0xc8, 0x00, 0x00) self.ctrl_write(0x14, 0x00, 0x06, 0x00, 0x64, 0xc8, 0x00, 0x00) self.ctrl_write(0x14, 0x00, 0x07, 0x00, 0x64, 0x00, 0x00, 0x00) self.ctrl_write(0x08, 0x02, 0x01, 0x05, 0x32, 0x08, 0x00, 0x00) def set_mono_color(self, color): for i in range(1,5,1): self.set_area(i,color) def main(): control = Controller(vendor_id=0x048d, product_id=0xce00) parser = argparse.ArgumentParser( description=textwrap.dedent(''' Supply at least one of the options [-a|-c|-b|-d]. Colors available: [red|green|blue|teal|pink|purple|white|yellow|orange|olive|maroon|brown|gray|skyblue|navy|crimson|darkgreen|lightgreen|gold|violet] '''), formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-a', '--area', help='Select an area. (1-4)', type=int, choices=range(1,5)) parser.add_argument( '-c', '--color', help='Select a color for a specific area or all keys.') parser.add_argument( '-b', '--brightness', help='Set brightness, 1 is minimum, 4 is maximum.', type=int, choices=range(1, 5)) #parser.add_argument('-s', '--style', # help='One of (rainbow, marquee, wave, raindrop, aurora, random, reactive, breathing, ripple, reactiveripple, reactiveaurora, fireworks). Additional single colors are available for the following styles: raindrop, aurora, random, reactive, breathing, ripple, reactiveripple, reactiveaurora and fireworks. These colors are: Red (r), Orange (o), Yellow (y), Green (g), Blue (b), Teal (t), Purple (p). Append those styles with the start letter of the color you would like (e.g. rippler = Ripple Red') parser.add_argument('-d', '--disable', action='store_true', help='Turn keyboard backlight off'), parsed = parser.parse_args() if parsed.disable: control.disable_keyboard() else : if parsed.color: if parsed.area: control.set_area(parsed.area, parsed.color) else: control.set_mono_color(parsed.color) if parsed.brightness: control.set_brightness(parsed.brightness) else : pass #print("Invalid or absent command") sys.exit(1) if __name__ == "__main__": main()
29,943
https://github.com/ke-sasso/serviciosgenerales/blob/master/resources/views/layouts/top-nav.blade.php
Github Open Source
Open Source
MIT
null
serviciosgenerales
ke-sasso
PHP
Code
115
456
<!-- BEGIN TOP NAV --> <div class="top-navbar {{ (Session::get('cfgHideMenu',false))?'toggle':'' }}"> <div class="top-navbar-inner"> <!-- Begin Logo brand --> <div class="logo-brand success-color"> <a>{!! Html::image('img/logo.png') !!}</a> </div><!-- /.logo-brand --> <!-- End Logo brand --> <div class="top-nav-content"> <!-- Begin button sidebar left toggle --> <div class="btn-collapse-sidebar-left"> <i class="fa fa-long-arrow-right icon-dinamic {{ (Session::get('cfgHideMenu',false))?'rotate-180':'' }}" onclick="changeConfigMenu()"></i> </div><!-- /.btn-collapse-sidebar-left --> <!-- End button sidebar left toggle --> </div><!-- /.top-nav-content --> <!-- Begin user session nav --> <ul class="nav-user navbar-right"> <li class="dropdown"> <a href="#fakelink" class="dropdown-toggle" data-toggle="dropdown"> Hola, <strong>{{ Auth::user()->nombresUsuario.' '.Auth::user()->apellidosUsuario }}</strong> </a> <ul class="dropdown-menu square primary margin-list-rounded with-triangle"> <li><a href="{{ url('/logout') }}">Cerrar Sesión</a></li> </ul> </li> </ul> <!-- End user session nav --> </div><!-- /.top-navbar-inner --> </div><!-- /.top-navbar --> <!-- END TOP NAV -->
6,795
https://github.com/hankaibo/mydnd/blob/master/src/pages/dnd/components/SourceContainer.js
Github Open Source
Open Source
MIT
null
mydnd
hankaibo
JavaScript
Code
92
287
import React from 'react'; import { Collapse } from 'antd'; import { connect } from 'umi'; import SourceWrap from './SourceWrap'; const { Panel } = Collapse; const SourceContainer = connect(({ dnd: { sourceDnDComponentList } }) => ({ sourceDnDComponentList, }))(({ sourceDnDComponentList }) => { const recursion = (dataSource) => { return dataSource.map((collapse, index) => { if (collapse.subCollapse) { return <Collapse defaultActiveKey={index}>{recursion(collapse.subCollapse)}</Collapse>; } return ( <Panel header={collapse.title} key={collapse.id}> <div style={{ display: 'flex', flexWrap: 'wrap' }}> {collapse.children.map((item) => ( <SourceWrap key={item.id} item={item} /> ))} </div> </Panel> ); }); }; return <Collapse>{recursion(sourceDnDComponentList)}</Collapse>; }); export default SourceContainer;
19,068
https://github.com/Kunstmaan/KunstmaanBundlesCMS/blob/master/src/Kunstmaan/AdminBundle/Repository/UserRepository.php
Github Open Source
Open Source
MIT
2,023
KunstmaanBundlesCMS
Kunstmaan
PHP
Code
102
402
<?php namespace Kunstmaan\AdminBundle\Repository; use Doctrine\ORM\EntityRepository; use Kunstmaan\AdminBundle\Entity\User; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; /** * UserRepository */ class UserRepository extends EntityRepository implements PasswordUpgraderInterface { /** * Get user(s) that have the specified role(s) * * @param string|array $role The role(s) for which you want to retrieve the users * * @return array */ public function getUsersByRole($role) { if (\is_array($role)) { $roles = $role; } else { $roles = [$role]; } $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('u') ->from(User::class, 'u') ->innerJoin('u.groups', 'g') ->innerJoin('g.roles', 'r') ->where('u.enabled= :enabled') ->andWhere('r.role IN (:roles)') ->setParameter('roles', $roles) ->setParameter('enabled', true); return $qb->getQuery()->getResult(); } public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newEncodedPassword): void { $user->setPassword($newEncodedPassword); $this->getEntityManager()->flush(); } }
15,106
https://github.com/Aryo-Patel/Axotl/blob/master/client/src/actions/companies.js
Github Open Source
Open Source
MIT
2,021
Axotl
Aryo-Patel
JavaScript
Code
116
369
import axios from 'axios' import { GET_COMPANIES, GET_COMPANY, COMPANY_ERROR, CHANGE_DISPLAYED_COMPANIES} from './Types' export const getCompanies = (pageNumber) => async dispatch => { try { const res = await axios.get(`/api/profiles/sponsor/${pageNumber}`) dispatch({ type: GET_COMPANIES, payload: res.data }) } catch (err) { console.error(err.message) dispatch({ type: COMPANY_ERROR }) } } // //get one company's profile for display export const getCompany = (id) => async dispatch => { try { const res = await axios.get(`/api/profiles/sponsor/${id}`) dispatch({ type: GET_COMPANY, payload: res.data }) } catch (err) { console.error(err.message) dispatch({ type: COMPANY_ERROR }) } } export const getDistances = (pageNumber) => async(dispatch) => { try { const response = await axios.get(`/api/profiles/sponsor/search/locations/${pageNumber}`) dispatch({ type: GET_COMPANIES, payload: response.data }) } catch (err) { console.error(err.message) } }
10,658
https://github.com/centrumkanalen/smil-player/blob/master/src/components/playlist/mock/mockBrokenSmil.ts
Github Open Source
Open Source
MIT
null
smil-player
centrumkanalen
TypeScript
Code
410
2,114
export const mockBrokenSmil = { region: { video: { regionName: "video", left: "10", top: "10", width: "1280", height: "720", "z-index": "1", backgroundColor: "#FFFFFF", mediaAlign: "topLeft", region: [{ regionName: "video1", left: "0", top: "0", width: "640", height: "720", "z-index": "1", backgroundColor: "transparent", }, { regionName: "video2", left: "640", top: "0", width: "640", height: "720", "z-index": "1", backgroundColor: "transparent", }], }, widget13: { regionName: "widget13", left: "1280", top: "0", width: "640", height: "506", "z-index": "1", backgroundColor: "transparent", }, widget14: { regionName: "widget14", left: "1280", top: "506", width: "640", height: "574", "z-index": "1", backgroundColor: "transparent", }, }, refresh: 90, rootLayout: { width: "1920", height: "1080", backgroundColor: "#FFFFFF", top: "0", left: "0", }, playlist: { systemComponent: "http://www.w3.org/1999/xhtml", style: "background-color:#FFFFFF", par: { seq: [], par: { begin: "__prefetchEnd.endEvent", repeatCount: "indefinite", excl: { repeatCount: "indefinite", priorityClass: { lower: "never", peer: "stop", higher: "stop", par: { begin: "wallclock(R/2011-01-01T00:00:00/P1D)", end: "wallclock(R/2011-01-01T23:00:00/P1D)", seq: { repeatCount: "indefinite", excl: { begin: "0", repeatCount: "indefinite", priorityClass: { higher: "stop", pauseDisplay: "hide", par: { begin: "0", par: [{ seq: { repeatCount: "1", video1: { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }, video2: { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }, }, }], seq: [{ repeatCount: "indefinite", video3: { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }, video4: { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }, }, { begin: "wallclock(R/2011-01-01T07:00:00/P1D)", end: "wallclock(R/2011-01-01T17:00:00/P1D)", video5: { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }, video6: { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }, }], excl: [], priorityClass: { lower: "never", peer: "stop", higher: "stop", }, }, }, }, }, }, }, }, }, }, }, video: [{ src: "http://butikstv.centrumkanalen.com/play/media/ladd/landscape.mp4", }, { src: "https://signageos-demo.s3.eu-central-1.amazonaws.com/smil/samples/assets/landscape1.mp4", type: "application/widget", region: "video", param: { name: "cacheControl", value: "onlyIfCached", }, }], img: [], ref: [], audio: [], intro: [{ repeatCount: "indefinite", video0: { src: "http://butikstv.centrumkanalen.com/play/media/ladd/landscape.mp4", }, }], sensors: [{ type: "rfid", id: "rfid1", driver: "nexmosphere", address: "003", }, { type: "rfid", id: "rfid2", driver: "nexmosphere", address: "005", }, { type: "rfid", id: "rfid3", driver: "nexmosphere", address: "007", test5: "111", }], triggerSensorInfo: { "rfid1-1": { trigger: "trigger3", stringCondition: "or", condition: [{ action: "placed", }], }, "rfid2-2": { trigger: "trigger3", stringCondition: "or", condition: [{ action: "placed", }], }, "rfid3-3": { trigger: "trigger2", stringCondition: "or", condition: [{ action: "placed", }], }, }, triggers: {}, };
4,934
https://github.com/darylwei/MusicProj/blob/master/main.js
Github Open Source
Open Source
MIT
null
MusicProj
darylwei
JavaScript
Code
374
1,142
const { app, BrowserWindow, dialog, Menu } = require('electron') const path = require('path') const url = require('url') const join = require('path').join; const fs = require('fs') const openAboutWindow = require('about-window').default; let win function createWindow() { // Create the browser window. win = new BrowserWindow({ width: 1000, height: 620, icon: __dirname + '/dusk.png' }) var light = false fs.readFile('theme.txt', 'utf-8', function (err, buf) { if (err) return var temp = buf.toString(); if (temp == "light") light = true // console.log(temp); }); var menu = Menu.buildFromTemplate([ { label: 'Folders', accelerator: 'CommandOrControl+o', click: function () { openFolderDialog() } }, { label: 'Theme', submenu:[ { label: 'Toggle', type: "checkbox", checked: light, click: function () { var theme = "" if(light){ theme = "dark" light = false } else{ theme = "light" light = true } fs.writeFile('theme.txt', theme, function (err, data) { if (err) console.log(err); }); // win.webContents.send('theme-change', msg) } } ] }, { label: 'Info', click: function () { openAboutWindow({ product_name: "Dusk Player", copyright: "By Aveek Saha", icon_path: join(__dirname, 'build/icon.png'),}) } } ]) Menu.setApplicationMenu(menu) // and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'app/index.html'), protocol: 'file:', slashes: true })) // fs.readFile('path.txt', 'utf-8', function (err, buf) { // if (err) { // return // } // var temp = [buf.toString()]; // scanDir(temp); // }); // Open the DevTools. // win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { win = null }) } app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (win === null) { createWindow() } }) function openFolderDialog() { dialog.showOpenDialog(win, { properties: ['openDirectory'] }, function (filePath) { if (filePath) { fs.writeFile('path.txt', filePath, function (err, data) { if (err) console.log(err); }); // console.log(filePath); scanDir(filePath) } }) } function scanDir(filePath) { if (!filePath || filePath[0] == 'undefined') return; fs.readdir(filePath[0], function (err, files) { var arr = []; for (var i = 0; i < files.length; i++) { if (files[i].substr(-4) === '.mp3' || files[i].substr(-4) === '.m4a' || files[i].substr(-5) === '.webm' || files[i].substr(-4) === '.wav' || files[i].substr(-4) === '.aac' || files[i].substr(-4) === '.ogg' || files[i].substr(-5) === '.opus') { arr.push(files[i]); } } // console.log(filePath); var objToSend = {}; objToSend.files = arr; objToSend.path = filePath; win.webContents.send('selected-files', objToSend) // console.log(win.webContents); }) }
23,342
https://github.com/hieuhdh/Multi-tasking-program/blob/master/src/Control/Control.py
Github Open Source
Open Source
MIT
null
Multi-tasking-program
hieuhdh
Python
Code
448
1,292
from webbrowser import open_new from PIL import ImageTk,Image from Control.Application import* from Control.Login import* from Control.Sign import* from Control.About import* from Control.Home import* from Tools.CenterDisplay import* root = Tk() root.title("De Uteri") root.iconbitmap('images/frame/icon.ico') root.geometry("960x540") root.background = Label(bg = "#6753c6").place(x = 0, y = 0, relwidth = 1, relheight = 1) root.resizable(0,0) makecenter(root) ## set background image init_frame=Frame(root, width = 900, height = 540, bg = '#823af7') init_frame.place(x=60,y=0) global image_default image_default = ImageTk.PhotoImage(file = 'images/interfaces/background_home.png') Frame_default = Frame(init_frame, bg = "#823af7") Frame_default.place(x = 0,y = 0, height = 540, width=900) logo_default = Label(Frame_default, image = image_default ) logo_default.place( x = 0, y = 0, relheight = 1, relwidth = 1 ) makecenter(root) ## Set logic for button ## global home, login, signup, app, about def openHome(): home = Home(root) def openLogin(): login = Login(root) def openSign_up(): signup = Sign(root) def openApp(): if isLoginSuccessfully() == True: app = Application(root) else: messagebox.showerror("Error","You must login first to run the application.", parent = root) def openAbout_me(): about = AboutMe(root) def control(): def swapFrame(): global home_bg, frame_home fist_frame=Frame(root, width = 300, height = 540, bg = '#823af7') fist_frame.place(x=0,y=0) ## Make button in frame "open" frameButton(fist_frame, -1, 80, ' H O M E ', '#7626d7', '#823af7', openHome, None) frameButton(fist_frame, -1, 130, ' L O G I N ', '#7626d7', '#823af7', openLogin, None) frameButton(fist_frame, -1, 180, ' S I G N U P ', '#7626d7', '#823af7', openSign_up, None) frameButton(fist_frame, -1, 230, ' A P P L I C A T I O N S ', '#7626d7', '#823af7', openApp, None) frameButton(fist_frame, -1, 280, ' A B O U T M E ', '#7626d7', '#823af7', openAbout_me, None) frameButton(fist_frame, -1, 460, ' b y D e u t e r i ', '#7626d7', '#823af7', None, None) ## Icon global facebook_control, google_control, github_control, logo_image Frame_logo = Frame(fist_frame, bg = "#823af7") Frame_logo.place(x = 0,y = 350, height = 190, width=300) logo_image = ImageTk.PhotoImage(file = "images/interfaces/logo_anime.png") logo = Label(Frame_logo, image = logo_image ) logo.place( x = 0, y = 0, relheight = 1, relwidth = 1 ) def deleleFrame(): fist_frame.destroy() ## Display background image again second_frame=Frame(root, width = 900, height = 540, bg = '#823af7') second_frame.place(x=60,y=0) global image_default image_default = ImageTk.PhotoImage(file = 'images/background_home.png') Frame_default = Frame(second_frame, bg = "#823af7") Frame_default.place(x = 0,y = 0, height = 540, width=900) logo_default = Label(Frame_default, image = image_default ) logo_default.place( x = 0, y = 0, relheight = 1, relwidth = 1 ) global image_close image_close = ImageTk.PhotoImage(file = "images/buttons/close.png") Button(fist_frame, image = image_close, border = 0, command = deleleFrame, bg = '#823af7', activebackground = '#823af7').place(x = 5, y = 10) image_open = ImageTk.PhotoImage(file = "images/buttons/open.png") Button(root, image = image_open, command = swapFrame, border = 0, bg = '#6753c6', activebackground ='#6753c6').place(x = 5, y = 10) root.mainloop()
37,795
https://github.com/passyweb/csharp-2021/blob/master/Chap03_Proprietes/Program.cs
Github Open Source
Open Source
MIT
null
csharp-2021
passyweb
C#
Code
38
90
using System; namespace Chap03_Proprietes { class Program { static void Main(string[] args) { Product item = new Product(); var item2 = new Product(); Product item3 = new(); item.Name = " Stylo"; var s = item.Name; } } }
14,937
https://github.com/hbbsoft/OpenClubhouse-Worker/blob/master/worker.py
Github Open Source
Open Source
MIT
2,021
OpenClubhouse-Worker
hbbsoft
Python
Code
686
2,701
from pymongo import MongoClient # from pymongo.objectid import ObjectId from ch_helper import ClubHouseHelper from collections import deque import time import random import json class Worker(): def __init__( self, clubHouseHelper: ClubHouseHelper, mongo_uri: str, token_file: str = None, fresh_interval: int = 3600, max_retries: int = 5, user_limit: int = 500): """ Params: - clubHouseHelper: ClubHouseHelper obj. - mongo_uri: full mongoDB connect uri. - token_file: token json file. If it is None, load token from DB. - fresh_time: the timeing to update channel user counts. Unit is second - max_retries: maximum retry attempts for some action. """ self.client = MongoClient(mongo_uri) self.db = self.client.clubhouse self.chh = clubHouseHelper self.channels = set() self.check_queue = deque() self.join_queue = deque() self.token_id = None self.token_file = token_file self.last_fresh_time = 0 self.fresh_interval = fresh_interval self.max_retries = max_retries self.user_limit = user_limit if self.token_file is not None: print("GetTokenFromJsonFile") self.getTokenFromJsonFile(self.token_file) else: print("getTokenFromDB") self.getTokenFromDB() self.getAllAliveChannelsFromDB() def login(self): print("Try to login...") res = self.chh.start_auth() # res = {'success': True} if res['success'] is True: verification_code = input('Input verification_code: ') res = self.chh.login(verification_code) if res['success'] is True: self.chh.setSecret( res['user_profile']['user_id'], res["auth_token"]) if self.token_file is not None: self.saveToken2JsonFile(self.token_file, res) else: self.saveToken2DB(res) print("Login Success!") return print(res) raise Exception("Failed to login.") def getTokenFromDB(self): token = self.db.tokens.find_one({'is_alive': True}) if token: self.chh.setSecret( token['user_profile']['user_id'], token["auth_token"]) self.token_id = token['_id'] else: self.login() def getTokenFromJsonFile(self, file: str): try: with open(file, 'r') as fp: token = json.load(fp) self.chh.setSecret( token['user_profile']['user_id'], token["auth_token"]) except Exception as e: print("Failed to load token", repr(e)) self.login() def saveToken2JsonFile(self, file: str, token: dict): with open(file, 'w') as fp: json.dump(token, fp) def saveToken2DB(self, token): if self.token_id is not None: self.db.tokens.update_one( {"_id": self.token_id}, {"$set": {"is_alive": False}} ) token['is_alive'] = True cursor = self.db.tokens.insert_one(token) if cursor: self.token_id = cursor.inserted_id def getChannels(self, retry_times=0): "Query all channels from CH" if retry_times < self.max_retries: try: res = self.chh.getChannels() fresh = False if time.time() - self.last_fresh_time > self.fresh_interval: fresh = True self.last_fresh_time = time.time() for channel in res['channels']: channel_uid = (channel['channel_id'], channel['channel']) if channel_uid not in self.channels: print(f"Find a new Channel {channel_uid}") self.addChannel2Set(channel) self.pushChannel2Queue(channel) self.insertChannel2DB(channel) elif fresh: print(f"Update a old Channel {channel_uid}") self.updateChannelInfo2DB(channel) else: print(f"Skip a old Channel {channel_uid}") return True except Exception as e: if 401 <= int(e.args[0]) <= 403: self.login() return self.getChannels(retry_times + 1) else: raise Exception(f"Failed to get channels", repr(e)) raise Exception(f"Maximum attempts for getChannels") def joinChannel(self, channel_uid: tuple): "Get token and all users of a specific channel" if not self.checkChannelStatus(channel_uid, pushintoqueue=False): channel_id, channel_str = channel_uid # attempts = self.max_retries # while attempts > 0: try: res = self.chh.joinChannel(channel_str) if res['success'] is True: self.db.channels.update_one( {"_id": channel_id}, {"$set": { "success": res['success'], "is_empty": res['is_empty'], "token": res['token'], "rtm_token": res['rtm_token'], "pubnub_token": res['pubnub_token'], "pubnub_origin": res['pubnub_origin'], "pubnub_heartbeat_value": res['pubnub_heartbeat_value'], "pubnub_heartbeat_interval": res['pubnub_heartbeat_interval'], "pubnub_enable": res['pubnub_enable'], "agora_native_mute": res['agora_native_mute'], "users": res['users'][:self.user_limit], "joined": True }} ) self.pushJoinedChannel2Queue(channel_uid) elif "That room is no longer available" in res['error_message']: self.endChannel(channel_uid) else: print( f"Error: Failed to join Channel[{channel_uid}-{channel_uid}], reason:{res} ") except Exception as e: print( f"Cannot join channel {channel_uid}.", repr(e)) self.pushUnjoinedChannel2Queue(channel_uid) def checkChannelStatus(self, channel_uid: tuple, pushintoqueue=True): "Check if a channel is end" try: channel_id, channel_str = channel_uid isEnd = self.chh.checkChannelIsEnd(channel_str) if isEnd: self.endChannel(channel_uid) print(f"Room {channel_uid} is ended!") elif pushintoqueue: self.pushJoinedChannel2Queue(channel_uid) return isEnd except Exception as e: print(f"Cannot check channel {channel_uid} status.", repr(e)) return False def endChannel(self, channel_uid): "Mark a channel end" try: channel_id, channel_str = channel_uid self.db.channels.update_one( {"_id": channel_id}, {"$set": {'success': False}}) self.channels.remove(channel_uid) print(f"Channel{channel_uid} is end.") except Exception as e: print(f"Cannot end channel {channel_uid} status.", repr(e)) def getAllAliveChannelsFromDB(self): cursor = self.db.channels.find({"success": True}) for channel in cursor: self.addChannel2Set(channel) self.pushChannel2Queue(channel) def insertChannel2DB(self, channel: dict): channel['reviewed'] = False channel['_id'] = channel['channel_id'] channel['success'] = True channel['joined'] = False self.db.channels.insert_one(channel) def updateChannelInfo2DB(self, channel: dict): self.db.channels.update_one( {"_id": channel['channel_id']}, {"$set": { "num_speakers": channel['num_speakers'], "num_all": channel['num_all'], }}) def pushUnjoinedChannel2Queue(self, channel_uid: tuple): self.join_queue.append(channel_uid) def pushJoinedChannel2Queue(self, channel_uid: tuple): self.check_queue.append(channel_uid) def pushChannel2Queue(self, channel: dict): channel_uid = (channel['channel_id'], channel['channel']) if "token" not in channel: self.pushUnjoinedChannel2Queue(channel_uid) else: self.pushJoinedChannel2Queue(channel_uid) def addChannel2Set(self, channel: dict): self.channels.add((channel['channel_id'], channel['channel'])) def wait(self, left: int, right: int): wait_time = random.randint(left, right) print(f"Sleep {wait_time}s") time.sleep(wait_time) def autoRun(self): while True: print(f"Call getChannels()") # 1. get all channels self.getChannels() # 2. join new channels join_size = len(self.join_queue) while join_size: channel_uid = self.join_queue.popleft() join_size -= 1 print(f"Call joinChannel({channel_uid})") self.joinChannel(channel_uid) self.wait(5, 20) # 3. update channels' status check_size = len(self.check_queue) while check_size > 0: channel_uid = self.check_queue.popleft() check_size -= 1 print(f"Call checkChannelStatus({channel_uid})") self.checkChannelStatus(channel_uid, True) self.wait(5, 10)
27,763
https://github.com/bsomeshwer/version-comparison/blob/master/src/Repo/ExpressionValidator.php
Github Open Source
Open Source
MIT
2,018
version-comparison
bsomeshwer
PHP
Code
774
2,411
<?php namespace Someshwer\VersionComparison\Repo; use Illuminate\Support\Facades\Log; use Someshwer\VersionComparison\Lib\ResponseMaker; use Someshwer\VersionComparison\Repo\ExpressionEvaluator; use Someshwer\VersionComparison\Repo\Lexer; use Someshwer\VersionComparison\Repo\Parser; /** * ExpressionValidator class * * @author Someshwer <[email protected]> * Date: 06-10-2018 */ class ExpressionValidator { /** * Allowed operators variable * * @var array */ private $allowed_operators = ['(', ')', '$', '&', '|', '>', '.', '<', '=', '!', ' ', 'v']; /** * Allowed digits variable * * @var array */ private $allowed_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; /** * Excluded characters variable * * @var array */ private $excluded_characters = ['$', 'v']; /** * Test version number variable * * @var string */ private $test_version_number = '1.1'; /** * ExpressionEvaluator variable * * @var ExpressionEvaluator */ private $expression_evaluator; /** * Constant values for validation messages. */ const VER_EXP_ERR_MSG = 'Version number and expression both are required!'; const VER_ERR_MSG = 'Version number is required!'; const VER_EXP_MSG = 'Expression is required!'; const IN_VALID_EXP_MSG = 'Invalid expression!'; const IN_APPROPRIATE_EXP__MSG = 'Something is inappropriate with the expression.'; const CHECK_AGAIN_MSG = 'Please check and submit the expression again.'; const CHECK_LOG_MSG = 'Check log for more info.'; const NOT_ALLOWED_MSG = 'are not allowed in the expression.'; /** * ExpressionEvaluator constructor function * * @param ExpressionEvaluator $expression_evaluator */ public function __construct(ExpressionEvaluator $expression_evaluator) { $this->expression_evaluator = $expression_evaluator; } /** * Returns allowed operators and digits * * @return array */ private function getAllowedOperatorsAndDigits() { return $allowed_operators_and_digits = array_merge($this->allowed_operators, $this->allowed_digits); } /** * Returns allowed characters * * @return array */ private function getAllowedCharacterSet() { return array_diff($this->getAllowedOperatorsAndDigits(), $this->excluded_characters); } /** * Returns invalid characters in the expression * * @param string $expression * @param array $allowed_operators_and_digits * @return array */ private function getInvalidCharacters($expression, $allowed_operators_and_digits) { // Breaking string into single character pieces $expression_arr = str_split(trim($expression)); $invalid_characters = []; foreach ($expression_arr as $item) { if (!in_array($item, $allowed_operators_and_digits, true)) { $invalid_characters[] = $item; } } return $invalid_characters; } /** * Validating expression to allow specified characters. * * @param string $expression * @param integer $flag * @return array */ private function validateExpressionData($expression, $flag = null) { if ($flag == 1) { $allowed_operators_and_digits = $this->getAllowedCharacterSet(); } else { $allowed_operators_and_digits = $this->getAllowedOperatorsAndDigits(); } $invalid_characters = $this->getInvalidCharacters($expression, $allowed_operators_and_digits); if (count($invalid_characters) > 0) { return $invalid_characters; } else { return []; } } /** * Making expression to evaluate-able and evaluating it using expression language * and returning boolean value. * * @param string $expression * @param integer $flag * @return mixed */ private function validateExpByExpressionLanguage($expression, $flag = null) { $parser = new Parser(); if ($flag == 1) { $expression_to_be_evaluated = $parser->formatVersionExpression($expression); } else { $expression_to_be_evaluated = $parser->getExpressionToBeEvaluated($this->test_version_number, $expression); } try { $result = $this->expression_evaluator->evaluateExpByExpressionLanguage($expression_to_be_evaluated); if (!is_bool($result)) { return Self::IN_VALID_EXP_MSG . ' ' . self::IN_APPROPRIATE_EXP__MSG . ' ' . self::CHECK_AGAIN_MSG; } return $result; } catch (\Exception $e) { Log::error($e); return Self::IN_VALID_EXP_MSG . ' ' . $e->getMessage() . ' ' . self::CHECK_LOG_MSG; } } /** * Analyzing expression by breaking expression into individual sub expressions and * evaluating each sub expression and then building new boolean expression with the * result of individual sub expressions and finally evaluating the boolean expression. * * @param string $expression * @param integer $flag * @return mixed */ private function validateExpByAnalysis($expression, $flag = null) { $parser = new Parser(); $lexer = new Lexer(); try { if ($flag == 1) { $expression_to_be_evaluated = $parser->formatVersionExpression($expression); } else { $expression_to_be_evaluated = $parser->getExpressionToBeEvaluated($this->test_version_number, $expression); } $sub_expressions = $lexer->getSubExpressions($expression_to_be_evaluated); $sanitized_sub_expressions = $parser->sanitizeSubExpressions($sub_expressions); $evaluations_of_sub_expressions = $this->expression_evaluator->evaluateSubExpressions($sanitized_sub_expressions); $boolean_expression = $parser->substituteEvaluations($evaluations_of_sub_expressions, $expression_to_be_evaluated); $result = $this->expression_evaluator->evaluateExpByExpressionLanguage($boolean_expression); $result = ResponseMaker::makeResult($result); if (!is_bool($result)) { return Self::IN_VALID_EXP_MSG . ' ' . self::IN_APPROPRIATE_EXP__MSG . ' ' . self::CHECK_AGAIN_MSG; } return 'SUCCESS'; } catch (\Exception $e) { \Log::error($e); return Self::IN_VALID_EXP_MSG . ' ' . $e->getMessage() . '. ' . self::CHECK_LOG_MSG; } } /** * Validates pure version expression. * * @param string $expression * @return mixed */ public function validatePureVersionExpression($expression) { if (!$expression) { return self::VER_EXP_MSG; } $data_validation = $this->validateExpressionData($expression, 1); if (count($data_validation)) { return Self::IN_VALID_EXP_MSG . ' [' . implode(', ', $data_validation) . '] ' . self::NOT_ALLOWED_MSG; } $evaluation = $this->validateExpByExpressionLanguage($expression, 1); if (!is_bool($evaluation)) { return $evaluation; } $analysis = $this->validateExpByAnalysis($expression, 1); if ($analysis != 'SUCCESS') { return $analysis; } return null; } /** * Validates version and expression * * @param string $version_number * @param string $expression * @return mixed */ public function validateVersionAndExpression($version_number, $expression) { if ((!$version_number) && (!$expression)) { return self::VER_EXP_ERR_MSG; } if (($version_number) && (!$expression)) { return self::VER_EXP_MSG; } if ((!$version_number) && ($expression)) { return self::VER_ERR_MSG; } $data_validation = $this->validateExpressionData($expression); if (count($data_validation)) { return Self::IN_VALID_EXP_MSG . ' [' . implode(', ', $data_validation) . '] ' . self::NOT_ALLOWED_MSG; } $evaluation = $this->validateExpByExpressionLanguage($expression); if (!is_bool($evaluation)) { return $evaluation; } $analysis = $this->validateExpByAnalysis($expression); if ($analysis != 'SUCCESS') { return $analysis; } return null; } }
35,086
https://github.com/obarnard99/vilio/blob/master/features/himario/grakn/conceptnet.py
Github Open Source
Open Source
MIT
2,021
vilio
obarnard99
Python
Code
751
2,681
from grakn.client import GraknClient import csv import random from loguru import logger REL = [ "/r/RelatedTo", "/r/FormOf", "/r/IsA", "/r/PartOf", "/r/HasA", "/r/UsedFor", "/r/CapableOf", "/r/AtLocation", "/r/Causes", "/r/HasSubevent", "/r/HasFirstSubevent", "/r/HasLastSubevent", "/r/HasPrerequisite", "/r/HasProperty", "/r/MotivatedByGoal", "/r/ObstructedBy", "/r/Desires", "/r/CreatedBy", "/r/Synonym", "/r/Antonym", "/r/DistinctFrom", "/r/DerivedFrom", "/r/SymbolOf", "/r/DefinedAs", "/r/MannerOf", "/r/LocatedNear", "/r/HasContext", "/r/SimilarTo", "/r/EtymologicallyRelatedTo", "/r/EtymologicallyDerivedFrom", "/r/CausesDesire", "/r/MadeOf", "/r/ReceivesAction", "/r/ExternalURL", ] def company_template(company): return 'insert $company isa company, has name "' + company["name"] + '";' def person_template(person): # insert person graql_insert_query = f'insert $person isa person, has phone-number "{ person["phone_number"] }"' if person["first_name"] == "": # person is not a customer graql_insert_query += ", has is-customer false" else: # person is a customer graql_insert_query += f""" , has is-customer true , has first-name "{ person["first_name"] }" , has last-name "{ person["last_name"] }" , has city "{ person["city"] }" , has age "{ str(person["age"]) }" """ graql_insert_query += ";" return graql_insert_query def contract_template(contract): # match company graql_insert_query = 'match $company isa company, has name "' + contract["company_name"] + '";' # match person graql_insert_query += ' $customer isa person, has phone-number "' + contract["person_id"] + '";' # insert contract graql_insert_query += " insert (provider: $company, customer: $customer) isa contract;" return graql_insert_query def call_template(call): # match caller graql_insert_query = 'match $caller isa person, has phone-number "' + call["caller_id"] + '";' # match callee graql_insert_query += ' $callee isa person, has phone-number "' + call["callee_id"] + '";' # insert call graql_insert_query += (" insert $call(caller: $caller, callee: $callee) isa call; " + "$call has started-at " + call["started_at"] + "; " + "$call has duration " + str(call["duration"]) + ";") return graql_insert_query def parse_data_to_dictionaries(input): items = [] with open(input["data_path"] + ".csv") as data: # 1 for row in csv.DictReader(data, skipinitialspace = True): item = { key: value for key, value in row.items() } items.append(item) # 2 return items def load_data_into_grakn(input, session): items = parse_data_to_dictionaries(input) for item in items: with session.transaction().write() as transaction: graql_insert_query = input["template"](item) print("Executing Graql Query: " + graql_insert_query) transaction.query(graql_insert_query) transaction.commit() print("\nInserted " + str(len(items)) + " items from [ " + input["data_path"] + "] into Grakn.\n") def build_phone_call_graph(inputs): with GraknClient(uri="localhost:48555") as client: with client.session(keyspace = "phone_calls") as session: for input in inputs: print("Loading from [" + input["data_path"] + "] into Grakn ...") load_data_into_grakn(input, session) """ SEP """ def fitler_csv_by_language(csv_path, output_path): result_lines = [] with open(csv_path, 'r') as f: for line in f: _, relation, entity_a, entity_b, meta = line.split('\t') is_en = entity_a.startswith('/c/en/') and entity_b.startswith('/c/en') if is_en: result_lines.append(line) print('result_lines: ', len(result_lines)) with open(output_path, 'w') as f: f.writelines(result_lines) def build_en_graph(): # build_phone_call_graph(inputs=inputs) conceptnet_csv = '/home/ron/Downloads/hateful_meme_cache/conceptnet-assertions-5.7.0.csv' conceptnet_csv_en = '/home/ron/Downloads/hateful_meme_cache/conceptnet-en-5.7.0.csv' fitler_csv_by_language( conceptnet_csv, conceptnet_csv_en, ) def define_schema(host='35.234.48.188', port=48555): schema = """ define edge sub relation, relates head, relates tail, has edge_id, has edge_type; node sub entity, plays head, plays tail, has name, has supply_info_json; edge_id sub attribute, value long; edge_type sub attribute, value string; name sub attribute, value string; supply_info_json sub attribute, value string; """ with GraknClient(uri=f"{host}:{port}") as client: with client.session(keyspace = "conceptnet") as session: with session.transaction().write() as transaction: transaction.query(schema) transaction.commit() def delete_all(host='35.234.48.188', port=48555): query = """ match $p isa node; $r isa edge; delete $p isa node; $r isa edge; """ with GraknClient(uri=f"{host}:{port}") as client: with client.session(keyspace = "conceptnet") as session: with session.transaction().write() as transaction: transaction.query(query) transaction.commit() def gql_insert_node(head_name, tail_name, edge_type, edge_id, head_json={}, tail_json={}): querys = [ # f'insert $head isa node, has name "{head_name}", has supply_info_json "{head_json}";', # f'insert $tail isa node, has name "{tail_name}", has supply_info_json "{tail_json}";', f""" insert $head isa node, has name "{head_name}", has supply_info_json "{head_json}"; $tail isa node, has name "{tail_name}", has supply_info_json "{tail_json}"; $rel (head: $head, tail: $tail) isa edge, has edge_id {edge_id}, has edge_type "{edge_type}"; """ ] _ = f""" insert $rel (head: $head_node, tail: $tail_node) isa edge; $rel has edge_id "{edge_id}"; $rel has edge_type "{edge_type}"; """ rela = ( f'match $head_node isa node, has name "{head_name}"; ' f' $tail_node isa node, has name "{tail_name}"; ' f"insert $rel (head: $head_node, tail: $tail_node) isa edge;" ) # querys.append(rela) print(querys[0]) return querys def insert_triplets(csv_path, host='35.234.48.188', port=48555, batch_query=100): ccnet_triplets = [] with open(csv_path, 'r') as f: for line in f: _, relation, entity_a, entity_b, meta = line.split('\t') entity_a = entity_a.replace('/c/en/', '').split('/')[0] entity_b = entity_b.replace('/c/en/', '').split('/')[0] meta = meta.replace('\"', '\'') ccnet_triplets.append([relation, entity_a, entity_b, meta]) # random.shuffle(ccnet_triplets) with GraknClient(uri=f"{host}:{port}") as client: with client.session(keyspace = "conceptnet") as session: transaction = session.transaction().write() for i, triplet in enumerate(ccnet_triplets): logger.info(f"[{i}/{len(ccnet_triplets)}]") # with session.transaction().write() as transaction: relation, entity_a, entity_b, meta = triplet ql_str_list = gql_insert_node(entity_a, entity_b, relation, i, head_json="", tail_json="") for ql_str in ql_str_list: transaction.query(ql_str) # if i > 10: # break if i % batch_query == 0: transaction.commit() transaction = session.transaction().write() if __name__ == "__main__": # define_schema() delete_all() insert_triplets('/home/ron/Downloads/hateful_meme_cache/conceptnet-en-5.7.0.csv')
11,067
https://github.com/academydistrict20/notifications/blob/master/packages/shared/src/types.ts
Github Open Source
Open Source
MIT
2,020
notifications
academydistrict20
TypeScript
Code
179
496
import { NotificationsPlugin } from './plugin' export const enum NotificationImportance { INFO = 'info', ALERT = 'alert', EMERGENCY = 'emergency', SUCCESS = 'success', } export const enum NotificationTypes { BANNER = 'banner', FLOATING = 'floating', INLINE = 'inline', STATUS = 'status', } export interface Notification { id: string title: string description: string startDateTime: string endDateTime: string categories: string[] icon?: string callToActionUrl?: string callToActionLabel?: string dismissible?: boolean color?: string detailLinkUrl?: string detailLinkLabel?: string importance?: string | NotificationImportance type?: NotificationTypes } export function notificationFactory(source: Partial<Notification>): Notification { return { id: source.id || `${new Date().getTime()}`, title: source.title || '', description: source.description || '', startDateTime: source.startDateTime || new Date().toISOString(), endDateTime: source.endDateTime || new Date().toISOString(), categories: source.categories || [], icon: source.icon || '', callToActionUrl: source.callToActionUrl || '', callToActionLabel: source.callToActionLabel || '', dismissible: source.dismissible || true, color: source.color || '', detailLinkUrl: source.detailLinkUrl || '', detailLinkLabel: source.detailLinkLabel || '', importance: source.importance || NotificationImportance.INFO, type: source.type || NotificationTypes.FLOATING, } } export interface NotificationsByType { banner?: Notification[] floating?: Notification[] inline?: Notification[] status?: Notification[] } export interface NotificationsClient { config: { storageKey: string storage?: Storage plugins?: NotificationsPlugin[] } }
28,129
https://github.com/emranbm/bazel/blob/master/src/main/java/com/google/devtools/build/lib/query2/aquery/AqueryUtils.java
Github Open Source
Open Source
Apache-2.0
2,019
bazel
emranbm
Java
Code
244
703
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.query2.aquery; import static com.google.devtools.build.lib.query2.engine.InputsFunction.INPUTS; import static com.google.devtools.build.lib.query2.engine.MnemonicFunction.MNEMONIC; import static com.google.devtools.build.lib.query2.engine.OutputsFunction.OUTPUTS; import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; /** Utility class for Aquery */ public class AqueryUtils { /** * Return true if the given {@code action} matches the filters specified in {@code actionFilters}. * * @param action the analysis metadata of an action * @param actionFilters the filters parsed from the query expression * @return whether the action matches the filtering patterns */ public static boolean matchesAqueryFilters( ActionAnalysisMetadata action, AqueryActionFilter actionFilters) { Iterable<Artifact> inputs = action.getInputs(); Iterable<Artifact> outputs = action.getOutputs(); String mnemonic = action.getMnemonic(); if (actionFilters.hasFilterForFunction(MNEMONIC)) { if (!actionFilters.matchesAllPatternsForFunction(MNEMONIC, mnemonic)) { return false; } } if (actionFilters.hasFilterForFunction(INPUTS)) { Boolean containsFile = Streams.stream(inputs) .anyMatch( artifact -> actionFilters.matchesAllPatternsForFunction( INPUTS, artifact.getExecPathString())); if (!containsFile) { return false; } } if (actionFilters.hasFilterForFunction(OUTPUTS)) { Boolean containsFile = Streams.stream(outputs) .anyMatch( artifact -> actionFilters.matchesAllPatternsForFunction( OUTPUTS, artifact.getExecPathString())); return containsFile; } return true; } }
9,695
https://github.com/BorhanMiah/Development-of-Hospital-Management-System-for-Rowshan-Hospital-project/blob/master/resources/views/backend/presception/print.blade.php
Github Open Source
Open Source
MIT
null
Development-of-Hospital-Management-System-for-Rowshan-Hospital-project
BorhanMiah
PHP
Code
149
1,099
<!DOCTYPE html> <html> <head> <title>Print presception</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <h1 style="text-align: center;">United Hospital Limited</h1> <hr style="color: white;"> <h3 style="text-align: center;">Doctor Presception</h3> <br> <div style="padding: 10px;"> <p style="display: inline; ">Doctor Name:<span style="margin-left: 7px;"> {{$presception->d_name}}</span></p> <p style="display: inline; margin-left: 100px;">Date:<span style="margin-left: 7px;"> {{$presception->date}}</span></p> </div> <div style="padding: 10px;"> <p style="display: inline;">Patient Name:<span style="margin-left: 7px;"> {{$presception->p_name}}</span></p> <p style="display: inline; margin-left: 50px;">Age:<span style="margin-left: 7px;"> {{$presception->age}}</span></p> <p style="display: inline; margin-left: 50px;">Gender:<span style="margin-left: 7px;"> {{$presception->gender}}</span></p> </div> <hr> <br> <table class="table"> <tr> <th >Disease Description</th> <td >{{$presception->diseas}}</td> </tr> <tr> <th >On Examinations</th> <td >{{$presception->examination}}</td> </tr> <tr> <th >Provisional Diagnosis</th> <td >{{$presception->provisional}}</td> </tr> <tr> <th >Differential Diagnosis</th> <td >{{$presception->differential}}</td> </tr> <tr> <th >Lab test</th> <td >{{$presception->lab}}</td> </tr> <tr> <th >Advice</th> <td >{{$presception->advice}}</td> </tr> <tr> <th >Medicine</th> <td >{{$presception->medicine}}</td> </tr> </table> <br> <br> <br> <h5 style="text-decoration: overline; margin-left: 20px;">Doctor Signature</h5> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
48,293
https://github.com/me-framework/me-app/blob/master/public/index.php
Github Open Source
Open Source
Apache-2.0
null
me-app
me-framework
PHP
Code
13
69
<?php define('ME_DEBUG', true); require '../vendor/autoload.php'; require '../vendor/me-framework/me/Me.php'; $config = include '../config/api.php'; (new \me\components\Application($config))->run();
17,945
https://github.com/thicsilva/SearchRepair/blob/master/repository/linux/test397.c
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,019
SearchRepair
thicsilva
C
Code
11
21
void test(int bio, int parent){ parent = bio - > ;}
7,671
https://github.com/CodeDone4U/niche-one/blob/master/wp-content/plugins/woocommerce/packages/woocommerce-blocks/assets/js/utils/test/products.js
Github Open Source
Open Source
LGPL-2.0-or-later, LicenseRef-scancode-warranty-disclaimer, LGPL-2.1-or-later, GPL-3.0-or-later, GPL-1.0-or-later, GPL-3.0-only, LicenseRef-scancode-other-copyleft, LicenseRef-scancode-unknown-license-reference, GPL-2.0-only, GPL-2.0-or-later
2,020
niche-one
CodeDone4U
JavaScript
Code
349
713
/** * Internal dependencies */ import { getImageSrcFromProduct, getImageIdFromProduct } from '../products'; describe( 'getImageSrcFromProduct', () => { test( 'returns first image src', () => { const imageSrc = getImageSrcFromProduct( { images: [ { src: 'foo.jpg' } ], } ); expect( imageSrc ).toBe( 'foo.jpg' ); } ); test( 'returns empty string if no product was provided', () => { const imageSrc = getImageSrcFromProduct(); expect( imageSrc ).toBe( '' ); } ); test( 'returns empty string if product is empty', () => { const imageSrc = getImageSrcFromProduct( {} ); expect( imageSrc ).toBe( '' ); } ); test( 'returns empty string if product has no images', () => { const imageSrc = getImageSrcFromProduct( { images: null } ); expect( imageSrc ).toBe( '' ); } ); test( 'returns empty string if product has 0 images', () => { const imageSrc = getImageSrcFromProduct( { images: [] } ); expect( imageSrc ).toBe( '' ); } ); test( 'returns empty string if product image has no src attribute', () => { const imageSrc = getImageSrcFromProduct( { images: [ {} ] } ); expect( imageSrc ).toBe( '' ); } ); } ); describe( 'getImageIdFromProduct', () => { test( 'returns first image id', () => { const imageUrl = getImageIdFromProduct( { images: [ { id: 123 } ], } ); expect( imageUrl ).toBe( 123 ); } ); test( 'returns 0 if no product was provided', () => { const imageUrl = getImageIdFromProduct(); expect( imageUrl ).toBe( 0 ); } ); test( 'returns 0 if product is empty', () => { const imageUrl = getImageIdFromProduct( {} ); expect( imageUrl ).toBe( 0 ); } ); test( 'returns 0 if product has no images', () => { const imageUrl = getImageIdFromProduct( { images: null } ); expect( imageUrl ).toBe( 0 ); } ); test( 'returns 0 if product has 0 images', () => { const imageUrl = getImageIdFromProduct( { images: [] } ); expect( imageUrl ).toBe( 0 ); } ); test( 'returns 0 if product image has no src attribute', () => { const imageUrl = getImageIdFromProduct( { images: [ {} ] } ); expect( imageUrl ).toBe( 0 ); } ); } );
40,017
https://github.com/dhimant1990/coffee-time/blob/master/mobile/lib/core/utils/asset_loader.dart
Github Open Source
Open Source
MIT
2,020
coffee-time
dhimant1990
Dart
Code
17
55
import 'dart:async' show Future; import 'package:flutter/services.dart' show rootBundle; Future<String> loadAsset(String path) async { return await rootBundle.loadString(path); }
7,196
https://github.com/tevesz/cloudbreak/blob/master/cloud-aws/src/main/java/com/sequenceiq/cloudbreak/cloud/aws/connector/resource/AwsRdsTerminateService.java
Github Open Source
Open Source
Apache-2.0
null
cloudbreak
tevesz
Java
Code
469
1,796
package com.sequenceiq.cloudbreak.cloud.aws.connector.resource; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.DeleteStackRequest; import com.amazonaws.services.cloudformation.model.DescribeStacksRequest; import com.amazonaws.waiters.Waiter; import com.amazonaws.waiters.WaiterParameters; import com.sequenceiq.cloudbreak.cloud.aws.AwsClient; import com.sequenceiq.cloudbreak.cloud.aws.AwsStackRequestHelper; import com.sequenceiq.cloudbreak.cloud.aws.CloudFormationStackUtil; import com.sequenceiq.cloudbreak.cloud.aws.client.AmazonCloudFormationRetryClient; import com.sequenceiq.cloudbreak.cloud.aws.scheduler.StackCancellationCheck; import com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException; import com.sequenceiq.cloudbreak.cloud.model.CloudResource; import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus; import com.sequenceiq.cloudbreak.cloud.model.DatabaseStack; import com.sequenceiq.cloudbreak.cloud.notification.PersistenceNotifier; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.inject.Inject; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import static com.sequenceiq.cloudbreak.cloud.aws.scheduler.BackoffCancellablePollingStrategy.getBackoffCancellablePollingStrategy; @Service public class AwsRdsTerminateService { private static final Logger LOGGER = LoggerFactory.getLogger(AwsRdsTerminateService.class); @Inject private CloudFormationStackUtil cfStackUtil; @Inject private AwsClient awsClient; @Inject private AwsStackRequestHelper awsStackRequestHelper; /** * Terminates a database server (stack). * * @param ac authenticated cloud context * @param stack database stack to delete * @param force whether to continue even if stack termination fails in AWS * @param persistenceNotifier notifies Resources table of resource deletion * @param resources list of resources tracked in DB * @return list of affected cloud resources (not yet implemented) * @throws AmazonServiceException if the search for the stack fails * @throws ExecutionException if stack deletion fails (and force is false) * @throws TimeoutException if stack deletion times out * @throws InterruptedException if the wait for stack deletion is interrupted * @throws CloudConnectorException if stack deletion fails due to a runtime exception */ public List<CloudResourceStatus> terminate(AuthenticatedContext ac, DatabaseStack stack, boolean force, PersistenceNotifier persistenceNotifier, List<CloudResource> resources, boolean existOnProviderSide) throws Exception { String cFStackName = cfStackUtil.getCfStackName(ac); AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(cFStackName); AmazonCloudFormationRetryClient cfRetryClient; try { cfRetryClient = getCloudFormationRetryClient(credentialView, regionName); if (existOnProviderSide) { initiateCFTemplateDeletion( ac, cFStackName, credentialView, regionName, cfRetryClient, describeStacksRequest ); } } catch (AmazonServiceException e) { return getAmazonServiceException(force, cFStackName, e); } catch (Exception ex) { Exception runtimeException = getRuntimeException(force, cFStackName, ex); if (runtimeException != null) { throw runtimeException; } } CloudContext cloudContext = ac.getCloudContext(); resources.forEach(r -> persistenceNotifier.notifyDeletion(r, cloudContext)); // FIXME return List.of(); } public Exception getRuntimeException(boolean force, String cFStackName, Exception e) { if (force) { LOGGER.warn("Stack deletion for '{}' failed, continuing because termination is forced", cFStackName, e); return null; } else { if (e instanceof RuntimeException) { return new CloudConnectorException("RDS termination failed " + e.getMessage(), e); } else { return e; } } } @NotNull public List<CloudResourceStatus> getAmazonServiceException(boolean force, String cFStackName, AmazonServiceException e) { if (!e.getErrorMessage().contains(cFStackName + " does not exist") && !force) { throw e; } LOGGER.warn("Stack " + cFStackName + " does not exist, assuming that it has already been deleted"); // FIXME return List.of(); } private AmazonCloudFormationRetryClient getCloudFormationRetryClient(AwsCredentialView credentialView, String regionName) { return awsClient.createCloudFormationRetryClient(credentialView, regionName); } private void initiateCFTemplateDeletion( AuthenticatedContext ac, String cFStackName, AwsCredentialView credentialView, String regionName, AmazonCloudFormationRetryClient cfRetryClient, DescribeStacksRequest describeStacksRequest ) { cfRetryClient.describeStacks(describeStacksRequest); DeleteStackRequest deleteStackRequest = awsStackRequestHelper.createDeleteStackRequest(cFStackName); cfRetryClient.deleteStack(deleteStackRequest); LOGGER.debug("CloudFormation stack deletion request sent with stack name: '{}' for stack: '{}'", cFStackName, ac.getCloudContext().getId()); AmazonCloudFormationClient cfClient = awsClient.createCloudFormationClient(credentialView, regionName); Waiter<DescribeStacksRequest> stackDeleteCompleteWaiter = cfClient.waiters().stackDeleteComplete(); StackCancellationCheck stackCancellationCheck = new StackCancellationCheck(ac.getCloudContext().getId()); WaiterParameters<DescribeStacksRequest> describeStacksRequestWaiterParameters = new WaiterParameters<>(describeStacksRequest) .withPollingStrategy(getBackoffCancellablePollingStrategy(stackCancellationCheck)); stackDeleteCompleteWaiter.run(describeStacksRequestWaiterParameters); } private void wrapExceptionIfNeeded(Exception e) throws Exception { } }
8,607
https://github.com/cash2one/xai/blob/master/xai/brain/wordbase/nouns/_intricacies.py
Github Open Source
Open Source
MIT
2,017
xai
cash2one
Python
Code
24
119
from xai.brain.wordbase.nouns._intricacy import _INTRICACY #calss header class _INTRICACIES(_INTRICACY, ): def __init__(self,): _INTRICACY.__init__(self) self.name = "INTRICACIES" self.specie = 'nouns' self.basic = "intricacy" self.jsondata = {}
36,323
https://github.com/lucasgomesgp/transport/blob/master/js/script.js
Github Open Source
Open Source
MIT
null
transport
lucasgomesgp
JavaScript
Code
39
142
const home = document.getElementById("home"); const btnToggle = document.getElementById("toggler"); const menuHamburguer = document.getElementById("menu_hamburguer"); let toggle = true; btnToggle.addEventListener("click", () => { if(toggle){ menuHamburguer.style.display = "initial"; home.style.marginTop = "12rem"; }else{ menuHamburguer.style.display = "none"; home.style.marginTop = "4rem"; } toggle = !toggle; });
53,140
https://github.com/nabilahnarjis02/UASPILADMIN_2018114029_Nabilahnarjis_Siebisnis/blob/master/resources/views/pengalamans/index.blade.php
Github Open Source
Open Source
MIT
2,021
UASPILADMIN_2018114029_Nabilahnarjis_Siebisnis
nabilahnarjis02
Blade
Code
116
578
@extends('template') @section('content') <div class="row mt-5 mb-5"> <div class="col-lg-12 margin-tb"> <div class="float-left"> <h2>Halaman Pengalaman Bekerja/Usaha</h2> </div> <div class="float-right"> <a class="btn btn-success" href="{{ route('pengalamans.create') }}"> Create Pengalaman</a> </div> </div> </div> @if ($message = Session::get('success')) <div class="alert alert-success"> <p>{{ $message }}</p> </div> @endif <table class="table table-bordered"> <tr> <th width="20px" class="text-center">No</th> <th>Kode Admin</th> <th>Nama Perusahaan</th> <th>Tahun Bekerja</th> <th>Posisi</th> <th width="280px"class="text-center">Action</th> </tr> @foreach ($pengalamans as $post) <tr> <td class="text-center">{{ ++$i }}</td> <td>{{ $post->kode_admin }}</td> <td>{{ $post->nama_perusahaan }}</td> <td>{{ $post->tahun_bekerja }}</td> <td>{{ $post->posisi }}</td> <td class="text-center"> <form action="{{ route('pengalamans.destroy',$post->id) }}" method="POST"> <a class="btn btn-primary btn-sm" href="{{ route('pengalamans.edit',$post->id) }}">Edit</a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus data ini?')">Delete</button> </form> </td> </tr> @endforeach </table> {!! $pengalamans->links() !!} @endsection
32,974
https://github.com/marozau/cocurc/blob/master/sources/timed_idle/abstract_timed_worker.cpp
Github Open Source
Open Source
BSL-1.0
2,014
cocurc
marozau
C++
Code
35
137
#include "abstract_timed_worker.h" namespace cocurc { abstract_timed_worker::abstract_timed_worker( const size_t delay, const bool first_run ) : timed_idle_( delay, [ this ](){ job_(); }, first_run ) { } abstract_timed_worker::~abstract_timed_worker() { } // void abstract_timed_worker::run() { timed_idle_.check(); } }
41,684
https://github.com/jaredhanson/crane-amqp/blob/master/lib/broker.js
Github Open Source
Open Source
MIT
null
crane-amqp
jaredhanson
JavaScript
Code
1,551
3,670
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , amqp = require('amqp') , util = require('util') , Queue = require('./queue') , Message = require('./message') , NoQueueError = require('./errors/noqueueerror') , NoSubscriptionError = require('./errors/nosubscriptionerror') , debug = require('debug')('crane-amqp') , uid = require('uid'); /** * Message delivery mode constants. */ var NONPERSISTENT_MODE = 1; var PERSISTENT_MODE = 2; /** * `Broker` constructor. * * @api public */ function Broker(options) { EventEmitter.call(this); this._exchange = null; this._queues = {}; this._ctags = {}; this._options = options; } /** * Inherit from `EventEmitter`. */ util.inherits(Broker, EventEmitter); /** * Connect to AMQP server. * * For AMQP brokers, `options` argument should be an object that specifies the * following parameters: * * - `port` port the client should connect to, defaults to 5672 * - `host` host the client should connect to, defaults to localhost * * Examples: * * broker.connect({ host: '127.0.0.1', port: 5672 }, function() { * console.log('ready'); * }); * * broker.connect({ host: '127.0.0.1', port: 5672, exchange: 'amq.topic' }, function() { * console.log('ready'); * }); * * broker.connect({ host: '127.0.0.1', port: 5672, * exchange: { * name: 'app1.topic', * options: { type: 'topic', confirm: false } * } }, * function() { * console.log('ready'); * }); * * @param {Object} options * @param {Function} readyListener * @api public */ Broker.prototype.connect = function(options, readyListener) { if (typeof options == 'function') { readyListener = options; options = undefined; } options = options || {}; if (readyListener) { this.once('ready', readyListener); } //debug('connecting %s:%s', options.host || 'localhost', options.port || 5672); var self = this; this._connection = amqp.createConnection(this._options, { reconnect: false }); this._connection.once('ready', function() { var exchange = options.exchange; console.log('CONNECTING TO EXCHANGE! - ' + exchange); if (!exchange) { debug('default exchange'); // Get the default exchange, which is a direct exchange, and thus suitable // for use as a task queue. self._exchange = self._connection.exchange(); // TODO: Emit ready after callback to `exchange()`. return self.emit('ready'); } else { var name = exchange , opts = {}; if (typeof exchange == 'object') { name = exchange.name; opts = exchange.options; } // AMQP uses period ('.') separators rather than slash ('/') name = name.replace(/\//g, '.'); if (name.indexOf('amq.') !== 0) { opts.type = (opts.type === undefined) ? 'direct' : opts.type; opts.durable = (opts.durable === undefined) ? true : opts.durable; opts.autoDelete = (opts.autoDelete === undefined) ? false : opts.autoDelete; opts.confirm = (opts.confirm === undefined) ? true : opts.confirm; } else { // Options for built-in exchanges can not be overridden. opts = {}; } debug('exchange %s %s', name); self._exchange = self._connection.exchange(name, opts, function(exchange) { return self.emit('ready'); }); self._exchange.on('error', function(err) { // NOTE: This will occur if an exchange is redeclared with different // properties. // // For example, the underlying `amqp` emits an error with the // following properties: // - message: PRECONDITION_FAILED - cannot redeclare exchange // 'foo' in vhost '/' with different type, durable, // internal or autodelete value // - code: 406 return self.emit('error', err); }); } }); this._connection.on('error', this.emit.bind(this, 'error')); } /** * Publish a message to the exchange. * * In AMQP, publishing a message to an exchange has the effect of enqueuing that * message on all queues that are bound to the exchange with a routing key that * matches the topic. * * Examples: * * broker.enqueue('tasks/mail', { to: '[email protected]', body: 'Welcome!' }, function(err) { * if (err) { throw err; } * ... * }); * * broker.enqueue('metrics/cpu', { timestamp: 1396288552169, value: 32 }); * * @param {String} topic * @param {Mixed} msg * @param {Object} options * @param {Function} cb * @api public */ Broker.prototype.publish = function(topic, msg, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; // AMQP uses period ('.') separators rather than slash ('/') topic = topic.replace(/\//g, '.'); options.deliveryMode = (options.deliveryMode === undefined) ? PERSISTENT_MODE : options.deliveryMode; // TODO: This option appears to have no effect. Investigate why. //options.mandatory = (options.mandatory === undefined) ? true : options.mandatory; if (this._exchange.options && this._exchange.options.confirm) { debug('publish %s (confirm)', topic); console.log('PUBLISH 1: ' + topic); this._exchange.publish(topic, msg, options, function(hadError, err) { if (hadError) { err = err || new Error('Failed to publish message to topic "' + topic + '"'); return cb(err); } return cb(); }); } else { debug('publish %s', topic); console.log('PUBLISH 0: ' + topic); this._exchange.publish(topic, msg.body, options); if (cb) { return process.nextTick(cb); } } } /** * Subscribe to messages enqueued in a queue. * * Once subscribed, messages will be delivered and emitted in `message` events. * A Crane application can be registered as a listener for these events, * allowing worker processes to be developed in a style similar to that of * Express applications. * * Examples: * * broker.subscribe('tasks/mail', function(err) { * if (err) { throw err; } * ... * }); * * broker.subscribe('tasks/serial', { exclusive: true }, function(err) { * if (err) { throw err; } * ... * }); * * @param {String} queue * @param {Object} options * @param {Function} cb * @api public */ Broker.prototype.consume = function(queue, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; if (!queue) { queue = this.address } console.log('SUBSCRIBE NOW'); console.log(queue) // AMQP uses period ('.') separators rather than slash ('/') queue = queue.replace(/\//g, '.'); options.ack = (options.ack === undefined) ? true : options.ack; var self = this , q = this._queues[queue]; if (!q) { return cb(new NoQueueError('Queue "' + queue + '" not declared')); } function declared(q) { var onError = function(err) { return cb(err); }; debug('subscribe %s', queue); q.subscribe(options, function(message, headers, deliveryInfo, messageObject) { console.log('GOT MESSAGE :)'); console.log(message); console.log(headers); console.log(deliveryInfo) console.log(messageObject) var m = new Message(message, headers, deliveryInfo, messageObject); m.broker = self; self.emit('message', m); //m.ack(); }).addCallback(function(ok) { // This callback is invoked when the subscription was successful, and is // equivalent to the registering a listener for the queue's `basicConsumeOk` // event. q.removeListener('error', onError); self._ctags[queue] = ok.consumerTag; return cb(); }).addErrback(function(err) { // NOTE: Promise errbacks are not properly invoked by the underlying `amqp` // module. As a workaround, a listener is explicitly registered for // the queue's `error` event. }); // NOTE: This will occur if an attempt is made to subscribe to a queue that // already has an exclusive subscription. // // For example, the underlying `amqp` emits an error with the following // properties: // - message: ACCESS_REFUSED - queue 'foo' in vhost '/' in exclusive // use // - code: 403 q.once('error', onError); } declared(q); } /** * Unsubscribe from messages enqueued in a queue. * * Once unsubscribed, messages will no longer be delivered or emitted in * `message` events. * * Examples: * * broker.unsubscribe('tasks/mail', function(err) { * if (err) { throw err; } * ... * }); * * @param {String} queue * @param {Object} options * @param {Function} cb * @api public */ Broker.prototype.unsubscribe = function(queue, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; // AMQP uses period ('.') separators rather than slash ('/') queue = queue.replace(/\//g, '.'); options.close = (options.close === undefined) ? true : options.close; var self = this , q = this._queues[queue] , ctag = this._ctags[queue]; if (!q) { return cb(new NoQueueError('Queue "' + queue + '" not declared')); } if (!ctag) { return cb(new NoSubscriptionError('Not subscribed to queue "' + queue + '"')); } debug('unsubscribe %s', queue); q.unsubscribe(ctag) .addCallback(function(ok) { delete self._ctags[queue]; if (options.close) { q.close(); return cb(); } else { return cb(); } }) .addErrback(function(err) { }); } /** * Declare a queue. * * Examples: * * broker.declare('tasks/mail', function(err, queue) { * if (err) { throw err; } * ... * }); * * @param {String} queue * @param {Object} options * @param {Function} cb * @api public */ Broker.prototype.declare = function(queue, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; var bind = (options.bind === undefined) ? true : options.bind; console.log('DECLARE QUQUE: ' + queue); // AMQP uses period ('.') separators rather than slash ('/') if (queue) { queue = queue.replace(/\//g, '.'); } if (!queue) { queue = queue || ('entity-' + uid(16)); console.log('TEMP QUEU NAME: ' + queue); options.exclusive = true; options.durable = false; this.address = queue; console.log('DECLARED, ADDRESS - ' + this.address); //bind = false } // Task queues are declared as durable, by default. This ensures that tasks // are not lost in the event that that server is stopped or crashes. options.durable = (options.durable === undefined) ? true : options.durable; options.autoDelete = (options.autoDelete === undefined) ? false : options.autoDelete; var self = this; var onError = function(err) { return cb(err); }; debug('declare %s', queue); var q = this._connection.queue(queue, options, function onOpen(q) { console.log('OPEN!'); var wq = new Queue(q, self._exchange.name); q.removeListener('error', onError); if (bind) { wq.bind(queue, function(err) { if (err) { return cb(err); } return cb(null, wq); }); } else { return cb(null, wq); } }); // FIXME: //return; this._queues[queue] = q; // NOTE: This will occur if a queue is redeclared with different properties. // // For example, the underlying `amqp` emits an error with the following // properties: // - message: PRECONDITION_FAILED - parameters for queue 'foo' in // vhost '/' not equivalent // - code: 406 q.once('error', onError); } /** * Expose `Broker`. */ module.exports = Broker;
16,143
https://github.com/Atlanticity91/Aurora/blob/master/Aurora/Diagnostics/DiagnosticReport.cs
Github Open Source
Open Source
MIT
null
Aurora
Atlanticity91
C#
Code
647
1,448
/** * * /\ * / \ _ _ _ __ ___ _ __ __ _ * / /\ \| | | | '__/ _ \| '__/ _` | * / ____ \ |_| | | | (_) | | | (_| | * /_/ \_\__,_|_| \___/|_| \__,_| * * Licensed under the MIT License <http://opensource.org/licenses/MIT>. * SPDX-License-Identifier : MIT * Project source : https://github.com/Atlanticity91/Aurora * * MIT License * * Copyright( c ) 2020 ALVES Quentin * * 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. * **/ using Aurora.Utils; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Aurora.Diagnostics { /// <summary> /// DiagnosticReport sealed class /// </summary> /// <author>ALVES Quentin</author> /// <note>Defined Aurora core code for diagnostic report support</note> public sealed class DiagnosticReport { private List<Diagnostic> diags; public string Emitter { get; } public bool HasDiagnostics => this.diags.Count > 0; public IEnumerable< Diagnostic > Diagnostics => this.diags.ToImmutableArray( ); public int Size => this.diags.Count; public int InfoCount => this.diags.Count( diag => diag.Type == EDiagnosticTypes.EDT_INFO ); public int WarnCount => this.diags.Count( diag => diag.Type == EDiagnosticTypes.EDT_INFO ); public int ErrrCount => this.diags.Count( diag => diag.Type == EDiagnosticTypes.EDT_INFO ); /// <summary> /// Constructor /// </summary> /// <author>ALVES Quentin</author> /// <param name="emitter" >Diagnostic emitter</param> public DiagnosticReport( string emitter ) { this.Emitter = emitter; this.diags = new List<Diagnostic>( ); } /// <summary> /// Clear method /// </summary> /// <author>ALVES Quentin</author> /// <note>Clear the current report</note> public void Clear( ) => this.diags.Clear( ); /// <summary> /// Merge method /// </summary> /// <author>ALVES Quentin</author> /// <note>Merge to report</note> /// <param name="report" >The other query report to merge</param> public void Merge( DiagnosticReport report ) { if ( report.HasDiagnostics ) this.diags.AddRange( report.Diagnostics ); } /// <summary> /// Emit method /// </summary> /// <author>ALVES Quentin</author> /// <note>Add a line to the report</note> /// <param name="type" >Type of diagnostic</param> /// <param name="message" >Message of the diagnostic</param> /// <param name="meta" >Metadata of the diagnostic</param> private void Emit( EDiagnosticTypes type, string message, Textmeta meta ) { var diag = new Diagnostic( type, message, meta ); this.diags.Add( diag ); } /// <summary> /// EmitInfo method /// </summary> /// <author>ALVES Quentin</author> /// <note>Add an info line to the report</note> /// <param name="message" >Message of the diagnostic</param> /// <param name="meta" >Metadata of the diagnostic</param> public void EmitInfo( string message, Textmeta meta ) => this.Emit( EDiagnosticTypes.EDT_INFO, message, meta ); /// <summary> /// EmitWarn method /// </summary> /// <author>ALVES Quentin</author> /// <note>Add a warning line to the report</note> /// <param name="message" >Message of the diagnostic</param> /// <param name="meta" >Metadata of the diagnostic</param> public void EmitWarn( string message, Textmeta meta ) => this.Emit( EDiagnosticTypes.EDT_WARN, message, meta ); /// <summary> /// EmitErrr method /// </summary> /// <author>ALVES Quentin</author> /// <note>Add an error line to the report</note> /// <param name="message" >Message of the diagnostic</param> /// <param name="meta" >Metadata of the diagnostic</param> public void EmitErrr( string message, Textmeta meta ) => this.Emit( EDiagnosticTypes.EDT_ERRR, message, meta ); } }
28,179
https://github.com/themattharris/chimehack/blob/master/client/Pods/Pods-UIResponder+MNActions-dummy.m
Github Open Source
Open Source
MIT
2,015
chimehack
themattharris
Objective-C
Code
10
58
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_UIResponder_MNActions : NSObject @end @implementation PodsDummy_Pods_UIResponder_MNActions @end
10,728
https://github.com/bmottag/andromeda/blob/master/assets/js/validate/inspection/vehicle_inspection_v2.js
Github Open Source
Open Source
MIT
null
andromeda
bmottag
JavaScript
Code
412
1,457
$( document ).ready( function () { $("#hours").bloquearTexto().maxlength(10); $( "#form" ).validate( { rules: { hours: { number: true, minlength: 2, maxlength: 10 }, belt: { required: true }, powerSteering: { required: true }, oil: { required: true }, coolantLevel: { required: true }, waterLeaks: { required: true }, headLamps: { required: true }, hazardLights: { required: true }, bakeLights: { required: true }, workLights: { required: true }, turnSignals: { required: true }, beaconLight: { required: true }, clearanceLights: { required: true }, brakePedal: { required: true }, emergencyBrake: { required: true }, gauges: { required: true }, horn: { required: true }, seatbelts: { required: true }, driverSeat: { required: true }, insurance: { required: true }, registration: { required: true }, cleanInterior: { required: true }, nuts: { required: true }, glass: { required: true }, cleanExterior: { required: true }, wipers: { required: true }, backupBeeper: { required: true }, passengerDoor: { required: true }, properDecals: { required: true }, fireExtinguisher: { required: true }, firstAid: { required: true }, emergencyReflectors:{ required: true }, spillKit: { required: true }, steeringAxle: { required: true }, drivesAxle: { required: true }, greaseFront: { required: true }, greaseEnd: { required: true }, grease: { required: true }, hoist: { required: true }, heater: { required: true }, steering_wheel: { required: true }, suspension_system: { required: true }, air_brake: { required: true }, fuel_system: { required: true } }, errorElement: "em", errorPlacement: function ( error, element ) { // Add the `help-block` class to the error element error.addClass( "help-block" ); error.insertAfter( element ); }, highlight: function ( element, errorClass, validClass ) { $( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" ); }, unhighlight: function (element, errorClass, validClass) { $( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" ); }, submitHandler: function (form) { return true; } }); $("#btnSubmit").click(function(){ if ($("#form").valid() == true){ //Activa icono guardando $('#btnSubmit').attr('disabled','-1'); $("#div_load").css("display", "inline"); $("#div_error").css("display", "none"); $.ajax({ type: "POST", url: base_url + "inspection/save_daily_inspection", data: $("#form").serialize(), dataType: "json", contentType: "application/x-www-form-urlencoded;charset=UTF-8", cache: false, success: function(data){ if( data.result == "error" ) { alert(data.mensaje); $("#div_load").css("display", "none"); $('#btnSubmit').removeAttr('disabled'); $("#span_msj").html(data.mensaje); $("#div_error").css("display", "inline"); return false; } if( data.result )//true { $("#div_load").css("display", "none"); $('#btnSubmit').removeAttr('disabled'); var url = base_url + "inspection/add_daily_inspection/" + data.idDailyInspection; $(location).attr("href", url); } else { alert('Error. Reload the web page.'); $("#div_load").css("display", "none"); $("#div_error").css("display", "inline"); $('#btnSubmit').removeAttr('disabled'); } }, error: function(result) { alert('Error. Reload the web page.'); $("#div_load").css("display", "none"); $("#div_error").css("display", "inline"); $('#btnSubmit').removeAttr('disabled'); } }); }//if else { alert('There are missing fields that have not been filled.'); } }); });
32,691
https://github.com/pankajsa/splus/blob/master/splus/commands/clientuser_commands.py
Github Open Source
Open Source
MIT
2,020
splus
pankajsa
Python
Code
377
1,267
import logging import click from common import add_if from common import send_response from common import my_global_options from managers import RestMgr suburl = 'clientUsernames' logger = logging.getLogger(__name__) @click.group() def clientuser(): pass @clientuser.command() @click.argument("name") @click.option('--acl-profile', default='default', show_default=True, help='ACL Profile of the Client Username') @click.option('--client-profile', default='default', show_default=True, help='Client Profile of the Client Username') @click.option('--enable/--no-enable', default=True, show_default=True, help='When disabled, all clients currently connected as the Client Username are disconnected') @click.option('--gm-perm-override/--no-gm-perm-override', default=False, show_default=True, help='Manage guaranteed endpoint permission override for the Client Username. When enabled all guaranteed endpoints may be accessed, modified or deleted with the same permission as the owner') @click.option('--password', help='Password for the Client Username') @click.option('--subscription-manager/--no-subscription-manager', default=False, show_default=True, help='Manage the subscription management capability of the Client Username. This is the ability to manage subscriptions on behalf of other Client Usernames.') @my_global_options def create( name, acl_profile, client_profile, enable, gm_perm_override, password, subscription_manager, **kwargs): '''Create a new client username''' upsert(True, name, acl_profile, client_profile, enable, gm_perm_override, password, subscription_manager, **kwargs) def upsert(is_post, name, acl_profile, client_profile, enable, gm_perm_override, password, subscription_manager, **kwargs): dict = {} add_if(dict, acl_profile, 'clientUsername', name) add_if(dict, acl_profile, 'aclProfileName', acl_profile) add_if(dict, client_profile, 'clientProfileName', client_profile) add_if(dict, enable, 'enabled') add_if(dict, gm_perm_override, 'guaranteedEndpointPermissionOverrideEnabled') add_if(dict, password, 'password', password) add_if(dict, subscription_manager, 'subscriptionManagerEnabled') rest_mgr = RestMgr(kwargs) if is_post: res = rest_mgr.post('clientUsernames', dict) else: res = rest_mgr.patch('clientUsernames', name, dict) send_response(res) @clientuser.command() @click.argument("name") @click.option('--acl-profile', help='ACL Profile of the Client Username') @click.option('--client-profile', help='Client Profile of the Client Username') @click.option('--enable/--no-enable', default=None, help='When disabled, all clients currently connected as the Client Username are disconnected') @click.option('--gm-perm-override/--no-gm-perm-override', default=None, help='Manage guaranteed endpoint permission override for the Client Username. When enabled all guaranteed endpoints may be accessed, modified or deleted with the same permission as the owner') @click.option('--password', help='Password for the Client Username') @click.option('--subscription-manager/--no-subscription-manager', default=None, help='Manage the subscription management capability of the Client Username. This is the ability to manage subscriptions on behalf of other Client Usernames.') @my_global_options def update( name, acl_profile, client_profile, enable, gm_perm_override, password, subscription_manager, **kwargs): '''Update an existing client username''' upsert(False, name, acl_profile, client_profile, enable, gm_perm_override, password, subscription_manager, **kwargs) @clientuser.command() @click.argument("name") @my_global_options def show(name, **kwargs): '''Show details of an existing client username''' rest_mgr = RestMgr(kwargs) res = rest_mgr.get(suburl, name) send_response(res) @clientuser.command() @my_global_options def list(**kwargs): '''List all client usernames in the Message VPN''' rest_mgr = RestMgr(kwargs) res = rest_mgr.get(suburl) send_response(res) @clientuser.command() @click.argument("name") @my_global_options def remove(name, **kwargs): '''Remove a client username''' rest_mgr = RestMgr(kwargs) res = rest_mgr.delete(suburl, name) send_response(res)
725
https://github.com/pushpithaDilhan/ReadItNow/blob/master/resources/views/book.blade.php
Github Open Source
Open Source
MIT
2,017
ReadItNow
pushpithaDilhan
Blade
Code
223
1,262
@extends('layouts.master') @section('title') Book Shelf @endsection @section('content') @include('layouts.navbar-bookreader') <div style="margin-top:180px;"> <img src="{{URL::asset('/books/'.$image.'.jpg')}}" alt="profile Pic" style="display:inline; margin-left:80px;" width="256" height="384"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <h2 style="display:inline-block; vertical-align:top;" ><b>{{$title}}</b> <br> <p style="display:inline-block; vertical-align:top;font-size:20px">{{$author}}</p> <br> <p style="display:inline-block; vertical-align:top;font-size:20px"> {{$category}} </p> <br> <p style="font-size:20px"><span class="glyphicon glyphicon-star" ></span> {{$orating}}/10 </p> <br> <p style="font-size:20px"> <b> Description </b></p> <p style="font-size:18px">{{$description}}</p> @if(Session::get('role')=='r') <a href="../completed/{{$image}}"><button type="submit" class="btn btn-success" style="display:inline-block;">I have read</button></a> <a href="../toread/{{$image}}"><button type="submit" class="btn btn-info" style="display:inline-block;">I need to read</button></a> <br><br> <a href="../buy/{{$image}}"><button type="submit" class="btn btn-danger" style="display:inline-block;">Where to buy</button></a> @endif @if(Session::get('role')=='s') <a href="../list/{{$image}}"><button type="submit" class="btn btn-success" style="display:inline-block;">We have this</button></a> <a href="../buy/{{$image}}"><button type="submit" class="btn btn-danger" style="display:inline-block;">Where to buy</button></a> @endif </div> </h2> <br><br> @if(Session::get('role')=='r') <h3 style="margin-left:50px;">Leave a review</h3> <form style="margin-left:50px; margin-right:50px;" action="/comment" method="POST"> <input type="hidden" name="bookid" value="{{ $image }}"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <div class="form-group"> <label for="title">Title :</label> <input type="text" name="title" class="form-control" id="title-comment"> </div> <div class="form-group"> <label for="comment">Review :</label> <textarea class="form-control" name="comment" rows="5" required></textarea> </div> <select class="form-group btn" name="rating"> <option value="" disabled selected>Rate</option> <option>10</option> <option>9</option> <option>8</option> <option>7</option> <option>6</option> <option>5</option> <option>4</option> <option>3</option> <option>2</option> <option>1</option> </select> &nbsp;&nbsp; <button type="submit" class="btn btn-success" style="display:inline-block;">Submit</button> </form> <br><br> @endif <div id="movie-reviews"> <h3><span class="glyphicon glyphicon-star"></span> Book Reviews</h3> <br> @for ($i = 0; $i < count($comments); $i++) <div class="jumbotron"> <div> Reviewed by <span ><b>{{ $comments[$i]->fname }} {{ $comments[$i]->sname }}</b></span> <span class="glyphicon glyphicon-star"></span> <span class="review-rating">{{ $comments[$i]->rating }} / 10</span> </div> <h4>{{ $comments[$i]->title }}</h4> <article style="height: 125px;"> <p> {{ $comments[$i]->comment }} </p> </article> </div> @endfor </div> @endsection
54,216
https://github.com/DasSheep/Massivesoft_ITE220/blob/master/secure/config.php
Github Open Source
Open Source
MIT
2,017
Massivesoft_ITE220
DasSheep
PHP
Code
63
305
<?php //Created by Trin [DB connector and config] ob_start(); session_start(); date_default_timezone_set('Asia/Bangkok'); //DB credentials !CHANGE IF NEW HOST! define('DBHOST','localhost'); define('DBUSER','root'); define('DBPASS',''); define('DBNAME','Massivesoft'); define('DIR','localhost'); define('SITEEMAIL','[email protected]'); try { //Establish DB connection. $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { //Throws DB error if any. echo '<div class="alert alert-danger alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'.$e->getMessage().'</div>'; exit; } include('classes/user.php'); include('classes/phpmailer/mail.php'); $user = new User($db); ?>
53,919
https://github.com/SoporteUti/Graduacion/blob/master/pguesfinal/resources/views/ues/solicitudes/reprobacionxabandono.blade.php
Github Open Source
Open Source
MIT
2,021
Graduacion
SoporteUti
Blade
Code
447
2,213
<div style="width: 20px;float: left;"> <img src="{{ public_path('img/minerva2.png') }}" width="100px" height="110px" ></img> </div> <style type="text/css"> html { margin:2cm 2cm 2cm 2cm; } </style> <h4 align="center"> Universidad de El Salvador<br> Facultad Multidisciplinaria Paracentral<br> @foreach($grupo as $gru) @if($gru->codigoG==$codigo) @foreach($carrera as $c) @if($c->idcarrera == $gru->idcarrera) @foreach($departamento as $d) @if($d->iddepartamento ==$c->iddepartamento) Departamento de {{$d->nombre}} <?php $iddepto=$d->iddepartamento; $idcarrera=$gru->idcarrera; $anio=$gru->fecharegistro; ?> @endif @endforeach @endif @endforeach @endif @endforeach <br > Coordinaci&oacute;n General de Trabajos de Graduaci&oacute;n <br > </h4> <h5 align="right"> San Vicente, <?php echo date('d');?> de <?php $meses = array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre" ); echo $meses[idate('m')-1]; ?> de <?php echo date('Y');?></h5> <p align="justify"> <h> <?php $newformat = date('Y',strtotime($anio)); ?> @foreach($rol_carrera as $rlc) @if($rlc->idrol==4 ) @foreach($docentes as $d) @if($d->iddocente==$rlc->iddocente) @foreach($personas as $p) @if($p->idpersona==$d->idpersona) {{$d->titulo}}{{" "}}{{$p->nombres}}{{" "}}{{$p->apellidos}} @endif @endforeach @endif @endforeach @foreach($rol as $r) @if($r->idrol==$rlc->idrol && $r->idrol==4) <br> Director General de Trabajos de Graduaci&oacute;n @endif @endforeach @endif @endforeach <br>Presente.</h></p> <p align="justify"><h >Estimado/a<br>Reciba cordiales saludos y deseos de &eacute;xitos en sus labores diarias.</h></p> <p align="justify"> <h >@foreach($enunciado as $en) @if($en->idsolicitud==8 &&$en->idrol==3) {{$en->enunciado}} @endif @endforeach, le solicitamos que se gestione ante la Junta Directiva la <strong>reprobaci&oacute;n</strong> por abandono de parte del/la estudiante con carnet N°: {{$estudianteselec}} al Trabajo de Graduaci&oacute;n que se detalla a continuaci&oacute;n:</h> <p align="justify"> @foreach($grupo as $gru) @if($gru->codigoG==$codigo) C&oacute;digo: {{$gru->codigoG}} <br> <h >Tema:{{$gru->tema}}</h> @endif @endforeach </p> </p>@foreach($grupo as $gru) @if($gru->codigoG==$codigo) @endif @endforeach <p align="justify"><h > Docente/es Asesor/es:</h></p> <table class="table table-hover" width="600px" cellspacing="5px" align="center" > <thead> <tr > <th width="45%"></th> <th width="20%"></th> <th width="25%"></th> </tr> </thead> <tbody> @foreach($asesores as $ase) @if($ase->idgrupo==$gru->idgrupo) @foreach($docentes as $doc) @if($ase->iddocente==$doc->iddocente) @foreach($personas as $per) @if($per->idpersona==$doc->idpersona) @foreach($tipoasesor as $tias) @if($tias->idtipoasesor==$ase->idtipoasesor) <tr> <td>{{$doc->titulo}}{{" "}}{{$per->nombres}}{{" "}}{{$per->apellidos}}{{" - "}}{{$tias->tipoasesor}}</td> <td></td> <td></td> </tr> @endif @endforeach @endif @endforeach @endif @endforeach @endif @endforeach </tbody> </table> <br> <br> <p align="justify"> <h>Dicha petici&oacute;n obedece a que el/la estudiante no se ha presentado a las asesorias programadas en repetidas ocaciones sin presentar ninguna justificaci&oacute;n</h> <br> <h >Sin otro particular. Atentamente.</h></p> <h4 align="center">"HACIA LA LIBERTAD POR LA CULTURA"</h4> <br> <br> <p> <div style="width: 250px; float: left;"> @foreach($rol_carrera as $rlc) @if($rlc->idrol==3 && $rlc->anio == $newformat && $rlc->idcarrera==$idcarrera) @foreach($docentes as $d) @if($d->iddocente==$rlc->iddocente) @foreach($personas as $p) @if($p->idpersona==$d->idpersona) {{$d->titulo}}{{" "}}{{$p->nombres}}{{" "}}{{$p->apellidos}} @endif @endforeach @endif @endforeach @foreach($rol as $r) @if($r->idrol==$rlc->idrol && $r->idrol==3) Coordinador General de Trabajos de Graduaci&oacute;n @endif @endforeach @endif @endforeach @foreach($grupo as $gru) @if($gru->codigoG==$codigo) @foreach($carrera as $c) @if($c->idcarrera == $gru->idcarrera) @foreach($departamento as $d) @if($d->iddepartamento ==$c->iddepartamento) Departamento de {{$d->nombre}} @endif @endforeach @endif @endforeach @endif @endforeach </div> <div style="width: 250px; float: right; "> @foreach($rol_carrera as $rlc) @if($rlc->idrol==2 && $rlc->idcarrera==$idcarrera) @foreach($docentes as $d) @if($d->iddocente==$rlc->iddocente) @foreach($personas as $p) @if($p->idpersona==$d->idpersona) {{$d->titulo}}{{" "}}{{$p->nombres}}{{" "}}{{$p->apellidos}} @endif @endforeach @endif @endforeach @foreach($rol as $r) @if($r->idrol==$rlc->idrol && $r->idrol==2) Jefe de Departamento @endif @endforeach @endif @endforeach @foreach($grupo as $gru) @if($gru->codigoG==$codigo) @foreach($carrera as $c) @if($c->idcarrera == $gru->idcarrera) @foreach($departamento as $d) @if($d->iddepartamento ==$c->iddepartamento) {{$d->nombre}} @endif @endforeach @endif @endforeach @endif @endforeach </div> </p>
6,880
https://github.com/kcgithub2014/setup/blob/master/preferences/_os_.prefs
Github Open Source
Open Source
MIT
2,018
setup
kcgithub2014
Shell
Code
47
149
#!/usr/bin/env zsh # Set wallpaper CURRENT_WALLPAPER=$DIR_SYNC/Wallpapers/wallpaper_mikael_gustafsson.png echo_title "Updating wallpaper to $CURRENT_WALLPAPER" # npmig wallpaper-cli # wallpaper $CURRENT_WALLPAPER # wallpaper-cli does not like macos-refresh method # so this simple command below is enough for macOS osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$CURRENT_WALLPAPER\""
24,734
https://github.com/awesome-archive/WeRoBot/blob/master/travis/terryfy/test_pyver_ge.sh
Github Open Source
Open Source
BSD-2-Clause, MIT
2,017
WeRoBot
awesome-archive
Shell
Code
96
269
# Test python version comparison utility if [ -n "$(pyver_ge 2.7.8 3.4.0)" ]; then RET=1; fi if [ -z "$(pyver_ge 3.8.2 3.4.0)" ]; then RET=1; fi if [ -n "$(pyver_ge 3.3.8 3.4.0)" ]; then RET=1; fi if [ -z "$(pyver_ge 2.7.8 2.6.9)" ]; then RET=1; fi if [ -z "$(pyver_ge 3.4.0 3.4.0)" ]; then RET=1; fi if [ -n "$(pyver_ge 3.4.0 3.4.1)" ]; then RET=1; fi if [ -n "$(pyver_ge 2.1.1 3.0.0)" ]; then RET=1; fi if [ -n "$(pyver_ge 3.0.0 3.0.1)" ]; then RET=1; fi if [ -n "$(pyver_ge 3.0.1 3.1.0)" ]; then RET=1; fi
6,578
https://github.com/kchulj/boa-sdk-ts/blob/master/src/modules/net/error/ErrorTypes.ts
Github Open Source
Open Source
MIT
2,021
boa-sdk-ts
kchulj
TypeScript
Code
369
866
/******************************************************************************* Contains definition for error types Copyright: Copyright (c) 2020-2021 BOSAGORA Foundation All rights reserved. License: MIT License. See LICENSE for details. *******************************************************************************/ /** * The class used when a network error occurs */ export class NetworkError extends Error { /** * The status code */ public status: number; /** * The status text */ public statusText: string; /** * The message of response */ public statusMessage: string; /** * Constructor * @param status The status code * @param statusText The status text * @param statusMessage The message of response */ constructor(status: number, statusText: string, statusMessage: string) { super(statusText); this.name = "NetworkError"; this.status = status; this.statusText = statusText; this.statusMessage = statusMessage; } } /** * When status code is 404 */ export class NotFoundError extends NetworkError { /** * Constructor * @param status The status code * @param statusText The status text * @param statusMessage The message of response */ constructor(status: number, statusText: string, statusMessage: string) { super(status, statusText, statusMessage); this.name = "NotFoundError"; } } /** * When status code is 400 */ export class BadRequestError extends NetworkError { /** * Constructor * @param status The status code * @param statusText The status text * @param statusMessage The message of response */ constructor(status: number, statusText: string, statusMessage: string) { super(status, statusText, statusMessage); this.name = "BadRequestError"; } } /** * It is a function that handles errors that occur during communication * with a server for easy use. * @param error This is why the error occurred * @returns The instance of Error */ export function handleNetworkError(error: any): Error { if ( error.response !== undefined && error.response.status !== undefined && error.response.statusText !== undefined ) { let statusMessage: string; if (error.response.data !== undefined) { if (typeof error.response.data === "string") statusMessage = error.response.data; else if (typeof error.response.data === "object" && error.response.data.statusMessage !== undefined) statusMessage = error.response.data.statusMessage; else if (typeof error.response.data === "object" && error.response.data.errorMessage !== undefined) statusMessage = error.response.data.errorMessage; else statusMessage = error.response.data.toString(); } else statusMessage = ""; switch (error.response.status) { case 400: return new BadRequestError(error.response.status, error.response.statusText, statusMessage); case 404: return new NotFoundError(error.response.status, error.response.statusText, statusMessage); default: return new NetworkError(error.response.status, error.response.statusText, statusMessage); } } else { if (error.message !== undefined) return new Error(error.message); else return new Error("An unknown error has occurred."); } }
10,412
https://github.com/leonardolira14/serverqvalapp/blob/master/application/controllers/Clientes.php
Github Open Source
Open Source
MIT
null
serverqvalapp
leonardolira14
PHP
Code
75
514
<?php defined('BASEPATH') OR exit('No direct script access allowed'); require_once( APPPATH.'/libraries/REST_Controller.php' ); use Restserver\libraries\REST_Controller; class Clientes extends REST_Controller { function __construct() { header("Access-Control-Allow-Methods: GET"); header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding"); header("Access-Control-Allow-Origin: *"); parent::__construct(); $this->load->model("Model_Clientes"); $this->load->model("Model_Usuarios"); } public function checkpass_post(){ $datos= $this->post(); //vdebug($datos); if($datos["tipo"]==="E"){ $clave=md5($datos["clave"]); $data["ok"]=$this->Model_Clientes->checkpassword($datos["idempresa"],$clave); }else{ $data["ok"]=$this->Model_Usuarios->checkpassword($datos["idempresa"],$datos["clave"]); } $this->response($data); } public function updatepass_post(){ $datos= $this->post(); $aleatoria=""; $caracteres = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.#!'; for($x = 0; $x < 1; $x++){ $aleatoria =$aleatoria. substr(str_shuffle($caracteres), 0, 6); } $clave=md5($aleatoria); $this->Model_Clientes->updatepassword($datos["empresa"],$clave); $data["clave"]=$aleatoria; $this->response($data); } }
17,721
https://github.com/CS2103-AY1819S2-W13-3/main/blob/master/src/main/java/seedu/address/ui/SourceCard.java
Github Open Source
Open Source
MIT
2,019
main
CS2103-AY1819S2-W13-3
Java
Code
204
621
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.source.Source; /** * An UI component that displays information of a {@code Source}. */ public class SourceCard extends UiPart<Region> { private static final String FXML = "SourceListCard.fxml"; /** * Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX. * As a consequence, UI elements' variable names cannot be set to such keywords * or an exceptions will be thrown by JavaFX during runtime. * * @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on AddressBook level 4</a> */ public final Source source; @FXML private HBox cardPane; @FXML private FlowPane pinned; @FXML private Label id; @FXML private Label title; @FXML private Label author; @FXML private Label type; @FXML private Label detail; @FXML private FlowPane tags; public SourceCard(Source source, int displayedIndex) { super(FXML); this.source = source; if (source.getPinnedState() == true) { pinned.getChildren().add(new Label("Pinned")); } id.setText(displayedIndex + ". "); title.setText(source.getTitle().title); author.setText(source.getAuthor().author); type.setText(source.getType().type); detail.setText(source.getDetail().detail); source.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof SourceCard)) { return false; } // state check SourceCard card = (SourceCard) other; return id.getText().equals(card.id.getText()) && source.equals(card.source); } }
46,451
https://github.com/learn-more/BadApp/blob/master/BadApp/Heap.c
Github Open Source
Open Source
MIT
2,022
BadApp
learn-more
C
Code
315
1,058
/* * PROJECT: BadApp * LICENSE: MIT (https://spdx.org/licenses/MIT) * PURPOSE: Heap bugs * COPYRIGHT: Copyright 2018 Mark Jansen ([email protected]) */ #include "stdafx.h" static HANDLE g_Heap1; static HANDLE g_Heap2; #define ALLOCATION_SIZE 0x0d PVOID BADAPP_EXPORT DoAllocation(void) { PVOID Allocation = HeapAlloc(g_Heap1, 0, ALLOCATION_SIZE); Output(L"Alloc(Heap1, 0x%x)=%p", ALLOCATION_SIZE, Allocation); return Allocation; } void BADAPP_EXPORT NormalFree1FN(void) { PVOID Allocation = DoAllocation(); HeapFree(g_Heap1, 0, Allocation); } void BADAPP_EXPORT NormalFree2FN(void) { PVOID Allocation = HeapAlloc(g_Heap2, 0, ALLOCATION_SIZE); Output(L"Alloc(Heap2, 0x%x)=%p", ALLOCATION_SIZE, Allocation); HeapFree(g_Heap2, 0, Allocation); } void BADAPP_EXPORT UseAfterFreeFN(void) { PVOID Allocation = DoAllocation(); PBYTE ptr = (PBYTE)Allocation; HeapFree(g_Heap1, 0, Allocation); ptr[0] = 0x11; } void BADAPP_EXPORT DoubleFreeFN(void) { PVOID Allocation = DoAllocation(); HeapFree(g_Heap1, 0, Allocation); HeapFree(g_Heap1, 0, Allocation); } void BADAPP_EXPORT WrongHeapFN(void) { PVOID Allocation = DoAllocation(); HeapFree(g_Heap2, 0, Allocation); } void BADAPP_EXPORT OverflowFN(void) { PVOID Allocation = DoAllocation(); PBYTE ptr = (PBYTE)Allocation; ptr[ALLOCATION_SIZE] = 0x11; HeapFree(g_Heap1, 0, Allocation); } static BAD_ACTION g_Actions[] = { { L"Normal alloc Heap1", L"Allocate and free memory using HeapAlloc and HeapFree. This can be used to trigger checks in the heap functions. This function operates on Heap1.", NormalFree1FN, NoIcon }, { L"Normal alloc Heap2", L"Allocate and free memory using HeapAlloc and HeapFree. This can be used to trigger checks in the heap functions. This function operates on Heap1.", NormalFree2FN, NoIcon }, { L"Use after free", L"Free memory using HeapFree, and modify it afterwards.", UseAfterFreeFN, BadIcon }, { L"Double free", L"Free memory twice using HeapFree.", DoubleFreeFN, BadIcon }, { L"Free wrong heap", L"Allocate memory using HeapAlloc from Heap1, then free it using HeapFree from Heap2.", WrongHeapFN, BadIcon }, { L"Buffer overflow", L"Write 2 bytes past the allocated space, then free the memory using HeapFree.", OverflowFN, BadIcon }, { NULL }, }; static BAD_ACTION g_Category = { L"Heap", L"Trigger various heap bugs", NULL, NoIcon }; void BADAPP_EXPORT Heap_Init(void) { g_Heap1 = HeapCreate(0, 0, 0); g_Heap2 = HeapCreate(0, 0, 0); Register_Category(&g_Category, g_Actions); Output(L"Heap1: %p", g_Heap1); Output(L"Heap2: %p", g_Heap2); }
18,112
https://github.com/AmanziTel/neo4j-index/blob/master/lib/neo4j-index/range_tree/index_node.rb
Github Open Source
Open Source
MIT
2,011
neo4j-index
AmanziTel
Ruby
Code
76
329
module Neo4jIndex module RangeTree module IndexNode class << self def create_raw(index_values, level) index_node = Neo4j::Node.new index_node[:level] = level index_node[:index_values] = index_values index_node end def create_first(indexer, values) create_child(nil, indexer, values) end def create_child(parent_index_node, indexer, values) level = parent_index_node ? parent_index_node[:level] - 1 : 0 child_index_node = create_raw(indexer.calculate_index_values(level, values), level) parent_index_node && Neo4j::Relationship.new(indexer.relationship, parent_index_node, child_index_node) child_index_node end def create_parent(child_index_node, indexer) level = child_index_node[:level] + 1 parent_index_node = create_raw(child_index_node[:index_values], level) Neo4j::Relationship.new(indexer.relationship, parent_index_node, child_index_node) parent_index_node end end end end end
14,617
https://github.com/vishalbelsare/XDATA/blob/master/textstructure/topic/src/chowtree/InterfaceObservationLikelihood.h
Github Open Source
Open Source
Apache-2.0
2,016
XDATA
vishalbelsare
C++
Code
192
521
#ifndef INTERFACEOBSERVATIONLIKELIHOOD_H_ #define INTERFACEOBSERVATIONLIKELIHOOD_H_ #include <vector> #include <string> #include "InterfaceDetectorModel.h" //#include "InterfacePlaceModel.h" class InterfaceObservationLikelihood { public: //takes the training data in the form [image[histogram of image]] and generates the naive Bayes model or the Chow Liu tree InterfaceObservationLikelihood(std::vector<std::vector<int> >& training_data, std::string pCLTreeFilename, bool calculateModel=false) {}; // loads the stored naive Bayes model or Chow Liu Tree from file InterfaceObservationLikelihood(std::string pCLTreeFilename) {}; virtual ~InterfaceObservationLikelihood() {}; // returns P(Z_k | L_i) as defined in equations (5)-(8) for the naive Bayes model or (9)-(14) for the Chow Liu trees /* virtual double evaluate(std::vector<int>& observations, int location, InterfaceDetectorModel* detectorModel, InterfacePlaceModel* placeModel) = 0; */ // returns the marginal probability for observing a single attribute p(z_attr = val) virtual double getMarginalPriorProbability(int attr, int val) = 0; // returns the whole marginal probabilities vector virtual std::vector<std::vector<double> >& getMarginalPriorProbabilities() = 0; // returns p(Z_k | L_u) for a randomly sampled place L_u with randomly sampled obervations Z_k as needed in equation (17) virtual double sampleNewPlaceObservation(InterfaceDetectorModel* detectorModel, std::vector<int>& observation) = 0; // returns p(Z_k | L_{avg}) for the average place L_{avg} as needed in equation (16) virtual double meanFieldNewPlaceObservation(InterfaceDetectorModel* detectorModel, const std::vector<int>& observation) = 0; }; #endif /* INTERFACEOBSERVATIONLIKELIHOOD_H_ */
17,103
https://github.com/budeci/amma-1/blob/master/resources/views/partials/products/item-block.blade.php
Github Open Source
Open Source
MIT
2,016
amma-1
budeci
Blade
Code
34
196
<div class="item product"> @include('partials.products.item.info-label') <div class="display-table"> <div class="wrapp_img with_hover td wrapp_countdown"> {{--@include('partials.products.item.countdown')--}} <a href="{{ route('view_product', ['product' => $item->id]) }}"><img src="{{ $item->present()->cover() }}" alt="" width="279" height="180"></a> </div> </div> @include('partials.products.item.name') <div class="wrapp_info"> @include('partials.products.item.price') @include('partials.products.item.stock') </div> </div>
6,845
https://github.com/tatarch/yii/blob/master/views/list/index.php
Github Open Source
Open Source
2,020
yii
tatarch
PHP
Code
116
456
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use unclead\multipleinput\MultipleInput; /* @var $this yii\web\View */ /** @var \app\models\TaskList[] $taskLists */ $this->title = 'Task Lists'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="task-list-index"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Create Task List', ['create'], ['class' => 'btn btn-success']) ?> </p> <?php foreach ($taskLists as $taskList): ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($taskList, 'tasks')->widget(MultipleInput::className(), [ 'min' => count($taskList->tasks), 'max' => count($taskList->tasks), 'addButtonPosition' => false, 'columns' => [ [ 'name' => 'name', 'title' => 'Name' ], [ 'name' => 'goal', 'title' => 'Goal', 'enableError' => true, 'options' => [ 'class' => 'input-priority' ] ] ] ])->label($taskList->name); ?> <?= $form->field($taskList, 'id')->hiddenInput()->label(false); ?> <div class="form-group"> <a href="/web/list/update?id=<?= $taskList->id ?>">Update</a> </div> <?php ActiveForm::end(); ?> <?php endforeach; ?> </div>
11,420
https://github.com/Morning-Train/wp-blocks/blob/master/src/Classes/BlockMeta.php
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,022
wp-blocks
Morning-Train
PHP
Code
116
370
<?php namespace Morningtrain\WP\Blocks\Classes; use Mockery\Exception; class BlockMeta { public array $editorStyleDependencies = []; public mixed $renderCallback = null; public mixed $view = null; public array $scriptDependencies = []; public array $styleDependencies = []; public function __construct(protected ?array $blockMeta) { } public function enqueueDependencies() { if (! has_block($this->blockMeta['name'])) { return; } foreach ($this->styleDependencies as $dep) { \wp_enqueue_style($dep); } foreach ($this->scriptDependencies as $dep) { \wp_enqueue_script($dep); } } public function enqueueAdminDependencies() { if (! has_block($this->blockMeta['name'])) { return; } foreach ($this->editorStyleDependencies as $dep) { \wp_enqueue_style($dep); } } public function view(?array $blockAttributes) { // Make sure View Class exists if (! class_exists('Morningtrain\WP\View\View')) { throw new Exception('Can\'t render views. View class does not exist'); } //render view return \Morningtrain\WP\View\View::render($this->view, $blockAttributes); } }
1,537
https://github.com/remicollet/horde/blob/master/chora/lib/Renderer/File/Plain.php
Github Open Source
Open Source
Adobe-Glyph
null
horde
remicollet
PHP
Code
50
130
<?php /** * Copyright 2000-2017 Horde LLC (http://www.horde.org/) * * See the enclosed file COPYING for license information (GPL). If you * did not receive this file, see http://www.horde.org/licenses/gpl. * * @author Chuck Hagenbuch <[email protected]> * @package Chora */ class Chora_Renderer_File_Plain extends Chora_Renderer_File { public function render() { } }
46,910
https://github.com/bepintocosta/CleanArchitecture/blob/master/src/Application/Features/Products/Queries/GetAllProducts/GetAllProductsQueryHandler.cs
Github Open Source
Open Source
MIT
2,021
CleanArchitecture
bepintocosta
C#
Code
60
308
namespace CleanArchitecture.Application.Features.Products.Queries.GetAllProducts; using CleanArchitecture.Application.Common.Wrappers; using MediatR; using System.Linq; using System.Threading; using System.Threading.Tasks; public class GetAllProductsQueryHandler : IRequestHandler<GetAllProductsQuery, Result<PagedResponse<GetAllProductsDTO>>> { private readonly IProductRepository _productRepository; public GetAllProductsQueryHandler(IProductRepository productRepository) { _productRepository = productRepository; } public async Task<Result<PagedResponse<GetAllProductsDTO>>> Handle(GetAllProductsQuery request, CancellationToken cancellationToken) { var pagedResponse = await _productRepository.GetPagedReponseAsync(request.PageNumber, request.PageSize); PagedResponse<GetAllProductsDTO> response = new PagedResponse<GetAllProductsDTO>( pagedResponse.PageNumber, pagedResponse.PageSize, pagedResponse.TotalCount, pagedResponse.Data.Select(s => GetAllProductsDTO.ToDto(s)).ToList().AsReadOnly()); return Result.Ok(response); } }
35,924
https://github.com/l00k/phala-miner-monitor-ui/blob/master/src/core/Loader/ModuleLoader.ts
Github Open Source
Open Source
MIT
2,021
phala-miner-monitor-ui
l00k
TypeScript
Code
116
321
import { InitiationException } from '@100k/intiv/Exception'; type Callback = (data : any, previousResult : any) => any; type Listners = { [eventName : string] : Callback[] }; export default class ModuleLoader { public async _loadModules(types : string[], require) { const modules = []; for (const path of require.keys()) { const pathParts = path.replace(/^[./]+/g, '').split('/'); const moduleName = pathParts.shift(); const objectName = pathParts.join('/'); if (!path) { continue; } let includable = false; for (let type of types) { if (objectName.indexOf(type) === 0) { includable = true; break; } } if (includable) { const module = require(path); modules.push(module); } } return modules; } public async load(types : string[]) { return this._loadModules( types, require.context('@/modules', true, /\.(ts|vue)/) ); } }
6,148
https://github.com/LucidSigma/Daily-Coding-Problems/blob/master/Days 221 - 230/Day 227/BoggleWordFinder.cpp
Github Open Source
Open Source
MIT
null
Daily-Coding-Problems
LucidSigma
C++
Code
295
940
#include <algorithm> #include <array> #include <cstddef> #include <cstdlib> #include <iostream> #include <iterator> #include <string> #include <vector> static constexpr size_t GridSize = 4u; using Dictionary = std::vector<std::string>; using BoggleGrid = std::array<std::array<char, GridSize>, GridSize>; using VisitedGrid = std::array<std::array<bool, GridSize>, GridSize>; inline bool IsValidWord(const std::string& word, const Dictionary& dictionary) noexcept { return std::find(std::cbegin(dictionary), std::cend(dictionary), word) != std::cend(dictionary); } void FindAllWordsHelper(const BoggleGrid& boggleGrid, VisitedGrid& visited, const Dictionary& dictionary, std::vector<std::string>& validWords, const size_t i, const size_t j, std::string& currentWord) noexcept { visited[i][j] = true; currentWord += boggleGrid[i][j]; if (IsValidWord(currentWord, dictionary)) { validWords.push_back(currentWord); } for (int row = i - 1; row <= static_cast<int>(i + 1); ++row) { for (int column = j - 1; column <= static_cast<int>(j + 1); ++column) { if (row < GridSize && column < GridSize && row >= 0 && column >= 0 && !visited[row][column]) { FindAllWordsHelper(boggleGrid, visited, dictionary, validWords, row, column, currentWord); } } } currentWord.pop_back(); visited[i][j] = false; } std::vector<std::string> FindAllWords(const BoggleGrid& boggleGrid, const Dictionary& dictionary) noexcept { std::string currentWord; std::vector<std::string> validWords; for (size_t i = 0; i < GridSize; ++i) { for (size_t j = 0; j < GridSize; ++j) { VisitedGrid visitedCells{ std::array<bool, GridSize>{ false } }; FindAllWordsHelper(boggleGrid, visitedCells, dictionary, validWords, i, j, currentWord); } } return validWords; } template <typename T> std::ostream& operator <<(std::ostream& outputStream, const std::vector<T>& values) noexcept { for (const auto& value : values) { outputStream << value << " "; } return outputStream; } int main(int argc, char* argv[]) { const Dictionary dictionary { "AUTO", "SHORT", "RETURN", "EXPLICIT", "CATCH", "ALIGNAS", "FOR", "WHILE", "NOEXCEPT", "INLINE" }; const BoggleGrid boggleGrid { std::array<char, GridSize>{ 'A', 'C', 'X', 'E' }, std::array<char, GridSize>{ 'T', 'C', 'P', 'N' }, std::array<char, GridSize>{ 'F', 'H', 'L', 'I' }, std::array<char, GridSize>{ 'Q', 'T', 'I', 'C' }, }; std::cout << FindAllWords(boggleGrid, dictionary) << "\n"; std::cin.get(); return EXIT_SUCCESS; }
17,620
https://github.com/test-ci-bot/fabric8-planner/blob/master/src/app/components_ngrx/label-selector/label-selector.component.ts
Github Open Source
Open Source
Apache-2.0
null
fabric8-planner
test-ci-bot
TypeScript
Code
497
1,848
import { EventService } from './../../services/event.service'; import { Component, ElementRef, EventEmitter, Input, Output, OnInit, SimpleChanges, ViewChild } from '@angular/core'; import { cloneDeep } from 'lodash'; import { LabelUI, LabelModel } from './../../models/label.model'; import { LabelService } from './../../services/label.service'; import { SelectDropdownComponent } from './../../widgets/select-dropdown/select-dropdown.component'; // ngrx stuff import { Store } from '@ngrx/store'; import { AppState } from './../../../app/states/app.state'; import * as LabelActions from './../../actions/label.actions'; @Component({ selector: 'label-selector', templateUrl: './label-selector.component.html', styleUrls: ['./label-selector.component.less'] }) export class LabelSelectorComponent implements OnInit { @ViewChild('labelname') labelnameInput: ElementRef; @ViewChild('dropdown') dropdownRef: SelectDropdownComponent; @Input('allLabels') set allLabelsSetter(labels: LabelUI[]) { this.allLabels = [...labels]; this.createDisabled = false; this.backup = cloneDeep(this.allLabels.map((label: LabelUI) => { return { id: label.id, color: label.backgroundColor, border: label.borderColor, name: label.name, selected: false } })); if (this.searchValue.length) { this.labels = cloneDeep(this.backup.filter(i => i.name.indexOf(this.searchValue) > - 1)); } else { this.labels = cloneDeep(this.backup); } if (this.labelnameInput) { this.labelnameInput.nativeElement.value = ''; this.labelnameInput.nativeElement.focus(); } this.updateSelection(); } @Input('selectedLabels') set selectedLabelsSetter(labels: LabelUI[]) { this.selectedLabels = labels; this.updateSelection(); } @Output() onSelectLabel: EventEmitter<LabelUI[]> = new EventEmitter(); @Output() onOpenSelector: EventEmitter<any> = new EventEmitter(); @Output() onCloseSelector: EventEmitter<LabelUI[]> = new EventEmitter(); private activeAddLabel: boolean = false; private backup: any[] = []; private colorPickerActive: boolean = false; private colors: any[] = []; private createDisabled: boolean = false; private labels: any[] = []; private newSelectedColor: any = {}; private searchValue: string = ''; private allLabels: LabelUI[] = []; private selectedLabels: LabelUI[] = []; constructor( private labelService: LabelService, private eventService: EventService, private store: Store<AppState> ) {} ngOnInit() { this.colors = [ {color: '#fbdebf', border: '#f39d3c'}, {color: '#f7bd7f', border: '#f39d3c'}, {color: '#fbeabc', border: '#f39d3c'}, {color: '#f9d67a', border: '#f39d3c'}, {color: '#e4f5bc', border: '#ace12e'}, {color: '#cfe7cd', border: '#6ec664'}, {color: '#9ecf99', border: '#6ec664'}, {color: '#bedee1', border: '#3a9ca6'}, {color: '#7dbdc3', border: '#3a9ca6'}, {color: '#beedf9', border: '#35caed'}, {color: '#7cdbf3', border: '#35caed'}, {color: '#c7bfff', border: '#8461f7'}, {color: '#a18fff', border: '#8461f7'}, {color: '#ededed', border: '#bbbbbb'}, {color: '#d1d1d1', border: '#bbbbbb'} ]; this.newSelectedColor = this.colors[Math.floor(Math.random()*this.colors.length)]; } onSelect(event: any) { let findSelectedIndex = this.selectedLabels.findIndex(i => i.id === event.id); if (findSelectedIndex > -1) { this.selectedLabels.splice(findSelectedIndex, 1); } else { let findLabel = cloneDeep(this.allLabels.find(i => i.id === event.id)); if (findLabel) { this.selectedLabels.push(findLabel); } } this.updateSelection(); this.onSelectLabel.emit(cloneDeep(this.selectedLabels)); } updateSelection() { this.labels.forEach((label, index) => { if (this.selectedLabels.find(l => label.id === l.id)) { this.labels[index].selected = true; } else { this.labels[index].selected = false; } }); this.backup.forEach((label, index) => { if (this.selectedLabels.find(l => label.id === l.id)) { this.backup[index].selected = true; } else { this.backup[index].selected = false; } }); } onSearch(event: any) { let needle = event.trim(); this.searchValue = needle; if (needle.length) { this.labels = cloneDeep(this.backup.filter(i => i.name.indexOf(needle) > -1)); } else { this.labels = cloneDeep(this.backup); } } clickOnAddLabel() { this.newSelectedColor = this.colors[Math.floor(Math.random()*this.colors.length)]; this.activeAddLabel = true; } closeAddLabel() { this.activeAddLabel = false; } toggleColorPicker() { this.colorPickerActive = !this.colorPickerActive; } selectColor(color: any) { this.newSelectedColor = color; } createLabel(name: any) { if (name.trim() === '' || this.createDisabled) { return; } this.createDisabled = true; let labelPayload: LabelModel = { attributes: { 'name': name, 'background-color': this.newSelectedColor.color, 'border-color': this.newSelectedColor.border }, type: 'labels' }; this.store.dispatch(new LabelActions.Add(labelPayload)); } onOpen(event) { this.onOpenSelector.emit('open'); } onClose(event) { this.onCloseSelector.emit(cloneDeep(this.selectedLabels)); } openDropdown() { this.dropdownRef.openDropdown(); } closeDropdown() { this.dropdownRef.closeDropdown(); } }
42,797
https://github.com/RajeshMaster/larainvoice/blob/master/resources/views/Engineerdetails/index.blade.php
Github Open Source
Open Source
MIT
null
larainvoice
RajeshMaster
PHP
Code
1,213
5,212
@extends('layouts.app') @section('content') @php use App\Http\Helpers; @endphp <script type="text/javascript"> var datetime = '<?php echo date('Ymdhis'); ?>'; var mainmenu = '<?php echo $request->mainmenu; ?>'; $(document).ready(function() { setDatePicker("startdate"); setDatePicker("enddate"); }); function mulclick(divid){ if($('#'+divid).css('display') == 'block'){ document.getElementById(divid).style.display = 'none'; document.getElementById(divid).style.height= "240px"; }else { document.getElementById(divid).style.display = 'block'; } } </script> <style type="text/css"> .sort_asc { background-image:url({{ URL::asset('resources/assets/images/upArrow.png') }}) !important; } .sort_desc { background-image:url({{ URL::asset('resources/assets/images/downArrow.png') }}) !important; } </style> {{ HTML::script('resources/assets/js/engineerdetails.js') }} {{ HTML::script('resources/assets/js/switch.js') }} {{ HTML::script('resources/assets/js/hoe.js') }} {{ HTML::style('resources/assets/css/extra.css') }} {{ HTML::style('resources/assets/css/hoe.css') }} {{ HTML::style('resources/assets/css/switch.css') }} {{ HTML::script('resources/assets/js/lib/bootstrap-datetimepicker.js') }} {{ HTML::style('resources/assets/css/lib/bootstrap-datetimepicker.min.css') }} {{ HTML::script('resources/assets/js/lib/lightbox.js') }} {{ HTML::style('resources/assets/css/lib/lightbox.css') }} <div class="CMN_display_block" id="main_contents"> <!-- article to select the main&sub menu --> <article id="sales" class="DEC_flex_wrapper " data-category="sales sales_sub_7"> {{ Form::open(array('name'=>'frmcustomerplusindex', 'id'=>'frmcustomerplusindex', 'url' => 'Engineerdetails/index?mainmenu='.$request->mainmenu.'&time='.date('YmdHis'), 'files'=>true, 'method' => 'POST')) }} {{ Form::hidden('plimit', $request->plimit , array('id' => 'plimit')) }} {{ Form::hidden('page', $request->page , array('id' => 'page')) }} {{ Form::hidden('sorting', $request->sorting, array('id' => 'sorting')) }} {{ Form::hidden('searchmethod', $request->searchmethod, array('id' => 'searchmethod')) }} {{ Form::hidden('sortOrder', $request->sortOrder , array('id' => 'sortOrder')) }} {{ Form::hidden('ordervalue', $request->ordervalue, array('id' => 'ordervalue')) }} {{ Form::hidden('selMonth', $request->selMonth, array('id' => 'selMonth')) }} {{ Form::hidden('mainmenu', $request->mainmenu, array('id' => 'mainmenu')) }} {{ Form::hidden('selYear', $request->selYear, array('id' => 'selYear')) }} {{ Form::hidden('prevcnt', $request->prevcnt, array('id' => 'prevcnt')) }} {{ Form::hidden('nextcnt', $request->nextcnt, array('id' => 'nextcnt')) }} {{ Form::hidden('account_val', $account_val, array('id' => 'account_val')) }} {{ Form::hidden('engineeridClick', '' , array('id' => 'engineeridClick')) }} <!-- Start Heading --> <div class="row hline"> <div class="col-sm-12 mt10"> <img class="pull-left box40 mt5" src="{{ URL::asset('resources/assets/images/Client.png') }}"> <h2 class="pl5 pull-left mt10">{{ trans('messages.lbl_engg_details') }}</h2> </div> </div> @if($request->searchmethod =="6" || $request->searchmethod=="") <div class="box100per pr10 pl10 mt10"> <div class="mt10"> {{ Helpers::displayYear_MonthEst($account_period, $year_month, $db_year_month, $date_month, $dbnext, $dbprevious,$last_year, $current_year, $account_val) }} </div> </div> @endif <!-- End Heading --> @if($request->searchmethod !="3") <div class="col-xs-12 pm0 pull-left mb10 pl10 mt10 pr10"> <div class="form-group pm0 pull-right moveleft nodropdownsymbol" id="moveleft"> <a href="javascript:clearsearch()" title="Clear Search"> <img class="pull-left box30 mr5 " src="{{ URL::asset('resources/assets/images/clearsearch.png') }}"> </a> {{ Form::select('engineerdetailssort', [null=>''] + $engineerdetailssortarray, $request->engineerdetailssort, array('class' => 'form-control'.' ' .$request->sortstyle.' '.'CMN_sorting pull-right', 'id' => 'engineerdetailssort', 'style' => $sortMargin, 'name' => 'engineerdetailssort')) }} </div> </div> @endif @if($request->searchmethod =="3") <div class="col-xs-12 pm0 pull-left mb10 pl10 pr10 mt20 fwb"> {{ trans('messages.lbl_employeeid').':' }} <span class="mr40 ml12" style="color:blue;"> {{ $engineerdet[0]->EMPID }} </span> {{ trans('messages.lbl_empName').':' }} <span style="color:#9C0000;margin-left: 10px"> {{ $engineerdet[0]->LastName }} </span> </div> @endif <div class="minh350 box100per pl10 pr10"> <table class="tablealternate box100per CMN_tblfixed width98"> <colgroup> @if($request->searchmethod =="3") <col width="2%"> <col width="6%"> <col width="6%"> @else <col width="4%"> <col width="9%"> <col width="9%"> @endif @if($request->searchmethod !="3") <col width="10%"> <col width="12%"> @endif @if($request->searchmethod =="3") <col width="20%"> <col width="10%"> <col width="6%"> @else <col width="20%"> <col width="12%"> <col width="12%"> @endif </colgroup> <thead class="CMN_tbltheadcolor"> <tr class="tableheader fwb tac"> <th class="tac">{{ trans('messages.lbl_sno') }}</th> <th class="tac">{{ trans('messages.lbl_invoiceno') }}</th> <th class="tac">{{ trans('messages.lbl_dateofissue') }}</th> @if($request->searchmethod !="3") <th class="tac">{{ trans('messages.lbl_employeeid') }}</th> <th class="tac">{{ trans('messages.lbl_empName') }}</th> @endif <th class="tac">{{ trans('messages.lbl_companyname') }}</th> <th class="tac">{{ trans('messages.lbl_content') }}</th> <th class="tac">{{ trans('messages.lbl_estamount') }}</th> </tr> </thead> <tbody> @if($request->searchmethod !="3") <tr style="background-color: #DDDDDD;"> <td colspan="6"></td> <td align="right" style="font-weight: 700">{{ trans('messages.lbl_total') }}</td> <td align="right" style="color: blue;font-weight: 700;">{{ number_format($grandtotal) }}</td> </tr> @else <tr style="background-color: #DDDDDD;"> <td colspan="4"></td> <td align="right" style="font-weight: 700">{{ trans('messages.lbl_total') }}</td> <td align="right" style="color: blue;font-weight: 700;">{{ number_format($grandtotal) }}</td> </tr> @endif {{ $temp = ""}} {{--*/ $row = '0' /*--}} {{ $tempcomp = ""}} {{--*/ $rowcomp = '0' /*--}} {{ $tempcompany = ""}} {{--*/ $rowcompany = '0' /*--}} {{ $tempemp = ""}} {{--*/ $rowemp = '0' /*--}} {{ $tempname = ""}} {{--*/ $rowname = '0' /*--}} <?php $i=0; $style_tr=""; $style_trcomp=""; ?> @if(count($engineerdet)!="") @foreach ($engineerdet as $key => $value) {{--*/ $loc = $value->company_name /*--}} {{--*/ $loccomp = $value->quot_date /*--}} {{--*/ $loccompany = $value->company_name /*--}} {{--*/ $locempid = $value->EMPID /*--}} {{--*/ $locname = $value->LastName /*--}} @if($loc != $temp) @if($row==1) {{--*/ $style_tr = 'background-color: #E5F4F9;' /*--}} {{--*/ $row = '0' /*--}} @else {{--*/ $style_tr = 'background-color: #FFFFFF;' /*--}} {{--*/ $row = '1' /*--}} @endif {{--*/ $style_td = '' /*--}} @else {{--*/ $style_td = 'border-top: hidden;' /*--}} @endif @if($loccomp != $tempcomp) @if($rowcomp==1) {{--*/ $style_trcomp = 'background-color: #E5F4F9;' /*--}} {{--*/ $rowcomp = '0' /*--}} @else {{--*/ $style_trcomp = 'background-color: #FFFFFF;' /*--}} {{--*/ $rowcomp = '1' /*--}} @endif {{--*/ $style_tdcomp = '' /*--}} @else {{--*/ $style_tdcomp = 'border-top:hidden;' /*--}} @endif @if($loccompany != $tempcompany) @if($rowcompany==1) {{--*/ $style_trcompany = 'background-color: #E5F4F9;' /*--}} {{--*/ $rowcompany = '0' /*--}} @else {{--*/ $style_trcomp = 'background-color: #FFFFFF;' /*--}} {{--*/ $rowcompany = '1' /*--}} @endif {{--*/ $style_tdcompany = '' /*--}} @else {{--*/ $style_tdcompany = 'border-top:hidden;' /*--}} @endif @if($locempid != $tempemp) @if($rowemp==1) {{--*/ $style_tremp = 'background-color: #E5F4F9;' /*--}} {{--*/ $rowemp = '0' /*--}} @else {{--*/ $style_tremp = 'background-color: #FFFFFF;' /*--}} {{--*/ $rowemp = '1' /*--}} @endif {{--*/ $style_tdemp = '' /*--}} @else {{--*/ $style_tdemp = 'border-top:hidden;' /*--}} @endif @if($locname != $tempname) @if($rowname==1) {{--*/ $style_trname = 'background-color: #E5F4F9;' /*--}} {{--*/ $rowname = '0' /*--}} @else {{--*/ $style_trname = 'background-color: #FFFFFF;' /*--}} {{--*/ $rowname = '1' /*--}} @endif {{--*/ $style_tdname = '' /*--}} @else {{--*/ $style_tdname = 'border-top:hidden;' /*--}} @endif <tr style="{{$style_tr}}"> <td class="text-center"> {{ $key + 1 }} </td> <td class="" style="{{$style_td}}" > <div class="tac"> <label class="pm0 vam" style="color:#136E83;"> @if($loc!=$temp) {{ $value->InvoiceNo }} @endif </label> </div> </td> <td class="" style="{{$style_tdcomp}}"> <div class="tac"> @if($loccomp!=$tempcomp) {{ $value->quot_date }} @endif </div> </td> @if($request->searchmethod !="3") <td class="" style="{{$style_tdemp}}"> <div class="tac"> @if($locempid != $tempemp) {{ $value->EMPID }} @endif </div> </td> <td style="{{$style_tdname}}" @if(mb_strlen($value->LastName, 'UTF-8') > 8) title ="{{ $value->LastName }}" @endif> <a class="colbl tdn" name="namevalue" href="javascript:engineeridclick(' {{ $value->EMPID }}');" class="blue"> @if($locname!=$tempname) @if(mb_strlen($value->LastName, 'UTF-8') > 8) @php echo mb_substr($value->LastName, 0, 12, 'UTF-8')."..." @endphp @else {{ $value->LastName }} @endif @endif </a> </td> @endif <td class="" style="{{$style_tdcompany}}"> <div class="tal"> @if($loccompany!=$tempcompany) {{ $value->company_name }} @endif </div> </td> <td class=""> <div class="fll"> {{ $value->work_spec }} </div> </td> <td class="" align="right" style="padding-right: 5px;"> {{ $value->amount }} </td> </tr> {{--*/ $temp = $loc /*--}} {{--*/ $tempcomp = $loccomp /*--}} {{--*/ $tempcompany = $loccompany /*--}} {{--*/ $tempemp = $locempid /*--}} {{--*/ $tempname = $locname /*--}} @endforeach @else <tr> @if($request->searchmethod =="3") <td class="text-center fr" colspan="6"> @else <td class="text-center fr" colspan="8"> @endif {{ trans('messages.lbl_nodatafound') }}</td> </tr> @endif </tbody> </table> @if(!empty($engineerdet->total())) <div class="text-center"> <span class="pull-left mt24"> {{ $engineerdet->firstItem() }} ~ {{ $engineerdet->lastItem() }} / {{ $engineerdet->total() }} </span> {{ $engineerdet->links() }} <div class="CMN_display_block flr"> {{ $engineerdet->linkspagelimit() }} </div> </div> @endif <!-- SEARCH --> <div style="top: 136px!important;position: fixed;" @if ($request->searchmethod == 1 || $request->searchmethod == 2) class="open CMN_fixed pm0" @else class="CMN_fixed pm0 pr0" @endif id="styleSelector"> <div class="selector-toggle"> <a id="sidedesignselector" href="javascript:void(0)"></a> </div> <ul> <span> <li style=""> <p class="selector-title">{{ trans('messages.lbl_search') }}</p> </li> </span> <li class="theme-option ml6"> <div class="box100per mt5" onKeyPress="return checkSubmitsingle(event)"> {!! Form::text('singlesearch', $request->singlesearch, array('','class'=>' form-control box80per pull-left','style'=>'height:30px;','id'=>'singlesearch')) !!} {{ Form::button('<i class="fa fa-search" aria-hidden="true"></i>', array('class'=>'ml5 mt2 pull-left search box15per btn btn-info btn-sm', 'type'=>'button', 'name' => 'advsearch', 'onclick' => 'javascript:usinglesearch();', 'style'=>'border: none;' )) }} <div> </li> </ul> <div class="mt5 ml10 pull-left mb5"> <a onclick="mulclick('demo');" class="" style="font-family: arial, verdana;cursor: pointer;"> {{ trans('messages.lbl_multi_search') }} </a> </div> <div> <ul id="demo" @if ($request->searchmethod == 2) class="collapse in ml5 pull-left" @else class="collapse ml5 pull-left" @endif> <li class="theme-option" onKeyPress="return checkSubmitmulti(event)"> <div class="mt5"> <span class="pt3" style="font-family: arial, verdana;"> {{ trans('messages.lbl_employeeid') }} </span> <div class="mt5 box88per" style="display: inline-block!important;"> {!! Form::text('employeeno', $request->employeeno, array('','id' => 'employeeno','style'=>'height:30px;','class'=>'box93per ')) !!} </div> </div> <div class="mt5"> <span class="pt3" style="font-family: arial, verdana;"> {{ trans('messages.lbl_empName') }} </span> <div class="mt5 box88per" style="display: inline-block!important;"> {!! Form::text('employeename', $request->employeename, array('','id' => 'employeename','style'=>'height:30px;','class'=>'box93per ')) !!} </div> @if($request->searchmethod =="3") <div> <B>{{ trans('messages.lbl_total') }} &nbsp : &nbsp {{ number_format($grandtotal) }}</B> </div> @else <div> <B>{{ trans('messages.lbl_total') }} &nbsp : &nbsp {{ number_format($grandtotal) }}</B> </div> @endif </div> <div class="mt5 mb6"> {{ Form::button( '<i class="fa fa-search" aria-hidden="true"></i> '.trans('messages.lbl_search'), array('class'=>'mt10 btn btn-info btn-sm ', 'onclick' => 'javascript:return umultiplesearch()', 'type'=>'button')) }} </div> </li> </ul> </div> </div> {{ Form::close() }} </article> </div> @endsection
43,089
https://github.com/zhangjunfang/jstorm-0.9.6.3-/blob/master/jstorm-client/src/main/java/backtype/storm/metric/api/MultiCountMetric.java
Github Open Source
Open Source
Apache-2.0
2,015
jstorm-0.9.6.3-
zhangjunfang
Java
Code
72
243
package backtype.storm.metric.api; import backtype.storm.metric.api.IMetric; import java.util.HashMap; import java.util.Map; @SuppressWarnings({"unchecked","rawtypes"}) public class MultiCountMetric implements IMetric { Map<String, CountMetric> _value = new HashMap(); public MultiCountMetric() { } public CountMetric scope(String key) { CountMetric val = _value.get(key); if (val == null) { _value.put(key, val = new CountMetric()); } return val; } @Override public Object getValueAndReset() { Map ret = new HashMap(); for (Map.Entry<String, CountMetric> e : _value.entrySet()) { ret.put(e.getKey(), e.getValue().getValueAndReset()); } return ret; } }
29,543