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
PHP
UTF-8
1,466
2.609375
3
[]
no_license
<?php namespace LwcBlog\Form; use Zend\Form\Element\Submit; use Zend\Form\Element\Textarea; use Zend\Form\Element\Text; use Zend\Form\Element\Hidden; use Zend\Form\Form; class EntryForm extends Form { public function __construct($name = null) { // we want to ignore the name passed parent::__construct('entry'); $title = new Text('title'); $title->setAttribute('maxlength', 70) ->setLabel('Name'); $this->add($title); $id = new Hidden('id'); $id->setAttribute('maxlength', 10) ->setLabel('Id'); $this->add($id); $text = new Textarea('text'); $text->setAttributes(array( 'cols' => 60, 'rows' => 10 )) ->setLabel('Text'); $this->add($text); $button = new Submit('submitEntry'); $button->setAttribute('class', 'btn btn-primary') ->setValue('Submit Entry'); $this->add($button); //@TODO define input filter //$this->setInputFilter($inputFilter); } /* * public function getInputFilterSpecification() { $nameInput = new Input('name'); // configure input... and all others $inputFilter = new InputFilter(); // attach all inputs $form->setInputFilter($inputFilter); }*/ }
Java
UTF-8
1,308
3.0625
3
[]
no_license
package com.javarush.task.task19.task1921; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Pattern; /* Хуан Хуанович */ public class Solution { public static final List<Person> PEOPLE = new ArrayList<Person>(); public static void main(String[] args) throws IOException, ParseException { BufferedReader bfr = new BufferedReader(new FileReader(args[0])); String pattern = "dd MM yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); while (bfr.ready()) { String line = bfr.readLine(); System.out.println(line); String[] mass = line.trim().split("\\s+"); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < mass.length - 3; i++) { stringBuilder.append(mass[i]).append(" "); } Date data = simpleDateFormat.parse(mass[mass.length - 3] + " " + mass[mass.length - 2] + " " + mass[mass.length - 1]); PEOPLE.add(new Person(stringBuilder.substring(0,stringBuilder.length()-1), data)); } bfr.close(); } }
Java
UTF-8
242
1.554688
2
[]
no_license
package com.controlechamada.chamada.repositories; import com.controlechamada.chamada.domain.entities.Aula; import org.springframework.data.jpa.repository.JpaRepository; public interface AulaRepository extends JpaRepository<Aula, Long> { }
Python
UTF-8
5,395
3.5625
4
[]
no_license
account_details = {} def user_verification(email): if email in account_details.keys(): return email return False def check_password(password,confirm_password): if len(password) > 5: if password == confirm_password: return password else: return False def create_account(): print("\nCREATE NEW ACCOUNT\n") new_email = str(input("Enter a valid email: ")).lower() #check email format~ if len(new_email) > 5 and ('@' in new_email) and ('.' in new_email): if user_verification(new_email): print("Email Already exists! Try again") create_account() else: new_password = str(input("Enter a valid password: ")) confirm_password = str(input("Confirm password: ")) if check_password(new_password, confirm_password): account_details[new_email] = {'password' : new_password, 'balance': 0.00} print("Account created successfully!") landing_page() else: print("****** Invalid Password ******\n") create_account() else: print("Invalid Email address") create_account() def authenticate_user(): print("\n>>>>>>>>> LOG IN <<<<<<<<\n") user_email = str(input("Enter email: ")).lower() user_password = str(input("Enter password: ")) if user_email in account_details.keys(): if account_details[user_email]['password'] == user_password: transaction_options(user_email) else: print("User don't exist! Create Account\n" ) create_account() def transaction_options(account): print("\n******* TRANSACTION PAGE *********\n") more_options = int(input(''' Press 1: check balance Press 2: deposit Press 3: withdraw Press 4: transfer Press 0: To return to home ''')) if more_options == 1: check_balance(account) elif more_options == 2: make_deposit(account) elif more_options == 3: make_withdrawal(account) elif more_options == 4: make_transfer(account) elif more_options == 0: landing_page() else: print("Enter a valid action") transaction_options(account) def check_balance(account): print("\n====================== CHECK BALANCE ===================\n") print("Your account balance is: ", account_details[account]['balance']) transaction_options(account) def make_deposit(account): print("\n====================== MAKE DEPOSIT ===================\n") deposit_amount = int(input("Input amount to be deposited:\n")) account_details[account]['balance'] = account_details[account]['balance'] + deposit_amount new_balance = account_details[account]['balance'] print("Amount deposited: ", deposit_amount, "\nAvailable balance: ", new_balance) transaction_options(account) def make_withdrawal(account): print("\n====================== MAKE WITHDRAWAL ===================\n") amount = int(input("Input amount to withdraw:\n ")) if bank_accounts[account]['balance'] == 0.00: print("You have no money in your account. Kindly make deposit and try again.\n") make_deposit(account) elif bank_accounts[account]['balance'] < amount: print("Cannot withdraw more than you have in your account\n ") make_deposit(account) else: account_details[account]['balance'] = account_details[account]['balance'] - amount current_balance = account_details[account]['balance'] print("\n============== Withdrawal Successful ==========\n Amount withdrawn: ", amount, "\nCurrent available balance: ", current_balance) transaction_options(account) def make_transfer(account): print("\n====================== MAKE TRANSFER ===================\n") transfer_amount = int(input("Enter amount to be transfered: ")) beneficiary = str(input("Enter beneficiary's email: ")).lower() if transfer_amount > account_details[account]['balance']: print("You have *** insuffient *** funds to perform transaction! Kindly make deposit and try again\n") transaction_options(account) else: if verify_account(beneficiary): account_details[beneficiary]['balance'] = account_details[beneficiary]['balance'] + transfer_amount # User's current balance after making a transfer account_details[account]['balance'] = account_details[account]['balance'] - transfer_amount account_balance = account_details[account]['balance'] print("------- Transfer Successful -------\nAmount transfered: ", transfer_amount, "\nBeneficiary's email: ", beneficiary, "\nAccount Balance: ", account_balance) transaction_options(account) else: print("\n------- Invalid Beneficiary -----\n Kindly verify email address") transaction_options(account) def landing_page(): print("\n>>>>>>>>>>>>> HOME PAGE <<<<<<<<<<<<<<<<<") welcome_page = int(input("Hello,\n Press 1: create account\n Press 2: transaction\n Press 0: Quit program\n")) if welcome_page == 1: create_account() elif welcome_page == 2: authenticate_user() elif welcome_page == 0: quit() else: print("Enter a valid option") landing_page() landing_page()
Java
UTF-8
174
1.984375
2
[]
no_license
package com.javamaster.service; import com.javamaster.model.OrderRequest; public interface OrderCalculator { Integer calculateTotalOrderPrice(OrderRequest request); }
SQL
UTF-8
254
3.53125
4
[]
no_license
SELECT distinct movieId, title FROM movies M1 NATURAL JOIN playsin P1 NATURAL JOIN actors WHERE 60 + byear < any (SELECT distinct byear FROM movies M2 NATURAL JOIN playsin NATURAL JOIN actors WHERE M1.movieId = M2.movieId) ORDER BY movieId, title;
Markdown
UTF-8
1,222
2.765625
3
[]
no_license
--- cycle: 2022 layout: daily2022 title: "8/3 第31週 第3天 艾城之役" date: 2022-08-03 categories: daily permalink: /daily/2022/wk31-day3-daily.html weekNum: 31 dayNum: 3 --- ### 問題:神如何藉著約書亞的智慧幫助以色列奪取艾城? {%- include BibleLinks2022.html -%} ### 默想:神的故事 + 神幫助約書亞,通過一個機智的軍事戰略來擊敗和摧毀艾城。 + 對比耶利哥和艾城戰役,都是神的作為,一個是通過神跡,一個是藉著人的謀略成就。神在這兩場戰役中用的不同方法可以幫助我們理解神的作為。 ### 默想:我的故事 + 【價值定位】當亞干認罪之後,神不計前嫌,重新帶領以色列人爭戰得勝。在我們認罪悔改之後,神因著耶穌基督寶血的赦免帶給我們出人意外的平安。我還在為自己曾經的過犯而難以釋懷嗎?仰望耶穌救恩的十字架,把內疚化為對基督赦免之恩典的感激。 + 【服事忠誠】神使用約書亞的計謀幫助以色列人奪取了艾城。我是否願意把自己的一切恩賜、能力、資源、時間獻上,讓神使用來成就祂的使命? ### 禱告: ### 筆記與生活回應:
Markdown
UTF-8
8,804
2.84375
3
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
--- layout: post title: "我亲历的瓜菜代生活" date: 2002-07-15 author: 杨金声 from: http://www.yhcqw.com/ tags: [ 炎黄春秋 ] categories: [ 炎黄春秋 ] --- [ 2002年第7期 我亲历的瓜菜代生活 作者:杨金声 ] 三年困难时期,我在安徽省无为县当教师。那时粮食极其紧缺,比黄金还贵重,有钱能买到黄金,而无粮票或粮本,持钱去粮站根本买不到粮食。1958年大炼钢铁时,曾要我们“放开肚皮吃饭,鼓足干劲生产”,可是不到两个月,口粮月供应标准又恢复到28市斤。从1959年春季起,再降为24市斤(内含不能吃的杂糠,两个月后取消杂糠),继又降为22市斤,后来稳定在25市斤,还要节约一斤(由粮站代扣),实为24市斤。 在国家干部月口粮供应标准为22市斤时,县城和农村集镇上吃商品粮的居民,分别降为17市斤和16市斤。 当时市场上既买不到高蛋白、高脂肪鱼肉荤腥等食物,也买不到豆类和豆制品。国家粮站米价是一角三厘一市斤,黑市米和粮票4元一市斤,只听说有人偷卖米和粮票,但从未见人买过,因私自买卖粮食系破坏粮食政策,是违法犯罪行为,谁敢公开买卖?我当时月工资36元,不够买10市斤黑市米,全靠仅有的24市斤口粮和4市两(合十两制为2.5两)菜籽油活命。当时县邮电局营业间里供寄信人贴邮票用的糨糊,一放到柜台上就被人偷吃光,足见当时充饥度命的食物,紧张奇缺到何等程度! 那时我正年轻,食量大,消化力强,24市斤口粮只够吃二十三四天左右,每天吃饭不是斤斤计较,而是两两计算。我每周要上16节课,且大都排在上午,如某天上午授课量不重,只有一节或两节,学校食堂早餐稀饭即使很浓稠,也舍不得多吃一分稀饭(学校食堂一斤粮票购一角二分饭票,付一角二分钱);要是上午授课量重,有三节课,食堂早餐稀饭即使稀得“一口吹三条浪”,也得忍痛吃三分饭票的稀饭,否则是撑不住的,特别是上午第四节课,饿得肚皮紧贴脊梁骨,上气不接下气,靠在黑板上,硬撑着将课讲完,下课铃一响,就像战士冲锋一样冲进食堂,不管青菜萝卜,还是冬南二瓜(校内园地师生共同生产的),首先买一碗(限购一碗,不准多购,学生也一样),填进饿得发慌的空肚里,然后再买三分饭票的饭,绝不敢多吃一分饭。晚餐也是如此,先吃瓜菜,后吃两三分饭票的饭,因晚上办公要到深夜11点左右才敢下班,反“右派”后的“大跃进”,谁敢不积极?晚上9点多钟就下班,怕人说没干劲,思想落后,空熬着肚皮,也要撑到11点钟左右。 那时,若遗失10来斤粮票或饭票等于自绝生路,谁也救不了你。家庭因饭票短缺或遗失,而产生互相猜疑、指责、谩骂、造成夫妻反目、兄弟龃龆、母女不欢、姐妹失和的事时有所闻。有位中层干部,家里有四个子女,将从食堂打回的饭,按各人的供应标准数量,用秤分而食之(农村较普遍),谁也不能多吃、多沾谁一点。这种看似无情而实无奈的荒唐怪诞的生活方式,是享受着充裕物质生活的今天青年无法理解的,但它却在我们这辈人的生活旅程中,留下极其沉重的苦涩与酸楚。 在这种情况下,“低标准,瓜菜代”是当时整个社会求生存、想活命的人必然趋势。那时大小会议经常讲,连几岁的孩子都知道“低标准,瓜菜代”是什么含义,因为这关系到每个人的生命能否延续维持下去的极其严重问题,是头等大事。 秋冬季节,冬南二瓜吃尽了,青菜萝卜生长速度慢,赶不上吃的需求,上级号召我们大搞“小秋收”来充饥度命。所谓“小秋收”,顾名思义,是和大秋收相对而言,大秋收是指农田里生长的庄稼,农民种的粮食,而“小秋收”则是指野生植物,农产品的下脚料,如米糠、稗子、秕稻,以及极少的水面植物和水生螺丝肉、蚌肉等。 当时任县委副书记的谢永康同志,曾奉命代表县委在一次动员县直机关干部大搞“小秋收”的大会上说,现在证明,凡是猪能吃的一切东西,人都能吃!所以我们要大搞“小秋收”,以解决目前的困难(大意)。42年后的今天,我仍清楚地记得他说过的这句话。 谢永康同志是我省当时县委书记中极少数大学出身的知识分子,以他的文化知识水准和道德良心,无论如何,这句话他是说不出口的。解放这些年了,怎么能要老百姓吃猪食呢?但是,当时庐山会议精神已经传达,正在贯彻执行,全国正在抓“彭德怀分子”和“右倾机会主义分子”,我们县正在抓“张恺帆爪牙”和“小张恺帆分子”,他能说什么呢? 在粮食极端短缺的情况下,1960年10月26日的县常委会议上,议定可抵口粮的“小秋收”有下列各种名称(每种都有具体数字,共一亿斤,从略): 藕、荸荠、茨菇、菱角、芡实、高瓜(茭白)、玉米叶、玉米皮芯、高粱秆、黄豆秆子、芝麻秆子、花生藤、花生壳、橡子、毛栗、葛根、蕨根、野绿豆、野泥豆、山萝卜、野凉茶、大头薇、萎蒿、野红花草、马兰草、水草、鹅耳肠、野菜、荷叶秆子、芡实秆子、螺丝、蚌肉等,共32种。 上述“小秋收”中的玉米叶、玉米皮芯、、高粱秆、黄豆秆子、芝麻秆子、花生藤、花生壳、荷叶秆子、芡实秆子等,连猪都不吃,人怎能吃? 实际上,为了充饥度命,人们早就在寻找能吃的野生植物了。1959年冬天,在青菜萝卜供不应求时,我们学校曾派人去城外水塘里捞红浮萍,洗净磨碎,掺一点稗子粉,做成浮萍粑粑,供应师生,一分饭票买两个。我至今仍记得浮萍粑粑的味道,一股青气,粗糙微涩,难以下咽,但饥肠难熬,只得勉强吞咽下肚,胃是没有味觉的,只觉得不舒服,呼呼作响,且有隐疼感,远没有茭瓜青菜萝卜充饥好受。一位在农村工作过的同志告诉我,他在农村吃过苦涩难咽的山芋藤子、巴根草和双季稻根做的粑粑,他愤愤地说:“那是稻草!猪都不吃,人怎能吃?吃这种东西度命,怎能不死人?!” 国家干部、县城里和乡村集镇上吃商品粮的居民,不论月供应量是22市斤也好,还是18、16市斤也好,多少还有一点成品粮大米能熬粥度命,而最苦、最惨、最目不忍睹的是我们的衣食父母、生产粮食的农民,在“大跃进”刮起的“共产风”袭击下,他们的家禽家畜被这股妖风刮掉了;他们的自留地被刮掉了;他们烧饭的锅被刮掉了。 为了迎合好大喜功者的狂热虚荣心理,严重的浮夸风造成对农田里的庄稼高额估产,高额估产带来的高额征购,高额征购调走包括农民口粮、种子在内的大量粮食,仅剩下的一点不够农民糊口的粮食,又全集中在公共食堂里。而公共食堂的大权,完全被基层干部生产队长把持着,成了卡农民咽喉的“鬼门关”。当时的顺口溜有云:“一两二两,饿不死队长,一钱二钱,饿不死炊事员。” 据我县公安局统计:1959年,全县饿死82278人,1960年,饿死126524人。1957年年底统计,全县人口为982979人,1960年底为662557人,减少人口320422人。1961年饿死的人数还未统计在内。据此推算,“大跃进”的三年“共产风”时期,即使扣除正常死亡人数,全县饿死人应在30万人以上。 这种现象到底是如何造成的?前国家主席刘少奇同志,1962年元月27日在中共中央七千人大会上的报告中,说这是“三分天灾七分人祸”。原报告在传达时,曾有人说:“三分天灾讲多了,七分人祸还讲少了。”以我们安徽无为县来说,这句话完全正确。 从1958年到1961年这4年我县的气象资料看,无论是从月降水量、最长连续降水日数和最长连续无降水日数看,还是从暴雨日数和暴雨连续日数看,既不存在涝灾,也不存在旱灾,虽不像古书上说的5日一风、10日一雨,但气象资料表明,绝对构不成自然灾害,正如本地老农所说,那几年(1958年至1961年)基本风调雨顺,何来自然灾害?30余万人被饿死,完全是一场人祸。(责任编辑 吴思)
JavaScript
UTF-8
78
2.984375
3
[]
no_license
var output = ""; for(var i =0; i<10; i++){ console.log(output += "*"); }
C++
UTF-8
1,054
2.921875
3
[ "CC0-1.0" ]
permissive
/* Kahan - Kahan summation Written in 2015 by <Ahmet Inan> <xdsopl@googlemail.com> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ #ifndef KAHAN_HH #define KAHAN_HH template <typename T> class Kahan { T high, low; public: Kahan() : high(0), low(0) {} Kahan(T init) : high(init), low(0) {} #if __clang__ [[clang::optnone]] #elif __GNUC__ [[gnu::optimize("no-associative-math")]] #else #error unsupported compiler #endif T operator ()(T input) { T tmp = input - low; T sum = high + tmp; low = (sum - high) - tmp; return high = sum; } T operator ()() { return high; } }; template <class I, class T> T kahan_sum(I begin, I end, T init) { Kahan<T> kahan(init); while (begin != end) kahan(*begin++); return kahan(); } #endif
C++
UTF-8
404
3.046875
3
[]
no_license
#ifndef _BADSTRING_H_ #define _BADSTRING_H_ #include <iostream> #include <string> using namespace std; class BadString { private: string _reason; size_t _index; public: BadString(string reason = "", size_t index = 0) : _reason(reason), _index(index) {} ~BadString() {}; void show() const { cerr << _reason << " at index " << _index << endl; } }; #endif // _BADSTRING_H_
Java
UTF-8
1,595
2.890625
3
[]
no_license
package alerts; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.layout.GridPane; import javafx.scene.layout.StackPane; import javafx.stage.Modality; import javafx.stage.Stage; public class WarningAlert { public static void desplay(String title, String message) { Stage window = new Stage(); window.setResizable(false); window.initModality(Modality.APPLICATION_MODAL); //creating nodes Label messageLabel = new Label(message); Button okButton = new Button("\u062a\u0623\u0643\u064a\u062f"); okButton.setStyle("-fx-background-color: #2b4067; -fx-text-fill: white"); okButton.setPrefWidth(50); okButton.setPrefHeight(30); okButton.setCursor(Cursor.HAND); //handling action events okButton.setOnMouseClicked(e -> { window.close(); }); //Creating the root node GridPane layout = new GridPane(); layout.setAlignment(Pos.CENTER); layout.add(messageLabel, 0, 0); layout.add(okButton, 0, 1); layout.setVgap(20); GridPane.setHalignment(okButton, HPos.RIGHT); StackPane root = new StackPane(layout); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(40, 20, 40, 20)); root.setMinWidth(200); //creating scene Scene scene = new Scene(root); window.setScene(scene); window.setTitle(title); window.getIcons().add(new Image("/Image/Logo5.png")); window.show(); window.centerOnScreen(); } }
Java
UTF-8
1,434
2.859375
3
[]
no_license
import java.io.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; int testCases; int n, m; int k,l; //int table[][]; //int denominations[]; StringBuffer b = new StringBuffer(); if((line = br.readLine())!= null){ testCases = Integer.parseInt(line.trim()); //System.out.println(""); while(testCases-->0){ line = br.readLine().trim(); String strArr[] = line.split(" "); n = Integer.parseInt(strArr[0]); m = Integer.parseInt(strArr[1]); int table[][] = new int[m][n]; int denominations[] = new int[n]; for(int i = 0; i< n; i++){ denominations[i] = Integer.parseInt(br.readLine().trim()); } for(int i=0; i<n; i++){ if((k = denominations[i]) <= m) table[k-1][i] = 1; for(int j=0; j<m; j++){ // System.out.print("P "+table[j][i]+" "); // if(i > 0 && j != k-1) // table[j][i] = table[j][i-1]; if(i > 0){ l= table[j][i-1]; if( l == 1){ table[j][i] = table[j][i-1]; if( j + k < m){ table[j+k][i] = 1; } } } // System.out.print(table[j][i]+" "); } // System.out.println(""); } if(table[m-1][n-1] == 1) b.append("Yes").append('\n'); else b.append("No").append('\n'); } System.out.print(b); } } }
Java
UTF-8
308
1.820313
2
[ "Apache-2.0" ]
permissive
package io.github.rcarlosdasilva.weixin.core.exception; /** * 名字就是搞笑用的 * * @author Dean Zhao (rcarlosdasilva@qq.com) */ public class MaydayMaydaySaveMeBecauseAccessTokenSetMeFuckUpException extends RuntimeException { private static final long serialVersionUID = -8535962890149581715L; }
Java
UTF-8
2,298
3.078125
3
[]
no_license
package message; import price.Price; public class CancelMessage implements Comparable<CancelMessage> { private String user; private String product; private Price price; private int volume; private String details; private String side; public String id; public CancelMessage(String u, String prd, Price p, int v, String dt, String s, String i) throws InvalidDataOperation{ setUser(u); setProduct(prd); setPrice(p); setVolume(v); setDetails(dt); setSide(s); setId(i); } private void setUser(String userIn) throws InvalidDataOperation{ if(userIn == null || userIn.isEmpty()){ throw new InvalidDataOperation("Username is null or empty string"); } user = userIn; } private void setProduct(String productIn) throws InvalidDataOperation{ if(productIn == null || productIn.isEmpty()){ throw new InvalidDataOperation("Product name is null or empty string"); } product = productIn; } private void setPrice(Price priceIn) throws InvalidDataOperation { if(priceIn == null){ throw new InvalidDataOperation("Price is null"); } price = priceIn; } private void setVolume(int volumeIn) throws InvalidDataOperation { if(volumeIn < 1){ throw new InvalidDataOperation("Volume is less than 1"); } volume = volumeIn; } public void setDetails(String details) { this.details = details; } public void setSide(String side) { this.side = side; } public void setId(String id) throws InvalidDataOperation{ if(id == null){ throw new InvalidDataOperation("ID is null"); } this.id = id; } public String getUser() { return user; } public String getProduct() { return product; } public Price getPrice() { return price; } public int getVolume() { return volume; } public String getDetails() { return details; } public String getSide() { return side; } public String getId() { return id; } public int compareTo(CancelMessage cm) { return price.compareTo(cm.getPrice()); } public String toString() { return "User: " + user + " Product: " + product + " Price: " + price + " Volume: " + volume + " Details: " + details + " SIDE: " + side + " ID: " + id; } }
Python
UTF-8
2,185
2.734375
3
[]
no_license
import logging LOG = logging.getLogger(__name__) import requests import time import json import numpy as np def _test_adaptive_question_backend(): """ 测试出题接口 """ unit_list = ["5.1.02", "1.1.05", "5.2.01", "1.1.04", "4.2.01", "4.2.03"] url = f"http://127.0.0.1:{PORT}/api/realTimeCompute/createNextQuestion" for unit in unit_list: request_json_dict = { "parameters": { "student_id": "0101010011201001", "textbook_id": "A1", "unit_id": unit, "question_list": [ {"is_right": "", "question_id": ""} ] } } result_rate_len = 0 i = 0 while i < 15: LOG.info("request with json %s", json.dumps(request_json_dict)) beg_time = time.time() res = requests.post(url, json=json.dumps(request_json_dict)) LOG.info("[total] %s", time.time() - beg_time) # 请求正常返回 assert res.status_code == 200 # 接口运行正常 post_result = json.loads(res.content) LOG.info("receive %s", post_result) assert post_result["code"] == 10000 # 每次得到的掌握程度都比上一次要多(至少数量一样) result_rate = [ (item["point_id"], item["rate"]) for item in post_result["point_list"] ] assert len(result_rate) >= result_rate_len result_rate_len = len(result_rate) LOG.info("[mastery result] %s", result_rate) question_next = post_result["question_list"][0]["question_id"] if question_next == "": break request_json_dict["parameters"]["question_list"][0][ "question_id"] = question_next request_json_dict["parameters"]["question_list"][0][ "is_right"] = np.random.choice( ["true", "false"], p=[0.8, 0.2]) i += 1 # 结束出题时,做题数量小于等于12(终止条件是否有效) assert i <= 12
Python
UTF-8
6,036
2.671875
3
[]
no_license
''' n_estimators = 100 learning_rate = 0.5 max_depth = 5 : log loss = 0.687561242769 n_estimators = 100 learning_rate = 0.48 max_depth = 1 log loss = 0.651815005376 n_estimators = 100 learning_rate = 0.45 max_depth = 3: log loss = 0.623512266363 n_estimators = 100 learning_rate = 0.5 max_depth = 2 : log loss = 0.614801832018 n_estimators = 100 learning_rate = 0.48 max_depth = 3 log loss = 0.600838380242 n_estimators = 100 learning_rate = 0.49 max_depth = 2 log loss = 0.600396528478 n_estimators = 100 learning_rate = 0.495 max_depth = 3 log loss = 0.596102075079 n_estimators = 100 learning_rate = 0.475 max_depth = 3 log loss = 0.591128964187 n_estimators = 100 learning_rate = 0.475 max_depth = 2 log loss = 0.583600418683 n_estimators = 100 learning_rate = 0.48 max_depth = 2 log loss = 0.581117435124 n_estimators = 100 learning_rate = 0.5 max_depth = 3 : log loss = 0.574187134015 with bagging: n_estimators = 100 learning_rate = 0.5 max_depth = 3 log loss = 0.534818037693 n_estimators = 100 learning_rate = 0.4 max_depth = 3 log loss = 0.530011997962 ''' #import xgboost import pandas as pd import numpy as np import sklearn import time import csv from math import log import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import GradientBoostingClassifier, BaggingClassifier from sklearn.metrics import log_loss def write_pred_prob(probs): id_f = open('../test_set.csv', 'rb') id_r = csv.reader(id_f) ids = [row[0] for row in id_r] ids = ids[1:] id_f.close() f = open('prob.csv', 'wb') writer = csv.writer(f) labels = ['id'] for i in range(9): labels.append('Class_'+str(i+1)) writer.writerow(labels) data = [] for l in range(len(probs)): new = [ids[l]] new += probs[l] data.append(new) writer.writerows(data) f.close() print 'finish writting <prob.csv>' def log_loss_implement(actual, predicted, eps = 1e-15): predicted = np.minimum(np.maximum(predicted,eps),1-eps) sum1 = 0 N = len(actual) M = num_labels(actual) result_list = [] for j in range(M): sum2 = 0 count = 0 for i in range(N): y = 1 if j==actual[i] else 0 if j==actual[i]: y = 1 count += 1 else: y = 0 p = predicted[i][j] temp = y*log(p) sum2 += temp cla_logloss = (-1)*sum2/float(count) print 'Class', j, 'log loss =', cla_logloss result_list.append([j, cla_logloss]) sum1 += sum2 logloss = (-1)*sum1/float(N) return logloss, result_list def num_labels(actual): labels = {} size = 0 for l in actual: if l not in labels: size += 1 labels[l] = 0 return size def write_pred_logloss(logloss_list): f = open('logloss.csv', 'wb') writer = csv.writer(f) labels = ['class', 'log loss'] writer.writerow(labels) data = [] for l in logloss_list: data.append(l) writer.writerows(data) f.close() print 'finish writting <logloss.csv>' # read file, get training data X = pd.read_csv('../train_set.csv') # remove id X = X.drop('id', axis=1) # get target and encode y = X.target.values y = LabelEncoder().fit_transform(y) # remove target X = X.drop('target', axis=1) # split data # Reference: http://stackoverflow.com/questions/29438265/stratified-train-test-split-in-scikit-learn #Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.20, random_state=36) Xtrain = X ytrain = y Xt = pd.read_csv('../test_set.csv') # remove id Xt = Xt.drop('id', axis=1) # get target and encode yt = Xt.target.values yt = LabelEncoder().fit_transform(yt) # remove target Xt = Xt.drop('target', axis=1) Xtest = Xt ytest = yt lr = 0.4#learning_rate_list[0] md = 3 #max_depth_list[0] ne = 100#n_estimators_list[i] gbm = GradientBoostingClassifier(learning_rate=lr, max_depth=md, n_estimators=ne) gbm = BaggingClassifier(gbm, n_estimators=5) model = gbm.fit(Xtrain, ytrain) pred_prob = model.predict_proba(Xtest) pred_clas = model.predict(Xtest) logloss = log_loss(ytest, pred_prob) logloss2, class_logloss = log_loss_implement(ytest, pred_prob) write_pred_prob(pred_prob) write_pred_logloss(class_logloss) print 'n_estimators =', ne, 'learning_rate =', lr, 'max_depth =', md, 'log loss =', logloss print 'logloss implement =', logloss2 ''' learning_rate_list = [0.01, 0.05, 0.1, 0.2, 0.3, 0.5] max_depth_list = [3,5,10] n_estimators_list = [10, 20, 50, 100, 200] for i in range(len(n_estimators_list)): lr = learning_rate_list[0] md = max_depth_list[0] ne = n_estimators_list[i] gbm = GradientBoostingClassifier(learning_rate=lr, max_depth=md, n_estimators=ne) model = gbm.fit(Xtrain, ytrain) pred_prob = model.predict_proba(Xtest) pred_clas = model.predict(Xtest) logloss = log_loss(ytest, pred_prob) print 'n_estimators =', ne, 'learning_rate =', lr, 'max_depth =', md, 'log loss =', logloss for i in range(len(learning_rate_list)): lr = learning_rate_list[i] md = max_depth_list[0] ne = n_estimators_list[0] gbm = GradientBoostingClassifier(learning_rate=lr, max_depth=md, n_estimators=ne) model = gbm.fit(Xtrain, ytrain) pred_prob = model.predict_proba(Xtest) pred_clas = model.predict(Xtest) logloss = log_loss(ytest, pred_prob) print 'n_estimators =', ne, 'learning_rate =', lr, 'max_depth =', md, 'log loss =', logloss for i in range(len(max_depth_list)): lr = learning_rate_list[0] md = max_depth_list[i] ne = n_estimators_list[0] gbm = GradientBoostingClassifier(learning_rate=lr, max_depth=md, n_estimators=ne) model = gbm.fit(Xtrain, ytrain) pred_prob = model.predict_proba(Xtest) pred_clas = model.predict(Xtest) logloss = log_loss(ytest, pred_prob) print 'n_estimators =', ne, 'learning_rate =', lr, 'max_depth =', md, 'log loss =', logloss '''
Java
UTF-8
233
1.953125
2
[]
no_license
package com.meishe.yangquan.inter; public interface OnResponseListener { void onSuccess(Object object); void onSuccess(int type,Object object); void onError(Object obj); void onError(int type,Object obj); }
Java
UTF-8
252
2.09375
2
[]
no_license
/* * Created on 10/10/2006 */ package japa.parser.ast.expr; import japa.parser.ast.Node; /** * @author Julio Vilmar Gesser */ public abstract class Expression extends Node { public Expression(int line, int column) { super(line, column); } }
Java
UTF-8
920
3.125
3
[]
no_license
package aoop.asteroids.database; import java.awt.Color; import java.awt.Graphics2D; public class DBState { /** The x and y coordinate of the drawing to the screen */ private int X = 350, Y; protected Database dbManager; public void render(Graphics2D g) { g.setColor(Color.WHITE); g.drawString("NAME SCORE", X, 30); dbManager = new Database(); if (dbManager != null) { Y = 45; for (String s : dbManager.getNames()) { g.drawString(s, X, Y); Y += 20; } Y = 45; for (Integer i : dbManager.getScores()) { g.drawString(" "+i, X + 30, Y); Y += 20; } } g.drawString("* PRESS ESC TO GO BACK", 340, 790); } /** Set the manager to null */ public void destroy() { dbManager = null; } }
Java
UTF-8
5,739
1.703125
2
[]
no_license
package irvine.oeis.a106; import junit.framework.Test; import junit.framework.TestSuite; /** * Test class for all tests in this directory. * * @author Sean A. Irvine */ public class AllTests extends TestSuite { public static Test suite() { final TestSuite suite = new TestSuite(); suite.addTestSuite(A106006Test.class); suite.addTestSuite(A106035Test.class); suite.addTestSuite(A106036Test.class); suite.addTestSuite(A106037Test.class); suite.addTestSuite(A106055Test.class); suite.addTestSuite(A106056Test.class); suite.addTestSuite(A106133Test.class); suite.addTestSuite(A106157Test.class); suite.addTestSuite(A106173Test.class); suite.addTestSuite(A106175Test.class); suite.addTestSuite(A106176Test.class); suite.addTestSuite(A106197Test.class); suite.addTestSuite(A106201Test.class); suite.addTestSuite(A106202Test.class); suite.addTestSuite(A106231Test.class); suite.addTestSuite(A106232Test.class); suite.addTestSuite(A106233Test.class); suite.addTestSuite(A106247Test.class); suite.addTestSuite(A106248Test.class); suite.addTestSuite(A106249Test.class); suite.addTestSuite(A106250Test.class); suite.addTestSuite(A106251Test.class); suite.addTestSuite(A106252Test.class); suite.addTestSuite(A106253Test.class); suite.addTestSuite(A106256Test.class); suite.addTestSuite(A106257Test.class); suite.addTestSuite(A106273Test.class); suite.addTestSuite(A106274Test.class); suite.addTestSuite(A106275Test.class); suite.addTestSuite(A106318Test.class); suite.addTestSuite(A106328Test.class); suite.addTestSuite(A106329Test.class); suite.addTestSuite(A106330Test.class); suite.addTestSuite(A106331Test.class); suite.addTestSuite(A106352Test.class); suite.addTestSuite(A106353Test.class); suite.addTestSuite(A106354Test.class); suite.addTestSuite(A106355Test.class); suite.addTestSuite(A106373Test.class); suite.addTestSuite(A106374Test.class); suite.addTestSuite(A106387Test.class); suite.addTestSuite(A106388Test.class); suite.addTestSuite(A106389Test.class); suite.addTestSuite(A106390Test.class); suite.addTestSuite(A106392Test.class); suite.addTestSuite(A106393Test.class); suite.addTestSuite(A106400Test.class); suite.addTestSuite(A106403Test.class); suite.addTestSuite(A106434Test.class); suite.addTestSuite(A106435Test.class); suite.addTestSuite(A106438Test.class); suite.addTestSuite(A106450Test.class); suite.addTestSuite(A106466Test.class); suite.addTestSuite(A106469Test.class); suite.addTestSuite(A106472Test.class); suite.addTestSuite(A106498Test.class); suite.addTestSuite(A106511Test.class); suite.addTestSuite(A106514Test.class); suite.addTestSuite(A106515Test.class); suite.addTestSuite(A106517Test.class); suite.addTestSuite(A106521Test.class); suite.addTestSuite(A106523Test.class); suite.addTestSuite(A106525Test.class); suite.addTestSuite(A106526Test.class); suite.addTestSuite(A106533Test.class); suite.addTestSuite(A106541Test.class); suite.addTestSuite(A106565Test.class); suite.addTestSuite(A106567Test.class); suite.addTestSuite(A106568Test.class); suite.addTestSuite(A106570Test.class); suite.addTestSuite(A106586Test.class); suite.addTestSuite(A106603Test.class); suite.addTestSuite(A106607Test.class); suite.addTestSuite(A106608Test.class); suite.addTestSuite(A106609Test.class); suite.addTestSuite(A106612Test.class); suite.addTestSuite(A106614Test.class); suite.addTestSuite(A106624Test.class); suite.addTestSuite(A106627Test.class); suite.addTestSuite(A106632Test.class); suite.addTestSuite(A106648Test.class); suite.addTestSuite(A106664Test.class); suite.addTestSuite(A106666Test.class); suite.addTestSuite(A106668Test.class); suite.addTestSuite(A106669Test.class); suite.addTestSuite(A106670Test.class); suite.addTestSuite(A106672Test.class); suite.addTestSuite(A106673Test.class); suite.addTestSuite(A106674Test.class); suite.addTestSuite(A106675Test.class); suite.addTestSuite(A106676Test.class); suite.addTestSuite(A106677Test.class); suite.addTestSuite(A106678Test.class); suite.addTestSuite(A106679Test.class); suite.addTestSuite(A106680Test.class); suite.addTestSuite(A106681Test.class); suite.addTestSuite(A106682Test.class); suite.addTestSuite(A106684Test.class); suite.addTestSuite(A106685Test.class); suite.addTestSuite(A106691Test.class); suite.addTestSuite(A106706Test.class); suite.addTestSuite(A106707Test.class); suite.addTestSuite(A106710Test.class); suite.addTestSuite(A106729Test.class); suite.addTestSuite(A106731Test.class); suite.addTestSuite(A106791Test.class); suite.addTestSuite(A106802Test.class); suite.addTestSuite(A106803Test.class); suite.addTestSuite(A106804Test.class); suite.addTestSuite(A106805Test.class); suite.addTestSuite(A106824Test.class); suite.addTestSuite(A106825Test.class); suite.addTestSuite(A106826Test.class); suite.addTestSuite(A106832Test.class); suite.addTestSuite(A106833Test.class); suite.addTestSuite(A106835Test.class); suite.addTestSuite(A106839Test.class); suite.addTestSuite(A106845Test.class); suite.addTestSuite(A106850Test.class); suite.addTestSuite(A106851Test.class); suite.addTestSuite(A106852Test.class); suite.addTestSuite(A106853Test.class); suite.addTestSuite(A106854Test.class); suite.addTestSuite(A106855Test.class); return suite; } public static void main(final String[] args) { junit.textui.TestRunner.run(suite()); } }
Java
UTF-8
7,290
2.40625
2
[]
no_license
package ch.epfl.scrumtool.gui.utils.test; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import ch.epfl.scrumtool.entity.Issue; import ch.epfl.scrumtool.entity.MainTask; import ch.epfl.scrumtool.entity.Player; import ch.epfl.scrumtool.entity.Priority; import ch.epfl.scrumtool.entity.Project; import ch.epfl.scrumtool.entity.Role; import ch.epfl.scrumtool.entity.Sprint; import ch.epfl.scrumtool.entity.Status; import ch.epfl.scrumtool.entity.User; import ch.epfl.scrumtool.entity.User.Gender; /** * * @author * */ public class MockData { public static final long CURRENT_TIME = Calendar.getInstance().getTimeInMillis(); public static final String TEST_TEXT = "test text"; public static final String ERROR_MESSAGE = "error"; public static final String VERY_LONG_TEXT = "blablablablablablablablablablablablablablabla" + "blablablablabla"; public static final Float NO_ESTIMATION = 0f; public static final Float ESTIMATION = 2f; public static final Float LARGE_ESTIMATION = 125f; public static final long THREADSLEEPTIME = 100; // Users public static final User USER1 = buildUser("some@example.com", "Some", "One", CURRENT_TIME, "Polytech", Gender.FEMALE, "Proffessor"); public static final User USER2 = buildUser("other@example.com", "Other", "Example", CURRENT_TIME, "University", Gender.MALE, "Student"); // Players public static final Player USER1_ADMIN = buildPlayer("player1", true, false, Role.PRODUCT_OWNER, USER1); public static final Player USER2_DEV = buildPlayer("player2", false, true, Role.DEVELOPER, USER2); // Projects public static final Project PROJECT = buildProject("project1", "Murcs", "murcs description"); // Sprints public static final Sprint SPRINT1 = buildSprint("sprint1", "week 1", CURRENT_TIME); public static final Sprint SPRINT2 = buildSprint("sprint2", "week 2", CURRENT_TIME); // Maintasks public static final MainTask TASK1 = buildMaintask("task1", "write tests", "description", Priority.HIGH, Status.IN_SPRINT, 1000, 200, 5, 2); // Issues public static final Issue ISSUE1 = buildIssue("Issue1", "tests for server", "desc", 20, Priority.URGENT, Status.FINISHED, USER1_ADMIN, SPRINT1); public static final Issue ISSUE2 = buildIssue("Issue2", "test", "test desc", 5, Priority.NORMAL, Status.IN_SPRINT, USER2_DEV, SPRINT1); public static final Issue ISSUE3 = buildIssue("Issue3", "test new issue", "test for status", 0, Priority.NORMAL, Status.READY_FOR_ESTIMATION, USER2_DEV, null); public static final Issue ISSUE4 = buildIssue("Issue4", "test unsprinted issue", "test unsprinted issue", 3, Priority.NORMAL, Status.READY_FOR_SPRINT, USER1_ADMIN, null); public static final List<User> USERLIST = generateUserLists(); public static final List<Player> PLAYERLIST = generatePlayerLists(); public static final List<Project> PROJECTLIST = generateProjectLists(); public static final List<MainTask> MAINTTASKLIST = generateMainTaskLists(); public static final List<Issue> ISSUELIST = generateIssueLists(); public static final List<Sprint> SPRINTLIST = generateSprintLists(); public static final List<Issue> UNSPRINTEDISSUELIST = generateUnsprintedIssueLists(); public static List<User> generateUserLists() { List<User> list = new ArrayList<User>(); list.add(USER1); list.add(USER2); return list; } public static List<Player> generatePlayerLists() { List<Player> list = new ArrayList<Player>(); list.add(USER1_ADMIN); list.add(USER2_DEV); return list; } public static List<Project> generateProjectLists() { List<Project> list = new ArrayList<Project>(); list.add(PROJECT); return list; } public static List<MainTask> generateMainTaskLists() { List<MainTask> list = new ArrayList<MainTask>(); list.add(TASK1); return list; } public static List<Issue> generateIssueLists() { List<Issue> list = new ArrayList<Issue>(); list.add(ISSUE1); list.add(ISSUE2); return list; } public static List<Sprint> generateSprintLists() { List<Sprint> list = new ArrayList<Sprint>(); list.add(SPRINT1); list.add(SPRINT2); return list; } public static List<Issue> generateUnsprintedIssueLists() { List<Issue> list = new ArrayList<Issue>(); list.add(ISSUE3); list.add(ISSUE4); return list; } private static Sprint buildSprint(String key, String title, long deadline) { Sprint.Builder sprint = new Sprint.Builder(); sprint.setKey(key) .setTitle(title) .setDeadline(deadline); return sprint.build(); } private static MainTask buildMaintask(String key, String name, String description, Priority priority, Status status, float totalTime, float finishedTime, int totalIssues, int finishedIssues) { MainTask.Builder maintask = new MainTask.Builder(); maintask.setKey(key) .setName(name) .setDescription(description) .setTotalIssueTime(totalTime) .setFinishedIssueTime(finishedTime) .setTotalIssues(totalIssues) .setTotalIssues(totalIssues) .setFinishedIssues(finishedIssues); return maintask.build(); } private static Issue buildIssue(String key, String name, String description, float time, Priority priority, Status status, Player player, Sprint sprint) { Issue.Builder issue = new Issue.Builder(); issue.setKey(key) .setName(name) .setDescription(description) .setEstimatedTime(time) .setPriority(priority) .setStatus(status) .setPlayer(player) .setSprint(sprint); return issue.build(); } private static Project buildProject(String key, String name, String description) { Project.Builder project = new Project.Builder(); project.setKey(key) .setName(name) .setDescription(description); return project.build(); } private static User buildUser(String email, String name, String lastName, long birth, String company, Gender sex, String proffession) { User.Builder user = new User.Builder(); user.setEmail(email) .setName(name) .setLastName(lastName) .setDateOfBirth(birth) .setCompanyName(company) .setGender(sex) .setJobTitle(proffession); return user.build(); } private static Player buildPlayer(String key, boolean admin, boolean invited, Role role, User user) { Player.Builder player = new Player.Builder(); player.setKey(key) .setIsAdmin(admin) .setIsInvited(invited) .setRole(role) .setUser(user) .setProject(PROJECT); return player.build(); } }
C#
UTF-8
734
2.875
3
[]
no_license
using Entities.Post; using System.Collections.Generic; using System.Linq; namespace Services.Recommend { public class PostRatingPrediction { public float Label; public float Score; } public static class Posts { public static List<Post> All = new List<Post>(); /// <summary> /// Get a single post. /// </summary> /// <param name="id">The identifier of the post to get.</param> /// <returns>The post instance corresponding to the specified identifier.</returns> public static Post Get(int id) { return All.Single(m => m.Id == id); } // ... I removed all private members for brevity ... } }
Java
UTF-8
2,176
2.421875
2
[]
no_license
package services; /** * Created by Admin on 3/9/2017. */ public class ClassRoomQueries { public static String INSERT = "INSERT INTO `classroom`" + "(`id`,\n" + "`subject_id`,\n" + "`professor_id`,\n" + "`assistant`,\n" + "`roomNumber`)\n" + "VALUES\n" + "(?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?)\n" + ";"; public static String UPDATE = "UPDATE `classroom`" + "SET\n" + "`subject_id` = ?,\n" + "`professor_id` = ?,\n" + "`assistant` = ?,\n" + "`roomNumber` = ?\n" + "WHERE `id` = ?;"; public static String DELETE = "DELETE FROM `classroom`\n" + "WHERE id = ?;"; public static String GET_ALL = "SELECT *\n" + "FROM `classroom`;"; public static String GET_BY_ID = "SELECT *\n" + "FROM `classroom`\n" + "WHERE id = ?;"; public static String GET_ALL_WITH_STUDENTS = "select cr.*, p.*, a.*, pu.*, au.*, s.*\n" + "from class_room cr \n" + "inner join proffesore p on cr.proffesore_id = p.id\n" + "inner join users pu on pu.id = p.user_id\n" + "inner join proffesore a on cr.assistent_id = a.id\n" + "inner join users au on au.id = a.user_id\n" + "inner join class_room_student crt on crt.class_room_id = cr.id\n" + "inner join users s on s.id = crt.student_id\n" + "order by cr.id;"; public static String GET_ALL_WITH_STUDENTS_BY_ID = "select cr.*, p.*, a.*, pu.*, au.*, s.*\n" + "from class_room cr \n" + "inner join proffesore p on cr.proffesore_id = p.id\n" + "inner join users pu on pu.id = p.user_id\n" + "inner join proffesore a on cr.assistent_id = a.id\n" + "inner join users au on au.id = a.user_id\n" + "inner join class_room_student crt on crt.class_room_id = cr.id\n" + "inner join users s on s.id = crt.student_id\n" + "where cr.id = ?\n" + "order by cr.id;"; }
Java
UTF-8
505
1.742188
2
[]
no_license
package com.example.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //import org.springframework.beans.factory.annotation.Value; @RestController public class HelloWorldController { //@Value("${app.smtp.name}") //private String smtpName; @RequestMapping("/hello") public String hello() { return "HELLO"; } @RequestMapping("/method") public String method() { return "METHOD"; } }
Markdown
UTF-8
11,441
3.84375
4
[ "MIT" ]
permissive
--- title: Web Frontend Development (10) - JavaScript 06 key: C20190910 tags: JavaScript; String; String方法; 正则表达式 layout: article --- # Week Ten: Web Frontend Development(10)---JavaScript 06 <!--more--> # 10.1 字符串方法(String) - ## 包装类 - 在JS中提供了3个包装类。通过3个包装类可以将基本数据类型的数据转换为对象。 - `String()`可以将基本数据类型**字符串**转换为String对象。 - `Number()`可以将基本数据类型的**数字**转换为Number对象。 - `Boolean()`可以将基本数据类型的**布尔值**转换为Boolean对象。 - **注意**:实际开发中不会使用基本数据类型的对象。 - 如果使用基本类型对象,比较可能出错。 - 当我们对一些基本数据类型的值去调用属性和方法时,浏览器会临时使用包装类将其转换为对象,然后再调用对象的属性和方法,调用完后再转换为基本数据类型。 ```javascript num = new Number (3) Number {3} num Number {3} num.hello = "abcdfe" "abcdfe" num Number {3, hello: "abcdfe"} str = new String('Hello') String {"Hello"} str.sayname = "name" "name" str String {"Hello", sayname: "name"} str.length 5 num2 = new Number(3) Number {3} num == num2 false /*转换基本数据类型*/ num2.toString() "3" num2 Number {3} ``` - ## `String`方法 - `str.length`获取字符串长度(空格也算1个) - `str.charAt(num)`返回指定位置的字符。 - `str.charCodeAt(num)`返回指定位置字符的Unicode编码。 - `String.fromCharCode(num)`根据字符编码获取字符。 - `str.concat()`连接两个或多个字符串。 - 作用和`+`一样 - `str.indexof('str',fromIndex)`检索一个字符串是否含有指定内容。 - 如果字符串中含有该内容,则会返回其第一次出现的索引。 - 如果没有找到指定内容,则返回-1 - 可以指定查找开始位置`fromIndex`。 - `str.lastIndexOf('str',num)`和`indexOf()`功能一样。 - **只是从后往前检索** - `str.slice(startNumOfIndex,endNumOfIndex)`截取指定索引位置[)内容。 - `str.substring(startNumOfIndex,endNumOfIndex)`和`str.slice()`功能一样。 - **不同点**: - 如果传递一个负值,则默认使用0 - 如果第二个参数小于第一个参数,则会自动调换位置。 - `str.substr(startNumOfIndex,length)`和`str.slice()`功能一样。 - **不同点**: - 后一个参数为截取长度。 - `str.split('str')`可以将字符串拆分成一个数组。 - 参数:拆分的字符串 - 如果用**空串**,则会将每个字符都拆分为数组中的一个元素。 - `str.toLowerCase()`&`str.toUpperCase()`转换大小写 ```javascript str = 'aabbccddeeaa' "aabbccddeeaa" str.charAt(3) "b" str.charCodeAt(3) 98 String.fromCharCode(98) "b" str.concat('bb') "aabbccddeeaabb" str.indexOf('b') 2 str.indexOf('b',1) 2 str.indexOf('a',4) 10 str.lastIndexOf('a',4) 1 str.slice(1,10) "abbccddee" str.substring(10,1) "abbccddee" str.substr(1,5) "abbcc" str.split('a') (5) ["", "", "bbccddee", "", ""] str.split('') (12) ["a", "a", "b", "b", "c", "c", "d", "d", "e", "e", "a", "a"] str.toLocaleUpperCase() "AABBCCDDEEAA" ``` - ## 正则表达式 (Regular Expression) - 用于定义字符串规则,计算机可以根据正则表达式来检查一个字符串是否符合规则,或获取字符串中符合规则的内容提取出来。 - 语法 ```javascript /*创建方式1--构造函数*/ var 变量 = new RegExp('正则表达式','匹配模式') /*创建方式2--字面量*/ var 变量 = /正则表达式/匹配模式 ``` - 在构造函数中可以传递一个匹配模式作为第二个参数: - `i` 忽略大小写 - `g` 全局匹配模式 - `test()`方法检查正则表达式 ```javascript /*创建方式1*/ var reg = new RegExp('a') undefined reg /a/ reg.test('abc') true reg.test('ABC') false /*创建方式2*/ reg2 /ab/i reg2.test('abcd') true reg2.test('ACD') false ``` - ## [正则表达式语法](https://www.w3school.com.cn/jsref/jsref_obj_regexp.asp) - `|``[]`或关系 - `[ab] == a|b` - `[a-z]`任意小写字母 - `[A-Z]`任意大写字母 - `[A-z]`任意字母 - `[0-9]`任意数字 ```javascript /*检查一个字符串中是否含有abc或adc或aec*/ reg = /a[bde]c/ ``` - `^`非 ```javascript /*检查除了[ab] 之外还有其他元素*/ reg = /[^ab]/ /[^ab]/ reg.test('abc') true reg.test('a') false reg.test('AB') true ``` - ## 正则式方法 - `split()` - 可以将一个字符串拆分成一个数组。 - 方法中可以传递一个正则表达式作为参数拆分字符串。 - **即使不设置为全局匹配模式`g`,也可拆分所有内容。** - `search()` - 可以搜索字符串中是否含有指定内容。 - **如果搜索到指定内容,则会返回第一次出现的索引。如果没有搜索到,则返回-1。同str.indexof()方法。** - 它可以接受一个正则表达式作为参数,然后根据正则表达式去检索字符串。 - **即使设置全局匹配模式`g`,也只查找第一个匹配索引。** - `match()` - 可以根据正则表达式,从一个字符串中将符合条件的内容提取出来。 - 默认情况下,`match`只会找到第一个符合要求的内容,找到后就停止检索。 - **可以设置正则表达式为全局匹配模式`g`,这样可以匹配到所有内容。** - `match()`返回一个数组。 - `replace(“原内容”,“新内容”)` - 可以将字符串中指定内容替换为新的内容。 - 默认情况下,只替换第一个匹配内容。 - **可以设置正则表达式为全局匹配模式`g`,这样可以匹配到所有内容。** ```javascript /*str.split()*/ str = "abc 123 aec 456 adc 789 aaa 000" "abc 123 aec 456 adc 789 aaa 000" str.split('a') (7) ["", "bc 123 ", "ec 456 ", "dc 789 ", "", "", " 000"]0: ""1: "bc 123 "2: "ec 456 "3: "dc 789 "4: ""5: ""6: " 000"length: 7__proto__: Array(0) str.split(/[a-z]/) (13) ["", "", "", " 123 ", "", "", " 456 ", "", "", " 789 ", "", "", " 000"] result = str.split(/[ab]/) (8) ["", "", "c 123 ", "ec 456 ", "dc 789 ", "", "", " 000"] result[7] " 000" /*str.search()*/ str.search(/[0-9]/) 4 str.search(/[0-9]/ig) 4 /*str.match()*/ str.match(/a[A-z]b/) null str.match(/a[A-z]c/) ["abc", index: 0, input: "abc 123 aec 456 adc 789 aaa 000", groups: undefined] str.match(/a[A-z]c/ig) (3) ["abc", "aec", "adc"] /*str.replace()*/ str.replace(/[A-z]/, "@") "@bc 123 aec 456 adc 789 aaa 000" str.replace(/[A-z]/g, "@") "@@@ 123 @@@ 456 @@@ 789 @@@ 000" ``` - ### 量词 - 设置一个内容出现的次数 - `(ab){n}`ab出现n次 - `(ab){n,m}`ab出现n-m次 - `(ab){n,}`ab出现n次以上 - `ab+c`表示b出现至少1次,相当于`{1,}` - `ab*c`表示0个或多个,相当于`{0,}` - `ab?c`表示0个或1个,相当于`{0,1}` ```javascript reg = /(ab){3}/ /(ab){3}/ reg.test('abab') false reg.test('abaaabddabcc') false reg.test('abababaabbcc') true reg2 = /(ab){1,3}/ /(ab){1,3}/ reg2.test('abaaabddab') true reg2.test('ababababaa') true /*只要连续出现即可*/ reg3 = /(ab){3}/ /(ab){3}/ reg3.test('abab') false reg3.test('abababcc') true reg4 = /ab+c/ /ab+c/ reg4.test('abbbc') true reg4.test('ac') false reg5 = /ab*c/ /ab*c/ reg5.test('ac') true reg5.test('abc') true reg5.test('abbc') true reg6 = /ab?c/ /ab?c/ reg6.test('ac') true reg6.test('abc') true reg6.test('abbc') false /*?和*区别之处*/ ``` - 开头结尾 - 检查一个字符串是否以某个字符开头或结尾。 - `^`表示开头 - `$`表示结尾 ```javascript reg = /^a/ /^a/ reg.test('abcd') true reg.test('bcde') false reg1 = /a$/ /a$/ reg1.test('abcd') false reg1.test('cdea') true /*注意开头和结尾符号同时使用情况!*/ /^a$/ reg2.test('aba') false reg2.test('a') true ``` - 如果正则表达式中同时使用`^`和`$`,则要求字符串完全符合正则表达式。 - 练习 - 创建一个手机号码检查正则表达式: - 规则: - 以1开头 - 第二位3-9 - 三位以后任意数字9个 ```javascript phone = /^1[3-9][0-9]{9}$/ /^1[3-9][0-9]{9}$/ phone.test('13344567890') true phone.test('110123456789') false ``` - `.` - 表示任意字符 - 使用`\.`转义字符强制转义 - `\\`表示`\` - **使用构造函数时,由于它的参数是一个字符串,而`\`是字符串中的转义字符,如果要使用字符串`\`则需要打两个`\\`。** ```javascript eg = new RegExp('\\.') /\./ reg1 = /\./ /\./ \*注意构造函数和字面量之间\的区别*\ reg1.test('\.') true reg1.test('\\') false ``` - ### 字母 - `\w`表示任意字母或数字或`_` = `[A-z0-9_]` - `\W`表示除了任意字母或数字或`_` = `[^A-z0-9_]` - `\d`表示任意数字`[0-9]` - `\D`表示除了数字`[^0-9]` - `\s`表示空格 - `\S`表示除了空格 - `\b`单词边界 - **单词边界标示独立单词** - `\B`除了单词边界 - 检查词中词根 - 练习1:去除字符串开头结尾空格 ```javascript str = prompt('输入用户名: leo ') str = str.replace(/^\s*|\s*$/g, '') "leo" ``` - 练习2:邮件正则规则 - 规则(如:hello.nihao@abc.com.cn): - 任意字母数字下划线 .任意字母数字下划线@任意字母数字.任意字母(2-5).任意字母(2-5) ```javascript email = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/ /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/ email.test('hello.nihao@abc.com.cn') true /*注意*+对于多位字母数字必不可少 注意区分【】(){}的含义*/ ``` - ### [正则表达式大全](https://www.jianshu.com/p/a2164e370e29) - [常用正则表达式生成器](sojson.com/regex/generate)
Java
UTF-8
882
3.546875
4
[]
no_license
package array_assignment; import java.util.Scanner; public class Ex2 { public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); int[] a = new int [n]; inputArray(a,n); sortArrayA(a,n); } private static void inputArray(int[] a, int n) { for (int i=0; i<n; i++){ System.out.println("Nhập số thứ "+i+" : "); a[i] = new Scanner(System.in).nextInt(); } } private static void sortArrayA(int[] a, int n) { int temp=0; for (int i=0; i<n; i++){ for (int j= i+1; j<n; j++){ if (a[i]>a[j]){ temp = a[j]; a[j] = a[i]; a[i] = temp; } } } for (int i=0; i<n; i++){ System.out.println(a[i]); } } }
Markdown
UTF-8
1,647
2.65625
3
[ "MIT" ]
permissive
Managing Attachments --- When you login and edit a page, you'll find the "Attachments" interface below the text editing area. To add a new attachment to the page click the **+** icon. If you need to you can upload multiple attachments at once by clicking the **+** icon once for each attachment you'll be adding. Attachments are **not** added or deleted until the page is saved. Therefore, if you accidentally deleted something you meant to keep, simply cancel the page edit. You'll also find a list of all page attachments under the [Attachments](/admin/page_attachments) tab. There you'll be able to find a link to each attachment, a link to it's associated page, and some sample code for displaying the attachment. Usage --- * See the "available tags" documentation built into the Radiant page admin for more details. * Reference an attachment by name `<r:attachment name="file.txt">...</r:attachment>` * Display an attachment's URL `<r:attachment:url name="file.jpg"/>` * Display an attachment's `#{key}` attribute `<r:attachment:#{key} name="file.jpg"/>` * Display the date an attachment was added `<r:attachment:date name="file.txt"/>` * Display an attached image `<r:attachment:image name="file.jpg"/>` * Display a link to an attachment `<r:attachment:link name="file.jpg"/>` or `<r:attachment:link name="file.jpg">Click Here</r:attachment:link>` * Display name of the user who added the attachment `<r:attachment:author name="file.jpg"/>` * Iterate through all the attachments on a page `<r:attachment:each><r:link/></r:attachment:each>` * Display the extension of an attachement inside iterations with `<r:attachment:extension/>`
Java
UTF-8
541
2.75
3
[]
no_license
package zelfstudieopdrachten.zelfstudie1; import java.util.ArrayList; public class Main { public static void main(String[] args){ Zelfstudie1 test = new Zelfstudie1(); System.out.println("Opdracht 1:"); test.forLoop(); System.out.println("\nOpdracht 2:"); test.whileLoop(); System.out.println("\nOpdracht 3:"); test.randomNums(); System.out.println("\nOpdracht 4:"); test.sumNums(); System.out.println("\nOpdracht 5:"); test.zaag(); } }
C++
UTF-8
1,789
2.828125
3
[]
no_license
//Robotkol Desktop Application #include "axis.h" #include <iostream> #include <sstream> #include <utility> namespace rk { void axis_handler::set_deactive() { _robot_inf.send_data<char>('<'); _robot_inf.send_data<char>('\n'); } void axis_handler::set_active() { _robot_inf.send_data<char>('>'); _robot_inf.send_data<char>('\n'); } void axis_handler::set_axis_angle(axis_type axis_t, double angle, bool is_recording) { int int_angle = static_cast<int>(angle); std::stringstream ss; switch(axis_t) { case axis_type::axis_1: ss << "1:" << int_angle << std::endl; break; case axis_type::axis_2: ss << "2:" << int_angle << std::endl; break; case axis_type::axis_3: ss << "3:" << int_angle << std::endl; break; case axis_type::axis_4: ss << "4:" << int_angle << std::endl; break; } if(!is_recording) _robot_inf.send_data<std::string>(ss.str()); else _last_record << ss.str(); } void axis_handler::set_gripper_status(bool status, bool is_recording) { if(!is_recording) { _robot_inf.send_data<std::string>("G:"); _robot_inf.send_data<bool>(std::move(status)); _robot_inf.send_data<char>('\n'); } else { _last_record << "G:"; _last_record << status << std::endl; } } void axis_handler::clear_last_record() { _last_record.str(std::string()); } void axis_handler::play_last_record() { _robot_inf.send_record(_last_record.str()); } std::string axis_handler::get_last_record() { return _last_record.str(); } bool axis_handler::check_last_record() { return _last_record.tellp() == std::streampos(0) ? false : true; } bool axis_handler::init(const std::string& port_adress) { return _robot_inf.connect(port_adress.c_str()); } }
C++
UTF-8
871
3.1875
3
[]
no_license
#include <iostream> using namespace std; void Heapify(int a[],int n,int index) { int largest = index; int left = 2*index+1; int right = 2*index+2; if(left<n && a[left]>a[largest]) largest = left; if(right<n &&a[right]>a[largest]) largest = right; if(largest!=index) { swap(a[largest],a[index]); Heapify(a,n,largest); } } void buildHeap(int arr[],int n) { for(int i = (n-1)/2;i>=0;i--) Heapify(arr,n,i); } int main() { int t; cin>>t; while(t--) { int size,k; cin>>size>>k; int arr[size]; for(int i=0;i<size;i++) cin>>arr[i]; buildHeap(arr,size); for (int i=size-1; k>0; k--,i--) { cout<<arr[0]<<" "; swap(arr[0], arr[i]); Heapify(arr, i, 0); } cout<<endl; } return 0; }
Java
UTF-8
3,030
2.328125
2
[]
no_license
package com.fred.ecoxp; import java.io.File; import java.io.IOException; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.fred.ecoxp.commands.EcoXPCommand; import com.fred.ecoxp.commands.LevelsCommand; import com.fred.ecoxp.commands.XPShopCommand; import com.fred.ecoxp.listeners.BuyListener; import com.fred.ecoxp.listeners.InventoryClickListener; import com.fred.ecoxp.listeners.LevelEventListener; import com.fred.ecoxp.listeners.PlayerLevelUpListener; import com.fred.ecoxp.listeners.XPGain; import com.fred.ecoxp.utils.Eco; import net.milkbowl.vault.permission.Permission; public class EcoXP extends JavaPlugin { public static Permission perms = null; @Override public void onEnable() { setup(this); setupPermissions(); // Register Commands. getCommand("levels").setExecutor(new LevelsCommand(this)); getCommand("xpshop").setExecutor(new XPShopCommand(this)); getCommand("ecoxp").setExecutor(new EcoXPCommand()); // Register Listeners. getServer().getPluginManager().registerEvents(new XPGain(this), this); getServer().getPluginManager().registerEvents(new LevelEventListener(), this); getServer().getPluginManager().registerEvents(new InventoryClickListener(this), this); getServer().getPluginManager().registerEvents(new BuyListener(this), this); getServer().getPluginManager().registerEvents(new PlayerLevelUpListener(this), this); } @Override public void onDisable() {} /* * == CONFIGURING VAULT == */ private boolean setupPermissions() { RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class); perms = rsp.getProvider(); return perms != null; } /* * == CONFIGURING YAML FILES == */ public FileConfiguration xp; File xpfile; // Setup xp.yml public void setup(Plugin p) { getConfig().options().copyDefaults(true); saveConfig(); if(getConfig().contains("eco-symbol")) { Eco.setCS(getConfig().getString("eco-symbol")); } if(getConfig().contains("chat-prefix")) { Eco.setPrefix(getConfig().getString("chat-prefix")); } if(!p.getDataFolder().exists()) { try { p.getDataFolder().createNewFile(); } catch(IOException e) { Bukkit.getServer().getLogger().severe("Couldn't create xp folder."); } } xpfile = new File(p.getDataFolder(), "xp.yml"); if(!xpfile.exists()) { try { xpfile.createNewFile(); } catch(IOException e) { Bukkit.getServer().getLogger().severe("Could not create xp.yml"); } } xp = YamlConfiguration.loadConfiguration(xpfile); } public FileConfiguration xp() { return xp; } public void savexp() { try { xp.save(xpfile); } catch (IOException e) { Bukkit.getServer().getLogger().severe("Couldn't save xp.yml"); } } }
C++
UTF-8
9,216
2.578125
3
[]
no_license
/* * MRawEventList.cxx * * * Copyright (C) by Andreas Zoglauer. * All rights reserved. * * * This code implementation is the intellectual property of * Andreas Zoglauer. * * By copying, distributing or modifying the Program (or any work * based on the Program) you indicate your acceptance of this statement, * and all its terms. * */ //////////////////////////////////////////////////////////////////////////////// // // MRawEventList.cxx // // This is a list of MRERawEvent-objects. // The different objects are different expressions (different hit sequenence, // track direction) of the same underlying (one and only) event. // // The destructor does not delete the objects, but you have to call // DeleteAll() before destructing. // //////////////////////////////////////////////////////////////////////////////// // Standard libs: #include <limits> #include <algorithm> using namespace std; // MEGAlib libs: #include "MAssert.h" #include "MRawEventList.h" #include "MStreams.h" #include "MRETrack.h" #ifdef ___CINT___ ClassImp(MRawEventList) #endif //////////////////////////////////////////////////////////////////////////////// MRawEventList::MRawEventList() { // Create a new MRawEventList object Init(); } //////////////////////////////////////////////////////////////////////////////// MRawEventList::MRawEventList(MGeometryRevan* Geometry) { // Create a new MRawEventList object Init(); m_Geometry = Geometry; } //////////////////////////////////////////////////////////////////////////////// MRawEventList::~MRawEventList() { // This does not delete the raw events itself! // Call DeleteAll() before if you want to delete the MRERawEvents, too } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::Init() { // Some initialisations equal for all constructors: m_RawEventList.clear(); m_InitialEvent = 0; m_OptimumEvent = 0; m_BestTryEvent = 0; m_EventCounter = 0; } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::SetGeometry(MGeometryRevan* Geometry) { // Set the geometry description m_Geometry = Geometry; } //////////////////////////////////////////////////////////////////////////////// MString MRawEventList::ToString(bool WithLink, int Level) { // Returns a MString containing the relevant data of this object, i.e. // it calls ToString(...) of the raw events // // WithLink: Display the links of the rawevents sub elements // Level: A level of N displays 3*N blancs before the text MString String(""); for (int i = 0; i < Level; i++) { String += MString(" "); } String += MString("Raw event with the following possible combinations:\n"); char Text[100]; for (int e = 0; e < GetNRawEvents(); e++) { for (int i = 0; i < Level; i++) { String += MString(" "); } sprintf(Text, "Combination %d:\n", e+1); String += MString(Text); String += GetRawEventAt(e)->ToString(WithLink, Level+1); } return String; } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::AddRawEvent(MRERawEvent* RE) { // Add a raw event to the list m_RawEventList.push_back(RE); } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::RemoveRawEvent(MRERawEvent* RE) { // Remove a raw event from the list but do NOT delete it if (RE == m_InitialEvent) m_InitialEvent = 0; if (RE == m_OptimumEvent) m_OptimumEvent = 0; if (RE == m_BestTryEvent) m_BestTryEvent = 0; m_RawEventList.erase(find(m_RawEventList.begin(), m_RawEventList.end(), RE)); } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::DeleteRawEvent(MRERawEvent* RE) { // Remove a raw event from the list and delete it if (RE == m_InitialEvent) m_InitialEvent = 0; if (RE == m_OptimumEvent) m_OptimumEvent = 0; if (RE == m_BestTryEvent) m_BestTryEvent = 0; m_RawEventList.erase(find(m_RawEventList.begin(), m_RawEventList.end(), RE)); delete RE; } //////////////////////////////////////////////////////////////////////////////// MRERawEvent* MRawEventList::GetRawEventAt(int i) { // Get the raw event at position i. Counting starts with zero! if (i < int(m_RawEventList.size())) { return m_RawEventList[i]; } merr<<"Index ("<<i<<") out of bounds (0, "<<m_RawEventList.size()-1<<")"<<endl; return 0; } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::SetRawEventAt(MRERawEvent* RE, int i) { // Set the raw event at position i. Counting starts with zero! if (i < int(m_RawEventList.size())) { m_RawEventList[i] = RE; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<m_RawEventList.size()-1<<")"<<endl; massert(i < int(m_RawEventList.size())); } } //////////////////////////////////////////////////////////////////////////////// int MRawEventList::GetNRawEvents() { // Get the number of raw events in the list return m_RawEventList.size(); } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::DeleteAll() { // Delete all elements of the list while (m_RawEventList.size() != 0) { DeleteRawEvent(GetRawEventAt(0)); } m_InitialEvent = 0; m_OptimumEvent = 0; m_BestTryEvent = 0; } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::SetInitialRawEvent(MRERawEvent* RE) { // add the first raw event and start the analysis of the event massert(RE != 0); //! Delete all previous events DeleteAll(); m_InitialEvent = RE; m_OptimumEvent = 0; m_BestTryEvent = 0; AddRawEvent(RE); } //////////////////////////////////////////////////////////////////////////////// bool MRawEventList::HasOptimumEvent() { // Check if we have an optimum event if (m_OptimumEvent != 0) { mdebug<<"Optimum event!"<<endl; return true; } mdebug<<"No optimum event!"<<endl; return false; } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::SetBestTryEvent(MRERawEvent* BestTryEvent) { // Set the event which is the best shot, but is definitely not the correct one m_BestTryEvent = BestTryEvent; } //////////////////////////////////////////////////////////////////////////////// bool MRawEventList::HasBestTry() { // Check if we have abest try event... if (m_BestTryEvent != 0) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// MRERawEvent* MRawEventList::GetBestTryEvent() { // Return a pointer to the best try... return m_BestTryEvent; } //////////////////////////////////////////////////////////////////////////////// void MRawEventList::SetOptimumEvent(MRERawEvent* OptimumEvent) { // Set the optimum event if (OptimumEvent != 0) { massert(OptimumEvent->IsGoodEvent() == true); } m_OptimumEvent = OptimumEvent; } //////////////////////////////////////////////////////////////////////////////// MRERawEvent* MRawEventList::GetOptimumEvent() { // Return the optimum event return m_OptimumEvent; } //////////////////////////////////////////////////////////////////////////////// MRERawEvent* MRawEventList::GetInitialRawEvent() { // Return the inital event, i.e. the mere hits event... return m_InitialEvent; } //////////////////////////////////////////////////////////////////////////////// bool MRawEventListTrackCompareGoodAreHigh(MRERawEvent* a, MRERawEvent* b) { // No quality factor is a large number, so make sure it is at the end of the list! if (a->GetTrackQualityFactor() == MRERawEvent::c_NoQualityFactor) { return false; } if (a->GetTrackQualityFactor() > b->GetTrackQualityFactor()) { return true; } else if (a->GetTrackQualityFactor() == b->GetTrackQualityFactor()) { if (a->GetRESEAt(0)->GetEnergy() < b->GetRESEAt(0)->GetEnergy()) { return true; } else { return false; } } else { return false; } }; //////////////////////////////////////////////////////////////////////////////// bool MRawEventListTrackCompareGoodAreLow(MRERawEvent* a, MRERawEvent* b) { if (a->GetTrackQualityFactor() < b->GetTrackQualityFactor()) { return true; } else if (a->GetTrackQualityFactor() == b->GetTrackQualityFactor()) { if (a->GetRESEAt(0)->GetEnergy() < b->GetRESEAt(0)->GetEnergy()) { return true; } else { return false; } } else { return false; } }; //////////////////////////////////////////////////////////////////////////////// void MRawEventList::SortByTrackQualityFactor(bool GoodAreHigh) { // This is some kind of basic quicksort algorithm: if (GoodAreHigh == true) { sort(m_RawEventList.begin(), m_RawEventList.end(), MRawEventListTrackCompareGoodAreHigh); } else { sort(m_RawEventList.begin(), m_RawEventList.end(), MRawEventListTrackCompareGoodAreLow); } } // MRawEventList.cxx: the end... ////////////////////////////////////////////////////////////////////////////////
C++
UTF-8
4,316
2.875
3
[]
no_license
#pragma once #include "gdl/base/exception.h" #include "gdl/math/serial/sparseMatCLLSerial.h" #include <iostream> namespace GDL { // -------------------------------------------------------------------------------------------------------------------- template <typename _type> SparseMatCLLSerial<_type>::Node::Node(U32 row, _type value) : mRow{row} , mValue{value} { } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> inline SparseMatCLLSerial<_type>::SparseMatCLLSerial(U32 rows, U32 cols) : mRows{rows} , mCols{cols} { } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> inline _type SparseMatCLLSerial<_type>::operator()(U32 row, U32 col) const { DEV_EXCEPTION(row >= mRows || col >= mCols.size(), "Selected row or column exceeds matrix size"); const ForwardList<Node>& colList = mCols[col]; auto currValue = colList.begin(); if (colList.empty() || row < currValue->mRow) return 0; while (currValue != colList.end() && currValue->mRow < row) ++currValue; if (currValue == colList.end() || currValue->mRow > row) return 0; return currValue->mValue; } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> inline U32 SparseMatCLLSerial<_type>::Cols() const { return mCols.size(); } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> inline U32 SparseMatCLLSerial<_type>::CountStoredValues() const { U32 numStoredValues = 0; for (U32 i = 0; i < mCols.size(); ++i) for ([[maybe_unused]] const auto& node : mCols[i]) ++numStoredValues; return numStoredValues; } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> void SparseMatCLLSerial<_type>::Remove(U32 row, U32 col) { ForwardList<Node>& colList = mCols[col]; auto currValue = colList.begin(); if (currValue == colList.end()) return; if (currValue->mRow == row) colList.pop_front(); auto prevValue = currValue++; while (true) { if (currValue == colList.end() || currValue->mRow > row) return; if (currValue->mRow == row) { colList.erase_after(prevValue); return; } prevValue = currValue++; } } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> inline U32 SparseMatCLLSerial<_type>::Rows() const { return mRows; } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> inline void SparseMatCLLSerial<_type>::Set(U32 row, U32 col, _type value) { DEV_EXCEPTION(row >= mRows || col >= mCols.size(), "Selected row or column exceeds matrix size"); if (value == 0.0) { Remove(row, col); return; } ForwardList<Node>& colList = mCols[col]; auto currValue = colList.begin(); // New element is in front of first if (colList.empty() || currValue->mRow > row) { colList.emplace_front(row, value); return; } auto nextValue = ++colList.begin(); while (nextValue != colList.end() && nextValue->mRow <= row) { currValue = nextValue; ++nextValue; } if (currValue->mRow == row) currValue->mValue = value; else colList.emplace_after(currValue, row, value); } // -------------------------------------------------------------------------------------------------------------------- template <typename _type> std::ostream& operator<<(std::ostream& os, const SparseMatCLLSerial<_type>& mat) { for (U32 i = 0; i < mat.Rows(); ++i) { os << "| "; for (U32 j = 0; j < mat.Cols(); ++j) os << mat(i, j) << " "; os << "|" << std::endl; } return os; } } // namespace GDL
PHP
UTF-8
583
2.5625
3
[]
no_license
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateTicketClassTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ticket_class', function(Blueprint $table) { $table->integer('tid', true); $table->text('name')->nullable(); $table->string('class', 10)->nullable(); $table->string('flg', 10)->default('Y'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('ticket_class'); } }
Markdown
UTF-8
946
3.296875
3
[ "MIT" ]
permissive
--- name: Remove user as a collaborator example: octokit.rest.projects.removeCollaborator({ project_id, username }) route: DELETE /projects/{project_id}/collaborators/{username} scope: projects type: API method --- # Remove user as a collaborator Removes a collaborator from an organization project. You must be an organization owner or a project `admin` to remove a collaborator. ```js octokit.rest.projects.removeCollaborator({ project_id, username, }); ``` ## Parameters <table> <thead> <tr> <th>name</th> <th>required</th> <th>description</th> </tr> </thead> <tbody> <tr><td>project_id</td><td>yes</td><td> The unique identifier of the project. </td></tr> <tr><td>username</td><td>yes</td><td> The handle for the GitHub user account. </td></tr> </tbody> </table> See also: [GitHub Developer Guide documentation](https://docs.github.com/rest/reference/projects#remove-project-collaborator).
Java
UTF-8
2,891
2.078125
2
[]
no_license
package com.tw.shoppify.inventory.api; import com.tw.shoppify.inventory.ApiTest; import com.tw.shoppify.inventory.appservice.Product; import com.tw.shoppify.inventory.domain.Inventory; import com.tw.shoppify.inventory.domain.InventoryRepo; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.List; import static com.tw.shoppify.inventory.TestSupport.prepareInventories_13_12_11; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.text.MatchesPattern.matchesPattern; import static org.mockserver.model.HttpResponse.response; /** * @author hf_cherish * @date 4/17/18 */ public class InventoryApiTest extends ApiTest { @Autowired InventoryRepo inventoryRepo; @Test public void should_201_pricing() { Product product = new Product("test", "test_store"); setProductExists(product); String location = myGiven() .body(new HashMap() {{ put("amount", 10); }}) .when() .post(inventoriesUrl(product.getId())) .then() .statusCode(201) .header("Location", matchesPattern("^.*/inventories/.*$")) .extract() .header("Location"); String[] split = location.split("/"); String pricingId = split[split.length - 1]; inventoryRepo.deleteById(pricingId); } @Test public void should_404_when_pricing_for_product_not_exists() { whenGetProduct("notExistId") .respond( response() .withStatusCode(404) ); myGiven() .body(new HashMap() {{ put("amount", 10); }}) .when() .post(inventoriesUrl("notExistId")) .then() .statusCode(404); } private String inventoriesUrl(String productId) { return "/products/" + productId + "/inventories"; } @Test public void should_get_product_current_inventory() throws InterruptedException { Product product = new Product("name1", "store"); setProductExists(product); List<Inventory> inventories = prepareInventories_13_12_11(product); inventoryRepo.saveAll(inventories); myGiven() .when() .get(inventoriesUrl(product.getId()) + "/current") .then() .statusCode(200) .body("product_id", is(product.getId())) .body("amount", is(11)) .body("id", is(notNullValue())) .body("create_at", is(notNullValue())); inventoryRepo.deleteAll(inventories); } }
JavaScript
UTF-8
13,400
3.5625
4
[]
no_license
(function(goma){ "use strict"; /** * クラス宣言はfunction式と同様に巻き上げされないので * 宣言前に参照するとエラーになる。 */ //let pt = new Point(1, 1); class Point{ constructor(x = 0, y = 0){ this.x = x; this.y = y; } get coords(){ return [this.x, this.y]; } /** * Object.toStringと同様,文字列を要求された際に自動で呼び出される。 */ toString(){ return this.coords.toString(); } calcDistance(point){ const deltaX = this.x - point.coords[0]; const deltaY = this.y - point.coords[1]; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); } static getDistance(p1, p2){ /** * staticメソッドの中でstaticでないメンバを参照してもエラーにならない。 * ただし値はundefinedになっている。 */ goma.log(this.coords); return p1.calcDistance(p2); } } class Point3D extends Point{ /** * NaNやnullが渡された時は引数のデフォルト値が使われない。 * undefinedが渡された時は引数のデフォルト値が使われる。 */ constructor(x = 0, y = 0, z = 0){ /** * super.constructorと書くとthisが未定義だというエラーが発生する。 */ super(x, y); this.z = z; } /** * コンストラクタのオーバーロードはできない。というのもECMAScriptにおける * クラスは関数の特殊な形でしかないからだ。ECMAScriptの関数はオーバーロード * できない。従ってクラスもオーバーロードできない。 * またRest parameterはデフォルト値を指定することができない。 */ //constructor(...coords){ // this.constructor(coords[0], coords[1], coords[2]); //} /** * スーパークラスのアクセッサメソッドをオーバーライドする。 */ get coords(){ let cs = super.coords; cs.push(this.z); return cs; } } /** * インターフェースのようなものを定義している。 * 各メソッド内ではスーパークラスのメンバにアクセスすることができる。 * スーパークラスの別名(ここではBase)を介してstaticメソッドに * アクセスすることもできる。 */ const Sail = Base => class extends Base { sail() { return this.name + Base.getVersion() + "Sail::sailing!"; } }; const Fly = Base => class extends Base { fly() { return this.decoratedName + "Fly::flying!"; } }; class Plane { /** * フィールドを定義することはできない。 * シンタックスエラーになる。 */ //let _name = "sample"; constructor(name) { this.name = name; } get decoratedName() { return "***" + this.name + "***"; } static getVersion() { return "1.0"; } cruise() { return "Plane::cruising!"; } } /** * Java: * class X extends Y implements A, B * * ECMAScript6: * class X extends A(B(Y)) */ class SeaPlane extends Sail(Fly(Plane)) { constructor(name){ super(name); } cruise() { /** * thisキーワードが無いとReferenceErrorになる。 * このクラスが該当するメソッドを実装していたとしてもエラーになる。 * super.cruise()をthis.cruise()と書いてしまうと * 「too much recursion」と通知されエラーになる。 */ return [this.sail(), this.fly(), super.cruise()].join(" "); } toString() { return this.name + " -> " + this.cruise(); } } const scripts = [ g => { const base = ".class-practice-container "; const resultArea = g.select(base + ".result-area"); let points = []; g.clickListener(g.select(base + ".append-info"), e => { const x = g.rand(10), y = g.rand(10); const p = new Point(x, y); g.log(p.coords); g.println(resultArea, p); points.push(p); }); g.clickListener(g.select(base + ".clear-info"), e => { g.clear(resultArea); points = []; }); g.clickListener(g.select(".distance-info"), e => { if(points.length <= 1){ return; } let distance = 0; /** * constで宣言された定数もletで宣言された変数と同様に * ブロックスコープを持つ。 */ const startP = points[0]; const lastP = points[points.length - 1]; points.reduce((p1, p2) => { distance += p1.calcDistance(p2); return p2; }); g.println(resultArea, "合計距離:" + distance); g.println(resultArea, "始点から終点の直線距離:" + Point.getDistance(startP, lastP)); }); }, g => { /** * constとletは同時に指定できない。 */ const container = ".class-extends-container "; const resultArea = g.select(container + ".result-area"); const displayCoords = e => { const inputCoords = g.values(g.selectAll(container + ".extends-coords"), parseInt); const point3d = new Point3D(...inputCoords); g.println(resultArea, point3d.coords); }; const clearResult = e => { g.clear(resultArea); }; g.clickListener(g.select(container + ".display-extends-coords"), displayCoords); g.clickListener(g.select(container + ".clear-extends-result"), clearResult); }, g => { const container = ".class-mixin-container "; const resultArea = g.select(container + ".result-area"); const diplayResult = e => { const seaPlane = new SeaPlane("Sample plane"); g.println(resultArea, seaPlane); }; const clearResult = e => { g.clear(resultArea); }; g.clickListener(g.select(container + ".display-mixin-result"), diplayResult); g.clickListener(g.select(container + ".clear-mixin-result"), clearResult); }, g => { const base = ".inspection-new-target ", resultArea = g.select(base + ".result-area"), targetTypes = g.selectAll(base + ".new-target-type-selection input[name='new-target-type']"), withNewOp = g.select(base + ".with-new-operator"), runner = g.select(base + ".display-result"), clearer = g.select(base + ".clear-result"); const getNewTarget = target => target || {}; function SampleFunc() { return getNewTarget(new.target); } class BaseSample { constructor() { g.log(new.target); this.targetName = getNewTarget(new.target).name; } get name() { /** * constructor関数以外の場所ではnew.targetはundefinedになっている。 */ //g.log(new.target); //return getNewTarget(new.target).name; return this.targetName; } } class SubSample extends BaseSample { /** * 継承した場合new.targetの値はサブクラスを示す値になる。 */ constructor() { super(); } } /** * アロー関数はnew演算子と合わせて呼び出したらエラーになるので * new.targetの値を確認することができない。 * new演算子と合わせずに呼び出した時はundefinedである。 */ const SampleArrowFunc = () => getNewTarget(new.target); const newTargets = { function_sentence: SampleFunc, class_no_inheritance: BaseSample, class_with_inheritance: SubSample, arrow_function: SampleArrowFunc }; const getSelectedTargetType = () => g.getSelectedValue(targetTypes); g.clickListener(runner, () => { const targetType = getSelectedTargetType(), Target = newTargets[targetType]; let result; try { let target; if (withNewOp.checked) { target = new Target(); } else { target = Target(); } result = target.name; } catch(err) { result = err.message; } g.println(resultArea, result); }); g.clickListener(clearer, () => { g.clear(resultArea); }); }, g => { const base = ".override-constructor ", resultArea = g.select(base + ".result-area"), clearer = g.select(base + ".clear-result"), runner = g.select(base + ".display-result"); class Parent { constructor (value) { this.value = value; } add (v) { return this.value + v; } get version() { return 1; } }; class ChildNoOverride extends Parent { /** * スーパークラスのコンストラクタ関数をオーバーライドしない。 * この場合このクラスのインスタンス生成時もスーパークラスの * コンストラクタが使用される。 */ } class ChildWithOverride extends Parent { constructor (value) { /** * super()を書かなかったりスーパークラスのコンストラクタ呼び出しを * <pre> * super.constructor(value); * </pre> * と書いてしまうと,スーパークラスのメソッド呼び出した時点で * エラーになる。呼ばれたメソッド内でthisを参照しているかどうかは * 関係無い。 */ super(value); this.value = String(value); } get version() { return super.version + ".B"; } } runner.addEventListener("click", () => { const param = 1; const result = []; try{ const o1 = new ChildNoOverride(param); result.push("ChildNoOverride result ... " + o1.add(param)); result.push("ChildNoOverride version ... " + o1.version); const o2 = new ChildWithOverride(param); result.push("ChildWithOverride result ... " + o2.add(param)); result.push("ChildWithOverride version ... " + o2.version); } catch (err) { result.push(err.message); } g.println(resultArea, result.join("<br />")); }); clearer.addEventListener("click", () => g.clear(resultArea)); } ]; goma.run(scripts, { reject: err => { alert(err); goma.error(err); } }); }(window.goma));
PHP
UTF-8
4,903
3.15625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace League\Glide\Manipulators; use Intervention\Image\Image; use League\Glide\Manipulators\Helpers\Color; use League\Glide\Manipulators\Helpers\Dimension; /** * @property string $border * @property string $dpr */ class Border extends BaseManipulator { /** * Perform border image manipulation. * * @param Image $image The source image. * * @return Image The manipulated image. */ public function run(Image $image) { if ($border = $this->getBorder($image)) { list($width, $color, $method) = $border; if ('overlay' === $method) { return $this->runOverlay($image, $width, $color); } if ('shrink' === $method) { return $this->runShrink($image, $width, $color); } if ('expand' === $method) { return $this->runExpand($image, $width, $color); } } return $image; } /** * Resolve border amount. * * @param Image $image The source image. * * @return (float|string)[]|null The resolved border amount. * * @psalm-return array{0: float, 1: string, 2: string}|null */ public function getBorder(Image $image) { if (!$this->border) { return; } $values = explode(',', $this->border); $width = $this->getWidth($image, $this->getDpr(), isset($values[0]) ? $values[0] : null); $color = $this->getColor(isset($values[1]) ? $values[1] : null); $method = $this->getMethod(isset($values[2]) ? $values[2] : null); if ($width) { return [$width, $color, $method]; } } /** * Get border width. * * @param Image $image The source image. * @param float $dpr The device pixel ratio. * @param string $width The border width. * * @return float|null The resolved border width. */ public function getWidth(Image $image, $dpr, $width) { return (new Dimension($image, $dpr))->get($width); } /** * Get formatted color. * * @param string $color The color. * * @return string The formatted color. */ public function getColor($color) { return (new Color($color))->formatted(); } /** * Resolve the border method. * * @param string $method The raw border method. * * @return string The resolved border method. */ public function getMethod($method) { if (!in_array($method, ['expand', 'shrink', 'overlay'], true)) { return 'overlay'; } return $method; } /** * Resolve the device pixel ratio. * * @return float The device pixel ratio. */ public function getDpr() { if (!is_numeric($this->dpr)) { return 1.0; } if ($this->dpr < 0 or $this->dpr > 8) { return 1.0; } return (float) $this->dpr; } /** * Run the overlay border method. * * @param Image $image The source image. * @param float $width The border width. * @param string $color The border color. * * @return Image The manipulated image. */ public function runOverlay(Image $image, $width, $color) { return $image->rectangle( (int) round($width / 2), (int) round($width / 2), (int) round($image->width() - ($width / 2)), (int) round($image->height() - ($width / 2)), function ($draw) use ($width, $color) { $draw->border($width, $color); } ); } /** * Run the shrink border method. * * @param Image $image The source image. * @param float $width The border width. * @param string $color The border color. * * @return Image The manipulated image. */ public function runShrink(Image $image, $width, $color) { return $image ->resize( (int) round($image->width() - ($width * 2)), (int) round($image->height() - ($width * 2)) ) ->resizeCanvas( (int) round($width * 2), (int) round($width * 2), 'center', true, $color ); } /** * Run the expand border method. * * @param Image $image The source image. * @param float $width The border width. * @param string $color The border color. * * @return Image The manipulated image. */ public function runExpand(Image $image, $width, $color) { return $image->resizeCanvas( (int) round($width * 2), (int) round($width * 2), 'center', true, $color ); } }
PHP
UTF-8
2,872
3.046875
3
[]
no_license
<?php /** * This file is part of the Asar Web Framework * * (c) Wayne Duran <asartalo@projectweb.ph> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Asar\Content; use Asar\Http\Message\Response; use Asar\Http\Message\Request; use Asar\Routing\Route; use Asar\Template\TemplateAssembler; /** * An object representation of a web page */ class Page { private $assembler; private $route; private $request; private $response; private $contents = array(); /** * Constructor * * @param TemplateAssembler $assembler the template assembler * @param Route $route the request route * @param Request $request the request */ public function __construct(TemplateAssembler $assembler, Route $route, Request $request) { $this->assembler = $assembler; $this->route = $route; $this->request = $request; $this->response = new Response; } /** * Gives a response * * @return Response */ public function getResponse() { $content = ''; if ($template = $this->getTemplate()) { $content = $template->render($this->contents); } $this->response->setContent($content); $this->response->setHeader('content-type', 'text/html; charset=utf-8'); return $this->response; } /** * Retrieves the template used * * @return Asar\Template\TemplateAssembly */ public function getTemplate() { return $this->assembler->find( $this->route->getName(), array( 'type' => 'html', 'method' => $this->request->getMethod(), 'status' => $this->response->getStatus() ) ); } /** * Sets a response header * * @param string $key the response header key * @param mixed $value the response header value */ public function setHeader($key, $value) { $this->response->setHeader($key, $value); } /** * Sets a response status * * @param integer $statusCode the response status code */ public function setStatus($statusCode) { $this->response->setStatus($statusCode); } /** * Sets a content parameter * * @param mixed $var the content parameter key or an associative * array of parameter keys and values * @param string $value the content parameter value */ public function set($var, $value = null) { if (is_array($var)) { foreach ($var as $key => $value) { $this->contents[$key] = $value; } } else { $this->contents[$var] = $value; } } }
C#
UTF-8
1,383
2.765625
3
[]
no_license
using UnityEngine; public abstract class Controller : MonoBehaviour { [Header("Pawn")] [SerializeField] protected Pawn _controlledPawn; private bool _controlsEnabled = true; protected Inputs NoControlInputs = new Inputs(); protected virtual void Start() { if (!SetControlledPawn(_controlledPawn)) { _controlledPawn = null; } } public bool SetControlledPawn(Pawn pawn) { // Can't take control of a pawn already controlled! if (pawn?.Controller) { return false; } // Free any pawn already controlled if (_controlledPawn) { _controlledPawn.UpdateWithInputs(NoControlInputs); _controlledPawn.SetController(null); } if (pawn) { pawn.SetController(this); } _controlledPawn = pawn; return true; } public Pawn GetControlledPawn() { return _controlledPawn; } // Returns if the pawn have control of himself. public virtual bool ControlsEnabled() { return _controlsEnabled; } public virtual void EnableControl(bool enable) { _controlsEnabled = enable; if (!enable && _controlledPawn) { _controlledPawn.UpdateWithInputs(NoControlInputs); } } }
Java
UTF-8
1,267
2.375
2
[]
no_license
package com.example.customviews; import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.customviews.databinding.NameItemBinding; import java.util.List; public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.NameViewHolder> { List<String> nameList; public NamesAdapter(List<String> nameList) { this.nameList = nameList; } @Override public NameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { NameItemBinding binding = NameItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false); return new NameViewHolder(binding.getRoot()); } @Override public void onBindViewHolder(NameViewHolder holder, int position) { holder.binding.setName(nameList.get(position)); } @Override public int getItemCount() { return nameList.size(); } public class NameViewHolder extends RecyclerView.ViewHolder { NameItemBinding binding; public NameViewHolder(View itemView) { super(itemView); binding = DataBindingUtil.bind(itemView); } } }
Ruby
UTF-8
949
2.875
3
[]
no_license
require 'twitter' class DepressedUnicornBot def tweet composed_tweet end def composed_tweet [subject, action, object, location, closing_remark].join(' ') end def subject random_phrase_from('subjects.txt') end def action random_phrase_from('actions.txt') end def object random_phrase_from('objects.txt') end def location random_phrase_from('locations.txt') end def closing_remark random_phrase_from('closing_remarks.txt') end def random_phrase_from(filename) open("lib/#{filename}").read.split("\n").sample.strip end end # exit unless ((Time.now.hour % 3) == 0) sentence = DepressedUnicornBot.new.tweet client = Twitter::REST::Client.new do |config| config.consumer_key = ENV["consumer_key"] config.consumer_secret = ENV["consumer_secret"] config.access_token = ENV["access_token"] config.access_token_secret = ENV["access_token_secret"] end client.update(sentence)
Java
UTF-8
5,139
1.992188
2
[ "Apache-2.0" ]
permissive
package com.colin; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.colin.controller.CartItemController; import com.colin.controller.ProductController; import com.colin.models.CartItem; import com.colin.models.Category; import com.colin.models.Product; import com.colin.models.ProductCategory; import com.colin.models.ProductQuantity; import com.colin.models.Role; import com.colin.models.User; import com.colin.repo.CategoryRepository; import com.colin.repo.UserRepository; import com.colin.service.CartItemService; import com.colin.service.ProductService; import com.colin.service.UserDetailsServiceImpl; import com.fasterxml.jackson.databind.ObjectMapper; @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @SpringBootTest @AutoConfigureMockMvc public class CartItemControllerTest { ObjectMapper map; @MockBean CartItemService cartItemService; @MockBean CategoryRepository categoryRepository; @MockBean UserDetailsServiceImpl userDetails; @MockBean ProductService productService; @InjectMocks CartItemController controllerUnderTest; private MockMvc mvc; @BeforeEach public void contextLoads() { map = new ObjectMapper(); MockitoAnnotations.openMocks(this); this.mvc = MockMvcBuilders.standaloneSetup(controllerUnderTest).build(); Category c = new Category(1, "Dairy", new ArrayList<>()); Product p = new Product(1, "Milk", 3, 2.99, c, new ArrayList<>()); Set<Role> roles = new HashSet<>(); Role r = new Role(); r.setName("ROLE_USER"); roles.add(r); User u = new User(1, "Percy", "pepperbox", roles, true, new ArrayList<>()); CartItem cI = new CartItem(3, 2, LocalDateTime.now(), u, p); cartItemService.createCartItem(cI); } @Test public void testGetAllProducts() throws Exception { ArrayList<CartItem> cartItems = new ArrayList<>(); Category c = new Category(1, "Dairy", new ArrayList<>()); Product p = new Product(1, "Milk", 3, 2.99, c, new ArrayList<>()); Set<Role> roles = new HashSet<>(); Role r = new Role(); r.setName("ROLE_USER"); roles.add(r); User u = new User(1, "Percy", "pepperbox", roles, true, new ArrayList<>()); CartItem cI = new CartItem(1, 2, LocalDateTime.now(), u, p); cartItems.add(cI); when(cartItemService.getUserCart(1l)).thenReturn(cartItems); mvc.perform(get("/api/cart/{userid}", 1) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(jsonPath("$[0].product.name").value("Milk")) .andExpect(jsonPath("$[0].product.quantity").value(3)) .andExpect(jsonPath("$[0].product.price").value(2.99)) .andExpect(jsonPath("$[0].quantity").value(2)); } @Test void addNewCartItem() throws Exception { Category c = new Category(1, "Dairy", new ArrayList<>()); Product p = new Product(1, "Milk", 3, 2.99, c, new ArrayList<>()); Set<Role> roles = new HashSet<>(); Role r = new Role(); r.setName("ROLE_USER"); roles.add(r); User u = new User(1, "Percy", "pepperbox", roles, true, new ArrayList<>()); Optional<Product> returnP = Optional.ofNullable(p); when(userDetails.findById(1l)).thenReturn(u); when(productService.getById(1l)).thenReturn(returnP); mvc.perform(post("/api/cart/{userid}", 1) .content(toJsonString(new ProductQuantity(2, 1l))) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @Test public void deleteCartItem() throws Exception { mvc.perform(delete("/api/cart/{userid}/product/{productid}", 1, 1)) .andExpect(status().isAccepted()); } @Test public void deleteAllCartItems() throws Exception { mvc.perform(delete("/api/cart/{userid}", 1)) .andExpect(status().isAccepted()); } public static String toJsonString(final Object obj) { try { return new ObjectMapper().writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException(e); } } }
Java
UTF-8
1,863
2.734375
3
[ "MIT" ]
permissive
package nullblade.craftanddeath.items; import nullblade.craftanddeath.items.alloys.AlloyManager; import nullblade.craftanddeath.items.alloys.OreAlloy; import nullblade.craftanddeath.main.DamageManager; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.Map; public class ItemManager { private static ItemManager instance; public static ItemManager getInstance() { return instance; } private Map<String, CustomItem> items; public ItemManager() { instance = this; items = new HashMap<>(); } public void registerItem(CustomItem item) { items.put(item.id, item); // The great wall of ifs. TODO: get rid of it if (item instanceof UsableItem) { ItemEventManager.getInstance().addUsable(item.id, (UsableItem) item); } if (item instanceof ArmourItem) { DamageManager.getInstance().registerArmourPiece(item.id, (ArmourItem) item); } if (item instanceof OreAlloy) { AlloyManager.getInstance().registerAlloy(((OreAlloy) item).getBase(), (OreAlloy) item); } if (item instanceof ConsumableItem) { ItemEventManager.getInstance().addConsumable(item.id, (ConsumableItem) item); } } public Map<String, CustomItem> getItems() { return items; } public ItemStack get(String id) { CustomItem item = items.get(id); if (item == null ){ return null; } else { return item.item; } } public static String get(ItemStack i) { if (i == null || !i.hasItemMeta() || !i.getItemMeta().hasLore() || i.getItemMeta().getLore().size() < 1) { return null; } return i.getItemMeta().getLore().get(i.getItemMeta().getLore().size()-1).substring(2); } }
Java
UTF-8
6,423
2.421875
2
[]
no_license
package com.example.accesoconcorreo; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import ModeloDominio.Lista; import ModeloDominio.ReadAndWriteSnippets; import ModeloDominio.Usuario; /** * Esta clase define el fragmento llamado "fragment_introducir_nom_lista2" que sirve para introducit un nombre para una nueva lista. * * @author: Pablo Ochoa, Javier Pérez, Marcos Moreno, Álvaro Bayo * * @version: 30/04/2021 */ public class introducir_nom_lista extends DialogFragment { //Representa el EditText en el cual habrá que introducir el nombre que se le querra dar a la lista private EditText etNombre; //Representa el botón de Aceptar del Fragment private Button btnAceptar; //Representa el botón de Cancelar del Fragment private Button btnCancelar; //Representa una cadena que indica el tipo de lista que se tendrá que crear private String tipoLista; //Representa una cadena que indica el email del usuario private String email; //Representa una cadena que indica el nick del usuario private String nick; //Representa una cadena que indica el nombre de la lista que introducirás private String nombreLista; //Representa el nombre del último botón en el cual se ha hecho click private String ultBoton=""; /** * Constructor * * @param tipoLista Define si la lsita es personal o grupal * @param email Representa el correo del usuaria al que está creando la lista * @param nick Representa el nick del usuaria al que está creando la lista */ public introducir_nom_lista(String tipoLista,String email,String nick){ this.email=email; this.nick=nick; this.tipoLista = tipoLista; } /** * Devuelve el nombre del último botón que se a clickado o la cadena vacía en caso de que no se haya clickado ninguno * @return ultBoton */ public String getUltBoton(){ return this.ultBoton; } /** * Devuelve el nombre de la lista * @return nombreLista */ public String getNombreLista(){ return this.nombreLista; } /** * Método que inicializa las componentes del dialogfragment * @param view * @param savedInstanceState */ @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ReadAndWriteSnippets.actualizaContadorListas(); etNombre = (EditText) view.findViewById(R.id.etNombre); btnAceptar = (Button) view.findViewById(R.id.btnAceptar); btnCancelar = (Button) view.findViewById(R.id.btnCancelar); btnAceptar.setOnClickListener(new View.OnClickListener() { /** * Método que sirve para comprobar que lo introducido en los campos de usuario y * contraseña corresponden a un usuario existente * @param v Representa al objeto View sobre el cual se ha hecho click */ @Override public void onClick(View v) { ultBoton = "Aceptar"; String nombreLista = etNombre.getText().toString(); if(nombreLista != null && nombreLista.trim().length() > 0) { if (tipoLista.equals("grupal")) { fragment_crear_compartida fragment=new fragment_crear_compartida(email,nick,etNombre.getText().toString()); FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); transaction.replace(R.id.nom_lista, fragment); transaction.addToBackStack(null); transaction.commit(); /* fragment.show(getActivity().getSupportFragmentManager(),"tag"); fragment.getLifecycle().getCurrentState(); */ } else { List<Usuario> lista=new ArrayList<>(); ReadAndWriteSnippets.insertarLista(nombreLista,nick,false); cerrarFragment(); Intent intent = new Intent(getContext(), ListaProductos.class); intent.putExtra("nick",nick); intent.putExtra("email",email); intent.putExtra("nombreLista",nombreLista); intent.putExtra("idLista",String.valueOf(Lista.getContLista())); startActivity(intent); } }else{ Toast.makeText(getActivity(),"Error, se debe introducir un nombre para la lista",Toast.LENGTH_SHORT).show(); } } }); btnCancelar.setOnClickListener(new View.OnClickListener() { /** * Método que sirve para comprobar que lo introducido en los campos de usuario y * contraseña corresponden a un usuario existente * @param v Representa al objeto View sobre el cual se ha hecho click */ @Override public void onClick(View v) { getFragmentManager().beginTransaction().remove(introducir_nom_lista.this).commit(); } }); } /** * Método que devuelve el inflater del fragment * @param inflater * @param container * @param savedInstanceState * @return */ @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_introducir_nom_lista2, container, false); } @Override public void onDestroy() { super.onDestroy(); } /** * Método que sirve para cerrar el Fragment */ private void cerrarFragment() { } }
C#
UTF-8
20,976
3.15625
3
[ "MIT" ]
permissive
using System; using System.Threading; using System.Threading.Tasks; namespace Sophos.Commands { /// <summary> /// This Command encapsulates a Task. The static Create() methods might suffice for simple Task wrappers. /// Concrete classes must implement the abstract method that creates the Task. If your implementation is /// naturally asynchronous but does not make use of Tasks (i.e. the Task class), inherit directly from /// AsyncCommand instead. If your command is actually synchronous in nature, in that its execution finishes /// on the same thread it started on, inherit directly from SyncCommand instead (otherwise asynchronous /// execution will block, because it is expected that TaskCommand implementations are asynchronous). /// </summary> /// <remarks> /// <para> /// <see cref="Command.SyncExecute(object)"/> and <see cref="Command.AsyncExecute(ICommandListener, object)"/> will accept /// an object for the 'runtimeArg'. This is passed on to the abstract <see cref="CreateTask" /> method. /// </para> /// <para> /// This command returns from synchronous execution the value of type TResult that the underlying Task returns. The 'result' parameter of /// <see cref="ICommandListener.CommandSucceeded"/> will be set in similar fashion. It is the caller's responsibility to dispose of this /// response object if needed. /// </para> /// </remarks> /// <typeparam name="TResult">The type returned with the Task</typeparam> /// <typeparam name="TArg">The type of argument passed to the method that generates the task</typeparam> public abstract class TaskCommand<TArg, TResult> : AsyncCommand { /// <summary> /// This class wraps a delegate as a Command. When the command is executed, the delegate is run. /// </summary> /// <param name="func"> /// The delegate that returns a Task. This will be run when the command is executed. This function /// is passed a cancellation token that can be passed to methods that return tasks. /// </param> /// <returns>The created command. It ignores the runtimeArg passed to SyncExecute() or AsyncExecute()</returns> public static TaskCommand<TArg, TResult> Create(Func<CancellationToken, Task<TResult>> func) { return Create(func, null); } /// <summary> /// This class wraps a delegate as a Command. When the command is executed, the delegate is run. /// </summary> /// <param name="func"> /// The delegate that returns a Task. This will be run when the command is executed. This function /// is passed a cancellation token that can be passed to methods that return tasks. /// </param> /// <param name="owner"> /// Specify null to indicate a top-level command. Otherwise, this command will be owned by 'owner'. /// Owned commands are disposed of when the owner is disposed. /// </param> /// <returns>The created command. It ignores the runtimeArg passed to SyncExecute() or AsyncExecute()</returns> public static TaskCommand<TArg, TResult> Create(Func<CancellationToken, Task<TResult>> func, Command owner) { return new DelegatedTaskCommand(func, owner); } /// <summary> /// Covariant implementation of <see cref="Command.SyncExecute()"/> /// </summary> /// <returns>the same value that the underlying task returns</returns> /// <remarks>See <see cref="Command.SyncExecute()"/> for further details.</remarks> public new TResult SyncExecute() { return (TResult)base.SyncExecute(); } /// <summary> /// Covariant implementation of <see cref="Command.SyncExecute(object)"/> /// </summary> /// <param name="runtimeArg">this is passed to the task instantiation method</param> /// <returns>the same value that the underlying task returns</returns> /// <remarks>See <see cref="Command.SyncExecute(object)"/> for further details.</remarks> public new TResult SyncExecute(object runtimeArg) { return (TResult)base.SyncExecute(runtimeArg); } /// <summary> /// Covariant implementation of <see cref="Command.SyncExecute(object)"/> /// </summary> /// <param name="runtimeArg">this is passed to the task instantiation method</param> /// <returns>the same value that the underlying task returns</returns> /// <remarks>See <see cref="Command.SyncExecute(object)"/> for further details.</remarks> public TResult SyncExecute(TArg runtimeArg) { return (TResult)base.SyncExecute(runtimeArg); } /// <summary> /// Covariant implementation of <see cref="Command.SyncExecute(object, Command)"/> /// </summary> /// <param name="runtimeArg">this is passed to the task instantiation method</param> /// <param name="owner"> /// If you want this command to pay attention to abort requests of a different command, set this value to that command. /// Note that if this Command is already assigned an owner, passing a non-null value will raise an exception. Also note /// that the owner assignment is only in effect during the scope of this call. Upon return, this command will revert to /// having no owner. /// </param> /// <returns>the same value that the underlying task returns</returns> /// <remarks>See <see cref="Command.SyncExecute(object, Command)"/> for further details.</remarks> public new TResult SyncExecute(object runtimeArg, Command owner) { return (TResult)base.SyncExecute(runtimeArg, owner); } /// <summary> /// Covariant implementation of <see cref="Command.SyncExecute(object, Command)"/> /// </summary> /// <param name="runtimeArg">this is passed to the task instantiation method</param> /// <param name="owner"> /// If you want this command to pay attention to abort requests of a different command, set this value to that command. /// Note that if this Command is already assigned an owner, passing a non-null value will raise an exception. Also note /// that the owner assignment is only in effect during the scope of this call. Upon return, this command will revert to /// having no owner. /// </param> /// <returns>the same value that the underlying task returns</returns> /// <remarks>See <see cref="Command.SyncExecute(object, Command)"/> for further details.</remarks> public TResult SyncExecute(TArg runtimeArg, Command owner) { return (TResult)base.SyncExecute(runtimeArg, owner); } /// <summary> /// Covariant implementation of <see cref="Command.AsyncExecute(Action{object}, Action, Action{Exception})"/> /// </summary> /// <param name="onSuccess">Callback for successful operation</param> /// <param name="onAbort">Callback for aborted operation</param> /// <param name="onFail">Callback for failed operation</param> /// <remarks>See <see cref="Command.AsyncExecute(Action{object}, Action, Action{Exception})"/> for further details</remarks> public void AsyncExecute(Action<TResult> onSuccess, Action onAbort, Action<Exception> onFail) { AsyncExecute(new DelegateCommandListener<TResult>(onSuccess, onAbort, onFail)); } /// <summary> /// Covariant implementation of <see cref="Command.AsyncExecute(ICommandListener)"/> /// </summary> /// <param name="listener">One of this member's methods will be called upon completion of the command</param> /// <remarks>See <see cref="Command.AsyncExecute(ICommandListener)"/> for further details</remarks> public void AsyncExecute(ICommandListener<TResult> listener) { base.AsyncExecute(new CovariantListener<TResult>(listener)); } /// <summary> /// Covariant implementation of <see cref="Command.AsyncExecute(Action{object}, Action, Action{Exception}, object)"/> /// </summary> /// <param name="onSuccess">Callback for successful operation</param> /// <param name="onAbort">Callback for aborted operation</param> /// <param name="onFail">Callback for failed operation</param> /// <param name="runtimeArg">This value is passed to the method that instantiates the task</param> /// <remarks>See <see cref="Command.AsyncExecute(Action{object}, Action, Action{Exception}, object)"/> for further details</remarks> public void AsyncExecute(Action<TResult> onSuccess, Action onAbort, Action<Exception> onFail, TArg runtimeArg) { AsyncExecute(new DelegateCommandListener<TResult>(onSuccess, onAbort, onFail), runtimeArg); } /// <summary> /// Covariant implementation of <see cref="Command.AsyncExecute(ICommandListener, object)"/> /// </summary> /// <param name="listener">One of this member's methods will be called upon completion of the command</param> /// <param name="runtimeArg">This value is passed to the method that instantiates the task</param> /// <remarks>See <see cref="Command.AsyncExecute(ICommandListener, object)"/> for further details</remarks> public void AsyncExecute(ICommandListener<TResult> listener, TArg runtimeArg) { base.AsyncExecute(new CovariantListener<TResult>(listener), runtimeArg); } /// <summary> /// Constructor for a top-level command /// </summary> protected TaskCommand() : this(null) { } /// <summary> /// Constructor /// </summary> /// <param name="owner"> /// Specify null to indicate a top-level command. Otherwise, this command will be owned by 'owner'. Owned commands respond to /// abort requests made of their owner. Also, owned commands are disposed of when the owner is disposed. /// </param> protected TaskCommand(Command owner) : base(owner) { } /// <summary> /// Do not call this method from a derived class. It is called by the framework. /// </summary> /// <param name="listener">Not applicable</param> /// <param name="runtimeArg">This is passed on to the underlying Task creation method.</param> protected sealed override async void AsyncExecuteImpl(ICommandListener listener, object runtimeArg) { _cancellationTokenSource = new CancellationTokenSource(); try { Task<TResult> task; try { CheckAbortFlag(); // in case someone snuck in and called Abort after execution but before we got going. task = CreateTask(runtimeArg == null ? default(TArg) : (TArg)runtimeArg, _cancellationTokenSource.Token); } catch (Exception e) { // We failed synchronously. This is most likely due to an exception occuring before // the first await. Let's be consistent about this and make the callback on the listener. // The framework guarantees that will be done on a separate thread. // // Besides, throwing exceptions from async void methods (which this method is) // does not behave as one would expect. The caller will not be able to catch it!! task = new Task<TResult>(() => throw e); } using (task) { TResult result = default(TResult); Exception error = null; try { if (task.Status == TaskStatus.Created) { task.Start(); } result = await task.ConfigureAwait(continueOnCapturedContext: false); } catch (Exception exc) { error = exc is OperationCanceledException && AbortRequested ? new CommandAbortedException() : exc; } _cancellationTokenSource.Dispose(); _cancellationTokenSource = null; switch (error) { case null: listener.CommandSucceeded(result); break; case CommandAbortedException _: listener.CommandAborted(); break; default: listener.CommandFailed(error); break; } } } finally { _cancellationTokenSource?.Dispose(); _cancellationTokenSource = null; } } /// <inheritdoc /> protected override void AbortImpl() { _cancellationTokenSource?.Cancel(); } /// <summary> /// Concrete classes must implement this by returning a Task. If the delegate method takes significant /// time, it is advisable to have it be responsive to abort requests by checking /// <see cref="Command.AbortRequested"/> or calling <see cref="Command.CheckAbortFlag"/>. If your /// implementation does not finish on a thread that is different from the one it started on, you should /// not be inheriting from TaskCommand. Rather, inherit from SyncCommand. /// </summary> /// <param name="runtimeArg"> /// Concrete implementations decide what to do with this. This value is passed on from the runtimeArg /// that was provided to the synchronous or asynchronous execution methods. /// </param> /// <param name="cancellationToken"> /// If your implementation will create tasks that require a cancellation token to be responsive /// to abort requests, pass this token along. /// </param> /// <returns> /// This value is passed along as the return value of synchronous execution routines, or the 'result' parameter /// of <see cref="ICommandListener.CommandSucceeded"/> for asynchronous execution routines. /// </returns> protected abstract Task<TResult> CreateTask(TArg runtimeArg, CancellationToken cancellationToken); private class DelegatedTaskCommand : TaskCommand<TArg, TResult> { internal DelegatedTaskCommand(Func<CancellationToken, Task<TResult>> func, Command owner) : base(owner) { _func = func; } protected sealed override Task<TResult> CreateTask(TArg _, CancellationToken cancellationToken) { return _func(cancellationToken); } private readonly Func<CancellationToken, Task<TResult>> _func; } private volatile CancellationTokenSource _cancellationTokenSource; } /// <summary> /// This Command encapsulates a Task. The static Create() method might suffice for simple Task wrappers. /// Concrete classes must implement the abstract method that creates the Task. If your implementation is /// naturally asynchronous but does not make use of Tasks (i.e. the Task class), inherit directly from /// AsyncCommand instead. /// </summary> /// <remarks> /// <para> /// <see cref="Command.SyncExecute(object)"/> and <see cref="Command.AsyncExecute(ICommandListener, object)"/> will accept /// an object for the 'runtimeArg'. This is passed on to the abstract <see cref="CreateTask" /> method. /// </para> /// <para> /// This command returns from synchronous execution the bool value true. The 'result' parameter of /// <see cref="ICommandListener.CommandSucceeded"/> will be set to true as well. /// </para> /// </remarks> /// <typeparam name="TArg">The type of argument passed to method that creates the task</typeparam> public abstract class TaskCommand<TArg> : TaskCommand<TArg, bool> { /// <summary> /// This method wraps a delegate as a Command. When the command is executed, the delegate is run. /// </summary> /// <param name="func"> /// The delegate that returns a Task. This will be run when the command is executed. This function /// is passed a cancellation token that can be passed to methods that return tasks. /// </param> /// <returns>The created command. It ignores the runtimeArg passed to SyncExecute() or AsyncExecute()</returns> public static TaskCommand<TArg> Create(Func<CancellationToken, Task> func) { return Create(func, null); } /// <summary> /// This method wraps a delegate as a Command. When the command is executed, the delegate is run. /// </summary> /// <param name="func"> /// The delegate that returns a Task. This will be run when the command is executed. This function /// is passed a cancellation token that can be passed to methods that return tasks. /// </param> /// <param name="owner"> /// Specify null to indicate a top-level command. Otherwise, this command will be owned by 'owner'. /// Owned commands are disposed of when the owner is disposed. /// </param> /// <returns>The created command. It ignores the runtimeArg passed to SyncExecute() or AsyncExecute()</returns> public static TaskCommand<TArg> Create(Func<CancellationToken, Task> func, Command owner) { return new DelegatedTaskCommand(func, owner); } /// <summary> /// Constructor /// </summary> /// <param name="owner"> /// Specify null to indicate a top-level command. Otherwise, this command will be owned by 'owner'. Owned commands respond to /// abort requests made of their owner. Also, owned commands are disposed of when the owner is disposed. /// </param> protected TaskCommand(Command owner) : base(owner) { } /// <summary> /// Concrete classes must implement this by returning a Task. If the delegate method takes significant /// time, it is advisable to have it be responsive to abort requests by checking /// <see cref="Command.AbortRequested"/> or calling <see cref="Command.CheckAbortFlag"/>. If your /// implementation does not finish on a thread that is different from the one it started on, you should /// not be inheriting from TaskCommand. Rather, inherit from SyncCommand. /// </summary> /// <param name="runtimeArg"> /// Concrete implementations decide what to do with this. This value is passed on from the runtimeArg /// that was provided to the synchronous or asynchronous execution methods. /// </param> /// <param name="cancellationToken"> /// If your implementation will create tasks that require a cancellation token to be responsive /// to abort requests, pass this token along. /// </param> /// <returns> /// This value is passed along as the return value of synchronous execution routines, or the 'result' parameter /// of <see cref="ICommandListener.CommandSucceeded"/> for asynchronous execution routines. /// </returns> protected abstract Task CreateTaskNoResult(TArg runtimeArg, CancellationToken cancellationToken); /// <inheritdoc /> protected sealed override async Task<bool> CreateTask(TArg runtimeArg, CancellationToken cancellationToken) { using (Task task = CreateTaskNoResult(runtimeArg, cancellationToken)) { if (task.Status == TaskStatus.Created) { task.Start(); } await task.ConfigureAwait(continueOnCapturedContext: false); return true; } } private class DelegatedTaskCommand : TaskCommand<TArg> { internal DelegatedTaskCommand(Func<CancellationToken, Task> func, Command owner) : base(owner) { _func = func; } protected sealed override Task CreateTaskNoResult(TArg _, CancellationToken cancelToken) { return _func(cancelToken); } private readonly Func<CancellationToken, Task> _func; } } }
Python
UTF-8
5,467
2.71875
3
[ "Apache-2.0" ]
permissive
import json import os import re from asyncio import tasks from contextlib import contextmanager from datetime import datetime from threading import Thread import jscaller from requests.cookies import RequestsCookieJar, create_cookie from config import get_config, SECTION_WORKER NoneType = type(None) def current_time(): """ 返回 '时:分:秒' 格式的当前时间文本。""" return datetime.now().strftime('%H:%M:%S.%f') def split_name_version(script_name): """ 返回分割的脚本名称,版本。""" name_version = script_name.rsplit('-', 1) if len(name_version) == 1: name, version = name_version[0], None else: name, version = name_version try: version = float(version) except ValueError: # 若无法转为浮点,那么将判定为其后的-是非版本号 name = script_name version = None return name, version def run_forever(function, *args, name=None, **kwargs): """ 进程周期内的运行线程。""" Thread(target=function, args=args, kwargs=kwargs, name=name, daemon=True).start() def cancel_all_tasks(loop): """ 关闭循环中剩余的所有任务。 asyncio.runners._cancel_all_tasks""" to_cancel = tasks.all_tasks(loop) if not to_cancel: return for task in to_cancel: task.cancel() loop.run_until_complete( tasks.gather(*to_cancel, loop=loop, return_exceptions=True)) for task in to_cancel: if task.cancelled(): continue if task.exception() is not None: loop.call_exception_handler({ 'message': 'unhandled exception during asyncio.run() shutdown', 'exception': task.exception(), 'request_task': task, }) def extract_cookies_str_to_jar(cookies_str, cookiejar=None, overwrite=True, cookies_specified_kw=None): """ cookies字符串提取成CookieJar。 :param cookies_str: cookie字符串文本 cookiejar: (可选)指定cookie添加到的cookiejar对象 overwrite: (可选)指定是否覆盖已经存在的cookie键 cookie_kwargs: (可选)指定Cookie的参数,参见 cookielib.Cookie 对象 - domain: 指定所在域 - path: 指定所在路径 """ # 分割cookies文本并提取到字典对象。 cookie_dict = {} for cookie in cookies_str.split(';'): try: key, value = cookie.split('=', 1) except ValueError: continue else: cookie_dict[key] = value if not cookies_specified_kw: cookies_specified_kw = {} return cookiejar_from_dict(cookie_dict, cookiejar, overwrite, cookies_specified_kw) def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True, cookies_specified_kw=None): """ 以下代码引用自requests库 具体参数说明参考:requests.cookies.cookiejar_from_dict。 """ if not cookies_specified_kw: cookies_specified_kw = {} if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): # 添加参数 cookies_specified_kw cookiejar.set_cookie(create_cookie(name, cookie_dict[name], **cookies_specified_kw)) return cookiejar def json_stringify(source, replace=None, keys=(float('nan'), float('inf'), float('-inf')), indent=None): """ 处理非标准JSON的格式化问题。由于python内置的json会对nan, inf, -inf进行处理,这会造成非标准的JSON。""" def check_dict(o): return {go_check(k): go_check(v) for k, v in o.items()} def check_list_tuple_set(o): return [go_check(v) for v in o] def go_check(o): if isinstance(o, (list, tuple, set)): return check_list_tuple_set(o) elif isinstance(o, dict): return check_dict(o) elif type(o) in (int, float, str, bytes, NoneType): if o in keys: o = replace return o else: raise ValueError(o) try: result = json.dumps(source, allow_nan=False, indent=indent) except ValueError: result = json.dumps(go_check(source), allow_nan=False, indent=indent) return result utility_package = { 'extract_cookies_str_to_jar': extract_cookies_str_to_jar, 'current_time': current_time, } @contextmanager def js_session(source, timeout=None, engine=None): from requester.request import jsruntime worker = get_config(SECTION_WORKER, 'jsruntime') timeout = timeout or worker.get('timeout') if not engine: engine = jscaller.engine.JSEngine( name=worker['name'], source=worker['source'], shell=worker['shell'], version=worker['version'], encoding='utf-8', ) if os.path.isfile(source): session = jscaller.session else: session = jscaller.Session with session(source, timeout, engine) as sess: yield sess req = jsruntime(sess) task = req.start_request() result = task.result() return result REG_VALID_PATHNAME = re.compile(r'[\\/:*?"<>|\r\n]+')
Markdown
UTF-8
6,496
3.015625
3
[ "Apache-2.0" ]
permissive
# Release process ## Explanation of the process sequence The assumption that the current state of *master* will constitute the release... #### 1. Pre-release checks Make the following checks before performing a release: * Do all unit tests pass? * Do all examples work? * Does documentation build? * Have the new features been applied on a separate branch with compatibility with `jdk8`? #### 2. Update VERSION and CHANGELOG #### Increment the version number. The application is released with the compatibility for both: `jdk11` and `jdk8`, the latest version number are: in the [CHANGELOG.md](CHANGELOG.md) file for `jdk11` and [CHANGELOG-JDK8.md](CHANGELOG-JDK8.md) file for `jdk8`. The version number structure is: *major* **.** *minor* **.** *revision*. * *major* = significant incompatible change (e.g. partial or whole rewrite). * *minor* = some new functionality or changes that are mostly/wholly backward compatible. * *revision* = very minor changes, e.g. bugfixes. For `jdk8` only, the version number is the same as the `jdk11` one, with the suffix: `-jdk8`. e.g. if the new release version would be `X.Y.Z` then the `jdk8` correspondent one is: `X.Y.Z-jdk8` #### Update the change log The changes, that are going to be released, need to be specified in the `CHANGELOG` file. Ensure it mentions any noteworthy changes since the previous release. Make the following check before performing a release: * Add the version is going to be released * Place the release date next to the version number (the format is: `yyyy.mm.dd`) * Specify under the `### Added` label everything that has been introduced by the new version * Specify under the `### Changed` label everything that has been changed in the new version * Specify under the `### Removed` label everything that has been removed in the new version the same changes must be reported in [CHANGELOG-JDK8.md](CHANGELOG-JDK8.md) #### 3. Prepare the jdk8 release All the changes implemented need to be reported to a `jdk8` compatible version. The BULL code for the `jdk8` is slightly different so all the changes need to be reported on the other version starting from it's latest release tag. The first thing to do is to create a branch (that would have the same name as the `jdk11` one plus the suffix: `-jdk8`) starting from the latest `jdk8` release tag: ```shell script $ git checkout -b [branch name]-jdk8 [latest jdk8 release tag] ``` e.g. if the latest `jdk8` release tag is: `1.7.0-jdk8` and the new feature branch is: `feature/my-new-feature` the command to perform is: ```shell script $ git checkout -b feature/my-new-feature-jdk8 1.7.0-jdk8 ``` **IMPORTANT:** In the new branch, apply only the changes introduced comparing the code with the `jdk11` branch. When completed, commit your code and verify that the [Travis build](https://travis-ci.org/ExpediaGroup/bull/builds) is green. ## Example of a release process sequence The following examples assume that your local repository is: * a clone and the working copy is currently at the head of the master branch * is all synced with GitHub * the Pull Request has been approved and merged on master The guide explains how to do a release both the `jdk11` and `jdk8` compatible: * [JDK8 Release](https://github.com/ExpediaGroup/bull/blob/master/RELEASE.md#jdk8-release) * [JDK11 Release](https://github.com/ExpediaGroup/bull/blob/master/RELEASE.md#jdk11-release) **IMPORTANT:** In case something goes wrong, do not leave ghost tags or tags not related to a successful release. ### JDK8 Release The following steps will do a release "`X.Y.Z-jdk8`" ```shell script $ git status On branch master Your branch is up-to-date with 'origin/master'. nothing to commit, working directory clean ``` #### 1. Create a branch from the latest JDK8 release tag Assuming that: * The latest release for `jdk8` was: `A.B.C-jdk8` * your new feature branch is: `feature/my-new-feature` * The new release version is: `X.Y.Z-jdk8` the release branch would be: `release/my-new-feature-jdk8` ```shell script $ git checkout -b release/my-new-feature-jdk8 A.B.C-jdk8 $ git push --set-upstream origin release/my-new-feature-jdk8 ``` #### 2. Apply the changes to the new branch Apply all the changes you implemented to this branch. #### 3. Change the maven version The maven version is now set with the latest released, but you need to change it with the new one you are going to release: ```shell script $ mvn versions:set -D newVersion=X.Y.Z-jdk8 ``` Commit all the changes and verify that the [Travis build](https://travis-ci.org/ExpediaGroup/bull/builds) is green. #### 4. Create a new tag for the release version Once you will have created the tag, and pushed it to the remote repo, an automatic release will be performed by Travis. ```shell script $ git tag -a X.Y.Z-jdk8 -m "my version X.Y.Z-jdk8" $ git push origin --tags ``` #### 5. Remove the no longer needed branch If the release went successfully, you can now delete the branch: ```shell script $ git branch -D release/my-new-feature-jdk8 $ git push <remote_name> --delete release/my-new-feature-jdk8 ``` ### JDK11 Release The following steps will do a release "`X.Y.Z`" ```shell script $ git status On branch master Your branch is up-to-date with 'origin/master'. nothing to commit, working directory clean ``` #### 1. Create a branch from the master branch Assuming that: * The latest release for `jdk11` was: `A.B.C` * your new feature branch is: `feature/my-new-feature` * The new release version is: `X.Y.Z` the release branch would be: `release/my-new-feature` ```shell script $ git checkout -b release/my-new-feature ``` #### 2. Change the maven version The maven version is now set with the latest released, but you need to change it with the new one you are going to release: ```shell script $ mvn versions:set -D newVersion=X.Y.Z ``` Commit all the changes and verify that the [Travis build](https://travis-ci.org/ExpediaGroup/bull/builds) is green. #### 3. Create a new tag for the release version Once you will have created the tag, and pushed it to the remote repo, an automatic release will be performed by Travis. ```shell script $ git tag -a X.Y.Z -m "my version X.Y.Z" $ git push origin --tags ``` #### 4. Remove the no longer needed branch If the release went successfully, you can now delete the branch: ```shell script $ git branch -D release/my-new-feature $ git push <remote_name> --delete release/my-new-feature-jdk8 ```
Java
UTF-8
236
2.4375
2
[ "MIT" ]
permissive
package ninja.egg82.primitive.doubles; import it.unimi.dsi.fastutil.Stack; public interface DoubleStack extends Stack<Double> { //functions void push(double k); double popDouble(); double topDouble(); double peekDouble(int i); }
TypeScript
UTF-8
1,201
2.671875
3
[]
no_license
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators, AbstractControl} from '@angular/forms'; import { Persona } from '../models/persona'; import { PersonaService } from 'src/app/services/persona.service'; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { persona: Persona;  formGroup: FormGroup; constructor(private personaService: PersonaService, private formBuilder: FormBuilder) { } ngOnInit() {     this.buildForm(); } private buildForm() {     this.formGroup = this.formBuilder.group({ identificacion: ['', Validators.required], nombre: ['', Validators.required], sexo: ['', [Validators.required, this.ValidaSexo]],     });   } private ValidaSexo(control: AbstractControl) {  const sexo = control.value;  if (sexo.toLocaleUpperCase() !== 'M' && sexo.toLocaleUpperCase() !== 'F') {   return { validSexo: true, messageSexo: 'Sexo No Valido' };  }   return null; } }
Markdown
UTF-8
1,127
3.515625
4
[]
no_license
[217. 存在重复元素](https://leetcode-cn.com/problems/contains-duplicate/) 给定一个整数数组,判断是否存在重复元素。 如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。 示例 1: 输入: [1,2,3,1] 输出: true 示例 2: 输入: [1,2,3,4] 输出: false 示例 3: 输入: [1,1,1,3,3,4,3,2,4,2] 输出: true 通过次数234,282提交次数425,210 217. Contains Duplicate Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/contains-duplicate 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ```java class Solution { public boolean containsDuplicate(int[] nums) { } } ```
Python
UTF-8
1,301
2.65625
3
[]
no_license
#!/bin/python import requests, smtplib from pathlib import Path import json import hashlib from bs4 import BeautifulSoup import os dirname = os.path.dirname(__file__) CONFIG_FILE = os.path.join(dirname, 'config.json') def send_mail(body): email_address = 'xxxxx@gmail.com' s = smtplib.SMTP(host='smtp.gmail.com', port=587) s.starttls() s.login(email_address, 'xxxxxxx') from email.mime.text import MIMEText msg = MIMEText(body) msg['From'] = email_address msg['To'] = email_address msg['CC'] = "yyyyy@gmail.com" msg['Subject'] = "WEBSITE CHANGE ALERT" s.send_message(msg) s.quit() del msg def alert_changed(site_to_alert): print('changed..' + site_to_alert['url']) send_mail(site_to_alert['url']) def run_main(): config_json = Path(CONFIG_FILE).read_text() config = json.loads(config_json) for idx, site in enumerate(config): page = requests.get(site['url']) soup = BeautifulSoup(page.content, 'html.parser') hashed = hashlib.md5(soup.text.encode('utf8')).hexdigest() if hashed != site['hash']: alert_changed(site) config[idx]['hash'] = hashed with open(CONFIG_FILE, 'w') as fp: json.dump(config, fp, sort_keys=True, indent=4) if __name__ == '__main__': run_main()
Markdown
UTF-8
12,027
3.15625
3
[]
no_license
# myisamchk 是用来做什么的? 它用来压缩 MyISAM 表,这减少了磁盘或内存使用。 MyISAM Static 和 MyISAM Dynamic 有什么区别? 在 MyISAM Static 上的所有字段有固定宽度。动态 MyISAM 表将具有像 TEXT, BLOB 等字段,以适应不同长度的数据类型。 MyISAM Static 在受损情况下更容易恢复。 # 如果一个表有一列定义为 TIMESTAMP,将发生什么? 每当行被更改时,时间戳字段将获取当前时间戳。 **列设置为 AUTO INCREMENT 时,如果在表中达到最大值,会发生什么情况?** 它会停止递增,任何进一步的插入都将产生错误,因为密钥已被使用。 **怎样才能找出最后一次插入时分配了哪个自动增量?** LAST_INSERT_ID 将返回由 Auto_increment 分配的最后一个值,并且不需要指 定表名称。 # 你怎么看到为表格定义的所有索引? 索引是通过以下方式为表格定义的: ```sql SHOW INDEX FROM <tablename>; ``` # LIKE 声明中的%和 _ 是什么意思?_ %对应于 0 个或更多字符,_只是 LIKE 语句中的一个字符。 **如何在 Unix 和 MySQL 时间戳之间进行转换?** UNIX_TIMESTAMP 是从 MySQL 时间戳转换为 Unix 时间戳的命令 FROM_UNIXTIME 是从 Unix 时间戳转换为 MySQL 时间戳的命令 # 列对比运算符是什么? 在 SELECT 语句的列比较中使用=,<>,<=,<,> =,>,<<,>>,<=>,AND, OR 或 LIKE 运算符。 # BLOB 和 TEXT 有什么区别? BLOB 是一个二进制对象,可以容纳可变数量的数据。TEXT 是一个不区分大小写 的 BLOB。 BLOB 和 TEXT 类型之间的唯一区别在于对 BLOB 值进行排序和比较时区分大小 写,对 TEXT 值不区分大小写。 # MySQL_fetch_array 和 MySQL_fetch_object 的区别是 什么? 以下是 MySQL_fetch_array 和 MySQL_fetch_object 的区别: MySQL_fetch_array() – 将结果行作为关联数组或来自数据库的常规数组返回。 MySQL_fetch_object – 从数据库返回结果行作为对象。 # MyISAM 表格将在哪里存储,并且还提供其存储格式? 每个 MyISAM 表格以三种格式存储在磁盘上: - ·“.frm”文件存储表定义 - 数据文件具有“.MYD”(MYData)扩展名 - 索引文件具有“.MYI”(MYIndex)扩展名 # MySQL 如何优化 DISTINCT? DISTINCT 在所有列上转换为 GROUP BY,并与 ORDER BY 子句结合使用。 SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a; # 可以使用多少列创建索引? 任何标准表最多可以创建 16 个索引列。 ## NOW()和 CURRENT_DATE()有什么区别? NOW()命令用于显示当前年份,月份,日期,小时,分钟和秒。 CURRENT_DATE()仅显示当前年份,月份和日期。 # 什么是非标准字符串类型? 1、TINYTEXT 2、TEXT 3、MEDIUMTEXT 4、LONGTEXT # 什么是通用 SQL 函数? 1、CONCAT(A, B) – 连接两个字符串值以创建单个字符串输出。通常用于将两个 或多个字段合并为一个字段。 2、FORMAT(X, D)- 格式化数字 X 到 D 有效数字。 3、CURRDATE(), CURRTIME()- 返回当前日期或时间。 4、NOW() – 将当前日期和时间作为一个值返回。 5、MONTH(),DAY(),YEAR(),WEEK(),WEEKDAY() – 从日期 值中提取给定数据。 6、HOUR(),MINUTE(),SECOND() – 从时间值中提取给定数据。 7、DATEDIFF(A,B) – 确定两个日期之间的差异,通常用于计算年龄 8、SUBTIMES(A,B) – 确定两次之间的差异。 9、FROMDAYS(INT) – 将整数天数转换为日期值。 # MySQL 里记录货币用什么字段类型好 NUMERIC 和 DECIMAL 类型被 MySQL 实现为同样的类型,这在 SQL92 标准允 许。他们被用于保存值,该值的准确精度是极其重要的值,例如与金钱有关的数 据。当声明一个类是这些类型之一时,精度和规模的能被(并且通常是)指定。 例如: salary DECIMAL(9,2) 在这个例子中,9(precision)代表将被用于存储值的总的小数位数,而 2(scale)代 表将被用于存储小数点后的位数。 因此,在这种情况下,能被存储在 salary 列中的值的范围是从-9999999.99 到 9999999.99。 # MySQL 有关权限的表都有哪几个? MySQL 服务器通过权限表来控制用户对数据库的访问,权限表存放在 MySQL 数 据库里,由 MySQL_install_db 脚本初始化。这些权限表分别 user,db,table_priv, columns_priv 和 host。 # 列的字符串类型可以是什么? 字符串类型是: 1、SET2、BLOB 3、ENUM 4、CHAR 5、TEXT # MySQL 数据库作发布系统的存储,一天五万条以上的增量, 预计运维三年,怎么优化? 1、设计良好的数据库结构,允许部分数据冗余,尽量避免 join 查询,提高效率。 2、选择合适的表字段数据类型和存储引擎,适当的添加索引。 3、MySQL 库主从读写分离。 4、找规律分表,减少单表中的数据量提高查询速度。 5、添加缓存机制,比如 memcached,apc 等。 6、不经常改动的页面,生成静态页面。 7、书写高效率的 SQL。比如 SELECT * FROM TABEL 改为 SELECT field_1, field_2, field_3 FROM TABLE. # 锁的优化策略 1、读写分离 2、分段加锁 3、减少锁持有的时间 4.多个线程尽量以相同的顺序去获取资源 不能将锁的粒度过于细化,不然可能会出现线程的加锁和释放次数过多,反而效 率不如一次加一把大锁。 # 索引的底层实现原理和优化 B+树,经过优化的 B+树 主要是在所有的叶子结点中增加了指向下一个叶子节点的指针,因此 InnoDB 建 议为大部分表使用默认自增的主键作为主索引。 # 什么情况下设置了索引但无法使用 1、以“%”开头的 LIKE 语句,模糊匹配 2、OR 语句前后没有同时使用索引 3、数据类型出现隐式转化(如 varchar 不加单引号的话可能会自动转换为 int 型) # SQL优化 [阿里P8架构师谈:MySQL慢查询优化、索引优化、以及表等优化总结 | 优知学院 (youzhixueyuan.com)](https://youzhixueyuan.com/MySQL-slow-query-optimization-index-optimization.html) # 简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面) 索引是一种特殊的文件(InnoDB 数据表上的索引是表空间的一个组成部分),它们 包含着对数据表里所有记录的引用指针。 普通索引(由关键字 KEY 或 INDEX 定义的索引)的唯一任务是加快对数据的访问速 度。 普通索引允许被索引的数据列包含重复的值。如果能确定某个数据列将只包含彼 此各不相同的值,在为这个数据列创建索引的时候就应该用关键字 UNIQUE 把它 定义为一个唯一索引。也就是说,唯一索引可以保证数据记录的唯一性。 主键,是一种特殊的唯一索引,在一张表中只能定义一个主键索引,主键用于唯 一标识一条记录,使用关键字 PRIMARY KEY 来创建。 索引可以覆盖多个数据列,如像 INDEX(columnA, columnB)索引,这就是联合索 引。 索引可以极大的提高数据的查询速度,但是会降低插入、删除、更新表的速度, 因为在执行这些写操作时,还要操作索引文件。 # SQL 注入漏洞产生的原因?如何防止? SQL 注入产生的原因:程序开发过程中不注意规范书写 sql 语句和对特殊字符进 行过滤,导致客户端可以通过全局变量 POST 和 GET 提交一些 sql 语句正常执行。 防止 SQL 注入的方式: 开启配置文件中的 magic_quotes_gpc 和 magic_quotes_runtime 设置 执行 sql 语句时使用 addslashes 进行 sql 语句转换 Sql 语句书写尽量不要省略双引号和单引号。 过滤掉 sql 语句中的一些关键词:update、insert、delete、select、 * 。 提高数据库表和字段的命名技巧,对一些重要的字段根据程序的特点命名,取不 易被猜到的。 # 为表中得字段选择合适得数据类型 字段类型优先级: 整形>date,time>enum,char>varchar>blob,text 优先考虑数字类型,其次是日期或者二进制类型,最后是字符串类型,同级别得 数据类型,应该优先选择占用空间小的数据类型 # 存储时期 Datatime:以 YYYY-MM-DD HH:MM:SS 格式存储时期时间,精确到秒, 占用 8 个字节得存储空间,datatime 类型与时区无关 Timestamp:以时间戳格式存储,占用 4 个字节,范围小 1970-1-1 到 2038-1-19, 显示依赖于所指定得时区,默认在第一个列行的数据修改时可以自动得修改 timestamp 列得值 Date:(生日)占用得字节数比使用字符串.datatime.int 储存要少,使用 date 只 需要 3 个字节,存储日期月份,还可以利用日期时间函数进行日期间得计算 Time:存储时间部分得数据 注意:不要使用字符串类型来存储日期时间数据(通常比字符串占用得储存空间小, 在进行查找过滤可以利用日期得函数) 使用 int 存储日期时间不如使用 timestamp 类型 # 解释 MySQL 外连接、内连接与自连接的区别 先说什么是交叉连接: 交叉连接又叫笛卡尔积,它是指不使用任何条件,直接将一 个表的所有记录和另一个表中的所有记录一一匹配。 内连接 则是只有条件的交叉连接,根据某个条件筛选出符合条件的记录,不符合 条件的记录不会出现在结果集中,即内连接只连接匹配的行。 外连接 其结果集中不仅包含符合连接条件的行,而且还会包括左表、右表或两个 表中 的所有数据行,这三种情况依次称之为左外连接,右外连接,和全外连接。 左外连接,也称左连接,左表为主表,左表中的所有记录都会出现在结果集中, 对于那些在右表中并没有匹配的记录,仍然要显示,右边对应的那些字段值以 NULL 来填充。右外连接,也称右连接,右表为主表,右表中的所有记录都会出现 在结果集中。左连接和右连接可以互换,MySQL 目前还不支持全外连接。 # 完整性约束包括哪些? 数据完整性(Data Integrity)是指数据的精确(Accuracy)和可靠性(Reliability)。 分为以下四类: 1、实体完整性:规定表的每一行在表中是惟一的实体。 2、域完整性:是指表中的列必须满足某种特定的数据类型约束,其中约束又包括 取值范围、精度等规定。 3、参照完整性:是指两个表的主关键字和外关键字的数据应一致,保证了表之间 的数据的一致性,防止了数据丢失或无意义的数据在数据库中扩散。 4、用户定义的完整性:不同的关系数据库系统根据其应用环境的不同,往往还需 要一些特殊的约束条件。用户定义的完整性即是针对某个特定关系数据库的约束 条件,它反映某一具体应用必须满足的语义要求。 与表有关的约束:包括列约束(NOT NULL(非空约束))和表约束(PRIMARY KEY、 foreign key、check、UNIQUE) 。 # NULL 是什么意思 答:NULL 这个值表示 UNKNOWN(未知):它不表示“”(空字符串)。对 NULL 这 个值的任何比较都会生产一个 NULL 值。您不能把任何值与一个 NULL 值进行比 较,并在逻辑上希望获得一个答案。 使用 IS NULL 来进行 NULL 判断 # 你可以用什么来确保表格里的字段只接受特定范围里的值? 答:Check 限制,它在数据库表格里被定义,用来限制输入该列的值。 触发器也可以被用来限制数据库表格里的字段能够接受的值,但是这种办法要求 触发器在表格里被定义,这可能会在某些情况下影响到性能。
Java
UTF-8
576
2.765625
3
[]
no_license
import org.junit.Before; import org.junit.Test; import static junit.framework.TestCase.assertEquals; public class TestInheritence { private Dog aDog; @Before public void before() { aDog = new Dog("Woof", 4); } @Test public void testDogHasHasNoise() { assertEquals("I make Woof as my noise", aDog.getNoise()); } @Test public void testDogHasLegs() { assertEquals(4, aDog.getNumberOfLegsLeft()); } @Test public void testNumberOfDogLimbs() { assertEquals(6, aDog.getNumberOfLimbs()); } }
Markdown
UTF-8
3,332
3.8125
4
[ "MIT" ]
permissive
--- layout: default title: Operators nav_order: 6 --- # Operators {: .no_toc } ## Table of contents {: .no_toc .text-delta } 1. TOC {:toc} --- ## Operators | Operator | Description | Example | |:-------------|:---------------------------------------------------------------|:---------------------------| | and | Returns true if both operands are truthy values otherwise false | true and true | | or | Returns the first truthy operand unless all are false and the last operand is returned | true or false | | not | Returns the inverse boolean value for a given operand | not true | | + | Adds the values on either side of the operator together | 10 + 10 | | - | Subtracts the values on either side of the operator together | 10 - 10 | | * | Multiplies the values on either side of the operator together | 10 * 2 | | / | Divides the values on either side of the operator together. | 10 / 3 | | % | Modulo of values on either side of the operator | 10 % 2 | | ** | Exponent (power) of the values | 2 ** 2 | | & | Bitwise AND of the values | 10 & 2 | | ^ | Bitwise XOR of the values | 10 ^ 2 | | \| | Bitwise OR of the values | 10 \| 2 | | += | Same as +, however its shorthand to assign too | x += 10 Same as x = x + 10 | | -= | Same as -, however its shorthand to assign too | x -= 10 Same as x = x - 10 | | *= | Same as *, however its shorthand to assign too | x *= 10 Same as x = x * 10 | | /= | Same as /, however its shorthand to assign too | x /= 10 Same as x = x / 10 | | &= | Same as &, however its shorthand to assign too | x &= 10 Same as x = x & 10 | | ^= | Same as ^, however its shorthand to assign too | x ^= 10 Same as x = x ^ 10 | | \|= | Same as \|, however its shorthand to assign too | x \|= 10 Same as x = x | | ? | Ternary operator - See below | true ? 'value' : 'other' | | ?. | Optional chaining - See [classes](/docs/classes/#optional-chaining) | object?.someMethod() | ### Ternary Operator The ternary operator is an operator which takes 3 operands and returns either the second or third depending on whether the first operand is truthy. ```cs var value = true ? 'true!' : 'false!'; print(value); // 'true!' var otherValue = 0 ? 'true!' : 'false!'; print(otherValue); // 'false!' ``` ## Precedence Precedence table from highest to lowest, with all operators having a left-to-right associativity. | Operators | | . () [] | | ?. | | ! - | | \*\* | | * / | | \+ \- | | & | | ^ | | \| | | < > <= >= | | == != | | and | | or | | \= |
PHP
UTF-8
5,839
2.78125
3
[ "MIT" ]
permissive
<?php namespace SignatureTech\ResponseBuilder; use Illuminate\Http\Response; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; class ResponseBuilder { /** @var bool */ private bool $status; /** @var string|null */ private string|null $message = null; /** @var int */ private int $httpCode; /** @var mixed */ private mixed $data = null; /** @var mixed */ private mixed $meta = null; /** @var mixed */ private mixed $link = null; /** @var array */ private array $httpHeaders = []; /** @var array */ private array $response = []; /** @var array */ private array $appends = []; /** * @param bool $status */ public function __construct(bool $status = true, $httpCode = Response::HTTP_OK) { $this->status = $status; $this->httpCode = $httpCode; } /** * @param int|null $httpCode * @return static */ public static function asSuccess(?int $httpCode = null): self { return new static(true, $httpCode ?? Response::HTTP_OK); } /** * @param int|null $httpCode * @return static */ public static function asError(?int $httpCode = null): self { return new static(false, $httpCode ?? Response::HTTP_INTERNAL_SERVER_ERROR); } /** * @param string|null $message * @return $this */ public function withMessage(string $message = null): self { $this->message = $message; return $this; } /** * @param array|null $headers * @return $this */ public function withHttpHeaders(?array $headers): self { $this->httpHeaders = $headers; return $this; } /** * @param string $key * @param mixed $value * @return $this */ public function with(string $key, mixed $value): self { $this->appends[$key] = $value; return $this; } /** * @param $data * @param $resourceNamespace * @return $this */ public function withData($data = null, $resourceNamespace = null): self { if ($data instanceof LengthAwarePaginator) { $this->withPagination($data, $resourceNamespace); } else { $this->data = $data; } return $this; } /** * @param LengthAwarePaginator $query * @return $this */ public function withPagination(LengthAwarePaginator $resource, $resourceNamespace = null): self { $this->meta = [ 'total_page' => $resource->lastPage(), 'current_page' => $resource->currentPage(), 'total_item' => $resource->total(), 'per_page' => (int)$resource->perPage(), ]; $this->link = [ 'next' => $resource->hasMorePages(), 'prev' => boolval($resource->previousPageUrl()) ]; if (!empty($resourceNamespace)) { $this->data = $resource instanceof LengthAwarePaginator || $resource instanceof Collection ? $resourceNamespace::collection($resource) : $resourceNamespace::make($resource); } else { $this->data = $resource->items(); } return $this; } /** * @param bool $condition * @param callable $callback * @return $this */ public function when(bool $condition, callable $callback): self { if ($condition) { return $callback($this); } return $this; } /** * @param mixed $data * @param string|null $message * @param int|null $httpCode * @param array $appends * @return Response */ public static function success(mixed $data, string $message = null, int $httpCode = null, array $appends = []): Response { return self::asSuccess($httpCode) ->when(!empty($data), function (ResponseBuilder $builder) use ($data) { return $builder->withData($data); }) ->when(!empty($message), function (ResponseBuilder $builder) use ($message) { return $builder->withMessage($message); }) ->when(!empty($appends), function (ResponseBuilder $builder) use ($appends) { foreach ($appends as $key => $value) { $builder->with($key, $value); } return $builder; })->build(); } /** * @param $message * @param $httpCode * @param $appends * @return Response */ public static function error($message, $httpCode = null, $appends = []): Response { return self::asError($httpCode) ->when(!empty($message), function (ResponseBuilder $builder) use ($message) { return $builder->withMessage($message); }) ->when(!empty($appends), function (ResponseBuilder $builder) use ($appends) { foreach ($appends as $key => $value) { $builder->with($key, $value); } return $builder; }) ->build(); } /** * @return Response */ public function build(): Response { $this->response['status'] = $this->status; !is_null($this->message) && $this->response['message'] = $this->message; foreach ($this->appends as $key => $value) { $this->response[$key] = $value; } !is_null($this->data) && $this->response['data'] = $this->data; !is_null($this->meta) && $this->response['meta'] = $this->meta; !is_null($this->link) && $this->response['link'] = $this->link; return response($this->response, $this->httpCode, $this->httpHeaders); } }
PHP
UTF-8
3,001
2.59375
3
[ "MIT" ]
permissive
<?php // Make sure SimplePie is included. You may need to change this to match the location of autoloader.php // For 1.0-1.2: #require_once('../simplepie.inc'); // For 1.3+: require_once('../autoloader.php'); $url = 'http://bbc.co.uk'; $url = 'http://dailymail.co.uk'; // We'll process this feed with all of the default options. $feed = new SimplePie(); // Set the feed to process. $feed->set_feed_url($url); // Run SimplePie. $feed->init(); // This makes sure that the content is sent to the browser as text/html and the UTF-8 character set (since we didn't change it). $feed->handle_content_type(); // Let's begin our XHTML webpage code. The DOCTYPE is supposed to be the very first thing, so we'll keep it on the same line as the closing-PHP tag. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <html xmlns=" <head> <title>Sample SimplePie Page</title> <style type="text/css"> body { font:12px/1.4em Verdana, sans-serif; color:#333; background-color:#fff; width:700px; margin:50px auto; padding:0; } a { color:#326EA1; text-decoration:underline; padding:0 1px; } a:hover { background-color:#333; color:#fff; text-decoration:none; } div.header { border-bottom:1px solid #999; } div.item { padding:5px 0; border-bottom:1px solid #999; } </style> </head> <body> <div class="header"> <h1><a href="<?php echo $feed->get_permalink(); ?>"><?php echo $feed->get_title(); ?></a></h1> <p><?php echo $feed->get_description(); ?></p> </div> <?php /* Here, we'll loop through all of the items in the feed, and $item represents the current item in the loop. */ foreach ($feed->get_items() as $item): ?> <div class="item"> <h2><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h2> <p><?php echo $item->get_description(); ?></p> <p><small>Posted on <?php echo $item->get_date('j F Y | g:i a'); ?></small></p> </div> <?php endforeach; ?> </body> </html> <?php if ($feed->error): ?> <p><?php echo $feed->error; ?></p> <?php endif; ?> <?php foreach ($feed->get_items() as $item): ?> <?php if ($enclosure = $item->get_enclosure()) { // Display the thumbnail as an image and link it back to the YouTube page, and adding the video's title as a tooltip for the link. echo '<a href="' . $item->get_permalink() . '" title="' . $item->get_title() . '"><img class="u-full-width-alt" src="' . $enclosure->get_thumbnail() . '" /></a>'; } ?> <div class="chunk"> <h6 style="background:url(<?php $feed = $item->get_feed(); ?>)"><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4> <p class="footnote">Source: <a href="<?php $feed = $item->get_feed(); echo $feed->get_permalink(); ?>"> <?php $feed = $item->get_feed(); echo $feed->get_title(); ?></a> |<?php echo $item->get_description(); ?> <?php echo $item->get_date('j M Y | g:i a T'); ?></p> </div> <?php endforeach; ?>
Python
UTF-8
1,714
2.921875
3
[ "MIT" ]
permissive
#!/usr/bin/env python import sys import click from koolsla import ( __version__, recommender, data ) help_message = ''' Food recommendation tool with Machine learning. Usage $ python koolsla.py [<options> ...] Options --help, -h Display help message --dish, -d <int> Input dish ID [Can be any integer 0-424508] --list, -l List available dish titles --recommend, -r <int> Number of recommendations [Can be any integer 1-30] --version, -v Display installed version Examples $ python koolsla.py --help $ python koolsla.py --dish 25 $ python koolsla.py -d 25 --recommend 3 ''' koolsla_version = __version__ @click.command(add_help_option=False) @click.option('-d', '--dish', default=25, help='Input dish ID') @click.option( '-r', '--recommend', default=3, help='Number of dish recommendations') @click.option( '-v', '--version', is_flag=True, default=False, help='Display installed version') @click.option( '-h', '--help', is_flag=True, default=False, help='Display help message') @click.option( '-l', '--list', is_flag=True, default=False, help='List dish titles') def main(dish, recommend, version, help, list): if (help): print(help_message) sys.exit(0) else: if (version): print('koolsla' + ' ' + koolsla_version) else: if (list): listLength = click.prompt('Number of dishes to list', type=int) data.list_of_dishes(length=listLength) else: recommender.recommend(dish_id=dish, recommendation_count=recommend) if __name__ == '__main__': main()
JavaScript
UTF-8
390
2.59375
3
[]
no_license
const axios = require('axios'); const bakeTimeCalc = () => { var bakeTime = new Date(); bakeTime.setHours(bakeTime.getHours() + 8); return bakeTime.toLocaleTimeString().replace(/(.*)\D\d+/, '$1'); }; const getPastLoafData = (cb) => { axios.get('http://localhost:3001/pastLoafData') .then(loafs => { cb(loafs); } ); }; module.exports = {bakeTimeCalc, getPastLoafData};
Java
UTF-8
2,116
2.546875
3
[ "MIT" ]
permissive
package edu.hm.hafner.analysis.parser; import java.io.IOException; import java.util.Iterator; import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.Issue; import edu.hm.hafner.analysis.Issues; import edu.hm.hafner.analysis.Priority; import static edu.hm.hafner.analysis.assertj.Assertions.*; import static edu.hm.hafner.analysis.assertj.SoftAssertions.*; /** * Tests the class {@link ResharperInspectCodeParser}. */ public class ResharperInspectCodeParserTest extends ParserTester { /** * Parses a file with warnings of the Reshaper InspectCodeParser tools. * * @throws IOException * if the file could not be read */ @Test public void parseWarnings() { Issues<Issue> warnings = new ResharperInspectCodeParser().parse(openFile()); assertThat(warnings).hasSize(3); Iterator<Issue> iterator = warnings.iterator(); assertSoftly(softly -> { softly.assertThat(iterator.next()) .hasLineStart(16) .hasLineEnd(16) .hasMessage("Cannot resolve symbol 'GetError'") .hasFileName("ResharperDemo/Program.cs") .hasCategory("CSharpErrors") .hasPriority(Priority.HIGH); softly.assertThat(iterator.next()) .hasLineStart(23) .hasLineEnd(23) .hasMessage("Expression is always true") .hasFileName("ResharperDemo/Program.cs") .hasCategory("ConditionIsAlwaysTrueOrFalse") .hasPriority(Priority.NORMAL); softly.assertThat(iterator.next()) .hasLineStart(41) .hasLineEnd(41) .hasMessage("Convert to auto-property") .hasFileName("ResharperDemo/Program.cs") .hasCategory("ConvertToAutoProperty") .hasPriority(Priority.LOW); }); } @Override protected String getWarningsFile() { return "ResharperInspectCode.xml"; } }
Java
UTF-8
4,371
1.726563
2
[]
no_license
package ice_pbru.aupan.jutarat.travelsouth; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; public class MainActivity extends AppCompatActivity { //Explicit private Button AboutMeButton; private ListView travelsouth_Listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //bind widget bindWidget(); buttonController(); createListView(); }//Main Method private void createListView() { final int[] intIcon = {R.drawable.lawlang_01, R.drawable.panyhi_02, R.drawable.lampomtaw_03, R.drawable.fantasy_04, R.drawable.hgi_05, R.drawable.lanta_06, R.drawable.kokao_07, R.drawable.tugboran_08, R.drawable.kainok_09, R.drawable.nangyan_10, R.drawable.pahgan_11, R.drawable.kradan_12, R.drawable.kowsog_13, R.drawable.payam_14, R.drawable.praboromtatchaiya_15,R.drawable.pukattrigai_16, R.drawable.sanbutterfly_17, R.drawable.samui_18, R.drawable.tachai_19, R.drawable.sannam_20}; final String[] titleStrings = new String[20]; titleStrings[0] = "เกาะเหลาเหลียง"; titleStrings[1] = "เกาะปันหยี"; titleStrings[2] = "แหลมพรหมเทพ"; titleStrings[3] = "ภูเก็ตแฟนตาซี"; titleStrings[4] = "เกาะไหง"; titleStrings[5] = "เกาะลันตา"; titleStrings[6] = "เกาะคอเขา"; titleStrings[7] = "ตึกโบราณสถาปัตยกรรมแบบชิโน-โปรตุกีส เมืองเก่าภูเก็ต"; titleStrings[8] = "เกาะไข่นอก"; titleStrings[9] = "เกาะนางยวน"; titleStrings[10] = "เกาะพะงัน"; titleStrings[11] = "เกาะกระดาน"; titleStrings[12] = "อุทยานแห่งชาติเขาสก"; titleStrings[13] = "เกาะพยาม"; titleStrings[14] = "วัดพระบรมธาตุไชยาราชวรวิหาร"; titleStrings[15] = "ภูเก็ต ทริกอาย มิวเซียม "; titleStrings[16] = "สวนผีเสื้อและโลกแมลง ภูเก็ต "; titleStrings[17] = "เกาะสมุย"; titleStrings[18] = "เกาะตาชัย"; titleStrings[19] = "สวนน้ำ Splash Jungle"; String[] detailStrings = getResources().getStringArray(R.array.detail_short); MyAdapter myAdapter = new MyAdapter(MainActivity.this, intIcon, titleStrings, detailStrings); travelsouth_Listview.setAdapter(myAdapter); travelsouth_Listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { Intent intent = new Intent(MainActivity.this, DetailActivity.class); intent.putExtra("Title", titleStrings[i]); intent.putExtra("Image", intIcon[i]); intent.putExtra("Index", i); startActivity(intent); } }); }//create list view private void buttonController() { AboutMeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://fongbeerza.wordpress.com/2014/05/21/%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%A7%E0%B8%B1%E0%B8%95%E0%B8%B4%E0%B8%AA%E0%B9%88%E0%B8%A7%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7-3/")); startActivity(intent); } }); }//button controller private void bindWidget() { AboutMeButton = (Button) findViewById(R.id.button); travelsouth_Listview = (ListView) findViewById(R.id.listView); }//bind widget }//Main Class
C++
UTF-8
6,599
2.703125
3
[]
no_license
#include "Utils.h" #include <string> #include <vector> #include <iostream> #include <getopt.h> #include <sstream> #include <TipoFlor/TipoFlor.h> #include <dirent.h> #include <cstring> #include <sys/stat.h> #include <TipoPedido/TipoPedido.h> #include <dirent.h> void Utils::join(const std::vector<std::string>& v, char c, std::string& s) { s.clear(); for (std::vector<std::string>::const_iterator p = v.begin(); p != v.end(); ++p) { s += *p; if (p != v.end() - 1) s += c; } } void Utils::join(const std::vector<std::string>& v, std::string& s) { s.clear(); for (std::vector<std::string>::const_iterator p = v.begin(); p != v.end(); ++p) { s += *p; } } std::string& Utils::ltrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); return str; } std::string& Utils::rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); return str; } std::string& Utils::trim(std::string& str) { const std::string& chars = "\t\n\v\f\r "; return ltrim(rtrim(str, chars), chars); } t_parametros Utils::tomarParametros(int argc,char* argv[]) { int c; bool pendingParams = true; t_parametros params; params.cantProductores = 0; params.cantDistribuidores = 0; params.cantPuntosVenta = 0; params.debug = false; params.reanudar = false; while (pendingParams) { static struct option long_options[] = { {"productores", required_argument, nullptr, 'p'}, {"distribuidores", required_argument, nullptr, 'd'}, {"puntosventa", required_argument, nullptr, 'v'}, {"debug", no_argument, nullptr, 'x'}, {"reanudar", no_argument, nullptr, 'r'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long(argc, argv, "p:d:v:x:r", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 'p': params.cantProductores = atoi(optarg); break; case 'd': params.cantDistribuidores = atoi(optarg); break; case 'v': params.cantPuntosVenta = atoi(optarg); break; case 'x': params.debug = true; break; case 'r': params.reanudar = true; break; case '?': /* getopt_long already printed an error message. */ break; default: pendingParams = false; } } return params; } std::string Utils::formatearMensajeLog(std::string mensaje) { time_t timestamp = time(nullptr); string timeString = asctime(localtime(&timestamp)); timeString.pop_back(); std::stringstream logMessage; logMessage << "pid: " << std::setw(5) << to_string(getpid()) <<" ("<< std::setw(24) << timeString <<") "<< mensaje; return logMessage.str(); } string Utils::getTextTipoFlor(TipoFlor tipoFlor) { switch (tipoFlor) { case Tulipan: return "Tulipan"; case Rosa: return "Rosa"; case Ninguno: return "Ninguna"; default: return std::to_string(tipoFlor); } } string Utils::getTextTipoPedido(TipoPedido tipoPedido) { switch (tipoPedido) { case INTERNET: return "Internet"; case LOCAL: return "Local"; default: return std::to_string(tipoPedido); } } vector<string> Utils::listarArchivosConPrefijo(const char* path, string prefijo) { DIR *d = opendir(path); vector<string> files; if (d) { struct dirent *p; while ((p = readdir(d))) { if(Utils::startsWith(prefijo.c_str(), p->d_name)) { files.push_back(p->d_name); } } } closedir(d); return files; } bool Utils::startsWith(const char *pre, const char *str) { size_t lenpre = strlen(pre), lenstr = strlen(str); return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0; } int Utils::remove_directory(const char *path) { DIR *d = opendir(path); size_t path_len = strlen(path); int r = -1; if (d){ struct dirent *p; r = 0; while (!r && (p=readdir(d))){ int r2 = -1; char *buf; size_t len; if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")){ continue; } len = path_len + strlen(p->d_name) + 2; buf = (char*)malloc(len); if (buf){ struct stat statbuf; snprintf(buf, len, "%s/%s", path, p->d_name); if (!stat(buf, &statbuf)){ if (S_ISDIR(statbuf.st_mode)){ r2 = remove_directory(buf); } else{ r2 = unlink(buf); } } free(buf); } r = r2; } closedir(d); } if (!r) { r = rmdir(path); } return r; } int Utils::countFiles(std::string carpeta) { int count = 0; DIR *dir; struct dirent *ent; if ((dir = opendir (carpeta.c_str())) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { count++; } closedir (dir); } else { /* could not open directory */ perror (""); return EXIT_FAILURE; }; return count-2; } std::vector<std::string> Utils::split(const std::string &str, const std::string &delim) { vector<string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == string::npos) pos = str.length(); string token = str.substr(prev, pos-prev); if (!token.empty()) tokens.push_back(token); prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } TipoFlor Utils::getTipoFlor(int tipoFlor) { switch (tipoFlor) { case 0: return Tulipan; case 1: return Rosa; case 2: return Ninguno; default: { string mensajeError = "Tipo de flor invalido"; throw(std::string(mensajeError)); } } }
Markdown
UTF-8
670
3.015625
3
[]
no_license
## Html File Read html file and return the code. `read_html(html_path, full=False)` ### Type * :type html_path: str * :type full: bool ### Description * :param html_path: html file path. * :param full: True to get full code, otherwise code in body tag. (optional) ### Return * :rtype: str * :return: html code of the file. ### Example `wp.read_html("C\\Path\\To\\File.html")` *** ## Docx File Convert docx file to html code. `docx_to_html(docx_path)` ### Type * :type docx_path: str ### Description * :param docx_path: Path of docx file. ### Return * :rtype: str * :return: html code of the file. ### Example `wp.docx_to_html("C\\Path\\To\\File.docx")` ***
Java
UTF-8
771
3.359375
3
[]
no_license
package com.frostmaster.algorithms.implementation.FindDigits; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int c[] = new int[n]; for(int c_i=0; c_i < n; c_i++){ c[c_i] = in.nextInt(); } for(int i = 0; i < n; i++){ int temp = c[i]; int result = 0; int digits = 0; while ( temp != 0) { result = temp%10; temp /= 10; if(result == 0) continue; if(c[i] % result == 0) digits++; } System.out.println(digits); } } }
Java
UTF-8
1,960
1.929688
2
[]
no_license
package br.com.etecia.appmenutwo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import android.widget.Toolbar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar= findViewById(R.id.idToolbar); getSupportActionBar().setTitle("AAA"); getSupportActionBar().setIcon(R.drawable.ic_arrow_back_dp); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_principal, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mShare: Toast.makeText(getApplicationContext(), "Shared", Toast.LENGTH_SHORT).show(); break; case R.id.mSettings: Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show(); break; case R.id.mFavorite: Toast.makeText(getApplicationContext(), "Favorite", Toast.LENGTH_SHORT).show(); break; case R.id.mInfo: Toast.makeText(getApplicationContext(), "Info", Toast.LENGTH_SHORT).show(); break; case R.id.mSearch: Toast.makeText(getApplicationContext(), "Search", Toast.LENGTH_SHORT).show(); break; case R.id.mSave: Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show(); break; } return super.onContextItemSelected(item); } }
Java
UTF-8
474
3.0625
3
[]
no_license
public class l1624 { public int maxLengthBetweenEqualCharacters(String s) { int count = 0; int ans = -1; for (int i = 0; i < s.length()-1; i++) { for (int j = i+1; j < s.length(); j++) { if(s.charAt(i)==s.charAt(j)) { count = j-i-1; if(ans<count) { ans = count; } } } } return ans; } }
Java
UTF-8
2,274
2.484375
2
[]
no_license
package devin.spittr.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * 用于配置 ${@link org.springframework.web.servlet.DispatcherServlet} 应用上下文中的 bean * 通常是 Web 组件的 bean, 如控制器、视图解析器以及处理器映射 * @author devin * @since 1.0.0 */ @Configuration @EnableWebMvc @ComponentScan("devin.spittr.web") public class WebConfig extends WebMvcConfigurerAdapter{ /** 视图的前缀 **/ private static final String RESOLVER_PREFIX = "/WEB-INF/views/"; /** 视图的后缀 **/ private static final String RESOLVER_SUFFIX = ".jsp"; /** * 默认的视图解析器是 {@link org.springframework.web.servlet.view.BeanNameViewResolver} * 这个解析器会查找 ID 与视图名称匹配的 bean, 并且查找的 bean 要实现 ${@link org.springframework.web.servlet.View} 接口 * * <p> 这里添加 {@link InternalResourceViewResolver} 视图解析器用来解析 JSP 文件。 * @return * @since 1.0.0 */ @Bean public ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix(RESOLVER_PREFIX); resolver.setSuffix(RESOLVER_SUFFIX); resolver.setExposeContextBeansAsAttributes(true); return resolver; } /** * 通过在重写该方法的过程中调用 <code>enbale()</code> 使得 {@link org.springframework.web.servlet.DispatcherServlet} * 对静态资源的请求转发到 Servlet 容器中默认的 servlet 上进行处理。 * @param configurer * @since 1.0.0 */ @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
JavaScript
UTF-8
2,955
3.046875
3
[]
no_license
"use strict"; const LOCAL_STORAGE_KEY_TBRS = "tbrs"; let readBooks2021 = document.querySelector("#read-books-2021"); let readBooks2020 = document.querySelector("#read-books-2020"); let button2020 = document.querySelector("#btn-2020"); let button2021 = document.querySelector("#btn-2021"); let tbrs = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY_TBRS)) || []; function saveList() { localStorage.setItem(LOCAL_STORAGE_KEY_TBRS, JSON.stringify(tbrs)); } function hide(hide, show) { hide.classList.add("hide"); show.classList.remove("hide"); } button2020.addEventListener("click", () => { hide(readBooks2021, readBooks2020); button2020.classList.add("underline"); button2021.classList.remove("underline"); }); button2021.addEventListener("click", () => { hide(readBooks2020, readBooks2021); button2020.classList.remove("underline"); button2021.classList.add("underline"); }); function createItem(ElementType, innerText) { let item = document.createElement(ElementType); item.innerText = innerText; return item; } function createListItem(book) { let listItem = document.createElement("li"); listItem.classList.add("grid", "book-list"); let titleLink = createItem("a", book.title); titleLink.classList.add("book-title"); titleLink.setAttribute("href", "reviews.html#" + book.id); let author = createItem("p", book.author); author.classList.add("author"); let pages = createItem("p", book.pages); let score = createItem("p", book.score + "/5"); let addToTbr = createItem("button", "+"); addToTbr.classList.add("button-text"); addToTbr.addEventListener("click", () => { let bookAlreadyAdded = false; tbrs.forEach((item) => { if (item.id === book.id) { bookAlreadyAdded = true; addToTbr.innerText = "Already added"; } }); if (!bookAlreadyAdded) { tbrs.push(book); addToTbr.innerText = "Added"; saveList(); } }); listItem.append(titleLink, author, pages, score, addToTbr); return listItem; } fetch("./content/books.json", {}) .then((response) => { console.log(response); return response.json(); }) .then((data) => { console.log(data); data.forEach((book) => { if (book.read[0]) { let listItem = createListItem(book); if (book.read[1] === 2021) { document.querySelector("#app-2021-root").append(listItem); } else if (book.read[1] === 2020) { document.querySelector("#app-2020-root").append(listItem); } } else if (book.read[1] === "currently reading") { let currentReadImg = document.createElement("img"); currentReadImg.setAttribute( "alt", book.title + " by " + book.author + " book cover" ); currentReadImg.setAttribute("src", book.img); document.querySelector("#current-read-root").append(currentReadImg); } }); }) .catch((error) => { console.error(error); });
Shell
UTF-8
1,867
2.859375
3
[]
no_license
#!/bin/bash source /cvmfs/dune.opensciencegrid.org/products/dune/setup_dune.sh setup geant4 v4_10_6_p01 -q e19:prof setup cmake v3_14_3 setup root v6_18_04d -q e19:prof #Added by Marcos -> CRY library of Geant4 #export G4INSTALL=/cvmfs/larsoft.opensciencegrid.org/products/geant4/v4_10_6_p01/Linux64bit+3.10-2.17-e19-prof #export G4SYSTEM=Linux-g++ #export G4WORKDIR=$HOME/geant4_workdir #source /lhome/ific/m/marcosmr/20cm1mmFibers_without_Lead_without_VETO/cry_v1.7/setup WORKING_DIRECTORY=$(pwd) echo "Working directory: " $WORKING_DIRECTORY echo "Hostname: " hostname echo "id: " id Ini=6696 RunNumber1=$1 RunNumber2=$((Ini+$1)) AcquisitionTime=600 SourceAcquivity=600 #Bq/L randSeed=$RANDOM FOLDER=DATA OUTPUT_FILE1="MultipleFibbers_"$SourceAcquivity"BqL_Run_"$RunNumber1".root" OUTPUT_FILE2="MultipleFibbers_"$SourceAcquivity"BqL_Run_"$RunNumber2".root" echo "OUTPUT_FILE1: " $OUTPUT_FILE1 echo "OUTPUT_FILE2: " $OUTPUT_FILE2 #SBATCH --nodes=1\n\ #SBATCH --tasks-per-node=1\n\ #SBATCH --ntasks=1\n\ #SBATCH --cpus-per-task=1\n\ #SBATCH --time=120\n\ #SBATCH --mem=600\n\ #SBATCH --partition=short\n\ #SBATCH--job-name="+resultsFile+"\n\ #SBATCH -o "+WORKING_DIRECTORY+"/OUTPUTS/"+resultsFile+".out\n\ #SBATCH -e "+WORKING_DIRECTORY+"/ERRORS/"+resultsFile+".err\n\ #SBATCH --mail-user=marcos.martinez@ific.uv.es\n\ #SBATCH --mail-type=FAIL\n\ if [ -d $FOLDER ]; then echo 1 else mkdir $FOLDER fi ./MultipleFibbers run1.mac $RunNumber1 0 $AcquisitionTime $SourceAcquivity $randSeed ./MultipleFibbers run1.mac $RunNumber2 0 $AcquisitionTime $SourceAcquivity $randSeed #root -q -l Analise.C\(\"MultipleFibbers_"$SourceAcquivity"BqL_Run_"$1".root\"\) echo "ls -al: " ls -al echo "stat file.root: " stat $OUTPUT_FILE1 stat $OUTPUT_FILE2 root -q -l Analise.C\(\"$OUTPUT_FILE1\"\) root -q -l Analise.C\(\"$OUTPUT_FILE2\"\) #mv *.root $WORKING_DIRECTORY/$FOLDER
Java
UTF-8
1,398
3.484375
3
[]
no_license
/*Краткое описание * * Игра предусматривает один игровой объект и три объекта-игрока. Генерируются случайные числа от 0 до 9, а три объекта-игрока пытаются их угадать * * Классы: GuessGame.class Player.class Main.class * * Логика: * 1) Класс Main - это точка, из которой стартует прилоджение. Содержит класс main. * 2) В методе main() создается объект GuessGame, из которого вызывается метод startGame(). * 3) В методе startGame() объекта GuessGame происходлит весь игровой процесс. Он создает трех игроков, затем "придумывает" случайные числа * (которые игроки должны угадывать). * После того как каждого из игроков просят угадать число, проверяется результат и либо выводится информация о победителях, либо игроков просят угадать еще раз.*/ package com.company; public class Main { public static void main(String[] args) { GuessGame game = new GuessGame(); game.startGame(); } }
Java
UTF-8
290
2.390625
2
[ "Apache-2.0" ]
permissive
package tech.mhuang.core.clone; /** * 拷贝接口 * * @param T 拷贝后的对象 * @author mhuang * @since 1.0.0 */ public interface BaseCloneable<T> extends java.lang.Cloneable { /** * 拷贝接口 * * @return 拷贝后得到的数据 */ T clone(); }
Java
UTF-8
4,747
2.078125
2
[]
no_license
package com.jy.modules.externalplatform.application.extinterfaceparamsref.service; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fintech.platform.core.common.BaseDTO; import com.jy.modules.externalplatform.application.extinterfaceparamsref.dao.ExtInterfaceParamsRefDao; import com.jy.modules.externalplatform.application.extinterfaceparamsref.dto.ExtInterfaceParamsRefDTO; /** * @classname: ExtInterfaceParamsRefService * @description: 定义 接口参数映射表 实现类 * @author: Administrator */ @Service("com.jy.modules.externalplatform.application.extinterfaceparamsref.service.ExtInterfaceParamsRefService") public class ExtInterfaceParamsRefService implements Serializable { private static final long serialVersionUID = 1L; @Autowired private ExtInterfaceParamsRefDao dao; /** * @author Administrator * @description: 分页查询 接口参数映射表列表 * @date 2017-05-16 15:10:22 * @param searchParams 条件 * @return * @throws */ public List<ExtInterfaceParamsRefDTO> searchExtInterfaceParamsRefByPaging(Map<String,Object> searchParams) throws Exception { List<ExtInterfaceParamsRefDTO> dataList = dao.searchExtInterfaceParamsRefByPaging(searchParams); return dataList; } /** * @author Administrator * @description: 按条件查询接口参数映射表列表 * @date 2017-05-16 15:10:22 * @param searchParams 条件 * @return * @throws */ public List<ExtInterfaceParamsRefDTO> searchExtInterfaceParamsRef(Map<String,Object> searchParams) throws Exception { List<ExtInterfaceParamsRefDTO> dataList = dao.searchExtInterfaceParamsRef(searchParams); return dataList; } /** * @author Administrator * @description: 查询接口参数映射表对象 * @date 2017-05-16 15:10:22 * @param id * @return * @throws */ public ExtInterfaceParamsRefDTO queryExtInterfaceParamsRefByPrimaryKey(String id) throws Exception { ExtInterfaceParamsRefDTO dto = dao.findExtInterfaceParamsRefByPrimaryKey(id); if(dto == null) dto = new ExtInterfaceParamsRefDTO(); return dto; } /** * @title: insertExtInterfaceParamsRef * @author Administrator * @description: 新增 接口参数映射表对象 * @date 2017-05-16 15:10:22 * @param dto * @return * @throws */ @SuppressWarnings("all") public Long insertExtInterfaceParamsRef(ExtInterfaceParamsRefDTO dto) throws Exception { Map<String, Object> paramMap = new HashMap<String, Object>(); dto.setCreateBy(String.valueOf(dto.getOpUserId())); paramMap.put("dto", dto); int count = dao.insertExtInterfaceParamsRef(paramMap); ExtInterfaceParamsRefDTO resultDto = (ExtInterfaceParamsRefDTO) paramMap.get("dto"); Long keyId = resultDto.getId(); return keyId; } /** * @title: updateExtInterfaceParamsRef * @author Administrator * @description: 修改 接口参数映射表对象 * @date 2017-05-16 15:10:22 * @param paramMap * @return * @throws */ public void updateExtInterfaceParamsRef(ExtInterfaceParamsRefDTO dto) throws Exception { Map<String, Object> paramMap = new HashMap<String, Object>(); dto.setModifyBy(String.valueOf(dto.getOpUserId())); paramMap.put("dto", dto); dao.updateExtInterfaceParamsRef(paramMap); } /** * @title: deleteExtInterfaceParamsRefByID * @author Administrator * @description: 删除 接口参数映射表,按主键 * @date 2017-05-16 15:10:22 * @param paramMap * @throws */ public void deleteExtInterfaceParamsRefByID(BaseDTO baseDto,String ids) throws Exception { if(StringUtils.isEmpty(ids)) throw new Exception("删除失败!传入的参数主键为null"); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("dto", baseDto); paramMap.put("ids", ids); dao.deleteExtInterfaceParamsRefByID(paramMap); } /** * @title: deleteExtInterfaceParamsRefByID * @author Administrator * @description: 删除 接口参数映射表,按主键 * @date 2017-05-16 15:10:22 * @param paramMap * @throws */ public void deleteExtInterfaceParamsRefByInterfaceNo(String interfaceNo) throws Exception { if(StringUtils.isEmpty(interfaceNo)) throw new Exception("删除失败!传入的参数为null"); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("interfaceNo", interfaceNo); dao.deleteExtInterfaceParamsRefByInterfaceNo(paramMap); } }
C#
UTF-8
2,335
2.734375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Route : MonoBehaviour { //https://en.wikipedia.org/wiki/B%C3%A9zier_curve //https://www.youtube.com/watch?v=11ofnLOE8pw&list=WL [SerializeField] Transform[] controlPoints = new Transform[0]; [SerializeField] float sizeSphere = 1f; [SerializeField] int amountSphere = 100; public int ID; public int pointId1; public int pointId2; Vector2 gizmosPosition; bool canUse; private void OnDrawGizmos() { if (controlPoints.Length == 4) { canUse = true; foreach (var point in controlPoints) { if (point == null) { canUse = false; break; } } } else canUse = false; if(canUse) { for (float i = 0; i <= 1; i += 1f/amountSphere) { gizmosPosition = Mathf.Pow(1 - i, 3) * controlPoints[0].position + 3 * Mathf.Pow(1 - i, 2) * i * controlPoints[1].position + 3 * (1 - i) * Mathf.Pow(i, 2) * controlPoints[2].position + Mathf.Pow(i, 3) * controlPoints[3].position; Gizmos.DrawSphere(gizmosPosition, sizeSphere); } Gizmos.DrawLine(new Vector2(controlPoints[0].position.x, controlPoints[0].position.y), new Vector2(controlPoints[1].position.x, controlPoints[1].position.y)); Gizmos.DrawLine(new Vector2(controlPoints[2].position.x, controlPoints[2].position.y), new Vector2(controlPoints[3].position.x, controlPoints[3].position.y)); } } /// <summary> /// 0 - First point; /// 1 - First curve; /// 2 - Second curve; /// 3 - Last point /// </summary> /// <param name="x"></param> public Transform GetPoint(int x) { switch (x) { case 0: return controlPoints[x]; case 1: return controlPoints[x]; case 2: return controlPoints[x]; case 3: return controlPoints[x]; default: return null; } } }
Python
UTF-8
254
3.125
3
[]
no_license
a = int(input()) array = [int(i) for i in input().split()] maxi1 = -10000 maxi2 = -10001 for i in range(len(array)): if array[i] > maxi1: maxi2 = maxi1 maxi1 = array[i] elif array[i] > maxi2: maxi2 = array[i] print(maxi2)
Python
UTF-8
4,645
2.8125
3
[]
no_license
import numpy as np from sklearn.feature_extraction.image import extract_patches_2d from process_images import get_Y from sklearn.linear_model import orthogonal_mp import matplotlib.pyplot as plt from scipy.sparse.linalg import svds class KSVDDenoiser(): def __init__(self, patch_size = 8, iterations = 10, lambd = 10, sigma = 2, sparsity = 2, noise_gain = 1.1, viz_dict = False): self.lambd = lambd self.iterations = iterations self.patch_size = patch_size self.image_shape = None self.sigma = sigma self.noise_gain = noise_gain self.sparsity = sparsity self.A = None self.D = None self.viz_dict = viz_dict def denoise(self, image, dictionary): self.D = dictionary if image.shape[0] != image.shape[1]: print("The image must be a square matrix") return self.image_shape = image.shape[0] # convert image to patches and vectorize Y = get_Y(image, self.patch_size) for itr in range(self.iterations): print("Iteration Number " + str(itr)) if self.viz_dict: self.visualize_dictionary(itr) self.sparse_code(Y) self.dictionary_update(Y) recon_img = np.zeros(image.shape) weight_img = np.zeros(image.shape) # Source: Matlab code in Michael Elads book cf. Elad, M. (2010). i, j = 0, 0 for k in range((self.image_shape - self.patch_size + 1)** 2): patch = np.reshape(self.D @ self.A[:, k], (self.patch_size, self.patch_size)) recon_img[j:j + self.patch_size, i:i + self.patch_size] += patch weight_img[j:j + self.patch_size, i:i + self.patch_size] += 1 if i < self.image_shape - self.patch_size: i += 1 else: i, j = 0, j + 1 return np.divide(recon_img + self.lambd * image, weight_img + self.lambd) def sparse_code(self, Y): print("Running OMP..") # self.A = orthogonal_mp(self.D, Y, n_nonzero_coefs=self.sparsity, # tol=self.noise_gain * self.sigma, precompute=True) n, K = self.D.shape alphas = [] for yy in Y.T: coeffs = np.zeros(K) res = yy i = 0 while True: proj = np.dot(self.D.T, res) max_i = int(np.argmax(np.abs(proj))) alpha = proj[max_i] res = res - alpha * self.D[:, max_i] if np.isclose(alpha, 0): break # update coefficients coeffs[max_i] += alpha if self.noise_gain is not None: if np.linalg.norm(res) ** 2 < n * (self.noise_gain * self.sigma)**2 or i > n/2: break else: if np.count_nonzero(coeffs) >= self.sparsity: break i += 1 alphas.append(coeffs) self.A = np.array(alphas).T def dictionary_update(self, Y): print("Updating Dictionary..") n, K = self.D.shape Res = Y - np.dot(self.D, self.A) for k in range(K): # get non zero entries nk = np.nonzero(self.A[k, :])[0] if len(nk) == 0: continue Ri = np.dot(self.D[:, k].reshape((-1, 1)), self.A[k, nk].reshape((1, -1))) + Res[:, nk] U, Sg, V = svds(Ri, k=1) self.D[:, k] = U[:, 0] # 1 svd step self.A[k, nk] = Sg[0] * V[0, :] Res[:, nk] = Ri - np.dot(self.D[:, k].reshape((-1, 1)), self.A[k, nk].reshape((1, -1))) def visualize_dictionary(self, itr): n, K = self.D.shape # patch size n_r = int(np.sqrt(n)) # patches per row / column K_r = int(np.sqrt(K)) # we need n_r*K_r+K_r+1 pixels in each direction dim = n_r * K_r + K_r + 1 V = np.ones((dim, dim)) * np.min(self.D) # compute the patches patches = [np.reshape(self.D[:, i], (n_r, n_r)) for i in range(K)] # place patches for i in range(K_r): for j in range(K_r): V[j * n_r + 1 + j:(j + 1) * n_r + 1 + j, i * n_r + 1 + i:(i + 1) * n_r + 1 + i] = patches[ i * K_r + j] V *= 255 plt.imsave('dictionary/dict_' + str(itr) + '.png', V, cmap='gray') plt.show()
JavaScript
UTF-8
1,947
2.53125
3
[ "MIT" ]
permissive
import findIndex from 'lodash/findIndex' import { initialState } from './selectors' import { RESOURCE_CREATE_SUCCESS, RESOURCE_LIST_READ_REQUEST, RESOURCE_LIST_READ_SUCCESS, RESOURCE_DETAIL_READ_REQUEST, RESOURCE_DETAIL_READ_SUCCESS, RESOURCE_UPDATE_SUCCESS, RESOURCE_DELETE_SUCCESS, } from './actions' const updateOrDeleteReducer = (state, action) => { const needleIsObject = typeof action.needle === 'object' const index = needleIsObject ? findIndex(state.list, action.needle) : state.list.indexOf(action.needle) if (index < 0) { return state } switch (action.type) { case RESOURCE_UPDATE_SUCCESS: return { ...state, list: [ ...state.list.slice(0, index), typeof action.needle === 'object' ? { ...state.list[index], ...action.detail } : action.detail, ...state.list.slice(index + 1), ], } case RESOURCE_DELETE_SUCCESS: return { ...state, list: [...state.list.slice(0, index), ...state.list.slice(index + 1)], } // istanbul ignore next default: return state } } export default (state = initialState, action) => { switch (action.type) { case RESOURCE_CREATE_SUCCESS: return { ...state, list: [action.detail, ...state.list], } case RESOURCE_LIST_READ_REQUEST: return { ...state, list: initialState.list, } case RESOURCE_LIST_READ_SUCCESS: return { ...state, list: action.list, } case RESOURCE_DETAIL_READ_REQUEST: return { ...state, detail: initialState.detail, } case RESOURCE_DETAIL_READ_SUCCESS: return { ...state, detail: action.detail, } case RESOURCE_UPDATE_SUCCESS: case RESOURCE_DELETE_SUCCESS: return updateOrDeleteReducer(state, action) default: return state } }
Java
UTF-8
5,443
2.375
2
[]
no_license
package com.springapp.mvc; import org.hibernate.StatelessSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import java.sql.*; import java.util.List; import javax.persistence.Query; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 13. 7. 25 * Time: 오후 12:53 * To change this template use File | Settings | File Templates. */ @Component @Scope("singleton") @Path("/customer") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public class UserRestful { @Autowired UserRepository userRepository; @PersistenceContext (unitName = "oracleUnit") private EntityManager entityManager; @PersistenceContext (unitName = "mysqlUnit") private EntityManager mysqlEntityManager; @GET @Path("/list") public UserResponse getUsers() { UserResponse userResponse = new UserResponse(); List<User> users = userRepository.findAll(); userResponse.setUsers(users); for (int i = 0; i < users.size(); i++) { printUser(users.get(i)); } return userResponse; } @GET @Path("/{userId}") public UserResponse getUser(@PathParam("userId") Long id) { UserResponse userResponse = new UserResponse(); User user = userRepository.findOne(id); printUser(user); userResponse.setId(user.getId()); userResponse.setFirstName(user.getFirstName()); userResponse.setLastName(user.getLastName()); userResponse.setEmail(user.getEmail()); return userResponse; } @GET @Path("/oracle/{userId}") @Transactional(value = "transactionManager2") public UserResponse getOracle(@PathParam("userId") Long id){ UserResponse userResponse = new UserResponse(); /* // 최후의 수단!! JDBC 커넥션을 맺어서 proceduer을 호출한다!! Connection conn = null; PreparedStatement pstmt = null; //디비의 주소와 디비정보들.. final String IP = "192.168.44.128"; String jdbc_driver = "oracle.jdbc.driver.OracleDriver"; String jdbc_url = "jdbc:oracle:thin:@" + IP + ":1521:XE"; //JDBC 드라이버 로드 try { Class.forName(jdbc_driver); //데이터베이스 연결 conn = DriverManager.getConnection(jdbc_url, "test", "1234"); CallableStatement cs = conn.prepareCall("{ call TESTPROC7(?) }"); cs.setInt(1,2); // first parameter index start with 1 cs.execute(); // call stored procedure cs.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (SQLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } */ /* <<<<<<<<<< TEST PROCEDURE >>>>>>>>>> CREATE OR REPLACE PROCEDURE TESTPROC7 ( vid IN ACCOUNT.ID%TYPE ) IS BEGIN UPDATE ACCOUNT SET email='test@co.k.r' WHERE ID=vid; END; */ try { Query query = entityManager.createNativeQuery("call TESTPROC7(?)"); query.setParameter(1, 2); query.executeUpdate(); //System.out.print(">>>>>>>>>>>>"+ (String) query.getSingleResult()); //userResponse.setEmail((String) query.getSingleResult()); } catch (Exception e) { e.printStackTrace(System.out); } return userResponse; } @GET @Path("/mysql/{userId}") @Transactional(value = "transactionManager") public UserResponse getMysql(@PathParam("userId") Long id){ UserResponse userResponse = new UserResponse(); try { Query query = mysqlEntityManager.createNativeQuery("update account set email=? where id=1"); query.setParameter(1, "test@naver.com"); query.executeUpdate(); //System.out.print(">>>>>>>>>>>>"+ (String) query.getSingleResult()); //userResponse.setEmail((String) query.getSingleResult()); } catch (Exception e) { e.printStackTrace(System.out); } return userResponse; } @GET @Path("/old") public Response getUser() { return Response.ok().entity("<xml>씨팔</xml>").build(); } private void printUser(final User user) { System.out.println("-------------------"); System.out.println(user.getId()); System.out.println(user.getFirstName()); System.out.println(user.getLastName()); System.out.println(user.getEmail()); } }
Markdown
UTF-8
3,995
3
3
[ "MIT" ]
permissive
# Recast Recast helps make your old extensions compatible with Kodular Creator version 1.5.0 or above. ## Prerequisites To use Recast, you need to have Java Runtime Environment (JRE) installed on your system. To check if you have it pre-installed, open your favorite terminal app and run the following: ```.sh java -version ``` If you get an output similar to below, JRE is already available on your system. ```.sh java version "1.8.0_281" Java(TM) SE Runtime Environment (build 1.8.0_281-b09) ``` If you don't see an output similar to the above, you will need to install Java before installing Recast. ## Installing Recast is a command-line tool, and therefore, you first need to install it on your computer to use it. As of now, Recast can be installed on the following operating systems: * Windows (64 bit) * macOS (x86_64 arch) * GNU/Linux (x86_64 arch) ### Using PowerShell (Windows) 1. Open PowerShell. 2. Copy and paste the following and hit enter: ```.ps1 iwr https://raw.githubusercontent.com/shreyashsaitwal/recast/main/scripts/install.ps1 -useb | iex ``` 3. Done! Run `recast --help` to verify installation. ### Using Shell (macOS and Linux) 1. Open your favorite shell (terminal). 2. Copy and paste the following and hit enter: ```.sh curl https://raw.githubusercontent.com/shreyashsaitwal/recast/main/scripts/install.sh -fsSL | sh ``` 3. Once the download is complete, add Recast to your `PATH` by copying the export command from the output (as shown below) and running it: ![export](assets/export.gif) 4. Done! Run `recast --help` to verify installation. ## Usage ### Recasting extensions (AIX) To make your old extension compatible with Kodular >1.5.0 using Recast, go through the following steps: 1. Navigate to the directory/folder where your extension is placed. 2. Open your favorite terminal in that directory. 3. Now, run the following: ```.sh recast --input you.extension.aix ``` (Here, `your.extension.aix` is the name of your extension) 4. Bingo! A new, recasted extension with the name `your.extension.x.aix` is generated in the current working and ready to be used. ### Recasting AIAs Starting with Recast v0.2.0, you get the ability to recast your AIA files as well. This reduces the manual work of re-importing every recasted extension in your project. 1. Navigate to the directory/folder where your AIA is placed. 2. Open your favorite terminal in that directory. 3. Now, run the following: ```.sh recast --input you_app.aia ``` (Here, `you_app.aia` is the name of your AIA file) 4. And there you go! All the extensions in your AIA are now recasted, and the new AIA can be found in the same directory with name `your_app_x.aia`. > **Note:** When you import a recasted AIA in Kodular (or AI2), your existing project isn't affected. Instead, a separate project with name `your_app_x` is created with all the existing work preserved. ## Tips * You can recast multiple extensions/AIAs all at once by gathering them all in one directory and then running: ```.sh recast --input directory_path ``` (Here, `directory_path` is the path to the directory where extensions/AIAs are stored.) * If you want to output the recasted extension/AIAs in a separate directory, all you need to do is specify the `--output` option and pass the path to your desired directory. ```.sh recast --input you_aix_or_aia --output output_dir_path ``` (Here, `output_dir_path` is the path to the output directory.) ## FAQ 1. Do I need to recast every extension to make it compatible with Kodular >1.5.0?<br> **Ans.** No, you don't need to. Only the extensions that started throwing errors after the latest update need to be recasted. 2. Why does Recast print **`No references to support libraries found`** when I try to recast my extension?<br> **Ans.** It means that your extension is already compatible with Kodular >1.5.0, and you don't need to recast it.
Java
UTF-8
353
2.84375
3
[]
no_license
package theFactory.method; public class ChemicalWarehouse extends Warehouse { @Override public Entity createEntity(EntityType entityType) { switch(entityType) { //some DB logic is possible case LARGE: return new Tank(); case MASSIVE: return new LargeTank(); case SMALL: return new SteelBox(); default: return null; } } }
Python
UTF-8
105
3.203125
3
[]
no_license
d,t,s = input().split() gool = int(d) / int(s) if gool <= int(t): print('Yes') else: print('No')
TypeScript
UTF-8
4,173
2.90625
3
[ "MIT" ]
permissive
declare namespace ccui { /** * The button controls of Cocos UI. * @class * @extends ccui.Widget * * @property {String} titleText - The content string of the button title * @property {String} titleFont - The content string font of the button title * @property {Number} titleFontSize - The content string font size of the button title * @property {String} titleFontName - The content string font name of the button title * @property {cc.Color} titleColor - The content string font color of the button title * @property {Boolean} pressedActionEnabled - Indicate whether button has zoom effect when clicked */ export class Button extends Widget { protected _buttonNormalSpriteFrame: cc.SpriteFrame; protected _buttonClickedSpriteFrame: cc.SpriteFrame; protected _buttonDisableSpriteFrame: cc.SpriteFrame; protected _titleRenderer: cc.LabelTTF; protected _scale9Enabled: boolean; protected _pressedTextureLoaded: boolean; protected _normalTextureLoaded: boolean; protected _disabledTextureLoaded: boolean; protected _normalTextureScaleXInSize: number; protected _normalTextureScaleYInSize: number; protected _zoomScale: number; protected _buttonScale9Renderer: ccui.Scale9Sprite; protected pressedActionEnabled: boolean; /** * the zoom action time step of ccui.Button * @constant * @type {number} */ static ZOOM_ACTION_TIME_STEP: number; public constructor(normalImage?: string, selectedImage?: string, disableImage?: string, texType?: number); /** * Load normal state texture for button. * @param {String} normal normal state of texture's filename. * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ public loadTextureNormal(normal: string, texType: number): void; /** * Load selected state texture for button. * @param {String} selected selected state of texture's filename. * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ public loadTexturePressed(selected: string, texType: number): void; /** * Load dark state texture for button. * @param {String} disabled disabled state of texture's filename. * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ public loadTextureDisabled(disable: string, texType: number): void; /** * Sets title text to ccui.Button * @param {String} text */ public setTitleText(text: string): void; /** * Sets title color to ccui.Button. * @param {cc.Color} color */ public setTitleColor(color: cc.Color): void; /** * Sets title fontSize to ccui.Button * @param {cc.Size} size */ public setTitleFontSize(size: number): void; /** * When user pressed the button, the button will zoom to a scale. * The final scale of the button equals (button original scale + _zoomScale) * @since v3.2 * @param scale */ public setZoomScale(scale: number): void; /** * Returns a zoom scale * @since v3.2 * @returns {number} */ public getZoomScale(): number; /** * Sets title fontName to ccui.Button. * @param {String} fontName */ public setTitleFontName(name: string): void; /** * Sets if button is using scale9 renderer. * @param {Boolean} able true that using scale9 renderer, false otherwise. */ public setScale9Enabled(able: boolean): void; /** * Changes if button can be clicked zoom effect. * @param {Boolean} enabled */ public setPressedActionEnabled(enabled: boolean): void; protected _onPressStateChangedToNormal(): void; } }
Markdown
UTF-8
1,390
2.890625
3
[]
no_license
# Iframes I've always heard iframes are dangerous and should be avoided from both a security and usability point-of-view. So what I'm interested in is, of course. what vectors does the iframe offer? Get document's iframes var frames = document.getElementByTagName('iframe'); for (var frame in frames)     frame.contentWindow.frames[1].name = 'foo' `window.postMessage` If there is no origin check when message sent from the parent via postMessage, check if you can use the postMessage as a gadget to manipulate the behaviour of the enclosed site. `No X-Frame-Options header` This means the victim site can be embedded as an iframe. If that victim site has an iframe in it (e.g. Recaptcha). You can then control, for instance, the `src` of an iframe using the attacker's to manipulate the victim's site's iframe. This does not violate same-origin policy. You can also do stuff like DOM Clobbering on the victim site using this technique, by changing the name or id of the victm site's iframe. `allow-scripts and allow-same-origin on page.origin == iframe.origin sites.` Setting both the allow-scripts and allow-same-origin keywords together when the embedded page has the same origin as the page containing the iframe allows the embedded page to simply remove the sandbox attribute and then reload itself, effectively breaking out of the sandbox altogether.
Swift
UTF-8
2,135
2.59375
3
[ "MIT" ]
permissive
// // SimpleGeometryRenderer.swift // Alloy // // Created by Andrey Volodin on 15/05/2019. // import Metal import simd public class SimpleGeometryRenderer { public let pipelineState: MTLRenderPipelineState public init(library: MTLLibrary, pixelFormat: MTLPixelFormat, blending: BlendingMode = .alpha, label: String = "Simple Geometry Renderer") throws { guard let fragment = library.makeFunction(name: "plainColorFragment"), let vertex = library.makeFunction(name: "simpleVertex") else { throw CommonErrors.metalInitializationFailed } let renderPipelineStateDescriptor = MTLRenderPipelineDescriptor() renderPipelineStateDescriptor.label = label renderPipelineStateDescriptor.vertexFunction = vertex renderPipelineStateDescriptor.fragmentFunction = fragment renderPipelineStateDescriptor.colorAttachments[0].pixelFormat = pixelFormat renderPipelineStateDescriptor.colorAttachments[0].setup(blending: blending) renderPipelineStateDescriptor.depthAttachmentPixelFormat = .invalid renderPipelineStateDescriptor.stencilAttachmentPixelFormat = .invalid try self.pipelineState = library.device .makeRenderPipelineState(descriptor: renderPipelineStateDescriptor) } public func render(geometry: MTLBuffer, type: MTLPrimitiveType = .triangle, fillMode: MTLTriangleFillMode = .fill, indexBuffer: MTLIndexBuffer, matrix: float4x4 = float4x4(diagonal: float4(1)), color: float4 = float4(1, 0, 0, 1), using encoder: MTLRenderCommandEncoder) { encoder.setVertexBuffer(geometry, offset: 0, index: 0) encoder.set(vertexValue: matrix, at: 1) encoder.set(fragmentValue: color, at: 0) encoder.setTriangleFillMode(fillMode) encoder.setRenderPipelineState(self.pipelineState) encoder.drawIndexedPrimitives(type: type, indexBuffer: indexBuffer) } }
Python
UTF-8
1,300
2.84375
3
[]
no_license
# First Arg: path to directory with video files # Second Arg: output path # python imgToVideo.py ~/Devel/data_link/FZI_crossing/beginning/ ~/Devel/data_link/FZI_crossing/FZI_Video.avi from os import listdir from os.path import isfile, join import cv2 import sys import os def imgToVideo(inputPath, outputPath): print("Start Conversion") # Read all images imgfiles = [f for f in listdir(inputPath) if isfile(join(inputPath, f)) and not f.endswith('txt')] images = sorted(imgfiles, key=lambda x: float(x.split(".png")[0].split("T")[1])) #print(images) #return # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(outputPath, fourcc, 20, (960, 540)) print("##### Total images: %s\n"%len(imgfiles)) print("##### Start video creation!") j = 1 for i in images: #print(i) img = cv2.imread(inputPath+i, -1) #print(img.shape) frame = cv2.resize(img, (960, 540)) print("%d: %s"%(j, i)) # write the frame out.write(frame) j += 1 # Release everything if job is finished out.release() cv2.destroyAllWindows() print("##### Finished!") # MAIN inputPath = sys.argv[1] outputPath = sys.argv[2] imgToVideo(inputPath, outputPath)
C++
UTF-8
815
3.4375
3
[]
no_license
#include "Complex.h" Complex::Complex() { this->real = 0; this->img = 0; } Complex::Complex(int real, int img) { this->real = real; this->img = img; } Complex Complex::Add(Complex c){ Complex res; res.real = this->real + c.real; res.img = this->img + c.img; return res; } /* Complex Complex::operator+(Complex c){ Complex res; res.real = this->real + c.real; res.img = this->img + c.img; return res; }*/ Complex operator+(Complex c1,Complex c2){ Complex temp; temp.real=c1.real+c2.real; temp.img=c1.img+c2.img; return temp; } ostream& operator<<(ostream &O, Complex &c){ O <<c.real <<" + i" <<c.img <<endl; return O; } void Complex::Display(){ cout <<this->real <<" + i" <<this->img <<endl; } Complex::~Complex() { //dtor }
Python
UTF-8
445
3.84375
4
[]
no_license
nums = [1, 2, 3, 4, 5] for e in nums: if e == 3: print('Found it!') break print(e) for e in nums: if e == 3: print('Found it!') continue #skips to the next iteration print(e) for i in range(1, 11): print(i) x = 0 while x < 10: print(x) x += 1 # fruits = ['apple', 'banana', 'orange'] # x = 0 # for fruit in range(len(fruits)): # print(fruits[x]) # x += 1
C
UTF-8
419
3
3
[]
no_license
#include <stdio.h> #include <unistd.h> #include <wait.h> #include <sys/errno.h> int main() { int status; pid_t pid; printf("Hello\n"); pid = fork(); printf("%d\n",!pid); if(pid != 0){ if(waitpid(-1,&status,0) > 0){ if(WIFEXITED(status) != 0){ printf("parent = %d\n",WEXITSTATUS(status)); } } } printf("Bye\n"); _exit(2); }
SQL
UTF-8
218
2.71875
3
[]
no_license
create table IF NOT EXISTS student ( id bigint primary key AUTO_INCREMENT, name varchar(255) not null, passport_number varchar(255) not null, modified TIMESTAMP AS CURRENT_TIMESTAMP, primary key(id) );
Markdown
UTF-8
10,948
3.078125
3
[]
no_license
--- layout: post title: "Physics" description: "Collision Demo" date: 2019-2-18 categories: image: /assets/Collision/Screenshot_1.png --- All references links are still pending to add. <iframe width="100%" height="315" src="https://www.youtube.com/embed/EDhVRpYAZzA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> Used CPU: Ryzen 7 2700x ## Pre-calculating potential expensive operations. An specific struct has been added to store all the possible expensive values such as all the normals of the triangles, to avoid calculate them on each iteration. Also, when the heightmap is loaded, a Bounding Volume Hierarchy is generated, to speed up the triangle detection with all the spheres. It contains all the triangles of the heightmap, and, as it is static, is generated once, and prepared using a specific order to make the checking as fast as possible. The order is a depth-first search order, but per each node, add the next node in case checking the current one, results in a fail, and create a vector with all this information. ![My helpful screenshot](/assets/Collision/Screenshot_2.png) This way, if we test the node number 1 and its checking is right, if we increment the variable used as an index, we access the number 2, but if node number 1 fails, we can access directly to the number 4. That way, all the information is contiguous in memory, and any single jump with pointers is performed. The iteration method is a while loop with no conditions, increment an index in case we hit a right value, and ask for the next one if we fail if the current index is 0xffffffff we break the whole tree and exit. ![My helpful screenshot](/assets/Collision/Screenshot_3.png) The same patterns have been used to speed up the sphere against sphere collision check, regenerating a BVH for all the spheres being updated, but it takes more time to use the BVH hierarchy for this purpose, if all the spheres are close to each other’s, only works if the geometry is split up around the world, because it will discard unnecessary collisions faster. Even adding the cost of regenerating the tree and transforming it into a vector. Another algorithm, using a stack to check collisions is also provided, but as it is slower, is not been used, and the default enabled is the brute force method, checking every single sphere against the rest of them. All this was pre-computed following some raytracing optimizations, as said in (Wald, Boulos, and Shirley es) paper, considering the percentage of geometry that is completely static, can be completely prepared just once on load time, and reused each needed time. The iteration algorithm is inspired by the (Laine,Samuli), on the paper “Restart Trail for stackless BVH traversal”, where a stackless algorithm is proposed, and the main ideas are implemented. The main collision algorithms that are used, are from the book “Realtime Collision Detection” of (Ericson ), including sphere triangle, and capsule sphere. Also, the BVH construction algorithm is also inspired by the (Wald et al. es) BVH explanation on the paper “Ray Tracing Deformable Scenes using Dynamic Bounding Volume Hierarchies.” ## Simple Class Structure The main class is called SimpleSphere, it represents what it might be called GameObject. Is the Node that joins all the components that have been created for this demo purpose, following the Entity/System/Component structure. Meaning we have containers of data, all the systems created, and the executors of this data, the classes that these systems contain. ![My helpful screenshot](/assets/Collision/Screenshot_4.png) All systems have a templated parent class created to make a new system easier, and all the components that contain derive from the same class, so all of them have a proper ID variable and access to the owner of themselves. Following the design proposed by (Mike Acton ). All the systems deal with each update for their components. ![My helpful screenshot](/assets/Collision/Screenshot_5.png) ##### Transform System and Transform: Deals with all the information and operations regarding position, rotation, and scaling. Although the only scale and position are being implemented in the collision system. ##### Physics System and Physics: Deals with all the collision detection and collision resolution methods, following a pipeline, step by step order. ##### Collider System and Collider: Represents the collider of each entity, and is the component that adjusts the position, scale and rotation of all the AABB used, and the Capsule information used. A couple of custom classes that act like helpers have been also created, just to deal with all the BVH information, that way we also have **BasicBVHNode** that deals with all the pointers of the tree, and the class used in the vector called GPUBasicBVHNode, making sure is rightly padded. The default functions for dealing with the ray-triangle, have been replaced. In the case the sphere is moving below a certain speed,it makes use of a more simple triangle – Sphere detection. So the heightmap class allow us to choose with comparison method used. (ray - triangle or Sphere - triangle) Also, some helper classes to store the collision impact data has been used. ## Physics System. The main task, it is almost performed on the Physics System class, and on the Physics class. As said early, it follows a step by step division, that means, instead of detecting and solving possible collisions, one by one, All the work is divided into 4 steps: 1. Checking for possible collisions: * Here the order does not really matter, as we are not updating any variable like position, radius… We are checking if any sphere is colliding with the heightmap and storing the data of the collision. * Then we perform the same operation, but with all the spheres. 2. All possible collisions are resolved, first spheres against spheres, and then spheres against heightmap. 3. All physics objects are updated, meaning that all positions are calculated using a simple Uniform Accelerated Rectilinear Movement equation. 4. Finally, we perform a test to solve the penetration of the spheres and avoid the sinking effect. Any sphere overlapping the plane or another sphere. Overwriting the last position the sphere had. For the collision detection we are using the BVH of the heightmap for the sphere against the plane, and depending on the selected option, the brute force or the BVH of the spheres, to solve the sphere against sphere. The collision resolution is performed as precise as possible, meaning we are using the radius of the sphere, mass of each object, friction, and Coefficient of Restitution. ![My helpful screenshot](/assets/Collision/Screenshot_6.png) The Updating step is performed using this formula, being V the current velocity of the sphere, T the delta time multiplied by the dilated time, A the acceleration of the sphere. The main problem is how to avoid the sphere going through another sphere or the heightmap, because of the speed, to avoid this, the capsule against AABB and capsule against capsule have been implemented, meaning that if any sphere is going fast, its collision method detection is going to be replaced, depending on the velocity of each object. Currently supports: * A slow sphere moving towards a fast-moving sphere. * Both spheres moving slow. * Slow Sphere against triangle of the heightmap. * A fast sphere against the plane. When the sphere is going at a high speed, and it needs the capsule to detect collisions, one AABB is generated containing the capsule, and is sent to the heightmap BVH to be tested, if any triangle success, a ray is sent, following the segment of the capsule, and is checked the impact point with the radius of the capsule, resulting or not on a collision. As (Szauer ) stated in the book “Game Physics Cookbook”, the first thing we do is find the relative velocity between the two rigid bodies. If the rigid bodies are moving apart from each other, we stop the function, as no collision occurs. This is performed using a simple dot product between the normal of the impact, being the vector obtained with the positions of both spheres, and the relative velocity of the spheres. Pointing to the same direction. Then (Szauer ) propose a method to calculate the magnitude of the impulse vector, to resolve the collision. Using the minimum coefficient of restitution of both spheres. And apply it to both spheres, one being an addition, and the other one the opposite vector. After applying the linear impulse, (Szauer )propose to implement a friction calculation, as said on its book “Game Physics Cookbook”, To apply friction, we first find a vector tangential to the collision normal, once the tangential vector is found, we have to find ‘it’, the magnitude of the friction we are applying to this collision. We need to clamp the magnitude between ‘-j * friction’ and ‘j * friction’. This property is called Coulomb’s Law. With this vector we can overwrite the velocity we already write to each sphere, again adding it to our velocity vector. The same method is used to solve the collision between the plane and the sphere, but assuming the heightmap is static, its velocity is zero, and it has infinite mass, its mass is zero. Also, is important to consider, that every step is parallelized. What means that for example, when we are calculating all possible collisions, we are reading information, but not writting on the used Physics component, what means that we can perform the detection between spheres and the plane, and the spheres against other spheres, at the same time. That way, if processing the plane takes 1 millisecond, and processing the spheres 2 milliseconds, we are not waiting 3 milliseconds, we saved 1 millisecond, and spent 2 calculating everything. Another key point, is that the collision resolution between spheres and the plane is stored on a vector of possible hitresults, so this step can be also performed across all possible threads, what allows this demo to easily handle 4000 spheres at the same time, and colliding all of them against the plane. Making use of the BVH iteration across all threads again, as is static can also increase the perfomance. ## Works Cited Ericson, Christer. Real-Time Collision Detection. 1st ed. CRC Press, 2004. Web. Unity at GDC - A Data-Oriented Approach to using Component Systems. Dir. Mike Acton. Perf. Mike Acton. Unity, 2018. Youtube. Szauer, Gabor. Game Physics Cookbook. 1st ed. Packt Publishing, 2017. Web. Wald, Ingo, Solomon Boulos, and Peter Shirley. "Ray Tracing Deformable Scenes using Dynamic Bounding Volume Hierarchies." ACM Transactions on Graphics (TOG) 26.1 (2007): es. Web. Samuli Laine, NVIDIA Research, “Restart Trail for stackless BVH traversal”, Web
Java
UTF-8
14,157
1.875
2
[]
no_license
package lx.gs.leaderboard; import cfg.CfgMgr; import cfg.Const; import cfg.bonus.RankType; import common.RefObject; import gnet.link.Onlines; import gs.FixedPriorityQueue; import lx.gs.event.EventModule; import lx.gs.event.RankingRefreshEvent; import lx.gs.family.FFamilyModule; import lx.gs.leaderboard.msg.BoardEntry; import lx.gs.leaderboard.msg.BoardInfo; import lx.gs.leaderboard.msg.SRoleRanking; import lx.gs.leaderboard.msg.SYesterdayRanking; import lx.gs.logger.FLogger; import xbean.BoardRecordEntry; import xbean.Pod; import xdb.Procedure; import xdb.Trace; import xtable.Family; import xtable.Leaderboardrecord; import xtable.Leaderboards; import xtable.Roleinfos; import java.util.*; import java.util.stream.Collectors; /** * @author Jin Shuai */ public class FLeaderBoard { protected static void recordByType(int type, long id, long val1) { if (type == RankType.CLIMB_TOWER) { throw new IllegalArgumentException("call method recordClimbTower()"); } Map<Integer, BoardRecordEntry> recordMap = getRecordById(id).getRecords(); if (!recordMap.containsKey(type)) { BoardRecordEntry entry = Pod.newBoardRecordEntry(); entry.setUpdatetime(System.currentTimeMillis()); recordMap.putIfAbsent(type, entry); } BoardRecordEntry entry = recordMap.get(type); if (val1 > entry.getVal1()) { entry.setVal1(val1); entry.setUpdatetime(System.currentTimeMillis()); } } protected static void recordClimbTower(long roleId, long val1, int val2) { int type = RankType.CLIMB_TOWER; Map<Integer, BoardRecordEntry> recordMap = getRecordById(roleId).getRecords(); if (!recordMap.containsKey(type)) { BoardRecordEntry entry = Pod.newBoardRecordEntry(); entry.setUpdatetime(System.currentTimeMillis()); recordMap.putIfAbsent(type, entry); } BoardRecordEntry entry = recordMap.get(type); if (val2 <= 0) { Trace.error("climb tower time can't less than 1, roleid:{}, floor:{}, time:{}", roleId, val1, val2); return; } if (val1 > entry.getVal1() || (entry.getVal1() == val1 && val2 < entry.getVal2())) { entry.setVal1(val1); entry.setVal2(val2); entry.setUpdatetime(System.currentTimeMillis()); } } private static xbean.BoardRecord getRecordById(long id) { xbean.BoardRecord record = Leaderboardrecord.get(id); if (record == null) { record = Pod.newBoardRecord(); Leaderboardrecord.add(id, record); } return record; } private static xbean.BoardInfo getDbBoardByType(int type) { xbean.BoardInfo boardInfo = Leaderboards.get(type); if (boardInfo == null) { boardInfo = Pod.newBoardInfo(); Leaderboards.add(type, boardInfo); } return boardInfo; } protected static BoardInfo getBordByType(int type) { BoardInfo boardInfo = new BoardInfo(); new Procedure() { @Override protected boolean process() throws Exception { int entryNum = CfgMgr.rank.get(type).showsize; for (xbean.BoardEntry entry : Leaderboards.select(type).getLatestboard().values()) { BoardEntry boardEntry = convert(entry); if (type == RankType.FAMILY) { boardEntry.id = Family.selectChiefid(entry.getId()); } boardInfo.info.add(boardEntry); if (boardInfo.info.size() >= entryNum) { break; } } return true; } }.call(); return boardInfo; } private static BoardEntry convert(xbean.BoardEntry entry) { return new BoardEntry(entry.getId(), entry.getName(), entry.getVal1(), entry.getVal2()); } protected static void refreshBoardByType(int type) { new Procedure() { @Override protected boolean process() throws Exception { Map<Long, BoardRecordEntry> history = new HashMap<>(); Leaderboardrecord.getTable().walk((aLong, record) -> { BoardRecordEntry recordEntry = record.getRecords().get(type); if (recordEntry != null) { history.put(aLong, recordEntry); } return true; }); xbean.BoardInfo boardInfo = getDbBoardByType(type); boardInfo.setLastupdatetime(System.currentTimeMillis()); int rankNum = CfgMgr.rank.get(type).ranksize; /** 小值在前 */ Comparator<CompareObj> comparator = (o1, o2) -> { int ret = Long.compare(o1.val1, o2.val1); //值小的在前面(战力,等级等) if (ret == 0 && type == RankType.CLIMB_TOWER) { //爬塔榜还需要计算时间 ret = Integer.compare(o1.val2, o2.val2) * -1; // 时间用的多的在前面 } return ret != 0 ? ret : Long.compare(o1.updateTime, o2.updateTime) * -1; // 记录晚的在前面 }; FixedPriorityQueue<CompareObj> compareQueue = new FixedPriorityQueue<>(rankNum, comparator); List<xbean.BoardEntry> boardData = new LinkedList<>(); Map<Long, CompareObj> compareObjMap = new HashMap<>(); history.forEach((id, record) -> { CompareObj compareObj = new CompareObj(record); if (rankNum >= history.size() || compareQueue.offer(compareObj)) { xbean.BoardEntry boardEntry = Pod.newBoardEntry(); boardEntry.setRanking(0); boardEntry.setName(""); boardEntry.setId(id); boardEntry.setVal1(record.getVal1()); boardEntry.setUpdatetime(record.getUpdatetime()); boardEntry.setVal2(record.getVal2()); boardData.add(boardEntry); compareObjMap.put(boardEntry.getId(), compareObj); } }); Map<Integer, xbean.BoardEntry> latestboard = boardInfo.getLatestboard(); Map<Long, Integer> roleRank = boardInfo.getRolerank(); latestboard.clear(); roleRank.clear(); int ranking = 1; Collections.sort(boardData, (o1, o2) -> comparator.compare(compareObjMap.get(o1.getId()), compareObjMap.get(o2.getId())) * -1); for (xbean.BoardEntry entry : boardData) { entry.setRanking(ranking); latestboard.put(ranking, entry); roleRank.put(entry.getId(), ranking); ranking++; } if (type == RankType.FAMILY) { LeaderBoardModule.familyRankMap = boardInfo.getLatestboard().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getId())); } return true; } }.call(); // 先把名次排好,在把名字一一取出来再放进去,以免死锁 Map<Long, String> id2Name = new HashMap<>(); new Procedure() { @Override protected boolean process() throws Exception { Leaderboards.select(type).getRolerank().keySet().forEach(aLong -> id2Name.put(aLong, type == RankType.FAMILY ? Family.selectFamilyname(aLong) : Roleinfos.selectName(aLong))); return true; } }.call(); new Procedure() { @Override protected boolean process() throws Exception { getDbBoardByType(type).getLatestboard().values() .forEach(entry -> entry.setName(id2Name.getOrDefault(entry.getId(), ""))); return true; } }.call(); } public static void syncRanking(long roleid) { SRoleRanking sRoleRanking = new SRoleRanking(); LeaderBoardModule.INSTANCE.getRankType().forEach(type -> sRoleRanking.info.put(type, getRankingById(roleid, type))); Onlines.getInstance().send(roleid, sRoleRanking); } public static void syncYesterdayRanking(long roleid) { SYesterdayRanking ret = new SYesterdayRanking(); LeaderBoardModule.INSTANCE.getRankType().forEach(type -> ret.info.put(type, getYesterdayRanking(roleid, type))); Onlines.getInstance().send(roleid, ret); EventModule.INSTANCE.broadcastEvent(new RankingRefreshEvent(roleid, ret.info)); } public static int getRankingById(long id, int rankType) { RefObject<Integer> ret = new RefObject<>(Const.NULL); new Procedure() { @Override protected boolean process() throws Exception { ret.value = Leaderboards.select(rankType).getRolerank().getOrDefault(id, Const.NULL); return true; } }.call(); return ret.value; } public static int getYesterdayRanking(long id, int rankType) { RefObject<Integer> ret = new RefObject<>(Const.NULL); new Procedure() { @Override protected boolean process() throws Exception { ret.value = getDbBoardByType(rankType).getYesterdayrank().getOrDefault(id, Const.NULL); return true; } }.call(); return ret.value; } public static void removeRecord(long id, int rankType) { getRecordById(id).getRecords().remove(rankType); } public static Map<Integer, xbean.BoardEntry> getLatestboard(int rankType) { return getDbBoardByType(rankType).getLatestboard(); } /** * 获取家族排名 * * @param from * @param length 长度 * @return */ public static List<Long> getFamilyIdByRanking(int from, int length) { final Map<Integer, Long> ranks = LeaderBoardModule.familyRankMap; List<Long> ret = new ArrayList<>(); for (int i = from, n = Math.min(from + length-1, ranks.size()); i <= n ; i++) { ret.add(ranks.get(i)); } return ret; } public static void recordYesterdayRanking() { LeaderBoardModule.INSTANCE.championRoleIds.clear(); LeaderBoardModule.INSTANCE.getRankType().forEach(type -> { RefObject<Long> id = new RefObject<Long>(Long.valueOf(Const.NULL)); new Procedure() { @Override protected boolean process() throws Exception { xbean.BoardInfo boardInfo = getDbBoardByType(type); if(LeaderBoardModule.INSTANCE.broadcastBoards.containsKey(type)){ xbean.BoardEntry boardEntry = boardInfo.getLatestboard().get(1); if(boardEntry != null){ id.value = boardEntry.getId(); } } Map<Long, Integer> yest = boardInfo.getYesterdayrank(); yest.clear(); yest.putAll(boardInfo.getRolerank()); return true; } }.call(); if(type == RankType.FAMILY && id.value != Const.NULL){ new Procedure() { @Override protected boolean process() throws Exception { Long temp = Family.selectChiefid(id.value); id.value = temp == null ? Const.NULL : temp; return true; } }.call(); } if(id.value != Const.NULL){ LeaderBoardModule.INSTANCE.championRoleIds.put(type, id.value); } }); // 给运营记录日志 recordLog(); } private static void recordLog() { try { final int logCount = 100; LeaderBoardModule.INSTANCE.getRankType().stream() .forEach(type -> new Procedure() { @Override protected boolean process() throws Exception { xbean.BoardInfo boardInfo = Leaderboards.select(type); Map<Integer, xbean.BoardEntry> latest = boardInfo.getLatestboard(); boardInfo.getYesterdayrank().forEach((id, rank) -> { if (rank > 0 && rank <= logCount) { if (type == RankType.FAMILY) { FLogger.familyRank(id, rank); } else { FLogger.nomarlRank(id, Roleinfos.select(id), type, rank, latest.get(rank).getVal1()); } } }); return true; } }.call()); } catch (Exception e){ Trace.error("record leaderboard log error", e); } } static class CompareObj { private long val1; private int val2; private long updateTime; public CompareObj(BoardRecordEntry record) { this.val1 = record.getVal1(); this.val2 = record.getVal2(); this.updateTime = record.getUpdatetime(); } } }
C#
UTF-8
1,365
2.703125
3
[]
no_license
using GoogleEarthConversions.Core.KML.Geometry.Attributes; using Xunit; namespace GoogleEarthConventions.Tests.KML.Geometry.Attributes { public class AltitudeModeTests { [Fact] public void AltitudeMode_CanInstantiate() { var sut = new AltitudeMode(); Assert.NotNull(sut); } [Fact] public void AltitudeMode_AllPropertiesInitialised() { var sut = new AltitudeMode(); foreach (var prop in sut.GetType().GetProperties()) { var value = prop.GetValue(sut); Assert.NotNull(value); } } [Theory] [InlineData(AltMode.ClampToGround, "")] [InlineData(AltMode.RelativeToGround, "<altitudeMode>relativeToGround</altitudeMode>")] [InlineData(AltMode.Absolute, "<altitudeMode>absolute</altitudeMode>")] [InlineData(AltMode.ClampToSeaFloor, "<gx:altitudeMode>clampToSeaFloor</gx:altitudeMode>")] [InlineData(AltMode.RelativeToSeaFloor, "<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>")] public void AltitudeMode_CorrectlyConvertsToKML(AltMode value, string expected) { var sut = new AltitudeMode(value); var result = sut.SerialiseToKML(); Assert.Equal(expected, result); } } }
Shell
UTF-8
453
3.265625
3
[ "MIT", "Apache-2.0" ]
permissive
#!/usr/bin/env bash # Stop script on NZEC set -e # Stop script if unbound variable found (use ${var:-} if intentional) set -u channel=$1 curl -SLo dotnet-monitor.nupkg.version https://aka.ms/dotnet/diagnostics/monitor$channel/dotnet-monitor.nupkg.version # Read version file and remove newlines monitorVer=$(tr -d '\r\n' < dotnet-monitor.nupkg.version) rm dotnet-monitor.nupkg.version echo "##vso[task.setvariable variable=monitorVer]$monitorVer"
Markdown
UTF-8
1,500
2.625
3
[]
no_license
# Unsupervised Learning Investigation - Clustering - for discrete problems - Used more than it should be because people assume an underlying domain has discrete classes in it. In reality data is continuous. - **K-means Clustering:** NP-hard problem, based on Euclidean distance. Algorithm Steps: a) Find the closest cluster center b) Recompute the cluster centroid. Solution isn't optimal. - **DBSCAN:** performs density-based clustering, follows the shape of neighborhood of points. - Regressions - **Matrix Factorization:** model has more degrees of freedom than we have data. (Topic Modeling). From a factorization we can fill in missing values (Matrix Completion). Can be used with stochastic gradient descent. Issue with SGD is the local optima problem, where convergence happens in a local minima. Use MCMC (Markov-chain Monte-Carlo to reduce local optima issue, sometime method moves against the gradient. MCMC is the most accurate method for matrix factorization right now). - Latent Semantic Indexing (LSI): identifies on words and phrases that occur frequently with each other - Latent Derilicht Allocation - Probabilistic latent semantic analysis Can be used to extract topics from the text Could be used to summarize a task Text Categorization https://medium.com/ml2vec/topic-modeling-is-an-unsupervised-learning-approach-to-clustering-documents-to-discover-topics-fdfbf30e27df https://medium.com/@fatmafatma/industrial-applications-of-topic-model-100e48a15ce4
Python
UTF-8
2,669
2.84375
3
[]
no_license
import os import sys import time def rw_single(input_path, output_path, results_file): input_file=open(input_path, 'rb') output_file=open(output_path, 'wb') #READ start=time.clock_gettime(time.CLOCK_REALTIME) data=input_file.read() os.fsync(input_file) input_file.close() end=time.clock_gettime(time.CLOCK_REALTIME) results_file.write(str(end-start)+",") new_data=os.urandom(len(data)) #WRITE TO NEW FILE start=time.clock_gettime(time.CLOCK_REALTIME) output_file.write(new_data) os.fsync(output_file) output_file.close() end=time.clock_gettime(time.CLOCK_REALTIME) results_file.write(str(end-start)+",") #WRITE TO EXISTING FILE output_file=open(input_path, 'wb') new_data=os.urandom(len(data)) start=time.clock_gettime(time.CLOCK_REALTIME) output_file.write(new_data) os.fsync(output_file) output_file.close() end=time.clock_gettime(time.CLOCK_REALTIME) results_file.write(str(end-start)+",") def rw_multi(input_path, output_path, results_file, num_files): data=[] #READ start=time.clock_gettime(time.CLOCK_REALTIME) for i in range(num_files): input_file=open(input_path+"_"+str(i), 'rb') data.append(input_file.read()) os.fsync(input_file) input_file.close() end=time.clock_gettime(time.CLOCK_REALTIME) results_file.write(str(end-start)+",") #WRITE TO NEW FILE start=time.clock_gettime(time.CLOCK_REALTIME) for i in range(num_files): output_file=open(output_path+"_"+str(i), 'wb') output_file.write(data[i]) os.fsync(output_file) output_file.close() end=time.clock_gettime(time.CLOCK_REALTIME) results_file.write(str(end-start)+",") #WRITE TO EXISTING FILE #modified_data=os.urandom(len(data[0])) start=time.clock_gettime(time.CLOCK_REALTIME) for i in range(num_files): output_file=open(input_path+"_"+str(i), 'wb') output_file.write(data[i]) os.fsync(output_file) output_file.close() end=time.clock_gettime(time.CLOCK_REALTIME) results_file.write(str(end-start)+",") if len(sys.argv)<6: print("Usage: read_write_benchmark.py <Input file> <Output file> <Input file small> <Output file small> <Results file>") results_file = open(sys.argv[5], 'a') results_file.write("\n") results_file.write("Read time 1GB,Write time 1GB unmodified,Write time 1GB modified,\ Read time 10*100MB,Write time 10*100MB unmodified,Write time 10*100MB modified,\ Read time 100MB,Write time 100MB unmodified,Write time 100MB modified\n") #1GB rw_single(sys.argv[1], sys.argv[2], results_file) #100MB*10 rw_multi(sys.argv[3], sys.argv[4], results_file, 10) #100MB rw_single(sys.argv[3]+"_10", sys.argv[4]+"_10", results_file) print("Resolution: "+str(time.clock_getres(time.CLOCK_REALTIME))+"s")
Java
UTF-8
2,974
3.0625
3
[]
no_license
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.IntToDoubleFunction; import java.util.function.LongToDoubleFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; public class Chromosome implements Comparable<Chromosome> { public static final int CHROMOSOME_SIZE = 6; public static final double CROSSOVER_RATE = 0.5; public static final double AVERAGE_RATE = 0.5; public static final double MUTATION_RATE = 0.05; public static final int FITNESS_EVALUATIONS = 1; public static final double PERTERB_RANGE = 1; private List<Double> genes; private double fitness = -1; public Chromosome() { genes = IntStream.range(0, CHROMOSOME_SIZE).boxed() .map(i -> (new Random()).nextGaussian()*PERTERB_RANGE) .collect(Collectors.toList()); } public Chromosome(Chromosome p1, Chromosome p2) { genes = new ArrayList<>(); double random = Math.random(); if (random < CROSSOVER_RATE) { // Random crossover for (int i = 0; i < CHROMOSOME_SIZE; i++) { if (Math.random() < 0.5) { genes.add(p1.getGenes().get(i)); } else { genes.add(p2.getGenes().get(i)); } } } else if (random - CROSSOVER_RATE < AVERAGE_RATE) { // Average crossover genes.addAll(IntStream.range(0, CHROMOSOME_SIZE) .mapToDouble(i -> (p1.getGenes().get(i)+ p2.getGenes().get(i))) .boxed().collect(Collectors.toList())); } else { genes.addAll(p1.genes); } } public Chromosome crossover(Chromosome other) { return (new Chromosome(this, other)).mutate(); } private Chromosome mutate() { for (int i=0; i<genes.size(); i++) { if (Math.random() < MUTATION_RATE) { genes.set(i, genes.get(i) + (new Random()).nextGaussian()*PERTERB_RANGE); } } return this; } @Override public int compareTo(Chromosome o) { return Double.compare(this.getFitness(), o.getFitness()); } public double getFitness() { return fitness; } public void evaluateFitness(long seed) { LongToDoubleFunction fitnessEvaluator = i -> { TetrisState s = new TetrisState(this, i); while (!s.hasLost()) { s.makeMove(s.getBestMove()); } return s.getRowsCleared(); }; Random seededRandom = new Random(seed); fitness = LongStream.range(0, FITNESS_EVALUATIONS) .map(i -> seededRandom.nextLong()) .parallel() .mapToDouble(fitnessEvaluator) .average().orElse(0); } public List<Double> getGenes() { return genes; } }
C++
UTF-8
5,162
2.5625
3
[]
no_license
// Server side C/C++ program to demonstrate Socket programming #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <iostream> #include <arpa/inet.h> #include <unordered_map> #include <sstream> #include <vector> #include <thread> #define PORT 8080 using namespace std ; unordered_map <string,string> details ; void shareproc(int new_socket,string filp) { //recv(new_socket,buffer.c_str(),512000,0) ; char buffer[512000] ; read(new_socket,buffer,512000) ; string temp = buffer ; string temp1,temp2 ; //char tempv[512], tempv1[512] ; stringstream s; s << temp ; s>>temp ; if(temp.compare("share") == 0) { s>>temp; s>>temp1 ; s>>temp2 ; //cout<<"Hello"<<endl ; // cout<<temp<<endl<<temp1<<endl<<temp2<<endl ; FILE *fp = fopen(filp.c_str(),"a+") ; string temp3 = temp + temp1 ; if(details.find(temp3) == details.end()) { details[temp3] = temp2 ; fprintf(fp,"%s\n%s\n%s\n",temp.c_str(),temp1.c_str(),temp2.c_str()) ; } memset(buffer,0,sizeof(buffer)) ; fclose(fp) ; } // else if(temp.compare("get") ==0) // { // string hashish // s>>hashish ; // int len = details[hashish].size() ; // for(int i = 0 ; i < len; i++) // { // cin>> // send(new_socket,) // } // } else if(temp.compare("remove") == 0) { string hashish ; string clip ; s>>hashish ; s>>clip ; // char a[512000] ; string temp3 = hashish+clip ; details.erase(temp3) ; FILE *fp ; remove(filp.c_str()) ; fp = fopen(filp.c_str(),"w") ; for(auto i = details.begin(); i!= details.end(); i++) { fprintf(fp,"%s\n%s\n%s\n",i->first.substr(0,39).c_str(),i->first.substr(40,i->first.length()).c_str(),i->second.c_str() ); } // send(new_socket,buffer,40,0) ; fclose(fp) ; } else if(temp.compare("get") == 0) { cout<<"Hello" ; string hashish ; s>>hashish ; char *tv = new char[52223]; cout<<hashish<<endl ; // for(auto i = details.begin(); i!=details.end(); i++) // { // if(i->first.substr(0,39).compare(hashish) == 0) // { // // send(new_socket,i->first.substr(40,i->first.length()).c_str(),40,0) ; // //tosend = tosend + " " + i->first.substr(40,i->first.length()) + " " + i->second ; // cout<<"Hello"<<endl ; // } // } FILE *fp = fopen(filp.c_str(),"r") ; while(!feof(fp)) { fscanf(fp,"%s\n",tv) ; if(hashish.compare(tv) == 0){ fscanf(fp,"%s\n",tv) ; send(new_socket,tv,strlen(tv),0) ; // fscanf(fp,"%s\n",tv) ; // send(new_socket,tv,strlen(tv),0) ; } } fclose(fp) ; } } int main(int argc, char const *argv[]) { FILE *fp4 = fopen(argv[1],"w+") ; fclose(fp4) ; FILE *fp3 = fopen(argv[1],"r") ; while(!feof(fp3)) { char temp[512],temp1[512],temp2[5120] ; fscanf(fp3,"%s\n%s\n%s\n",temp,temp1,temp2) ; strcat(temp,temp1) ; if(!details[temp].empty()) details[temp] = temp2 ; } fclose(fp3) ; int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; char buffer[512000] ; int addrlen = sizeof(address); // Creating socket file descriptor int count = 0 ; if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, 1,&opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons( PORT ); // Forcefully attaching socket to the port 8080 if (::bind(server_fd, (struct sockaddr *)&address,sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } while(1){ if ((new_socket = accept(server_fd, (struct sockaddr *)&address,(socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } thread t {shareproc,new_socket,argv[1]} ; t.detach() ; } return 0; }
Java
UTF-8
383
3.03125
3
[]
no_license
package com.javacore; public class MySecondClass { public static void main(String[] args) { MyClass myClass = new MyClass("Neelam"); String name = myClass.getName(); System.out.println("Hi "+name+". How are you?"); MyClass myClass2 = new MyClass(); String returnValue = myClass2.testAndProvideOutput("X", "Z"); System.out.println(returnValue); } }
JavaScript
UTF-8
6,029
2.5625
3
[]
no_license
var watson = require('watson-developer-cloud'); var fs = require('fs'); var mic = require('mic'); var Forecast = require('forecast'); var wav = require('wav'); var Speaker = require('speaker'); var Sound = require('node-aplay'); var Q = require('q'); var moment = require('moment'); var forecastKey = process.env.FORECAST_KEY; var speechToTextUsername = process.env.STT_USERNAME; var speechToTextPassword = process.env.STT_PASSWORD; var textToSpeechUsername = process.env.TTS_USERNAME; var textToSpeechPassword = process.env.TTS_PASSWORD; var forecast = new Forecast({ service: 'forecast.io', key: forecastKey, units: 'celcius', // Only the first letter is parsed cache: true, // Cache API requests? ttl: { // How long to cache requests. Uses syntax from moment.js: http://momentjs.com/docs/#/durations/creating/ minutes: 27, seconds: 45 } }); var micInstance = mic({ 'rate': '44100', 'channels': '1', 'debug': true, exitOnSilence: 10 }); var micInputStream = micInstance.getAudioStream(); var outputFileStream = fs.WriteStream('command.wav'); var speech_to_text = watson.speech_to_text({ password: speechToTextPassword, username: speechToTextUsername, version: 'v1' }); var text_to_speech = watson.text_to_speech({ password: textToSpeechPassword, username: textToSpeechUsername, version: 'v1' }); micInputStream.pipe(outputFileStream); /** * PROCESS INCOMING COMMANDS */ var contextCommand; micInputStream.on('data', function(data) { console.log("Recieved Input Stream: " + data.length); }); micInputStream.on('error', function(err) { console.log("Error in Input Stream: " + err); }); micInputStream.on('startComplete', function() { console.log("Got SIGNAL startComplete"); }); micInputStream.on('pauseComplete', function() { console.log("Got SIGNAL pauseComplete"); var params = { audio: fs.createReadStream('./command.wav'), content_type: 'audio/l16; rate=44100' }; speech_to_text.recognize(params, function(err, res) { if (err) { console.log(err); return; } if (!res.results[0]) { return; } if (res.results[0].alternatives.length > 1) { console.log('more than one alternative found!'); console.log(res.results[0].alternatives); } else { respond(res.results[0].alternatives[0].transcript) } micInstance.resume(); }); }); micInputStream.on('silence', function() { console.log("Got SIGNAL silence, stopping"); micInstance.pause(); }); micInputStream.on('processExitComplete', function() { console.log("Got SIGNAL processExitComplete"); }); /** * STARTUP */ var startupText = "Computer active, awaiting query." var startupTextParams = { text: startupText, voice: 'en-US_AllisonVoice', // Optional voice accept: 'audio/wav' }; // Pipe the synthesized text to a file var speechPipe = text_to_speech.synthesize(startupTextParams).pipe(fs.createWriteStream('./startup.wav')); speechPipe.on('finish', function () { var startupSound = new Sound('./startup.wav'); startupSound.play(); startupSound.on('complete', function () { console.log('sound played'); micInstance.start(); }); }); /** * RESPONSE */ function respond(text) { var trimmed = text.toLowerCase().trim(); console.log(trimmed); if (contextCommand) { return processContextCommand(trimmed); } if (trimmed.indexOf('weather') > -1) { return processWeather(trimmed); } if (trimmed.indexOf('create') > -1) { return processCreate(trimmed); } return processUnknown(trimmed); } function processUnknown(text) { var deferred = Q.defer(); var response = "Unknown command: " + text; processResponse(response).then(function () { deferred.resolve(); }); return deferred.promise; } function processContextCommand(trimmed) { if (contextCommand == 'newNote') { return createNewNote(trimmed); } } function processCreate(text) { if (text.indexOf('note') > -1) { return processTextDirectory('~/notes', text); } } function processTextDirectory(path, text) { if (text.indexOf('create') > -1) { contextCommand = 'newNote'; var now = moment(); return processResponse("Creating new note for " + buildSpokenDate()); } } function processWeather(text) { var deferred = Q.defer(); var response; forecast.get([40.7128, 74.0059], function (err, weather) { if (err) { deferred.reject(err); return; } //console.log(weather); if (text.indexOf('today') > -1) { console.log('today is present'); response = weather.daily.summary; } console.log(response); processResponse(response).then(function () { deferred.resolve(); }); }); return deferred.promise; } function processResponse(text) { var deferred = Q.defer(); var responseTextParams = { text: text, voice: 'en-US_AllisonVoice', // Optional voice accept: 'audio/wav' }; // Pipe the synthesized text to a file var responseStream = text_to_speech.synthesize(responseTextParams).pipe(fs.createWriteStream('response.wav')); responseStream.on('finish', function () { var startupSound = new Sound('response.wav'); startupSound.play(); startupSound.on('complete', function () { deferred.resolve(); }); }); return deferred.promise; } function createNewNote(text) { var deferred = Q.defer(); var fileName = "~/notes/" + buildReadableDate() + ".txt"; fs.writeFile(fileName, text, function (err) { if (err) { deferred.reject(err); } processResponse("Note saved.").then(function () { clearContext(); deferred.resolve(); }); }); return deferred.promise; } function buildSpokenDate() { var now = moment(); return now.format("MMMM") + " " + now.format("Do") + " " + now.format("YYYY"); } function buildReadableDate() { var now = moment(); return now.format("MM") + " " + now.format("DD") + " " + now.format("YYYY"); } function clearContext() { commandContext = null; }
C#
UTF-8
976
2.875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MoviesSite.Models { public class Actor { private ICollection<Movie> maleMovies; private ICollection<Movie> femaleMovies; public Actor() { this.maleMovies = new HashSet<Movie>(); this.femaleMovies = new HashSet<Movie>(); } [Key] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [Range(0, 100)] public int Age { get; set; } public bool Male { get; set; } public virtual ICollection<Movie> MaleMovies { get { return this.maleMovies; } set { this.maleMovies = value; } } public virtual ICollection<Movie> FemaleMovies { get { return this.femaleMovies; } set { this.femaleMovies = value; } } } }