language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
2,094
1.96875
2
[]
no_license
package com.aroominn.aroom.presenter.impl; import com.aroominn.aroom.base.BaseImpl; import com.aroominn.aroom.base.BasicResponse; import com.aroominn.aroom.bean.Comment; import com.aroominn.aroom.bean.HomeInfo; import com.aroominn.aroom.bean.Result; import com.aroominn.aroom.bean.Story; import com.aroominn.aroom.model.HomePageModel; import com.aroominn.aroom.model.TaleModel; import com.aroominn.aroom.model.impl.HomePageModelImpl; import com.aroominn.aroom.model.impl.TaleModelImpl; import com.aroominn.aroom.presenter.HomePagePresenter; import com.aroominn.aroom.presenter.TalePresenter; import com.aroominn.aroom.presenter.listener.OnHomePageListener; import com.aroominn.aroom.presenter.listener.OnTaleListener; import com.aroominn.aroom.view.views.HomePageView; import com.aroominn.aroom.view.views.TaleView; import org.json.JSONObject; public class TalePresenterImpl implements TalePresenter, OnTaleListener { private TaleView view; private TaleModel model; public TalePresenterImpl(TaleView view) { this.view = view; model = new TaleModelImpl(this); } @Override public void likeStory(BaseImpl context, JSONObject param) { model.loadLike(context, param); } @Override public void collocationStory(BaseImpl context, JSONObject param) { model.loadCollect(context, param); } @Override public void reportStory(BaseImpl context, JSONObject param) { model.loadReport(context, param); } @Override public void repostStory(BaseImpl context, JSONObject param) { model.loadRepost(context, param); } @Override public void commentStory(BaseImpl context, JSONObject param) { model.loadComment(context, param); } @Override public void deleteTale(BaseImpl context, JSONObject param) { model.loadDelete(context,param); } @Override public void onSuccess(Result result) { view.setTale(result); } @Override public void onError(BasicResponse response, String url) { view.showError(response, url); } }
JavaScript
UTF-8
2,759
2.90625
3
[ "MIT" ]
permissive
function initSelectors(measurements){ let names = Object.keys(measurements); var container = document.getElementById("observationsContainer"); var listItems = ""; for (let i = 0; i < names.length; i++){ let curMeasurement = filteredMeasurements[names[i]]; let numObs = Object.keys(curMeasurement).length; var currentHTML = ` <li> <a href="#" onclick="lineChart('${names[i]}')" id="selectorFor${names[i]}">${names[i]} (${numObs})</a> </li> `; listItems += currentHTML; } var html = ` <div class="btn-group"> <button type="button" class="btn btn-info btn-block dropdown-toggle" data-toggle="dropdown" id="observationSelectorBtn" aria-haspopup="true" aria-expanded="false"> Select Observation <span class="caret"></span> </button> <ul class="dropdown-menu" style="position: absolute;"> ${listItems} </ul> </div> `; var observationsDropdown = document.createElement("div"); observationsDropdown.innerHTML = html; container.appendChild(observationsDropdown); } function getFirstWords(str, numWords){ let words = str.split(" "); let firstWords = words.slice(0, numWords).join(" ").replace(",", ""); return firstWords; } function createSpiderChartSelectors(chartNames){ //build HTML var resHTML = ""; chartNames.forEach(name => { let first3Words = name.split(" ").slice(0, 3).join(" "); let button = ` <button type="button" class="btn btn-primary" onclick="initSpider('${name}')"> ${first3Words} </button> `; resHTML += button; }); //insert HTML var containerDiv = document.createElement("div"); containerDiv.innerHTML = resHTML; var container = document.getElementById("observationsContainer"); container.appendChild(containerDiv); } function lineChart(name, updatePersist=true){ //check if exist to avoid duplicate let container = document.getElementById("line"); let exists = false; container.childNodes.forEach(child => { let childName = child.id.replace("lineChart", "") .replace(/[^\w\s]/gi, ''); if (childName === name.replace(" ", "").replace(/[^\w\s]/gi, '')) { exists = true; } }); if(!exists){ new LineChart("#line", this, name, 'all', filteredMeasurements[name], 200, 700, fhir=true); initRemovalFunctionality(name, updatePersist, 'observation'); } }
C++
UTF-8
270
3.046875
3
[]
no_license
#include <iostream> //this program breaks a spell by saying Abracadabra however many times the user input using namespace std; int main() { int days , i; cin >> days; for (i = 0; i < days; i++) cout << i + 1 << " Abracadabra" << endl; return 0; }
JavaScript
UTF-8
2,505
3.21875
3
[]
no_license
(function () { var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; var upAlphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; var body = document.getElementsByTagName('body')[0]; var input = document.getElementById('input'); var buttonShorten = document.getElementById('btn_short'); var containerResults = document.getElementById('cont_result'); var arrayOfLinks = JSON.parse(localStorage.getItem('arrayOfLinks')); if (arrayOfLinks && arrayOfLinks.length > 0) { for (var i = 0; i < arrayOfLinks.length; i++) { var wrapOriginalUrl = document.createElement('div'); var wrapNewUrl = document.createElement('div'); var buttonRemove = document.createElement('button'); buttonRemove.innerHTML = 'remove'; wrapOriginalUrl.innerHTML = arrayOfLinks[i].originalLink; wrapNewUrl.innerHTML = arrayOfLinks[i].newLink; containerResults.appendChild(wrapOriginalUrl); containerResults.appendChild(wrapNewUrl); containerResults.appendChild(buttonRemove); } } buttonShorten.addEventListener('click', getNewLink); function getRandomValueFromArray(array) { var randomIndex = Math.floor(Math.random() * array.length); return array[randomIndex]; } function getNewLink() { if (!input.value) { return; } var wrapOriginalUrl = document.createElement('div'); var wrapNewUrl = document.createElement('div'); var buttonRemove = document.createElement('button'); var numberRandom = Math.floor(Math.random() * 10); var randomLowerLetter = getRandomValueFromArray(alphabet); var randomUpperLetter = getRandomValueFromArray(upAlphabet); var linkObj = { 'originalLink': input.value, 'newLink': 'http://goo.gl/' + numberRandom + randomLowerLetter + randomUpperLetter }; var arrayOfLinks = JSON.parse(localStorage.getItem('arrayOfLinks')); if (arrayOfLinks && arrayOfLinks.length > 0) { arrayOfLinks.push(linkObj); localStorage.setItem('arrayOfLinks', JSON.stringify(arrayOfLinks)); } else { localStorage.setItem('arrayOfLinks', JSON.stringify([linkObj])); } wrapOriginalUrl.innerHTML = linkObj.originalLink; wrapNewUrl.innerHTML = linkObj.newLink; buttonRemove.innerHTML = 'remove'; containerResults.appendChild(wrapOriginalUrl); containerResults.appendChild(wrapNewUrl); containerResults.appendChild(buttonRemove); } }());
Markdown
UTF-8
197
2.671875
3
[ "MIT", "CC-BY-SA-4.0" ]
permissive
# Add New Properties to a JavaScript Object You can add new properties to existing JavaScript objects the same way you would modify them. Here is how: ```javascript myDog.bark = "woof-woof"; ```
C++
UTF-8
678
3.0625
3
[ "Apache-2.0" ]
permissive
#include <proton/container.hpp> #include <proton/messaging_handler.hpp> #include <iostream> class ExampleHandler: public proton::messaging_handler { const std::string url_; void on_container_start(proton::container& c) override { c.connect(url_); } void on_connection_open(proton::connection& c) override { std::cout << "Connection to " << url_ << " is open\n"; } public: ExampleHandler(const std::string& url) : url_(url) {} }; int main() { try { auto&& h = ExampleHandler{"127.0.0.1:5672"}; proton::container(h).run(); } catch (std::exception& e) { std::cout << "Caught error: " << e.what() << "\n"; } }
Python
UTF-8
578
2.953125
3
[ "Apache-2.0" ]
permissive
def learn(db_support): print "Learning data" def learn_name(messageToBot): if(messageToBot.startswith("call me ")): return "Clarissa: Okay. I will call you "+messageToBot.replace("call me ", "") elif(messageToBot.startswith("Call me")): return "Clarissa: Okay. I will call you "+messageToBot.replace("Call me ", "") def learn_hobby(inputText): if(hobbyText.startswith("I like to ")): print "Clarissa: That's a neat hobby!" elif(hobbyText.startswith("i like to ")): print "Clarissa: That's a neat hobby!"
Shell
UTF-8
558
3.015625
3
[]
no_license
#! /bin/bash # Extracts FA information from processed data # Requires $FSLDIR to be properly set # Specify path to atlas and number of atlas regions atlasPath = /usr/local/fsl/data/atlases/JHU/JHU-ICBM-labels-1mm.nii.gz numroi = 48 for roinum in {1..$numroi}; do fslmaths atlasPath -thr $roinum -uthr $roinum -bin roimask fslmaths roimask -mas mean_FA_skeleton_mask.nii.gz -bin padroi=`$FSLDIR/bin/zeropad $roinum 3` fslmeants -i all_AD_skeletonised.nii.gz -m roimask -o ./JHU-skeletonized-AD/meants_roi${padroi}.txt done
Markdown
UTF-8
3,533
2.890625
3
[ "MIT" ]
permissive
--- title: Learning JavaScript Properly pt. 1 author: andrew date: 2013-09-14 template: article.jade --- Only a few days have passed since embarking on my mission to [learn JavaScript properly](http://javascriptissexy.com/how-to-learn-javascript-properly/). The schedule for the first two weeks was mostly review, so I was able to get through the first several chapters of my book [Professional JavaScript for Web Developers](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=dp_ob_title_bk) in a few days. I'm now on Chapter 5 and I've been going through all of the important methods for strings and arrays on [devdocs.io](http://devdocs.io/), which is a very nice looking interface for the Mozilla Dev Docs. I've been trying to spend enough time playing with each of the methods to create some muscle memory, so that I don't have to look up syntax for basic methods. The part of Chapter 5 that is going to take a little longer is the section on regular expressions. While I continue to move through the JavaScript book, I'm going to spend a little time each day working through [Zed Shaw's](http://www.zedshaw.com) book on regular expressions, called: [Learn Regex the Hard Way](http://regex.learncodethehardway.org/book/). I've also been digging into open source projects on GitHub and trying to get a feel for JavaScript formatting conventions. I really like the jQuery style of adding extra spaces inside tokens such as parentheses, braces, brackets and semicolons. I find it to be extremely easy to read, so it seems like a good style to copy for now. I'm not totally sure why this hasn't caught on more. And now for the boring stuff: I've been using SublimeText again... although I've been using it in Vintage Mode (i.e. with Vim keybindings). The only thing that I miss from *actual* Vim (vs. Vintage Mode in Sublime) is ctrl-R. Ctrl-R would allow you to type over characters without inserting new spaces. It's a very handy mode, and it's a little sad that it's not implemented in Vintage Mode. Hopefully, someone will add this little bit of functionality. Unfortunately, I'm way too busy learning JS stuff to start messing with writing Sublime plugins right now. I've also gotten with it and installed some of the more useful Sublime plugins, like [SublimeLinter](https://github.com/SublimeLinter/SublimeLinter), which makes a box around my JavaScript in realtime if there are any missing semicolons etc. And for this blog (which I write in Markdown), I installed a spellchecking plugin called [CheckBounce](https://github.com/phyllisstein/CheckBounce), which works great and keeps me from looking like an illiterate git when I inevitably make a spelling error. The last Sublime plugin I installed was [Dayle Rees Colour Schemes](https://github.com/daylerees/colour-schemes). It's a plugin that you can install with package manager that adds about 50 color schemes to your menu. There are many classics and I'm currently enjoying [Snappy Light](https://github.com/daylerees/colour-schemes/blob/master/screenshots/snappylight.png). At some point, I should make a post about some of my Sublime key bindings. Most of them won't blow any minds, but I'm pretty happy with how I have split-screen buffers mapped out. Perhaps next time... I should probably get some rest. I have another day of coding tomorrow and then I'm going to a MeetUp that I bought tickets for several weeks ago: [Full-stack Web Development with Node.js](http://www.meetup.com/codecrewny/events/136333482/).
JavaScript
UTF-8
1,641
2.515625
3
[]
no_license
var shortid = require("shortid"); var db = require("../db"); module.exports.see = function(req, res) { var page = parseInt(req.query.page) || 1; //n var perPage = 8; //x var start = (page - 1) * perPage; var end = page * perPage; var drop = (page - 1) * perPage; res.render("books/see", { //books: db.get("books").value() books: db.get('books').drop(drop).take(perPage).value() }); }; module.exports.searchBook = function(req, res){ var q = req.query.q; var matchedBooks = db.get('books').value().filter(function(book){ return book.title.toLowerCase().indexOf(q.toLowerCase()) !== -1; }); res.render('books/see', { books: matchedBooks }); }; module.exports.getAdd = function(req, res) { res.render("books/add"); }; module.exports.postAdd = function(req, res) { req.body.id = shortid.generate(); db.get("books") .push(req.body) .write(); res.render("books/see", { books: db.get("books").value() }); res.redirect("/books"); }; module.exports.update = function(req, res) { res.render("books/update"); }; module.exports.getUpdate = function(req, res) { var id = req.params.id; res.render("books/update", { id: id }); }; module.exports.postUpdate = function(req, res) { var id = req.body.id; var title = req.body.title; db.get("books") .find({ id: id }) .assign({ title: title }) .write(); res.redirect("/books/see"); }; module.exports.delete = function(req, res) { var title = req.params.title; db.get("books") .remove({ title: title }) .write(); res.render("books/see", { books: db.get("books").value() }); };
Markdown
UTF-8
7,890
2.75
3
[]
no_license
八 “洒家把你们都杀光了,这件事还有谁知道。” “你能把中原武林人全部杀光?” “中原武林算得了什么,洒家站在这里不动,看你有什么本事尽管使出来,能不能伤到洒家一根汗毛!” 商七不由大怒道:“番僧无知,你不过仗着一点气功就以为天下无敌!” 红衣喇嘛裂嘴怪道:“你怎么不试试,洒家就站在这里,绝不还手。” 商七忍无可忍,一振铁算盘正待出手,半空中突然有人接口道:“商老板,你休息一下,让我来试试这位大喇嘛的气功!” 声落人现,是扈三娘,她和楚湘玲同时出手,把无类教埋伏在暗中一批暗器高手清除后,回来正好赶上红衣喇嘛和商七的对话。 扈三娘突然从空中降落,红衣喇嘛倒是颇感意外,见到她的高大身材,更是一呆。 但这番僧脸很快的就浮起邪意,忍不住得意大笑道:“娘子好健的身材,好俊的轻功,洒家在离开西域时就已得到神明的指示……” 扈三娘不等他完,已冷冷一笑道:“你的神可是指示你,此番东来会遇上我?” 红衣喇嘛认真的点点道:“不错!洒家原是天上星宿下凡,此番东来说是为了迎接娘娘。” 扈三娘的笑意更浓,道:“你既有天神相助,在西域国的地位想必不低了!” “当然!洒家曾一度当上红衣教的教主,因受奸人所害,所以才流落东土!” “现任红衣教主是谁?” “是洒家的侄子叫雅鲁达。” “大喇嘛东来是为了夺回教主的宝座了?” “喇嘛教的教主本来就是洒家的,我因受奸害才流落在外。” “这种封疆裂土的大事,你应该到朝中去活动,怎么跑来找无类教帮忙?” “这个皇帝昏庸无能,他根本管不了边疆大事!” “你们来到关东一共有几个人?” “只有洒家一人。” “你身后这个喇嘛不是跟你一起来的?” 红衣喇嘛暗中一惊,赶忙回头看去。 可是就在他转头之际,扈三娘右手疾扬,一支银针无声无息的自他的右耳穿进,从左耳出。 这是气功练不到的地方,也是人身最脆弱的地方,银针的体积不大,但却把一个人的神经中枢整个破坏了。 红衣喇嘛中针后,身子跳起来一丈多高,但他落地后居然没有倒下,伸手指着扈三娘厉声道:“你这个贼婆娘!为什么要暗算洒家……” 扈三娘脸色一沉道:“黑天星,别人不知道你的底细,我可清楚得很!” 红衣喇嘛脸色一变道:“你这个婆娘是怎么知道洒家法号的?……” “你在教中犯了淫戒,按照喇嘛教规,犯了淫戒是该处死刑的,因为你是现任教主的叔叔,才将你关在水火洞中,希望你能悔过,准备在下次长老大会上设法为你脱罪,谁知你劣性未改,反而暗中勾结无类教,杀死四名守洞教徒,逃到关东,不到三年,你竟奸杀了两百多名良家妇女……” 黑天星不等她说完,已厉声大叫道:“贼婆娘!你怎么知道这么多?” 扈三娘冷笑一声道:“两年前在黑龙江,那个以先天剑气削去你一只耳朵的蒙面人就是我,现在你死得不算冤吧!” 黑天星大叫一声,倒地后再也不动了。 商七摇摇头道:“这个喇嘛气功练到难伤境界,幸好扈女侠来得及时!” 扈三娘苦笑道:“我假如不用夺命银针暗中出手,想杀他还真不容易!” “难道扈女侠的先天剑气也杀不了他?” 扈三娘道:“西域红衣教的气功也是属于正宗心法,我除非使用身剑合一剑术才能杀得了他,但对黑天星这样的高手,使用身剑合一,至少也要耗去三成真力,因为咱们前面还有更厉害的强敌,到时我可就没有把握!” 商七不由一惊道:“他们前面还有埋伏?” “为了拦截下老醉鬼,无类教这次出动了将近三分之一的高手!” “他们的消息倒真够快,短短两个时辰,竟然派出这么多高手!” “你们不应该放走催命郎中的,他才是一头老狐狸。” “当时刘兄杀关小月,已有脱力的现象,向卜灵是在混乱中逃跑的,咱们都没有注意……” “你们注意也没有用,催命郎中不但一肚子坏水,而在江湖中更是出了名的阴险狡诈,要想拦住他,只有一个办法!” “什么办法?” “一剑砍掉他的脑袋是最好的办法。” 商七叹了口气道:“今夜如不是扈女侠及时赶到,咱们兄弟怕有负刘兄的托付了。” “对手实力太强,是刘二白把他们估计低了。” “刘兄凭着一人一剑,连挑无类教十多处分坛,而中毒后还杀了二三十名高手,是我们兄弟太无能了……” 扈三娘突然想起一事,道:“咱们打了半天,怎么没有刘二白的动静?” 商七也是一怔,假如刘二白毒发身亡,贾八也应该回来通知,他越想越觉不对,赶忙首先朝那个岩石奔去,扈三娘也随在他身后。 二十多丈距离,几起伏就到了,可是等他们奔到近前时,只见雪地上还清晰的留着两个人卧过的印痕,除此之外,却什么也没有。 商七是亲眼看着刘二白和贾八隐身在这块岩石下面的,但人到哪里去了呢?他不由呆住当地,一时竟不知如何开口。 扈三娘看清了现场地形,也是一惊,但她经过一番冷静的分析后,忍不住冷笑一声道:“老醉鬼临死还不肯服输,他打前站先走了!” 商七显得不安道:“刘兄所剩力,连一层都不到,他怎么还能和人动手!” “也许是出现了奇迹。”扈三娘冷声道:“刘二白的个性我是清楚,他如果没有把握杀人,决不会自动找去杀人!” “可是老朽亲眼看到他毒发后,连拔剑的力气都没有。” 扈三娘见他急得团团转,反而不忍多说,想了一下道:“咱们也到前面看看去吧!就是死了也有个收尸的。” 商七怔了一下道:“扈女侠,你对刘兄好像有什么不谅解之处……” “我不谅解?你商老板对他了解多少?” “商某兄弟则在今天才认识刘兄的,而且是在他中毒以后……” 扈三娘笑笑道:“我跟刘二白是同住在一个村子里,而且从小又是在一起长大的,你认为了解程度够不够?” “商某以为刘兄不失一代大侠风范,他和无类教结梁子乃是为了朋友。” “这一点我比你更清楚,刘二白为了朋友可以两肋插刀,也可以不要命,可是……” 可是什么,她没有说出来,却偷偷的流了两滴清泪。 商七是个老江湖,虽然他也是个老光棍,但对人情世故,他毕竟懂得多,他知道扈三娘虽是女中豪杰,但她跟刘二白既是一起长大的,可能早就有了男女间的感情,可是这种事他又不便多问。 两个人默默的走着,都没有说话,速度虽然有快,但经过一阵奔行,至少也走了有二三十里,可是在途山路上却什么也没发现。 二人都是老江湖,他们很清楚这种过份的平静不是正常的现象。 楚湘玲已经完成清理工作,从后面追了上来,她靠近扈三娘两步,放低声音道:“三姨,这里的气氛好像不大对劲……” “没见到刘二叔?” “还没有,但我能感觉出,他就在咱们附近。” “在咱们附近?他为什么不肯和咱们见面?”
Shell
UTF-8
8,090
2.90625
3
[]
no_license
#!/bin/sh ########################################################### # Script that: # - Do DInSAR for each pair of SLCs. # - GAMMA scripts are used all over this scr. # Written by, # -T.LI @ ISEIS, 29/04/2013 ###################################### #!/bin/sh ########################################################### # Purpose: # Create diff-interferograms for each pair of SLC. # Calling Sequence: # ./diff_all.sh # Inputs: # None # Optinal Input Parameters: # None # Outputs: # Diff images # Commendations: # None # Modification History: # 29/04/2013: Written by T.L @ InSAR Team in SWJTU & CUHK. dem="/mnt/data_tli/Data/DEM/HKDEM/HKDem/HKDEM.dem" #原始DEM所在路径 path="/mnt/data_tli/ForExperiment/TSX_HKAirport/rslc" #裁剪之后的SLC所在路径 master="20090120" slave='20090131' masterpwr=$path/$master.rslc.pwr mslc_par=$path/$master.rslc.par MASTER=$master SLAVE=$slave M_P=${MASTER} S_P=${SLAVE} m_slc=../$M_P.rslc s_slc=../$S_P.rslc par_m=$m_slc.par par_s=$s_slc.par MS_off=$M_P-$S_P.off width=$(awk '$1 == "range_samples:" {print $2}' $mslc_par) line=$(awk '$1 == "azimuth_lines:" {print $2}' $mslc_par) type=0 format=$(awk '$1 == "image_format:" {print $2}' $mslc_par) if [ "$format"=="SCOMPLEX" ] then type=1 fi multi_look $path/$master.rslc $path/$master.rslc.par $masterpwr $masterpwr.par 1 1 if false then # Create dem_seg rm -f dem_seg des_seg.par $master.offs $master.diff_par sim_sar lookup lookup_fine gc_map $masterpwr.par - $dem.par $dem dem_seg.par dem_seg lookup 1 1 sim_sar # Use disdem_par to check dem_seg. echo -ne "$M_P-$S_P\n 0 0\n 32 32\n 64 64\n 7.0\n 0\n\n" > create_diffpar create_diff_par $masterpwr.par - $master.diff_par 1 <create_diffpar rm -f create_diffpar offset_pwrm sim_sar ave.pwr $master.diff_par $master.offs $master.snr - - offsets 2 offset_fitm $master.offs $master.snr $master.diff_par coffs coffsets - - offset_pwrm sim_sar ave.pwr $master.diff_par $master.offs $master.snr - - offsets 4 40 40 - #解算偏移量参数 width_dem=$(awk '$1 == "width:" {print $2}' dem_seg.par) width_mli=$(awk '$1 == "range_samples:" {print $2}' $mslc_par) line_mli=$(awk '$1 == "azimuth_lines:" {print $2}' $mslc_par) gc_map_fine lookup $width_dem $master.diff_par lookup_fine 1 #Fine look up table 使用偏移量参数改进lookup table geocode_back $masterpwr $width_mli lookup_fine $master.utm.rmli $width_dem - 3 0 #Geocoded pwr raspwr ave.utm.rmli $width_dem - - - - - - - ave.utm.rmli.ras ##运行第二遍的时候,吐核了 nlines_map=$(awk '$1 == "nlines:" {print $2}' dem_seg.par) col_post=$(awk '$1 == "post_north:" {print $2}' dem_seg.par) row_post=$(awk '$1 == "post_east:" {print $2}' dem_seg.par) geocode lookup_fine sim_sar $width_dem sim_sar.rdc $width_mli $line_mli 2 0 geocode lookup_fine dem_seg $width_dem $master.hgt $width - 1 0 raspwr $master.hgt $width_mli 1 0 1 1 1. .35 1 $master.ght.ras ###################################### echo -ne "$M_P-$S_P\n 0 0\n 32 32\n 64 64\n 7.0\n 0\n\n" > temp ###################################### create_offset $par_m $par_s $MS_off 1 1 1 <temp rm -f temp interf_SLC $m_slc $s_slc $par_m $par_s $MS_off $M_P-$S_P.pwr1 $M_P-$S_P.pwr2 $M_P-$S_P.int 1 1 ###################################### width=$(awk '$1 == "interferogram_width:" {print $2}' $MS_off) line=$(awk '$1 == "interferogram_azimuth_lines:" {print $2}' $MS_off) ###################################### #rasmph $M_P-$S_P.int $width 1 0 1 1 1. 0.35 1 $M_P-$S_P.int.bmp rasmph_pwr $M_P-$S_P.int $M_P-$S_P.pwr1 $width 1 1 0 1 1 1. 0.35 1 $M_P-$S_P.intandpwr.bmp base_init $par_m $par_s $MS_off $M_P-$S_P.int $M_P-$S_P.base 0 1024 1024 base_perp $M_P-$S_P.base $par_m $MS_off > $M_P-$S_P.base.perp.txt phase_sim $par_m $MS_off $M_P-$S_P.base $M_P.hgt $M_P-$S_P.sim_unw.unflt 0 0 - - phase_sim $par_m $MS_off $M_P-$S_P.base $M_P.hgt $M_P-$S_P.sim_unw.flt 1 0 - - rasrmg $M_P-$S_P.sim_unw.unflt $M_P-$S_P.pwr1 $width - - - - - - - - - - $M_P-$S_P.sim_unw.unflt.bmp rasrmg $M_P-$S_P.sim_unw.flt $M_P-$S_P.pwr1 $width - - - - - - - - - - $M_P-$S_P.sim_unw.flt.bmp ###################################### ###Subtracting the simulated unwrapped phase from the complex interferogram ###################################### echo -ne "$M_P-$S_P\n 0 0\n 64 64\n 256 256\n 7.0\n" > create_diff_parin create_diff_par $MS_off - $M_P-$S_P.diff.par 0 < create_diff_parin rm -f create_diff_parin sub_phase $M_P-$S_P.int $M_P-$S_P.sim_unw.unflt $M_P-$S_P.diff.par $M_P-$S_P.diff.int 1 0 rasmph_pwr $M_P-$S_P.diff.int $M_P-$S_P.pwr1 $width 1 1 0 1 1 1. 0.35 1 $M_P-$S_P.diff.int.pwr.bmp fi if false then ###################################### ###################################### ### Curved Earth phase trend removal("flattening") ###ph_slop_base Subtract/add interferogram flat-Earth phase trend as estimated from initial baseline ###################################### ph_slope_base $M_P-$S_P.int $par_m $MS_off $M_P-$S_P.base $M_P-$S_P.flt 1 0 #rasmph $M_P-$S_P.flt $width 1 0 1 1 1. 0.35 1 $M_P-$S_P.flt.bmp rasmph_pwr $M_P-$S_P.flt $M_P-$S_P.pwr1 $width 1 1 0 1 1 1. 0.35 1 $M_P-$S_P.fltandpwr.bmp ###################################### ###filter flattened interferogram ###################################### adf $M_P-$S_P.flt $M_P-$S_P.flt.sm1 $M_P-$S_P.sm.cc1 $width 0.3 64 adf $M_P-$S_P.flt.sm1 $M_P-$S_P.flt.sm $M_P-$S_P.sm.cc $width 0.3 32 rasmph_pwr $M_P-$S_P.flt.sm $M_P-$S_P.pwr1 $width 1 1 0 1 1 1. 0.35 1 $M_P-$S_P.fltsmpwr.bmp cc_wave $M_P-$S_P.flt $M_P-$S_P.pwr1 $M_P-$S_P.pwr2 $M_P-$S_P.cc $width 5.0 5.0 2 - - - - #rascc $M_P-$S_P.cc - $width 1 1 0 1 1 .1 .9 1. .35 1 $M_P-$S_P.cc.bmp rascc $M_P-$S_P.cc $M_P-$S_P.pwr1 $width 1 1 0 1 1 .1 .9 1. .35 1 $M_P-$S_P.ccandpwr.bmp ###################################### ###rasshd:generate raster image of DEM as shaded relief DEM ###################################### width_map=$(awk '$1 == "width:" {print $2}' dem_seg.par) nlines_map=$(awk '$1 == "nlines:" {print $2}' dem_seg.par) col_post=$(awk '$1 == "post_lat:" {print $2}' dem_seg.par) row_post=$(awk '$1 == "post_lon:" {print $2}' dem_seg.par) ###################################### ###################################### ###simulation of unwrapped topographic phase phase_sim $par_m $MS_off $M_P-$S_P.base ../$M_P.hgt $M_P-$S_P.sim_unw 0 0 - - width=$(awk '$1 == "interferogram_width:" {print $2}' $MS_off) line=$(awk '$1 == "interferogram_azimuth_lines:" {print $2}' $MS_off) ###################################### ###Subtractiing the simulated unwrapped phase from the complex interferogram ###################################### echo -ne "$M_P-$S_P\n 0 0\n 64 64\n 256 256\n 7.0\n" > create_diff_parin create_diff_par $MS_off - $M_P-$S_P.diff.par 0 < create_diff_parin rm -f create_diff_parin sub_phase $M_P-$S_P.int $M_P-$S_P.sim_unw $M_P-$S_P.diff.par $M_P-$S_P.diff.int 1 0 rasmph_pwr $M_P-$S_P.diff.int $M_P-$S_P.pwr1 $width 1 1 0 1 1 1. 0.35 1 $M_P-$S_P.diff.int.pwr.bmp fi ###################################### # Filter Differential Interferogram ###################################### adf $M_P-$S_P.diff.int $M_P-$S_P.diff.int.sm1 $M_P-$S_P.diff.sm.cc1 $width 0.5 128 adf $M_P-$S_P.diff.int.sm1 $M_P-$S_P.diff.int.sm2 $M_P-$S_P.diff.sm.cc2 $width 0.5 64 adf $M_P-$S_P.diff.int.sm2 $M_P-$S_P.diff.int.sm $M_P-$S_P.diff.sm.cc $width 0.5 rasmph_pwr $M_P-$S_P.diff.int.sm $M_P-$S_P.pwr1 $width 1 1 0 1 1 1. 0.35 1 $M_P-$S_P.diff.sm.pwr.bmp ############################################# # Unwrap Differential Flattened Interferogram ############################################# corr_flag $M_P-$S_P.diff.sm.cc $M_P-$S_P.diff.sm.flag $width 0.5 neutron $M_P-$S_P.pwr1 $M_P-$S_P.diff.sm.flag $width - - - residue $M_P-$S_P.diff.int.sm $M_P-$S_P.diff.sm.flag $width tree_cc $M_P-$S_P.diff.sm.flag $width 64 #grasses $M_P-$S_P.diff.int.sm $M_P-$S_P.diff.sm.flag $M_P-$S_P.diff.int.sm.unw $width grasses $M_P-$S_P.diff.int.sm $M_P-$S_P.diff.sm.flag $M_P-$S_P.diff.int.sm.unw $width - - - - - - rasrmg $M_P-$S_P.diff.int.sm.unw $M_P-$S_P.pwr1 $width 1 1 0 1 1 1.0 1. 0.35 .0 1 $M_P-$S_P.diff.int.sm.unw.bmp
JavaScript
UTF-8
490
3.84375
4
[]
no_license
const readlineSync = require("readline-sync"); class Circle { constructor(xPos, yPos, radius) { this.xPos = xPos; this.yPos = yPos; this.radius = radius; } get surface() { return Math.PI * (this.radius * this.radius); } move(xOffset, yOffset) { this.xPos += xOffset; this.yPos += yOffset; } } const cercle = new Circle(2, 2, 5); cercle.move(2, 2); console.log(cercle.xPos, cercle.yPos); console.log(cercle.surface);
Shell
UTF-8
2,764
4.125
4
[]
no_license
#!/bin/bash get_ack() { # https://djm.me/ask local prompt default reply while true; do if [ "${2:-}" = "Y" ]; then prompt="Y/n" default=Y elif [ "${2:-}" = "N" ]; then prompt="y/N" default=N else prompt="y/n" default= fi # Ask the question (not using "read -p" as it uses stderr not stdout) echo -n "$1 [$prompt] " # Read the answer (use /dev/tty in case stdin is redirected from somewhere else) read reply </dev/tty # Default? if [ -z "$reply" ]; then reply=$default fi # Check if the reply is valid case "$reply" in Y*|y*) return 0;; N*|n*) return 1;; esac done } echo "CheckUPS configuration for RevPi"; if [ "$EUID" -ne 0 ]; then echo "Please run as root or sudo" exit fi echo "This script assumes the configuration is saved in the same folder as this script "; echo "Required files:"; echo "- rpi_sensehat_mqtt.py"; echo "- rpi_sensehat_mqtt.logrotate"; echo "- rpi_sensehat_mqtt.env"; echo "- rpi_sensehat_mqtt.service"; if ! (get_ack "Do you want to continue?" N;) then echo "Exiting, bye!"; exit 0; fi restart_service=false; echo "Moving script files"; if test -f "./rpi_sensehat_mqtt.py"; then sudo /bin/chown -R root:root ./rpi_sensehat_mqtt.py sudo /bin/mkdir -p /etc/rpi_broadcaster/ sudo /bin/mv ./rpi_sensehat_mqtt.py /etc/rpi_broadcaster/ restart_service=true; else echo "Script files not present, skip"; fi echo "Creating log folder for rpi_broadcaster"; if test -d "/var/log/rpi_broadcaster/"; then echo "Log folder already present, skip"; else sudo /bin/mkdir -p /var/log/rpi_broadcaster/ restart_service=true; fi echo "Moving logrotate files"; if test -f "./rpi_sensehat_mqtt.logrotate"; then sudo /bin/chown -R root:root ./rpi_sensehat_mqtt.logrotate sudo /bin/mv ./rpi_sensehat_mqtt.logrotate /etc/logrotate.d/rpi_sensehat_mqtt else echo "Logrotate files not present, skip"; fi echo "Moving environment files"; if test -f "./rpi_sensehat_mqtt.env"; then sudo /bin/chown -R root:root ./rpi_sensehat_mqtt.env sudo /bin/mv ./rpi_sensehat_mqtt.env /etc/default/rpi_sensehat_mqtt restart_service=true; else echo "Environment files not present, skip"; fi echo "Moving service files"; if test -f "./rpi_sensehat_mqtt.service"; then sudo /bin/chown -R root:root ./rpi_sensehat_mqtt.service sudo /bin/mv ./rpi_sensehat_mqtt.service /lib/systemd/system/rpi_sensehat_mqtt.service restart_service=true; else echo "Service files not present, skip"; fi echo "Reload and reboot service"; if $restart_service; then sudo /bin/systemctl daemon-reload sudo /bin/systemctl enable rpi_sensehat_mqtt.service sudo /bin/systemctl restart rpi_sensehat_mqtt.service else echo "No changes to service related files, skip"; fi echo "Done";
Java
UTF-8
1,464
3.140625
3
[ "MIT" ]
permissive
package partytime; public class Topic { private String name; private int interest; private double importance; private String [] statements; // List of statements about topic private String [] replies; // List of responses public Topic(Topic t) { this.name = t.name; this.interest = t.getInterest(); this.importance = t.getImportance(); this.statements = t.statements; this.replies = t.replies; } public Topic(String t_name, String[] t_statements, String[] t_replies) { this.name = t_name; this.statements = t_statements; this.replies = t_replies; } public String getName() { return this.name; } public int getInterest() { return this.interest; } public double getImportance() { return importance; } public String getStatement(int i) { int x = i; if(i<0) x = 0; else if(i>9) x = 9; if(this.statements.length-1 < x) x = this.statements.length-1; return this.statements[x].toString(); } public String getReply(int i) { int x = i; if(i<0) x = 0; else if(i>9) x = 9; if(this.replies.length-1 < x) x = this.replies.length-1; return this.replies[x].toString(); } public void setInterest(int i) { this.interest = i; } public void setImportance(double i) { this.importance = i; } // Dependency for Person.java public void setInterestRatio(double tk) {this.interest *= tk;} }
C
GB18030
448
2.90625
3
[]
no_license
#pragma once #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> typedef int DataType; struct Node; typedef struct Node* PtrToNode; typedef PtrToNode Stack; int IsEmpty(Stack S); Stack CreatStack(); //һջ void MakeEmpty(Stack S); //ջÿ void Push(DataType x, Stack S); //ջ DataType Top(Stack S); //ջԪ void Pop(Stack S); //ջ struct Node { DataType data; PtrToNode next; };
Java
UTF-8
1,111
2.078125
2
[]
no_license
package br.edu.usj.ads.lpii.clientecrud; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.NoArgsConstructor; @Entity @NoArgsConstructor public class Contato { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column String nome; public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } @Column String endereco; public String getEndereco() { return this.endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } @Column String telefone; public String getTelefone() { return this.telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } }
PHP
UTF-8
5,662
2.671875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace backend\models; use common\models\Website; use Yii; use yii\base\Model; use yii\helpers\Html; /** * Website Contact form */ class WebsiteContactForm extends Model { public $contactTitle; public $contactDescription; public $contactMapEmbedCode; public $contactFullname; public $contactLocation; public $contactAddress; public $contactPhone; public $contactEmail; public $contactUrlSite; public $contactMetaTitle; public $contactMetaDescription; public $contactMetaKeywords; /** * @inheritdoc */ public function rules() { return [ [['contactTitle', 'contactDescription', 'contactMapEmbedCode', 'contactFullname', 'contactLocation', 'contactAddress', 'contactPhone', 'contactEmail', 'contactUrlSite', 'contactMetaTitle', 'contactMetaDescription', 'contactMetaKeywords'], 'string'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'contactTitle' => Yii::t('model', 'Заголовок'), 'contactDescription' => Yii::t('model', 'Краткий текст'), 'contactMapEmbedCode' => Yii::t('model', 'Код карты'), 'contactFullname' => Yii::t('model', 'ФИО'), 'contactLocation' => Yii::t('model', 'Локация'), 'contactAddress' => Yii::t('model', 'Адрес'), 'contactPhone' => Yii::t('model', 'Телефон'), 'contactEmail' => Yii::t('model', 'E-mail'), 'contactUrlSite' => Yii::t('model', 'Ссылка на коммерческий сайт'), 'contactMetaTitle' => Yii::t('model', 'Title'), 'contactMetaDescription' => Yii::t('model', 'Description'), 'contactMetaKeywords' => Yii::t('model', 'Keywords'), ]; } /** * Save Data. * * @return bool */ public function process() { if ($this->validate()) { $model = Website::getByParam(Website::PARAM_CONTACT_TITLE); $model->content = Html::encode($this->contactTitle); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_DESCRIPTION); $model->content = Html::encode($this->contactDescription); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_MAP_EMBED_CODE); $model->content = Html::encode($this->contactMapEmbedCode); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_FULLNAME); $model->content = Html::encode($this->contactFullname); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_LOCATION); $model->content = Html::encode($this->contactLocation); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_ADDRESS); $model->content = Html::encode($this->contactAddress); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_PHONE); $model->content = Html::encode($this->contactPhone); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_EMAIL); $model->content = Html::encode($this->contactEmail); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_URL_SITE); $model->content = Html::encode($this->contactUrlSite); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_META_TITLE); $model->content = Html::encode($this->contactMetaTitle); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_META_DESCRIPTION); $model->content = Html::encode($this->contactMetaDescription); $model->save(); $model = Website::getByParam(Website::PARAM_CONTACT_META_KEYWORDS); $model->content = Html::encode($this->contactMetaKeywords); $model->save(); return true; } return false; } /** * @return WebsiteContactForm */ public static function loadFromDb() { $form = new static(); $form->contactTitle = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_TITLE)); $form->contactDescription = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_DESCRIPTION)); $form->contactMapEmbedCode = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_MAP_EMBED_CODE)); $form->contactFullname = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_FULLNAME)); $form->contactLocation = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_LOCATION)); $form->contactAddress = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_ADDRESS)); $form->contactPhone = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_PHONE)); $form->contactEmail = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_EMAIL)); $form->contactUrlSite = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_URL_SITE)); $form->contactMetaTitle = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_META_TITLE)); $form->contactMetaDescription = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_META_DESCRIPTION)); $form->contactMetaKeywords = Html::decode(Website::getParamContent(Website::PARAM_CONTACT_META_KEYWORDS)); return $form; } }
Java
UTF-8
12,494
1.679688
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.05.28 at 11:46:26 AM WAT // package org.openmrs.module.nigeriaemr.model.ndr; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p> * Java class for RegimenType complex type. * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RegimenType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="VisitID" type="{}StringType"/> * &lt;element name="VisitDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="PrescribedRegimen" type="{}CodedSimpleType"/> * &lt;element name="PrescribedRegimenTypeCode" type="{}CodeType"/> * &lt;element name="PrescribedRegimenLineCode" type="{}CodeType" minOccurs="0"/> * &lt;element name="PrescribedRegimenDuration" type="{}CodeType"/> * &lt;element name="PrescribedRegimenDispensedDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="DateRegimenStarted" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="DateRegimenStartedDD" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="0"/> * &lt;maxLength value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="DateRegimenStartedMM" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="0"/> * &lt;maxLength value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="DateRegimenStartedYYYY" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="0"/> * &lt;maxLength value="4"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="DateRegimenEnded" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="DateRegimenEndedDD" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="0"/> * &lt;maxLength value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="DateRegimenEndedMM" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="0"/> * &lt;maxLength value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="DateRegimenEndedYYYY" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="0"/> * &lt;maxLength value="4"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RegimenType", propOrder = { "visitID", "visitDate", "prescribedRegimen", "prescribedRegimenTypeCode", "prescribedRegimenLineCode", "prescribedRegimenDuration", "prescribedRegimenDispensedDate", "dateRegimenStarted", "dateRegimenStartedDD", "dateRegimenStartedMM", "dateRegimenStartedYYYY", "dateRegimenEnded", "dateRegimenEndedDD", "dateRegimenEndedMM", "dateRegimenEndedYYYY" }) public class RegimenType { @XmlElement(name = "VisitID", required = true) protected String visitID; @XmlElement(name = "VisitDate", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar visitDate; @XmlElement(name = "PrescribedRegimen", required = true) protected CodedSimpleType prescribedRegimen; @XmlElement(name = "PrescribedRegimenTypeCode", required = true) protected String prescribedRegimenTypeCode; @XmlElement(name = "PrescribedRegimenLineCode") protected String prescribedRegimenLineCode; @XmlElement(name = "PrescribedRegimenDuration", required = true) protected String prescribedRegimenDuration; @XmlElement(name = "PrescribedRegimenDispensedDate", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar prescribedRegimenDispensedDate; @XmlElement(name = "DateRegimenStarted") @XmlSchemaType(name = "date") protected XMLGregorianCalendar dateRegimenStarted; @XmlElement(name = "DateRegimenStartedDD") protected String dateRegimenStartedDD; @XmlElement(name = "DateRegimenStartedMM") protected String dateRegimenStartedMM; @XmlElement(name = "DateRegimenStartedYYYY") protected String dateRegimenStartedYYYY; @XmlElement(name = "DateRegimenEnded") @XmlSchemaType(name = "date") protected XMLGregorianCalendar dateRegimenEnded; @XmlElement(name = "DateRegimenEndedDD") protected String dateRegimenEndedDD; @XmlElement(name = "DateRegimenEndedMM") protected String dateRegimenEndedMM; @XmlElement(name = "DateRegimenEndedYYYY") protected String dateRegimenEndedYYYY; /** * Gets the value of the visitID property. * * @return possible object is {@link String } */ public String getVisitID() { return visitID; } /** * Sets the value of the visitID property. * * @param value allowed object is {@link String } */ public void setVisitID(String value) { this.visitID = value; } /** * Gets the value of the visitDate property. * * @return possible object is {@link XMLGregorianCalendar } */ public XMLGregorianCalendar getVisitDate() { return visitDate; } /** * Sets the value of the visitDate property. * * @param value allowed object is {@link XMLGregorianCalendar } */ public void setVisitDate(XMLGregorianCalendar value) { this.visitDate = value; } /** * Gets the value of the prescribedRegimen property. * * @return possible object is {@link CodedSimpleType } */ public CodedSimpleType getPrescribedRegimen() { return prescribedRegimen; } /** * Sets the value of the prescribedRegimen property. * * @param value allowed object is {@link CodedSimpleType } */ public void setPrescribedRegimen(CodedSimpleType value) { this.prescribedRegimen = value; } /** * Gets the value of the prescribedRegimenTypeCode property. * * @return possible object is {@link String } */ public String getPrescribedRegimenTypeCode() { return prescribedRegimenTypeCode; } /** * Sets the value of the prescribedRegimenTypeCode property. * * @param value allowed object is {@link String } */ public void setPrescribedRegimenTypeCode(String value) { this.prescribedRegimenTypeCode = value; } /** * Gets the value of the prescribedRegimenLineCode property. * * @return possible object is {@link String } */ public String getPrescribedRegimenLineCode() { return prescribedRegimenLineCode; } /** * Sets the value of the prescribedRegimenLineCode property. * * @param value allowed object is {@link String } */ public void setPrescribedRegimenLineCode(String value) { this.prescribedRegimenLineCode = value; } /** * Gets the value of the prescribedRegimenDuration property. * * @return possible object is {@link String } */ public String getPrescribedRegimenDuration() { return prescribedRegimenDuration; } /** * Sets the value of the prescribedRegimenDuration property. * * @param value allowed object is {@link String } */ public void setPrescribedRegimenDuration(String value) { this.prescribedRegimenDuration = value; } /** * Gets the value of the prescribedRegimenDispensedDate property. * * @return possible object is {@link XMLGregorianCalendar } */ public XMLGregorianCalendar getPrescribedRegimenDispensedDate() { return prescribedRegimenDispensedDate; } /** * Sets the value of the prescribedRegimenDispensedDate property. * * @param value allowed object is {@link XMLGregorianCalendar } */ public void setPrescribedRegimenDispensedDate(XMLGregorianCalendar value) { this.prescribedRegimenDispensedDate = value; } /** * Gets the value of the dateRegimenStarted property. * * @return possible object is {@link XMLGregorianCalendar } */ public XMLGregorianCalendar getDateRegimenStarted() { return dateRegimenStarted; } /** * Sets the value of the dateRegimenStarted property. * * @param value allowed object is {@link XMLGregorianCalendar } */ public void setDateRegimenStarted(XMLGregorianCalendar value) { this.dateRegimenStarted = value; } /** * Gets the value of the dateRegimenStartedDD property. * * @return possible object is {@link String } */ public String getDateRegimenStartedDD() { return dateRegimenStartedDD; } /** * Sets the value of the dateRegimenStartedDD property. * * @param value allowed object is {@link String } */ public void setDateRegimenStartedDD(String value) { this.dateRegimenStartedDD = value; } /** * Gets the value of the dateRegimenStartedMM property. * * @return possible object is {@link String } */ public String getDateRegimenStartedMM() { return dateRegimenStartedMM; } /** * Sets the value of the dateRegimenStartedMM property. * * @param value allowed object is {@link String } */ public void setDateRegimenStartedMM(String value) { this.dateRegimenStartedMM = value; } /** * Gets the value of the dateRegimenStartedYYYY property. * * @return possible object is {@link String } */ public String getDateRegimenStartedYYYY() { return dateRegimenStartedYYYY; } /** * Sets the value of the dateRegimenStartedYYYY property. * * @param value allowed object is {@link String } */ public void setDateRegimenStartedYYYY(String value) { this.dateRegimenStartedYYYY = value; } /** * Gets the value of the dateRegimenEnded property. * * @return possible object is {@link XMLGregorianCalendar } */ public XMLGregorianCalendar getDateRegimenEnded() { return dateRegimenEnded; } /** * Sets the value of the dateRegimenEnded property. * * @param value allowed object is {@link XMLGregorianCalendar } */ public void setDateRegimenEnded(XMLGregorianCalendar value) { this.dateRegimenEnded = value; } /** * Gets the value of the dateRegimenEndedDD property. * * @return possible object is {@link String } */ public String getDateRegimenEndedDD() { return dateRegimenEndedDD; } /** * Sets the value of the dateRegimenEndedDD property. * * @param value allowed object is {@link String } */ public void setDateRegimenEndedDD(String value) { this.dateRegimenEndedDD = value; } /** * Gets the value of the dateRegimenEndedMM property. * * @return possible object is {@link String } */ public String getDateRegimenEndedMM() { return dateRegimenEndedMM; } /** * Sets the value of the dateRegimenEndedMM property. * * @param value allowed object is {@link String } */ public void setDateRegimenEndedMM(String value) { this.dateRegimenEndedMM = value; } /** * Gets the value of the dateRegimenEndedYYYY property. * * @return possible object is {@link String } */ public String getDateRegimenEndedYYYY() { return dateRegimenEndedYYYY; } /** * Sets the value of the dateRegimenEndedYYYY property. * * @param value allowed object is {@link String } */ public void setDateRegimenEndedYYYY(String value) { this.dateRegimenEndedYYYY = value; } }
Markdown
UTF-8
993
2.53125
3
[ "Apache-2.0" ]
permissive
```swift extension GraphQLRequest { static func getWithoutDescription(byId id: String) -> GraphQLRequest<Todo> { let operationName = "getTodo" let document = """ query getTodo($id: ID!) { \(operationName)(id: $id) { id name } } """ return GraphQLRequest<Todo>(document: document, variables: ["id": id], responseType: Todo.self, decodePath: operationName) } } ``` decode パスは `responseType`にデシリアライズするレスポンスのどの部分を指定します。 「data.getTodo」でオブジェクトをデシリアライズする操作名をTodoモデルに正常に指定する必要があります。 次に、Todo ID で Todo をクエリします ```swift Amplify.API.query(request: .getWithoutDescription(byId: "[UNIQUE_ID]")) { // result を処理する ```
Markdown
UTF-8
1,887
2.90625
3
[]
no_license
# Configure IFTTT to Send Alert Our final step for this app is to send meaningful alerts to an external source - email, text, etc - letting us know that the trains r fucked. There are many ways to achieve this, but we will specifically look into integrating with the [IFTTT Maker Webhook API](https://ifttt.com/maker_webhooks) which lets **us** make a call to IFTTT whenever we feel like it. IFTTT, short for [If This Then That](https://ifttt.com/), is a service that allows users to chain together triggers and actions without having to write any code. The Maker Webhook can act as a trigger which we can then use to send ourselves a text or email. ## Set up code to trigger IFTTT Take the `filter_by_lines` function and call it for the subway line(s) you use most often / will need to get home tonight. Then: 1. Determine if any of the lines you filtered by are delayed. 2. If any of the lines you care about **are** delayed, trigger a **POST** request to the IFTTT Maker Webhook endpoint with the names of the lines that are delayed. 3. Configure IFTTT to send a text or email if trigger is received. 4. Test your code and ensure that it works! (Note, I purposefully skimped on documentation here - it's important to be able to sniff out the correct docs for tasks on your own as you mature in your programming background! Goodluck!) ## BACKGROUND: Drawbacks The main drawback to this technique is that if your computer is turned off or PyCharm is closed...nothing happens. To circumvent this, we can upload our code to **pythonanywhere**, which will run our code on the cloud. Look through pythonanywhere docs to see if there is an easy way to upload a PyCharm project to it. You can also set up your code in pythonanywhere to run every hour or every 30 mins via something called a **CRON** job which means you can get more "real-time" notifications of subway slowdowns.
Python
UTF-8
1,820
4.1875
4
[]
no_license
""" Numpy Basics: It provides a high performance multidimensional array object, and tools for working with these arrays [1]. It provides option as: [2]. Less Memory optimized [3]. Fast performance [4]. Convenient and easy to use """ import numpy as np import matplotlib.pyplot as plt arr = np.array([(1, 2, 3, 4, 5), (4, 5, 6, 7, 8)]) # Find dimension of an array print("Dimension:", arr.ndim) # Find byte size of each element print("Byte size:", arr.itemsize) # Find data type of each element print("Data type:", arr.dtype) # Array size print("Array size:", arr.size) # Array shape (Cols * Rows) print("Array shape:", arr.shape) # Re Array shape arr = arr.reshape(5, 2) print("Re Array shape:", arr.shape) arr = arr.reshape(2, 5) # Slicing array arr = np.array([('R1C1', 'R1C2', 'R1C3', 'R1C4', 'R1C5'), ('R2C1', 'R2C2', 'R2C3', 'R2C4', 'R2C5'), ('R3C1', 'R3C2', 'R3C3', 'R3C4', 'R3C5'), ('R4C1', 'R4C2', 'R4C3', 'R4C4', 'R4C5')]) print(arr[0:8, :0]) # array operations arr1 = np.array([(11, 12, 13), (14, 15, 16), (17, 18, 19)]) arr2 = np.array([(21, 22, 23), (24, 25, 26), (27, 28, 29)]) # array sum print(arr1 + arr2) # array mul print(arr1 * arr2) # array sub print(arr2 - arr1) # print mod print(arr1 / arr2) # square root print(np.sqrt(arr1)) # standard deviation print(np.std(arr1)) # Special functions arrX = np.arange(0, 3*np.pi, 0.1) arrSin = np.sin(arrX) plt.plot(arrX, arrSin) plt.show() # Cosine arrCos = np.cos(arrX) plt.plot(arrX, arrCos) plt.show() # tan ... arrTan = np.tan(arrX) plt.plot(arrX, arrTan) plt.show() arrSpec = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)]) # Exponential print(np.exp(arrSpec)) # log module print(np.log(arrSpec)) # Advanced ar = np.arange(12).reshape(3, 4) print(ar)
Python
UTF-8
872
2.9375
3
[]
no_license
#pip install speechrecognition #brew install portaudio #pip install pyaudio import speech_recognition as SRG import time import textblob list = [] store = SRG.Recognizer() with SRG.Microphone() as s: print("Speak....") audio_input = store.record(s, duration=5) print("Recording time:",time.strftime("%I:%M:%S")) try: text_output = store.recognize_google(audio_input) print("Text converted from audio:\n") print(text_output) #list.append(text_output) print("Finished") print("Execution time :", time.strftime("%I:%M:%S")) except: print("Couldn't process the audio input") from textblob import TextBlob print("Score",TextBlob(text_output).sentiment.polarity) if TextBlob(text_output).sentiment.polarity > 0.5: print("Positive") else: print("Negative")
PHP
UTF-8
197
2.875
3
[]
no_license
<?php //Turns text into html entities if ($_SERVER['REQUEST_METHOD'] === 'POST') { if(isset($_POST["msg"])) { $altered_msg = htmlentities($_POST["msg"]); echo $altered_msg; } } ?>
Rust
UTF-8
2,369
2.59375
3
[ "Apache-2.0" ]
permissive
use schema_core::{ commands::DiagnoseMigrationHistoryOutput, commands::{diagnose_migration_history, DiagnoseMigrationHistoryInput}, schema_connector::SchemaConnector, CoreError, CoreResult, }; use tempfile::TempDir; #[must_use = "This struct does nothing on its own. See DiagnoseMigrationHistory::send()"] pub struct DiagnoseMigrationHistory<'a> { api: &'a mut dyn SchemaConnector, migrations_directory: &'a TempDir, opt_in_to_shadow_database: bool, } impl<'a> DiagnoseMigrationHistory<'a> { pub fn new(api: &'a mut dyn SchemaConnector, migrations_directory: &'a TempDir) -> Self { DiagnoseMigrationHistory { api, migrations_directory, opt_in_to_shadow_database: false, } } pub fn opt_in_to_shadow_database(mut self, opt_in_to_shadow_database: bool) -> Self { self.opt_in_to_shadow_database = opt_in_to_shadow_database; self } pub async fn send(self) -> CoreResult<DiagnoseMigrationHistoryAssertions<'a>> { let output = diagnose_migration_history( DiagnoseMigrationHistoryInput { migrations_directory_path: self.migrations_directory.path().to_str().unwrap().to_owned(), opt_in_to_shadow_database: self.opt_in_to_shadow_database, }, None, self.api, ) .await?; Ok(DiagnoseMigrationHistoryAssertions { output, _migrations_directory: self.migrations_directory, }) } #[track_caller] pub fn send_sync(self) -> DiagnoseMigrationHistoryAssertions<'a> { test_setup::runtime::run_with_thread_local_runtime(self.send()).unwrap() } #[track_caller] pub fn send_unwrap_err(self) -> CoreError { test_setup::runtime::run_with_thread_local_runtime(self.send()).unwrap_err() } } pub struct DiagnoseMigrationHistoryAssertions<'a> { output: DiagnoseMigrationHistoryOutput, _migrations_directory: &'a TempDir, } impl std::fmt::Debug for DiagnoseMigrationHistoryAssertions<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DiagnoseMigrationHistoryAssertions {{ .. }}") } } impl<'a> DiagnoseMigrationHistoryAssertions<'a> { pub fn into_output(self) -> DiagnoseMigrationHistoryOutput { self.output } }
Java
UTF-8
197
1.578125
2
[]
no_license
package com.gdw.afn02; import com.gdw.afn01.AbstractAfn01; import com.gdw.annotation.Item; /** * 退出登录 */ @Item(name = "退出登录", fn = 2) public class F2 extends AbstractAfn01 { }
C#
UTF-8
832
2.859375
3
[]
no_license
using Sirenix.OdinInspector; using UnityEngine; namespace Kit.Behaviours { /// <summary>Move the <see cref="Transform" /> in a given direction.</summary> public class MoveInDirection: MonoBehaviour { /// <summary>Direction to move in.</summary> [ShowInInspector] [PropertyTooltip("Direction to move in.")] public Vector3 Direction { get => direction; set => direction = value.normalized; } /// <summary>The speed at which to move.</summary> [Tooltip("The speed at which to move.")] public float Speed = 5.0f; [SerializeField] [HideInInspector] protected Vector3 direction = Vector3.up; protected new Transform transform; private void Awake() { transform = base.transform; } protected virtual void Update() { transform.Translate(direction * (Speed * Time.deltaTime)); } } }
Java
UTF-8
1,677
1.828125
2
[]
no_license
package com.oop.service; import java.util.Date; import java.util.List; import com.oop.model.AppointmentModel; import com.oop.model.UserAppointmentModel; import com.oop.model.UserModel; import com.oop.model.VehicleModel; public interface AppointmentServices { public AppointmentModel createAppointment(String userId , String vehi_NO, Date AppointDate, String vehiBrand, String vehiModel, String vehiTransmission, String vehiFuel, String vehEngine, int vehiYear, String serviceID, String appointTime, String packID, int appointDay); public UserModel GetUserById(String userId); public VehicleModel getVehicleByAppointmentId(String appId); public AppointmentModel UpdateAppointment(String appoint_No, String vehi_no, String brand, String model, String transmission, String fuel, String date, String time, String pack, String Service); public List<AppointmentModel> getPendingAppointments(); public void assignMechanic(String appointment, String assignrdMec); public void SetRemarksToAppointment(String appointment, String remark); public void Changestatus(String appointment, String status); public void delelteRequest(String appointment, String vehicle); public List<AppointmentModel> getAllAppointments(); public List<AppointmentModel> SearchAdvanceAppointments( String appId , String userRegNo, String vehicleI_No, String amount, String service_id, String status, String prefDate); public AppointmentModel getAppointmentByAppID(String appointmentID); public List<UserAppointmentModel> getUserWithAppointment(); public void Setrating(int rating, String appointmentID); public void Addfeedback(String fullFeed, String appointID); }
Swift
UTF-8
2,270
2.875
3
[ "MIT" ]
permissive
// // Binding.swift // SwiftBindings // // Created by bakaneko on 21/11/2014. // Copyright (c) 2014 nekonyan. All rights reserved. // import Foundation import ObjectiveC let bindingContext = UnsafeMutablePointer<()>() /** * Swift-based basic 2-way binding. */ public class BasicBinding<T: Equatable, O1: MutableObservable, O2: MutableObservable, V: AnyValueChange where O1.ValueType == T, O2.ValueType == T, V.ValueType == T, O1.ObservedValueChange == V, O2.ObservedValueChange == V>: AnyBinding { typealias SourceType = T typealias TargetType = T typealias SourceObservableType = O1 typealias TargetObservableType = O2 typealias ObservedValueChange = V var source: O1 var target: O2 var ss: EventSubscription<ObservedValueChange>? var st: EventSubscription<ObservedValueChange>? public init(_ source: SourceObservableType, _ target: TargetObservableType) { self.source = source self.target = target self.target.value = self.source.value // initialize target value to source value. self.ss = self.source.subscribe(ValueChangeType.After, sourceObserver) self.st = self.target.subscribe(.After, targetObserver) } func sourceObserver(change: SourceObservableType.ObservedValueChange) { // debugPrintln("changing \(change.oldValue) to \(change.newValue), source: \(source.value)") if target.value != change.newValue { target.value = change.newValue } } func targetObserver(change: TargetObservableType.ObservedValueChange) { // debugPrintln("changing \(change.oldValue) to \(change.newValue), target: \(target.value)") if source.value != change.newValue { source.value = change.newValue } } public func unbind() { if let sub = ss { self.source -= sub } if let sub = st { self.target -= sub } } deinit { unbind() } } public class EquivalentClassBinding<T: Equatable, O: MutableObservable, V: AnyValueChange where O.ValueType == T, V.ValueType == T, O.ObservedValueChange == V> : BasicBinding<T, O, O, V> { override public init(_ source: O, _ target: O) { super.init(source, target) } }
Python
UTF-8
6,058
3
3
[]
no_license
# 导入并行调度模块 import random import rpc # 导入Object Stream模块 import network class Sum(rpc.AbsSimpleExecutor): def __init__(self, node_id: int, working_group: set, initializer_id): """ 构造函数接收的参数是固定的,无法增加新的参数,所需的其他数据要依赖 requests 方法在构造后请求。 :param node_id: 指示当前 Executor 在哪个 Worker 上 :param working_group: 指示当前 Executor 从属于哪个工作组,集合内包含了本组 所有节点的id。 :param initializer_id: 指示当前发起任务的 Coordinator 的ID """ super().__init__(node_id, working_group, initializer_id) # 预留 data 变量 self.__data = None def requests(self) -> list: """ Worker 的 Request 列表,返回Worker所需的数据类别, Coordinator通过Worker ID和请求类别决定给该Worker返回 什么数据。 :return: List[object] 类型。用于标志 Worker 需要什么数据。 """ return ["Numbers"] def satisfy(self, reply: list) -> list: """ 处理从 Coordinator 返回的 Replies ,在网速良好且 Worker 数目不多的 情况下, Replies 是批量打包返回的。 :param reply: List[IReplyPackage] 类型,为 Coordinator 依照 Request 请求 逐条确认返回的数据。数据确保完好送达或未送达,不会送达损坏的数据。 :return: List[object] 类型,函数返回尚未从此次 Replies 获取到的数据,用于 通知 Coordinator 本 Worker 尚未收到哪些数据。 """ # 使用 for 循环逐个处理 for rep in reply: # 因为 word count 只有一种类别的数据,直接赋值 self.__data = rep.content() # 没有所需的额外数据了。 return [] def ready(self) -> bool: """ 向 Worker 确认是否可以开始执行。 每次批量接收 replies 后都会调用该方法确认 Executor 是否可以正常执行了。 :return: Bool型 """ return self.__data is not None def run(self, com: rpc.Communication) -> object: """ 具体任务的执行流程。 :param com: rpc 提供的内核调度机制,可以控制进度和切换调度线程,或者处理 来自Coordinator的调度信号,终止执行流程。 :return: 返回任意类型,如果该节点不需要报告结果,返回None。 该返回值可以使用 Coordinator 中的 join 方法接收。 """ # 建字典 sum = 0 # 逐行检查 for number in self.__data: sum += number # 返回不重复的单词数目 return sum if __name__ == '__main__': # 添加一个ip作为Worker nodes = network.NodeAssignment() # 分配 Worker 的 ID 和 IP 地址 # ID 为整型,不可重复,不可占用内部ID # 这里添加了一个ID为0的Worker,地址为127.0.0.1 nodes.add(0, '127.0.0.1') # 可以添加更多的Worker # 请求类 net = network.Request() # 生成一千个随机数 rnd = random.Random() numbers = [rnd.random() for i in range(1000)] # 获取当前已经添加的Node数目 node_cnt = len(nodes) # 算一下每个节点能分到多少数据 numbers_per_node = len(numbers) // node_cnt # 配置数据集分发逻辑 # dispatch_map 参数接收一个 Callable Object, # 满足参数类型为 (int, object) 返回值为 (IReplyPackage) # resource_dispatch 部分为强类型约束的,需要对类型进行声明。 # 关于 Python3 的类型约束 # 参考 pep-0484 : https://www.python.org/dev/peps/pep-0484/ def dispatch(node_id: int, request: object) -> rpc.ReplyPackage: """ Dispatch 函数 :param node_id: 忽略掉了 node_id 参数。该参数为节点 id 信息,为 int 型。 :param request: 请求的类型,即 Sum 类中 requests 的返回值。 注意:这里 request 不是一个列表,是逐条确认的。 :return: 返回 IReplyPackage 类型,将由 Coordinator 回复给 Worker 并确认。 # 可以自定义返回值类型,返回值需要实现 IReplyPackage 接口。 # 这里我们没有用自定义类型,而是使用默认的 ReplyPackage 来包装我们的数据, # 使用自定义类型可以实现一些预操作,但是意义不大。 """ if request == "Numbers": numbers_for_this_node = numbers[node_id * numbers_per_node: (node_id + 1) * numbers_per_node] return rpc.ReplyPackage(numbers_for_this_node) else: return rpc.ReplyPackage(None) # 发起一个请求 # 如果客户端已经启动了,则可以直接提交,无需将代码更新至客户端。 with net.request(nodes) as req: # 在请求的集群上创建一个协调者 master = rpc.Coordinator(req) # 提交任务 master.submit_group(Sum, package_size=18000) # 注册数据分发函数 master.resources_dispatch(dispatch_map=dispatch) # 等待执行完成 # 返回值为两个,第一个元素是执行结果,第二个元素代表执行过程中是否报错 # 返回每个Worker上的最终执行结果,Worker不区分主从,全部按照id排序。 # 以dict()形式组织:Key为Worker id,Value为返回值。 res, err = master.join() if not err: # 汇总结果 reduce = 0 for node_id in res: reduce += res[node_id] print("We have the result:\t{}.".format(reduce)) else: print("Ops, there was an error during execution.")
PHP
UTF-8
341
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use yii\base\Model; /** * Class Route * @package old_backend\models */ class Route extends Model { /** * @var string Route value. */ public $route; /** * @inheritdoc */ public function rules() { return [ [['route'], 'safe'], ]; } }
Markdown
UTF-8
913
2.765625
3
[]
no_license
--- layout: post title: "github Permission denied (publickey)" date: 2018-11-01 17:19:44 +0800 comments: true categories: technology keywords: Permission denied --- 今天重新生成了github的ssh key,添加完以后发现提示 ``` ssh git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. ``` 然后查了一下资料,因为我在创建的时候给文件输入了个名字 ``` ssh Generating public/private rsa key pair. Enter file in which to save the key (/Users/murphy/.ssh/id_rsa): github ``` 可以通过``ssh-add ~/.ssh/your_file_name``的方式解决。 也可以在 ~/.ssh/ 目录下编辑config配置文件 ``` vi config Host github.com HostName github.com User git IdentityFile ~/.ssh/github_rsa ``` User 就是用户名 最后验证一下 ```ssh -T git@github.com```
C
UTF-8
333
3.609375
4
[]
no_license
#include "holberton.h" /** * _strcmp - compares two strings. * * @s1: first string. * @s2: second string. * Return: Always 0. */ int _strcmp(char *s1, char *s2) { int result; int i = 0; while (s1[i] == s2[i]) { if (s1[i] == '\0' && s2[i] == '\0') { break; } i++; } result = s1[i] - s2[i]; return (result); }
JavaScript
UTF-8
1,690
2.8125
3
[ "MIT" ]
permissive
// Read data from the filtered selection made bu the user // and render as a table d3.csv("../resources/filter/summaryData.csv", function(error, data) { if (error) throw error; var sortAscending = true; var table = d3.select('#page-wrap').append('table'); var titles = d3.keys(data[0]); var headers = table.append('thead').append('tr') .selectAll('th') .data(titles).enter() .append('th') .text(function (d) { return d; }) .on('click', function (d) { headers.attr('class', 'header'); if (sortAscending) { rows.sort(function(a, b) { return b[d] < a[d]; }); sortAscending = false; this.className = 'aes'; } else { rows.sort(function(a, b) { return b[d] > a[d]; }); sortAscending = true; this.className = 'des'; } }); var rows = table.append('tbody').selectAll('tr') .data(data).enter() .append('tr'); rows.selectAll('td') .data(function (d) { return titles.map(function (k) { return { 'value': d[k], 'name': k}; }); }).enter() .append('td') .attr('data-th', function (d) { return d.name; }) .text(function (d) { return d.value; }); });
JavaScript
UTF-8
3,166
4.53125
5
[]
no_license
/* The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the k-th integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer. Example 1: Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. Example 2: Input: lo = 1, hi = 1, k = 1 Output: 1 Example 3: Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7. Example 4: Input: lo = 10, hi = 20, k = 5 Output: 13 Example 5: Input: lo = 1, hi = 1000, k = 777 Output: 570 Constraints: 1 <= lo <= hi <= 1000 1 <= k <= hi - lo + 1 */ /** * @param {number} lo * @param {number} hi * @param {number} k * @return {number} lo: 2 hi: 7 [2, 3, 4, 5, 6, 7] => [1, 7, 2, 5, 8, 8] sorted by power is: [2, 4, 5, 3, 6, 7] k: 3 return 5 */ var getKth = function(lo, hi, k) { //create the list of values and their power var values = []; //step 1: create an array to push each pair to for (var i = lo; i <= hi; i++) { //step 2: run each x through a find power function //step 3: push {val: x, pow: power} to the array values.push({ val: i, pow: getPower(i) }) } //sort array by power in ascending (1 lowest) values.sort(function(a, b) { if (a.pow > b.pow) { return 1; } else if (a.pow < b.pow) { return -1; } else { //if two have the same power, sort by ascending values if (a.val > b.val) { return 1; } else { return -1; } } }) //return the kth value in the sorted list (array[k - 1].val) return values[k - 1].val }; var getPower = function(x) { //count how many steps I go thru to get to 1 //create a counter variable var steps = 0; //while x > 1 while (x > 1) { //if x is even, divide by two and increment counter if (x % 2 === 0) { x = x / 2; steps++; } else { //if x is odd, multiply by three and add one, increment counter x = (x * 3) + 1; steps++; } } return steps }
Java
UTF-8
9,906
1.84375
2
[]
no_license
package net.richardsprojects.teamod.main; import org.apache.logging.log4j.Logger; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.VillagerRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.WeightedRandomChestContent; import net.minecraftforge.common.ChestGenHooks; import net.minecraftforge.common.MinecraftForge; import net.richardsprojects.teamod.entity.CoffeeBushEntity; import net.richardsprojects.teamod.entity.EmptyCupEntity; import net.richardsprojects.teamod.entity.FullCoffeeCupEntity; import net.richardsprojects.teamod.entity.FullTeaCupEntity; import net.richardsprojects.teamod.entity.HalfCoffeeCupEntity; import net.richardsprojects.teamod.entity.HalfTeaCupEntity; import net.richardsprojects.teamod.entity.MortarAndPestleEntity; import net.richardsprojects.teamod.entity.TableLeftEntity; import net.richardsprojects.teamod.entity.TableRightEntity; import net.richardsprojects.teamod.entity.TeaBushEntity; import net.richardsprojects.teamod.lib.Strings; import net.richardsprojects.teamod.render.CoffeeBushRenderer; import net.richardsprojects.teamod.render.EmptyCupRenderer; import net.richardsprojects.teamod.render.FullCoffeeCupRenderer; import net.richardsprojects.teamod.render.FullTeaCupRenderer; import net.richardsprojects.teamod.render.HalfCoffeeCupRenderer; import net.richardsprojects.teamod.render.HalfTeaCupRenderer; import net.richardsprojects.teamod.render.MortarAndPestleRenderer; import net.richardsprojects.teamod.render.TableLeftRenderer; import net.richardsprojects.teamod.render.TableRightRenderer; import net.richardsprojects.teamod.render.TeaBushRenderer; @Mod(modid=Strings.MODID, name=Strings.MOD_NAME, version=Strings.VERSION) public class TeaMod { public static CreativeTabs teaModTab = new CreativeTabs("mainTab") { @SideOnly(Side.CLIENT) public Item getTabIconItem() { return ItemCoffeeBeans.roastedBean; } }; public static Logger logger; // The instance of your mod that Forge uses. @Instance("TeaMod") public static TeaMod instance; @EventHandler public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); registerBlocksAndItems(); registerTileEntities(); //Add Spawns to Chests - trying to keep lines under 80 characters. WeightedRandomChestContent chestContent1; ItemStack coffee = new ItemStack(ItemCoffeeBeans.roastedBean); chestContent1 = new WeightedRandomChestContent(coffee, 5, 24, 065); ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(chestContent1); WeightedRandomChestContent chestContent2; ItemStack teaLeaves = new ItemStack(ItemTeaLeaves.teaLeaves); chestContent2 = new WeightedRandomChestContent(teaLeaves, 5, 24, 065); ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(chestContent2); //Mineshafts ItemStack coffeeSeed = new ItemStack(ItemCoffeeBeans.unroastedBean); WeightedRandomChestContent chest1; chest1 = new WeightedRandomChestContent(coffeeSeed, 2, 5, 065); ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(chest1); WeightedRandomChestContent chest2; ItemStack teaSeeds = new ItemStack(ItemTeaSeeds.teaSeeds); chest2 = new WeightedRandomChestContent(teaSeeds, 2, 5, 065); ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(chest2); //Add Custom Trades for farmer TradeHandler th = new TradeHandler(); VillagerRegistry.instance().registerVillageTradeHandler(0, th); //Setup Events MinecraftForge.EVENT_BUS.register(new MCForgeModEvents()); FMLCommonHandler.instance().bus().register(new FMLModEvents()); addRecipes(); } @EventHandler @SideOnly(Side.CLIENT) public void loadClient(FMLInitializationEvent event) { //Setup Renderers - Client side only ClientRegistry.bindTileEntitySpecialRenderer(FullCoffeeCupEntity.class, new FullCoffeeCupRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(HalfCoffeeCupEntity.class, new HalfCoffeeCupRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(EmptyCupEntity.class, new EmptyCupRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(CoffeeBushEntity.class, new CoffeeBushRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(HalfTeaCupEntity.class, new HalfTeaCupRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(FullTeaCupEntity.class, new FullTeaCupRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(TeaBushEntity.class, new TeaBushRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(MortarAndPestleEntity.class, new MortarAndPestleRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(TableRightEntity.class, new TableRightRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(TableLeftEntity.class, new TableLeftRenderer()); } @EventHandler public void init(FMLInitializationEvent event) { //Register World Generator GameRegistry.registerWorldGenerator(new BushWorldGenerator(), 0); } private void registerBlocksAndItems() { BlockFullCoffeeCup.mainRegistry(); BlockHalfCoffeeCup.mainRegistry(); BlockEmptyCup.mainRegistry(); BlockCoffeeBush.mainRegistry(); BlockFullTeaCup.mainRegistry(); BlockHalfTeaCup.mainRegistry(); BlockHalfCoffeeCupSugar.mainRegistry(); BlockFullCoffeeCupSugar.mainRegistry(); BlockTeaBush.mainRegistry(); BlockMortarAndPestle.mainRegistry(); ItemCoffeeCup.mainRegistry(); ItemCoffeeCupSugar.mainRegistry(); ItemTeaCup.mainRegistry(); ItemWaterCup.mainRegistry(); ItemBoilingWaterCup.mainRegistry(); ItemEmptyCup.mainRegistry(); ItemClayCup.mainRegistry(); ItemCoffeeBeans.mainRegistry(); ItemCoffeeGrounds.mainRegistry(); ItemMortarAndPestle.mainRegistry(); ItemTeaSeeds.mainRegistry(); ItemTeaLeaves.mainRegistry(); ItemGroundTeaLeaves.mainRegistry(); BlockTableLeft.mainRegistry(); BlockTableRight.mainRegistry(); ItemCoffeeTable.mainRegistry(); //Add Seeds MinecraftForge.addGrassSeed(new ItemStack(ItemCoffeeBeans.unroastedBean, 1), 5); MinecraftForge.addGrassSeed(new ItemStack(ItemTeaSeeds.teaSeeds, 1), 5); } private void registerTileEntities() { GameRegistry.registerTileEntity(FullCoffeeCupEntity.class, "fullCoffeeCup"); GameRegistry.registerTileEntity(HalfCoffeeCupEntity.class, "halfCoffeeCup"); GameRegistry.registerTileEntity(EmptyCupEntity.class, "emptyCup"); GameRegistry.registerTileEntity(CoffeeBushEntity.class, "coffeeBush"); GameRegistry.registerTileEntity(HalfTeaCupEntity.class, "halfTeaCup"); GameRegistry.registerTileEntity(FullTeaCupEntity.class, "fullTeaCup"); GameRegistry.registerTileEntity(TeaBushEntity.class, "teaBush"); GameRegistry.registerTileEntity(MortarAndPestleEntity.class, "mortarAndPestleEntity"); GameRegistry.registerTileEntity(TableLeftEntity.class, "coffeeTableLeft"); GameRegistry.registerTileEntity(TableRightEntity.class, "coffeeTableRight"); } private void addRecipes() { //Smelting Recipe(s) GameRegistry.addSmelting(ItemCoffeeBeans.unroastedBean, new ItemStack(ItemCoffeeBeans.roastedBean, 1), 0.5f); GameRegistry.addSmelting(ItemClayCup.clayCup, new ItemStack(ItemEmptyCup.emptyCup, 1), 0.0f); GameRegistry.addSmelting(ItemWaterCup.waterCup, new ItemStack(ItemBoilingWaterCup.boilingWaterCup, 1), 0.99f); //Coffee Grounds Recipe final int WILDCARD_VALUE = Short.MAX_VALUE; GameRegistry.addShapelessRecipe(new ItemStack(ItemCoffeeGrounds.coffeeGrounds), new ItemStack(ItemCoffeeBeans.roastedBean), new ItemStack(ItemMortarAndPestle.mortarAndPestle, 1, WILDCARD_VALUE)); //Ground Tea Leaves GameRegistry.addShapelessRecipe(new ItemStack(ItemGroundTeaLeaves.groundTeaLeaves), new ItemStack(ItemTeaLeaves.teaLeaves), new ItemStack(ItemMortarAndPestle.mortarAndPestle, 1, WILDCARD_VALUE)); //Add Coffee Recipe GameRegistry.addRecipe(new ItemStack(ItemCoffeeCup.fullCoffeeCup), "xxx", "xyx", "xxx", 'x', new ItemStack(ItemCoffeeGrounds.coffeeGrounds, 1), 'y', new ItemStack(ItemBoilingWaterCup.boilingWaterCup, 1)); //Add Mortar And Pestle Recipe GameRegistry.addRecipe(new ItemStack(ItemMortarAndPestle.mortarAndPestle), " x", "yxy", " y ", 'x', new ItemStack(Items.iron_ingot, 1), 'y', new ItemStack(Blocks.stone, 1)); //Empty Cup Recipe GameRegistry.addRecipe(new ItemStack(ItemClayCup.clayCup), " ", "x x", " x ", 'x', new ItemStack(Items.clay_ball, 1)); //Add Tea Recipe GameRegistry.addRecipe(new ItemStack(ItemTeaCup.fullTeaCup), "xxx", "xyx", "xxx", 'x', new ItemStack(ItemGroundTeaLeaves.groundTeaLeaves, 1), 'y', new ItemStack(ItemBoilingWaterCup.boilingWaterCup, 1)); //Coffee with Sugar GameRegistry.addRecipe(new ItemStack(ItemCoffeeCupSugar.fullCoffeeCupSugar), "xxx", "xyx", "xxx", 'x', new ItemStack(Items.sugar, 1), 'y', new ItemStack(ItemCoffeeCup.fullCoffeeCup, 1)); } }
Java
UTF-8
2,578
2.59375
3
[]
no_license
package com.ssafy.edu.vue.dto; import java.io.Serializable; //com.ssafy.edu.vue.dto.EmployeeDto public class EmployeeDto implements Serializable { private int id; private String name; private String mailid; private String start_date; private int manager_id; private String title; private int dept_id; private double salary; private double commission_pct=0.0; public EmployeeDto() {} public EmployeeDto(int id, String name, String mailid, String start_date, int manager_id, String title, int dept_id, double salary, double commission_pct) { super(); this.id = id; this.name = name; this.mailid = mailid; this.start_date = start_date; this.manager_id = manager_id; this.title = title; this.dept_id = dept_id; this.salary = salary; this.commission_pct = commission_pct; } @Override public String toString() { return "EmployeeDto [id=" + id + ", name=" + name + ", mailid=" + mailid + ", start_date=" + start_date + ", manager_id=" + manager_id + ", title=" + title + ", dept_id=" + dept_id + ", salary=" + salary + ", commission_pct=" + commission_pct + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMailid() { return mailid; } public void setMailid(String mailid) { this.mailid = mailid; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public int getManager_id() { return manager_id; } public void setManager_id(int manager_id) { this.manager_id = manager_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getDept_id() { return dept_id; } public void setDept_id(int dept_id) { this.dept_id = dept_id; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public double getCommission_pct() { return commission_pct; } public void setCommission_pct(double commission_pct) { this.commission_pct = commission_pct; } } /* id DECIMAL(7) NOT NULL, name VARCHAR(25) NOT NULL, mailid VARCHAR(8), start_date DATE, manager_id DECIMAL(7), title VARCHAR(25), dept_id DECIMAL(7), salary DECIMAL(11, 2), commission_pct DECIMAL(4, 2) */
Java
UTF-8
1,001
2.40625
2
[]
no_license
package com.jack.service.common.crawler.parse.factory.impl; import com.jack.service.common.crawler.model.GrabType; import com.jack.service.common.crawler.parse.Parser; import com.jack.service.common.crawler.parse.factory.ParserFactory; /** * * @ClassName: AbstractParserFactory * @Description: * @author lksoulman * @date 2018-06-27 08:59:15 */ public abstract class AbstractParserFactory implements ParserFactory { @Override public synchronized Parser getParser(GrabType grabType) { Parser parser = null; switch (grabType) { case GRAB_HTML: parser = getHtmlParser(); break; case GRAB_LINK: parser = getLinkParser(); break; case GRAB_JSON: parser = getJsonParser(); break; case GRAB_TABLE: parser = getTableParser(); break; default: break; } return parser; } protected abstract Parser getHtmlParser(); protected abstract Parser getLinkParser(); protected abstract Parser getJsonParser(); protected abstract Parser getTableParser(); }
C
UTF-8
1,286
4
4
[]
no_license
#include<stdio.h> int main(){ int n[10], input ; // declaring array 'n' and input number to be searched as 'input' for(int i = 0 ; i<10 ; i++) // using -for- loop for iterating elements in array 'n' { scanf("%d,",&n[i]) ; } scanf("%d",&input) ; // taking 'input' from scanf int a = 0 , b = 9 , c ; // a--> start element , b--> end element , c = (a+b)/2 --> mid for(int j = 1 ; j<=4 ; j++) // using for loop to search 'input' in array 'n' { c = (a+b)/2 ; //middle element if(input<n[c]) //if 'input' is lesser than middle element(given using index of c) b = c - 1 ; // change the end element else if(input>n[c]) //similarly if it is greater a = c + 1 ; // change the first element else if(input==n[c]) //if it is equal { printf("%d %d", 1 , j ) ; // print '1' and the 'number of comparision break ; //break loop } } if(a>b) // if the first element index , i.e 'a' is greater than 'b' { // it means no element in 'n' is equal to 'input' printf("%d %d", 0 , 4) ; // therefore print "0" and 'number of comparision } return 0 ; }
Markdown
UTF-8
1,052
2.546875
3
[]
no_license
# Vue 3 新手夏令營 - [活動網址](https://www.hexschool.com/2021/07/07/2021-07-07-vue3-summer-camp/) - [上課文件 | HackMD](https://hackmd.io/@dbFY0UD9SUeKmNXhWf01ew/BkJoW-hn_/%2Fa2b7-VbeR5KOsArLSRWy1Q) - 上課影片 - [week1 : Vue.js 3 起手式教學](https://www.youtube.com/watch?v=gCd8Kg7avc0&t=8s&ab_channel=%E5%85%AD%E8%A7%92%E5%AD%B8%E9%99%A2) - [week2 : Vue 3 必學指令教學](https://www.youtube.com/watch?v=DUfmdaTj78k&ab_channel=%E5%85%AD%E8%A7%92%E5%AD%B8%E9%99%A2) - [week3 : Vue 3 Options API 實戰教學](https://www.youtube.com/watch?v=f3xwCDaN23I&ab_channel=%E5%85%AD%E8%A7%92%E5%AD%B8%E9%99%A2) - [week4 : Vue 3 Composition API 精髓掌握](https://www.youtube.com/watch?v=xOG-5fCvYbY&ab_channel=%E5%85%AD%E8%A7%92%E5%AD%B8%E9%99%A2) - 重要觀念 - [JavaScript 常見考題破解:物件傳值?傳參考?](https://www.youtube.com/watch?v=y1odVMpi6dU&ab_channel=%E5%85%AD%E8%A7%92%E5%AD%B8%E9%99%A2) - [JavaScript Promise 全介紹](https://wcc723.github.io/development/2020/02/16/all-new-promise/)
Python
UTF-8
805
2.96875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat May 9 12:13:15 2020 @author: leiya """ #注意用dp时候先给dp声明空间 #注意迭代公式里还有上步更新的dp值 class Solution: def minPathSum(self, grid: List[List[int]]) -> int: row = len(grid) col = len(grid[0]) dp = [[0 for _ in range(col)] for _ in range(row)] for i in range(row): for j in range(col): if i != 0 and j != 0: dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + grid[i][j] elif i == 0 and j == 0: dp[i][j] = grid[i][j] elif i == 0 and j != 0: dp[i][j] = dp[i][j-1] + grid[i][j] else: dp[i][j] = dp[i-1][j] + grid[i][j] return dp[-1][-1]
Python
MacCentralEurope
2,026
3.703125
4
[]
no_license
# Python Optparse # optparse Parser for command line options. # optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. # optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command # line. # optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you. # # While optparse is quite flexible and powerful, its also straightforward to use in most cases. # This script covers the code patterns that are common to any optparse-based program. # # # First, you need to import the OptionParser class; then, early in the main program, create an OptionParser instance: # from optparse import OptionParser # ... parser = OptionParser() # # Then you can start defining options. # The basic syntax is: # parser.add_option(opt_str, ..., attr=value, ...) # # Each option has one or more option strings, such as -f or --file, and several option attributes that tell optparse what to expect and what to do when it # encounters that option on the command line. # # # Typically, each option will have one short option string and one long option string, e.g.: # parser.add_option("-f", "--file", ...) # # Youre free to define as many short option strings and as many long option strings as you like (including zero), as long as there is at least one option # string overall. # # # The option strings passed to OptionParser.add_option() are effectively labels for the option defined by that call. For brevity, we will frequently refer # to encountering an option on the command line; in reality, optparse encounters option strings and looks up options from them. # # # Once all of your options are defined, instruct optparse to parse your programs command line: # (options, args) = parser.parse_args()
Java
UTF-8
454
2.546875
3
[]
no_license
package CommonClasses; //public class LobbyInformationMessage extends Message{ // // private enum StatusType {playerLogin, playerLogout }; // private StatusType state; // private String playerName; // private int playerID; // // public LobbyInformationMessage(String playerName, int playerID, StatusType s) { // super(MessageType.LobbyInformationMessage); // this.playerName = playerName; // this.playerID = playerID; // this.state = s; // } //}
C++
UTF-8
1,468
2.65625
3
[ "BSD-3-Clause" ]
permissive
#ifndef V4L2_Capability #define V4L2_Capability /** * Represents the capabilities of a V4L2 device. * Must be associated with a particular Device*. (TODO: Is this good?) */ #include <string> #include <linux/videodev2.h> struct v4l2_capability; namespace V4L2 { class Device; } namespace V4L2 { class Capability { public: /** * CTOR Gets V4L capabilities of the device. */ Capability(Device* device); /** * DTOR. */ ~Capability(); /** * Reset the capability structure. */ void reset(); /** * Print all information. */ void printAll(); /** * Accessors for driver and hardware information. */ const char* driver(); const char* card(); const char* busInfo(); int version(); /** * Check for individual device capabilities. */ bool hasVideoCapture(); bool hasVideoOutput(); bool hasVideoOverlay(); bool hasVbiCapture(); bool hasVbiOutput(); bool hasSlicedVbiCapture(); bool hasSlicedVbiOutput(); bool hasRdsCapture(); bool hasVideoOutputOverlay(); bool hasTuner(); bool hasAudio(); bool hasRadio(); bool hasReadWrite(); bool hasAsyncIo(); bool hasStreaming(); protected: /** * V4L2 capability struct. */ struct v4l2_capability capability; /** * Pointer to the device. */ Device* device; /** * Whether the device has been queried. */ bool queried; /** * Do the V4L2 capability query. */ bool doQuery(); }; } #endif
Java
UTF-8
826
2.15625
2
[]
no_license
package br.ifmg.edu.trabalho_java_avancado.visao.Vendas; import javax.swing.table.AbstractTableModel; /** * * @author Vitor */ public class ItensVendaTableModel extends AbstractTableModel { @Override public int getRowCount() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int getColumnCount() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Object getValueAt(int rowIndex, int columnIndex) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
Java
UTF-8
608
2.671875
3
[]
no_license
package br.fepi.si.interfaces; public abstract class Pessoa implements ValidaIdentificacao { private String cpf; private String nome; public static final int caracteres = 11; /** * @param cpf * @param nome */ public Pessoa(String cpf, String nome) { this.cpf = cpf; this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Override public String toString() { return "cpf=" + cpf + ", nome=" + nome + "]"; } }
Python
UTF-8
326
3.34375
3
[]
no_license
#!/usr/bin/env python3 import sys inPath = sys.argv[1] with open(inPath) as file: for line in file: phrases = line.strip().split(',') # print label in caps print(phrases[0].upper(), end=" ") for phrase in phrases[1:]: print(phrase.replace(" ", "_"), end=" ") print()
Java
UTF-8
335
2.65625
3
[]
no_license
package packInterface; public class ImplementierendeKlasse implements ISchnittstelle{ @Override public void method01() { System.out.println("method01()"); } @Override public void method02() { System.out.println("method02()"); } public void method03() { System.out.println("method03()"); } }
Python
UTF-8
2,989
3.171875
3
[ "MIT" ]
permissive
#coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np class LeNet5(nn.Module): # 定义Net的初始化函数,这个函数定义了该神经网络的基本结构 def __init__(self): super(LeNet5, self).__init__() # 复制并使用LeNet5的父类的初始化方法,即先运行nn.Module的初始化函数 # self.conv1 = nn.Conv2d(1, 6, 5) # 定义conv1函数的是图像卷积函数:输入为图像(1个频道,即灰度图),输出为 6张特征图, 卷积核为5x5正方形 self.conv1 = nn.Conv2d(1, 6, 3, stride=1, padding=1) self.conv2 = nn.Conv2d(6, 16, 5) # 定义conv2函数的是图像卷积函数:输入为6张特征图,输出为16张特征图, 卷积核为5x5正方形 # 定义fc1(fullconnect)全连接函数1为线性函数:y = Wx + b,并将16*4*4个节点连接到120个节点上。 self.fc1 = nn.Linear(400, 120) self.fc2 = nn.Linear(120, 84) # 定义fc2(fullconnect)全连接函数2为线性函数:y = Wx + b,并将120个节点连接到84个节点上。 self.fc3 = nn.Linear(84, 10) # 定义fc3(fullconnect)全连接函数3为线性函数:y = Wx + b,并将84个节点连接到10个节点上。 # 定义该神经网络的向前传播函数,该函数必须定义,一旦定义成功,向后传播函数也会自动生成(autograd) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # 输入x经过卷积conv1之后,经过激活函数ReLU,使用2x2的窗口进行最大池化Max pooling,然后更新到x。 x = F.max_pool2d(F.relu(self.conv2(x)), 2) # 输入x经过卷积conv2之后,经过激活函数ReLU,使用2x2的窗口进行最大池化Max pooling,然后更新到x。 x = x.view(-1, self.num_flat_features(x)) # view函数将张量x变形成一维的向量形式,总特征数并不改变,为接下来的全连接作准备。 x = F.relu(self.fc1(x)) # 输入x经过全连接1,再经过ReLU激活函数,然后更新x x = F.relu(self.fc2(x)) # 输入x经过全连接2,再经过ReLU激活函数,然后更新x x = self.fc3(x) # 输入x经过全连接3,然后更新x return x # 使用num_flat_features函数计算张量x的总特征量,比如x是4*2*2的张量,那么它的特征总量就是16。 def num_flat_features(self, x): size = x.size()[1:] # 这里为什么要使用[1:],是因为pytorch只接受批输入,也就是说一次性输入好几张图片,那么输入数据张量的维度自然上升到了4维。【1:】让我们把注意力放在后3维上面 num_features = 1 for s in size: num_features *= s return num_features
Markdown
UTF-8
2,541
2.890625
3
[]
no_license
# Dockerfile Sources Tool that given a list of repositories, it identifies all the Dockerfile files inside each repository, extracts the image names from the FROM statement, and returns a json with the aggregated information for all the repositories. ## Usage: Install python3 and requirements on your machine: ``` pip3 install -r ./requirement.txt ``` ``` python3 run.py <url> ``` or ``` python3 run.py -f <file_path> ``` Output saved in output.json Currently the App runs just 1 thread as github put rate-limit on multiple pull. In case of scaling this, threads can be in increased from config.json ## Implemention 1. Upon recieving argument/URL to `run.py` first thing app does is start logger. This feature basically lets us see what is happening in real time, you can find more detailed logs by tailing in logs directory 2. Once given argument, run.py calls on utils to parse config.json to identify number of threads to run and where to store output. Currently we are storing ouput in output.json so it can be later manipulated with jq as required! 3. In case URL is passed as argument, it calls on `dockerfile_source.app` this parses the URL and creates a list of valid enteries. Enteries that are in format: `<Repo url> <Sha>`. It ignores all other content in plaitext file. 4. Once it has the list ready with URL and SHA, `dockerfile_source.client` is called, where it clones and checks out the Repo. 5. Once cloned, it parses the available repo to check if there are in Dockerfile available. 6. In case there is a Dockerfile available, it will query Dockerfile to find the "FROM" statement. 7. This value is being stored and appended as app goes through all the lines of files and queries each dockerfile. 8. Once it has gone through each line it updates output.json with the data. 9. We keep counters that count number of repo queried, number of Dockerfiles and number of base containers, these are displayed at the end to avoid going through the whole output.json ## Features: 1. Can easily be scaled. 2. Can parse URL and csv file both 3. Logging, errors are logged too. Verbose execution 4. Containerized app. Just pass URL as ENV variable. To pull container: ``` docker pull docker.io/karanacad/docker_source ``` To run: ``` docker run -e "URL=<url>" karanacad/docker_source ``` For ex: ``` docker run -e "https://gist.githubusercontent.com/karanb21/0cf32a514efeb098cfe0a4df054b8d66/raw/eeeb263bd276dbfd0f9cb66fac5e69a6c3297df2/test.txt" karanacad/docker_source ``` # Remaing work: 1. Running this as minikube job!
Python
UTF-8
1,630
2.6875
3
[]
no_license
from app.models import UserType from app.postgres import nationality_functions def create_user_type(identification_number, resident, last_address, nationality_id): try: _nationality_id = nationality_functions.find_nationality_by_id(nationality_id) user_type = UserType(identification_number = identification_number, resident = resident, last_address = last_address, fk_nationality_id = _nationality_id.nationality_id).save() return user_type except Exception: print("Is not possible create user type") return None def find_user_type_by_identification_number(identification_number): try: user_type = UserType.objects.get(identification_number = identification_number) return user_type except UserType.DoesNotExist: print("user type not exist") return None def update_nationality(identification_number, resident, nationality_id, user_type_id): try: user_type = UserType.objects.get(user_type_id = user_type_id) user_type.identification_number = identification_number user_type.resident = resident user_type.fk_nationality_id = nationality_id user_type.save() return True except UserType.DoesNotExist: print("Nationality not updated") return None def update_last_address(last_address, user_type_id): try: user_type = UserType.objects.get(user_type_id = user_type_id) user_type.last_address = last_address user_type.save() return True except UserType.DoesNotExist: print("Last address not updated") return None
Java
UTF-8
233
1.820313
2
[]
no_license
package modelo; import javabeans.Cliente; public interface GestionClientes { boolean estaRegistrado(String user, String pass); void registrar(Cliente c); Cliente obtenerCliente(String usuario, String password); }
Java
GB18030
1,549
1.960938
2
[]
no_license
package com.kingdee.eas.fdc.sellhouse; import com.kingdee.bos.framework.ejb.EJBRemoteException; import com.kingdee.bos.util.BOSObjectType; import java.rmi.RemoteException; import com.kingdee.bos.framework.AbstractBizCtrl; import com.kingdee.bos.orm.template.ORMObject; import com.kingdee.bos.util.*; import com.kingdee.eas.common.EASBizException; import com.kingdee.bos.Context; import com.kingdee.bos.BOSException; import com.kingdee.eas.fdc.sellhouse.app.*; import java.util.Map; import com.kingdee.bos.framework.*; public class PrePurchaseDetailFacade extends AbstractBizCtrl implements IPrePurchaseDetailFacade { public PrePurchaseDetailFacade() { super(); registerInterface(IPrePurchaseDetailFacade.class, this); } public PrePurchaseDetailFacade(Context ctx) { super(ctx); registerInterface(IPrePurchaseDetailFacade.class, this); } public BOSObjectType getType() { return new BOSObjectType("CA049DF4"); } private PrePurchaseDetailFacadeController getController() throws BOSException { return (PrePurchaseDetailFacadeController)getBizController(); } /** *Ԥ-User defined method *@param map Ӽ *@return */ public Map getPrePurchaseData(Map map) throws BOSException, EASBizException { try { return getController().getPrePurchaseData(getContext(), map); } catch(RemoteException err) { throw new EJBRemoteException(err); } } }
Markdown
UTF-8
4,485
3.453125
3
[]
no_license
### 第3章 流、元素与基本尺寸 ##### 块级元素:里元素默认的display值是list-item,<table>元素默认的display值是table,但是他们均是“块级元素“,因为他们都符合块级元素的基本特征, 也就是一个水平流上只能单独显示一个元素,多个元素则换行显示。 由于块级元素的换行特性,所以他们可以配合clear属性来清除浮动带来的影响。 ``` .clear:after{ content:""; display:table;//也可以是block,或者是list-item clear:both; } ``` ie不支持伪元素的display值为list-item ##### 为什么list-item元素会出现项目符号? ###### list-item除了有一个“主块级盒子”,还有一个“附加盒子”(学名“标记盒子”), 专门用来放圆点、数字这些项目符号。IE浏览器下伪元素不支持list-item或许就是无法创建这个“标记盒子”导致的。 ##### 由于display:inle-block;的出现,按照display的属性值不同,值为block的元素的盒子实际由外在的“块级盒子”和内在的“块级容器盒子”组成, 值为inline-block的元素则由外在的“内联盒子”和内在的“块级容器盒子”组成,值为inline的元素则内外均是“内联盒子” #### 我们平时设置的width、height都是都是作用在内在的“容器盒子”上的。 #### width、height的具体细节: ##### width:auto 1. 外部尺寸与流体特性 * 正常流宽度 * 格式化宽度:仅出现在“绝对定位模型”中,也就是出现在position属性值为absolute或fixed的元素中。 在默认情况下,绝对定位元素的宽度表现是“包裹性”,宽度由内部尺寸决定。 对于非替换元素,当left/right或top/bottom对立方位的属性值同时存在的时候, 元素的宽度表现为“格式化宽度”,其宽度大小相对于最近的具有定位特性(position属性值不是static)的祖先元素计算。 2. 内部尺寸与流体特性 * 包裹性 * 首选最小宽度 * 最大宽度:等同于“包裹性”元素设置white-space:norwrap声明后的宽度 #### width值作用的细节: ##### 盒尺寸:“内在盒子”又被分成4个盒子,分别是content box、padding box 、border box 、margin box ##### 宽度分离原则:就是css中的width属性不与影响宽度的padding/border(有时候包括margin)属性共存 ##### 如何实现:width 独立占用一层标签,而padding、border、margin利用流动性在内部自适应呈现 #### box-sizing的作用:content-box/border-box #### 替换元素:原生普通文本框<input>和文本域<textarea>,尺寸由内部元素决定,改变display无法使其100%自适应父元素尺寸。 ### height:auto 对于width属性,就算父元素width为auto,其百分比也是支持的;但是,对于height元素,如果父元素height为auto,只要子元素在文档流中,其百分比值就完全被忽略了。( 父级没有具体高度值的时候,height:100%会无效) #### 如何让元素支持height:100%效果? 有两种办法: * 设定显式的高度值:例如设置height:600px,或者可以生效的百分比值高度。比如:html,body{height:100%} * 使用绝对定位。比如:div{height:100%;position:absolute;}此时的height:100%就会有计算值,即使祖先元素的height计算为auto也是如此。需要注意的是,绝对定位元素的百分比计算和非绝对定位的百分比计算是有区别的,区别在于绝对定位定位的宽高百分比计算是相对于padding box的,也就是说会把padding大小值计算在内,但是,非绝对定位元素则是相对于content box计算的。 1. max-width:权重很高,超越!important 2. 超越最大:指的是min-width覆盖max-width,此规则发生在min-width和max-width冲突的时候。 ### 内联元素: 1. 特征,可以和文字一行显示,文字是内联元素,图片是内联元素,按钮是内联元素,输入框下拉框等原生表单控件也是内联元素 2. 内联盒模型: * 内容区域 * 内联盒子:指元素的“外在盒子”,用来决定元素是内联还是块级。该盒子又可以细分为“内联盒子”和“匿名内联盒子”两类: * 行框盒子 * 包含盒子 3. 幽灵空白节点:在html5文档声明中,内联元素的所有解析和渲染表现就如同每个行框盒子的前面有一个‘空白节点’一样。
Python
UTF-8
2,937
2.546875
3
[]
no_license
#! /usr/bin/env python3 import os import re basedir = os.path.abspath(os.path.dirname(__file__)) f_path = basedir + '/static/axure/' rootNodes = 'rootNodes' pageName = 'pageName' url = 'url' type = 'type' children = 'children' class Axure: def __init__(self, id): path = f_path + str(id) + '/data/document.js' with open(path, 'r') as f: docjs_msg = f.read() self.cfg_set(docjs_msg) self.tree_str_set(docjs_msg) self.tree = self.tree_bulid(self.tree_msg) html_lst = [] for k in self.cfg: html = re.findall('.*\.html', self.cfg[k]) if html: html_lst.append(html[0][:-5]) self.html_lst = html_lst def cfg_set(self, docjs_msg): """ 获取data/document.js中的配置项 """ rule = '[a-zA-Z]+\s*=\s*".*?"' content = re.findall(rule, docjs_msg) d = {} for line in content: kv = line.split('=') k = kv[0] v = kv[1][1:-1] d[k] = v self.cfg = d def struct_idx(self, msg, start='(', end=')'): cnt = s_id = e_id = 0 lst = [] for idx in range(len(msg)): if msg[idx] == start: if cnt == 0: s_id = idx cnt += 1 if msg[idx] == end: cnt -= 1 if cnt == 0: e_id = idx lst.append((s_id, e_id)) return lst def tree_str_set(self, docjs_msg): d = self.cfg for k in d: if d[k] == rootNodes: break start = k rule = f'_\({start}.*\),' content = re.findall(rule, docjs_msg) tree_msg = content[0].replace('_', '') s_id, e_id = self.struct_idx(tree_msg)[0] self.tree_msg = tree_msg[s_id + 4:e_id - 1] def tree_bulid(self, msg): tree = [] lst = self.struct_idx(msg) for s, e in lst: # print(msg[s+1:e]) # 把前后的()都给移除掉 tree.append(self.node_create(msg[s+1:e])) return tree def node_create(self, msg): """ 构建Axure的节点信息 """ node = {} d = self.cfg msg_lst = msg.split(',') for i in range(len(msg_lst)): val = msg_lst[i] if d.get(val, val) in [pageName, type ,url]: node[d[val]] = d[msg_lst[i + 1]] if d.get(val, val) == children: children_msg = msg[msg.find('['):] node[children] = 'children' s,e = self.struct_idx(children_msg,'[',']')[0] node[children] = self.tree_bulid(children_msg[s+1:e]) break return node if __name__ == '__main__': a = Axure(3) print(a.tree) # print(a.tree_msg) #print(a.cfg) # print(a.html_lst)
C
UTF-8
836
3.5
4
[]
no_license
#include <stdio.h> #include <sys/time.h> int main () { double sum = 0; double add = 1; // Start measuring time struct timeval begin, end; gettimeofday(&begin, 0); int iterations = 1000*100; for (int i=0; i<iterations; i++) { sum += add; add /= 2.0; } // Stop measuring time and calculate the elapsed time gettimeofday(&end, 0); // long seconds = end.tv_sec - begin.tv_sec; // Para contar segundos utilizamos long microseconds = end.tv_usec - begin.tv_usec; double miliseconds = microseconds * 1e-3; //double elapsed = seconds + microseconds*1e-6; // se suman usegundos y segundos //printf("Result: %.6f\n", sum); printf("\nTime measured: %.3f miliseconds.\n\n", miliseconds); return 0; }
Python
UTF-8
1,782
2.921875
3
[]
no_license
import time import datetime import spidev as SPI import SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont import matplotlib.pyplot as plt from sklearn import datasets, svm, metrics import numpy as np RST = 19 DC = 16 bus = 0 device = 0 disp = SSD1306.SSD1306(rst=RST,dc=DC,spi=SPI.SpiDev(bus,device)) disp.begin() disp.clear() disp.display() digits = datasets.load_digits() images_and_labels = list(zip(digits.images, digits.target)) for index, (image, label) in enumerate(images_and_labels[:4]): plt.subplot(2, 4, index + 1) plt.axis('off') plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') plt.title('Training: %i' % label) # To apply a classifier on this data, we need to flatten the image, to # turn the data in a (samples, feature) matrix: n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) # Create a classifier: a support vector classifier classifier = svm.SVC(C=1.0,gamma=0.01) # We learn the digits on the first half of the digits classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2]) # Now predict the value of the digit on the second half: expected = digits.target[n_samples // 2:] predicted = classifier.predict(data[n_samples // 2:]) images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted)) for kk,prediction in images_and_predictions: digit=Image.fromarray((kk*8).astype(np.uint8),mode='L').resize((48,48)).convert('1') img=Image.new('1',(disp.width,disp.height),'black') img.paste(digit,(0,16,digit.size[0],digit.size[1]+16)) draw = ImageDraw.Draw(img) font = ImageFont.load_default() draw.text((0,0),'Prediction: %i' % prediction,font=font,fill=255) disp.clear() disp.image(img) disp.display() time.sleep(1)
Python
UTF-8
238
2.671875
3
[]
no_license
r,c=map(int,input().split()) m=[input().split() for i in range(r)] for i in range(r): for j in range(c): if m[i][j]=='B': m[i][j]='-' m=[sorted(i) for i in list(zip(*m))] m=list(zip(*m)) for i in m: print(*i)
Java
UTF-8
1,695
2.546875
3
[]
no_license
package wordnet.App.Service.Impl; import org.springframework.stereotype.Component; import wordnet.App.Service.ChooseMeanOfSynset; import wordnet.ProcessDataInput.Model.Synset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by chien on 19/03/2018. */ public class ChooseCaseOne implements ChooseMeanOfSynset { /** * case one * with condition: * 1. synset have more than two word form * 2. each mean of word in synset have more than one line mean vietnamese * 3. tất cả synset đều có chung một dòng nghĩa * @param synset * @return list mean of word in synset, choose with all o word in synset have less one mean */ @Override public List<String> choice(Synset synset) { List<String> listMean = new ArrayList<>(0); if (synset.getMapWordForm().size() >= 2) { Set<String> wordFormKeySet = synset.getMapWordForm().keySet(); for (String s : wordFormKeySet) { if (synset.getMapWordForm().get(s).getListMean().size() < 1) { return listMean; } } // do action Map<String, Integer> mapCountWord = CountMap.countWordInList(synset); int size = wordFormKeySet.size(); mapCountWord.forEach( (s, integer) -> { if (integer.equals(size) && !s.isEmpty()) { listMean.add(s); } } ); } return listMean; } @Override public String getNameStrategy() { return "1"; } }
Java
UTF-8
471
1.898438
2
[]
no_license
package currencyexchange.service; import currencyexchange.model.ExchangeTransaction; import currencyexchange.vo.TransactionsListVO; public interface ExchangeTransactionService { public void addTransaction(ExchangeTransaction exchangeTransaction); public TransactionsListVO getTransactions(String userName); public void declineTransaction(ExchangeTransaction exchangeTransaction); public ExchangeTransaction getExchangeTransaction(int transactionId); }
C++
UTF-8
4,067
2.953125
3
[]
no_license
/* ********************************************* * Programmer Name: Ashley De Lio * * Z-ID: Z1723695 * * Class: CSCI 330 - 2 * * Program: Assignment 9 * * Purpose: Exercise TCP server socket system * calls. Program implements a simple * file server. * ********************************************/ #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; int main(int argc, char *argv[]) { // check arguments if (argc != 2) { cerr << "USAGE: echoTCPServer port\n"; exit(EXIT_FAILURE); } // Create the TCP socket int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("socket"); exit(EXIT_FAILURE); } // create address structures struct sockaddr_in server_address; // structure for address of server struct sockaddr_in client_address; // structure for address of client unsigned int addrlen = sizeof(client_address); // Construct the server sockaddr_in structure memset(&server_address, 0, sizeof(server_address)); /* Clear struct */ server_address.sin_family = AF_INET; /* Internet/IP */ server_address.sin_addr.s_addr = INADDR_ANY; /* Any IP address */ server_address.sin_port = htons(atoi(argv[1])); /* server port */ // Bind the socket if (bind(sock, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) { perror("bind"); exit(EXIT_FAILURE); } // listen: make socket passive and set length of queue if (listen(sock, 64) < 0) { perror("listen"); exit(EXIT_FAILURE); } cout << "echoServer listening on port: " << argv[1] << endl; // Run until cancelled int connSock[11]; int i = 0; int rs; while (true) { connSock[i]=accept(sock, (struct sockaddr *) &client_address, &addrlen); if (connSock[i] < 0) { perror("accept"); exit(EXIT_FAILURE); } //Fork int pid; // fork will make 2 processes pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { // Child process: // read a message from the client char buffer[1024]; int received = read(connSock[i], buffer, sizeof(buffer)); if (received < 0) { perror("read"); exit(EXIT_FAILURE); } //GET cout << "Buffer: " << buffer << endl; //Begin process to divide request command and pathname string into reqCommand and path strings //Define deliminator and new array for reqCommand and path to be placed into const char delim[2] = " "; char * section[3]; int j = 0; char *token; string reqCommand, path; token = strtok(buffer, delim); //Place pieces of argv[2] (separated by whitespace) into section array and corresponding reqCommand and path strings while (token != NULL){ section[j] = (char *) malloc (strlen(token) + 1); strcpy(section[j], token); if (j == 0){ reqCommand = section[j]; } else if (j == 1){ path = section[j]; } j++; token = strtok(NULL, delim); } cout << "reqCommand is: " << reqCommand << endl; cout << "path is: " << path << endl; //if request command is GET, get and write back appropriate file or directory if (reqCommand == "GET"){ rs = execlp("/bin/ls", "/bin/ls", path.c_str(), (char*) NULL); if (rs == -1) { perror(reqCommand.c_str()); exit(EXIT_FAILURE); } // write the message back to client if (write(connSock[i], buffer, received) < 0) { perror("write"); exit(EXIT_FAILURE); } close(connSock[i]); } //if request command is INFO, get and write back the current date and time in text format else if (reqCommand == "INFO"){ // write the message back to client if (write(connSock[i], buffer, received) < 0) { perror("write"); exit(EXIT_FAILURE); } close(connSock[i]); } } else { // Parent process: continue to top of loop i++; if(i > 10){ i = 0; } continue; } } close(sock); return 0; }
Python
UTF-8
1,159
2.875
3
[]
no_license
# coding=UTF-8 import numpy as np class ConvolutionLayer(object): def __init__(self, filter_size, filter_num, stride, padding=0): self.filter_size = filter_size self.filter_num = filter_num self.stride = stride self.padding = padding # 使用均值为0、标准差为1的高斯分布初始化卷积核 # 组织成[filter_num, filter_size, filter_size]的形式 self.weights = np.random.normal(0, 0.01, self.filter_num * self.filter_size ** 2) \ .reshape((self.filter_num, self.filter_size, self.filter_size)) self.outputs = [] def setup(self, inputs_shape): # 根据输入数据计算当前层次输出结果的大小 # # 输入数据以4维数组的形式组织,具体格式为: # [batch, width, height, channel] outputs_size = (inputs_shape[1] + 2 * self.padding - self.filter_size) / self.stride + 1 self.outputs = np.zeros((inputs_shape[0], outputs_size, outputs_size, self.filter_num)) return self.outputs.shape # 计算卷积层的前向传播结果 def forward(self, inputs): pass
PHP
UTF-8
776
2.65625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace ComposerUnused\SymbolParser\Parser\PHP\Strategy; use PhpParser\Node; use PhpParser\Node\Expr\StaticCall; final class StaticStrategy implements StrategyInterface { public function canHandle(Node $node): bool { if (!$node instanceof StaticCall) { return false; } if (!$node->class instanceof Node\Name) { return false; } return $node->class->isFullyQualified() || $node->class->isQualified(); } /** * @param Node&StaticCall $node * @return array<string> */ public function extractSymbolNames(Node $node): array { /** @var Node\Name $class */ $class = $node->class; return [$class->toString()]; } }
C
WINDOWS-1251
1,918
4.03125
4
[]
no_license
#include "math.h" #include "stdio.h" #include "stdlib.h" /* , sin(x) main*/ double Nextsin(double x, int i) { double result; result = pow(-1, i) * pow(x, 2 * i) / (2 * i * (2 * i + 1)); return result; } /* , cos(x) main*/ double Nextcos(double x, int i) { double result; result = pow(-1, i) * pow(x, 2 * i) / (2 * i(2 * i - 1)); return result; } /* , arctg(x) main*/ double Nextarctan(double x, int i) { double result; result = pow(-1, i) * pow(x, 2 * i); return result; } /* x*/ void Tangent() { double x, sin, cos, tan, arctan, elem, elemNext; int i, K; scanf_s("%lf", &x); scanf_s("%lf", &K); arctan = x; elem = arctan; for (i = 1; i < K; i++) { elemNext = elem * Nextarctan(x, i) / (2 * i + 1); arctan += elemNext; } sin = x; elem = sin; for (i = 1; i < K; i++) { elemNext = elem * Nextsin(x, i); sin += elemNext; } cos = 1; elem = cos; for (i = 1; i < K; i++) { elemNext = elem * Nextcos(x, i); cos += elemNext; } tan = sin / cos; printf("tan=%lf arctan=%lf", tan, arctan); }
Shell
UTF-8
224
2.9375
3
[ "Unlicense" ]
permissive
#!/bin/bash # Deletes all compiled junk from folders _startdir=$(pwd) for _fullpath in $(find . -type d -name 'target'); do _path=$(dirname "$_fullpath") cd "$_path" cargo clean && echo "'cargo clean' run on $_path" done
Java
UTF-8
546
2.84375
3
[]
no_license
package pl.jedrik94.prototype_pattern; import org.apache.commons.lang3.SerializationUtils; import pl.jedrik94.prototype_pattern.model.Person; import pl.jedrik94.prototype_pattern.model.Address; public class AppPrototype { public static void main(String[] args) { Person jedrzej = new Person("Jedrzej", new Address("LesznoStreet", "Leszno", "Poland")); Person milosz = SerializationUtils.roundtrip(jedrzej); milosz.setName("Milosz"); System.out.println(jedrzej); System.out.println(milosz); } }
Java
UTF-8
1,400
2.453125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* * Copyright 2019 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ package io.proximax.dfms.model.exceptions; /** * Types of errors that are returned by the HTTP API calls */ public enum ResponseErrorType { /** * is a normal error. The command failed for some reason that is not a bug. */ NORMAL(0), /** * client made an invalid request. */ CLIENT(1), /** * there is a bug in the implementation. */ IMPLEMENTATION(2), /** * the operation has been rate-limited. */ RATE_LIITED(3), /** * the client doesn't have permission to perform the requested operation. */ FORBIDDEN(4); private final int code; /** * @param code */ private ResponseErrorType(int code) { this.code = code; } /** * @return the code */ public int getCode() { return code; } /** * retrieve instance by the actual code * * @param code the code indicating type of error * @return the instance */ public static ResponseErrorType getByCode(int code) { for (ResponseErrorType err: values()) { if (err.getCode() == code) { return err; } } throw new DFMSRuntimeException("Unrecognized error code " + code); } }
Java
UTF-8
1,313
2.578125
3
[]
no_license
package com.example.dressassistant.database; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; import com.example.dressassistant.database.table.PersInfo; /** * Created by lyh on 2017-12-17. */ public class DataBaseHelper extends SQLiteOpenHelper { /** *构造方法,创建数据库 * @param context * @param name 数据库名称 * @param factory 游标类 * @param version 数据库版本 */ public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version) { super(context,name,factory,version); } /** * 创建接口 * 实现各表的创建 */ public static interface TableCreateInterface{ public void onCreate(SQLiteDatabase db); public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion); } public void onCreate(SQLiteDatabase db){ //创建个人信息表 PersInfo.getInstance().onCreate(db); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ if( oldVersion >= newVersion ){ return; } //更新个人信息表 PersInfo.getInstance().onUpgrade(db,oldVersion,newVersion); } }
C
UTF-8
960
3.390625
3
[]
no_license
/* LAbs week 8 Erik Grunner Problem 3 */ #include <stdio.h> #define ROW 3 #define COL 2 int main() { int array[ROW][COL]={4,8,6,5,9,7}; int rowsum[ROW]={0}; int colsum[COL]={0}; int i,j; int highest=0; for(i=0;i<ROW;i++) { for(j=0;j<COL;j++) { rowsum[i]=rowsum[i]+array[i][j]; }//end inner for printf("Row %d sums up to be %d\n",i,rowsum[i]); }//end outer for for(i=0;i<COL;i++) { for(j=0;j<ROW;j++) { colsum[i]=colsum[i]+array[j][i]; }//end inner for printf("Col %d sums up to be %d\n",i,colsum[i]); }//end outer for for(i=0;i<COL;i++) { for(j=0;j<ROW;j++) { if(array[i][j]>highest) { highest=array[i][j]; }//end if }//end inner for }//end outer for printf("highest number is %d",highest); getchar(); return 0; }//end main
Python
UTF-8
842
2.84375
3
[ "MIT" ]
permissive
import unittest from acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): """Making sure Acme products are the tops!""" def test_default_product_price(self): """Test default product price being 10.""" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): """Test the toy's weight being 10.""" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_new_product_stealability(self): """test new product stealability to be 'Very stealable!'""" prod2 = Product("New Product", weight=1) self.assertEqual(prod2.stealability(), 'Very stealable!') if __name__ == '__main__': unittest.main()
Java
UTF-8
2,640
2.34375
2
[]
no_license
/** * */ package isa; import arc_project.Global; import arc_project.Instruction; /** * @author zzj * */ public class InstructionSet_SRC extends Instruction { /** * Shift Register by Count */ public InstructionSet_SRC() { // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see arc_project.Instruction#operate() */ @Override public void operate() throws Exception { // TODO Auto-generated method stub int count; // 5) DIR < IR 6 Global.LR.set(Global.IR.get(6),0); // RSR < IR 7-8 Global.RSR.set(Global.IR.get(7,8)); // STYPE < IR 9 Global.AL.set(Global.IR.get(9),0); // COUNT < IR 12-15 Global.COUNT.set(Global.IR.get(12,15)); count = Global.ALU.char2int(Global.COUNT.get()); char[] z = new char[count]; for(int i = 0; i<count; i++) z[i] = '0'; // 6) SR < Register(RSR) Global.SR.set(Global.R[Global.ALU.char2int(Global.RSR.get())].get()); // 7) IF (AL == 0) THEN // ARITHMATIC if( Global.AL.get(0) == '0' ){ // +8) IF (LR == 0) THEN // SHIFT RIGHT if( Global.LR.get(0) == '0' ){ // ++9) TR < SR 1 Global.TR.reset(); Global.TR.set(Global.SR.get(1,1+count-1),1); // ++10) SR 1-14 < SR 2-15 Global.SR.set(Global.SR.get(1+count,15),1); // ++11) SR 15 < 0 Global.SR.set(z,16-count); // ++12) IF (TR == 1) THEN cc(1) < 1 // OVERFLOW if( Global.ALU.char2int(Global.TR.get()) > 0 ) Global.CC.set('1',0); // ELSE // SHIFT LEFT } else { // ++9) TR < SR 15 Global.TR.reset(); Global.TR.set(Global.SR.get(15-count+1,15),15-count+1); // ++10) SR 2-15 < SR 1-14 Global.SR.set(Global.SR.get(1,15-count),1+count); // ++11) SR 1 < 0 Global.SR.set(z,1); // ++12) IF (TR == 1) THEN cc(2) < 1 // UNDERFLOW if( Global.ALU.char2int(Global.TR.get()) > 0 ) Global.CC.set('1',1); } // ELSE // LOGICAL } else { // +8) IF (LR == 0) THEN // SHIFT RIGHT if( Global.LR.get(0) == '0' ){ // ++9) TR < SR 0 Global.TR.reset(); Global.TR.set(Global.SR.get(0,count-1),0); // ++10) SR 0-14 < SR 1-15 Global.SR.set(Global.SR.get(count,15),0); // ++11) SR 15 < 0 Global.SR.set(z,16-count); // ELSE // SHIFT LEFT } else { // ++9) TR < SR 15 Global.TR.reset(); Global.TR.set(Global.SR.get(15-count+1,15),15-count+1); // ++10) SR 1-15 < SR 0-14 Global.SR.set(Global.SR.get(0,15-count),count); // ++11) SR 0 < 0 Global.SR.set(z,0); } } // 13) Register(RSR) < SR Global.R[Global.ALU.char2int(Global.RSR.get())].set(Global.SR.get()); // 14) PC < PC + 1 Global.PC.set(Global.ALU.add(Global.PC.get(), 1)); } }
Markdown
UTF-8
10,825
2.890625
3
[]
no_license
### Quick start ``` git clone https://github.com/ThomasLiu/comment.git cd comment npm install ``` ### Run test ``` npm run test ``` 运行test之前需要 通过 GET /api/appSecrets/new 获取 appId 和 appSecret 然后更新/config/sys.js 内的appId 和 appSecret ### Run ``` npm start ``` ### Run pm2 for production ``` NODE_ENV=production pm2 start bin/www -i 0 --name 'commnet' ``` ### Run pm2 for test ``` NODE_ENV=test pm2 start bin/www -i 0 --name 'test-commnet' ``` ## API #### 获取请求appId 和 appSecret GET /api/appSecrets/new <br> 请记住您的 appId 和 appSecret,只生成一次。 #### 获取请求Token POST /api/auth <br> send : {appId : yourAppId, appSecret : yourAppSecret} ``` { "data": { "success":true, "message":"Enjoy your data!", "token":"yourToken" }, "status":{ "code":0, "msg":"request success!" }, "http_code":200 } ``` #### RESTful API 返回格式都是json 每一个Model都有对应的RESTful API,以下以comment这个model为例<br> GET /api/comments[/] => comments.api.list()<br> GET /api/comments/:id => comments.api.show()<br> POST /api/comments[/] => comments.api.create()<br> PATCH /api/comments/:id => comments.api.update()<br> DELETE /api/comments/:id => comments.api.destroy()<br> ##### GET /api/comments[/] | 参数 | 类型 | 必填 | 默认值 | 说明 | | ------------- |:---------:|:----:| :-------------------------- | :--------------------------------------------------------------------------------------| | page | int | 否 | 1 | 获取列表的第几页 | | limit | int | 否 | /config/sys.js 的list_count | 一页中获取多小个对象 | | sort | string | 否 | '-createdAt' | 按照怎样的规则排序,参数规则按mongoose的sort规则,将对例 JSON.stringify({createdAt: -1}) | | where | string | 否 | 默认搜索全部 | 按照怎样的规则搜索,参数规则按mongoose的find()的参数规则,例 JSON.stringify({attribute1: 'a'}) | | attributes | string | 否 | 默认显示全部 | 返回的列表对象中的字段,例 JSON.stringify(['attribute1','attribute2','attribute3']) | | needCustomer | int | 否 | 0 | 返回对象是否包含关联对象,如userId,当该参数值为1时,对象中就会有user属性,装上userId对应的对象 | ###### 返回json ``` { "data": { "success":true, "message":"Enjoy your data!", "result":{ "count": 2, "rows":[ {commentModel},{commentModel} ] } }, "status":{ "code":0, "msg":"request success!" }, "http_code":200 } ``` ##### GET /api/comments/:id | 参数 | 类型 | 必填 | 默认值 | 说明 | | ------------- |:---------:|:----:| :-------------------------- | :--------------------------------------------------------------------------------------| | id | ObjectId | 是 | | 需要获取对象的id | | needCustomer | int | 否 | 0 | 返回对象是否包含关联对象,如userId,当该参数值为1时,对象中就会有user属性,装上userId对应的对象 | ###### 返回json ``` { "data": { "success":true, "message":"Enjoy your data!", "result":{commentModel} }, "status":{ "code":0, "msg":"request success!" }, "http_code":200 } ``` ##### POST /api/comments[/] ###### 参数 | 参数 | 类型 | 必填 | 默认值 | 说明 | | ------------- |:---------:|:----:| :-------------------------- | :--------------------------------------------------------------------------------------| | message | string | 是 | 无 | 评论内容,可包含html结构 | | threadId | ObjectId | 是 | 无 | 评论实例Id | | parentId | ObjectId | 否 | 无 | 回复评论Id | | userJwt | string | 是 | 无 | 评论者Jwt加密 | ``` //userJwt 生成代码样例 import jwt from 'jsonwebtoken' var secret = `${yourAppId}|${yourAppSecret}` var user = { name: 'Thomas Lau', headimgurl: 'http://image.hiredchina.com/FqaRXhs-501g_Bv0pKAByc91TgqD?imageMogr2/interlace/1', lastIp: '192.168.1.1', key: '111111' //自己系统上的ID,用来区分唯一性 } var userJwt = jwt.sign(user, secret, { expiresIn : 60 * 10 // 设置过期时间 10分钟 }) ``` ###### 返回json ``` { "data": { "success":true, "message":"Enjoy your data!", "result":{ _id: ObjectId } }, "status":{ "code":0, "msg":"request success!" }, "http_code":200 } ``` ##### PATCH /api/comments/:id ###### 参数 | 参数 | 类型 | 必填 | 默认值 | 说明 | | ------------- |:---------:|:----:| :-------------------------- | :--------------------------------------------------------------------------------------| | id | ObjectId | 是 | | 需要更新对象的id | 将需要更新的对象属性作为参数 post ``` //代码样例 var res = yield testApp .post('/api/auth') .send({ 'appId': yourAppId, 'appSecret': yourAppSecret }) var json = res.body.data var res = yield testApp .patch(`/api/comments/${id}`) .send({ message : 'update message' }) .set('x-access-token',json.token) ``` ###### 返回json ``` { "data": { "success":true, "message":"update success!", "result":{ "ok":1, "nModified":1, "n":1 } }, "status":{ "code":0, "msg":"request success!" }, "http_code":200 } ``` ##### DELETE /api/comments/:id ###### 参数 | 参数 | 类型 | 必填 | 默认值 | 说明 | | ------------- |:---------:|:----:| :-------------------------- | :--------------------------------------------------------------------------------------| | id | ObjectId | 是 | | 需要删除对象的id | ###### 返回json ``` { "data": { "success":true, "message":"delete success!" }, "status":{ "code":0, "msg":"request success!" }, "http_code":200 } ``` 详细例子可以看测试用例 /test/app/routes/api/comments.js <br> 需求列表所有测试用例 /test/app/routes/api/test.js #### Models ``` //Comment ip : {type: String}, //评论者目前Ip message: {type: String}, //评论内容 status: {type: String}, //评论状态。创建评论时,可能的状态:approved:已经通过;pending:待审核;spam:垃圾评论。 likes : {type: Number, default: 0}, //like 数量 reports : {type: Number, default: 0}, //report 数量 comments : {type: Number, default: 0}, //comment 数量 reposts : {type: Number, default: 0}, //repost 转发数量 rootId: { type: ObjectId , ref: 'Comment' }, //回复评论根Id parentId: { type: ObjectId , ref: 'Comment' }, //回复评论Id threadId: { type: ObjectId , ref: 'Thread' }, //评论实例Id userId: { type: ObjectId , ref: 'User' }, //评论用户Id appSecretId : { type: ObjectId , ref: 'AppSecret' }, //开发者用户Id createAt: { type: Date, default: Date.now }, updateAt: { type: Date, default: Date.now }, ``` ``` //Like ip : {type: String}, commentId: { type: ObjectId , ref: 'Comment' }, //评论Id threadId: { type: ObjectId , ref: 'Thread' }, //评论实例Id userId: { type: ObjectId , ref: 'User' }, //操作用户Id appSecretId : { type: ObjectId , ref: 'AppSecret' }, //开发者用户Id createAt: { type: Date, default: Date.now }, updateAt: { type: Date, default: Date.now }, ``` ``` //Report ip : {type: String}, message: {type: String}, //评论内容 commentId: { type: ObjectId , ref: 'Comment' }, //评论Id threadId: { type: ObjectId , ref: 'Thread' }, //评论实例Id userId: { type: ObjectId , ref: 'User' }, //操作用户Id appSecretId : { type: ObjectId , ref: 'AppSecret' }, //开发者用户Id createAt: { type: Date, default: Date.now }, updateAt: { type: Date, default: Date.now }, ``` ``` //Thread ip : {type: String}, title : {type: String}, //文章标题 message: {type: String}, //文章内容 type: {type: String}, //文章类别 likes : {type: Number, default: 0}, //like 数量 reports : {type: Number, default: 0}, //report 数量 comments : {type: Number, default: 0}, //comment 数量 reposts : {type: Number, default: 0}, //repost 转发数量 userId: { type: ObjectId , ref: 'User' }, appSecretId : { type: ObjectId , ref: 'AppSecret' }, //开发者用户Id createAt: { type: Date, default: Date.now }, updateAt: { type: Date, default: Date.now }, ``` ``` //User name : {type: String}, //评论上显示的名字 headimgurl: {type: String}, //评论上显示的用户头像链接 lastIp : {type: String}, //最后一次登陆的IP key: {type: String}, //自己系统上的ID,用来区分唯一性 appSecretId : { type: ObjectId , ref: 'AppSecret' }, //开发者用户Id createAt: { type: Date, default: Date.now }, updateAt: { type: Date, default: Date.now }, ```
Java
UTF-8
7,605
2.234375
2
[]
no_license
package com.tencent.hz.utils; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.os.Build; import android.view.Window; import android.view.WindowManager; public class Miscellaneous { /**************** * * 发起添加群流程。群号:android学习交流(1126670095) 的 key 为: lkhCw_ShTnxcfy9XRcdZG6kAgNW0B5Fr * 调用 加入群聊(lkhCw_ShTnxcfy9XRcdZG6kAgNW0B5Fr) 即可发起手Q客户端申请加群 流星国际体验服(1126670095) * * @param key 由官网生成的key * @return 返回true表示呼起手Q成功,返回fals表示呼起失败 ******************/ public static boolean 加入群聊(Context context, String key) { Intent jrql = new Intent(); jrql.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key)); // 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) try { context.startActivity(jrql); return true; } catch (Exception e) { // 未安装手Q或安装的版本不支持 MyToast.showLong(context, "未安装QQ或安装的版本不支持"); return false; } } public static boolean 联系QQ(Context context, String qq) { Intent lxqq = new Intent(); String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq; try { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } catch (Exception e) { // 未安装手Q或安装的版本不支持 e.printStackTrace(); MyToast.showLong(context, "未安装QQ或安装的版本不支持"); return false; } } public static boolean 邮箱反馈(Context context, String 收件人, String 抄送人, String 内容标题, String 内容) { Uri uri = Uri.parse("mailto:" + 收件人);//收件人 String[] email = {抄送人};//抄送人 Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra(Intent.EXTRA_CC, email); // 抄送人 intent.putExtra(Intent.EXTRA_SUBJECT, 内容标题); intent.putExtra(Intent.EXTRA_TEXT, 内容); try { context.startActivity(Intent.createChooser(intent, "邮件类应用")); return true; } catch (Exception e) { Toast.makeText(context, "未知错误", Toast.LENGTH_LONG).show(); return false; } } // 可逆的加密算法 public static String 可逆加密(String inStr) { // String s = new String(inStr); char[] a = inStr.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String s = new String(a); return s; } // 加密后解密 public static String 可逆解密(String inStr) { char[] a = inStr.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String k = new String(a); return k; } /*写出assets资源文件 *例子: * 写出assets资源文件(this,getFilesDir() + "/assets", "文件名");//这里写要写出的二进制文件 */ public static boolean 写出assets资源文件(Context context, String outPath, String fileName) { File file = new File(outPath); if (!file.exists()) { if (!file.mkdirs()) { Log.e("--Method--", "copyAssetsSingleFile: cannot create directory."); return false; } } try { InputStream inputStream = context.getAssets().open(fileName); File outFile = new File(file, fileName); FileOutputStream fileOutputStream = new FileOutputStream(outFile); // Transfer bytes from inputStream to fileOutputStream byte[] buffer = new byte[1024]; int byteRead; while (-1 != (byteRead = inputStream.read(buffer))) { fileOutputStream.write(buffer, 0, byteRead); } inputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } //调用事件S,运行二进制,等shell /** * 第一种:不能执行内存的二进制调用 * ExecuteElf("su");//申请root * ExecuteElf("chmod 777 "+getFilesDir()+"/assets/二进制文件名字");//,写二进制777权限 * ExecuteElf(getFilesDir()+"/assets/二进制文件名字");//执行二进制 * ------------------- * 第二种:什么都可以执行 * ExecuteElf("su -c"); * ExecuteElf("chmod 777 " + getFilesDir() + "/assets/二进制文件名字");//,写二进制777权限 * ExecuteElf("su -c " + getFilesDir() + "/assets/二进制文件名字");//执行二进制 * * @param shell */ public static void RunShell(String shell) { String s = shell; try { Runtime.getRuntime().exec(s, null, null);//执行 } catch (Exception e) { e.printStackTrace(); } } //点击返回桌面事件 public static void 返回桌面(Context context) { Intent mHomeIntent = new Intent(Intent.ACTION_MAIN); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); context.startActivity(mHomeIntent); }; //打开隐藏MIUI性能模式 public static void 打开MIUI性能模式(Context context) { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerModeSettings")); context.startActivity(intent); } // 网络连接判断 public static boolean 网络检测(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { return info.isConnected(); } else { return false; } } public static void StatusNavigationColor(Activity activity, int colorResId) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //顶部导航栏 Window window = activity.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(activity.getResources().getColor(colorResId)); //底部导航栏 window.setNavigationBarColor(activity.getResources().getColor(colorResId)); } } catch (Exception e) { e.printStackTrace(); } } }
Java
UTF-8
484
1.984375
2
[]
no_license
package com.example.awslambda.domain; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class StoreRepositoryTest { @Autowired private StoreRepository storeRepository; @Test void testSave() { Store s= new Store(); s=storeRepository.save(s); assertNotNull(s.getId()); } }
Python
UTF-8
3,733
2.53125
3
[]
no_license
#coding:utf-8 import csv import time import datetime import talib import pandas import numpy as np from DBHelper import DBHelper from DBConstants import DBConstants READ_DB_PATH = "/home/k-sui/fxdata/fxdata.db" WRITE_DB_PATH = "/home/k-sui/fxdata/fxdata.db" # 各インジケータを近いレンジになるように整形する() def formatIndicators(): # 読み込み用のDBHelperを作成(on memory) readIndiDBHelper = extractToMemory(READ_DB_PATH, DBConstants.INDICATOR_1HOUR_TBL, DBConstants.INDICATOR_COLUMNS, DBConstants.CREATE_INDICATOR_TABLE_STRING) readChartDBHelper = extractToMemory(READ_DB_PATH, DBConstants.CHART_1HOUR_TBL, DBConstants.CHART_COLUMNS, DBConstants.CREATE_CHART_TABLE_STRING) # 書き込み用のDBHelperを作成 writeDBHelper = DBHelper(WRITE_DB_PATH, DBConstants.INDICATOR_1HOUR_FORMAT_TBL, DBConstants.INDICATOR_COLUMNS) # 整形後のデータを格納するテーブルを作成 # writeDBHelper.createTable(DBConstants.CREATE_INDICATOR_TABLE_STRING) for row in readIndiDBHelper.getAllDataCursor(): # row = [time, sma5, sma25, rsi9, rsi11, rsi14, macd, macdsignal, macdhist, cci14, cci20, stocSlowk, stocSlowd, stocFastk, stocFastd, stocRSIk, stocRSId, trima5, trima25] # 同時刻の終値を取得 closePrice = readChartDBHelper.getCursor(row[0]).fetchone()[4] # 各カラムをそれぞれ整形 formated = [row[0], \ formatMA(row[1],closePrice), formatMA(row[2],closePrice), \ formatRSI(row[3]), formatRSI(row[4]), formatRSI(row[5]), \ formatMACD(row[6]), formatMACD(row[7]), formatMACD(row[8]), \ formatCCI(row[9]), formatCCI(row[10]), \ formatSTOC(row[11]), formatSTOC(row[12]), formatSTOC(row[13]), formatSTOC(row[14]), formatSTOC(row[15]), formatSTOC(row[16]), \ formatTRIMA(row[17],closePrice), formatTRIMA(row[18],closePrice)] # debug # print("compare row with formated") # print(row) # print(formated) # 書き込み writeDBHelper.add(formated) writeDBHelper.commit() # 移動平均からの終値の乖離率のイメージ。-1〜1のレンジにはかなり小さい値になるので、10倍しておく。 def formatMA(ma, close): if ma == 'nan': return 'nan' return (close-ma)*100.0 / ma # RSIは値が0〜100%なので、レンジが-1〜1になるよう、50を引いて100で割る def formatRSI(rsi): if rsi == 'nan': return 'nan' return (rsi * 1.0 - 50) / 100 # MACDはとりあえずそのままでレンジが合いそう def formatMACD(macd): if macd == 'nan': return 'nan' return macd # ±100%の前後で判断するので100で割ればおおよそレンジは合いそう def formatCCI(cci): if cci == 'nan': return 'nan' return cci/100 # ストキャスティクスは値が0〜100%なので、レンジが-1〜1になるよう、50を引いて100で割る def formatSTOC(stoc): if stoc == 'nan': return 'nan' return (stoc * 1.0 - 50) / 100 # 三角移動平均のレンジは移動平均と同じなので同じ計算式 def formatTRIMA(trima, close): if trima == 'nan': return 'nan' return (close-trima)*10.0 / trima def extractToMemory(dbPath, tableName, columns, createTBString): orgDB = DBHelper(dbPath, tableName, columns) onMemoryDB = DBHelper(':memory:', tableName, columns) onMemoryDB.createTable(createTBString) for row in orgDB.getAllDataCursor(): onMemoryDB.add(row) orgDB.close() orgDB = None return onMemoryDB if __name__ == "__main__": formatIndicators()
PHP
UTF-8
197
2.65625
3
[]
no_license
<?php class randomTemplate { public function randomize(){ $files = glob("templates" . '/*.*'); $file = array_rand($files); copy($files[$file],"templates/style.css"); } } ?>
PHP
UTF-8
1,298
2.59375
3
[ "MIT" ]
permissive
<?php namespace Dvsa\Olcs\Api\Domain\CommandHandler\IrhpPermitWindow; use Dvsa\Olcs\Api\Domain\CommandHandler\AbstractCommandHandler; use Dvsa\Olcs\Api\Domain\Exception\NotFoundException; use Dvsa\Olcs\Api\Domain\Exception\ValidationException; use Dvsa\Olcs\Transfer\Command\CommandInterface; /** * Delete an IRHP Permit Window * * @author Andy Newton */ final class Delete extends AbstractCommandHandler { protected $repoServiceName = 'IrhpPermitWindow'; /** * Delete Command Handler * * @param CommandInterface $command * @return \Dvsa\Olcs\Api\Domain\Command\Result * @throws ValidationException */ public function handleCommand(CommandInterface $command) { $id = $command->getId(); $window = $this->getRepo()->fetchById($id); if (!$window->canBeDeleted()) { throw new ValidationException(['irhp-permit-windows-cannot-delete-past-or-active-windows']); } try { $this->getRepo()->delete($window); $this->result->addId('id', $id); $this->result->addMessage(sprintf('Permit Window Deleted', $id)); } catch (NotFoundException $e) { $this->result->addMessage(sprintf('Id %d not found', $id)); } return $this->result; } }
TypeScript
UTF-8
4,519
3.03125
3
[ "MIT" ]
permissive
import { tValues, cValues, binomialCoefficients } from "./bezier-values"; import { Point } from "./types"; export const cubicPoint = (xs: number[], ys: number[], t: number): Point => { const x = (1 - t) * (1 - t) * (1 - t) * xs[0] + 3 * (1 - t) * (1 - t) * t * xs[1] + 3 * (1 - t) * t * t * xs[2] + t * t * t * xs[3]; const y = (1 - t) * (1 - t) * (1 - t) * ys[0] + 3 * (1 - t) * (1 - t) * t * ys[1] + 3 * (1 - t) * t * t * ys[2] + t * t * t * ys[3]; return { x: x, y: y }; }; export const cubicDerivative = (xs: number[], ys: number[], t: number) => { const derivative = quadraticPoint( [3 * (xs[1] - xs[0]), 3 * (xs[2] - xs[1]), 3 * (xs[3] - xs[2])], [3 * (ys[1] - ys[0]), 3 * (ys[2] - ys[1]), 3 * (ys[3] - ys[2])], t ); return derivative; }; export const getCubicArcLength = (xs: number[], ys: number[], t: number) => { let z: number; let sum: number; let correctedT: number; /*if (xs.length >= tValues.length) { throw new Error('too high n bezier'); }*/ const n = 20; z = t / 2; sum = 0; for (let i = 0; i < n; i++) { correctedT = z * tValues[n][i] + z; sum += cValues[n][i] * BFunc(xs, ys, correctedT); } return z * sum; }; export const quadraticPoint = ( xs: number[], ys: number[], t: number ): Point => { const x = (1 - t) * (1 - t) * xs[0] + 2 * (1 - t) * t * xs[1] + t * t * xs[2]; const y = (1 - t) * (1 - t) * ys[0] + 2 * (1 - t) * t * ys[1] + t * t * ys[2]; return { x: x, y: y }; }; export const getQuadraticArcLength = ( xs: number[], ys: number[], t: number ) => { if (t === undefined) { t = 1; } const ax = xs[0] - 2 * xs[1] + xs[2]; const ay = ys[0] - 2 * ys[1] + ys[2]; const bx = 2 * xs[1] - 2 * xs[0]; const by = 2 * ys[1] - 2 * ys[0]; const A = 4 * (ax * ax + ay * ay); const B = 4 * (ax * bx + ay * by); const C = bx * bx + by * by; if (A === 0) { return ( t * Math.sqrt(Math.pow(xs[2] - xs[0], 2) + Math.pow(ys[2] - ys[0], 2)) ); } const b = B / (2 * A); const c = C / A; const u = t + b; const k = c - b * b; const uuk = u * u + k > 0 ? Math.sqrt(u * u + k) : 0; const bbk = b * b + k > 0 ? Math.sqrt(b * b + k) : 0; const term = b + Math.sqrt(b * b + k) !== 0 && ((u + uuk) / (b + bbk)) != 0 ? k * Math.log(Math.abs((u + uuk) / (b + bbk))) : 0; return (Math.sqrt(A) / 2) * (u * uuk - b * bbk + term); }; export const quadraticDerivative = (xs: number[], ys: number[], t: number) => { return { x: (1 - t) * 2 * (xs[1] - xs[0]) + t * 2 * (xs[2] - xs[1]), y: (1 - t) * 2 * (ys[1] - ys[0]) + t * 2 * (ys[2] - ys[1]), }; }; function BFunc(xs: number[], ys: number[], t: number) { const xbase = getDerivative(1, t, xs); const ybase = getDerivative(1, t, ys); const combined = xbase * xbase + ybase * ybase; return Math.sqrt(combined); } /** * Compute the curve derivative (hodograph) at t. */ const getDerivative = (derivative: number, t: number, vs: number[]): number => { // the derivative of any 't'-less function is zero. const n = vs.length - 1; let _vs; let value; if (n === 0) { return 0; } // direct values? compute! if (derivative === 0) { value = 0; for (let k = 0; k <= n; k++) { value += binomialCoefficients[n][k] * Math.pow(1 - t, n - k) * Math.pow(t, k) * vs[k]; } return value; } else { // Still some derivative? go down one order, then try // for the lower order curve's. _vs = new Array(n); for (let k = 0; k < n; k++) { _vs[k] = n * (vs[k + 1] - vs[k]); } return getDerivative(derivative - 1, t, _vs); } }; export const t2length = ( length: number, totalLength: number, func: (t: number) => number ): number => { let error = 1; let t = length / totalLength; let step = (length - func(t)) / totalLength; let numIterations = 0; while (error > 0.001) { const increasedTLength = func(t + step); const increasedTError = Math.abs(length - increasedTLength) / totalLength; if (increasedTError < error) { error = increasedTError; t += step; } else { const decreasedTLength = func(t - step); const decreasedTError = Math.abs(length - decreasedTLength) / totalLength; if (decreasedTError < error) { error = decreasedTError; t -= step; } else { step /= 2; } } numIterations++; if (numIterations > 500) { break; } } return t; };
SQL
UTF-8
2,903
3.5
4
[]
no_license
CREATE TABLE closet ( id SERIAL PRIMARY KEY, closet_id integer, clothing_item integer, wearing boolean DEFAULT false ); CREATE TABLE clothing_item ( id SERIAL PRIMARY KEY, type integer, icon character varying(50), fit character varying(50), color character varying(50), length character varying(50), feature character varying(50) ); CREATE TABLE outfit ( id SERIAL PRIMARY KEY, outfit_id integer, clothing_item integer ); CREATE TABLE story ( id SERIAL PRIMARY KEY, senario character varying(1000) NOT NULL ); CREATE TABLE "user" ( id SERIAL PRIMARY KEY, username character varying(80) NOT NULL UNIQUE, password character varying(1000) NOT NULL, closet integer, -- TODO: storyState integer REFERENCES story(id), outfit integer ); INSERT INTO closet ("closet_id", "clothing_item", "wearing") VALUES (1, 25, TRUE) (1, 22, FALSE) (1, 17, FALSE) (1, 15, TRUE), (1, 20, FALSE); INSERT INTO clothing_item ("type", "icon", "fit", "color", "featureA", "featureB") VALUES (1, '______ |_ _| | | |___|', 'loose', 'grey', 'scoop neck', 'cap sleeve'), (1, '______ |_ _| | | |___|', 'tight', 'black', 'turtleneck', 'long'), (1, '______ |_ _| | | |___|', 'baggy', 'white', 'cardigan', 'knuckles'), (1, '______ |_ _| | | |___|', 'fitted', 'orange pattern', 'peterpan', 'sleevless'), (1, '______ |_ _| | | |___|', 'fitted', 'white', 'button up', 'short'), (1, '______ |_ _| | | |___|', 'normals', 'grey', 'ring', 'short'), (2, '______ | ^ | | | | | | | | |', 'tight', 'jeans', 'slim', 'heel'), (2, '______ | ^ | | | | | | | | |', 'normals', 'red with white stripe', '70s', 'thigh'), (2, '______ | ^ | | | | | | | | |', 'fitted', 'darkwash jeans', 'slim', 'heel'), (2, '______ | ^ | | | | | | | | |', 'loose', 'purple', 'bellbottoms', 'ankle'), (2, '______ | ^ | | | | | | | | |', 'sad tight', 'black', 'slacks', 'high rise'), (2, '______ | ^ | | | | | | | | |', 'saggy', 'acid wash jeans', 'bootcut', 'heel'); INSERT INTO outfit ("type", "clothing_item") VALUES (1, 15), (2, 25); INSERT INTO story (senario) VALUES ('Welcome to FASHION QUEST Let the adventure begin! *hint* to progress the story, type 'ok''), ('*ring ring ring*! Your friend Rick is calling.'), ('He wants to get coffee. Let''s get dressed. *hint* try typing ''outfit'', ''closet'', or ''change'''), ('you found an item'), ('where am i'), ('who are you and what is that');
C#
UTF-8
510
3.296875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericsInCShrap { class Program { static void Main(string[] args) { Comparision<int> comparison = new Comparision<int>(); Console.WriteLine(comparison.match(5, 5)); } } public class Comparision<T> { public bool match(T a, T b) { return a.Equals(b); } } }
Python
UTF-8
362
2.75
3
[]
no_license
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) LIGHT = 4 GPIO.setup(LIGHT,GPIO.OUT) try: while True : GPIO.output(LIGHT,True) time.sleep(0.5) GPIO.output(LIGHT,False) time.sleep(0.5) print("blink") except KeyboardInterrupt: GPIO.cleanup()
Markdown
UTF-8
3,214
2.5625
3
[ "MIT" ]
permissive
--- templateKey: blog-post title: Comandos de Git que uso todos los dìas date: 2021-01-18T17:16:47.524Z description: >- Recuerdo cuando empezaba a programar, hace mas o menos 8 años. La forma de agregar features a mi software era usando un servidor FTP y alterar archivos directo en el servidor. Hacìa backups duplicando la carpeta del còdigo, y luego la renombraba con un sufijo _BACKUP. Eso es cosa del pasado. Desde que aprendì las bases de git se ha vuelto a mi forma estàndar de trabajar con versionamiento de còdigo. Hoy te comparto los comandos que uso a diario, tal vez alguno te sirva. tags: - git - github - git commands --- ### TL;DR Estos comandos son bastante ùtiles para trabajar en equipo en el mismo repo de git. Desde como resetear una branch local, hasta como hacer rebase interactivo, cada comando tiene un valor bastante bueno en nuestra vida de programador. Todos los comandos estàn en [este gist](https://gist.github.com/LuisPaGarcia/cb52ac6163e9089155c3cebb99a41a68). ### Comandos y descripciòn corta Hacer stash de todos los archivos, nuevos o modificados . ```sh git stash save --include-untracked "nombre del stash" ``` Hacer stash de todos los archivos, nuevos o modificados MAS corto ```sh git stash -u ``` Retomar los cambios del ultimo stash guardado ```sh git stash pop ``` Hacer un hard reset local de una branch ```sh git reset --hard origin/branch_name ``` Remover N commits de una branch ```sh git reset --hard HEAD~5 # Ultimos 5 commits eliminados ``` Deshacer N commits de una branch, pero dejar los cambios locales ```sh git reset --soft HEAD~1 # Ultimo commit se convierte en cambios no commiteados ``` Actualizar branch actual con fetch y pull en un solo ```sh git fetch -p && git pull ``` Agregar cambios staged al ultimo commit, edita el ultimo commit ```sh git commit --amend --no-edit ``` Agregar commit (usando el hash) a la actual branch ```sh git cherry-pick ...HASH # 1 o > 1 hashes ``` Agregar cambios (usndo el hash) a la actual branch, como cambios no commiteados ```sh git cherry-pick -n ...HASH # 1 o > 1 hashes ``` Ver los commits en una linea cada uno ```sh git log --pretty=oneline --abbrev-commit ``` Ver los commits con un log mas legible ```sh git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit ``` Obtener el hash del ultimo commit ```sh git rev-parse --verify HEAD ``` Usar git rebase interactive para eliminar commits dentro de la branch ```sh git rebase -i HEAD~N # N es el numero de los ultimos de commits a evaluar ``` Usar siempre nano para editar rebases, mensajes de git, y asi ```sh git config --global core.editor "nano" ``` Como solucionar el CRLF problem en Windows y Git, [fuente] (https://stackoverflow.com/questions/49228693/how-to-change-eol-for-all-files-from-clrf-to-lf-in-visual-studio-code ) ```sh git config core.autocrlf false && git rm --cached -r . && git reset --hard ``` Asumir que un archivo no ha sido cambiado , y que git no lo trackee. ```sh git update-index --assume-unchanged /path/to/file ``` Espero que algùn comando te sirva. Happy coding!
C#
UTF-8
749
3.015625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsumerProducer { class Writer { private Data data; private Random rnd; private bool stopper; public Writer(Data data) { this.data = data; rnd = new Random(); } public void writeData() { while (!stopper) { Console.WriteLine("writer writing..."); data.addData(this.rnd.Next(1, 1000000)); Thread.Sleep(100); } } public void reqStop() { stopper = true; } } }
Java
UTF-8
653
2.625
3
[ "MIT" ]
permissive
package biologicalparkticketsystem.model.course; /** * Interface to define criteria strategy used for path calculation */ public interface ICriteriaStrategy { /** * Method to retrieve the edge weight depending on the strategy * @param connection connection to get weight * @return edge weight */ double getEdgeWeight(Connection connection); /** * Method to return criteria unit value * @return criteria unit */ String getUnit(); /** * Method to return criteria name * @return criteria name */ @Override String toString(); }
JavaScript
UTF-8
1,968
2.96875
3
[]
no_license
const range = document.querySelector("#strength"); const circle = document.querySelector(".dot"); const color = (e) => { if (e === "1") { circle.style.backgroundColor = "#D7CCC8"; } else if (e === "2") { circle.style.backgroundColor = "#BCAAA4"; } else if (e === "3") { circle.style.backgroundColor = "#A1887F"; } else if (e === "4") { circle.style.backgroundColor = "#8D6E63"; } else if (e === "5") { circle.style.backgroundColor = "#795548"; } else if (e === "6") { circle.style.backgroundColor = "#6D4C41"; } else if (e === "7") { circle.style.backgroundColor = "#5D4037"; } else if (e === "8") { circle.style.backgroundColor = "#4E342E"; } else if (e === "9") { circle.style.backgroundColor = "#3E2723"; } }; const data = document.querySelector("#data"); auth.onAuthStateChanged((user) => { db.collection("Restrictions") .doc(`${auth.currentUser.uid}`) .get() .then((doc) => { if (doc.exists) { data.name.value = doc.data().name; data.strength.value = parseInt(doc.data().strength) / 100; color((doc.data().strength/100).toString()); data.sugar.value = doc.data().sugar; } }) .catch((error) => { console.log("Error getting document:", error); }); }); data.addEventListener("submit", (e) => { e.preventDefault(); db.collection("Restrictions") .doc(`${auth.currentUser.uid}`) .set({ name: data.name.value, strength: parseInt(data.strength.value) * 100, sugar: data.sugar.value, }) .then(() => { data.reset(); window.location.href = "../order_page/order.html"; }); }); const slider = range.addEventListener("input", (e) => { console.log(e.target.value); color(e.target.value); });
Java
UTF-8
116
2.34375
2
[ "MIT" ]
permissive
interface Numbers { static double twoDecimalPlaces(double number) { return (int) (number * 100) / 100.; } }
Java
UTF-8
4,298
2.59375
3
[]
no_license
package com.neo.headhunter.manager.bounty; import com.neo.headhunter.HeadHunter; import com.neo.headhunter.util.config.ConfigAccessor; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.ConfigurationSection; import java.util.*; public final class BountyManager extends ConfigAccessor { private static final int LIST_PAGE_SIZE = 10; private List<BountyListEntry> bountyList; public BountyManager(HeadHunter plugin) { super(plugin, true, "bounties.yml", "data"); this.bountyList = getBountyList(); Collections.sort(this.bountyList); } // returns the total of all bounties on the victim public double getTotalBounty(OfflinePlayer victim) { double total = 0; ConfigurationSection victimSection = config.getConfigurationSection(id(victim)); if (victimSection != null) { for (String hunterKey : victimSection.getKeys(false)) { total += victimSection.getDouble(hunterKey); } } return total; } // returns the hunter's bounty on the victim public double getBounty(OfflinePlayer hunter, OfflinePlayer victim) { return config.getDouble(bountyPath(hunter, victim)); } // set's the hunter's bounty on the victim to the specified amount public void setBounty(OfflinePlayer hunter, OfflinePlayer victim, double amount) { config.set(bountyPath(hunter, victim), amount); saveConfig(); } // deletes all bounties on the victim, and returns their total public double removeTotalBounty(OfflinePlayer victim) { double totalBounty = getTotalBounty(victim); config.set(id(victim), null); saveConfig(); return totalBounty; } // deletes the hunter's bounty on the victim, and returns its amount public double removeBounty(OfflinePlayer hunter, OfflinePlayer victim) { double bounty = getBounty(hunter, victim); config.set(bountyPath(hunter, victim), null); ConfigurationSection victimSection = config.getConfigurationSection(id(victim)); if (victimSection == null || victimSection.getKeys(false).isEmpty()) { config.set(id(victim), null); } saveConfig(); return bounty; } public BountyListEntry getListEntry(int index) { try { return bountyList.get(index); } catch (IndexOutOfBoundsException ex) { return null; } } public List<BountyListEntry> getBountyListPage(int page) { List<BountyListEntry> result = new ArrayList<>(); if (!bountyList.isEmpty()) { int totalPages = (bountyList.size() - 1) / LIST_PAGE_SIZE + 1; if (page <= totalPages) { int fromIndex = Math.max(0, (page - 1) * LIST_PAGE_SIZE); int toIndex = Math.min(bountyList.size(), page * LIST_PAGE_SIZE); result.addAll(bountyList.subList(fromIndex, toIndex)); return result; } return null; } return result; } public OfflinePlayer getTopHunter(OfflinePlayer victim) { String victimPath = id(victim); ConfigurationSection hunterSection = config.getConfigurationSection(victimPath); String topHunterPath = null; double maxBounty = 0; if (hunterSection != null) { for (String hunterPath : hunterSection.getKeys(false)) { double bounty = hunterSection.getDouble(hunterPath); if (maxBounty < bounty || maxBounty == 0) { topHunterPath = hunterPath; maxBounty = bounty; } } } if (topHunterPath != null) { return Bukkit.getOfflinePlayer(UUID.fromString(topHunterPath)); } return null; } // helper method to improve readability private String bountyPath(OfflinePlayer hunter, OfflinePlayer victim) { return id(victim) + "." + id(hunter); } // helper method to improve readability private String id(OfflinePlayer player) { if (player != null) { return player.getUniqueId().toString(); } return null; } private List<BountyListEntry> getBountyList() { List<BountyListEntry> result = new ArrayList<>(); for (String victimIdString : config.getKeys(false)) { UUID victimId = UUID.fromString(victimIdString); OfflinePlayer victim; if ((victim = Bukkit.getPlayer(victimId)) == null) { victim = Bukkit.getOfflinePlayer(victimId); } double amount = getTotalBounty(victim); result.add(new BountyListEntry(victim, amount)); } return result; } @Override protected void saveConfig() { super.saveConfig(); this.bountyList = getBountyList(); Collections.sort(this.bountyList); } }
PHP
UTF-8
6,468
2.578125
3
[]
no_license
<?php /*================================================== MODELE MVC DEVELOPPE PAR Ngor SECK ngorsecka@gmail.com (+221) 77 - 433 - 97 - 16 PERFECTIONNEZ CE MODEL ET FAITES MOI UN RETOUR VOUS ETES LIBRE DE TOUTE UTILISATION Document redefini par samane_ui_admin de Pierre Yem Mback dialrock360@gmail.com ==================================================*/ namespace src\entities; use libs\system\Entitie; /*==================Classe creer par Samane samane_ui_admin le 11-12-2019 15:09:38=====================*/ class Department extends Entitie { /*==================Attribut liste=====================*/ private $iddep; private $ids; private $nomd; private $flag; /*==================End Attribut liste=====================*/ /*================== Constructor =====================*/ public function __construct() { parent::__construct(); $this->tablename="department"; $this->iddep = 'null' ; $this->ids = 0 ; $this->nomd = "" ; $this->flag = 0 ; } /*==================End constructor=====================*/ /*==================Getters liste=====================*/ public function getIddep() { return $this->iddep; } public function getIds() { return $this->ids; } public function getNomd() { return $this->nomd; } public function getFlag() { return $this->flag; } /*==================End Getters liste=====================*/ /*==================Setters liste=====================*/ public function setIddep($iddep) { $this->iddep = $iddep; } public function setIds($ids) { $this->ids = $ids; } public function setNomd($nomd) { $this->nomd = $nomd; } public function setFlag($flag) { $this->flag = $flag; } /*==================End Setters liste=====================*/ /*==================Persistence Methode list=====================*/ /*================== Count department =====================*/ public function countDepartment(){ $this->db->setTablename($this->tablename); return $this->db->getRows(array("return_type"=>"count")); } /*================== Get department =====================*/ public function get(){ $this->db->setTablename($this->tablename); $condition = array("iddep" =>$this->iddep); return $this->db->getRows(array("where"=>$condition,"return_type"=>"single")); } /*================== Liste department =====================*/ public function liste(){ $this->db->setTablename($this->tablename); return $this->db->getRows(array("return_type"=>"many")); } public function insert(){ $this->setTablename("department"); $this->setTablearray($this->ObjecToarrayMaker()); return $this->post(); } public function update(){ $this->setTablename("department"); $condition = array( 'iddep'=>$this->iddep ); $this->setTablearray($this->ObjecToarrayMaker()); return $this->put($condition); } public function delete(){ $this->setTablename("department"); $condition = array( 'iddep'=>$this->iddep ); return $this->remove($condition); } public function fldelete(){ $this->db->setTablename($this->tablename); return $id_department = $this->db->updateTable($this->ObjecToarrayMaker()); } /*================== If department existe =====================*/ public function ifDepartmentexiste($condition){ $this->db->setTablename($this->tablename); $existe=$this->db->getRows(array("where"=>$condition,"return_type"=>"single")); if($existe != null) { return 1; } return 0; } public function setPost($post,$file=array()){ extract($post); $this->iddep = (!isset($iddep) || empty($iddep) ) ? 0: $iddep; $this->ids = (!isset($ids) || empty($ids) ) ? 0: $ids; $this->nomd = (!isset($nomd) || empty($nomd) ) ? '': $nomd; $this->flag = (!isset($flag) || empty($flag) ) ? 0: $flag; } private function ObjecToarrayMaker(){ $OldTable=$this->emptyarrayMaker(); if ($this->id>0){ $OldTable=$this->get(); } $Table= array( 'iddep'=>($this->iddep == 0 || $this->iddep == 'null') ? $OldTable['iddep']:$this->iddep, 'ids'=>($this->ids == 0 ) ? $OldTable['ids']:$this->ids, 'NOMD'=>(!isset($this->nomd) || empty($this->nomd) ) ? $OldTable['nomd']:$this->nomd, 'flag'=>($this->flag == 0 ) ? $OldTable['flag']:$this->flag ); return $Table; } private function emptyarrayMaker(){ $Table= array( 'iddep'=>'null', 'ids'=>0, 'NOMD'=>"", 'flag'=>0 ); return $Table; } /*==================End Persistence Methode list=====================*/ } ?>
C#
UTF-8
797
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Plugin.Connectivity; namespace feelLuckyApp { public class CloudDataStore : IDataStore { HttpClient client; public CloudDataStore() { client = new HttpClient(); client.BaseAddress = new Uri($"{App.BackendUrl}/"); } public string GetLuckyString(bool forceRefresh = false) { string luckystring = "You are lucky today!"; if (forceRefresh && CrossConnectivity.Current.IsConnected) { luckystring = client.GetStringAsync(client.BaseAddress).Result; } return luckystring; } } }
Java
UTF-8
417
2.453125
2
[]
no_license
package com.anup.paint.command.exception; import com.anup.paint.command.model.InputCommand; public class CommandTypeNotSupportedBaseException extends InputCommandBaseException { public CommandTypeNotSupportedBaseException(InputCommand input) { super("Command type - "+input.getCommandType()+" not supported "); } public CommandTypeNotSupportedBaseException(String s) { super(s); } }
PHP
UTF-8
1,131
2.640625
3
[]
no_license
<?php namespace app\modules\mediator\implementation\messages; use app\modules\contactList\externalContracts\give\UserGetContactsInterface; use app\modules\messages\externalContracts\get\UserContactListInterface; use app\modules\user\externalContracts\give\UserFinderInterface; class UserContactList implements UserContactListInterface { /** @var UserGetContactsInterface */ private $userGetContacts; /** @var UserFinderInterface */ private $userFinder; /** * UserContactList constructor. * @param UserGetContactsInterface $userGetContacts * @param UserFinderInterface $userFinder */ public function __construct(UserGetContactsInterface $userGetContacts, UserFinderInterface $userFinder) { $this->userGetContacts = $userGetContacts; $this->userFinder = $userFinder; } /** * @inheritDoc */ public function getUserContactList($userId) { return array_map( function($el) { return $this->userFinder->getUserById($el); }, $this->userGetContacts->getUserContactsIdList($userId) ); } }
Python
UTF-8
3,107
2.703125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # created on 2014-03-31 19:07:37 """ 做成类似于Spring的@RequestParam注解的decorator形式,但是现在获得的函数参数有些问题 """ __author__ = 'wangqunwhuhb@126.com' import inspect import logging def str2IntList(s): return map(int, s) def request_param(method="GET", arg_offset=1, *args, **kwargs): """ this decorator's function is as java spring framewrok's @RequestParam anotation make sure to put it adjust to the view function as it will get view's args """ if len(args) > 0: raise ValueError("request_param cannot process args without default value") def __method(func): # get func's arg names argSpec = inspect.getargspec(func) ARG_NAME_LIST = argSpec.args ARG_DEFAULT_VALUE_TUPLE = argSpec.defaults HAS_DEFAULT_VALUE_INDEX = len(ARG_NAME_LIST) - len(ARG_DEFAULT_VALUE_TUPLE) def __call(*innerArgs, **innerKWargs): logging.debug("innerKWargs: %s ", str(innerKWargs)) logging.debug("kwargs: %s", str(kwargs)) logging.debug("HAS_DEFAULT_VALUE_INDEX: %d", HAS_DEFAULT_VALUE_INDEX) request = innerArgs[0] if request.method in method: if request.method == "GET": params = request.GET elif request.method == "POST": params = request.POST else: raise ValueError("unsupported method %s in request_param"%(request.method)) for i in range(arg_offset, len(ARG_NAME_LIST)): arg = ARG_NAME_LIST[i] if arg in innerKWargs: logging.debug("ignore %s as it has been filled", arg) continue convertor = kwargs.get(arg, None) if isinstance(convertor, tuple): logging.debug("get %s using getlist method", arg) value = params.getlist(arg, None) else: value = params.get(arg, None) if value == None or value == []: if i < HAS_DEFAULT_VALUE_INDEX: msg = "%s need param"%arg logging.debug(msg) raise ValueError(msg) else: logging.debug("do not find value for arg: %s, use default value", arg) else: #first convert string to the appropriate value if necessary #convert value if its not a list if convertor: convertor_func = convertor if not isinstance(convertor, tuple) else convertor[0] logging.debug("convertor arg: %s value: %s using %s", arg, str(value), convertor_func.__name__) value = convertor_func(value) innerKWargs[arg] = value logging.debug("mapping param %s to value %s", arg, value) return func(*innerArgs, **innerKWargs) return __call return __method
Java
UTF-8
4,748
1.976563
2
[]
no_license
package com.cczu.model.sbssgl.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.cczu.model.entity.BIS_EnterpriseEntity; import com.cczu.model.sbssgl.entity.SBSSGL_DXJEntity; import com.cczu.model.sbssgl.service.SBSSGLDxjService; import com.cczu.model.service.impl.BisQyjbxxServiceImpl; import com.cczu.sys.comm.controller.BaseController; import com.cczu.sys.system.service.ShiroRealm.ShiroUser; import com.cczu.sys.system.utils.UserUtil; /** * 设备设施管理-点巡检controller */ @Controller @RequestMapping("sbssgl/dxj") public class PageSbssglDxjController extends BaseController { @Autowired private SBSSGLDxjService sBSSGLDxjService; @Autowired private BisQyjbxxServiceImpl qyjbxxServiceImpl; /** * 列表显示页面 * @param model */ @RequestMapping(value="index") public String index(Model model, HttpServletRequest request) { ShiroUser sessionuser= UserUtil.getCurrentShiroUser(); if(sessionuser.getUsertype().equals("1")){//企业用户 BIS_EnterpriseEntity be = qyjbxxServiceImpl.findInfoById(sessionuser.getQyid()); if(be!=null&&be.getM1()!=null){//判断是否添加了企业基本信息 if(be.getIsbloc()!=null&&be.getIsbloc()==1)//判断是否为集团公司 model.addAttribute("type","2");//集团公司 else model.addAttribute("type","1");//子公司 }else//未添加企业基本信息错误提示页面 return "../error/001"; }else{ return "../error/403"; } if ("tzsb".equals(request.getParameter("sbtype"))) { model.addAttribute("sbtype","1");//特种设备 } else { model.addAttribute("sbtype","0");//普通设备 } return "sbssgl/dxj/index"; } /** * list页面 * @param request */ @RequestMapping(value="list") @ResponseBody public Map<String, Object> getData(HttpServletRequest request) { Map<String, Object> map = getPageMap(request); map.put("sbtype", request.getParameter("sbtype")); map.put("qyname", request.getParameter("qyname")); map.put("m1", request.getParameter("m1")); map.put("m2", request.getParameter("m2")); map.put("m3", request.getParameter("m3")); map.putAll(getAuthorityMap()); return sBSSGLDxjService.dataGrid(map); } /** * 删除 */ @RequestMapping(value = "delete/{ids}") @ResponseBody public String delete(@PathVariable("ids") String ids) { String datasuccess="删除成功"; //可以批量删除 String[] aids = ids.split(","); for(int i=0;i<aids.length;i++){ //删除点巡检信息 sBSSGLDxjService.deleteInfoById(Long.parseLong(aids[i])); } return datasuccess; } /** * 查看页面跳转 * @param id,model */ @RequestMapping(value = "view/{id}", method = RequestMethod.GET) public String view(@PathVariable("id") Long id, Model model) { //获取点巡检信息 Map<String,Object> dxj = sBSSGLDxjService.findById(id); model.addAttribute("dxj", dxj); return "sbssgl/dxj/view"; } /** * 添加页面跳转 * @param model */ @RequestMapping(value = "create" , method = RequestMethod.GET) public String create(Model model, HttpServletRequest request) { model.addAttribute("action", "create"); model.addAttribute("sbtype", request.getParameter("sbtype")); return "sbssgl/dxj/form"; } /** * 添加信息 * @param request,model */ @RequestMapping(value = "create" , method = RequestMethod.POST) @ResponseBody public String create(SBSSGL_DXJEntity entity, Model model,HttpServletRequest request) { String datasuccess="success"; sBSSGLDxjService.addInfo(entity); //返回结果 return datasuccess; } /** * 修改页面跳转 * @param id,model */ @RequestMapping(value = "update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") Long id, Model model, HttpServletRequest request) { SBSSGL_DXJEntity dxj = sBSSGLDxjService.find(id); model.addAttribute("dxj", dxj); //返回页面 model.addAttribute("action", "update"); model.addAttribute("sbtype", request.getParameter("sbtype")); return "sbssgl/dxj/form"; } /** * 修改信息 * @param request,model */ @RequestMapping(value = "update") @ResponseBody public String update(SBSSGL_DXJEntity entity, Model model,HttpServletRequest request){ String datasuccess="success"; sBSSGLDxjService.updateInfo(entity); //返回结果 return datasuccess; } }
C#
UTF-8
782
2.828125
3
[]
no_license
using SocketsShared.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebSocketsService.Hubs; namespace WebSocketsService.Mapper { public static class HubMapper { public static HubDto Map(this BaseHub hub) { return new HubDto { guid = hub.guid.ToString(), type = hub.hubType.ToString(), name = hub.GetType().Name }; } public static IEnumerable<HubDto> Map(this IEnumerable<BaseHub> hubs) { List<HubDto> listHubs = new(); foreach(var hub in hubs) { listHubs.Add(hub.Map()); } return listHubs; } } }
Java
UTF-8
4,124
2.0625
2
[]
no_license
package com.netmi.baselibrary.widget; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.netmi.baselibrary.R; import com.netmi.baselibrary.data.entity.ShareEntity; import com.netmi.baselibrary.utils.AppUtils; import java.util.HashMap; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.PlatformActionListener; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.wechat.friends.Wechat; import cn.sharesdk.wechat.moments.WechatMoments; /** * 类描述: * 创建人:Simple * 创建时间:2017/12/14 18:37 * 修改备注: */ public class ShareDialog extends Dialog implements PlatformActionListener { private ShareEntity entity; public ShareDialog(Context context, ShareEntity shareEntity) { super(context, R.style.showDialog); entity = shareEntity; if (entity == null) { entity = new ShareEntity(); entity.setActivity((Activity) context); } initUI(); } /** * 对话框布局初始化 */ private void initUI() { setContentView(R.layout.baselib_dialog_share_layout); findViewById(R.id.rl_wechat_friend).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(AppUtils.hasFunction()) return; shareToPlatform(Wechat.NAME); dismiss(); } }); findViewById(R.id.rl_wechat_circle).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(AppUtils.hasFunction()) return; shareToPlatform(WechatMoments.NAME); dismiss(); } }); findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } /** * 显示 */ public void showDialog() { Window dialogWindow = getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialogWindow.setAttributes(lp); dialogWindow.setWindowAnimations(R.style.dialog_bottom_anim_style); dialogWindow.setGravity(Gravity.BOTTOM); show(); } private void shareToPlatform(String platformName) { if (entity != null) { Platform.ShareParams shareParams = new Platform.ShareParams(); shareParams.setShareType(Platform.SHARE_WEBPAGE); shareParams.setTitle(entity.getTitle()); shareParams.setUrl(entity.getLinkUrl()); shareParams.setText(entity.getContent()); shareParams.setImageUrl(entity.getImgUrl()); Platform platform = ShareSDK.getPlatform(platformName); platform.setPlatformActionListener(this); platform.share(shareParams); } else { Toast.makeText(getContext(), "请先初始化分享数据!", Toast.LENGTH_SHORT).show(); } } @Override public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) { doResult(1, "感谢您的分享"); } @Override public void onError(Platform platform, int i, Throwable throwable) { doResult(-1, "分享失败了T.T"); } @Override public void onCancel(Platform platform, int i) { //doResult(0, "您取消了分享!"); } private void doResult(int resultCode, final String msg) { if (entity != null) { entity.getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } }); } } }
C++
UTF-8
371
3.390625
3
[]
no_license
#include <string> #include <algorithm> #include <iostream> using namespace std; string convertToTitle(int columnNumber) { string ans; while (columnNumber--) { ans += columnNumber % 26 + 'A'; columnNumber /= 26; } reverse(ans.begin(), ans.end()); return ans; } int main() { string ans = convertToTitle(52); cout << ans; }
Python
UTF-8
161
2.796875
3
[]
no_license
import turtle_square_using_function repeat = 5; while(repeat>0): print("repeat : ",str(repeat)); turtle_square_using_function.square(); repeat -= 1
Markdown
UTF-8
1,478
2.90625
3
[]
no_license
title: Swift设计模式之策略模式 categories: ios tags: 设计模式 date: 2016-05-10 17:36:01 --- <!--head--> **转自** * [Swift设计模式](http://qefee.com/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/) **原文** * [Design-Patterns-In-Swift](https://github.com/ochococo/Design-Patterns-In-Swift#behavioral) <!--more--> <!--body--> ```swift // 策略模式 // 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化 // 设计模式分类:行为型模式 /** * 打印策略接口 */ protocol PrintStrategy { func printString(string: String) -> String } /// 打印机类 class Printer { let strategy: PrintStrategy func printString(string: String) -> String { return self.strategy.printString(string) } init(strategy: PrintStrategy) { self.strategy = strategy } } /// 大写打印策略 class UpperCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.uppercaseString } } /// 小写打印策略 class LowerCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.lowercaseString } } var lower = Printer(strategy:LowerCaseStrategy()) lower.printString("O tempora, o mores!") var upper = Printer(strategy:UpperCaseStrategy()) upper.printString("O tempora, o mores!") ```
Python
UTF-8
508
3.5625
4
[]
no_license
#!/usr/bin/env python3 """ Module to add matrices """ def add_matrices(mat1, mat2): """ Adds two matrices """ if len(mat1) != len(mat2): return None addMatrix = [] for i in range(len(mat1)): if isinstance(mat1[i], list): resultAxis = add_matrices(mat1[i], mat2[i]) if resultAxis is None: return None addMatrix.append(resultAxis) else: addMatrix.append(mat1[i] + mat2[i]) return addMatrix
PHP
UTF-8
5,383
2.609375
3
[ "MIT" ]
permissive
<?php namespace Bdf\Prime\Mapper\Info; use Bdf\Prime\Mapper\Metadata; use Bdf\Prime\Types\PhpTypeInterface; use Bdf\Prime\Types\TypeInterface; use Bdf\Prime\Types\TypesRegistryInterface; use DateTimeInterface; /** * PropertyInfo */ class PropertyInfo implements InfoInterface { /** * The property name * * @var string */ protected $name; /** * The metadata from the metadata object * * @var array */ protected $metadata; /** * The metadata from the metadata object * * @var array */ protected $relation; /** * The types registry * * @var TypesRegistryInterface */ protected $typesRegistry; /** * Constructor * * @param string $name The property name * @param array $metadata The property metadata or the relation metadata * @param TypesRegistryInterface|null $typesRegistry The types registry */ public function __construct(string $name, array $metadata = [], ?TypesRegistryInterface $typesRegistry = null) { $this->name = $name; $this->metadata = $metadata; $this->typesRegistry = $typesRegistry; } /** * {@inheritdoc} */ public function name(): string { return $this->name; } /** * Get the property type * * @return string */ public function type(): string { return $this->metadata['type']; } /** * Get the property alias * * @return string|null */ public function alias(): ?string { return $this->metadata['field'] !== $this->metadata['attribute'] ? $this->metadata['field'] : null; } /** * Get the php type of the property * Class should have '\' char to be resolved with namespace. * * @return string */ public function phpType(): string { if (isset($this->metadata['phpOptions']['className'])) { return '\\'.ltrim($this->metadata['phpOptions']['className'], '\\'); } $type = $this->type(); if ($this->typesRegistry === null || !$this->typesRegistry->has($type)) { return $type; } return $this->typesRegistry->get($type)->phpType(); } /** * Check whether the property is a primary key * * @return bool */ public function isPrimary(): bool { return $this->metadata['primary'] !== null; } /** * Check if the property value is auto-generated (auto increment or sequence) * * @return bool */ public function isGenerated(): bool { return in_array($this->metadata['primary'], [Metadata::PK_AUTOINCREMENT, Metadata::PK_SEQUENCE], true); } /** * Check if the property can be null * * - Marked as nullable on mapper * - It's value is auto-generated * * @return bool */ public function isNullable(): bool { return !empty($this->metadata['nillable']) || $this->isGenerated(); } /** * {@inheritdoc} */ public function isEmbedded(): bool { return $this->metadata['embedded'] !== null; } /** * {@inheritdoc} */ public function belongsToRoot(): bool { return !$this->isEmbedded(); } /** * {@inheritdoc} */ public function isObject(): bool { return false; } /** * Check whether the property is a date time object * * @return bool */ public function isDateTime(): bool { return is_subclass_of($this->phpType(), DateTimeInterface::class); } /** * Gets the date timezone * * @return string|null */ public function getTimezone(): ?string { if (!$this->isDateTime()) { return null; } if (isset($this->metadata['phpOptions']['timezone'])) { return $this->metadata['phpOptions']['timezone']; } /** @var \Bdf\Prime\Types\AbstractDateTimeType $type */ $type = $this->getType(); /** @var \DateTimeZone $timezone */ $timezone = $type->getTimezone(); return $timezone ? $timezone->getName() : null; } /** * {@inheritdoc} */ public function isArray(): bool { return $this->phpType() === PhpTypeInterface::TARRAY; } /** * Check whether the property has a default value * * @return bool */ public function hasDefault(): bool { return $this->getDefault() !== null; } /** * Get the default value * * @return mixed */ public function getDefault() { return $this->metadata['default']; } /** * Get the default value * * @param mixed $value * @param bool $toPhp * @param array $fieldOptions * * @return mixed */ public function convert($value, bool $toPhp = true, array $fieldOptions = []) { if ($toPhp) { return $this->getType()->fromDatabase($value, $fieldOptions); } return $this->getType()->toDatabase($value); } /** * Get the type object * * @return TypeInterface */ protected function getType() { return $this->typesRegistry->get($this->type()); } }