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
JavaScript
UTF-8
3,697
3.21875
3
[ "MIT" ]
permissive
console.log('It works tho.') class Encounter{ constructor(name, description){ this.name = name this.description = description } } let button = document.getElementById('Engage'); console.dir(button) button.addEventListener('click', function (event) { let diceNumber = getRandomIntInclusive(1, 20); let randomEncounterValue = randomEncounters(diceNumber); let result = document.getElementById('The-Roll'); result.innerText = randomEncounterValue }); function getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } function terrainEncounters(roll) { const table = { 1: new Encounter('Boneyard', ` The characters come upon an eerie cavern littered with countless bones of various creatures. Whether the site is a natural graveyard for some Underdark species or the former lair of a fearsome predator, the characters can potentially gather useful material for crafting among the bones. When the party enters a boneyard, roll a d20 and consult the table to determine what creatures, if any are present. The undead rise up out of the bones and attack when the first characters are halfway across the cavern. `), 2: new Encounter('Cliff and ladder','No description yet'), 3: new Encounter('Crystal clusters','No description yet'), 4: new Encounter('Fungus cavern','No description yet'), 5: new Encounter('Gas leak','No description yet'), 6: new Encounter('Gorge','No description yet'), 7: new Encounter('High ledge','No description yet'), 8: new Encounter('Horrid sounds','No description yet'), 9: new Encounter('Lava swell','No description yet'), 10: new Encounter('Muck pit','No description yet'), 11: new Encounter('Rockfall','No description yet'), 12: new Encounter('Rope bridge','No description yet'), 13: new Encounter('Ruins','No description yet'), 14: new Encounter('Shelter','No description yet'), 15: new Encounter('Sinkhole','No description yet'), 16: new Encounter('Slime or mold','No description yet'), 17: new Encounter('Steam vent','No description yet'), 18: new Encounter('Underground stream','No description yet'), 19: new Encounter('Warning sign','No description yet'), 20: new Encounter('Webs','No description yet'), } return table[roll] } function randomEncounters(roll) { let diceNumber = getRandomIntInclusive(1, 20); let secondDiceNumber = getRandomIntInclusive(1, 20); if(roll < 14) { // noEncounter return 'No Encounter'; } else if(roll === 14 || roll === 15 ) { return terrainEncounters(diceNumber); } else if(roll === 16 || roll ===17) { // one or more creatures return creatureEncounters(diceNumber); } else { let monster = creatureEncounters(secondDiceNumber); let place = terrainEncounters(diceNumber); return `${monster} in ${place}`; // terrain encounter featuring one or more creatures } } function creatureEncounters(roll) { switch (true) { case roll === 1 || roll === 2 : return 'Ambushers'; // NOTE address that we need to reroll if characters are resting case roll === 3 : return 'Carrion Crawler'; case roll === 4 || roll === 5 : return 'Escaped Slaves'; case roll === 6 || roll === 7 : return 'Fungi'; case roll === 8 || roll === 9 : return 'Giant Fire Beetles'; case roll === 10 || roll === 11 : return 'Giant "Rocktopus"'; case roll === 12 : return 'Mad Creature'; case roll === 13 : return 'Ochre Jelly'; case roll === 14 || roll === 15 : return 'Raiders'; case roll === 16 : return 'Scouts'; case roll === 17 : return 'Society of Brilliance'; case roll === 18 : return 'Spore Servants'; default: return 'Traders'; } }
PHP
UTF-8
3,242
2.625
3
[ "MIT" ]
permissive
<?php namespace Api\Business; use Api\Helper\Mail; use Api\Model\ProductOrder; class ProductOrderBusiness extends Business { /** * get product order * @param $productId * @return mixed */ public static function productOrder($productId) { new static; $productOrders = ProductOrder::where('productid__c',$productId)->get(); return $productOrders->toArray(); } /** * get product order * @param $productOrderId * @return mixed */ public static function getProductOrderByNumber($productOrderNumber) { new static; $productOrder = ProductOrder::where('ordernumber__c', $productOrderNumber)->first(); if($productOrder) return $productOrder->toArray(); else return null; } /** * create new order from lead, product * @param $facebookId * @param $productId * @return bool */ public static function createOrder($facebookId, $productId) { new static; if ($facebookId == null || $productId == null) { return false; } $lead = LeadBusiness::getLeadByFacebookId($facebookId); $product = ProductBusiness::getProductById($productId); $promotion = PromotionBusiness::getPromotionByProductId($productId); if ($lead && $product) { $productOrder = New ProductOrder(); $productOrder->name = "Order". $product['name']; $productOrder->productid__c = $product['id']; $productOrder->leadid__c = $lead['id']; $productOrder->totalamount__c = $product['price__c']; $ordernumber = date('Y') . date('m') . random_int(100, 1000); $productOrder->ordernumber__c = $ordernumber; if ($promotion) { $productOrder->promotion__c = $promotion['sfid']; $discount = $promotion['discount__c']; } else { $discount = 0; } $productOrder->save(); if ($productOrder) { $fromEmail = getenv('PRIMARY_EMAIL_ADDRESS'); $subject = "Order Confirmation from Ebiz Solutions - Order No $ordernumber"; $toEmail = $lead['email']; $discountPrice = ($product['price__c'] * $discount)/100; $content['orderNumber'] = $ordernumber; $content['name'] = $lead['firstname']. " " .$lead['lastname']; $content['address'] = $lead['street']; $content['date'] = date('M d Y h:i:s'); $content['product'] = $product['name']; $content['price'] = $product['price__c']; $content['discount'] = $discount; $content['total'] = $product['price__c'] - $discountPrice; $body = Mail::renderOrder($content); try { Mail::sendMail($fromEmail, $subject, $toEmail, $body); return $ordernumber; } catch (\Exception $e) { return "Your order hasn't been sent"; } } } else { return false; } } }
Java
UTF-8
1,073
4.03125
4
[]
no_license
package com.SetJihe; import java.util.Comparator; import java.util.TreeSet; public class StuCompa { public static void main(String[] args) { //本例使用了匿名内部类实现类Comparator这个接口 // 然后,重载了compare方法 TreeSet<Student> tr=new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int num=o1.getAge()-o2.getAge(); int num2=num==0?o1.getName().compareTo(o2.getName()):num; return num2; } }); // CompareTo 是String里的方法 Student s1 = new Student(19, "小白"); Student s2 = new Student(20, "小白2"); Student s3 = new Student(1, "小白3"); tr.add(s1); tr.add(s2); tr.add(s3); //return 正数,s2>s1 都存 // 0 ,s2=s1 只存s1 // 负数 s2<s1 倒着存 for(Student s: tr){ System.out.println(s.getName()+" "+s.getAge()); } } }
Markdown
UTF-8
3,208
3.21875
3
[ "MIT" ]
permissive
--- { "description": "Kickstand UI's layout utility classes consist of width and height utilities to quickly manage responsive layouts.", "meta": [ { "property": "og:title", "content": "Layout Utilities - Kickstand UI" }, { "property": "og:image", "content": "https://kickstand-ui.com/images/screen_shots/layout.png" }, { "property": "og:description", "content": "Kickstand UI's layout utility classes consist of width and height utilities to quickly manage responsive layouts." }, { "property": "twitter:image:src", "content": "https://kickstand-ui.com/images/screen_shots/layout.png" } ] } --- # Layout Kickstand UI's layout utility classes consist of width and height utilities to quickly manage responsive layouts. ## Widths <div class="my-xxl"> <div class="my-md p-sm bg-light w-10">w-10</div> <div class="my-md p-sm bg-light w-20">w-20</div> <div class="my-md p-sm bg-light w-25">w-25</div> <div class="my-md p-sm bg-light w-30">w-30</div> <div class="my-md p-sm bg-light w-33">w-33</div> <div class="my-md p-sm bg-light w-40">w-40</div> <div class="my-md p-sm bg-light w-50">w-50</div> <div class="my-md p-sm bg-light w-60">w-60</div> <div class="my-md p-sm bg-light w-66">w-66</div> <div class="my-md p-sm bg-light w-70">w-70</div> <div class="my-md p-sm bg-light w-75">w-75</div> <div class="my-md p-sm bg-light w-80">w-80</div> <div class="my-md p-sm bg-light w-90">w-90</div> <div class="my-md p-sm bg-light w-100">w-100</div> </div> ```html <div class="w-10">w-10</div> <div class="w-20">w-20</div> <div class="w-25">w-25</div> <div class="w-30">w-30</div> <div class="w-33">w-33</div> <div class="w-40">w-40</div> <div class="w-50">w-50</div> <div class="w-60">w-60</div> <div class="w-66">w-66</div> <div class="w-70">w-70</div> <div class="w-75">w-75</div> <div class="w-80">w-80</div> <div class="w-90">w-90</div> <div class="w-100">w-100</div> ``` ## Heights <div class="my-xl"> <ks-row class="bg-light" style="height: 300px;"> <ks-column class="mx-md p-sm bg-primary-light h-25">h-25</ks-column> <ks-column class="mx-md p-sm bg-primary-light h-50">h-50</ks-column> <ks-column class="mx-md p-sm bg-primary-light h-75">h-75</ks-column> <ks-column class="mx-md p-sm bg-primary-light h-100">h-100</ks-column> </ks-row> </div> ```html <ks-row class="bg-light" style="height: 300px;"> <ks-column class="h-25">h-25</ks-column> <ks-column class="h-50">h-50</ks-column> <ks-column class="h-75">h-75</ks-column> <ks-column class="h-100">h-100</ks-column> </ks-row> ``` ## Responsive Classes You can also change the layout based on the user's screen size using the responsive variations of each class. By prefixing the class with the desired screen size (`xxs`-`xl`), you can adjust the behavior. <div class="my-xl"> <div class="bg-light p-sm w-50 md:w-100">I will be 50% width until a medium screen.</div> </div> ```html <div class="w-50 md:w-100">I will be 50% width until a medium screen.</div> ```
Swift
UTF-8
1,450
3.953125
4
[ "Apache-2.0" ]
permissive
//: [Previous](@previous) import Foundation public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int, next: ListNode? = nil) { self.val = val self.next = next } } class Solution { func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? { var n = 0 var p1 = head, p2 = head, p3 = p2 var ans: ListNode? = nil, last: ListNode? = nil while p1 != nil && p2 != nil { p3 = p2 p2 = p2?.next n += 1 if n == k { ans = p3 } if n % k == 0 { p3?.next = nil if n == k { ans = reverse(p1) } else { last?.next = reverse(p1) } last = p1 p1 = p2 } } last?.next = p1 return ans } func reverse(_ head: ListNode?) -> ListNode? { var p1 = head var p2: ListNode? = nil var p3: ListNode? = nil while p1 != nil { p3 = p1?.next p1?.next = p2 p2 = p1 p1 = p3 } return p2 } } var node = ListNode(1, next: ListNode(2, next: ListNode(3, next: ListNode(4, next: ListNode(5))))) var p = Solution().reverseKGroup(node, 5) while p != nil { print(p!.val) p = p?.next } //: [Next](@next)
Python
UTF-8
2,911
3.234375
3
[]
no_license
#import a bunch of stuff for sql from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import select from cockroachdb.sqlalchemy import run_transaction #set these to some of the imports so they can be called DBSession = sessionmaker() Base = declarative_base() #import random to create random numbers import random #describe the table data structure class words(Base): __tablename__ = 'words' english = Column(String, primary_key=True) spanish = Column(String) french = Column(String) secure_cluster = False # Set to False for insecure clusters connect_args = {} #create an empty list to store the words in late wordList = [] #set a global score variable score = 0 #set the connect args. If local just disable ssl if secure_cluster: connect_args = { 'sslmode': 'require', 'sslrootcert': 'certs/ca.crt', 'sslkey': 'certs/client.maxroach.key', 'sslcert': 'certs/client.maxroach.crt' } else: connect_args = {'sslmode': 'disable'} #set the db we are connecting to engine = create_engine( 'cockroachdb://root@localhost:26257/flash_cards', connect_args=connect_args, echo=True # Log SQL queries to stdout ) conn = engine.connect() #grab the data from db. Read each row into a dictionary then append each dictionary to a list. def queryTheDB(session): s = select([words]) result = conn.execute(s) for row in result: oneRow = {'english':row['english'],'spanish':row['spanish'],'french':row['french']} wordList.append(oneRow) #format the questions and check if the user's input matches the correct answer def vocabularyTest(languageChoice): #choose a random dictionary from the list localDictionary = wordList[random.randint(0,len(wordList)-1)] #ask the user what the English word is for the given Spanish or French word testQuestion = input("What is the English word for " + localDictionary[languageChoice] + "\n") #make the global score variable available locally global score #check if the user's answer is correct and increment the score if they got it. Give them the option to quit here if testQuestion.lower() == localDictionary['english']: score = score + 1 print("Correct! Score:", score) vocabularyTest(languageChoice) elif testQuestion == "quit": exit() else: print("Incorrect. The correct answer was:",localDictionary['english']) print("Score:", score) vocabularyTest(languageChoice) #ask the user what language they would like to test def main(): #load the words from the db run_transaction(sessionmaker(bind=engine), queryTheDB) languageChoice = input("Would you like to test your knowledge of French or Spanish vocabulary? \n") vocabularyTest(languageChoice.lower()) #start the program if __name__ == '__main__': main()
Python
UTF-8
373
3.109375
3
[]
no_license
import sqlite3 from contextlib import closing conn = sqlite3.connect("db/helpdesk.sqlite") with closing(conn.cursor()) as cursor: query = "SELECT * FROM employees WHERE employeeid = ?" cursor.execute(query, (1, )) employee = cursor.fetchone() print("Name: " + employee[1]) print("Email: " + employee[4]) # Close Connection if conn: conn.close()
C++
UTF-8
2,677
3.359375
3
[ "Unlicense" ]
permissive
/****************************************************************************** ******************************************************************************* ** ** Author: Lingurar Petru-Mugurel ** Written: miercuri 10 iunie 2015, 21:53:49 +0300 ** Last updated: --- ** ** Compilation: g++ -std=c++11 -Wall -Werror -Wextra -pedantic -Wshadow ** (g++ 5.1) -Woverloaded-virtual -Winvalid-pch -Wcast-align ** -Wformat=2 -Wformat-nonliteral -Wmissing-declarations ** -Wmissing-format-attribute -Wmissing-include-dirs ** -Wredundant-decls -Wswitch-default -Wswitch-enum ** ** Execution: ./... ** ** Description: ** Exercise 10.19: Rewrite the previous exercise to use stable_partition, ** which like stable_sort maintains the original element order in the ** paritioned sequence ** ** Bugs: ** --- None --- ** ** TODO: ** --- None --- ** ** Notes: ** The library defines an algorithm named partition that ** takes a predicate and partitions the container so that values for which ** the predicate is true appear in the first part and those for which the ** predicate is false appear in the second part. The algorithm returns an ** iterator just past the last element for which the predicate returned true. ** ******************************************************************************* ******************************************************************************/ #include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::cout << std::unitbuf; // flush the buffer after every output. std::vector<std::string> sentence = {"the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle"}; std::vector<std::string>::size_type orig_size = sentence.size(); std::cout << "\nSo we have a nice little sentence stored in a vector:\n\t"; std::for_each(sentence.cbegin(), sentence.cend(), [](const std::string &word) { std::cout << word << ' '; }); std::cout << "\n\nWe'll now partition this vector so to focus on just" << "\nwords that have >=5 characters:\n\t........."; std::vector<std::string>::const_iterator first_smaller; first_smaller = stable_partition(sentence.begin(), sentence.end(), [](std::string word) { return word.size() >= 5; }); std::cout << "\n\nSo the words with >= 5 chars are:\n\t"; std::for_each(sentence.cbegin(), first_smaller, [](const std::string &word) { std::cout << word << ' '; }); std::cout << "\n\nAnd the words with <5 chars are:\n\t"; std::for_each(first_smaller, sentence.cend(), [](const std::string &word) { std::cout << word << ' '; }); std::cout << '\n' << std::endl; return 0; }
JavaScript
UTF-8
1,710
3.265625
3
[ "MIT" ]
permissive
Date.prototype.format = function() { let s = ''; const mouth = (this.getMonth() + 1)>=10?(this.getMonth() + 1):('0'+(this.getMonth() + 1)); const day = this.getDate()>=10?this.getDate():('0'+this.getDate()); s += this.getFullYear() + '-'; // 获取年份。 s += mouth + "-"; // 获取月份。 s += day; // 获取日。 return (s); // 返回日期。 }; /** * 获取两个日期(格式:yyyy-MM-dd)内所有的日期 * @param begin * @param end */ const getAllByDateStr = (begin, end) => { const ab = begin.split("-"); const ae = end.split("-"); let db = new Date(); db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]); let de = new Date(); de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]); const unixDb = db.getTime(); const unixDe = de.getTime(); const result = []; for (let k = unixDb; k <= unixDe;) { result.push((new Date(parseInt(k))).format()); k = k + 24 * 60 * 60 * 1000; } return result; }; /** * 根据传入的时间毫秒数获取两个时间内所有的天数 * @param begin * @param end */ const getAllByMilliSecones = (begin, end) => { const beginStr = (new Date(parseInt(begin))).format(); const endStr = (new Date(parseInt(end))).format(); const ab = beginStr.split("-"); const ae = endStr.split("-"); let db = new Date(); db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]); let de = new Date(); de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]); const unixDb = db.getTime(); const unixDe = de.getTime(); const result = []; for (let k = unixDb; k <= unixDe;) { result.push((new Date(parseInt(k))).format()); k = k + 24 * 60 * 60 * 1000; } return result; }; module.exports = { getAllByDateStr, getAllByMilliSecones, };
Python
UTF-8
1,154
2.6875
3
[]
no_license
# file = open('test2.txt') # file2 = open('file2.txt', 'w') # num = 0 # for line in file: # file2.write(str(num) + " " + line) # num += 1 # file.close() # file2.close() import requests # url = "http://httpbin.org/get" # headers = {'user-agent':'roman browser'} # params = {'blah1':'yeah', 'blah2':'not yeah'} # resp = requests.get(url, headers = headers) # print(resp.text) # resp = requests.get(url, headers = headers, params=params) # print(resp.text) # print(resp.json()) book_data = {'title': 'Roman', 'author':'Me'} # book = requests.post("https://pulse-rest-testing.herokuapp.com/books/", data=book_data) # books = book.json() # print(books) r = requests.post("https://pulse-rest-testing.herokuapp.com/books/", data=book_data) book = r.json() print(book) bookDelete = requests.delete("https://pulse-rest-testing.herokuapp.com/books/"+str(book['id'])) bookDelete = requests.delete("https://pulse-rest-testing.herokuapp.com/books/"+"20") bookDelete = requests.delete("https://pulse-rest-testing.herokuapp.com/books/"+"22") bookDelete = requests.delete("https://pulse-rest-testing.herokuapp.com/books/"+"23") print(bookDelete.status_code)
Markdown
UTF-8
1,263
2.90625
3
[]
no_license
[![Build Status](https://travis-ci.org/robertotambunan/go-graphql-sample.svg?branch=master)](https://travis-ci.org/robertotambunan/go-graphql-sample) # Go-GraphQL-Sample This is a very simple project about how to implement graphQL in your golang project. The flow is so simple and very recommended for just quick learning. Dataset is just a simply array of struct. ## Getting Started Simply follow steps below to run this project ## How To Install and Run ``` 1. Clone the repository to your local machine (https://github.com/robertotambunan/go-graphql-sample.git) 2. go get -v 3. go build && ./go-graphql-sample Now your project is listening ``` ## How To Access Your GraphQL The project is running in localhost:9090/gql ### Query Hit localhost:9090/gql with method POST with body ``` {"query": "query { products { product_id, product_name, product_city, product_price } }"} ``` It will show you the data of your dataset # Mutation Hit localhost:9090/gql with method POST with body ``` {"query": "mutation { createProduct(product_id: 17, product_name: \"Baju Boxer\", product_price: \"Rp.500.000\", product_city: \"Jakarta\") { product_name,product_price, product_city } }"} ``` It will add new data to your dataset, you can check the data using Query
Python
UTF-8
907
2.890625
3
[]
no_license
stations = { 'kthree': {'nv', 'ca', 'or'}, 'kfour': {'nv', 'ut'}, 'ktwo': {'mt', 'wa', 'id'}, 'kone': {'nv', 'ut', 'id'}, 'kfive': {'az', 'ca'} } states_needed = {"mt", "wa", "or", "id", "nv", "ut", "ca", "az"} def temp(): remain_stations = dict(stations) remain_states = set(states_needed) result = list() while len(remain_states) > 0: targe = None score = 0 for one in stations: temp = len(stations[one].intersection(remain_states)) if temp > score: targe = one score = temp if score > 0: result.append(targe) remain_states.difference_update(remain_stations.pop(targe)) else: break print('结果', result) print('剩余', remain_states) # 贪婪算法, 局部最优解 if __name__ == '__main__': temp()
Java
UTF-8
2,412
1.984375
2
[]
no_license
package com.lvmama.jinjiang.model; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map; /** * 实时获取团信息 * @author chenkeke * */ public class SimpleGroup { private String groupCode; private Date departDate; private Date returnDate; private String groupStatus; private Integer advanceCloseDSO = 1; //提前预定天数 /*private Integer planNum; private Integer reserveNum; private Integer paidInNum; private Integer reservationNum; private Integer adultNum; private Integer childNum;*/ private Integer limitNum; private Integer requireNum; private List<GroupPrice> prices; private BigDecimal subAmount; private Date updateTime; private Map<String, String> extension; public String getGroupCode() { return groupCode; } public void setGroupCode(String groupCode) { this.groupCode = groupCode; } public Date getDepartDate() { return departDate; } public void setDepartDate(Date departDate) { this.departDate = departDate; } public Date getReturnDate() { return returnDate; } public void setReturnDate(Date returnDate) { this.returnDate = returnDate; } public String getGroupStatus() { return groupStatus; } public void setGroupStatus(String groupStatus) { this.groupStatus = groupStatus; } public Integer getAdvanceCloseDSO() { return advanceCloseDSO; } public void setAdvanceCloseDSO(Integer advanceCloseDSO) { this.advanceCloseDSO = advanceCloseDSO; } public Integer getRequireNum() { return requireNum; } public void setRequireNum(Integer requireNum) { this.requireNum = requireNum; } public List<GroupPrice> getPrices() { return prices; } public void setPrices(List<GroupPrice> prices) { this.prices = prices; } public BigDecimal getSubAmount() { return subAmount; } public void setSubAmount(BigDecimal subAmount) { this.subAmount = subAmount; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Map<String, String> getExtension() { return extension; } public void setExtension(Map<String, String> extension) { this.extension = extension; } public Integer getLimitNum() { return limitNum; } public void setLimitNum(Integer limitNum) { this.limitNum = limitNum; } }
C#
UTF-8
18,793
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace SmartGuardServer { public partial class MainForm : Form { /// <summary> /// 服务器状态,如果为false表示服务器暂停,true表示服务器开启 /// </summary> public bool ServerStatus = false; /// <summary> /// 服务器地址 /// </summary> public string ServerAddress; /// <summary> /// 服务器端口 /// </summary> public int ServerPort; /// <summary> /// 开启服务的线程 /// </summary> private Thread processor; /// <summary> /// 用于TCP监听 /// </summary> private TcpListener tcpListener; /// <summary> /// 与客户端连接的套接字接口 /// </summary> private Socket clientSocket; /// <summary> /// 用于处理客户事件的线程 /// </summary> private Thread clientThread; /// <summary> /// 手机客户端所有客户端的套接字接口 /// </summary> private Hashtable PhoneClientSockets = new Hashtable(); /// <summary> /// 手机用户类数组 /// </summary> public ArrayList PhoneUsersArray = new ArrayList(); /// <summary> /// 手机用户名数组 /// </summary> public ArrayList PhoneUserNamesArray = new ArrayList(); /// <summary> /// 图像数据流 /// </summary> private ArrayList StreamArray; public MainForm() { InitializeComponent(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; } private void phoneslistView_MouseDoubleClick(object sender, MouseEventArgs e) { if (phoneslistView.SelectedItems != null && phoneslistView.SelectedItems.Count > 0) { ListViewItem tempItem = phoneslistView.SelectedItems[0]; string tempUserName = tempItem.SubItems[1].Text; int tempIndex = GetPhoneUserIndex(tempUserName); if (tempIndex >= 0) { UserClass tempUser = (UserClass)(PhoneUsersArray[tempIndex]); if (tempUser != null) { PhoneVideoForm form = new PhoneVideoForm(tempUser); this.AddOwnedForm(form); form.Show(); } } } } #region 开启服务 /// <summary> /// 开启服务 /// </summary> public void StartServer() { try { if (this.ServerStatus)//服务器已经开启 { MessageBox.Show("服务已经开启!"); } else { processor = new Thread(new ThreadStart(StartListening));//建立监听服务器地址及端口的线程 processor.Start(); processor.IsBackground = true; StreamArray = new ArrayList(); PhoneUserNamesArray = new ArrayList(); } 停止服务器button.Enabled = true; 开启服务器button.Enabled = false; this.ServerStatus = true; } catch (Exception except) { MessageBox.Show(except.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } #endregion #region 停止服务 /// <summary> /// 停止服务 /// </summary> public void StopServer() { try { if (this.ServerStatus) { tcpListener.Stop(); Thread.Sleep(1000); processor.Abort(); } else MessageBox.Show("服务已经停止!"); 停止服务器button.Enabled = false; 开启服务器button.Enabled = true; this.ServerStatus = false; } catch (Exception except) { MessageBox.Show(except.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } #endregion /// <summary> /// 开始监听服务器地址和端口 /// </summary> private void StartListening() { try { IPAddress ipAddress = IPAddress.Parse(ServerAddress); tcpListener = new TcpListener(ipAddress, ServerPort);//建立指定服务器地址和端口的TCP监听 tcpListener.Start();//开始TCP监听 while (true) { Thread.Sleep(50); try { Socket tempSocket = tcpListener.AcceptSocket();//接受挂起的连接请求 clientSocket = tempSocket; clientThread = new Thread(new ThreadStart(ProcessClient));//建立处理客户端传递信息的事件线程 //线程于后台运行 clientThread.IsBackground = true; clientThread.Start(); } catch (Exception e) { } } } catch { this.ServerStatus = false; processor.Abort(); } } #region 处理客户端传递数据及处理事情 /// <summary> /// 处理客户端传递数据及处理事情 /// </summary> private void ProcessClient() { Socket client = clientSocket; bool keepalive = true; while (keepalive) { Thread.Sleep(50); Byte[] buffer = null; bool tag = false; try { buffer = new Byte[1024];//client.Available int count = client.Receive(buffer, SocketFlags.None);//接收客户端套接字数据 if (count > 0)//接收到数据 tag = true; } catch (Exception e) { keepalive = false; if (client.Connected) client.Disconnect(true); client.Close(); } if (!tag) { if (client.Connected) client.Disconnect(true); client.Close(); keepalive = false; } string clientCommand = ""; try { clientCommand = System.Text.Encoding.UTF8.GetString(buffer);//转换接收的数据,数据来源于客户端发送的消息 if (clientCommand.Contains("%7C"))//从Android客户端传递部分数据 clientCommand = clientCommand.Replace("%7C", "|");//替换UTF中字符%7C为| } catch { } //分析客户端传递的命令来判断各种操作 string[] messages = clientCommand.Split('|'); if (messages != null && messages.Length > 0) { string tempStr = messages[0];//第一个字符串为命令 if (tempStr == "PHONECONNECT")//手机连接服务器 { try { string tempClientName = messages[1].Trim(); PhoneClientSockets.Remove(messages[1]);//删除之前与该用户的连接 PhoneClientSockets.Add(messages[1], client);//建立与该客户端的Socket连接 UserClass tempUser = new UserClass(); tempUser.UserName = tempClientName; tempUser.LoginTime = DateTime.Now; Socket tempSocket = (Socket)PhoneClientSockets[tempClientName]; tempUser.IPAddress = tempSocket.RemoteEndPoint.ToString(); int tempIndex = PhoneUserNamesArray.IndexOf(tempClientName); if (tempIndex >= 0) { PhoneUserNamesArray[tempIndex] = tempClientName; PhoneUsersArray[tempIndex] = tempUser; MemoryStream stream2 = (MemoryStream)StreamArray[tempIndex]; if (stream2 != null) { stream2.Close(); stream2.Dispose(); } } else//新增加 { PhoneUserNamesArray.Add(tempClientName); PhoneUsersArray.Add(tempUser); StreamArray.Add(null); } RefreshPhoneUsers(); } catch (Exception except) { } } else if (tempStr == "PHONEDISCONNECT")//某个客户端退出了 { try { string tempClientName = messages[1]; RemovePhoneUser(tempClientName); int tempPhoneIndex = PhoneUserNamesArray.IndexOf(tempClientName); if (tempPhoneIndex >= 0) { PhoneUserNamesArray.RemoveAt(tempPhoneIndex); MemoryStream memStream = (MemoryStream)StreamArray[tempPhoneIndex]; if (memStream != null) { memStream.Close(); memStream.Dispose(); } StreamArray.RemoveAt(tempPhoneIndex); } Socket tempSocket = (Socket)PhoneClientSockets[tempClientName];//第1个为客户端的ID,找到该套接字 if (tempSocket != null) { tempSocket.Close(); PhoneClientSockets.Remove(tempClientName); } keepalive = false; } catch (Exception except) { } RefreshPhoneUsers(); } else if (tempStr == "PHONEVIDEO")//接收手机数据流 { try { string tempClientName = messages[1]; string tempForeStr = messages[0] + "%7C" + messages[1] + "%7C"; int startCount = System.Text.Encoding.UTF8.GetByteCount(tempForeStr); try { MemoryStream stream = new MemoryStream(); if (stream.CanWrite) { stream.Write(buffer, startCount, buffer.Length - startCount); int len = -1; while ((len = client.Receive(buffer)) > 0) { stream.Write(buffer, 0, len); } } stream.Flush(); int tempPhoneIndex = PhoneUserNamesArray.IndexOf(tempClientName); if (tempPhoneIndex >= 0) { MemoryStream stream2 = (MemoryStream)StreamArray[tempPhoneIndex]; if (stream2 != null) { stream2.Close(); stream2.Dispose(); } StreamArray[tempPhoneIndex] = stream; PhoneVideoForm form = GetPhoneVideoForm(tempClientName); if (form != null) form.DataStream = stream; } } catch { } } catch (Exception except) { } } } else//客户端发送的命令或字符串为空,结束连接 { try { client.Close(); keepalive = false; } catch { keepalive = false; } } } } #endregion #region 刷新手机用户列表 /// <summary> /// 刷新手机用户列表 /// </summary> public void RefreshPhoneUsers() { phoneslistView.Items.Clear(); if (PhoneUsersArray != null && PhoneUsersArray.Count > 0 && PhoneClientSockets != null && PhoneClientSockets.Count > 0) { int i, count = PhoneUsersArray.Count; UserClass tempUser; ListViewItem tempItem; ListViewItem.ListViewSubItem tempSubItem; Color tempColor; Socket tempSocket; for (i = 0; i < count; i++) { tempUser = (UserClass)PhoneUsersArray[i]; tempSocket = (Socket)PhoneClientSockets[tempUser.UserName]; tempItem = phoneslistView.Items.Add((i + 1).ToString()); if (tempUser.Enable) tempColor = Color.Blue; else tempColor = Color.Red; tempItem.ForeColor = tempColor; tempSubItem = tempItem.SubItems.Add(tempUser.UserName); tempSubItem.ForeColor = tempColor; tempSubItem = tempItem.SubItems.Add(tempUser.IPAddress); tempSubItem.ForeColor = tempColor; tempSubItem = tempItem.SubItems.Add(tempUser.LoginTime.ToString()); tempSubItem.ForeColor = tempColor; } } } #endregion #region 获取手机视频窗体 /// <summary> /// 获取手机视频窗体 /// </summary> /// <param name="username"></param> /// <returns></returns> public PhoneVideoForm GetPhoneVideoForm(string username) { PhoneVideoForm form = null; foreach (Form tempForm in this.OwnedForms) { if (tempForm is PhoneVideoForm) { PhoneVideoForm tempForm2 = tempForm as PhoneVideoForm; if (tempForm2.UserName == username) { form = tempForm2; break; } } } return form; } #endregion #region 删除手机用户 /// <summary> /// 从当前用户列表中删除指定用户 /// </summary> /// <param name="userName"></param> public void RemovePhoneUser(string userName) { if (PhoneUsersArray != null && PhoneUsersArray.Count > 0) { int i = 0; foreach (UserClass tempUser in PhoneUsersArray) if (tempUser.UserName == userName) { PhoneUsersArray.RemoveAt(i); break; } else i++; } } #endregion #region 寻找用户所在序号 /// <summary> /// 寻找用户所在序号 /// </summary> /// <param name="userName"></param> /// <returns></returns> public int GetPhoneUserIndex(string userName) { int result = -1; if (PhoneUserNamesArray != null && PhoneUserNamesArray.Count > 0) { int i = 0; foreach (string tempName in PhoneUserNamesArray) if (tempName == userName) { result = i; break; } else i++; } return result; } #endregion private void 开启服务器button_Click(object sender, EventArgs e) { ServerAddress = iptextBox.Text; int tempPort = 6666; if (int.TryParse(porttextBox.Text, out tempPort)) { ServerPort = tempPort; StartServer(); } else { MessageBox.Show("端口设置不正确!"); } } private void 停止服务器button_Click(object sender, EventArgs e) { StopServer(); } private void phoneslistView_SelectedIndexChanged(object sender, EventArgs e) { } } }
SQL
UTF-8
3,603
3.078125
3
[]
no_license
create database professorfacil; use professorfacil; create table usuarios( iduso int primary key auto_increment not null, uso_nome varchar(200) not null, uso_cidade varchar(100), uso_estado varchar(4), uso_endereco varchar(200), uso_end_num varchar(8), uso_email varchar(100), uso_cpf varchar(20), uso_celular varchar(50) not null, uso_cep varchar(30), uso_usuario varchar(50) not null, uso_senha varchar(50) not null, uso_componente varchar(400), uso_licenca varchar (50), uso_data_licensa varchar (30), uso_data_validade varchar (30), uso_perfil varchar(50), uso_datacadastro timestamp default current_timestamp ); insert into usuarios (uso_nome,uso_cidade,uso_estado,uso_endereco,uso_end_num,uso_email,uso_cpf,uso_celular,uso_cep,uso_usuario,uso_senha,uso_perfil,uso_componente) values ("Tarciso Nascimento Bezerra","Atiquemes","RO","Rua Presidente Prudente de Morais","1852","tarcisoedf@gmail.com","983.284.252-20","(69) 9.9209-9315","76.873-384","admin","admin","Administrador","Educação Física,Artes"); create table componentes ( idcomponente int primary key auto_increment not null, comp_nome varchar (100) ); insert into componentes (comp_nome) values ("Educação Física"); create table editora ( ideditora int primary key auto_increment not null, edit_nome varchar (100) ); insert into editora (edit_nome) values ("Moderna"); create table serie ( idserie int primary key auto_increment not null, seri_nivel varchar (10) ); insert into serie (seri_nivel) values ("1º"); create table livro ( idliv int primary key auto_increment not null, liv_componente varchar (150), liv_nomeautor varchar (200), liv_nome varchar (200), liv_editora varchar (150), liv_edicao varchar (50), liv_ano varchar (10), liv_serie varchar (10), liv_periodo varchar (50), liv_observacoes varchar (200), liv_foto longblob ); insert into livro (liv_componente,liv_nomeautor,liv_nome,liv_editora,liv_edicao,liv_ano,liv_serie,liv_periodo,liv_observacoes) values ("Educação Física","AA_Autor","Educação acima de tudo","Moderna","1º Edição","2020","1º","2020,2021,2022,2023","Sem Observações"); create table conteudo ( idconteudo int primary key auto_increment not null, cont_conteudo longblob, cont_habilidade longblob, cont_atividade longblob, cont_recurso longblob, cont_code_conteudo varchar (60), cont_serie varchar (10), cont_componente varchar (100), cont_unidadetematica varchar (200), idliv int not null ); insert into conteudo (cont_conteudo,cont_habilidade,cont_atividade,cont_recurso,cont_code_conteudo,cont_serie,cont_componente,idliv) values ("3","Aqui Vai as habilidades","aqui vai os recursos","aqui vao os conteudos","(EF254DF)","3º","Educação Física","1"); insert into conteudo (cont_code_conteudo,cont_serie,cont_componente,idliv) values ("10","1º","Ciências","1"); create table licenca ( idlicenca int primary key auto_increment not null, idcli int not null, lic_chave int not null, lic_licenca varchar (100), lic_data_valida varchar (30), lic_data_licenca timestamp default current_timestamp ); create table escola ( idescola int primary key auto_increment not null, esc_estado varchar (400), esc_secretaria varchar (400), esc_ecola varchar (400), esc_cidade varchar (150), esc_Uf varchar (10), esc_endereco varchar (250), esc_num varchar (10), esc_brasao longblob, idcli int not null ); create table compselecionado ( idcompselec int primary key auto_increment not null, iduso int not null, nomecomponente varchar(100) ); describe conteudo; select idliv,idconteudo,cont_code_conteudo,cont_unidadetematica from conteudo where idliv = '1' and cont_componente = "Educação Física" and cont_serie = "1º";
Python
UTF-8
2,552
3.640625
4
[]
no_license
#!/usr/bin/python """ comment in many lines many many lines """ import sys class obj: file = None addr = None def pass_arg(obj): obj.file = "bbb" __obj = obj() __obj.file = "aaa" __obj.addr = 0x123 pass_arg(__obj) print (__obj.file) #one line comment #number = 10 #add = number + 11 #print '45654', 'ppp', add, number #print (), 'enter your name' name = raw_input('enter your password ') print name ### practice multi line #msg = """one line #two line #three line""" # #print msg # #msg = "C:\\abcde\n efe" #print msg ### concatenate string """ msg = "ppp" msg2 = "bbb" final = msg * 3 print final final = msg + msg2 print final print len(final) print "123"*3 """ #age = 16 #msg = "ttt" #msg2 = str(age) + msg #print msg2 ### arithmetic #a = 100 #print 100 / 3 #print 100 / 3. #print float(a) / 3 #print float(a) // 3 ### test list #mylist = ["aaa", "bbb", "ccc", "ddd"] #mylist.append('2000') #print mylist #mylist.extend("5000") #print mylist #print mylist[4] #print mylist[1:4] #mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] #print mylist[1][2] #print mylist #mylist = [1, 2, 3] #mylist.append(4) #mylist.extend([5, 6]) #print mylist #mylist[3:5] = [3, 2, 7, 6, 8] #print mylist ### dictionary #mapping = {"one": "111", "two": "222", "three": "33"} #print mapping #print mapping["three"] #print dict[2] #mapping["two"] = "double two" #print mapping["two"] #qqq = mapping.copy() #print qqq #print qqq["one"] #print qqq.keys() #print qqq.values() ### print string #string = ("abc", 123, "def", 123) #print "%s %d %s %x" % string ##string = ["abc", 123, "def", 123] #this is wrong ##print "%s %d %s %x" % string #string = {"name": "qq", "age": 18} #print "her name is %(name)s and age is %(age)d" % string #print "her name is %(name)s" % {"name": "ppp"} ### if else #pp = 2 #if (pp == 2) : # print "pp = %d" % pp #elif (pp == 4) : # print "it's %d" % pp #else: # print "no" # print "pp = %d" % pp ### loop #for x in range(2, 100, 5): # print 2 to 100, every 5 step # print x #print "next" #for x in range(2, 100, 5): # print x, # all numbers will be in the same line #print # add a line break #print # a blank line #print "next line?" #i = 0 #while (i < 10) : # print i # i += 1 ### split and strip #line = " first ( second third " #print line #item = line.split('(') #print item #line = line.strip() #print line #item = line.split() #print item #line = " " #print line #item = line.split() #print item
C#
UTF-8
910
2.703125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent (typeof(Slider))] public class BarContoller : MonoBehaviour { private Slider Bar; public Text targedText; public int maxPoints = 100; public int value = 30; void Start () { if (Bar == null) Bar = GetComponent<Slider> (); } void Update () { BarChange (); } private void BarChange() { if (targedText != null) { targedText.text = Bar.value.ToString() + "/" + Bar.maxValue.ToString(); } if (maxPoints != Bar.maxValue) Bar.maxValue = maxPoints; if (value < Bar.value) Bar.value--; if (value > Bar.value) Bar.value++; if (value < 0) value = 0; if (value > maxPoints) value = maxPoints; } public void ChangeValue(int points) { value += points; } public void SetValue(int points) { value = points; } }
Python
UTF-8
4,624
2.59375
3
[]
no_license
# Configuration for gym_auv gym environment from dataclasses import dataclass import dataclasses from functools import cached_property from typing import Any, Callable, Tuple, Union # import gym_auv from gym_auv.utils.observe_functions import observe_obstacle_fun from gym_auv.utils.sector_partitioning import sector_partition_fun @dataclass class EpisodeConfig: # ---- EPISODE ---- # min_cumulative_reward: float = float( -2000 ) # Minimum cumulative reward received before episode ends max_timesteps: int = 10000 # Maximum amount of timesteps before episode ends min_goal_distance: float = float( 5 ) # Minimum aboslute distance to the goal position before episode ends min_path_progress: float = 0.99 # Minimum path progress before scenario is considered successful and the episode ended @dataclass class SimulationConfig: t_step_size: float = 1.0 # Length of simulation timestep [s] sensor_frequency: float = ( 1.0 # Sensor execution frequency (0.0 = never execute, 1.0 = always execute) ) observe_frequency: float = ( 1.0 # Frequency of using actual obstacles instead of virtual ones for detection ) @dataclass class VesselConfig: thrust_max_auv: float = 2.0 # Maximum thrust of the AUV [N] moment_max_auv: float = 0.15 # maximum moment applied to the AUV [Nm] vessel_width: float = 1.255 # Width of vessel [m] feasibility_width_multiplier: float = ( 5.0 # Multiplier for vessel width in feasibility pooling algorithm ) look_ahead_distance: int = 300 # Path look-ahead distance for vessel [m] render_distance: Union[ int, str ] = 300 # 3D rendering render distance, or "random" [m] include_original_observations: bool = False # Whether to include cross-track-error, as well as two # path-relative angles in observation use_relative_vectors: bool = True use_lidar: bool = ( False # True # Whether rangefinder sensors for perception should be activated ) sensor_interval_load_obstacles: int = 25 # Interval for loading nearby obstacles n_sensors_per_sector: int = 20 # Number of rangefinder sensors within each sector n_sectors: int = 9 # Number of sensor sectors sensor_use_feasibility_pooling: bool = False # Whether to use the Feasibility pooling preprocessing for LiDAR measurements sensor_use_velocity_observations: bool = False sector_partition_fun: Callable[ [Any, int], int ] = sector_partition_fun # Function that returns corresponding sector for a given sensor index sensor_rotation: bool = False # Whether to activate the sectors in a rotating pattern (for performance reasons) sensor_range: float = 150.0 # Range of rangefinder sensors [m] sensor_log_transform: bool = True # Whether to use a log. transform when calculating closeness # observe_obstacle_fun: Callable[ [int, float], bool ] = observe_obstacle_fun # Function that outputs whether an obstacle should be observed (True), # or if a virtual obstacle based on the latest reading should be used (False). # This represents a trade-off between sensor accuracy and computation speed. # With real-world terrain, using virtual obstacles is critical for performance. use_dict_observation: bool = False # True @property def n_sensors(self) -> int: # Calculates the number of sensors in total return self.n_sensors_per_sector * self.n_sectors @property def lidar_shape(self) -> Tuple[int, int]: lidar_channels = 1 if self.sensor_use_velocity_observations: lidar_channels = 3 return (lidar_channels, self.n_sensors) @property def n_lidar_observations(self) -> int: return self.lidar_shape[0] * self.lidar_shape[1] @property def dense_observation_size(self) -> int: n_reward_insights = 0 # TODO n_navigation_features = 6 # 7 # TODO return n_reward_insights + n_navigation_features @dataclass class RenderingConfig: show_indicators: bool = ( True # Whether to show debug information on screen during 2d rendering. ) autocamera3d: bool = ( True # Whether to let the camera automatically rotate during 3d rendering ) @dataclass class Config: episode: EpisodeConfig = EpisodeConfig() simulation: SimulationConfig = SimulationConfig() vessel: VesselConfig = VesselConfig() rendering: RenderingConfig = RenderingConfig() def __iter__(self): return iter(dataclasses.fields(self))
Python
UTF-8
646
3.15625
3
[]
no_license
import sys ''' n = int(input().strip()) s = str(bin(n)) print(len(max(s[2:].split('0')))) ''' #si.split('0') #print(si) #print(len(max(si))) ''' time = input().strip().upper() L = len(time) if time[L-2::1] == 'PM': hour = time[2:] if hour == '12': hour = '00' else: hour = int(time[:2])+12) new_time = str(int(time[:2])+12) + time[2:L-2] else: new_time = time[:L-2] print(new_time) n = int(input().strip()) arr = [] for i in range(n): arr.append(input()) print(arr) ''' def sum_arr(ar): if ar == []: return 0 else: return ar[0] + sum_arr(ar[1:]) arrr = [1,2,3,20] print(sum_arr(arrr))
C++
UTF-8
677
3.28125
3
[]
no_license
#include <iostream> #include <vector> using std::vector; int optimal_weight(int W, const vector<int> &w) { std::vector<std::vector<int>> maxWeight (w.size() + 1, std::vector<int> (W + 1)); int weight {}; for(int i {1}; i <= w.size(); i++) { for(int j {1}; j <= W; j++) { maxWeight[i][j] = maxWeight[i - 1][j]; if(w[i - 1] <= j) { weight = maxWeight[i - 1][j - w[i - 1]] + w[i - 1]; if(weight > maxWeight[i][j]) maxWeight[i][j] = weight; } } } return maxWeight[w.size()][W]; } int main() { int n, W; std::cin >> W >> n; vector<int> w(n); for (int i = 0; i < n; i++) { std::cin >> w[i]; } std::cout << optimal_weight(W, w) << '\n'; }
Java
UTF-8
395
3.015625
3
[]
no_license
package link.hooray.jdk8.feature.stream.usual; import java.util.stream.Stream; public class Demo02Filter { public static void main(String[] args) { Stream<String> stream = Stream.of("张三丰", "张翠山", "赵敏", "周芷若", "张无忌"); Stream<String> stream1 = stream.filter(s -> s.startsWith("张")); stream1.forEach(s -> System.out.println(s)); } }
Python
UTF-8
311
2.671875
3
[]
no_license
# # https://realpython.com/fast-flexible-pandas/ # import os import pandas as pd print(pd.__version__) dir_path = os.path.dirname(os.path.realpath(__file__)) data_file_path = os.path.join(dir_path, 'demand_profile.csv') print(f"file path: {data_file_path}") df = pd.read_csv(data_file_path) print(df.head())
Python
UTF-8
744
2.96875
3
[]
no_license
from math import * def getline(): return list(map(int, input().split())) def getint(): return int(input()) N = 10**3 + 1 prime = [True]*N prime[0] = prime[1] = False res = [1] * N primes = [] mem = {} for i in range(N): if prime[i]: res[i] = i+1 primes.append(i) for j in range(2*i, N, i): prime[j] = False temp = j exp = 0 while j % i == 0: j//=i exp += 1 res[temp] *= (i**(exp+1) - 1) / (i-1) mem[res[i]] = i count = 1 while True: cur = getint() if cur == 0: break print("Case {}: ".format(count), end="") if cur in mem: print(mem[cur]) else: print(-1) count += 1
PHP
UTF-8
611
2.828125
3
[]
no_license
<?php declare(strict_types=1); namespace Models\Patterns\FactoryMethod; /** * Class CommonsManager * * @package Models\Patterns\FactoryMethod */ abstract class CommonsManager { /** * Get instance of message encoder class * * @return MessageEncoder */ abstract public function getMessageEncoder(): MessageEncoder; /** * Get header text message * * @return string */ abstract public function getHeaderText(): string; /** * Get footer text message * * @return string */ abstract public function getFooterText(): string; }
Java
UTF-8
3,858
2.859375
3
[]
no_license
import java.sql.*; //import java.String.*; // exekveras med java DB2Luw_employee //127.0.0.1:50000/SAMPLE user password OBS ! Använd inte ODBC Data Source namn utan db2 instans dbname public class DB2Luw_employee { public static void main(String[] args) { String rsEMPNO; String rsFIRSTNME; String rsLASTNAME; String rsWORKDEPT; String rsJOB; String rsSALARY; String rsBONUS; String rsCOMM; String stmtsrc; Connection con; Statement stmt; ResultSet rs; String url; String user; String password; url = "jdbc:db2://127.0.0.1:50000/SAMPLE"; user = "LAT1"; password = "********"; try { // Load the driver Class.forName("com.ibm.db2.jcc.DB2Driver"); System.out.println("**** Loaded the JDBC driver"); // Create the connection using the IBM Data Server Driver for JDBC and SQLJ con = DriverManager.getConnection (url, user, password); // Commit changes manually con.setAutoCommit(false); System.out.println("**** Created a JDBC connection to the data source"); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // Create a Statement object // for a scrollable, updatable // ResultSet stmtsrc = "SELECT EMPNO, FIRSTNME, LASTNAME, WORKDEPT, JOB, SALARY , BONUS, COMM FROM LAT1.EMPLOYEE "; // + // "FOR UPDATE OF FIRSTNME"; rs = stmt.executeQuery(stmtsrc); // Create the ResultSet rs.afterLast(); // Position the cursor at the end of // the ResultSet System.out.format("%-6s, %-15s, %-12s, %-8s, %-8s, %10s, %10s, %10s\n", "EMPNO", "FIRSTNME", "LASTNAME", "WORKDEPT", "JOB", "SALARY", "BONUS", "COMM"); System.out.format("%-70s\n"," "); while (rs.previous()) { // Position the cursor backward rsEMPNO = rs.getString("EMPNO"); // Retrieve the employee number // (column 1 in the result table) rsFIRSTNME = rs.getString("FIRSTNME"); // Retrieve the employee firstname // (column 2 in the result table) rsLASTNAME = rs.getString("LASTNAME"); // Retrieve the employee firstname // (column 3 in the result table) rsWORKDEPT = rs.getString("WORKDEPT"); // Retrieve the employee firstname // (column 4 in the result table) rsJOB = rs.getString("JOB"); // Retrieve the employee firstname // (column 5 in the result table) rsSALARY = rs.getString("SALARY"); // Retrieve the employee firstname // (column 6 in the result table) rsBONUS = rs.getString("BONUS"); // Retrieve the employee firstname // (column 7 in the result table) rsCOMM = rs.getString("COMM"); // Retrieve the employee firstname // (column 8 in the result table) System.out.format("%-6s, %-15s, %-12s, %-8s, %-8s, %10s, %10s, %10s\n", rsEMPNO, rsFIRSTNME, rsLASTNAME, rsWORKDEPT, rsJOB, rsSALARY, rsBONUS, rsCOMM); // Print the column value //if (s.compareTo("000010") == 0) { // Look for employee 000010 //rs.updateString("FIRSTNME","QHRISTINE"); // Update their firstname number //rs.updateRow(); // Update the row //con.commit(); // Commit the update } // } rs.close(); // Close the ResultSet stmt.close(); // Close the Statement } catch (ClassNotFoundException e) { System.err.println("Could not load JDBC driver"); System.out.println("Exception: " + e); e.printStackTrace(); } catch(SQLException ex) { System.err.println("SQLException information"); while(ex!=null) { System.err.println ("Error msg: " + ex.getMessage()); System.err.println ("SQLSTATE: " + ex.getSQLState()); System.err.println ("Error code: " + ex.getErrorCode()); ex.printStackTrace(); ex = ex.getNextException(); // For drivers that support chained exceptions } } } } // End DB2Luw_employee.java
Markdown
UTF-8
2,045
2.609375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: <namedCaches> 的 <clear> 項目 ms.date: 03/30/2017 helpviewer_keywords: - <clear> element for <namedCaches> - clear element for <namedCaches> ms.assetid: ea01a858-65da-4348-800f-5e3df59d4d79 ms.openlocfilehash: bcc0e23f0c47ad3a98430e36da31d39612caa3c9 ms.sourcegitcommit: 4e2d355baba82814fa53efd6b8bbb45bfe054d11 ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 09/04/2019 ms.locfileid: "70252752" --- # <a name="clear-element-for-namedcaches"></a>\<清除 namedCaches 的\<> 元素 > 清除`namedCache` 集合`namedCaches`中記憶體快取的所有專案。 [ **\<configuration>** ](../configuration-element.md)\ &nbsp;&nbsp;[ **\<> 的緩存**](system-runtime-caching-element-cache-settings.md)\ &nbsp;&nbsp;&nbsp;&nbsp;[ **\<memoryCache >** ](memorycache-element-cache-settings.md)\ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ **\<namedCaches >** ](namedcaches-element-cache-settings.md)\ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; **\<清除 >** ## <a name="syntax"></a>語法 ```xml <namedCaches> <clear name="Default" /> <!-- child elements --> </namedCaches> ``` ## <a name="type"></a>類型 `Type` ## <a name="attributes-and-elements"></a>屬性和項目 下列各節描述屬性、子項目和父項目。 ### <a name="attributes"></a>屬性 `None` ### <a name="child-elements"></a>子元素 `None` ### <a name="parent-elements"></a>父項目 |項目|描述| |-------------|-----------------| |[\<namedCaches>](namedcaches-element-cache-settings.md)|包含已命名<xref:System.Runtime.Caching.MemoryCache>實例的設定集合。| ## <a name="remarks"></a>備註 元素會清除已`namedCache`命名快取集合中記憶體快取的所有專案。 `clear` 您可以使用`clear`專案,然後`add`使用專案來加入新的命名快取專案,以確保集合中沒有其他命名的快取。 ## <a name="see-also"></a>另請參閱 - [\<namedCaches > 元素(快取設定)](namedcaches-element-cache-settings.md)
SQL
UTF-8
2,625
3.296875
3
[]
no_license
DROP TABLE IF EXISTS `qn_qrcode`; CREATE TABLE IF NOT EXISTS `qn_qrcode` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL, `title` varchar(50) NOT NULL COMMENT '二维码标题', `max_scan` bigint(11) NOT NULL DEFAULT '10000' COMMENT '最大扫描次数', `view_mode` int(11) NOT NULL DEFAULT '1' COMMENT '显示模式', `sort` int(11) NOT NULL DEFAULT '1' COMMENT '排序', `status` tinyint(2) NOT NULL COMMENT '状态', `remark` varchar(255) NOT NULL COMMENT '备注', `scan_count` bigint(11) NOT NULL DEFAULT '0' COMMENT '总扫描量', `create_time` bigint(11) NOT NULL, `update_time` bigint(11) NOT NULL, `type_mode` int(11) NOT NULL DEFAULT '1' COMMENT '活码类型', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='二维码列表' AUTO_INCREMENT=1 ; DROP TABLE IF EXISTS `qn_qrcode_child`; CREATE TABLE IF NOT EXISTS `qn_qrcode_child` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL, `qr_pid` int(11) NOT NULL, `qr_img` bigint(11) NOT NULL DEFAULT '0' COMMENT '图片', `qr_link` varchar(255) DEFAULT NULL COMMENT '链接', `qr_text` text COMMENT '文本', `qr_card` text COMMENT '名片', `qr_type` int(11) NOT NULL DEFAULT '1', `scan_count` bigint(11) NOT NULL DEFAULT '0' COMMENT '总扫描量', `sort` tinyint(4) NOT NULL, `status` tinyint(4) NOT NULL, `create_time` bigint(11) NOT NULL, `update_time` bigint(11) NOT NULL, `title` varchar(255) DEFAULT NULL, `qr_province` varchar(200) DEFAULT NULL, `qr_city` varchar(200) DEFAULT NULL, `qr_district` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='二维码子分类' AUTO_INCREMENT=1 ; DROP TABLE IF EXISTS `qn_qrcode_domain`; CREATE TABLE IF NOT EXISTS `qn_qrcode_domain` ( `id` int(11) NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL, `in_domain` varchar(255) NOT NULL, `out_domain` text NOT NULL, `creat_time` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uid` (`uid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; DROP TABLE IF EXISTS `qn_qrcode_log`; CREATE TABLE IF NOT EXISTS `qn_qrcode_log` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `create_time` bigint(11) NOT NULL DEFAULT '0', `ip` varchar(50) DEFAULT NULL COMMENT 'IP', `ip_addr` varchar(255) DEFAULT NULL COMMENT 'IP归属地', `scan_device` text COMMENT '扫描设备', `qr_id` bigint(11) NOT NULL COMMENT '扫描二维码ID', `qr_cid` bigint(11) NOT NULL COMMENT '扫描子二维码ID', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='扫描记录' AUTO_INCREMENT=1 ;
C#
UTF-8
2,672
2.53125
3
[]
no_license
using System.Collections.Generic; using System.Threading.Tasks; using InchCapeTest.DtoS; using InchCapeTest.Enums; using InchCapeTest.Interfaces; using Microsoft.AspNetCore.Mvc; namespace InchCapeTest.Controllers.v1 { [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] public class VehiclePropertyController: ControllerBase { private readonly IVehiclePropertyService _vehiclePropertyService; public VehiclePropertyController(IVehiclePropertyService vehiclePropertyService) { _vehiclePropertyService = vehiclePropertyService; } [HttpGet] [Route("makes", Name = nameof(GetMakes))] public async Task<ActionResult<IList<VehiclePropertyModel>>> GetMakes() { return Ok(await _vehiclePropertyService.GetAll(VehiclePropertyEnum.Make)); } [HttpGet] [Route("quoteTypes", Name = nameof(GetQuoteTypes))] public async Task<ActionResult<IList<VehiclePropertyModel>>> GetQuoteTypes() { return Ok(await _vehiclePropertyService.GetAll(VehiclePropertyEnum.QuoteType)); } [HttpGet] [Route("vehicleTypes", Name = nameof(GetVehicleTypes))] public async Task<ActionResult<IList<VehiclePropertyModel>>> GetVehicleTypes() { return Ok(await _vehiclePropertyService.GetAll(VehiclePropertyEnum.VehicleType)); } [HttpPost] [Route("makes", Name = nameof(AddMake))] public IActionResult AddMake([FromBody] VehiclePropertyRequestModel model) { return AddNew(model, VehiclePropertyEnum.Make); } [HttpPost] [Route("quoteTypes", Name = nameof(AddQuoteType))] public IActionResult AddQuoteType([FromBody] VehiclePropertyRequestModel model) { return AddNew(model, VehiclePropertyEnum.QuoteType); } [HttpPost] [Route("vehicleTypes", Name = nameof(AddVehicleType))] public IActionResult AddVehicleType([FromBody] VehiclePropertyRequestModel model) { return AddNew(model, VehiclePropertyEnum.VehicleType); } private IActionResult AddNew(VehiclePropertyRequestModel model, VehiclePropertyEnum type) { if (string.IsNullOrEmpty(model.Label)) { return BadRequest(new { message = $"Value cannot be empty for {type.ToString()}" }); } _vehiclePropertyService.AddNew(model, type); return Ok(); } } }
JavaScript
UTF-8
1,509
3.03125
3
[]
no_license
const IMAGE_API_URL = "https://picsum.photos/200/300"; const TEXT_API_URL = "https://dummyapi.io/data/v1/user?limit=10"; let imageElement = document.getElementById("image"); let userInformation = document.getElementById("userInfo"); function myFetch(url, options) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(options ? options.method : "GET", url, true); if (url == "https://picsum.photos/200/300") { xhr.responseType = "blob"; } else { xhr.setRequestHeader("app-id", "6155fa5472aa4147002c1df3"); }; xhr.onload = () => { resolve(new Response(xhr.response)); }; xhr.send(); }); } myFetch(IMAGE_API_URL).then((res) => { return res.blob(); }).then((response) => { const reader = new FileReader(); reader.readAsDataURL(response); reader.onload = () => { insertImage(reader.result); }; }); function insertImage(src) { imageElement.src = src; } myFetch(TEXT_API_URL).then((res) => { return res.json(); }).then((response) => { response.data.forEach((person) => { userInformation.insertAdjacentHTML('beforeend', `<div class="usercard"> <img src="${person.picture}" alt="${person.id}"> <p>${person.firstName}</p> <p>${person.lastName}</p> <p>${person.title}</p> <p>${person.id}</p> </div>`); }); console.log(response); });
C++
UTF-8
2,106
3.46875
3
[]
no_license
/* 굉장히 재미있던 문제! 이분 탐색 + 다익스트라를 이용해면 시간 안에 해결을 할 수 있다. 1) 이분탐색 얼마 이하의 길들만 이용할지 를 기준으로 이분탐색을 진행한다. 그러면 이분탐색의 범위는 1 ~ 10^9 가 된다. 2) 다익스트라 이분탐색으로 얼마 이하의 길들을 이용할지 정해졌다면, A지점에서 B지점으로 최단 거리를 구하면 된다. 3) cost 이하의 길들만 이용해서 A에서 B로 가는 길이 우리가 가지고 있는 C원 이하이면 갈 수 있으므로 답을 갱신한다. --> 이분탐색과 다익스트라를 이용하면 복잡도를 줄일 수 있다. --> O( log(10^9) * M * log(M)) */ #include<iostream> #include<vector> #include<queue> using namespace std; using ll = long long; const ll INF = 1000000000000000; int N, M, A, B, x, y; ll C, c; vector<pair<int, ll>> graph[100001]; // A에서 B지점까지 cost 이하의 길들만 이용해서 가기! bool dijkstra(ll cost) { vector<ll> dist(N + 1, INF); priority_queue<pair<ll, int>> pq; pq.push({ 0L, A }); dist[A] = 0; while (!pq.empty()) { ll curCost = -pq.top().first; int cur = pq.top().second; pq.pop(); if (dist[cur] < curCost) continue; for (pair<int, ll> next : graph[cur]) { if (next.second > cost) continue; ll nextDist = curCost + next.second; if (nextDist < dist[next.first]) { dist[next.first] = nextDist; pq.push({ -nextDist, next.first }); } } } return (dist[B] <= C); } int main(void) { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> N >> M >> A >> B >> C; for (int i = 0; i < M; i++){ cin >> x >> y >> c; graph[x].push_back({ y, c }); graph[y].push_back({ x, c }); } // A에서 B로 탐색!!! ll left = 1, right = 1000000000, ans = -1; while (left <= right) { ll mid = (left + right) / 2; // A에서 B로 mid보다 작은 길들만 이용해서 최소로 고! if (dijkstra(mid)) { // 갈 수 있음! right = mid - 1; ans = mid; } else { left = mid + 1; } } cout << ans << '\n'; return 0; }
C#
UTF-8
2,234
3.109375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.AspNetCore.Identity; using NUnit.Framework; using WordGame.Helpers; using WordGame.Models; namespace WordGameTest { public class Tests { [SetUp] public void Setup() { } [Test] public void Get_Random_WordList() { var manager = new GameManager(); var list = manager.MakeRandomWordList(7); list.ForEach(x => Console.WriteLine(x.Name)); Assert.AreEqual(7, list.Count); } [Test] public void Get_Random_WordBoard() { var manager = new GameManager(); var boardSize = 10; var wordCount = 7; var board = manager.MakeRandomWordBoard(boardSize, wordCount); for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { Console.Write(board[i,j] + " "); } Console.WriteLine(); } Assert.NotNull(board[0,0]); } [Test] public void UserInputWork() { var manager = new GameManager(); var user = new User(); var boardSize = 10; var wordCount = 7; var board = new char[10,10]; board[0, 0] = 'b'; board[0, 1] = 'a'; board[0, 2] = 'k'; board[0, 3] = 'e'; var userInput = new List<Tuple<int, int>>(); userInput.Add(Tuple.Create(0, 0)); userInput.Add(Tuple.Create(0, 1)); userInput.Add(Tuple.Create(0, 2)); userInput.Add(Tuple.Create(0, 3)); var wordList = manager.MakeAllWordList(); var sb = new StringBuilder(); foreach (var tuple in userInput) { sb.Append(board[tuple.Item1,tuple.Item2]); } Console.WriteLine(sb); bool correct = wordList.Exists(x => x.Name == sb.ToString()); Assert.IsTrue(correct); } } }
Java
UTF-8
453
2.046875
2
[]
no_license
package com.coursera.admin.web.model; public class Token { public static String tokenID; public static String cognitoUserId; public static String getTokenID() { return tokenID; } public static void setTokenID(String tokenID) { Token.tokenID = tokenID; } public static String getCognitoUserId() { return cognitoUserId; } public static void setCognitoUserId(String cognitoUserId) { Token.cognitoUserId = cognitoUserId; } }
Markdown
UTF-8
2,053
2.984375
3
[]
no_license
# Trigger Pull Repo This little NodeJS app updates your local git repository when there is a change on the branch *master* of your remote repository. It uses a github webhook. ## Prerequisites * OS: Ubuntu * Already installed: [NodeJS](https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions), [npm](https://docs.npmjs.com/getting-started/installing-node) * Have an SSH access to Github: [Documentation](https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/) ## Installation ### Server Side #### Install nodegit Dependencies ```bash $ sudo add-apt-repository ppa:ubuntu-toolchain-r/test $ sudo apt update $ sudo apt install libstdc++-4.9-dev $ sudo apt install libssl-dev ``` #### Install pm2 ```bash $ npm install pm2 -g ``` #### Install App ```bash $ git clone https://github.com/petersg83/trigger_pull_repo $ cd trigger_pull_repo $ cp config.js.dist config.js $ npm install ``` Edit `config.js` with your information. Example: ```javascript module.exports = { repositoryPath: '/home/myname/myrepository', urlToListen: '/updateRepository', portToListen: 8000 } ``` #### Launch App ```bash $ pm2 start track_blog_modification.js ``` ### Github Side Go to your Github repository page: **Settings > Webhooks > Add webhook**. * **Payload URL**: put your payload URL according to your `config.js`. For example: `http://mywebsite.com:8000/updateRepository` * **Content type**: choose `application/json` * **Secret**: let empty * **Which events would you like to trigger this webhook?**: choose `Just the push event.` * **Active**: check it You're done :blush: ## Bonus If you need to restart your application after updating your local repository, it can be done automatically by using `pm2` and the option `--watch`. For example to launch an [Hexo](https://hexo.io/) blog, I use this script (hexo.sh): ```bash # !/usr/bin/env bash hexo server -p 8081 -i 127.0.0.1 ``` and this command line to launch it: ```bash $ pm2 start hexo.sh --watch --ignore-watch="db.json node_modules" ```
Ruby
UTF-8
373
2.65625
3
[]
no_license
towns = SmarterCSV.process('public/src_files/town_data.csv') towns.each do |town| town.delete :fecha town.delete :id_municipio town.delete :id_provincia Town.create town end parties = SmarterCSV.process('public/src_files/party_data.csv') parties.each do |party| town= Town.find_by town_code: party[:town_code] town.parties.create party end puts "Rake complete!"
C++
UTF-8
2,867
2.640625
3
[]
no_license
/* * Software by Thanh Phung -- thanhtphung@yahoo.com. * No copyrights. No warranties. No restrictions in reuse. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <new> #include <string> #include "appkit/CmdLine.hpp" #include "appkit/DelimitedTxt.hpp" #include "syskit/RefCounted.hpp" #include "syskit/macros.h" using namespace appkit; using namespace syskit; const char CMD_LINE[] = "/proc/self/cmdline"; const unsigned int BUF_SIZE = 4096; BEGIN_NAMESPACE class CmdLine1: public RefCounted { public: const CmdLine* cmdLine() const; virtual ~CmdLine1(); virtual void destroy() const; static const CmdLine1& instance(); private: CmdLine* cmdLine_; CmdLine1(); String getCmdLine(); String normalize(const String&); }; inline const CmdLine* CmdLine1::cmdLine() const { return cmdLine_; } CmdLine1::CmdLine1(): RefCounted(0) { String cmd00 = getCmdLine(); String cmdLine = normalize(cmd00); cmdLine_ = new CmdLine(cmdLine); } CmdLine1::~CmdLine1() { delete cmdLine_; } const CmdLine1& CmdLine1::instance() { static const CmdLine1* s_cmdLine1 = new CmdLine1; return *s_cmdLine1; } void CmdLine1::destroy() const { delete this; } String CmdLine1::getCmdLine() { String cmd00; int fd = open(CMD_LINE, O_RDONLY); if (fd >= 0) { for (;;) { char buf[BUF_SIZE]; ssize_t bytesRead = read(fd, buf, sizeof(buf)); if (bytesRead > 0) { cmd00.append(buf, bytesRead); continue; } break; } close(fd); } return cmd00; } String CmdLine1::normalize(const String& cmd00) { String cmdLine; const char* arg; size_t length; DelimitedTxt it(cmd00, false, 0); while (it.next(arg, length)) { if (!cmdLine.empty()) { cmdLine.append(1, ' '); } // Argument already in quotes. if (((arg[0] == '\'') || (arg[0] == '"')) && (arg[length - 1] == arg[0])) { cmdLine.append(arg, length); } // Enquote each argument just in case it contains some whitespace. else { cmdLine.append(1, '"'); cmdLine.append(arg, length); cmdLine.append(1, '"'); } } return cmdLine; } static RefCounted::Count s_cmdLine1Lock(CmdLine1::instance()); END_NAMESPACE BEGIN_NAMESPACE1(appkit) //! //! Return the singleton command line for the calling process. //! Each DLL/EXE has its own copy. //! const CmdLine& CmdLine::instance() { const CmdLine1& cmdLine1 = CmdLine1::instance(); return *cmdLine1.cmdLine(); } END_NAMESPACE1
C++
UTF-8
2,945
2.828125
3
[ "Apache-2.0" ]
permissive
#include "CacheConfig.hh" #include <string> #include "inipp.h" CacheConfig::CacheConfig(const CacheType type, const uint64_t size, const int line_size, const int set_size) : type(type), size(size), line_size(line_size), set_size(set_size) { } CacheConfig::CacheConfig(std::istream&& config_file) { inipp::Ini<char> ini; ini.parse(config_file); // Check that at most one level is defined // Otherwise, a CacheHierarcy, not a single Cache, should be build from this file if (ini.sections.size() == 1) { if (!ini.sections.begin()->first.empty()) throw std::invalid_argument("Invalid section in cache config file: " + ini.sections.begin()->first); } else if (ini.sections.size() > 2) throw std::invalid_argument("Too many sections section in cache config file: " + std::to_string(ini.sections.size())); else { // If there are exactly two sections, they must be "hierarchy" and "L1" for (const auto& section : ini.sections) if (section.first != "hierarchy" && section.first != "L1") throw std::invalid_argument("Invalid section in cache config file: " + section.first); try { const int nlevels = std::stoi(ini.sections.at("hierarchy").at("levels")); if (nlevels != 1) throw std::invalid_argument("Too many levels for a single cache: " + std::to_string(nlevels)); } catch (const std::out_of_range& e) { std::cout << "Malformed config file: " << e.what() << "\n"; } } auto config_section = ini.sections.size() == 1 ? ini.sections.at("") : ini.sections.at("L1"); read_config_map_(config_section); } CacheConfig::CacheConfig(const ConfigMap& config_map) { read_config_map_(config_map); } void CacheConfig::read_config_map_(const ConfigMap& config_map) { try { size = std::stoi(config_map.at("cache_size")); line_size = std::stoi(config_map.at("line_size")); set_size = config_map.find("set_size") != std::end(config_map) ? std::stoi(config_map.at("set_size")) : 1; } catch (const std::out_of_range& e) { throw std::invalid_argument(std::string("Malformed config file: ") + e.what()); } auto typestr = config_map.at("type"); typestr.erase(std::remove_if(typestr.begin(), typestr.end(), [](unsigned char c) { return std::isspace(c) || std::ispunct(c); })); std::transform(typestr.begin(), typestr.end(), typestr.begin(), [](unsigned char c) { return std::tolower(c); }); if (typestr == "infinite") type = CacheType::Infinite; else if (typestr == "directmapped") type = CacheType::DirectMapped; else if (typestr == "setassociative") type = CacheType::SetAssociative; else { throw std::invalid_argument("Invalid cache type in config file: " + typestr); } }
Markdown
UTF-8
7,060
3.140625
3
[ "MIT" ]
permissive
# README Library to access and modify the contents of an Epub ![logo](https://github.com/completelynovel/epub/raw/master/docs/logo.png) ## Usage Initialize with the path to an epub file, note any setters will edit the epub itself, so work on a copy if you don't want to modify the original epub = Epub::Document.new("9781449315306.epub") ### Structure An epub is defined into the following parts, the accessor methods are as named below * **metadata** - Metadata about to book (title, description etc...) * **manifest** - All the files in the epub * **guide** - NOT CURRENTLY ACCESSIBLE * **spine** - Ordered list of html files in the Epub * **toc** - Table of contents which refers to items in the manifest ### Accessing content The following describes how to access the content, example code for the below is [here](https://github.com/completelynovel/epub/tree/master/examples) #### Metadata To access the metadata epub.metadata #=> #<Epub::Metadata> You can set/get metadata in the Epub by using the Hash accessor, for example # Getter epub.metadata[:title] #=> "Behind the scenes: Badgers in offices" # Setter epub.metadata[:description] = "Secret look into the life of Badgers in offices" #### Manifest The manifest if the entry point to files in the epub, an Epub usually contains css, html, images and may also contain fonts. There are also some special files which define the structure of the epub which this gem hides from its API. To access the manifest epub.manifest #=> #<Epub::Manifest> Files within the Epub are refered to as 'items', you can access files directly via the `item` method passing either the *id* of the item in the manifest file or the absolute path to file from the root of the epub zip. epub.manifest.get(:id => "cover") #=> #<Epub::Item> epub.manifest.get(:path => "OEBPS/cover.html") #=> #<Epub::Item> Although its more likely that you don't have this information. To access all items in the Epub epub.manifest.items #=> [#<Epub::Item>, #<Epub::Item>, ...] You can also retrieve them by their type epub.manifest.html #=> [#<Epub::Item>, #<Epub::Item>, ...] epub.manifest.css #=> [#<Epub::Item>, #<Epub::Item>, ...] epub.manifest.images #=> [#<Epub::Item>, #<Epub::Item>, ...] epub.manifest.misc #=> [#<Epub::Item>, #<Epub::Item>, ...] # Group everything but html (css/images/misc) epub.manifest.assets #=> [#<Epub::Item>, #<Epub::Item>, ...] #### Spine The spine gives you the ordered list of html items which make up the epub. To access the spine epub.spine #=> #<Epub::Spine> epub.spine.items #=> [#<Epub::Item>, #<Epub::Item>, ...] #### Toc (Table of Contents) To access the toc epub.toc #=> #<Epub::Toc> To retrieve its contents epub.toc.as_hash # => Returns a nested hash of: # { # :label=>"Colophon", # :url=>"ch01.html#heading1", # :children=>[ # # Nested here # ], # } Passing `:normalize => true` will returned the flattened urls if its not already flattened ### Modifing files When ever you have an instance of a `Epub::Item` you can edit that file in place, for example to modify the first item in the epub # Get the first html item item = epub.spine.items.first # Display its contents puts item.read html = <<END <html> <body> <h1>Badger badger badger</h1> <p> Badger badger badger badger badger badger badger badger badger badger badger badger Mushroom mushroom </p> </body> </html>" END # Replace its contents item.write(html) ### Standardizing TODO!!! ePub standardization ensures the epub is valid ready for manipulation. The `standardize` command does the following: - html: - ensure proper head and body tags - strip js from html - css - namespace to avoid style conflicts - manifest - ensure references exist for all assets - ensure assets exist ### Normalizing Calling `normalize!` on an epub will normalise the directory struture, renaming all the urls in the css/html for the items in the manifest. For example the following directory structure / |-- META-INF | `-- container.xml |-- mimetype `-- OEBPS |-- random_dir1 |-- chA.css |-- ch01.html |-- ch02.html |-- image.jpg |-- random_dir2 |-- chB.css |-- ch03.html |-- ch04.html |-- image.jpg |-- toc.ncx |-- content.opf Will be normalized into the following format, note the file names get renamed to a MD5 hash of there original absolute filepath to ensure uniqueness / |-- META-INF | `-- container.xml |-- mimetype `-- OEBPS |-- content.opf |-- content |-- 899ee1.css (was chA.css) |-- f54ff6.css (was chB.css) |-- c4b944.html (was ch01.html) |-- 4e895b.html (was ch02.html) |-- 89332e.html (was ch03.html) |-- c50b75.html (was ch04.html) |-- toc.ncx |-- assets |-- 5a17aa.jpg (was image.jpg) |-- b50b4b.jpg (was image.jpg) ## Extracting If you want to extract an epub, for instance to serve the content up via a web interface you can to the following Epub::Document.extract('example.epub', '/some/directory/path') You can also pass a block which will re-zip the epub when the block exits. The block gets passed a <#Epub::Document> instance as an argument Epub::Document.extract('example.epub') do |epub| # Do some epub processing here... end ## Development To get extra logging either run with `ruby -v` which will be very verbose, or if you want just the library log lines run with `LIB_VERBOSE=true`. For example to run the [example scripts](https://github.com/completelynovel/epub/tree/master/examples) with verbose logging do either of the following ruby -v normalize.rb LIB_VERBOSE=true ruby normalize.rb ## Epub overview (TODO) An Epub is simply a zip file which has been with the `.epub` extension. Lets take a look at the [example.epub](TODO) mkdir extracted cp example.epub extracted/example.zip cd extracted unzip example.zip You should now have the following file structure extracted |-- META-INF | `-- container.xml (spec http://idpf.org/epub/20/spec/OCF_2.0.1_draft.doc) |-- mimetype `-- OEBPS |-- random_dir1 |-- chA.css |-- ch01.html |-- ch02.html |-- image.jpg |-- random_dir2 |-- chB.css |-- ch03.html |-- ch04.html |-- image.jpg |-- toc.ncx |-- content.opf (spec http://idpf.org/epub/20/spec/OPF_2.0.1_draft.htm) Explain further... ## Further documentation Yardoc is used for the documentation, you can start a server and see the docs by running the following command. yard server --reload
JavaScript
UTF-8
1,241
2.9375
3
[]
no_license
var bird; var pipes = []; var speed = 3; var tick = 0; var initJump = false; var counter = 0; var score; function setup() { createCanvas(window.innerWidth,window.innerHeight); bird = new Bird(); score = new Score(); } function draw() { background(52, 235, 235); for (var i = pipes.length-1; i >= 0; i--) { pipes[i].show(); pipes[i].update(); if (pipes[i].x == bird.x || pipes[i].x == bird.x + 1 || pipes[i].x == bird.x - 1) { counter++; console.log(counter); } if (pipes[i].kill()) { pipes.splice(i,1); } if (pipes[i].deadBird() || bird.y > height || bird.y < 0) { noLoop(); reset(); } } score.scoreboard(counter); if (tick == 200) { tick = 0; pipes.push(new Pipe()); } tick++; bird.show(); if (initJump) { bird.update(); } } function keyPressed() { if (key == ' ') { bird.jump(); initJump = true; } } function reset() { pipes.splice(0,pipes.length); bird.setColor(255, 255, 255); counter = 0; bird.y = height/2; initJump = false; loop(); }
Java
UTF-8
368
1.984375
2
[]
no_license
package com.lin.framework.soap; import com.lin.model.Customer; /** * @author lkmc2 * @date 2018/9/18 * @since 1.0.0 * @description 客户SOAP接口服务 */ public interface CustomerSoapService { /** * 根据客户ID获取客户对象 * @param customerId 客户id * @return 客户对象 */ Customer getCustomer(long customerId); }
Go
UTF-8
3,641
3.59375
4
[]
no_license
package tablet import ( "fmt" "regexp" "strconv" ) // Tablet describes a programmable sound making device type Tablet struct { instructions []instruction registers map[string]int playedSounds []int } // Make constructs a Tablet from a set of programming instructions func Make(rawInstructions []string) Tablet { tab := Tablet{ instructions: []instruction{}, registers: map[string]int{}, } instructionRegex := regexp.MustCompile(`^([a-z]+) (([a-z])|([0-9-]+))( (([a-z])|([0-9-]+)))?$`) for _, i := range rawInstructions { if matches := instructionRegex.FindStringSubmatch(i); matches != nil { command := matches[1] operandAReg := matches[3] operandAVal := matches[4] operandBReg := matches[7] operandBVal := matches[8] var opA operand if operandAReg != "" { tab.registers[operandAReg] = 0 opA = operand{ typ: "reg", inputRegister: operandAReg, } } else if operandAVal != "" { bVal, err := strconv.Atoi(operandAVal) if err != nil { panic(fmt.Errorf("failed converting opA value: %s", operandAVal)) } opA = operand{ typ: "val", inputVal: bVal, } } var opB operand if operandBReg != "" { tab.registers[operandBReg] = 0 opB = operand{ typ: "reg", inputRegister: operandBReg, } } else if operandBVal != "" { bVal, err := strconv.Atoi(operandBVal) if err != nil { panic(fmt.Errorf("failed converting opB value: %s", operandBVal)) } opB = operand{ typ: "val", inputVal: bVal, } } newInstruction := instruction{ command: command, operandA: opA, operandB: opB, } tab.instructions = append(tab.instructions, newInstruction) continue } panic(fmt.Errorf("instruction %s not understood", i)) } return tab } // Reset initialises the Tablet to a starting position where // all internal registers are set to zero. func (t *Tablet) Reset() { for r := range t.registers { t.registers[r] = 0 } } // Run executes the Tablet's instructions func (t *Tablet) Run() int { programCounter := 0 for programCounter < len(t.instructions) { thisInstruction := t.instructions[programCounter] programCounter++ switch thisInstruction.command { case "set": t.registers[thisInstruction.operandA.inputRegister] = t.valueOfOperand(thisInstruction.operandB) case "add": t.registers[thisInstruction.operandA.inputRegister] += t.valueOfOperand(thisInstruction.operandB) case "mul": t.registers[thisInstruction.operandA.inputRegister] *= t.valueOfOperand(thisInstruction.operandB) case "mod": t.registers[thisInstruction.operandA.inputRegister] = t.valueOfOperand(thisInstruction.operandA) % t.valueOfOperand(thisInstruction.operandB) case "snd": t.playedSounds = append(t.playedSounds, t.valueOfOperand(thisInstruction.operandA)) case "rcv": if t.valueOfOperand(thisInstruction.operandA) > 0 { return t.playedSounds[len(t.playedSounds)-1] } case "jgz": if t.valueOfOperand(thisInstruction.operandA) > 0 { programCounter += (t.valueOfOperand(thisInstruction.operandB) - 1) } default: panic("instruction type not understood: " + thisInstruction.command) } // fmt.Println(t.registers, programCounter) } panic("program exited with no rcv instruction") } func (t *Tablet) valueOfOperand(op operand) int { if op.typ == "val" { return op.inputVal } return t.registers[op.inputRegister] } type instruction struct { command string operandA operand operandB operand } type operand struct { typ string inputRegister string inputVal int }
TypeScript
UTF-8
609
3
3
[ "Apache-2.0" ]
permissive
import { set } from './set.js' import type { Writable } from './writable.js' /** * Returns a function to set the given store using the value returned by `setter`. * This is useful in conjunction with [subscribe](#subscribe). */ export function set_store_<Val extends unknown = unknown>( store:Writable<Val>, setter = (v:Val)=>v ):set_store_T<Val> { return (val:Val)=> set<Val>(store, typeof setter === 'function' ? setter.call(setter, val) : setter) } export type set_store_T<Val extends unknown = unknown> = (val:Val)=>void export { set_store_ as _set_store, set_store_ as _set__store, }
Shell
UTF-8
2,520
3.953125
4
[ "MIT" ]
permissive
#!/bin/bash set -e setupSSH() { local SSH_PATH="$HOME/.ssh" mkdir -p "$SSH_PATH" touch "$SSH_PATH/known_hosts" echo "$INPUT_KEY" > "$SSH_PATH/deploy_key" chmod 700 "$SSH_PATH" chmod 600 "$SSH_PATH/known_hosts" chmod 600 "$SSH_PATH/deploy_key" eval $(ssh-agent) ssh-add "$SSH_PATH/deploy_key" ssh-keyscan -t rsa $INPUT_PROXY_HOST >> "$SSH_PATH/known_hosts" } executeSSH() { if [ -z "$1" ]; then return fi local LINES=$1 local COMMAND="" # holds all commands separated by semi-colon local COMMANDS="" # this while read each commands in line and # evaluate each line agains all environment variables while IFS= read -r LINE; do LINE=$(eval 'echo "$LINE"') LINE=$(eval echo "$LINE") COMMAND=$(echo $LINE) if [ -z "$COMMANDS" ]; then COMMANDS="$COMMAND" else COMMANDS="$COMMANDS&&$COMMAND" fi done <<< $LINES echo "ssh -o StrictHostKeyChecking=no -p ${INPUT_PROXY_PORT:-22} $INPUT_PROXY_USER@$INPUT_PROXY_HOST \"ssh -o StrictHostKeyChecking=no -p ${INPUT_DST_PORT:-22} $INPUT_DST_USER@$INPUT_DST_HOST \\\"${COMMANDS%&&*}\\\"\"" ssh -o StrictHostKeyChecking=no -p ${INPUT_PROXY_PORT:-22} $INPUT_PROXY_USER@$INPUT_PROXY_HOST "ssh -o StrictHostKeyChecking=no -p ${INPUT_DST_PORT:-22} $INPUT_DST_USER@$INPUT_DST_HOST \"${COMMANDS%&&*}\"" } executeRsync() { local LINES=$1 local COMMAND= # this while read each commands in line and # evaluate each line agains all environment variables while IFS= read -r LINE; do LINE=$(eval 'echo "$LINE"') LINE=$(eval echo "$LINE") COMMAND=$(echo $LINE) if [ -z "$INPUT_CACHE" ]; then echo "rsync $INPUT_RSYNC_FLAGS -e \"ssh -o StrictHostKeyChecking=no -p ${INPUT_PROXY_PORT:-22}\" $INPUT_SRC_FILE $INPUT_PROXY_USER@$INPUT_PROXY_HOST:$INPUT_PROXY_FILE_PATH" # scp to board rsync $INPUT_RSYNC_FLAGS -e "ssh -o StrictHostKeyChecking=no -p ${INPUT_PROXY_PORT:-22}" $INPUT_SRC_FILE $INPUT_PROXY_USER@$INPUT_PROXY_HOST:$INPUT_PROXY_FILE_PATH # scp from board to dst fi ssh -o StrictHostKeyChecking=no -p ${INPUT_PROXY_PORT:-22} $INPUT_PROXY_USER@$INPUT_PROXY_HOST rsync $INPUT_PROXY_FILE_PATH/$INPUT_SRC_FILE $INPUT_DST_USER@$INPUT_DST_HOST:$INPUT_DST_FILE_PATH done <<< $LINES } setupSSH echo "------------ RUNNING BEFORE SSH ------------" executeSSH "$INPUT_SSH_BEFORE" echo "------------ RUNNING Rsync ------------" executeRsync echo "------------ RUNNING AFTER SSH ------------" executeSSH "$INPUT_SSH_AFTER"
JavaScript
UTF-8
398
3.84375
4
[]
no_license
function max() { let x = document.getElementById("FirstNumber").value let y = document.getElementById("SecondNumber").value document.getElementById("result").value = Math.max(x, y); } function min() { let x = document.getElementById("FirstNumber").value let y = document.getElementById("SecondNumber").value document.getElementById("result").value = Math.min(x, y); }
Python
UTF-8
194
3.1875
3
[]
no_license
# print sentences print "Hello World!" print "Hello Again" print "I like typing this" print "This is fun" print "Yay! Printing" print "I'd much rather you 'not" print 'I "said do not touch this'
Python
UTF-8
2,891
2.53125
3
[ "MIT" ]
permissive
from base64 import b64encode, b64decode import unittest from hamcrest import * from nose.tools import raises from backdrop.core.bucket import Bucket, BucketConfig from backdrop.core.errors import ValidationError from tests.core.test_bucket import mock_repository, mock_database class TestBucketAutoIdGeneration(unittest.TestCase): def setUp(self): self.mock_repository = mock_repository() self.mock_database = mock_database(self.mock_repository) def test_auto_id_for_a_single_field(self): objects = [{ "abc": "def" }] config = BucketConfig("bucket", data_group="group", data_type="type", auto_ids=["abc"]) bucket = Bucket(self.mock_database, config) bucket.parse_and_store(objects) self.mock_repository.save.assert_called_once_with({ "_id": b64encode("def"), "abc": "def" }) def test_auto_id_generation(self): objects = [{ "postcode": "WC2B 6SE", "number": "125", "name": "Aviation House" }] config = BucketConfig("bucket", data_group="group", data_type="type", auto_ids=("postcode", "number")) bucket = Bucket(self.mock_database, config) bucket.parse_and_store(objects) self.mock_repository.save.assert_called_once_with({ "_id": b64encode("WC2B 6SE.125"), "postcode": "WC2B 6SE", "number": "125", "name": "Aviation House" }) def test_no_id_generated_if_auto_id_is_none(self): object = { "postcode": "WC2B 6SE", "number": "125", "name": "Aviation House" } config = BucketConfig("bucket", data_group="group", data_type="type") bucket = Bucket(self.mock_database, config) bucket.parse_and_store([object]) self.mock_repository.save.assert_called_once_with(object) @raises(ValidationError) def test_validation_error_if_auto_id_property_is_missing(self): objects = [{ "postcode": "WC2B 6SE", "name": "Aviation House" }] config = BucketConfig("bucket", data_group="group", data_type="type", auto_ids=("postcode", "number")) bucket = Bucket(self.mock_database, config) bucket.parse_and_store(objects) def test_auto_id_can_be_generated_from_a_timestamp(self): objects = [{ "_timestamp": "2013-08-01T00:00:00+00:00", "foo": "bar" }] config = BucketConfig("bucket", data_group="group", data_type="type", auto_ids=["_timestamp", "foo"]) bucket = Bucket(self.mock_database, config) bucket.parse_and_store(objects) saved_object = self.mock_repository.save.call_args[0][0] assert_that(b64decode(saved_object['_id']), is_("2013-08-01T00:00:00+00:00.bar"))
Python
UTF-8
1,809
2.640625
3
[]
no_license
from ..base_node import BaseNode from ...core import socket_types as socket_types from ...core.Constants import Colors class Vector3(BaseNode): def __init__(self, scene, x=0, y=0): super().__init__(scene, title_background_color=Colors.vector3, x=x, y=y) self.change_title("[0.0, 0.0, 0.0]") self.output_vector = self.add_output(socket_types.Vector3SocketType(self), "vec3") self.output_x = self.add_output(socket_types.FloatSocketType(self), "x") self.output_y = self.add_output(socket_types.FloatSocketType(self), "y") self.output_z = self.add_output(socket_types.FloatSocketType(self), "z") _, self.txt_x = self.add_label_float("x: ", number_changed_function=self.number_changed) _, self.txt_y = self.add_label_float("y: ", number_changed_function=self.number_changed) _, self.txt_z = self.add_label_float("z: ", number_changed_function=self.number_changed) def number_changed(self): for txt in [self.txt_x, self.txt_y, self.txt_z]: if txt.text() == "": txt.setText("0.0") try: self.output_vector.set_value([float(self.txt_x.text()), float(self.txt_y.text()), float(self.txt_z.text())]) self.output_x.set_value(float(self.txt_x.text())) self.output_y.set_value(float(self.txt_y.text())) self.output_z.set_value(float(self.txt_z.text())) except ValueError as err: self.output_vector.set_value([0.0, 0.0, 0.0]) self.set_dirty(True) self.compute() def compute(self, force=False): if self.is_dirty(): self.change_title("[%s, %s, %s]" % (self.txt_x.text(), self.txt_y.text(), self.txt_z.text())) super().compute(force=force) self.set_dirty(False)
C++
UTF-8
507
2.875
3
[]
no_license
class Solution { public: bool judgeCircle(string moves) { int L = 0; int U = 0; for(int i = 0;i<moves.length();i++){ if(moves[i]=='R'){ L--; } else if(moves[i]=='L'){ L++; } else if(moves[i]=='D'){ U--; } else{ U++; } } if(L==0 && U==0){ return true; } return false; } };
Java
UTF-8
925
2.875
3
[]
no_license
package ie.gmit.sw; public class FinalResult { //variables for storing. private String fileName; private double jaccardSimilarity; private double minHashSimilarity; //constructor public FinalResult(String fileName, double jaccardSimilarity, double minHashSimilarity) { this.fileName = fileName; this.jaccardSimilarity = jaccardSimilarity; this.minHashSimilarity = minHashSimilarity; } //---Getters and setters--- public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public double getJaccardSimilarity() { return jaccardSimilarity; } public void setJaccardSimilarity(double jaccardSimilarity) { this.jaccardSimilarity = jaccardSimilarity; } public double getMinHashSimilarity() { return minHashSimilarity; } public void setMinHashSimilarity(double minHashSimilarity) { this.minHashSimilarity = minHashSimilarity; } }
Java
UTF-8
2,049
3.5625
4
[]
no_license
import java.util.Iterator; /** * @author jayadeepj * * GenericResizingStack : Doubles the size of the array in push() if it is full * Also the size of the array is halved in pop() if it is less than one-quarter full. * The Stack is able to handle generic entities. * @param <Item> */ public class GenericResizingStack<Item> implements Iterable<Item>{ private Item[] stackStorage = null; private int currentStackIndex; public GenericResizingStack(Item[] stackStorage) { super(); this.stackStorage = stackStorage; } @SuppressWarnings("unchecked") public GenericResizingStack() { super(); stackStorage = (Item[]) new Object[10]; currentStackIndex = -1; } public Item pop() { if(currentStackIndex<0) throw new RuntimeException("Currently No Elements in GenericResizingStack to POP "); Item item = stackStorage[currentStackIndex]; stackStorage[currentStackIndex--] = null; if(currentStackIndex<=(stackStorage.length/4)) updateStackStorageSize(0.5); return item; } public void push(Item item) { if(currentStackIndex>=stackStorage.length) updateStackStorageSize(2.0); stackStorage[++currentStackIndex] = item; } public void updateStackStorageSize(double updateFactor) { Item[] tempStackStorage = (Item[]) new Object[(int)(stackStorage.length*updateFactor)]; for (int i = 0; i < Math.min(stackStorage.length, tempStackStorage.length); i++) { tempStackStorage[i] = stackStorage[i]; } stackStorage = tempStackStorage; tempStackStorage = null; } public int getCurrentStackSize() { return currentStackIndex+1; } public boolean isEmpty() { return (currentStackIndex >= 0); } @Override public Iterator<Item> iterator() { return new GenericResizingStackIterator(); } private class GenericResizingStackIterator implements Iterator<Item>{ @Override public boolean hasNext() { return (currentStackIndex >= 0); } @Override public Item next() { return pop(); } @Override public void remove() { pop(); } } }
C++
UTF-8
615
2.546875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int test; cin >> test; for(int i=1; i<=test; i++) { double v1,v2,a1,a2,v3,d,s; cin >> v1 >> v2 >> v3 >> a1 >> a2; d = (((v1*v1)/a1) + ((v2*v2)/a2))/2; //s = (v1/a1)*v3; //if(s <= d) s = (v2/a2)*v3; double time1 = v1/a1; double time2 = v2/a2; double t; if(time1 > time2) t = time1; else t = time2; s = t * v3; printf("Case %d: %lf %lf\n",i,d,s); } return 0; }
Python
UTF-8
1,052
3
3
[]
no_license
class UnionFind: def __init__(self): self.id = {} self.weight = {} def __getnode__(self, node): if not node in self.id: self.id[node] = node self.weight[node] = 1 def root(self, node): while self.id[node] != node: self.id[node] = self.id[self.id[node]] node = self.id[node] return node def unite(self, nodepair): root1 = self.root(nodepair[0]) root2 = self.root(nodepair[1]) if root1 != root2: if self.weight[root1] < self.weight[root2]: self.id[root1] = self.root(root2) self.weight[root2] += self.weight[root1] else: self.id[root2] = self.root(root1) self.weight[root1] += self.weight[root2] return True else: return False def find(self, nodepair): return self.root(nodepair[0])== self.root(nodepair[1])
Python
UTF-8
3,114
2.828125
3
[]
no_license
import xlrd from xlutils.copy import copy from interface.pn1.utils.public import * from interface.pn1.utils.excal_data import * class OperationExcal: def getExcal(self): db = xlrd.open_workbook(data_dir(data='data', fileName='data3.xlsx')) # 获取excal第一个sheet sheet = db.sheet_by_index(0) return sheet def get_rows(self): """获取excal的行数""" return self.getExcal().nrows def get_row_cell(self, row, col): """ 获取单元格内容 :param row: 行 :param col: 列 :return: 内容 """"" return self.getExcal().cell_value(row, col) def get_caseID(self, row): """获取测试ID""" return self.get_row_cell(row, getCaseID()) def get_url(self, row): """获取请求地址""" # 行不确定,列确定 return self.get_row_cell(row, getUrl()) def get_request_data(self, row): """获取请求参数""" return self.get_row_cell(row, get_request_data()) def get_except(self, row): """获取期望结果""" return self.get_row_cell(row, getExcept()) def get_result(self, row): """获取实际结果""" return self.get_row_cell(row, getResult()) def writeResult(self, row, content): """将测试结果写入excal""" """ ce1.获取结果参数在ezcal中的列 2.打开ecxal将之前的内容去除复制 3.在将测试结果content写入,保存 """ # 获取测试结果在excal中的列 col = getResult() print(col) # excal 文件内容修改,此处excal写入存在问题 work = xlrd.open_workbook(data_dir(data="data", fileName='data3.xlsx')) old_content = copy(work) ws = old_content.get_sheet(0) ws.write(row, col, content) old_content.save(data_dir(data="data", fileName='data3.xls')) def getAll(self): """获取所有的测试用例数""" return int(self.get_rows() - 1) def run_success_result(self): """获取成功的测试用例数""" pass_count = [] # fail_count = None # print(self.get_rows()) for i in range(1, self.get_rows()): if self.get_result(row=i) == 'pass': pass_count.append(i) return int(len(pass_count)) def run_fail_result(self): """获取失败的测试列数""" return int(self.getAll()-self.run_success_result()) def run_pass_rate(self): """获取测试用例的通过率""" rate = ' ' if self.run_fail_result() == 0: rate = '100%' elif self.run_fail_result() != 0: rate = str(int(self.run_success_result()/self.getAll()*100)) + '%' return rate if __name__ == '__main__': opera = OperationExcal() # print(opera.writeResult(row=ce1, content='pass')) # print(opera.getSuccess()) #print(opera.get_rows()) # print(opera.run_success_result()) # print(opera.run_pass_rate()) print(opera.run_pass_rate())
C#
UTF-8
2,949
2.53125
3
[]
no_license
using AutoMapper; using MVCProject.Models; using MVCProject.Models.Repository; using MVCProject.Service.Interface; using MVCProject.Service.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MVCProject.Service { public class ProductService: BaseService, IProductService { public ProductService(BaseDbContext db, RepositoryWrapper repository, IMapper mapper) : base(db, repository, mapper) { } public IResult Create(ProductsViewModel instance) { if (instance == null) { throw new ArgumentNullException(); } IResult result = new Result(false); try { var product = _mapper.Map<ProductsViewModel, ProductsModel>(instance); product.ProductID = 0; _repository.products.Create(product); result.Success = true; } catch (Exception ex) { result.Exception = ex; } return result; } public IResult Update(ProductsViewModel instance) { if (instance == null) { throw new ArgumentNullException(); } IResult result = new Result(false); try { var product = _mapper.Map<ProductsViewModel, ProductsModel>(instance); _repository.products.Update(product); result.Success = true; } catch (Exception ex) { result.Exception = ex; } return result; } public IResult Delete(int productID) { IResult result = new Result(false); if (!this.IsExists(productID)) { result.Message = "資料不存在"; } try { var instance = _repository.products.Get(x => x.ProductID == productID); _repository.products.Delete(instance); result.Success = true; } catch (Exception ex) { result.Exception = ex; } return result; } public bool IsExists(int productID) { return _repository.products.GetAll().Any(x => x.ProductID == productID); } public ProductsViewModel GetByID(int productID) { var product = _repository.products.Get(x => x.ProductID == productID); return _mapper.Map<ProductsModel, ProductsViewModel>(product); } public IEnumerable<ProductsViewModel> GetAll() { var products = _repository.products.GetAllInclude("Category"); return _mapper.Map<IEnumerable<ProductsModel>, IEnumerable<ProductsViewModel>>(products); } } }
JavaScript
UTF-8
2,292
2.53125
3
[]
no_license
import React, {Component} from 'react' import jss from './JSS.jsx' import { Area, AreaChart, CartesianAxis, Tooltip, ResponsiveContainer, XAxis, YAxis, } from 'recharts' const brandColor = '#FF5443' const chartHeight = 200 const {classes} = jss.createStyleSheet({ root : { background : brandColor, color : '#FFF', paddingTop : '6em', }, info : { height : `${chartHeight}px`, textAlign : 'center', }, }).attach() type Props = { cities : string[], } class Stats extends Component<Props> { state = { data : [], } render() { const {data} = this.state const chart = ( <ResponsiveContainer height={200}> <AreaChart data={data} margin={{top: 0, right: 0, left: 0, bottom: 0}}> <CartesianAxis /> <XAxis dataKey='date' tick={{fill: '#FFF'}} axisLine={false} tickLine={false} /> <YAxis dataKey='temperature' tick={{fill: '#FFF'}} axisLine={false} tickLine={false} orientation='right' /> <Area dataKey='temperature' fill='#FFF' stroke={brandColor} /> <Tooltip wrapperStyle={{}} /> </AreaChart> </ResponsiveContainer> ) const emptyState = ( <div className={classes.info}>Pick one or more cities below to show up them</div> ) return ( <div className={classes.root}> {this.props.cities.length > 0 ? chart : emptyState} </div> ) } componentDidMount() { this._refreshData() } componentWillReceiveProps() { this._refreshData() } _refreshData = () => { const {cities} = this.props fetch('/api/chart?cities=' + cities.join(',')).then(resp => { return resp.json() }).then(data => { this.setState({ data }) }).catch(err => { // Ugly but at least it works console.error(err) alert('Cannot fetch data for chart') }) } } export default Stats
C++
GB18030
694
3.75
4
[]
no_license
#include <iostream> #include <string> using namespace std; struct student{ string name; int age; int score; }; //βθΪָ룬Լڴռ䣬ҲḴµconstԱֹ֤ void printstudent1(const student* s) { cout << s->name << endl; } int main_6() { student s = {"", 18, 80}; printstudent1(&s); system("pause"); return 0; } /* void printstudent(student* arr, int len) { for (int i = 0; i < len; i++) { cout << arr->name << endl; arr++; } } int main() { student s[3] = { {"", 18, 80}, {"", 19, 85}, {"", 20, 90} }; printstudent(s, 3); system("pause"); return 0; } */
Java
UTF-8
1,252
3.46875
3
[]
no_license
// https://leetcode.com/problems/merge-intervals/description/ /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class Solution { public List<Interval> merge(List<Interval> intervals) { List<Interval> merged = new LinkedList<Interval>(); if (intervals == null || intervals.size() < 1) return merged; // sort intervals Collections.sort(intervals, new Comparator<Interval>(){ @Override public int compare(Interval a, Interval b) { if (a.start == b.start) return a.end - b.end; return a.start - b.start; } }); for (Interval n: intervals) { if (merged.size() < 1) { merged.add(n); } else { Interval last = merged.get(merged.size() - 1); if (last.end >= n.start) last.end = Math.max(n.end, last.end); else{ merged.add(n); } } } return merged; } }
Rust
UTF-8
668
3.171875
3
[ "MIT", "Apache-2.0" ]
permissive
//! Cross-platform type abstractions over low-level platform-specific window events. /// Represents an interaction with an editor window. #[derive(Clone, Debug, PartialEq)] pub enum WindowEvent { /// XY coordinates. Each coordinate is based in the range [0, 1], scaled to the bounds of the /// window. Origin is at the top-left. The coordinates could be outside of the range if the /// cursor is outside of the window. CursorMovement(f32, f32), MouseClick(MouseButton), MouseRelease(MouseButton), } /// Represents one of the buttons on a mouse. #[derive(Clone, Debug, PartialEq, Eq)] pub enum MouseButton { Left, Right, Middle, }
PHP
UTF-8
539
2.578125
3
[ "Apache-2.0" ]
permissive
<? class Vonnegut_Namespace { public $name; public $classes; public $constants; public $functions; public $interfaces; public $namespaces; public $variables; public function __construct($name = null) { $this->name = $name; $this->classes = new StdClass(); $this->constants = new StdClass(); $this->functions = new StdClass(); $this->interfaces = new StdClass(); $this->namespaces = new StdClass(); $this->variables = new StdClass(); } }
Markdown
UTF-8
2,547
2.96875
3
[]
no_license
# Using Python scripts in Node.js server ref: https://www.ivarprudnikov.com/nodejs-server-running-python-scripts/ ## Using child process ```javascript= child_process.spawn() ``` > 目前 tdtoolkit_web 是使用 python-shell,不過開啟時需要 Loading moduled 相當費時,有沒有好的方法? ```javascript= const path = require('path') const {spawn} = require('child_process') /** * Run python script, pass in `-u` to not buffer console output * @return {ChildProcess} */ function runScript(){ return spawn('python', [ "-u", // prevent Python from buffering output path.join(__dirname, 'script.py'), "--foo", "some value for foo", ]); } const subprocess = runScript() // print output of script subprocess.stdout.on('data', (data) => { console.log(`data:${data}`); }); subprocess.stderr.on('data', (data) => { console.log(`error:${data}`); }); subprocess.on('close', () => { console.log("Closed"); }); ``` In [[express]] framework, we can use `pipe` to send the output to respones. ```javascript= const express = require('express') const app = express() // <...> app.get('/run', function (req, res) { const subprocess = runScript() res.set('Content-Type', 'text/plain'); subprocess.stdout.pipe(res) subprocess.stderr.pipe(res) }) app.listen(8080, () => console.log('Server running')) ``` But this method need client understand that response is chunked or to wait for script finished. ## Using WebSocket to render output To send back script output in chuncks, we could use [[WebSockets]]. ```javascript // server.js const express = require('express') const app = express() const http = require("http") const WebSocket = require("ws") const server = http.createServer(app); const wss = new WebSocket.Server({server}); wss.on('connection', (ws) => { ws.on('message', (message) => { ws.send(`You sent -> ${message}`); }); ws.send('Connection with WebSocket server initialized'); }); server.listen(8080, () => console.log('Server running')) ``` ```javascript // client.js var conn = {} function openConnection() { if (conn.readyState === undefined || conn.readyState > 1) { conn = new WebSocket('ws://' + window.location.host + '/'); conn.onopen = function () { console.log("Socket open") }; conn.onmessage = function (event) { console.log(event.data) }; conn.onclose = function (event) { console.log("Socket closed") }; } } if (window.WebSocket === undefined) { console.log("Sockets not supported") } else { openConnection(); } ```
C#
UTF-8
8,711
3.046875
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; namespace Ledger.Core { public class MemoryLedgerStore : ILedgerStore { private IList<IEntry> _entries = new List<IEntry>(); private IList<IEntryItem> _entryItems = new List<IEntryItem>(); private IDictionary<IBook, IList<IBalance>> _balancesMap = new Dictionary<IBook, IList<IBalance>>(); public virtual void Store(IEntry entry, ICollection<IBalance> balances) { _entries.Add(entry); foreach (var entryItem in entry.Items) _entryItems.Add(entryItem); foreach (var balance in balances) { IList<IBalance> balancesList; if (!_balancesMap.TryGetValue(balance.Book, out balancesList)) { balancesList = new List<IBalance>(); _balancesMap[balance.Book] = balancesList; } balancesList.Add(balance); } } public IComparable GetFirstIndex() { if (_entries.Count == 0) return null; return _entries[0].Index; } public IComparable GetLastIndex() { if (_entries.Count == 0) return null; return _entries[_entries.Count - 1].Index; } public virtual IEntry GetLastEntry() { if (_entries.Count == 0) return null; return _entries[_entries.Count - 1]; } public virtual ICollection<IEntry> GetEntries(ICollection<IComparable> indexes) { return _entries.Where(entry => indexes.Any(index => entry.Index.CompareTo(index) == 0)).ToList(); } public virtual ICollection<IEntry> GetEntries(IComparable startIndex, bool startInclusive, IComparable endIndex, bool endInclusive, bool reverse = false, int count = int.MaxValue) { if (reverse) return GetRangeReverse(_entries, endIndex, endInclusive, startIndex, startInclusive, count); return GetRange(_entries, startIndex, startInclusive, endIndex, endInclusive, count); } public virtual ICollection<IEntry> GetEntries() { return _entries; } public ICollection<IEntryItem> GetEntryItems(IBook book, IAccountPredicate accountPredicate, IComparable startIndex, bool startInclusive, IComparable endIndex, bool endInclusive) { var result = _entryItems.Where(x => x.Book.Equals(book)); if (startIndex != null) { if (startInclusive) result = result.Where(x => x.Entry.Index.CompareTo(startIndex) >= 0); else result = result.Where(x => x.Entry.Index.CompareTo(startIndex) > 0); } if (endIndex != null) { if (endInclusive) result = result.Where(x => x.Entry.Index.CompareTo(endIndex) <= 0); else result = result.Where(x => x.Entry.Index.CompareTo(endIndex) < 0); } return result.Where(x => accountPredicate.Matches(x.Account)).ToList(); } public virtual IBalance GetLastBalance(IBook book) { var balances = GetBalances(book); if (balances.Count == 0) return null; return balances[balances.Count - 1]; } public virtual ICollection<IBalance> GetBalances(IBook book, IEnumerable<IComparable> indexes) { return GetBalances(book).Where(balance => indexes.Any(index => balance.Index.CompareTo(index) == 0)).ToList(); } public virtual ICollection<IBalance> GetBalances(IBook book, IComparable startIndex, bool startInclusive, IComparable endIndex, bool endInclusive, bool reverse = false, int count = int.MaxValue) { var balances = GetBalances(book); if (reverse) return GetRangeReverse(balances, endIndex, endInclusive, startIndex, startInclusive, count); return GetRange(balances, startIndex, startInclusive, endIndex, endInclusive, count); } public ICollection<IBalance> GetBalances() { // Since this method is never used in calculations, I don't think the original order of combined balances matter return _balancesMap.Values.SelectMany(balances => balances).ToList(); } private IList<IBalance> GetBalances(IBook book) { IList<IBalance> balances; if (!_balancesMap.TryGetValue(book, out balances)) return new List<IBalance>(); return balances; } private static ICollection<T> GetRange<T>(IList<T> indexables, IComparable startIndex, bool startInclusive, IComparable endIndex, bool endInclusive, int count) where T : IIndexable { if (indexables.Count == 0) return new List<T>(); var start = 0; if (startIndex != null) { var newStart = FindIndex(indexables, startIndex, startInclusive, 1); if (newStart == -1) return new List<T>(); start = newStart; } var end = indexables.Count - 1; if (endIndex != null) { var newEnd = FindIndex(indexables, endIndex, endInclusive, -1); if (newEnd == -1) return new List<T>(); end = newEnd; } if (end - start + 1 > count) end = start + count - 1; var result = new List<T>(); for (var i = start; i <= end; i++) result.Add(indexables[i]); return result; } private static ICollection<T> GetRangeReverse<T>(IList<T> indexables, IComparable startIndex, bool startInclusive, IComparable endIndex, bool endInclusive, int count) where T : IIndexable { if (indexables.Count == 0) return new List<T>(); var start = indexables.Count - 1; if (startIndex != null) { var newStart = FindIndex(indexables, startIndex, startInclusive, -1); if (newStart == -1) return new List<T>(); start = newStart; } var end = 0; if (endIndex != null) { var newEnd = FindIndex(indexables, endIndex, endInclusive, 1); if (newEnd == -1) return new List<T>(); end = newEnd; } if (start - end + 1 > count) end = start - count + 1; var result = new List<T>(); for (var i = start; i >= end; i--) result.Add(indexables[i]); return result; } private static int FindIndex<T>(IList<T> indexables, IComparable index, bool inclusive, int direction) where T : IIndexable { // Uses binary search to find an item or its left or right neighbouring item based on the direction parameter var left = 0; var right = indexables.Count - 1; while (true) { var middle = (left + right) / 2; if (left - right == 1) { var findIndex = -1; switch (direction) { case -1: findIndex = right; break; case 1: findIndex = left; break; } if (findIndex > indexables.Count - 1 || findIndex < -1) findIndex = -1; return findIndex; } var result = index.CompareTo(indexables[middle].Index); if (result == 0) { if (inclusive) return middle; if (direction == 0) return -1; var findIndex = middle + direction; if (findIndex > indexables.Count - 1) return -1; return findIndex; } if (result < 0) right = middle - 1; else left = middle + 1; } } } }
Markdown
UTF-8
621
2.9375
3
[]
no_license
# exam_prep In-class hints for the final math exam. ## Week 2: XOR Implication (False case) Bitwise Considder one bit at a time and do a boolean result of each. * & and * && or Be able to add binary!! (quiz next week) ## Week 3: * Sets * Set Notation ## Week4: * multiply matricies * converting from matrix to graph and vice versa * graphs x4 brute force find shortest path * dont have to start at position A, can start at any node * will be only x4 nodes * adjacency lists – use dijkstra’s algorithm ### Please submit a pull request if you would like to add more info to this cooperative file. :)
Python
UTF-8
1,135
3.046875
3
[]
no_license
def run(): f = open('B-large.in') number_of_testcase = f.readline() for test_case in range(1, int(number_of_testcase)+1): game_param = f.readline().split(' ') game_param = map(lambda x: float(x), game_param) last_best_time = game_param[2] / 2.0 current_production_rate = 2.0 accum = 0.0 while True: new_time = calculated_time(game_param[0], game_param[1], game_param[2], current_production_rate, accum) if new_time > last_best_time: break else: last_best_time = new_time accum += game_param[0] / current_production_rate current_production_rate += game_param[1] print '%s%s%s%.7f' % ('Case #', test_case, ': ', last_best_time) f.close() def calculated_time(farm_cost, extra_production_rate, target_cookie, current_production_rate, accum): time_for_a_form = farm_cost / current_production_rate return float(target_cookie) / float(current_production_rate + extra_production_rate) + float(time_for_a_form) + float(accum) if __name__ == '__main__': run()
Java
UTF-8
528
1.835938
2
[]
no_license
package Premium.A02_service; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import Premium.A03_repository.A05_AndroidDao; import Premium.vo.And_work; import Premium.vo.And_workCeo; @Service public class A05_AndroidService { @Autowired private A05_AndroidDao dao; public ArrayList<And_work> alist (And_work aw){ return dao.alist(aw); } public ArrayList<And_workCeo> aclist(And_workCeo acw){ return dao.aclist(acw); } }
Ruby
UTF-8
476
3.046875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MP3Importer attr_reader :path, :files def initialize(file_path) @path = file_path end def files @file_array = Dir.entries(@path) @file_array.delete_if{|file| file.include?('mp3') == false} end def import self.files @chomped_array = @file_array.map{|file| file.chomp('.mp3')} @formatted_array = @chomped_array.map{|file| file.split(' - ')[1]} @formatted_array.each {|file| Song.new_by_filename(file)} end end
Markdown
UTF-8
1,522
3.125
3
[]
no_license
# text-based-adventure-game ## how it works This game is a text based adventure game based around classic murder mysteries like 'Clue' and 'Murder on the Orient Express' combined with a text-input game such as 'Zork' or 'Collosal Cave Adventure'. You are a detective that is trying to get away for an unplugged retreat at a mansion in the middle of the woods, however when you arrive your host has been recently killed and it is up to you to solve the mystery. You can interact with the world by typing commands such as 'go west', 'take letter', or 'ask ava about the victim', your goal is to pick up objects and explore the mansion in order to interrogate the guests and figure out who killed the host. When you have figured it out, you can go to the phone in the grand foyer and call the police. ## Installation First of all, the game needs python in order to run. If you have python already you may skip this step. 1. Go to: https://www.python.org/downloads/. 2. Download the latest release of python for your operating system. 3. Run the executable and follow the instructions to install python. After you install Python 1. Download this repository. 2. Unzip the file. 3. Navigate to the main folder of this repository (usually in downloads/text-based-adventure-game). 4. Double click on 'text-based-adventure-game.py' this should open a command line and start the game, or from the command line enter 'python3 text-based-adventure-game.py'. 5. Enter 'n' to get past the screen asking you to load a saved game.
Python
UTF-8
629
3.515625
4
[]
no_license
import pygame class Ship: """A class to manage the ship""" def __init__(self, ai_game): """Init the ship and starting position""" self.screen = ai_game.screen self.screen_rect = ai_game.screen.get_rect() # Load the ship image and get its rect self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() # Start each ship ate the bottom center of the screen self.rect.midbottom = self.screen_rect.midbottom def blitme(self): """Draw the ship at its currect location""" self.screen.blit(self.image, self.rect)
Python
UTF-8
623
2.765625
3
[]
no_license
from bs4 import BeautifulSoup import requests page = requests.get('https://forecast.weather.gov/MapClick.php?lat=33.94251000000003&lon=-118.40896999999995#.XOnRqlL0nIU') soup = BeautifulSoup(page.content, 'html.parser') week = soup.find(id='seven-day-forecast-body') items = week.find_all(class_='tombstone-container') period_names = [item.find(class_='period_name').get_text() for item in items] short_descriptions = [item.find(class_='short_desc').get_text() for item in items] temperatures = [item.find(class_='temp').get_text() for item in items] print(period_names) print(short_descriptions) print(temperatures)
C
UTF-8
1,484
3.8125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "functions.h" void random_array(int *array) { for (int i = 0; i < N; i++) { array[i] = (rand() % RANGE); } } void print_array(int *array) { for (int i = 0; i < N; i++) { printf_s("%2d", array[i]); } } void print_array_count(int *array, int size) { for (int i = 0; i < size; i++) { printf_s("%2d", array[i]); } } int new_array(const int *a, const int *b, int *c, int size) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (i == j) { c[size++] = a[i]; c[size++] = b[j]; } } } return size; } int unique_array(int *arr, int size) { int k; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { if (arr[i] == arr[j]) { for (k = j; k < size - 1; k++) { arr[k] = arr[k + 1]; } arr[k] = 0; size -= 1; if (arr[i] == arr[j]) { j--; } } } } return size; } void sort_array(int *array, int size) { int tmp; for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - 1 - i; j++) { if (array[j] > array[j + 1]) { tmp = array[j]; array[j] = array[j + 1]; array[j + 1] = tmp; } } } }
C#
UTF-8
1,241
2.921875
3
[]
no_license
/******************************************************************** Class : ListViewItemComparer Created by : Ali Özgür Contact : ali_ozgur@hotmail.com Copyright: Ali Özgür - 2007 *********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace PragmaSQL.Core { /// <summary> /// Implements the manual sorting of items by column. /// </summary> public class ListViewItemComparer : IComparer { private int col; private SortOrder order; public ListViewItemComparer() { col = 0; order = SortOrder.Ascending; } public ListViewItemComparer(int column, SortOrder order) { col = column; this.order = order; } public int Compare(object x, object y) { int returnVal = -1; returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text); // Determine whether the sort order is descending. if (order == SortOrder.Descending) // Invert the value returned by String.Compare. returnVal *= -1; return returnVal; } } }
JavaScript
UTF-8
2,361
2.6875
3
[]
no_license
const ImageBaseURL = 'https://image.tmdb.org/t/p/w500'; export const getPopularMovies = (page = 1) => { const path = page > 1 ? buildPath('/Movie', { pageNumber: page }) : '/Movie'; return new Promise((resolve, reject) => { fetch(path) .then(response => response.json()) .then(listings => { resolve(listings) }) .catch(err => reject(err)); }); }; export const searchMovies = (searchValue, page = 1) => { return new Promise((resolve, reject) => { if (!searchValue || page < 1) reject('Invalid Search Value'); fetch(buildPath('/Movie/Search', { pageNumber: page, searchValue: searchValue }), { method: "GET" }) .then(response => response.json()) .then(listings => { console.log('listings: ', listings); resolve(listings) }) .catch(err => reject(err)); }); }; export const getMovieDetails = (movieId) => { return new Promise((resolve, reject) => { if (!movieId) reject('Invalid Movie Id'); fetch(buildPath('/Movie/Detail', { movieId: movieId }), { method: "GET", headers: {'content-type': 'application/json'} }) .then(response => response.json()) .then(listings => { resolve(listings); }) .catch(err => reject(err)); }); }; export const getPeopleDetails = (personId) => { return new Promise((resolve, reject) => { if (!personId) reject('Invalid Movie Id'); fetch(buildPath('/Movie/People', { personId: personId }), { method: "GET", headers: {'content-type': 'application/json'} }) .then(response => response.json()) .then(listings => { resolve(listings); }) .catch(err => reject(err)); }); }; export const getImageURL = imageId => { return [ImageBaseURL, imageId].join('/'); }; function buildPath(base, options) { if (!options) return base; let params = null; for (const prop in options) { if (params) params += `&${prop}=${encodeURI(options[prop])}` else params = `${prop}=${encodeURI(options[prop])}`; } return `${base}?${params}`; }
Python
UTF-8
5,726
2.546875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
# Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ELF parsing related helper functions/classes.""" from __future__ import print_function import cStringIO import os from chromite.scripts import lddtree from elftools.elf import elffile from elftools.elf import enums from elftools.common import utils # Reverse dict() from numeric values to strings used to lookup st_shndx. SH_TYPE_VALUES = dict((value, name) for name, value in enums.ENUM_SH_TYPE.iteritems()) def ParseELFSymbols(elf): """Parses list of symbols in an ELF file. Args: elf: An elffile.ELFFile instance. Returns: A 2-tuple of (imported, exported) symbols. |imported| is a set of strings of undefined symbols. |exported| is a dict where the keys are defined symbols and the values are 3-tuples (st_info_bind, st_size, st_shndx) with the details of the corresponding exported symbol. Note that for imported symbols this information is always ('STB_GLOBAL', 0, 'SHN_UNDEF') and thus not included in the result. """ imp = set() exp = dict() if elf.header.e_type not in ('ET_DYN', 'ET_EXEC'): return imp, exp for segment in elf.iter_segments(): if segment.header.p_type != 'PT_DYNAMIC': continue # Find strtab and symtab virtual addresses. strtab_ptr = None symtab_ptr = None symbol_size = elf.structs.Elf_Sym.sizeof() for tag in segment.iter_tags(): if tag.entry.d_tag == 'DT_SYMTAB': symtab_ptr = tag.entry.d_ptr if tag.entry.d_tag == 'DT_STRTAB': strtab_ptr = tag.entry.d_ptr if tag.entry.d_tag == 'DT_SYMENT': assert symbol_size == tag.entry.d_val stringtable = segment._get_stringtable() # pylint: disable=W0212 symtab_offset = next(elf.address_offsets(symtab_ptr)) # Assume that symtab ends right before strtab. # This is the same assumption that glibc makes in dl-addr.c. # The first symbol is always local undefined, unnamed so we ignore it. for i in range(1, (strtab_ptr - symtab_ptr) / symbol_size): symbol_offset = symtab_offset + (i * symbol_size) symbol = utils.struct_parse(elf.structs.Elf_Sym, elf.stream, symbol_offset) if symbol['st_info']['bind'] == 'STB_LOCAL': # Ignore local symbols. continue symbol_name = stringtable.get_string(symbol.st_name) if symbol['st_shndx'] == 'SHN_UNDEF': if symbol['st_info']['bind'] == 'STB_GLOBAL': # Global undefined --> required symbols. # We ignore weak undefined symbols. imp.add(symbol_name) elif symbol['st_other']['visibility'] == 'STV_DEFAULT': # Exported symbols must have default visibility. st_shndx = SH_TYPE_VALUES.get(symbol['st_shndx'], symbol['st_shndx']) exp[symbol_name] = (symbol['st_info']['bind'], symbol['st_size'], st_shndx) return imp, exp def ParseELF(root, rel_path, ldpaths=None, parse_symbols=True): """Parse the ELF file. Loads and parses the passed elf file. Args: root: Path to the directory where the rootfs is mounted. rel_path: The path to the parsing file relative to root. ldpaths: The dict() with the ld path information. See lddtree.LoadLdpaths() for details. parse_symbols: Whether the result includes the dynamic symbols 'imp_sym' and 'exp_sym' sections. Disabling it reduces the time for large files with many symbols. Returns: If the passed file isn't a supported ELF file, returns None. Otherwise, returns a dict() with information about the parsed ELF. """ # Ensure root has a trailing / so removing the root prefix also removes any # / from the beginning of the path. root = root.rstrip('/') + '/' with open(os.path.join(root, rel_path), 'rb') as f: if f.read(4) != '\x7fELF': # Ignore non-ELF files. This check is done to speedup the process. return f.seek(0) # Continue reading and cache the whole file to speedup seeks. stream = cStringIO.StringIO(f.read()) try: elf = elffile.ELFFile(stream) except elffile.ELFError: # Ignore unsupported ELF files. return if elf.header.e_type == 'ET_REL': # Don't parse relocatable ELF files (mostly kernel modules). return { 'type': elf.header.e_type, 'realpath': rel_path, } if ldpaths is None: ldpaths = lddtree.LoadLdpaths(root) result = lddtree.ParseELF(os.path.join(root, rel_path), root=root, ldpaths=ldpaths) # Convert files to relative paths. for libdef in result['libs'].values(): for path in ('realpath', 'path'): if not libdef[path] is None and libdef[path].startswith(root): libdef[path] = libdef[path][len(root):] for path in ('interp', 'realpath'): if not result[path] is None and result[path].startswith(root): result[path] = result[path][len(root):] result['type'] = elf.header.e_type result['sections'] = dict((str(sec.name), sec['sh_size']) for sec in elf.iter_sections()) result['segments'] = set(seg['p_type'] for seg in elf.iter_segments()) # Some libraries (notably, the libc, which you can execute as a normal # binary) have the interp set. We use the file extension in those cases # because exec files shouldn't have a .so extension. result['is_lib'] = ((result['interp'] is None or rel_path[-3:] == '.so') and elf.header.e_type == 'ET_DYN') if parse_symbols: result['imp_sym'], result['exp_sym'] = ParseELFSymbols(elf) return result
Markdown
UTF-8
2,314
2.90625
3
[ "Apache-2.0" ]
permissive
# Project 4 - *Parstagram* This is an Instagram clone with a custom Parse backend that allows a user to post photos and view a global photos feed. Time spent: **6** hours spent in total ## User Stories The following **required** functionality is completed: - [x] User sees app icon in home screen and styled launch screen. (1pt) - [x] User can sign up to create a new account. (1pt) - [x] User can log in. (1pt) - [x] User can take a photo, add a caption, and post it to the server. (3pt) - [x] User can view the last 20 posts. (4pts) - [x] User stays logged in across restarts. (1pt) - [x] User can log out. (1pt) - [x] User can view comments on a post. (3pts) - [ ] User can add a new comment. (5pts) ## Bonus The following **bonus** features are implemented: - [x] User can pull to refresh. (1pt) - [x] User can load past tweets infinitely. (2pts) - [ ] User can add a profile picture. (2pts) - [ ] Profile pictures are shown for posts and comments. (2pts) ## Additional The following **additional** features are implemented: - [x] User password entry is protected. - [x] Tab Bar Navigation added. ## APP Walkthrough GIF Here's a walkthrough of implemented user stories: <img src='https://recordit.co/XBD7C26hlt.gif' width=250> GIF created with [RecordIt](https://recordit.co/XBD7C26hlt.gif). ### Notes I tried to make the app look as close to Instagram, but I made some 'styling' mistakes that did not allow me to finish 'posting comments'. I think it is an easy fix... Profile photos have not been added, there is a profile page that needs to be completed, code is set for displaying for posts... not yet for comments. Look forward to continuing work throughout the next week to complete the project and add more bells and whistles. ### License Copyright [2019] [Leonard Box] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
PHP
UTF-8
3,885
2.671875
3
[]
no_license
<?php require 'connection.inc.php'; function clean_values($con,$value){ $value=stripslashes($value); $value=stripcslashes($value); $value=mysqli_escape_string($con,$value); $value=mysqli_real_escape_string($con,$value); return $value; } // for inserting/Updating into database function insert_update($con,$query){ $res=mysqli_query($con,$query) or die(error_reporting()); if ($res==1) { return 1; }else{ return 0; } } // for fetching Data From Tables function fetch($con,$query){ $res=mysqli_query($con,$query) or die(error_reporting()); $rows=mysqli_fetch_assoc($res); if (!empty($rows)) { return $rows; }else{ return 0; } } // IP address DETAILS function get_ip_details($ip){ $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip)); if($query && $query['status'] == 'success') { return $query; }else{ return false; } } // Website Visitor function website_visited($con,$user_ip){ $ip_res=get_ip_details($user_ip); if ($ip_res!=false) { $isp=$ip_res['isp']; $country=$ip_res['country']; $city=$ip_res['city']; $region=$ip_res['region']; $zipcode=$ip_res['zip']; $latitude=$ip_res['lat']; $longitude=$ip_res['lon']; }else{ $city=$country=$isp=$region=$zipcode=$latitude=$longitude="unknown"; } $res=@"INSERT INTO page_visitor (ip,city,country,isp,region,zipcode,latitude,longitude) VALUES('$user_ip','$city','$country','$isp','$region','$zipcode','$latitude','$longitude') LIMIT 1"; insert_update($con,$res); } // Website Visitors function page_visited($con,$con_id){ $res=@"SELECT blog_view FROM blogs WHERE id =$con_id"; $rows=fetch($con,$res); $new_view=intval($rows['blog_view'])+1; $update_view=@"UPDATE blogs SET blog_view=$new_view WHERE id='$con_id' LIMIT 1"; insert_update($con,$update_view); } // like/ extract($_POST); if (isset($_POST['userId']) && isset($_POST['blogId']) && isset($_POST['like'])) { $blogId=clean_values($con,$_POST['blogId']); $userId=clean_values($con,$_POST['userId']); $like=clean_values($con,$_POST['like']); //--Check if already licked $query_check=@"SELECT * FROM like_dislike WHERE (ip='$userId' and blog_id='$blogId') LIMIT 1"; $res=mysqli_query($con,$query_check) or die(error_reporting()); if (mysqli_num_rows($res)==0) { // increasing like on blog table $query_blog=@"SELECT blog_like FROM blogs WHERE id='$blogId' LIMIT 1"; $res=fetch($con,$query_blog); if ($res!=false) { $like_count=intval($res['blog_like'])+1; // Updating Like $update_like=@"UPDATE blogs SET blog_like=$like_count WHERE id=$blogId LIMIT 1"; $update_res=insert_update($con,$update_like); if ($update_res==1) { $q="INSERT INTO like_dislike (ip, post_like, blog_id) VALUES('$userId','$like','$blogId')"; $query =mysqli_query($con,$q) or die(error_reporting(1)); } } } } //dislike if (isset($_POST['userId']) && isset($_POST['blogId']) && isset($_POST['dislike'])) { $blogId=clean_values($con,$_POST['blogId']); $userId=clean_values($con,$_POST['userId']); $dislike=clean_values($con,$_POST['dislike']); //--Check if already licked $query_check=@"SELECT * FROM like_dislike WHERE ((ip='$userId' and blog_id='$blogId') AND post_dislike=1) LIMIT 1"; $res=mysqli_query($con,$query_check) or die(error_reporting()); if (mysqli_num_rows($res)==0) { // increasing like on blog table $query_blog=@"SELECT blog_dislike FROM blogs WHERE id='$blogId' LIMIT 1"; $res=fetch($con,$query_blog); if ($res!=false) { $dislike_count=intval($res['blog_dislike'])+1; // Updating Like $update_like=@"UPDATE blogs SET blog_dislike=$dislike_count WHERE id=$blogId LIMIT 1"; $update_res=insert_update($con,$update_like); if ($update_res==1) { $q="INSERT INTO like_dislike (ip, post_dislike, blog_id) VALUES('$userId','$dislike','$blogId')"; $query =mysqli_query($con,$q) or die(error_reporting(1)); } } } } ?>
Java
UTF-8
416
3.25
3
[]
no_license
package T210930; public class ArrayTest03 { public static void main(String[] args) { // TODO Auto-generated method stub int aa[] = {10,20,30,40,50}; int count, size; count = aa.length; size=count*Integer.BYTES; System.out.printf("배열 aa[]의 요소의 개수는 %d 개입니다.\n", count); System.out.printf("배열 aa[]의 요소의 전체 크기는 %d 바이트입니다. \n", size); } }
Java
UTF-8
2,981
2.40625
2
[]
no_license
package cn.edu.sdwu.android.classroom.sn170507180227; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.Spinner; import android.widget.Toast; import android.widget.ToggleButton; import java.util.ArrayList; public class Ch7Activity1 extends AppCompatActivity { private ArrayList list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_ch7_1); ToggleButton toggleButton=(ToggleButton)findViewById(R.id.ch7_1_tb); toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b){ Toast.makeText(Ch7Activity1.this,"on",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(Ch7Activity1.this,"off",Toast.LENGTH_SHORT).show(); } } });//选择改变事件监听器 Spinner spinner=(Spinner)findViewById(R.id.ch7_1_spinner); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { //参数i代表当前选中的索引值 String[] stringArray = getResources().getStringArray(R.array.strArr); String content = stringArray[i]; Toast.makeText(Ch7Activity1.this,content,Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); spinner=(Spinner)findViewById(R.id.ch7_1_spinner2); //准备数据 list=new ArrayList(); list.add("spinnerItem1"); list.add("spinnerItem2"); list.add("spinnerItem3"); //实例化数组适配器 //ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,list); ArrayAdapter arrayAdapter=new ArrayAdapter(this,R.layout.layout_spinner_item,list); //设置到spinner中 spinner.setAdapter(arrayAdapter); //处理事件响应 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { //参数i代表当前选中的索引值 String content = list.get(i).toString(); Toast.makeText(Ch7Activity1.this,content,Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } }
TypeScript
UTF-8
189
3.0625
3
[]
no_license
export const makeArray = (from: number, length = 5) => { const newArr = new Array(length).fill(0); for (let i = 0; i < length; i++) { newArr[i] = from + i; } return newArr; };
Java
UTF-8
365
1.671875
2
[]
no_license
package com.fball.service; import java.util.List; import com.fball.dto.VirtualMatchDTO; public interface VirtualMatchService { List<VirtualMatchDTO> getListVirtualMatchByIdMatch(int id); String newVirtualMatchInId(int idVirtual, String string); String joinVirtualMatchInId(int id, String string); String cancelVirtualMatchInId(int id, String string); }
Java
GB18030
326
1.992188
2
[]
no_license
package com.insigma.mvc.model; public class ExcelExportModel implements java.io.Serializable { private String excel_info; // varchar2(36) ʱ֮ʱ public String getExcel_info() { return excel_info; } public void setExcel_info(String excel_info) { this.excel_info = excel_info; } }
Go
UTF-8
5,340
3.046875
3
[]
no_license
package controllers import ( "encoding/json" "fmt" "net/http" "regexp" "../models" "../utils" "github.com/gorilla/mux" ) // validateEmail checks if the ID is valid func validateEmail(email string) bool { Re := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`) return Re.MatchString(email) } // validateTelephone checks if the telephone number is valid func validateTelephone(telephone string) bool { if len(telephone) >= 8 && len(telephone) <= 10 { return true } return false } // GetStudents gets all of all students from the database func GetStudents(w http.ResponseWriter, r *http.Request) { // Check if the Method is correct if r.Method != "GET" { http.Error(w, http.StatusText(utils.WrongMethod), utils.WrongMethod) ResponseJSON(w, "Please use the GET method for this route") } fmt.Println("Getting all students details!") // Call the handler students, err := models.GetStudents() if err != "" { studentsdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.GetFailed, Data: students, } ResponseJSON(w, studentsdetails) return } studentsdetails := models.Response{ StatusCode: utils.SuccessCode, Message: utils.GotStudent, Data: students, } // Return from the function ResponseJSON(w, studentsdetails) } // GetStudent gets all the details of a student from the database func GetStudent(w http.ResponseWriter, r *http.Request) { // Check if the Method is correct if r.Method != "GET" { http.Error(w, http.StatusText(utils.WrongMethod), utils.WrongMethod) ResponseJSON(w, "Please use the GET method for this route") } fmt.Println("Getting student's details!") params := mux.Vars(r) // Call the handler student, err := models.GetStudent(params["id"]) studentdetails := models.Response{ StatusCode: utils.SuccessCode, Message: utils.GotStudent, Data: student, } if err != "" { studentdetails = models.Response{ StatusCode: utils.WrongParam, Message: utils.GetFailed, Data: student, } ResponseJSON(w, studentdetails) return } // Return from the function ResponseJSON(w, studentdetails) } // DeleteStudent deletes a student from the database func DeleteStudent(w http.ResponseWriter, r *http.Request) { // Check if the Method is correct if r.Method != "DELETE" { http.Error(w, http.StatusText(utils.WrongMethod), utils.WrongMethod) ResponseJSON(w, "Please use the DELETE method for this route") } fmt.Println("Deleting student's details!") w.Header().Set("Content-Type", "application/json") // Call the handler params := mux.Vars(r) err := models.DeleteStudent(w, r, params["id"]) if err != "" { studentdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.DeletionFailed, Data: utils.DeletionFailed, } ResponseJSON(w, studentdetails) return } studentdetails := models.Response{ StatusCode: utils.SuccessCode, Message: "Deleted the student!", Data: "Deleted the student!", } // Return from the function ResponseJSON(w, studentdetails) } // UpdateStudent updates details of a student func UpdateStudent(w http.ResponseWriter, r *http.Request) { // Check if the Method is correct if r.Method != "PUT" { http.Error(w, http.StatusText(utils.WrongMethod), utils.WrongMethod) ResponseJSON(w, "Please use the PUT method for this route") } fmt.Println("Updating student's details!") w.Header().Set("Content-Type", "application/json") // Get the user's input details from the POST body decoder := json.NewDecoder(r.Body) var student models.Students err := decoder.Decode(&student) if err != nil { panic(err) } // Check the user's input and then call the handler if student.FirstName == "" { studentdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.UpdatingFailed, Data: "Please give a first name", } // Return from the function ResponseJSON(w, studentdetails) } else if student.Password == "" { studentdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.UpdatingFailed, Data: "Please give a password", } // Return from the function ResponseJSON(w, studentdetails) } else if !validateEmail(student.EmailID) { studentdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.UpdatingFailed, Data: "Email address is invalid", } // Return from the function ResponseJSON(w, studentdetails) } else if !validateTelephone(student.Telephone) { studentdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.UpdatingFailed, Data: "Telephone number is invalid", } // Return from the function ResponseJSON(w, studentdetails) } else { params := mux.Vars(r) err := models.UpdateStudent(w, r, params["id"], student) if err != "" { studentdetails := models.Response{ StatusCode: utils.WrongParam, Message: utils.UpdatingFailed, Data: utils.UpdatingFailed, } // Return from the function ResponseJSON(w, studentdetails) return } studentdetails := models.Response{ StatusCode: utils.SuccessCode, Message: "Updating successful", Data: "Updating successful", } // Return from the function ResponseJSON(w, studentdetails) } }
Markdown
UTF-8
2,431
2.859375
3
[ "MIT" ]
permissive
# GBBS: Graph Based Benchmark Suite Clique Counting and Peeling Algorithms -------- This folder contains code for our parallel k-clique counting and peeling. Detailed information about the required compilation system and input graph formats can be found in the top-level directory of this repository. We describe here the various options implemented from our paper, [Parallel Clique Counting and Peeling Algorithms](https://arxiv.org/abs/2002.10047). Running Code ------- The applications take the input graph as input, as well as flags to specify desired optimizations. Note that the `-s` flag must be set to indicate a symmetric (undirected) graph. The options for arguments are: * `-k` followed by a positive integer > 2, which specifies k. * `--directType` followed by `GOODRICHPSZONA`, `BARENBOIMELKIN`, `KCORE`, `DEGREE`, or `ORIGINAL`, which specifies the ordering to use for the orientation in the algorithms. * `-e` followed by a float, which specifies the epsilon if the `GOODRICHPSZONA` or `BARENBOIMELKIN` orderings are selected (otherwise, this argument is ignored). * `--parallelType` followed by `VERT` or `EDGE`, which specifies if k-clique counting should use parallelism per vertex or per edge. * `--saveSpace`, which if set indicates that the first level of recursion should use space proportional to the squared arboricity rather than linear space, to reduce space usage overall. * `--peel`, which if set indicates that k-clique peeling should run following k-clique counting. Note that k-clique counting will compute counts per vertex, rather than in total. * `--sparse`, which if set indicates that approximate k-clique counting should run. Note that this cannot be set in conjunction with k-clique peeling or approximate k-clique peeling. * `--colors` followed by a positive integer, which specifies the number of colors to use in approximate k-clique counting if `--sparse` is selected (otherwise, this argument is ignored). * `--approxpeel`, which if set indicates that approximate k-clique peeling should run. * `--approxeps` followed by a float, which specifies the epsilon to use for approximate k-clique peeling if `--approxpeel` is selected (otherwise, this argument is ignored). **Example Usage** The main executable is `Clique_main`. A template command is: ```sh $ bazel run Clique_main -- -rounds 1 -k 4 --directType DEGREE --parallelType VERT --peel -s </path/to/input/graph> ```
PHP
UTF-8
1,603
2.703125
3
[]
no_license
<?php include("con_db.php"); if(isset($_POST['register'])){ if(strlen($_POST['name']) >= 1 && strlen($_POST['contraseña']) >= 1 && strlen($_POST['contraseña1']) >= 1){ if(strlen($_POST['contraseña']) > 3){ if($_POST['contraseña'] == $_POST['contraseña1']){ $name = trim($_POST['name']); $contraseña = trim($_POST['contraseña']); $contraseña1 = trim($_POST['contraseña1']); $imagen = "desconocido.png"; $fechareg = date("d/m/y"); $consulta = "INSERT INTO datos(nombre, contraseña, contraseña1, imagen, fecha_reg) VALUES ('$name','$contraseña','$contraseña1','$imagen','$fechareg')"; $resultado = mysqli_query($conex, $consulta); if($resultado){ ?> <div style="color:green">Registrado con éxito, <a href="login.php">Inicia sesión</a></div> <?php } else{ ?> <div style="color:red">Oops, ha ocurrido un error</div> <?php } }else{ ?> <div style="color:red">Introduzca la misma contraseña</div> <?php } }else{ ?> <div style="color:red">La contraseña debe tener 4 caracteres minimo</div> <?php } } else{ ?> <div style="color:red">Completa todos los campos</div> <?php } } ?>
C++
UTF-8
1,439
3.15625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <string> using namespace std; void process(int n, int *froms); void simulate(int n, int *froms); void print_solution(int n, int *froms); int main() { string line; while (!cin.eof()) { int n; cin >> n; printf("%d\n", n); int * froms = new int[n]; process(n, froms); simulate(n, froms); // print_solution(n, froms); printf("\n"); } return 0; } void process(int n, int * froms) { bool even = n & 1 == 0; int from = n + 2; for (int i = 0; i < n; i++) { froms[i] = from; from -= n - 1; if (from < 0) from += 2 * n + 2; } } void printline(int len, char *line) { for (int i = 0; i < len; i++) { cout << line[i]; } cout << endl; } void simulate(int n, int *froms) { int linelen = n * 2 + 2; char *line = new char[linelen]; line[0] = ' '; line[1] = ' '; for (int i = 2; i < linelen; i++) { line[i] = i & 1 ? 'A' : 'B'; } printline(linelen, line); int to = -1; for (int i = 0; i < n; i++) { // printf("%d to %d\n", froms[i], to); int from = froms[i]; line[to + 2] = line[from + 2]; line[to + 1] = line[from + 1]; line[from + 2] = ' '; line[from + 1] = ' '; printline(linelen, line); to = from; } delete [] line; } void print_solution(int n, int *froms) { int to = -1; for (int i = 0; i < n; i++) { printf("%d to %d\n", froms[i], to); to = froms[i]; } }
Python
UTF-8
1,225
2.71875
3
[]
no_license
import sqlite3 # g is object made for each request # current_app is object that points to Flask app handling request import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) #return rows that behave like dicts g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): db=g.pop('db',None) if db is not None: db.close() def init_db(): db = get_db() # open_resource looks for file local to flaskr package with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf-8')) # click.command creates a CLI command called init-db @click.command('init-db') @with_appcontext def init_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database') # Register necessary functions to the application def init_app(app): # app.teardown_appcontext specifies function to call after returning response app.teardown_appcontext(close_db) # app.cli.add_command adds new command that can be called via flask CLI (>flast command) app.cli.add_command(init_db_command)
Java
UTF-8
49
1.851563
2
[]
no_license
public enum PriorityType { normal, high, max }
JavaScript
UTF-8
1,499
2.5625
3
[]
no_license
import React, { Component } from 'react' import styled from 'styled-components' import { rgba } from 'polished' // TODO: // Refactor this one, rewrite entirely with styled comp. // Think about the way to use tag literal. // Something like: // <div> // DynamicCode` // <span> // ${this.props.text + 'px'} // </span> // ` // </div> const Code = styled.span` font-family: ${props => props.theme.monoFont}; white-space: pre; font-size: 20px; .code-preview__highlight { background-color: rgba(0, 0, 0, 0); transition: background-color 1.6s ease; border-radius: 2px; } .code-preview__highlight--flash { transition-duration: 0.15s; background-color: ${rgba('#fc7979', 0.5)}; } ` const DynamicCode = ({ children }) => <Code>{children}</Code> export class HightlightSegment extends Component { componentDidUpdate(prevProps) { if (!this.$root) { return } if (!this.props.pure || this.props.text !== prevProps.text) { this.$root.classList.add('code-preview__highlight--flash') // No good :) setTimeout( () => this.$root && this.$root.classList.remove('code-preview__highlight--flash'), 100 ) } } render() { return ( <span ref={e => { this.$root = e }} className="code-preview__highlight" > {this.props.text} </span> ) } } DynamicCode.H = HightlightSegment export default DynamicCode
Java
UTF-8
2,125
2.6875
3
[ "Apache-2.0" ]
permissive
package org.krystianekb.sorting.file; import com.google.code.externalsorting.ExternalSort; import org.apache.commons.lang3.time.StopWatch; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import static com.google.code.externalsorting.ExternalSort.mergeSortedFiles; import static com.google.code.externalsorting.ExternalSort.sortInBatch; public class MainApp { private static final List<String> sizeList = Arrays.asList("1g", "2g", "5g", "12g"); private static final List<String> lineSize = Arrays.asList("1k", "5k"); private static final String OUTPUT_DIR = "target"; private static final String SORTED_DIR = String.format("%s/sorted", OUTPUT_DIR); private static final String DATA_DIR = String.format("%s/data", OUTPUT_DIR); private static final String TMP_DIR = String.format("%s/tmp", OUTPUT_DIR); //public static final String TMP_DIR = "/home/krystian/tmp"; private static long measure(String size, String lineSize, int iter) throws IOException { String filename = String.format("%s-1k-%s-%d.txt", size, lineSize, iter); StopWatch overall = new StopWatch(); overall.start(); List <File> tmpFiles = sortInBatch(new File(String.format("%s/%s",DATA_DIR, filename)), ExternalSort.defaultcomparator, 1024, Charset.defaultCharset(), new File(TMP_DIR), false); mergeSortedFiles(tmpFiles, new File(String.format("%s/%s", SORTED_DIR, filename))); overall.stop(); return overall.getTime(); } public static void main(String[] args) throws IOException { for (String s : sizeList) { for (String l : lineSize) { for (int i=1; i<=2; i++) { long timeTaken = measure(s, l, i); System.out.println( String.format("Execution time for [%s,%s,%d] : %.2f s", s, l, i, timeTaken / 1000.0)); } } } } }
C++
UTF-8
1,947
2.734375
3
[ "MIT" ]
permissive
/* * ContactMap.h * * Created on: Jun 20, 2014 * Author: e4k2 */ #ifndef CONTACTMAP_H_ #define CONTACTMAP_H_ #include "Contact.h" #include <tr1/array> using namespace std; class ContactMapIterator; /** * Contains all contacts (distance determined by caller) added by the user using makeEntry and add */ class ContactMap { public: static const int CMENTRYSIZE = 5; // contact map entry size static const int FRACSTRUCINDEX = 0; // index for fraction of input structures with contact (within DISTCUTOFF) static const int MINDISTINDEX = 1; // index for minimum distance among the structures for this contact; can be INVALIDDISTANCE if coordinates do not exist static const int FRACSTRUCSPHINDEX = 2; // index for fraction of input structures with contact, allowing for intersectSphere static const int AVGINDEX = 3; // avg dist; if a structure is missing coordinates, the avg dist is set to INVALIDDISTANCE static const int STDEVINDEX = 4; tr1::unordered_map< Contact, tr1::array<double,CMENTRYSIZE> > contactMap; ContactMap(); ContactMap(const ContactMap& cm); virtual ~ContactMap(); friend void swap(ContactMap& cm1, ContactMap& cm2); ContactMap& operator=(ContactMap cm); void add(Contact& c, tr1::array<double,CMENTRYSIZE>& entry); // definition of contact depends on caller tr1::array<double,CMENTRYSIZE>& operator[](const Contact& c); static tr1::array<double, CMENTRYSIZE> makeEntry(double fractionContact, double minDist, double fractionContactSphere, double avgDist, double stdevDist); double get(Contact& c, int fieldIndex); // fieldIndex = must be one of the above static const ints (no checking is done) ContactMapIterator find(const Contact& c); int getNumContacts() const; int getNumContacts(double distCutoff) const; // num contacts where mindist <= distCutoff friend class ContactMapIterator; ContactMapIterator begin() const; ContactMapIterator end() const; }; #endif /* CONTACTMAP_H_ */
Java
UTF-8
11,110
2.390625
2
[ "BSD-2-Clause" ]
permissive
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static play.mvc.Http.Status.BAD_REQUEST; import static play.mvc.Http.Status.NOT_FOUND; import static play.mvc.Http.Status.SEE_OTHER; import static play.test.Helpers.callAction; import static play.test.Helpers.contentAsString; import static play.test.Helpers.fakeApplication; import static play.test.Helpers.fakeRequest; import static play.test.Helpers.inMemoryDatabase; import static play.test.Helpers.start; import static play.test.Helpers.status; import static play.test.Helpers.stop; import java.util.HashMap; import java.util.Map; import models.Book; import models.Offer; import models.Request; import models.Student; import org.junit.After; import org.junit.Before; import org.junit.Test; import play.mvc.Result; import play.test.FakeApplication; import play.test.FakeRequest; public class ControllerTest { private FakeApplication application; @Before public void startApp() { application = fakeApplication(inMemoryDatabase()); start(application); } @After public void stopApp() { stop(application); } @Test public void testStudentController() { // Test GET /students on an empty database Result result = callAction(controllers.routes.ref.Student.index()); assertTrue("Empty students", contentAsString(result).contains("Students")); // Test GET /students on a database containing a single student. String studentId = "Student-01"; Student student = new Student(studentId, "Name", "Email"); student.save(); Long primaryKey = student.getPrimaryKey(); result = callAction(controllers.routes.ref.Student.index()); assertTrue("One student", contentAsString(result).contains(studentId)); // Test GET /students/[primaryKey] result = callAction(controllers.routes.ref.Student.edit(primaryKey)); assertTrue("Student detail", contentAsString(result).contains(studentId)); // Test GET /students/[primaryKey + 1] (invalid primaryKey) result = callAction(controllers.routes.ref.Student.edit(primaryKey + 1)); assertEquals("Student detail (bad)", NOT_FOUND, status(result)); // Test POST /students (with simulated, valid form data). Map<String, String> studentData = new HashMap<String, String>(); studentData.put("studentId", "Student-02"); studentData.put("name", "OtherName"); studentData.put("email", "OtherEmail"); FakeRequest request = fakeRequest(); request.withFormUrlEncodedBody(studentData); result = callAction(controllers.routes.ref.Student.save(), request); assertEquals("Create new student", SEE_OTHER, status(result)); // Test POST /students (with simulated, invalid form data). request = fakeRequest(); result = callAction(controllers.routes.ref.Student.save(), request); assertEquals("Create bad student fails", BAD_REQUEST, status(result)); // Test DELETE /students/Student-01 (a valid studentId). result = callAction(controllers.routes.ref.Student.delete(primaryKey)); assertEquals("Delete current student OK", SEE_OTHER, status(result)); result = callAction(controllers.routes.ref.Student.edit(primaryKey)); assertEquals("Deleted student gone", NOT_FOUND, status(result)); result = callAction(controllers.routes.ref.Student.delete(primaryKey)); assertEquals("Delete missing student also OK", SEE_OTHER, status(result)); } @Test public void testBookController() { // Test GET /books on an empty database Result result = callAction(controllers.routes.ref.Book.index()); assertTrue("Empty books", contentAsString(result).contains("Books")); // Test GET /books on a database containing a single student. String bookId = "Book-01"; Book book = new Book(bookId, "Title", "Edition", 1234L, 123); book.save(); Long primaryKey = book.getPrimaryKey(); result = callAction(controllers.routes.ref.Book.index()); assertTrue("One book", contentAsString(result).contains(bookId)); // Test GET /books/[primaryKey] result = callAction(controllers.routes.ref.Book.edit(primaryKey)); assertTrue("Book detail", contentAsString(result).contains(bookId)); // Test GET /books/[primaryKey + 1] (invalid primaryKey) result = callAction(controllers.routes.ref.Book.edit(primaryKey + 1)); assertEquals("Book detail (bad)", NOT_FOUND, status(result)); // Test POST /books (with simulated, valid form data). Map<String, String> bookData = new HashMap<String, String>(); bookData.put("bookId", "Book-02"); bookData.put("title", "OtherTitle"); bookData.put("isbn", "4321"); FakeRequest request = fakeRequest(); request.withFormUrlEncodedBody(bookData); result = callAction(controllers.routes.ref.Book.save(), request); assertEquals("Create new book", SEE_OTHER, status(result)); // Test POST /books (with simulated, invalid form data). request = fakeRequest(); result = callAction(controllers.routes.ref.Book.save(), request); assertEquals("Create bad book fails", BAD_REQUEST, status(result)); // Test DELETE /books/Student-01 (a valid studentId). result = callAction(controllers.routes.ref.Book.delete(primaryKey)); assertEquals("Delete current book OK", SEE_OTHER, status(result)); result = callAction(controllers.routes.ref.Book.edit(primaryKey)); assertEquals("Deleted book gone", NOT_FOUND, status(result)); result = callAction(controllers.routes.ref.Book.delete(primaryKey)); assertEquals("Delete missing book also OK", SEE_OTHER, status(result)); } @Test public void testRequestController() { // Test GET /requests on an empty database. Result result = callAction(controllers.routes.ref.Request.index()); assertTrue("Empty requests", contentAsString(result).contains("Requests")); // Test GET /requests on a database containing a single request. String requestId = "Request-01"; Student student = new Student("Student-01", "Name", "Email"); Book book = new Book("Book-01", "Title", "Edition", 1234L, 123); Request request = new Request(requestId, student, book, 123); student.save(); book.save(); request.save(); Long primaryKey = request.getPrimaryKey(); result = callAction(controllers.routes.ref.Request.index()); assertTrue("One request", contentAsString(result).contains(requestId)); // Test GET /requests/[primaryKey] result = callAction(controllers.routes.ref.Request.edit(primaryKey)); assertTrue("Request detail", contentAsString(result).contains(requestId)); // Test GET /requests/[primaryKey + 1] result = callAction(controllers.routes.ref.Request.edit(primaryKey + 1)); assertEquals("Request detail (bad)", NOT_FOUND, status(result)); // Test POST /requests (with simulated, valid form data). Map<String, String> requestData = new HashMap<String, String>(); requestData.put("requestId", "Request-02"); requestData.put("studentId", "Student-01"); requestData.put("bookId", "Book-01"); requestData.put("targetPrice", "321"); FakeRequest fakeRequest = fakeRequest(); fakeRequest.withFormUrlEncodedBody(requestData); result = callAction(controllers.routes.ref.Request.save(), fakeRequest); assertEquals("Create new request", SEE_OTHER, status(result)); assertEquals("New request has correct student", "Name", Request.find().where().eq("requestId", "Request-02").findUnique().getStudent().getName()); assertEquals("New request has correct book", "Title", Request.find().where().eq("requestId", "Request-02").findUnique().getBook().getTitle()); // Test POST /requests (with simulated, invalid form data). fakeRequest = fakeRequest(); result = callAction(controllers.routes.ref.Request.save(), fakeRequest); assertEquals("Create bad request fails", BAD_REQUEST, status(result)); // Test DELETE /requests/Request-01 (a valid requestId). result = callAction(controllers.routes.ref.Request.delete(primaryKey)); assertEquals("Delete current request OK", SEE_OTHER, status(result)); result = callAction(controllers.routes.ref.Request.edit(primaryKey)); assertEquals("Deleted request gone", NOT_FOUND, status(result)); result = callAction(controllers.routes.ref.Request.delete(primaryKey)); assertEquals("Delete missing request also OK", SEE_OTHER, status(result)); } @Test public void testOfferControllers() { // Test GET /offers on an empty database. Result result = callAction(controllers.routes.ref.Offer.index()); assertTrue("Empty requests", contentAsString(result).contains("Offers")); // Test GET /offers on a database containing a single offer. String offerId = "Offer-01"; Student student = new Student("Student-01", "Name", "Email"); Book book = new Book("Book-01", "Title", "Edition", 1234L, 123); Offer offer = new Offer(offerId, student, book, 123); student.save(); book.save(); offer.save(); Long primaryKey = offer.getPrimaryKey(); result = callAction(controllers.routes.ref.Offer.index()); assertTrue("One Offer", contentAsString(result).contains(offerId)); // Test GET /offers/[primaryKey] result = callAction(controllers.routes.ref.Offer.edit(primaryKey)); assertTrue("Offer detail", contentAsString(result).contains(offerId)); // Test GET /offers/[primaryKey + 1] result = callAction(controllers.routes.ref.Request.edit(primaryKey + 1)); assertEquals("Request detail (bad)", NOT_FOUND, status(result)); // Test POST /offers (with simulated, valid form data). Map<String, String> offerData = new HashMap<String, String>(); offerData.put("offerId", "Offer-02"); offerData.put("studentId", "Student-01"); offerData.put("bookId", "Book-01"); offerData.put("targetPrice", "321"); FakeRequest fakeRequest = fakeRequest(); fakeRequest.withFormUrlEncodedBody(offerData); result = callAction(controllers.routes.ref.Offer.save(), fakeRequest); assertEquals("Create new offer", SEE_OTHER, status(result)); assertEquals("New offer has correct student", "Name", Offer.find().where().eq("offerId", "Offer-02").findUnique().getStudent().getName()); assertEquals("New offer has correct book", "Title", Offer.find().where().eq("offerId", "Offer-02").findUnique().getBook().getTitle()); // Test POST /offers (with simulated, invalid form data). fakeRequest = fakeRequest(); result = callAction(controllers.routes.ref.Offer.save(), fakeRequest); assertEquals("Create bad offer fails", BAD_REQUEST, status(result)); // Test DELETE /offers/Offer-01 (a valid OfferId). result = callAction(controllers.routes.ref.Offer.delete(primaryKey)); assertEquals("Delete current offer OK", SEE_OTHER, status(result)); result = callAction(controllers.routes.ref.Offer.edit(primaryKey)); assertEquals("Deleted offer gone", NOT_FOUND, status(result)); result = callAction(controllers.routes.ref.Offer.delete(primaryKey)); assertEquals("Delete missing offer also OK", SEE_OTHER, status(result)); } }
Java
UTF-8
1,885
2.171875
2
[ "MIT" ]
permissive
package uk.gov.hmcts.ccd.domain.model.std; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.jayway.jsonpath.PathNotFoundException; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import uk.gov.hmcts.ccd.config.JacksonUtils; import uk.gov.hmcts.ccd.endpoint.exceptions.ServiceException; @ToString @AllArgsConstructor @NoArgsConstructor @Getter public class SupplementaryData { @JsonIgnore private final ObjectMapper objectMapper = new ObjectMapper(); private Map<String, Object> response; public SupplementaryData(JsonNode data, Set<String> requestKeys) { if (requestKeys == null || requestKeys.isEmpty()) { this.response = JacksonUtils.convertJsonNode(data); } else { DocumentContext context = JsonPath.parse(jsonNodeToString(data)); this.response = new HashMap<>(); requestKeys.forEach(key -> { try { Object value = context.read("$." + key, Object.class); this.response.put(key, value); } catch (PathNotFoundException e) { throw new ServiceException(String.format("Path %s is not found", key)); } }); } } private String jsonNodeToString(JsonNode data) { try { return objectMapper.writeValueAsString(data); } catch (JsonProcessingException e) { throw new ServiceException("Unable to map object to JSON string", e); } } }
Java
UTF-8
1,519
2.9375
3
[]
no_license
class Site extends Thread{ /* Constantes associ�es au site */ static final int stockInit = 9; static final int stockMax = 10; static final int borneSup = 7; static final int borneInf = 2; int stockVelos; int numeroSite; public Site(int numeroSite){ this.numeroSite = numeroSite; this.stockVelos = stockInit; } public int getStockVelos() { return stockVelos; } public void setStockVelos(int stockVelos) { this.stockVelos = stockVelos; } public int getNumeroSite() { return numeroSite; } public void setNumeroSite(int numeroSite) { this.numeroSite = numeroSite; } public static int getStockinit() { return stockInit; } public static int getStockmax() { return stockMax; } public static int getBornesup() { return borneSup; } public static int getBorneinf() { return borneInf; } public synchronized void destockerSite(){ System.out.println("test1"); while(stockVelos <= borneSup){ try { System.out.println("test2"); wait(); } catch (InterruptedException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } } System.out.println("test3"); stockVelos--; //notifyAll(); } public synchronized void stockerSite(){ while(stockVelos <= borneInf){ try { wait(); } catch (InterruptedException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } } stockVelos++; notifyAll(); } public void run(){ } }
Java
UTF-8
1,023
1.703125
2
[]
no_license
package com.tencent.p177mm.plugin.wallet_payu.pwd.p1054a; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.p177mm.sdk.platformtools.C4990ab; import com.tencent.p177mm.wallet_core.p1512e.p1513a.C36383a; import java.util.HashMap; import org.json.JSONObject; /* renamed from: com.tencent.mm.plugin.wallet_payu.pwd.a.c */ public final class C29697c extends C36383a { public String token = ""; public C29697c(String str) { AppMethodBeat.m2504i(48504); HashMap hashMap = new HashMap(); hashMap.put("pin", str); mo70323M(hashMap); AppMethodBeat.m2505o(48504); } public final int cOX() { return 3; } /* renamed from: a */ public final void mo9383a(int i, String str, JSONObject jSONObject) { AppMethodBeat.m2504i(48505); C4990ab.m7410d("MicroMsg.NetScenePayUCheckPwd", "errCode " + i + " errMsg: " + str); this.token = jSONObject.optString("payu_reference"); AppMethodBeat.m2505o(48505); } }
C
UTF-8
198
2.609375
3
[ "MIT", "NCSA" ]
permissive
// This program should run. "The } that terminates a function is reached, and the value of the function call is not used by the caller (6.9.1)." int f(void){ } int main(void){ f(); return 0; }
Swift
UTF-8
774
2.890625
3
[]
no_license
// // DynamicTypeTextField.swift // TimersApp // // Created by Łukasz Bazior on 12/05/2020. // Copyright © 2020 Łukasz Bazior. All rights reserved. // import UIKit class DynamicTypeTextField: UITextField { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { nil } private func setup() { borderStyle = .roundedRect } } extension DynamicTypeTextField { convenience init(frame: CGRect = .zero, text: String? = nil, placeholder: String? = nil, textStyle: UIFont.TextStyle = .body) { self.init(frame: frame) self.text = text self.placeholder = placeholder self.font = .preferredFont(forTextStyle: textStyle) } }
Java
UTF-8
148
2.0625
2
[]
no_license
package d0922_1.Demo7; public class Father { //不能被重写,可以继承 public final void method1(){} public void method2(){} }
Java
UTF-8
2,216
2.734375
3
[]
no_license
package com.monkey.interceptor.test; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @program: demo * @description: TODO * @author: Mr.Wang * @create: 2018-01-05 17:59 **/ public class UserSecurityInterceptor implements HandlerInterceptor { //preHandle:预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Controller实现); // 返回值:true表示继续流程(如调用下一个拦截器或处理器); // false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应; //postHandle**:后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象) // 对模型数据进行处理或对视图进行处理,modelAndView也可能为null。 //afterCompletion**:整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间, // 还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion**。 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //业务处理 System.out.println("preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //业务处理 System.out.println("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //业务处理 System.out.println("afterCompletion"); } }
Shell
UTF-8
809
3.953125
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # Difido server # # description: Script that can be added to the /etc/init.d and will cause the server to run at the init stage. In additions, allows to use the start, stop and restart services. # # Instructions: # 1. Set the DIFIDO_PATH variable with the location of the difido-server. e.g. /usr/local/bin/difido-server # 2. Copy this script to /etc/init.d (Using root user) # 3. Cd to /user/init.d # 4. Execute the following command: # sudo update-rc.d difido defaults # # readonly DIFIDO_PATH=/usr/local/bin/difido-server function start { cd $DIFIDO_PATH /bin/bash bin/start.sh } function stop { cd $DIFIDO_PATH /bin/bash bin/stop.sh } case $1 in start) start ;; stop) stop ;; restart) stop start ;; esac exit 0
Java
UTF-8
2,460
3.09375
3
[]
no_license
package main.kazgarsrevenge.util.managers; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Set; import main.kazgarsrevenge.model.ChunkComponent; import main.kazgarsrevenge.model.impl.Room; import main.kazgarsrevenge.model.impl.RoomBlock; import main.kazgarsrevenge.util.IO.KRImageIO; /** * Manages operations using Images. Uses Singleton pattern * @author Brandon * */ public class ImageManager { // THE INSTANCE private static ImageManager instance; // Map of images for chunk components. Mapped by type, then name private Map<Class<? extends ChunkComponent>, Map<String, BufferedImage>> images; private BufferedImage unknownImage; private ImageManager() { images = new HashMap<>(); addBlocks(); addRooms(); addUnknown(); } /** * Gets an instance of the class * @return */ public static ImageManager getInstance() { if (instance == null) { instance = new ImageManager(); } return instance; } // Adds all of the known RoomBlock images private void addBlocks() { Map<String, BufferedImage> blockImages = KRImageIO.loadBlocks(); images.put(RoomBlock.class, blockImages); } // Adds all of the know Room images private void addRooms() { Map<String, BufferedImage> roomImages = KRImageIO.loadRooms(); images.put(Room.class, roomImages); } private void addUnknown() { unknownImage = KRImageIO.loadUnknownImage(); } /** * Loads any rooms found in the default folder that haven't already been loaded */ public void loadNewRooms() { Map<String, BufferedImage> knownImages = images.get(Room.class); Map<String, BufferedImage> newImages = KRImageIO.loadNewRooms(knownImages.keySet()); for (String key : newImages.keySet()) { knownImages.put(key, newImages.get(key)); } } /** * Returns the image with the associated with the given component and name * @param clazz * @param imageName * @return */ public BufferedImage getImage(Class<? extends ChunkComponent> clazz, String imageName) { Map<String, BufferedImage> map = images.get(clazz); if (!map.containsKey(imageName)) { System.out.println("Unknown room: " + imageName); return unknownImage; } return map.get(imageName); } /** * Returns the name for the images associated with the given class * @param clazz * @return */ public Set<String> getNames(Class<? extends ChunkComponent> clazz) { return images.get(clazz).keySet(); } }
Ruby
UTF-8
597
2.84375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby begin require 'feed_yamlizer' rescue LoadError require 'rubygems' require 'feed_yamlizer' end require 'open-uri' # just prints the text, not yaml def print_text(res) res[:items].each {|x| puts '-' * 30 puts x[:title] puts puts x[:content][:text] } end if ARGV.first == '-t' # text puts "Printing text form" @text = true ARGV.shift end result = if STDIN.tty? FeedYamlizer.process_url ARGV.first else FeedYamlizer.process_xml STDIN.read end if @text print_text result else puts result.to_yaml end
Ruby
UTF-8
1,211
2.859375
3
[]
no_license
require 'spec_helper' describe "XML menu" do before(:all) do @xml_menu = GuiseppesMenu.new end it "no price should be more than £10" do @xml_menu.price_array_maker @xml_menu.price_array.each do |price| expect(price).to be < 10 end end it "should have no item with calories over 1000 except for the full breakfast" do # Consider children element methods - Remember to step through the data and print out to the command line if you need it @xml_menu.calories_array_maker @xml_menu.name_array_maker (0..(@xml_menu.name_array.length-1)).each do |n| if @xml_menu.name_array[n] != 'Full Breakfast' expect(@xml_menu.calories_array[n]).to be <= 1000 end end end it "should have all waffle dishes stating you get two waffles" do # Consider children element methods - Remember to step through the data and print out to the command line if you need it @xml_menu.description_array_maker @xml_menu.name_array_maker (0..(@xml_menu.name_array.length-1)).each do |n| if @xml_menu.name_array[n].include? 'Waffle' expect(@xml_menu.description_array[n].downcase.include? 'two').to be true end end end end
C++
UTF-8
1,269
3.609375
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; // C++ 11 std. class triangle_numerics { public: double a, b, c; // triangle sides double circumference (double a, double b, double c); private: bool isIttriangle (double, double, double); }; double triangle_numerics::circumference (double a, double b, double c) { if (isIttriangle (a, b, c) == false){ cout << "This isn't sides of triangle.\n"; return(false); } else { return a + b + c; } } bool triangle_numerics::isIttriangle (double a, double b, double c) { // finding if Pythagoras' statement is fulfilled double max=0, el1=0, el2=0; if (a >= b && a >= c){ max = a; el1 = b; el2 = c; } else { if (b >= a && b >= c){ max = b; el1 = a; el2 = c; } else { max = c; el1 = a; el2 = b; } } if (pow (max, 2) == pow (el1, 2) + pow (el2, 2)){ return true; } else { return false; } } int main (void) { double a=0, b=0, c=0; // triangle sides cout<< "If you want to stop use Crtl + D" << endl << "Please put sides of the tringle :" << endl; while (1){ cin >> a >> b >> c; triangle_numerics* trian_1 = new triangle_numerics; cout << "Circumference of tringle: " << trian_1 -> circumference (a, b, c) << endl; delete trian_1; } }