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
Markdown
UTF-8
1,552
2.515625
3
[]
no_license
1.将对象交给容器管理,你只需要在spring配置文件总配置相应的bean,以及设置相关的属性,让spring容器来生成类的实例对象以及管理对象。在spring容器启动的时候,spring会把你在配置文件中配置的bean都初始化好,然后在你需要调用的时候,就把它已经初始化好的那些bean分配给你需要调用这些bean的类(假设这个类名是A),分配的方法就是调用A的setter方法来注入,而不需要你在A里面new这些bean了 2.请说明JAVA语言如何进行异常处理,关键字:throws,throw,try,catch,finally分别代表什么意义?在try块中可以抛出异常吗? 3.内存泄漏的原因:垃圾回收机制的不完善,引用计数法时,两个对象可以互相引用,实际上,对象已经没有用了,但垃圾回收机制无法进行回收;gc回收中有一种算法叫标记清理算法,它会产生内存碎片,如果有一个大对象或者组团的对象来,没有那么大的连续空间内存,就会产生内存泄露 4.死锁:死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁。死锁产生有四个必要条件,打破任意一个,就能打破死锁状态: 1 互斥条件 2 请求与保持 3 不剥夺 4 循环等待 5.请问过滤器有哪些作用?以及过滤器的用法又是什么呢?
C++
UTF-8
1,952
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool checkByNinga(vector<int> me,vector<int> nin) { if(me[0]==nin[0]||me[1]==nin[1]||(me[0]-me[1]==nin[0]-nin[1])||(me[0]+me[1]==nin[0]+nin[1])) return true; // find all valid knight positions of ninja int xMove[8] = { 2, 2, -2, -2, 1, 1, -1, -1 }; int yMove[8] = { 1, -1, 1, -1, 2, -2, 2, -2 }; for(int i=0;i<8;i++) { if(me[0]==nin[0]+xMove[i]&&me[1]==nin[1]+yMove[i]) return true; } return false; } bool checkByKing(vector<int> me,vector<int> king) { // find all 8 (valid only) positions of king int xMove[8] = { 1, 1, -1, -1, 0, 0, 1, -1 }; int yMove[8] = { 1, -1, 1, -1, 1, -1, 0, 0 }; for(int i=0;i<8;i++) { if(me[0]==king[0]+xMove[i]&&me[1]==king[1]+yMove[i]) return true; } return false; } bool checkStale(vector<int> me,vector<int> nin,vector<int> king) { // find all 8 positions of Me in vector allMe int xMove[8] = { 1, 1, -1, -1, 0, 0, 1, -1 }; int yMove[8] = { 1, -1, 1, -1, 1, -1, 0, 0 }; for(int i=0;i<8;i++) { // check validity vector<int> newMe{me[0]+xMove[i],me[1]+yMove[i]}; if(!(newMe[0]>=0&&newMe[0]<8&&newMe[1]>=0&&newMe[1]<8)) continue; if((!checkByNinga(newMe,nin))&&(!checkByKing(newMe,king))) return false; } return true; } int getC(int a) { int ct=0; while(a) { a=a&(a-1); ct++; } return ct; } bool isG(string &st1,string &st2) { // st1 inside st2 int i=0; int j=0; while(st1[i]!='\0'&&st2[j]!='\0') { if(st1[i]==st2[j]) { i++; j++; } else j++; } if(st1[i]=='\0') return true; return false; } int main(){ int t,n,i,sm,a,j,k,first,p,b,tn,s,mx,catsObs,catsHiding,c,d,l,ct,cfuel,f,mn,ans; string st; cin>>t; unordered_map<int,int> mp; while(t--) { cin>>n>>k; mn=INT_MAX; ans=-1; while(n--) { cin>>p; if(abs(k-p)%p==0) { if(abs(k-p)/p<mn) { mn=min(mn,abs(k-p)/p); ans=p; } } } cout<<ans<<endl; } return 0; }
JavaScript
UTF-8
3,337
2.515625
3
[ "MIT" ]
permissive
function languageSelectionClick(lang) { var languageClick = 'Lang:' + lang; digitalData.event.eventInfo.language.pageLanguage = digitalData.page.pageInfo.pageName + '^' + languageClick; digitalData.event.eventName = 'Page Language'; digitalData.event.eventInfo.eventName = 'Language Dropdown'; digitalData.event.eventInfo.language = lang; if ( typeof(Storage) !== "undefined" ) { localStorage.setItem("pageLanguage", digitalData.event.eventInfo.language.pageLanguage); localStorage.setItem("langEventName", "Page Language"); localStorage.setItem("eventInfoEventName", "Language Dropdown"); localStorage.setItem("eventInfoLanguage", lang); } else{ setCookie("pageLanguage", digitalData.event.eventInfo.language.pageLanguage); setCookie("langEventName", "Page Language"); setCookie("eventInfoEventName", "Language Dropdown"); setCookie("eventInfoLanguage", lang); } } function handleToggleLangDropdown(e) { if (e.keyCode === 13 || e.keyCode === 32) { e.preventDefault(); toggleLanguageDropDown(e.target); } } function toggleLanguageDropDown(elem) { var selectedElement; var ulElement = $('.uscb-lang-dropdown-selection'); var languageDropdown = $('.uscb-input-container') var target = $(elem); if (target.is("li") ) { selectedElement = target[0]; ulElement.toggleClass('uscb-hide-dropdown'); languageDropdown.attr('aria-expanded', false); languageSelectionClick($(selectedElement).text()); $(location).attr("href", $(selectedElement).attr("id")); } else { ulElement.toggleClass('uscb-hide-dropdown'); var newAriaExpandedState = languageDropdown.attr('aria-expanded') === 'true' ? 'false' : 'true'; languageDropdown.attr('aria-expanded', newAriaExpandedState); $('.uscb-lang-dropdown').prepend("<div class='uscb-dropdown-backdrop'></div>"); $('.uscb-dropdown-backdrop').click(function(event) { ulElement.toggleClass('uscb-hide-dropdown'); $(this).remove(); event.stopPropagation(); }); } } function onKeyParent(event) { if (event.keyCode === 40) { //down arrow var target = document.getElementById("languageSelector"); var element = target.querySelector(".lang-options"); if (element) { element.focus(); event.stopPropagation(); } } } function onKeyChild(event, element) { if (event.keyCode === 13 || event.keyCode === 32) { //enter or space event.preventDefault(); var ulElement = $('.uscb-lang-dropdown-selection'); var languageDropdown = $('.uscb-input-container') var target = $(element); var selectedElement = target[0]; languageDropdown.attr('aria-expanded', false); ulElement.toggleClass('uscb-hide-dropdown'); languageSelectionClick($(selectedElement).text()); $(location).attr("href", $(selectedElement).attr("id")); } } function moveLanguageSelector(){ if (Modernizr.mq('only screen and (min-width : 10px) and (max-width : 992px)')) {//was 576px $('#mobileLanguageSelectorContainer').append($('#languageSelector')); } else { $('#desktopLanguageSelectorContainer').append($('#languageSelector')); } } $(document).ready(function(){ moveLanguageSelector(); $(window).resize(function(){ moveLanguageSelector(); }); });//end document.ready function
TypeScript
UTF-8
1,260
3.765625
4
[]
no_license
// radix sort O(n) function createBuckets() { const result = []; for(let i = 0; i < 10; i++) { result.push([]); } return result } function baseSort(nums: number[]) { for (let i = 0; i < 9; i++) { const buckets = createBuckets(); nums.forEach((num) => { buckets[Math.floor(num % 10**(i + 1) / 10**i)].push(num); }); nums = buckets.reduce((res, bucket) => res.concat(bucket)); } return nums; } function longestConsecutive(nums: number[]): number { if (nums.length === 0) { return 0; } const pos = []; const neg = []; nums.forEach((num) => { if (num >= 0) { pos.push(num); } else { neg.push(-num); } }); const sortedArr = baseSort(neg).map((n) => -n).reverse().concat(baseSort(pos)); let max = 1; let prev = sortedArr[0]; let len = 1; for(let i = 1; i < sortedArr.length; i++) { if (sortedArr[i] === prev + 1) { len++; if (len > max) { max = len; } } else if (sortedArr[i] !== prev) { len = 1; } prev = sortedArr[i]; } return max; };
Markdown
UTF-8
1,065
2.578125
3
[ "Apache-2.0" ]
permissive
# coffeedates A little utility for generating matches for coffee dates. Matches are optimized for people who haven't been matched before, or if that is not possible, for matches in the more distant past. Run the utility to create a new dataset: ``` $> ./coffeeDates.py No Datasets available. You must create one first... What is the new dataset called? KitchenerOffice Dataset has been created for KitchenerOffice. Please add participants to the file ./KitchenerOffice/participants.txt $> ``` Add your participants to the participants.txt file: ``` Simon Clark:sclark Dana Loy:dloy Albert Zhong:azhong Miriam Novotny:mnovot ``` Run the utility again to generate the matches: ``` $> ./coffeeDates.py 1: KitchenerOffice C: Create new dataset... Which dataset do you want to generate matches for? 1 Generating matches for ./data/KitchenerOffice 4 Participants found. 2020-09-25 15:17:58.777407 @azhong is paired with @dloy @mnovot is paired with @sclark Weighting: 0.000000 Do you wish to proceed? (Y/N) y Committing matches $> ``` Copy and paste the matches to your slack channel
Python
UTF-8
4,102
3.171875
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import re import json import cpca while (1): try: address = input() if(address == "END"): break except EOFError: break if(address[0:2] == '1!'): #划分等级后删除标识符 flag = 1 address = address.strip('1!') elif(address[0:2] == '2!'): flag = 2 address = address.strip('2!') else: flag = 3 address = address.strip('3!') #获取姓名 NAME = re.compile(r'(.*),') name = NAME.findall(address) #获取手机号码 telephone = re.compile(r'\d{11}') #连续11位数字即是手机号码 telephone_num = telephone.findall(address) #获取地址 list_address = address.split(',') #以逗号为分隔符,将名字和剩余的信息分开 if(len(list_address) > 1): address = list_address[1] list_address = address.split(str(telephone_num[0])) #以电话号码为分隔符,分割该字符串中的地址信息 address = list_address[0] + list_address[1] #用cpca模块提取省市区信息(前三级) address1 = address.split() df = cpca.transform(address1, cut = False, lookahead = 13) #DataFrame list_address = df.values[0] if(list_address[0][0:2] != address1[0][0:2]): df = cpca.transform(address, cut=False, lookahead = 13) list_address = df.values[0] ADDRESS = list_address[-1] #取列表最后一个元素 list_address = list(list_address) list_address.pop() if(list_address[0] == '北京市'or'上海市'or'天津市'or'重庆市'): list_address[0] = str(list_address[0]).strip('市') #直辖市在第一级时要去掉'市' #提取详细地址 ADDRESS = ADDRESS.strip('.') #去掉句号 #提取第四级 TOWN = re.compile(r'(.*?)镇') town = TOWN.findall(ADDRESS) STREET = re.compile(r'(.*?)街道') street = STREET.findall(ADDRESS) XIANG = re.compile(r'(.*?)乡') xiang = XIANG.findall(ADDRESS) if (len(town) != 0): ADDRESS = ADDRESS.split('镇') ADDRESS[0] += '镇' list_address += ADDRESS ADDRESS = ADDRESS[1] elif (len(street) != 0): ADDRESS = ADDRESS.split('街道') ADDRESS[0] += '街道' list_address += ADDRESS ADDRESS = ADDRESS[1] elif (len(xiang) != 0): ADDRESS = ADDRESS.split('乡') ADDRESS[0] += '乡' list_address += ADDRESS ADDRESS = ADDRESS[1] else: ADDRESS = ADDRESS.split() list_address += ADDRESS list_address.insert(3, '') ADDRESS = ADDRESS[0] #提取第六级 if (flag == 2): list_address.pop() #删掉最后一个元素 road = re.search(r'(.*?路)|(.*?[路街港道])|(.*胡同)|(.*?乡道)|(.*?区)|(.*?里)|(.?坊)',ADDRESS) if (road == None): list_address.insert(4, '') # 缺失的道路位置保留空字符串 else: road = road.group(0) road = road.split() list_address += road road = road[0] ADDRESS = ADDRESS.replace(road, '', 1) #门牌号 door_number = re.search(r'(.*?号)|(.*?[道]|(.*?弄)|(.*?[乡]))', ADDRESS) if (door_number == None): list_address.insert(5, '') #缺失的门牌号位置保留空字符串 else: door_number = door_number.group(0) door_number = door_number.split() list_address += door_number door_number = door_number[0] ADDRESS = ADDRESS.replace(door_number, '', 1) if (len(ADDRESS) != 0): ADDRESS = ADDRESS.split() list_address += ADDRESS else: list_address .insert(6, '') #第七级详细信息缺失置空字符串 result = {'姓名':name[0],'手机':telephone_num [0],'地址':list_address} dict = json.dumps(result, ensure_ascii=False) #将dict转换为json print(dict)
Java
UTF-8
2,090
3.515625
4
[]
no_license
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class DummyProcessor { private Dummy pd; public DummyProcessor(Dummy d) { pd = d; } public void write() throws IOException { System.out.println("Entering Function write"); // if askUser() fails below, localBDummy would be released // for the garbage collector to process Dummy localBDummy = new Dummy("Local write() Dummy"); BufferedWriter file = new BufferedWriter(new FileWriter( "DummyOutput.txt")); file.write(pd.dummyName + ", " + pd.age); // never closed if write throws an exception! // solution is to catch here, or else a resource is leaked file.close(); System.out.println("Exiting Function write"); } public void askUser() throws IOException { System.out.println("Entering Function askUser"); // if askUser() fails below, localCDummy would be released // for the garbage collector to process Dummy localCDummy = new Dummy("Local changeName() Dummy"); Scanner keyboard = new Scanner(System.in); System.out.println("Enter the age of the Dummy: "); pd.age = keyboard.nextInt(); this.write(); // Scanner is never closed if write throws an exception! // solution is to catch here, or else a resource is leaked keyboard.close(); System.out.println("Exiting Function askUser"); } public void changeName() throws IOException { System.out.println("Entering Function changeName"); // if askUser() fails below, localCDummy would be released // for the garbage collector to process Dummy localCDummy = new Dummy("Local read() Dummy"); BufferedReader file = new BufferedReader(new FileReader("DummyInput.txt")); System.out.println("File opened"); pd.dummyName = pd.dummyName + " " + file.readLine(); this.askUser(); // BufferedReader and FileReader are never closed if write throws an exception! // solution is to catch here, or else a resource is leaked file.close(); System.out.println("Exiting Function changeName"); } }
Markdown
UTF-8
2,976
2.609375
3
[ "MIT" ]
permissive
--- title: 'GPO: User Backup To File Share' date: 2016-05-29T04:24:00+00:00 author: gerryw1389 layout: single classes: wide permalink: /2016/05/gpo-user-backup-to-file-share/ categories: - WindowsServer tags: - GroupPolicy - Backup --- <!--more--> ### Description: This is a quick user backup solution for users on a domain. We needed to setup a backup for users over the network that would backup their documents, favorites, and desktop. NOTE: We only have like 80 users on our domain so YMMV. If you have a large user base this is not suggested. {: .notice--success} ### 1. Create this user logon script batch file ```escape cd c:\windows\system32\ mkdir c:\users\%username%\Documents\IT robocopy C:\Users\%username%\Documents \\fileservername\userbackups\%username%\Documents /E /log:c:\users\%username%\Documents\IT\robo.log robocopy C:\Users\%username%\Desktop \\fileservername\userbackups\%username%\Desktop /E /log:c:\users\%username%\Documents\IT\robo.log robocopy C:\Users\%username%\Favorites \\fileservername\userbackups\%username%\Favorites /E /log:c:\users\%username%\Documents\IT\robo.log ``` - What it does: This script backs up all the files in those locations. If the user deletes them, they still stay on the fileserver. 2. Created a new GPO at the OU container for all users (Domain.com\CorporateUsers) 3. Edited the GPO, went to User Configuration\Policies\Windows Settings\Scripts(Logon/Logoff) and pointed to the script. - Located at: \\domain.com\SysVol\domain.com\Policies\{437B28BF-AEBB-45A6-B092-D65E463D5A95}\User\Scripts\Logon 4. Run => cmd => gpupdate on the server and on my computer. ### Maintenance: 1. When the user logs in for the first time, the folder will be created in the share automatically. 2. We then go into the share and edit the permissions for that folder: - Disable inheritance and convert to explicit permissions. <img class="alignnone size-full wp-image-718" src="https://automationadmin.com/assets/images/uploads/2016/09/user-backup-to-fileshare-2.png" alt="user-backup-to-fileshare-2" width="540" height="275" srcset="https://automationadmin.com/assets/images/uploads/2016/09/user-backup-to-fileshare-2.png 540w, https://automationadmin.com/assets/images/uploads/2016/09/user-backup-to-fileshare-2-300x153.png 300w" sizes="(max-width: 540px) 100vw, 540px" /> - Remove all users except that user and administrator. <img class="alignnone size-full wp-image-719" src="https://automationadmin.com/assets/images/uploads/2016/09/user-backup-to-fileshare-3.png" alt="user-backup-to-fileshare-3" width="369" height="392" srcset="https://automationadmin.com/assets/images/uploads/2016/09/user-backup-to-fileshare-3.png 369w, https://automationadmin.com/assets/images/uploads/2016/09/user-backup-to-fileshare-3-282x300.png 282w" sizes="(max-width: 369px) 100vw, 369px" /> 3. After an employee leaves, we move their folder over to another after x amount of days.
C#
UTF-8
1,445
2.9375
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.Threading.Tasks; using System.Windows.Forms; namespace Cuaderno { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Book book = new Book(); book.setcolor(textBox4.Text); book.sethojas(textBox3.Text); book.settamaño(textBox2.Text); if (textBox2.Text == "" & textBox3.Text == "" & textBox4.Text == "") { MessageBox.Show("no se deben dejar cuadros vacios"); } else { listBox1.Items.Add(book.getTodo()); } textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox2.Focus(); } private void Form1_Load(object sender, EventArgs e) { //agregar los datos al ListBox label1.Text = " Cuaderno"; label2.Text = "Tamaño"; label3.Text = " Hojas"; label4.Text = "Color"; button1.Text = "Agregar"; } private void textBox4_TextChanged(object sender, EventArgs e) { } } }
SQL
UTF-8
1,034
3.6875
4
[]
no_license
DROP DATABASE service_platform; CREATE DATABASE service_platform; USE service_platform; DROP USER 'iot4pwc'@'localhost'; FLUSH PRIVILEGES; CREATE USER 'iot4pwc'@'localhost' IDENTIFIED BY 'Heinz123!'; GRANT ALL PRIVILEGES ON service_platform.* TO 'iot4pwc'@'localhost'; DROP TABLE sensor_topic_map; DROP TABLE sensor_history; DROP TABLE sensor; CREATE TABLE sensor ( sensor_id INT(10) AUTO_INCREMENT, sensor_type VARCHAR(20), sensor_desc VARCHAR(80), model_no VARCHAR(40), installed_on DATE, expiration_date DATE, install_loc VARCHAR(40), CONSTRAINT sensor_pk PRIMARY KEY(sensor_id) ); CREATE TABLE sensor_topic_map( sensor_id INT(10), topic VARCHAR(40), CONSTRAINT sensor_topic_map_pk PRIMARY KEY(sensor_id, topic), CONSTRAINT sensor_topic_map_fk FOREIGN KEY (sensor_id) REFERENCES sensor(sensor_id) ); CREATE TABLE sensor_history ( record_id INT(10) AUTO_INCREMENT, sensor_id INT(10), recorded_time TIMESTAMP, value_content VARCHAR(200), CONSTRAINT sensor_history_pk PRIMARY KEY(record_id) );
C#
UTF-8
3,735
2.6875
3
[]
no_license
using HairForceOne.WinFormsDesktopClient.Model; using Meziantou.Framework.Win32; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; // håndter exceptions (custom exception??) // tag exception fra statuscode og håndter den // try catch (Måske) // navngiv metoder // async namespace HairForceOne.WinFormsDesktopClient.Controller { internal class ProductsController : IProductsController { private readonly HttpClient client = new HttpClient(); /// <summary> /// Initializes a new instance of the <see cref="ProductsController"/> class. /// </summary> public ProductsController() { client.BaseAddress = new Uri(ConfigurationManager.AppSettings["HairForceOneApiURL"]); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CredentialManager.ReadCredential(applicationName: "Token").Password); } /// <summary> /// This method gets a list of all Product objects using HttpClient /// </summary> /// <returns>A list of Products</returns> public List<Product> GetAllProducts() { Task<HttpResponseMessage> responseTask = client.GetAsync($"products"); responseTask.Wait(); if (responseTask.Result.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<List<Product>>(responseTask.Result.Content.ReadAsStringAsync().Result); } else { throw new NotImplementedException(); } } /// <summary> /// This method gets a specific ProductId from the list of Product objects using HttpClient /// /// </summary> /// <param name="id"></param> /// <returns>A Product object by ProductId</returns> //Todo public Service GetProduct(int id) { throw new NotImplementedException(); } /// <summary> /// This methods posts a new Product object using HttpClient /// </summary> /// <param name="product"></param> /// <returns></returns> public bool CreateNewProduct(Product product) { var JProduct = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = client.PostAsync($"products/", JProduct); responseTask.Wait(); return responseTask.Result.IsSuccessStatusCode; } /// <summary> /// This method updates the exsisting Product object using HttpClient /// </summary> /// <param name="product"></param> /// <returns></returns> public bool EditProduct(Product product) { var JProduct = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = client.PutAsync($"products/{product.ProductId}", JProduct); responseTask.Wait(); return responseTask.Result.IsSuccessStatusCode; } /// <summary> /// This method deletes the Product object from the database, using HttpClient /// </summary> /// <param name="id"></param> /// <returns></returns> public bool DeleteProduct(int id) { Task<HttpResponseMessage> responseTask = client.DeleteAsync($"products/{id}"); responseTask.Wait(); return responseTask.Result.IsSuccessStatusCode; } } }
C#
UTF-8
7,222
3.015625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.IO.Compression; namespace ZipWork { public class ZipManager { private string wPath; private string wInfo; private string ZipFileName; // Total number of files inside each zip file private int TotalNumFiles; public int FileCount; public int ActurisNB; public int ActurisMTA; public int ActurisRNC; public int AppliedNB; public int AppliedMTA; public int AppliedRNC; public int CDLNB; public int CDLMTA; public int CDLRNC; public int SSPNB; public int SSPMTA; public int SSPRNC; public ZipManager() { wInfo = ""; } public int FilesCount(string wLocalPath) { int wFileCount = Directory.GetFiles(wLocalPath, "*.zip", SearchOption.TopDirectoryOnly).Length; return wFileCount; } // Read each zip file from the current daily folder here: public bool CheckZipFolder() { string[] ZipFolder = Directory.GetFiles(wPath, "*.zip"); TotalNumFiles = 0; // Looping through all zip files in the daily zip folder: Console.WriteLine("Counting number of files inside each zip file..."); foreach (string filename in ZipFolder) { ZipFileName = filename; // Get the zip filename FileCount = NumberOfItems(); TotalNumFiles += FileCount; Console.WriteLine($"filename {ZipFileName} has {FileCount} files inside."); if (!(CheckProvider(ZipFileName, FileCount))) { Console.WriteLine($"File:{ZipFileName} is Wrong"); } } Console.WriteLine($"Total number of files to be processed: {TotalNumFiles}."); return true; } //Count the number of files inside the zip file private int NumberOfItems() { int wFileCount = 0; if (!File.Exists(ZipFileName)) { wInfo = "Incorrect filename."; return 0; } try { string wfilename = Path.GetFileName(ZipFileName); using ZipArchive csZipArchive = ZipFile.OpenRead(ZipFileName); foreach (var entry in csZipArchive.Entries) { if (!string.IsNullOrEmpty(entry.Name)) { wFileCount += 1; } } } catch (UnauthorizedAccessException) { wInfo = "Warning: Authorization required to open that file/object."; } finally { if (wInfo.Length > 0) { wFileCount = 0; } } return wFileCount; } private bool CheckProvider(string wZipFileName, int FilesCount) { // Acturis Processing if (wZipFileName.ToUpper().Contains("ACTURIS") && wZipFileName.ToUpper().Contains("NB")) { ActurisNB += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("ACTURIS") && wZipFileName.ToUpper().Contains("MTA")) { ActurisMTA += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("ACTURIS") && wZipFileName.ToUpper().Contains("RNL")) { ActurisRNC += FilesCount; return true; } // Applied Processing if (wZipFileName.ToUpper().Contains("APPLIED") && wZipFileName.ToUpper().Contains("NB")) { AppliedNB += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("APPLIED") && wZipFileName.ToUpper().Contains("MTA")) { AppliedMTA += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("APPLIED") && wZipFileName.ToUpper().Contains("RNL")) { AppliedRNC += FilesCount; return true; } // CDL Processing if (wZipFileName.ToUpper().Contains("CDL") && wZipFileName.ToUpper().Contains("NB")) { CDLNB += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("CDL") && wZipFileName.ToUpper().Contains("MTA")) { CDLMTA += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("CDL") && wZipFileName.ToUpper().Contains("RNL")) { CDLRNC += FilesCount; return true; } // SSP Processing if (wZipFileName.ToUpper().Contains("SSP") && wZipFileName.ToUpper().Contains("NB")) { SSPNB += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("SSP") && wZipFileName.ToUpper().Contains("MTA")) { SSPMTA += FilesCount; return true; } if (wZipFileName.ToUpper().Contains("SSP") && wZipFileName.ToUpper().Contains("RNL")) { SSPRNC += FilesCount; return true; } return false; } public void AssignToExcell(string ExcellPath) { ExcellInterface myXls = new ExcellInterface(); myXls.ActurisNB = this.ActurisNB; myXls.ActurisMTA = this.ActurisMTA; myXls.ActurisRNC = this.ActurisRNC; myXls.AppliedNB = this.AppliedNB; myXls.AppliedMTA = this.AppliedMTA; myXls.AppliedRNC = this.AppliedRNC; myXls.CDLNB = this.CDLNB; myXls.CDLMTA = this.CDLMTA; myXls.CDLRNC = this.CDLRNC; myXls.SSPNB = this.SSPNB; myXls.SSPMTA = this.SSPMTA; myXls.SSPRNC = this.SSPRNC; myXls.SheetName = TodaysDate; myXls.OpenXls(ExcellPath); // Open Xls files here and do all the check } public bool MakeZipFile(string[] ZipFiles, string ZipPath) { string wMainZipFileName = ZipPath + "package.zip"; ZipArchive zip = ZipFile.Open(wMainZipFileName, ZipArchiveMode.Create); foreach (string file in ZipFiles) { zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal); } zip.Dispose(); return true; } public string ZipFilesPath { get { return wPath; } set { wPath = value; } } public string TodaysDate { get; set; } } }
JavaScript
UTF-8
5,302
2.953125
3
[]
no_license
//variables const database = firebase.database() const opt_div = document.getElementById('opt-div') const q_para = document.getElementById("q-para") const qNum_div = document.getElementById('qNum-div') const timer_div = document.getElementById('timer-div') const nxt_btn = document.getElementById('nxt') const quizApp = document.getElementById('quizApp') const main = document.getElementById('main') const user_name = document.getElementById('user-name') window.value = "" var qcount = 0 var score = 0 var correctans = 0 var wrongans = 0 var attempt = 0 var unattempt = 0 //fetching data from database const showQ = (myCallback) => { var leadsRef = database.ref('question-dataset') leadsRef.on('value', function (snapshot) { snapshot.forEach(function (childSnapshot) { window.questions = childSnapshot.val() printQuestion(qcount,questions) }); }); } const printQuestion=(e,questions)=>{ //print question var q_paratxt = document.createTextNode(questions[e].q) q_para.appendChild(q_paratxt) //print options for (let i = 0; i < questions[e].op.length; i++) { var lab = document.createElement("label") var labTxt = document.createTextNode(questions[e].op[i]) var input = document.createElement("input") input.setAttribute("type", "radio") input.setAttribute("name", "q-op") input.setAttribute("onclick", "check(this)") lab.setAttribute("class", "active") lab.appendChild(input) lab.appendChild(labTxt) opt_div.appendChild(lab) var br = document.createElement("br") opt_div.appendChild(br) } //show question number in header div var x; x = qcount; var qNumTxt = document.createTextNode("Question Number :" + ++x + "/" + questions.length); qNum_div.appendChild(qNumTxt); } //to load data in body document.getElementById('quizApp').addEventListener("load",showQ(0,printQuestion)) //getting checked value from option div const check = (e) => window.value = e.parentNode.lastChild.nodeValue //next function const next = () => { opt_div.innerHTML = "" q_para.innerHTML = "" qNum_div.innerHTML = "" if (window.value == questions[qcount].ans) { score += 10; correctans++; attempt++; window.value = "" } else if (window.value == "") { unattempt++; } else if (window.value != questions[qcount].ans) { wrongans++; attempt++; window.value = "" } qcount++ if (qcount == questions.length) { printResult() } else { showQ(qcount,printQuestion) } } const printResult = () => { main.innerHTML = ""; var h1 = document.createElement("h1") var h1txt = document.createTextNode("Result") var br = document.createElement("br") var p1 = document.createElement("p") var p1txt = document.createTextNode("Correct Ans " + correctans) var p2 = document.createElement("p") var p2txt = document.createTextNode("Wrong Ans " + wrongans) var p3 = document.createElement("p") var p3txt = document.createTextNode("Scores " + score) var p4 = document.createElement("p") var p4txt = document.createTextNode("Attempt " + attempt) var p5 = document.createElement("p") var p5txt = document.createTextNode("Unattempt " + unattempt) h1.appendChild(h1txt) main.appendChild(h1) main.appendChild(br) p1.appendChild(p1txt) main.appendChild(p1) main.appendChild(br) p2.appendChild(p2txt) main.appendChild(p2) p3.appendChild(p3txt) main.appendChild(p3) main.appendChild(br) p4.appendChild(p4txt) main.appendChild(p4) main.appendChild(br) p5.appendChild(p5txt) main.appendChild(p5) main.appendChild(br) ///home link var homebtn = document.createElement("a") var homebtntxt = document.createTextNode("Go to Home page") homebtn.setAttribute("href","index.html") homebtn.appendChild(homebtntxt) main.appendChild(homebtn) ///start again var sabtn = document.createElement("a") var sabtntxt = document.createTextNode("Start Again") sabtn.setAttribute("href","quizApp.html") sabtn.setAttribute("style","float:right") sabtn.appendChild(sabtntxt) main.appendChild(sabtn) var userId=localStorage.getItem("uid") var d = new Date(); var dt=d.toLocaleString() var Data={ score:score, correctans:correctans, wrongans:wrongans, attempt:attempt, unattempt:unattempt, date:dt } database.ref("Users").child(userId).child("result").push(Data) } //timer var total_seconds = 300; var c_minutes = parseInt(total_seconds / 60); var c_seconds = parseInt(total_seconds % 60); const CheckTime = () => { timer_div.innerHTML = 'Time Left: ' + c_minutes + ' : ' + c_seconds + 's'; if (total_seconds <= 0) { for (i = 0; i < questions.length; i++) { next(); } } else { total_seconds = total_seconds - 1; c_minutes = parseInt(total_seconds / 60); c_seconds = parseInt(total_seconds % 60); setTimeout("CheckTime()", 1000); } } setTimeout("CheckTime()", 1000);
C++
UTF-8
885
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int len,g,p,r; while(scanf("%d %d",&len,&g),len||g){ vector<pair<int,int>> intervals; for(int i=0;i<g;i++){ scanf("%d %d",&p,&r); intervals.push_back({p-r,p+r}); } sort(intervals.begin(),intervals.end()); int cur = 0; int res = 0; for(int i=0;i<g && cur<len;i++){ if(intervals[i].first > cur) { break; } int furthestRight = intervals[i].second; while(i+1<intervals.size() && intervals[i+1].first <= cur){ furthestRight = max(intervals[++i].second,furthestRight); } res++; cur = furthestRight; } if(cur<len){ printf("-1\n"); } else { printf("%d\n",g-res); } } }
Python
UTF-8
763
3.5
4
[]
no_license
def permute(values): n=len(values) c=0 for i in (range(n-1)): if values[i]<values[i+1]: break c+=1 if c==n: values[:]=reversed(values[:]) return values c=0 for i in (range(n-1)): if values[i] > values[i+1]: break c += 1 if c == n: values[n-2:n] = reversed(values[n-2:n]) return values for i in reversed(range(n)): if values[i-1]<values[i]: values[i:]=sorted(values[i:]) j=i while values[i-1]>values[j]: j=j+1 values[i-1],values[j]=values[j],values[i-1] values[i:] = sorted(values[i:]) return values print(permute([1,2,3,8,7,7]))
Rust
UTF-8
2,351
3.375
3
[ "MIT" ]
permissive
use crate::transformer::{TransformContext, UniqTransformer, Uniqueness}; use fake::faker::internet::raw::*; use fake::locales::EN; use fake::Fake; use serde::{Deserialize, Serialize}; /// Transformer generates random emails /// /// # Examples /// /// ```yaml /// #... /// rules: /// field_name: /// email: /// kind: Safe /// ``` #[derive(Serialize, Deserialize, PartialEq, Eq, Hash, Clone, Debug)] pub struct EmailTransformer { /// Transformation kind pub kind: Option<EmailKind>, #[serde(default)] pub uniq: Uniqueness, } /// Kind of email generator #[derive(Serialize, Deserialize, PartialEq, Eq, Hash, Clone, Debug)] pub enum EmailKind { /// Used by default Free, /// Only for "gmail.com", "yahoo.com", "hotmail.com" providers FreeProvider, /// Generates only for .com, .net, .org domains Safe, } impl EmailTransformer { pub fn new() -> Self { Self::default() } } impl Default for EmailTransformer { fn default() -> Self { Self { kind: Some(EmailKind::Free), uniq: Uniqueness::default(), } } } impl UniqTransformer for EmailTransformer { fn do_transform( &self, _field_name: &str, _field_value: &str, _ctx: &Option<TransformContext>, ) -> String { match self.kind { Some(EmailKind::FreeProvider) => FreeEmailProvider(EN).fake(), Some(EmailKind::Free) => FreeEmail(EN).fake(), _ => SafeEmail(EN).fake(), } } fn uniq(&self) -> &Uniqueness { &self.uniq } } #[cfg(test)] mod tests { use super::EmailKind; use crate::Transformers; #[test] fn test_parse_config() { let config = r#"email: {}"#; let transformer: Transformers = serde_yaml::from_str(config).unwrap(); if let Transformers::Email(transformer) = &transformer { assert_eq!(transformer.kind, None); } assert!(matches!(transformer, Transformers::Email(_))); } #[test] fn test_different_email_kinds() { let config = r#" email: kind: Safe "#; let transformer: Transformers = serde_yaml::from_str(config).unwrap(); if let Transformers::Email(transformer) = &transformer { assert_eq!(transformer.kind, Some(EmailKind::Safe)); } } }
Python
UTF-8
250
4
4
[]
no_license
# Dictionary Comprehension # Without Dict Comprehension (Conditional) dict1 = {} for n in range(10): if n%2==0 : dict1[n]=n*2 print(dict1) # With Dictionary Comprehension (Conditional) dict2 = {n:n*2 for n in range(10) if n%2==0} print(dict2)
C++
UTF-8
1,629
3.15625
3
[]
no_license
#include "StringTokenizer.h" #include <iostream> namespace sys{ StringTokenizer::StringTokenizer(const char* s) : m_string(s), m_tokens() {} StringTokenizer::~StringTokenizer() {} // from http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html const std::vector<std::string>& StringTokenizer::get_tokens(const char* d){ m_tokens.clear(); const std::string delimiters(d); std::string::size_type lastPos = m_string.find_first_not_of(delimiters, 0); std::string::size_type pos = m_string.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. m_tokens.push_back(m_string.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = m_string.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = m_string.find_first_of(delimiters, lastPos); } return m_tokens; } std::string StringTokenizer::get_token_string(const char* delimiter, const char* space, unsigned int begin, unsigned int end){ std::string result; const std::string the_space(space); const std::vector<std::string>& tokens = get_tokens(delimiter); const unsigned int the_end((end == 0) ? tokens.size() : end); std::string last_result; unsigned int pos = begin; for(; pos < the_end && pos < tokens.size(); ++pos){ result += tokens[pos]; last_result = result; result += the_space; } result = last_result; return result; } }
Shell
UTF-8
815
3.34375
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env bash # Copyright 2017, Reef Technologies (reef.pl), All rights reserved. PROJECT_DIR=`cd "$(dirname "${BASH_SOURCE[0]}")" && pwd` # Install pip packages if [ `pip freeze | wc -l` -le "1" ]; then echo "Installing pip development requirements" eval "pip install --upgrade -r ${PROJECT_DIR}/app/src/requirements.txt" fi # Set default docker-compose.yml file ln -sf dc-virtualenv.yml docker-compose.yml # Backup .env file [[ ! -f "${PROJECT_DIR}/.env" ]] || mv "${PROJECT_DIR}/.env" "${PROJECT_DIR}/.env~" # Load .envrc from backup [[ ! -f "${PROJECT_DIR}/.envrc~" ]] || mv "${PROJECT_DIR}/.envrc~" "${PROJECT_DIR}/.envrc" # Create .envrc from template [[ -f "${PROJECT_DIR}/.envrc" ]] || cp "${PROJECT_DIR}/.envrc.template" "${PROJECT_DIR}/.envrc" # Enable direnv eval "direnv allow"
JavaScript
UTF-8
563
2.609375
3
[]
no_license
import { GET_ALL_INGREDIENTS, GET_INGREDIENT } from '../actions/types'; const initialState = { ingredient: null, ingredients: [], loading: true, error: {} }; export default function(state = initialState, action) { const { type, payload } = action; switch (type) { case GET_ALL_INGREDIENTS: return { ...state, ingredients: payload, loading: false }; case GET_INGREDIENT: return { ...state, ingredient: payload, loading: false }; default: return state; } }
Java
UTF-8
3,464
2.203125
2
[]
no_license
package edu.psu.ist.acs.micro.mid.scratch; import java.io.IOException; import java.util.List; import java.util.Random; import org.bson.Document; import edu.cmu.ml.rtw.generic.data.StoredItemSetInMemoryLazy; import edu.cmu.ml.rtw.generic.data.annotation.DocumentSetInMemoryLazy; import edu.cmu.ml.rtw.generic.data.annotation.nlp.DocumentNLP; import edu.cmu.ml.rtw.generic.data.annotation.nlp.DocumentNLPMutable; import edu.cmu.ml.rtw.generic.data.annotation.nlp.SerializerDocumentNLPBSON; import edu.cmu.ml.rtw.generic.data.store.Storage; import edu.cmu.ml.rtw.generic.data.store.StoredCollection; import edu.psu.ist.acs.micro.mid.data.MIDDataTools; import edu.psu.ist.acs.micro.mid.util.MIDProperties; /** * * SplitCOWData splits NLP annotated COW documents output * from edu.psu.ist.acs.micro.mid.scratch.ConstructCOWData * into train/dev/test split directories. The output of this * is currently stored on ds9 at * /data_reitter/micro/mid_bson/mid4_narratives_[train,dev,test]. * * @author Bill McDowell * */ public class SplitCOWData { private static Storage<?, Document> storage; private static MIDProperties properties; private static MIDDataTools dataTools; @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { dataTools = new MIDDataTools(); properties = new MIDProperties(); storage = (Storage<?, Document>)dataTools.getStoredItemSetManager().getStorage("MIDBson"); DocumentSetInMemoryLazy<DocumentNLP, DocumentNLPMutable> documents = new DocumentSetInMemoryLazy<>(dataTools.getStoredItemSetManager().getItemSet(storage.getName(), properties.getMID4NarrativeDocumentCollectionName())); List<StoredItemSetInMemoryLazy<DocumentNLP, DocumentNLPMutable>> parts = documents.makePartition(new double[] {.8, .1, .1}, new Random(1)); if (storage.hasCollection(properties.getMID4NarrativeDocumentCollectionName() + "_train")) storage.deleteCollection(properties.getMID4NarrativeDocumentCollectionName() + "_train"); if (storage.hasCollection(properties.getMID4NarrativeDocumentCollectionName() + "_dev")) storage.deleteCollection(properties.getMID4NarrativeDocumentCollectionName() + "_dev"); if (storage.hasCollection(properties.getMID4NarrativeDocumentCollectionName() + "_test")) storage.deleteCollection(properties.getMID4NarrativeDocumentCollectionName() + "_test"); StoredCollection<DocumentNLPMutable, Document> trainDocuments = (StoredCollection<DocumentNLPMutable, Document>)storage.createCollection(properties.getMID4NarrativeDocumentCollectionName() + "_train", new SerializerDocumentNLPBSON(dataTools)); StoredCollection<DocumentNLPMutable, Document> devDocuments = (StoredCollection<DocumentNLPMutable, Document>)storage.createCollection(properties.getMID4NarrativeDocumentCollectionName() + "_dev", new SerializerDocumentNLPBSON(dataTools)); StoredCollection<DocumentNLPMutable, Document> testDocuments = (StoredCollection<DocumentNLPMutable, Document>)storage.createCollection(properties.getMID4NarrativeDocumentCollectionName() + "_test", new SerializerDocumentNLPBSON(dataTools)); for (DocumentNLP document : parts.get(0)) trainDocuments.addItem((DocumentNLPMutable)document); for (DocumentNLP document : parts.get(1)) devDocuments.addItem((DocumentNLPMutable)document); for (DocumentNLP document : parts.get(2)) testDocuments.addItem((DocumentNLPMutable)document); } }
Java
UTF-8
276
1.992188
2
[]
no_license
package io.slack.blockchain.services.processing.exceptions; public class MissingDialogSubmissionException extends ProcessingException { private static final long serialVersionUID = 1L; public MissingDialogSubmissionException(final String message) { super(message); } }
Python
UTF-8
576
3.296875
3
[]
no_license
from collections import Counter from typing import List, Any def all_the_same(elements: List[Any]) -> bool: try: text = sorted(elements) count = Counter(text).most_common(len(elements)) if len(count) > 1: return False else: return True except TypeError: return False if __name__ == '__main__': assert all_the_same([1, 1, 1]) == True assert all_the_same([1, 2, 1]) == False assert all_the_same(['a', 'a', 'a']) == True assert all_the_same([]) == True assert all_the_same([1]) == True
Java
UTF-8
1,488
1.851563
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018-2020 adorsys GmbH & Co KG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.adorsys.psd2.xs2a.service.mapper.psd2; import de.adorsys.psd2.xs2a.core.error.ErrorType; import de.adorsys.psd2.xs2a.core.mapper.ServiceType; import org.junit.jupiter.api.Test; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; class ErrorTypeTest { @Test void getByServiceTypeAndErrorCode_shouldReturnValue() { // When Optional<ErrorType> errorType = ErrorType.getByServiceTypeAndErrorCode(ServiceType.AIS, 400); // Then assertTrue(errorType.isPresent()); assertEquals(ErrorType.AIS_400, errorType.get()); } @Test void getByServiceTypeAndErrorCode_withNotExistingCode_shouldReturnEmpty() { // When Optional<ErrorType> errorType = ErrorType.getByServiceTypeAndErrorCode(ServiceType.PIS, 423); // Then assertFalse(errorType.isPresent()); } }
Markdown
UTF-8
866
2.625
3
[]
no_license
# IPAdressingCSharp This repository demonstrates: - some experiments with different data structures to store IP addresses (`uint`, `byte[]`, `string`) - there is some *low-level byte-mangling* going on for the real nerds ;-) - shows how to use the dotnet `IPAddress`-class : `System.Net.IPAddress` - this makes (I-want-to-code-something-with-IP-addresses-)life a bit easier - some experiments with subnet-calculation (compare with e.g. http://jodies.de/ipcalc) # HOWTO run With Visual Studio 2019: - `cd` to your projects dir - `git clone https://github.com/vbrh-immalle/IPAddressingCSharp` - `cd IPAddressingCSharp` - Open `.sln`-file in Visual Studio 2019 From the command line (with `dotnet`-CLI-tools installed): - `cd` to your projects dir - `git clone https://github.com/vbrh-immalle/IPAddressingCSharp` - `cd IPAddressingCSharp` - `dotnet run`
Python
UTF-8
702
3.140625
3
[ "MIT" ]
permissive
class Country: # Complete the code for the initializer. The Country class has five private # properties: __countryName, __pop2007, __pop2008, __pop2009, __pop2010. # Note: Country names can stay as strings, but population data should be cast # to float! def __init__(self,line): # Complete the code for the getCountryName getter. def getCountryName(self): # Complete the code for the getPop2007 getter. def getPop2007(self): # Complete the code for the getPop2008 getter. def getPop2008(self): # Complete the code for the getPop2009 getter. def getPop2009(self): # Complete the code for the getPop2010 getter. def getPop2010(self):
Python
UTF-8
991
3.0625
3
[]
no_license
import pygame class Settings(): def __init__(self): self.bg_color = (0,0,0) #get information of the display winObject = pygame.display.Info() #gets height of the screen self.screen_height = winObject.current_h - int(winObject.current_h * 0.10 ) #gets width of the screen self.screen_width = winObject.current_w - int(winObject.current_w * 0.10 ) #Player Settings self.player_measure = 23.3 self.player_speed_factor = 1.2345 self.player_height = self.player_measure self.player_width = self.player_measure #Bullet settings self.bullet_color = (0, 84, 9) self.bullet_speed = 25 #Grid Ground settings self.cell_measure = 19.5 self.cell_color = (255,0,0) #Monster Prototype self.monster_color = (214, 23, 166) #Scoreboard self.board_bg_color = (0, 0, 0) self.board_font_color = (244, 244, 244)
JavaScript
UTF-8
4,617
3.328125
3
[ "MIT" ]
permissive
$('#search').on("click", function(){ //Prevents button from submitting form event.preventDefault(); //declares an empty variable to hold user input var word = ""; //catches user input, trims white space on ends, and makes it all lower case word = ($('#input').val().trim()).toLowerCase(); //all this does is clear the text form after the search button is activated. //it sets the value of the html element with id #input to an empty string $('#input').val(''); //URL to be passed to the API for request. Notice how word is dinamically inserted into //URL var queryURL = 'https://fathomless-plains-61908.herokuapp.com/dictionary/entries/en/' + "" + word + "" ; //This is where our AJAX call begins $.ajax({ url: queryURL, method: "GET" }).done(function(response){ console.log(response); console.log("Will use this to check whether there are examples sentences available or not: "); console.log(Object.keys(response.results[0].lexicalEntries[0].entries[0].senses[0])); // console.log("# OF LEXICAL ENTRIES: " + (response.results[0].lexicalEntries).length + "... meaning, there's more than one word type."); // console.log("lexicalEntries[i] > entries[i] > senses[i]: "+(response.results[0].lexicalEntries[0].entries[0].senses).length + "... meaning we have 5 available definitions"); //this conditional structure helps us determine whether the word is available //in more than one type... that is, adjective, noun, or verb. //if the words is only available in one form, we do one thing. but if it is //available in more than one type, we do something else... if ((response.results[0].lexicalEntries).length > 1){ //there is more than one lexical entry var numOfDefinitions = (response.results[0].lexicalEntries[0].entries[0].senses).length; var numOfLexicalEntries = (response.results[0].lexicalEntries).length; var $title = '<h2>' + word + ' ' + '<span class="glyphicon glyphicon-volume-up glyphstyle" aria-hidden="true" id="speak"></span>' + '</h2>'; //empties the #word-info container $('#word-info').empty(); $('#word-definition').html($title); $('#speak').on("click", function(){ responsiveVoice.speak(word, "US English Female"); }); //this loop, in essence, is used to grab and display information about the word //that was searched, such as wordType, and multiple possible definitions. for (var i = 0; i < numOfLexicalEntries; i++) { var wordType = (response.results[0].lexicalEntries[i].lexicalCategory).toLowerCase(); var $type = '<h4>' + wordType + '</h4>'; $('#word-definition').append($type); for (var ii = 0; ii < numOfDefinitions; ii++) { var $definition = '<strong>' + (ii+1) + '</strong>' + " " + response.results[0].lexicalEntries[0].entries[0].senses[ii].definitions[0]; $('#word-definition').append($definition); //here we're storing the contents of the senses array to check whether or not there is an 'examples' key var senses = Object.keys(response.results[0].lexicalEntries[0].entries[0].senses[ii]); //if there are examples sentences... display them if(senses.indexOf("examples")){ // console.log("there are example sentences"); var exampleSentence = response.results[0].lexicalEntries[0].entries[0].senses[ii].examples[0].text; $('#word-definition').append(": " + "<i>"+ exampleSentence + "</i>" + "." + "<br />" + "<br />"); } else{ //nothing } }; }; }else{ //there is only one lexical entry var definition = response.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0]; var wordType = (response.results[0].lexicalEntries[0].lexicalCategory).toLowerCase(); var exampleSentence = response.results[0].lexicalEntries[0].entries[0].senses[0].examples[0].text; //this looks horrible to the eye. var $wordInfo = '<h2>' + word + ' ' + '<span class="glyphicon glyphicon-volume-up glyphstyle" aria-hidden="true" id="speak"></span>' + "</h2>" + '<h4>' + wordType + '</h4>'; //when we placed the click event here, it didn't work. WHYYYYY $('#word-info').empty(); $('#word-info').html($wordInfo); $('#word-definition').html(definition); $('#word-definition').append(": " + "<i>"+ exampleSentence + "</i>" + "."); $('#speak').on("click", function(){ console.log("inside click event"); responsiveVoice.speak(word, "US English Female"); }); }; }); });
C++
UTF-8
1,975
2.8125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; const int N = 1e5; int father[N]; int sz[N]; // 以此节点为根节点的节点数量 // 并查集基本操作 void init(int n) { for (int i = 0; i < n; i++) { father[i] = i; sz[i] = 1; } } int find(int x) { return x == father[x] ? x : father[x] = find(father[x]); } void join(int u, int v) { int u = find(u); int v = find(v); if (u == v) return; father[v] = u; sz[u] += sz[v]; } int size(int x) { return sz[find(x)]; } vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) { int R = grid.size(); int C = grid[0].size(); // R * C 是记录以天花板节点为根节点的节点数量的节点 init(R*C+1); vector<vector<int>> gst(grid); for (int i = 0; i < hits.size(); i++) { gst[hits[i][0]][hits[i][1]] = 0; } for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (gst[i][j] == 1) { if (i == 0) join(i * C + j, R*C); if (i > 0 && gst[i-1][j] == 1) join((i-1)*C + j, i * C + j); if (j > 0 && gst[i][j-1] == 1) join(i * C + j - 1, i * C + j); } } } // 逆序求出敲除砖块前后天花板联通节点的差值 vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector<int> ret(hits.size(), 0); for (int i = hits.size() - 1; i >= 0; i--) { int r = hits[i][0], c = hits[i][1]; if (grid[r][c] == 0) continue; int prev = size(R * C); if (r == 0) join(R * C, c); for (auto d : directions) { int nr = r + d[0], nc = c + d[1]; if (nr >= 0 && nr < R && nc >= 0 && nc < C) { if (gst[nr][nc] == 1) join(nr * C + nc, r * C + c); } } int count = size(R * C); ret[i] = max(0, count - prev - 1); gst[r][c] = 1; } return ret; }
C++
UTF-8
515
2.8125
3
[]
no_license
#include<iostream> #include<cstdio> #include<map> using namespace std; int main() { map<int,int> m; map<int,int>::iterator p; int n,temp; cin >> n; for(int i = 0; i < n; i ++) { scanf("%d",&temp); p = m.find(temp); if(p == m.end()) m[temp] = 1; else p->second ++; } int max = m.begin()->first,maxtime = m.begin()->second; for(p = m.begin(); p != m.end(); p ++) if(p->second > maxtime) { maxtime = p->second; max = p->first; } cout<<max<<endl; //system("pause"); }
Markdown
UTF-8
3,357
4.28125
4
[]
no_license
# Practical-Sheet-04 - Encapsulation ### Q-01 Create a class called “Employee” which has 3 private variables (empID, empName, empDesignation) and create getters and setters for each field. Please note that this has no main method since this is just an added class to the console application. Inside the main class take user inputs for employee id , employee name. employee designation and pass values to added class and set values. From getters return relevant values and print the following message from main method.<br/> “Hello – ```Employee name``` – Your Employee ID is – ```EMPID```—and You are a – ```EmpDesignation``` --. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Q2 { class Program { static void Main(string[] args) { Console.WriteLine("Enter your ID:"); int id = int.Parse(Console.ReadLine()); Console.WriteLine("Enter your Name:"); string name = Console.ReadLine(); Console.WriteLine("Enter your Designation:"); string designation = Console.ReadLine(); encap en = new encap(); en.setempid(id); en.setempname(name); en.setempdesignation(designation); Console.WriteLine("Hello " + en.getempname() + " ,Your employee ID is " + en.getempid() + " , And you are a " + en.getempdesignation()); Console.ReadLine(); } } } ``` ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Q2 { class encap { private int EmpID; private string EmpName; private string EmpDesignation; public void setempid(int id) { EmpID = id; } public int getempid() { return EmpID; } public void setempname(string name) { EmpName = name; } public string getempname() { return EmpName; } public void setempdesignation(string designation) { EmpDesignation = designation; } public string getempdesignation() { return EmpDesignation; } } } ``` ### Q-02 Create a Console application program which contain an encapsulation class for four basic arithmetic operations. Inside the encapsulation class you should have two private variables and getters and setters for basic arithmetic operations. Then return answers for summation, subtraction, multiplication and division and print them on main method. ### Q-03 Create a Console application with two classes (Main class + another class).<br/> Inside the main class take a user input which is the size of the array.<br/> Pass the user inserted size as a parameter to the added class method.<br/> Inside the method create an integer array based on passed value from main method.<br/> Then take user inputs for the created array inside the separate class.<br/> Every user input value should be followed by value 0 inside the array.<br/> Eg Assume array size is 9 and it should as follows<br/> ```U.Input 0``` ```U.Input 0``` ```U.Input 0``` ```U.Input 0``` ```U.Input```<br/> Now print all the values inside the array.
Python
UTF-8
2,393
3.4375
3
[ "Apache-2.0" ]
permissive
import os import sys import nltk from nltk.stem.snowball import EnglishStemmer from nltk.corpus import stopwords import pprint #Based on: http://tech.swamps.io/simple-inverted-index-using-nltk/ class Index: """ Inverted index datastructure """ def __init__(self, tokenizer, stemmer=None, stopwords=None): """ tokenizer -- NLTK compatible tokenizer function stemmer -- NLTK compatible stemmer stopwords -- list of ignored words """ self.tokenizer = tokenizer self.stemmer = stemmer self.index = dict() self.documents = {} if not stopwords: self.stopwords = set() else: self.stopwords = set(stopwords) def lookup(self, text): """ Lookup a text in the index """ to_ret = dict() for word in self.tokenizer(text): word = word.lower() if self.stemmer: word = self.stemmer.stem(word) if word in self.stopwords: print "- Ignore word: %s" % word continue print "+ Search word: %s" % word to_ret.update({id:self.documents.get(id, None) for id in self.index.get(word, list())}) return to_ret def add(self, document_id, document): """ Add a document string to the index """ for token in self.tokenizer(document): token = token.lower() if token in self.stopwords: continue if self.stemmer: token = self.stemmer.stem(token) if document_id not in self.index.get(token, list()): if not self.index.has_key(token): self.index[token] = list() self.index[token].append(document_id) self.documents[document_id] = document #Create invertex index index = Index(nltk.word_tokenize, EnglishStemmer(), nltk.corpus.stopwords.words('english')) #Add documents for id in os.listdir('tweets'): filename = 'tweets/%s' % id content = open(filename, 'rt').read() index.add(id, content) #Search! search_str = " ".join(sys.argv[1:]) print "Searching \"%s\"" % search_str results = index.lookup(search_str) #Prettify to print, please pp = pprint.PrettyPrinter(indent=2) pp.pprint(results)
Python
UTF-8
1,704
2.515625
3
[]
no_license
""" Expose the memfd create method. """ import sys import os import mmap import socket import struct import time import ctypes import fcntl import platform machine = platform.machine() __NR_memfd_create = 356 if machine == 'x86_64': __NR_memfd_create = 319 elif machine == '__i386__': __NR_memfd_create = 356 elif machine == 'armv7l': __NR_memfd_create = 385 MFD_CLOEXEC = 0x0001 MFD_ALLOW_SEALING = 0x0002 F_LINUX_SPECIFIC_BASE = 1024 F_ADD_SEALS = F_LINUX_SPECIFIC_BASE + 9 F_GET_SEALS = F_LINUX_SPECIFIC_BASE + 10 F_SEAL_SEAL = 0x0001 # prevent further seals from being set F_SEAL_SHRINK = 0x0002 # prevent file from shrinking F_SEAL_GROW = 0x0004 # prevent file from growing F_SEAL_WRITE = 0x0008 # prevent writes syscall = ctypes.CDLL(None).syscall def memfd_create(name, flags): " call memfd create with the given name and flags " if isinstance(name, str): name = name.encode("ascii") # int memfd_create(const char *name, unsigned int flags) fd = syscall(385, name, flags) if fd == -1: raise OSError('memfd_create') return fd def new_memfd_region(msg_bytes, name="memfd_handle", region_size=1024): " create an memfd handle for the given message and seal it " fd = memfd_create(name, MFD_ALLOW_SEALING) os.truncate(fd, region_size) fcntl.fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK) shm = mmap.mmap(fd, region_size, flags=mmap.MAP_SHARED, prot=(mmap.MAP_SHARED | mmap.PROT_WRITE)) shm[:len(msg_bytes)] = msg_bytes shm.close() # seal memfd from further changs fcntl.fcntl(fd, F_ADD_SEALS, F_SEAL_WRITE) fcntl.fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL); return fd
Java
UTF-8
1,196
2.375
2
[]
no_license
package lk.ac.mrt.cse.dbs.simpleexpensemanager.data.impl; import android.content.Context; import java.util.Date; import java.util.List; import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.TransactionDAO; import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.model.DatabaseHelper; import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.model.ExpenseType; import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.model.Transaction; public class PersistentTransactionDAO implements TransactionDAO { private DatabaseHelper dbHelper; public PersistentTransactionDAO(Context context){ dbHelper = new DatabaseHelper(context); } @Override public void logTransaction(Date date, String accountNo, ExpenseType expenseType, double amount) { Transaction transaction = new Transaction(date,accountNo,expenseType,amount); if(accountNo != null){ dbHelper.logTransaction(transaction); } } @Override public List<Transaction> getAllTransactionLogs() { return dbHelper.getTransactions(); } @Override public List<Transaction> getPaginatedTransactionLogs(int limit) { return dbHelper.getTransactions(limit); } }
C
UTF-8
335
3.40625
3
[]
no_license
#include <stdio.h> int get_flag(const char *str) { if (str[0] == 'z') { puts(str); return 0; } else { puts("no"); return 1; } } int main(int argc, char **argv) { int ret; if (argc != 2) { printf("usage: %s <flag>\n", argv[0]); return 1; } ret = get_flag(argv[1]); printf("ret value: %d\n", ret); return 0; }
Java
UTF-8
558
2.21875
2
[]
no_license
package com.future.function.common.exception; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.Collections; import java.util.Set; @SuppressWarnings("squid:MaximumInheritanceDepth") public class BadRequestException extends ConstraintViolationException { public BadRequestException(String message) { this(message, Collections.emptySet()); } public <T> BadRequestException( String message, Set<ConstraintViolation<T>> violations ) { super(message, violations); } }
Python
UTF-8
309
3.15625
3
[]
no_license
def strings_eq2_first_last(list): count = 0 for i in list: if (len(i) >= 2) and (i[0] == i[-1]): #print(i) count +=1 return count print(strings_eq2_first_last(['aba', 'xyz', 'aa', 'x', 'bbb'])) print(strings_eq2_first_last(['x', 'xy', 'xyx', 'xx', '']))
C++
UTF-8
3,951
2.53125
3
[]
no_license
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class P8XCoinChangeAnother { public: vector <long long> solve(int n, long long s, long long c) { vector<long long> ret(n, 0); vector<long long> empty_set; for (int i=0; i<n-1; i++) { ret[i]+=(s&1); c -= (s&1); if (c < 0) return empty_set; s >>= 1; if (s < c) { long long x = c - s; ret[i] += x+x; s -= x; c -= x+x; if (c<0) return empty_set; } } if (s!=c) return empty_set; ret[n-1] = c; return ret; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof bool KawigiEdit_RunTest(int testNum, int p0, long long p1, long long p2, bool hasAnswer, vector <long long> p3) { cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2; cout << "]" << endl; P8XCoinChangeAnother *obj; vector <long long> answer; obj = new P8XCoinChangeAnother(); clock_t startTime = clock(); answer = obj->solve(p0, p1, p2); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(p3.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << p3[i]; } cout << "}" << endl; } cout << "Your answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(answer.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << answer[i]; } cout << "}" << endl; if (hasAnswer) { if (answer.size() != p3.size()) { res = false; } else { for (int i = 0; int(answer.size()) > i; ++i) { if (answer[i] != p3[i]) { res = false; } } } } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; int p0; long long p1; long long p2; vector <long long> p3; { // ----- test 0 ----- p0 = 2; p1 = 4ll; p2 = 3ll; long long t3[] = {2ll,1ll}; p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0])); all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right; // ------------------ } { // ----- test 1 ----- p0 = 3; p1 = 6ll; p2 = 3ll; long long t3[] = {0ll,3ll,0ll}; p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0])); all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right; // ------------------ } { // ----- test 2 ----- p0 = 2; p1 = 8ll; p2 = 1ll; p3.clear() /*{}*/; all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right; // ------------------ } { // ----- test 3 ----- p0 = 1; p1 = 10000000000ll; p2 = 10000000000ll; long long t3[] = {10000000000ll}; p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0])); all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING
Java
UTF-8
71
1.5
2
[]
no_license
package Traitements; public enum TypeSVC { LancementES,FinPrgm; }
Java
UTF-8
263
1.6875
2
[]
no_license
package com.example.cuni.service; import java.util.Map; import com.example.cuni.dto.Member; public interface MemberService { Map<String, Object> join(Map<String, Object> param); Member getMemberByLoginId(String loginId); Member getMemberById(int id); }
Markdown
UTF-8
8,124
3.125
3
[ "MIT" ]
permissive
--- layout: post title: "밑바닥부터 시작하는 딥러닝3 - STEP 18" date: 2021-01-17 12:15:15 author: Hoon categories: 딥러닝 --- ---- #### 필요 없는 미분값 삭제 기존의 DeZero에서는 모든 변수가 미분값을 변수에 저장해두고 있다. ~~~python x0 = Variable(np.array(1.0)) x1 = Variable(np.array(1.0)) t = add(x0, x1) y = add(x0, t) y.backward() print(y.grad, t.grad) print(x0.grad, x1.grad) ~~~ 실행 결과 ~~~python 1.0 1.0 2.0 1.0 ~~~ 대부분의 경우 역전파로 구하고 싶은 미분값은 `x0`, `x1` 둘뿐일 것이지만 기존 코드의 경우 모든 변수가 미분 결과를 메모리에 유지한다. 위의 예시에서는 `y`와 `t` 같은 중간 변수의 미분값은 필요하지 않으므로 이를 고려한 코드는 다음과 같다. ~~~python class Variable: .... def backward(self, retain_grad=False): if self.grad is None: self.grad = np.ones_like(self.data) funcs = [] seen_set = set() def add_func(f): if f not in seen_set: funcs.append(f) seen_set.add(f) funcs.sort(key=lambda x: x.generation) add_func(self.creator) while funcs: f = funcs.pop() gys = [output().grad for output in f.outputs] # output is weakref gxs = f.backward(*gys) if not isinstance(gxs, tuple): gxs = (gxs,) for x, gx in zip(f.inputs, gxs): if x.grad is None: x.grad = gx else: x.grad = x.grad + gx if x.creator is not None: add_func(x.creator) if not retain_grad: for y in f.outputs: y.grad = None ~~~ `retain_grad` 를 메서드 인자로 추가함으로 말단 변수 외에는 미분값을 유지하지 않도록 한다. ~~~python x0 = Variable(np.array(1.0)) x1 = Variable(np.array(1.0)) t = add(x0, x1) y = add(x0, t) y.backward() print(y.grad, t.grad) print(x0.grad, x1.grad) ~~~ 실행 결과 ~~~python None None 2.0 1.0 ~~~ 이제 중간 변수인 `y` 와 `t` 의 미분값이 삭제되어 그만큼의 메모리를 다른 용도로 사용할 수 있게 되었다. ---- #### Function 클래스 복습 DeZero에서 미분을 하러면 순전파를 수행한 뒤 역전파를 해주어야 하고 이를 위해 역전파 시 필요한 순전파의 계산 결괏값을 저장해둔다. ~~~python class Function: def __call__(self, *inputs): xs = [x.data for x in inputs] ys = self.forward(*xs) if not isinstance(ys, tuple): # 튜플이 아닌 경우 추가 지원 ys = (ys,) outputs = [Variable(as_array(y)) for y in ys] self.generation = max([x.generation for x in inputs]) for output in outputs: output.set_creator(self) self.inputs = inputs self.outputs = [weakref.ref(output) for output in outputs] return outputs if len(outputs) > 1 else outputs[0] ~~~ 위 코드에서 `self.inputs = inputs` 부분이 결괏값을 저장해두는 역할을 한다. 입력을 `inputs` 라는 인스턴스 변수로 참조하는 변수의 카운트가 1만큼 증가하고, `__call__` 메서드를 벗어난 뒤에도 메모리에 남게 된다. 역전파하는 경우라면 참조할 변수들을 `inputs` 에 미리 보관해둬야 하지만 떄로 미분값이 필요 없는 경우도 있다. 이 경우 중간 계산 결과를 저장할 필요가 없다. ---- #### Config 클래스를 활용한 모드 전환 순전파만 할 경우를 위한 개선을 추가하기 위해 역전파 활성 모드와 역전파 비활성 모드를 전환하는 구조가 필요하다. ~~~python class Config: enable_backprop = True ~~~ 불리언 타입인 `enable_backprop` 을 이용해 역전파 가능 여부를 결정하였다. 설정 데이터는 한곳에만 존재하는 것이 좋기 때문에 인스턴스화하지 않고 클래스 상태로 이용하도록 하였다. ~~~python class Function: def __call__(self, *inputs): xs = [x.data for x in inputs] ys = self.forward(*xs) if not isinstance(ys, tuple): ys = (ys,) outputs = [Variable(as_array(y)) for y in ys] if Config.enable_backprop: self.generation = max([x.generation for x in inputs]) for output in outputs: output.set_creator(self) self.inputs = inputs self.outputs = [weakref.ref(output) for output in outputs] return outputs if len(outputs) > 1 else outputs[0] ~~~ `Config.enable_backprop` 이 `True` 인 경우에만 역전파 코드가 실행되도록 기존 코드를 수정하였다. ---- #### 모드 전환 ~~~python Config.enable_backprop = True x = Variable(np.ones((100, 100, 100))) y = square(square(square(x))) y.backward() Config.enable_backprop = False x = Variable(np.ones((100, 100, 100))) y = square(square(square(x))) ~~~ 크기가 큰 다차원 배열인 형상이 (100, 100, 100)인 텐서를 이용해 실습하였다. `square` 함수를 세 번 적용(원소별 제곱)하면 `Config.enable_backprop = True` 인 경우는 중간 계산 결과가 계속 유지되어 그만큼 메모리를 차지하게 된다. 반면 `Config.enable_backprop = False` 인 경우 중간 계산 결과는 사용 직후 메모리에서 삭제 된다. ---- #### with 문을 활용한 모드 전환 파이썬에서는 후처리를 자동으로 수행하고자 할 때 `with` 구문을 사용할 수 있다. 만약 이를 사용하지 않고 파일에 무언가를 작성하려면 다음과 같이 `open` 과 `close` 를 이용해야 한다. ~~~python f = open('sample.txt', 'w') f.write('hellow world!') f.close() ~~~ 간혹 실수로 `close()` 를 까먹을수도 있고 매번 사용하기도 귀찮을수 있다. 하지만 `with` 를 사용하면 다음과 같이 코드를 수정할 수 있다. ~~~python with open('sample.txt', 'w') as f: f.write('hello world!') ~~~ 위의 코드에서는 `with` 블록에 들어갈 때 파일이 열리고 빠져나옴과 동시에 자동으로 닫힌다. 이와 같은 원리를 이용해 역전파 비활성 모드 전환을 수정하려고 한다. ~~~python with using_config('enable_backprop', False): x = Variable(np.array(2.0)) y = Square(x) ~~~ 아직 `using_config` 함수를 구현한 것이 아니기 때문에 위의 코드가 정상적으로 실행 되지는 않는다. 예시로 `contextlib` 모듈을 이용해 `with` 문을 사용한 모드 전환을 구현하면 다음과 같다. ~~~python import contextlib @contextlib.contextmanager def config_test(): print('start') # 전처리 try: yield finally: print('done') # 후처리 with config_test(): print('process') ~~~ 실행 결과 ~~~python start process done ~~~ `@contextlib.contextmanager` 데코레이터를 달면 문맥을 판단하는 함수가 만들어진다. 이 함수 내부에서 `yield` 전에는 전처리 로직을, `yield` 다음에는 후처리 로직을 작성한다. 후에 `with` 를 이용하면 블록안으로 들어갈 때 전처리가 실행되고 빠져나올 때 자동으로 후처리가 실행된다. 이를 이용해 `using_config` 를 다음과 같이 구현할 수 있다. ~~~python import contextlib @contextlib.contextmanager def using_config(name, value): old_value = getattr(Config, name) setattr(Config, name, value) try: yield finally: setattr(Config, name, old_value) ~~~ ~~~python with using_config('enable_backprop', False): x = Variable(np.array(2.0)) y = square(x) ~~~ 이와 같이 역전파가 필요없는 경우에는 `with` 블록을 이용해 순전파 코드만 실행하도록 하였다. 매번 `with using_config('enable_backprop', False):` 를 작성하기 귀찮기 때문에 코드를 간소화 하기 위해 마지막으로 다음과 같은 수정을 하였다. ~~~python def no_grad(): return using_config('enable_backprop', False): ~~~ ---- **출처:\- 사이토 고키, **『**밑바닥부터 시작하는 딥러닝3**』, 개앞맵시, 한빛미디어(2020)
Java
UTF-8
1,603
2.75
3
[]
no_license
package com.intsmaze.redis.model; import java.util.ArrayList; import java.util.List; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; public class ShardedJedisPoolDemo { public static void main(String[] args){ List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); shards.add(new JedisShardInfo("192.168.19.131", "8003")); shards.add(new JedisShardInfo("192.168.19.131", "8005")); // shards.add(new JedisShardInfo("192.168.19.131", "Redis001", 8003, 20 * 1000, 1)); // shards.add(new JedisShardInfo("192.168.19.131", "Redis002", 8004, 20 * 1000, 2)); JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(10); config.setMaxTotal(30); config.setMaxWaitMillis(3*1000); ShardedJedisPool shardedJedisPool = new ShardedJedisPool(config, shards); for (int i = 0; i < 10; i++) { ShardedJedis shardedJedis = shardedJedisPool.getResource();//发现Sharded的构造方法其实是在我们 jedisPool.getResource() 时就完成的,每次jedisPool.getResource() 都会初始化一次,所以通过这个功能完成了动态上下节点功能啪啪啪· String key = "shard" + i; shardedJedis.set(key, "v-" + i); System.out.println(shardedJedis.get(key)); JedisShardInfo shardInfo = shardedJedis.getShardInfo(key); System.out.println("getHost:" + shardInfo.getHost()); shardedJedis.close(); } shardedJedisPool.close(); shardedJedisPool.destroy(); } }
Java
UTF-8
398
1.625
2
[]
no_license
/** * generated by Xtext 2.21.0 */ package dk.chcla15.mathinterpreter.mathAssignmentLanguage; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Mult</b></em>'. * <!-- end-user-doc --> * * * @see dk.chcla15.mathinterpreter.mathAssignmentLanguage.MathAssignmentLanguagePackage#getMult() * @model * @generated */ public interface Mult extends ExpOp { } // Mult
PHP
UTF-8
1,882
2.703125
3
[ "MIT" ]
permissive
<?php /** * This file is part of the ImboClientCli package * * (c) Christer Edvartsen <cogo@starzinger.net> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace ImboClientCliTest; use ImboClientCli\Application, ImboClientCli\Version, Symfony\Component\Console\Tester\ApplicationTester; /** * @package Test suite * @author Christer Edvartsen <cogo@starzinger.net> * @covers ImboClientCli\Application */ class ApplicationTest extends \PHPUnit_Framework_TestCase { /** * @var ApplicationTester */ private $application; /** * Set up the application */ public function setUp() { $imboClientCli = new Application(); $imboClientCli->setAutoExit(false); $this->application = new ApplicationTester($imboClientCli); } /** * Tear down the application */ public function tearDown() { $this->application = null; } public function testDisplaysCorrectVersion() { $this->application->run(array()); $display = $this->application->getDisplay(); $this->assertContains('ImboClientCli version ' . Version::VERSION, $display); } public function testListsTheAddedCommands() { $this->application->run(array()); $display = $this->application->getDisplay(); foreach (array( 'activate Activate an imbo server', 'add-images Add one or more images to an Imbo server', 'deactivate Deactivate an imbo server', 'delete-image Delete an image from imbo', 'list-servers List configured servers', 'num-images Get the number of images on an imbo server', 'server-status Check server status', ) as $command) { $this->assertContains($command, $display); } } }
Markdown
UTF-8
4,389
3.015625
3
[]
no_license
# FakeView English Document. 顾名思义,假的View。 开发Android应用时,特别是开发一个通用列表时,列表中基本只使用ImageView和TextView,且不会使用其中很多功能。 FakeView就是为了提取出日常使用较多,且容易造成layout层级过多或过度绘制而导致页面卡顿(主要是滑动卡顿)的View,经过处理后,合并层级,减少过度绘制。 附带减少view层级的[工具](Tools.MD) 新增[NewText](NewText.MD)强力推荐 ## 原理 FakeView提取出在屏幕绘制一个控件最基本的动作:创建-计算-布局-绘制,并将其封装为FView和FViewGroup,分别模拟View和ViewGroup;提取出根调度器FViewRootImpl(View子类)模拟ViewRootImpl,调度"计算"、"布局"、"绘制"等动作,并将所有FView加进FViewRootImpl,实现合并图层,减少过度绘制。 ## 使用方法 gradle: ``` compile "xfy.fakeview.library:fview:0.73" ``` 直接生成FView: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); container = (ViewGroup) findViewById(R.id.container); container.addView(buildFView()); } private View buildFView() { FViewCreater creater = new FViewCreater(this); FFrameLayout layout = creater.buildRootFView(FFrameLayout.class); layout.setFLayoutParams(newMatchParentParams()); layout.setId(1); layout.setOnClickListener(this); layout.setOnLongClickListener(this); final FImageView imageView = creater.newFView(FImageView.class); imageView.setPadding(10, 10, 10, 10); imageView.setImageResource(R.drawable.me); imageView.setOnClickListener(this); imageView.setOnLongClickListener(this); imageView.setId(2); imageView.setBackgroundColor(Color.BLACK); layout.addView(imageView, new FFrameLayout.LayoutParams(IFViewGroup.FLayoutParams.WRAP_CONTENT, IFViewGroup.FLayoutParams.WRAP_CONTENT, Gravity.CENTER)); final FTextView textView = creater.newFView(FTextView.class); textView.setPadding(10, 10, 10, 10); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15); textView.setTextColor(Color.RED); textView.setBackgroundColor(Color.YELLOW); textView.setText(SpannableTextUtils.getColorableText("哈哈哈哈哈哈哈哈哈", new int[] {0, 2}, new int[]{1, 4}, new int[]{Color.BLACK, Color.BLUE})); layout.addView(textView, new FFrameLayout.LayoutParams(IFViewGroup.FLayoutParams.WRAP_CONTENT, IFViewGroup.FLayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER) .setMargins(0, 0, 0, 20)); View root = creater.build(); root.setLayoutParams(FViewCreater.newMatchParentLayoutParams()); return root; } //implement IFView.OnClickListener @Override public void onClick(IFView view) { switch (view.getId()) { case 1: Toast.makeText(this, "container click", Toast.LENGTH_LONG).show(); break; case 2: startActivity(new Intent(this, TestTranslateActivity.class)); break; } } ``` 将已有layout翻译为FView: ``` TranslatorManager translatorManager = new TranslatorManager(this); final ViewGroup container = (ViewGroup) findViewById(R.id.container); final IFViewRoot root = translatorManager.translateView(container); if(root != null) Log.d(tag, "translate success"); ``` 如果有点击或长按事件,需要在翻译前设置事件: ``` private OnClickListener onClickListener = new OnClickListener(this);//this -> OnClickListener.Trans private OnLongClickListener onLongClickListener = new OnLongClickListener(this);//this -> OnLongClickListener.Trans //implement OnClickListener.Trans @Override public void onClick(IView view) { if (view == null) { showToast("null view"); } switch (view.getId()) { case R.id.xxxx: break } } private void initEvent() { findViewById(R.id.xxxx).setOnClickListener(onClickListener); findViewById(R.id.xxxx).setOnLongClickListener(onLongClickListener); } ``` 如需调试,可设置`DebugInfo.setDebug(true);` ## 最后 迎提出意见及建议。 email: s18810577589@sina.com
Java
UTF-8
364
2.734375
3
[]
no_license
package uri; import java.util.*; public class MainClass { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input=new Scanner(System.in); int i,n; //m=input.nextInt(); n=input.nextInt(); for(i=1;i<=n;i++) { if(i%2==0) { int m=i*i; System.out.println(i+"^2"+" = "+m); } } } }
Python
UTF-8
443
3.015625
3
[]
no_license
""" 然而,标准库中所有执行阻塞型 I/O 操作的函数,在等待操作系统返回 结果时都会释放 GIL。这意味着在 Python 语言这个层次上可以使用多线 程,而 I/O 密集型 Python 程序能从中受益:一个 Python 线程等待网络响 应时,阻塞型 I/O 函数会释放 GIL,再运行一个线程。 因此,尽管有GIL,Python 线程还是能在 I/O 密集型应用中发挥作用。 """
Markdown
UTF-8
85,813
2.71875
3
[ "MIT" ]
permissive
# mattata mattata is a powerful, plugin-based Telegram bot similar to [topkecleon's](https://github.com/topkecleon/otouto). mattata boasts many nifty features such as a fully-fledged administration plugin, AI (native Cleverbot implementation, which utilises my [mattata-ai](https://github.com/wrxck/mattata-ai) library) and much more. ## Setup Installing & configuring mattata is very simple. Clone the repository using: ```Bash git clone https://github.com/wrxck/mattata ``` in Terminal. Then, run the following: ```Bash cd mattata/ chmod +x ./install.sh ./install.sh chmod +x ./launch.sh ``` You'll need sudo access to be able to install the dependencies required. Then, you need to fill in the values in `configuration.lua`. After you've done that, use: ```Bash ./launch.sh ``` to run your bot. ## Plugins mattata features an extensive, robust plugin system, similar to [topkecleon's](https://github.com/topkecleon/otouto). Below is a table containing a list of currently-documented plugins and their corresponding usage information. | Command | Plugin | Arguments | Description | Aliases | |---------------------------------|-----------------------|---------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------| | /administration | `administration.lua` | - | Configure the administration settings for your chat through an interactive menu sent via private message. | /antispam | | /apod | `apod.lua` | [dd/mm/yyyy] | Sends the Astronomy Picture of the Day via NASA's API. If a date is given, the Astronomy Picture for that date is returned. | - | | /appstore | `appstore.lua` | \<query\> | Displays information about the first app returned by iTunes for the given search query. | /app | | /avatar | `avatar.lua` | \<user\> [offset] | Sends the profile photos of the given user, of which can be specified by username or numerical ID. If an offset is given after the username (which must be a numerical value), then the nth profile photo is sent (if available). | - | | /base64 | `base64.lua` | \<text\> | Converts a string of text into base64-encoded text. | /b64 | | /binary | `binary.lua` | \<text\> | Converts a numerical value into binary. | /bin | | /bing | `bing.lua` | \<query\> | Searches Bing for the given search query and returns the top results. | - | | /blacklist | `administration.lua` | [user] | Prevents a user from using the bot in the chat. The user must be specified by username/ID, or by reply. | - | | /bugreport | `bugreport.lua` | \<text\> | Reports a bug to the configured developer. | /bug, /br | | /calc | `calc.lua` | \<expression\> | Solves the given mathematical expression using mathjs.org. | - | | /canitrust | `canitrust.lua` | \<url\> | Reveals any known security issues with a website. | - | | /catfact | `catfact.lua` | - | Sends a random, cat-themed fact. | - | | /cat | `cats.lua` | - | Sends a random photo of a cat. | /sarah | | /channel | `channel.lua` | \<channel\> \<message\> | Sends a message to a Telegram channel/group. The channel/group can be specified via ID or username. Messages can be formatted with Markdown. Users can only send messages to channels/groups they own and/or administrate. | /ch | | /chuck | `chuck.lua` | - | Sends a random Chuck Norris joke. | - | | /coinflip | `coinflip.lua` | [guess] | Flips a coin and returns the result! If a guess is given, the result is tested against it and reveals the accuracy accordingly. | /cf | | /copypasta | `copypasta.lua` | - | Riddles the replied-to message with cancerous emoji. | /😂 | | /currency | `currency.lua` | \<amount\> \<from\> TO \<to\> | Converts exchange rates for various currencies via Google Finance. | /convert, /cash | | /demod | `administration.lua` | [user] | Strip a user of their moderator status, revoking their ability to use administrative commands such as /ban, /kick and /unban. The user must be specified by username/ID, or by reply. | /demote | | /dice | `dice.lua` | \<number\> \<range\> | Rolls a die - returning random numbers between 1 and the given range the given number of times. | - | | /dictionary | `dictionary.lua` | \<word\> | Looks up the given word in the Oxford Dictionary and returns the relevant definition(s). | /define | | /dns | `dns.lua` | \<url\> \<record type\> | Sends the given URL's DNS records of the given type. The record types currently supported are AAAA, A, CERT, CNAME, DLV, IPSECKEY, MX, NS, PTR, SIG, SRV and TXT. | - | | /doggo | `doggo.lua` | - | Sends a random photo of a dog. | - | | /echo | `echo.lua` | \<text\> | Repeats the given string of text. | - | | /eightball | `eightball.lua` | - | Makes a decision for you using the (virtual) magic 8 ball! | /8ball | | /emoji | `emoji.lua` | \<emoji\> | Sends information about the given emoji. | - | | /facebook | `facebook.lua` | \<Facebook username\> | Sends the given Facebook user's profile picture. | /fb | | /fact | `fact.lua` | - | Returns a random (yet somewhat-untrue) fact! | - | | /flickr | `flickr.lua` | \<query\> | Searches Flickr for a photo matching the given search query and returns the most relevant result. | - | | /fortune | `fortune.lua` | - | Sends your fortune (featuring a seasonally-adjusting ASCII animal!). | - | | /game | `game.lua` | [stats] | Play a game of Tic-Tac-Toe. Use /game stats to view your current game statistics. | - | | /gif | `giphy.lua` | \<query\> | Searches GIPHY for the given search query and returns a random, relevant result. | /giphy | | /github | `github.lua` | \<GitHub username\> \<GitHub repository name\> | Returns information about the specified GitHub repository. | - | | /githubfeed | `githubfeed.lua` | \<sub \| del\> \<GitHub username\> \<GitHub repository name\> | Manage your subscriptions to updates from GitHub repositories. | /gh | | /google | `gsearch.lua` | \<query\> | Searches Google for the given search query and returns the most relevant result(s). | - | | /hackernews | `hackernews.lua` | - | Sends the top stories from Hacker News. | /hn | | /help | `help.lua` | [plugin] | A help-orientated menu is sent if no arguments are given. If arguments are given, usage information for the given plugin is sent instead. | /start | | /hexadecimal | `hexadecimal.lua` | \<text\> | Converts the given string of text into hexadecimal. | /hex | | /hextorgb | `hextorgb.lua` | \<hex code\> | Converts the given hex colour code into its RGB format. | - | | /id | `id.lua` | [chat] | Sends information about the given chat. Input is also accepted via reply. | - | | /identicon | `identicon.lua` | \<text\> | Generates an identicon from the given string of text. | - | | /imdb | `imdb.lua` | \<query\> | Searches IMDb for the given search query and returns the most relevant result(s). | - | | /instagram | `instagram.lua` | \<Instagram username\> | Sends the given Instagram user's profile picture. | /ig | | /insult | `insult.lua` | - | Generates a random insult. | - | | /isp | `isp.lua` | \<url\> | Sends information about the given URL's Internet Service Provider (ISP). | - | | /ispwned | `ispwned.lua` | \<account\> | Returns the existence of the given account in any major data leaks. | - | | /isup | `isup.lua` | \<url\> | Checks to see if the given URL is down for everyone or just you. | - | | /itunes | `itunes.lua` | \<query\> | Searches iTunes for the given search query and returns the most relevant result. | - | | /jsondump | `jsondump.lua` | - | Returns the raw JSON of your message. | - | | /kick | `kick.lua` | [user] | Bans, then unbans, a user from the chat (also known as a "soft-ban"). The user must be specified by username/ID, or by reply. | - | | /lastfm | `lastfm.lua` | [Last.fm username] | Returns what you, or the given Last.fm user, last listened to on Last.fm. | /np | | /link | `administration.lua` | - | Sends the group link. | - | | /lmgtfy | `lmgtfy.lua` | \<query\> | Sends a LMGTFY link for the given search query. | - | | /location | `location.lua` | [query] | Sends your location, or a location from Google Maps. | /loc | | /loremipsum | `loremipsum.lua` | - | Generates a paragraph of Lorem Ipsum text. | - | | /lyrics | `lyrics.lua` | \<query\> | Finds the lyrics to the given track. | - | | /me | `me.lua` | \<emote message\> | Allows you to emote, Minecraft-style. | - | | /minecraft | `minecraft.lua` | \<Minecraft username\> | Sends information about the given Minecraft user. | /mc | | /mod | `administration.lua` | [user] | Promote the given user to moderator status, allowing them use of administrative commands such as /ban, /kick and /unban. The user must be specified by username/ID, or by reply. | /promote | | /msglink | `msglink.lua` | - | Gets the link to the replied-to message. | - | | /name | `name.lua` | \<text\> | Changes the name that the bot's AI responds to. | - | | /netflix | `netflix.lua` | \<query\> | Searches Netflix for the given search query and returns the most relevant result. | /nf | | /news | `news.lua` | \<news source\> | Sends the current top story from the given news source. | - | | /ninegag | `ninegag.lua` | - | Returns a random image from the latest 9gag posts. | /9gag | | /nsources | `news.lua` | [query] | Returns a list of available sources that can be used with /news. If a query is given as a command argument, a Lua pattern match for the given query is made and a list of matching news sources is returned. | - | | /paste | `paste.lua` | \<text\> | Uploads the given text to a pasting service and returns the result URL. | - | | /pay | `pay.lua` | \<amount\> | Sends the replied-to user the given amount of mattacoins. | - | | /plugins | `plugins.lua` | - | Toggle the plugins you want to use in your chat with a slick inline keyboard, paginated and neatly formatted. | - | | /pokedex | `pokedex.lua` | \<query\> | /pokedex \<query\> - Returns a Pokedex entry from pokeapi.co. Alias: /dex. | | | /prime | `prime.lua` | \<number\> | /prime \<number\> - Tells you if a number is prime or not. | | | /pun | `pun.lua` | - | Generates a random pun. | - | | /qr | `qr.lua` | \<text\> | Converts the given string of text to a QR code. | /qrcode | | /randomword | `randomword.lua` | - | Generates a random word. | /rw | | /r/subreddit | `reddit.lua` | - | Returns the latest posts from the given subreddit. | - | | /rimg | `rimg.lua` | \<width\> [height] [-g \| -b] | Sends a random image which matches the dimensions provided, in pixels. If only 1 dimension is given, the other is assumed to be the same. Append -g to the end of your message to return a grayscale photo, or append -b to the end of your message to return a blurred photo. The maximum value for each dimension is 5000, and the minimum for each is 250. | - | | /s/\<pattern\>/\<substitution\> | `sed.lua` | - | s/\<pattern\>/\<substitution\> - Replaces all occurences, of text matching a given Lua pattern, with the given substitution. | - | | /setlang | `setlang.lua` | - | Allows you to select your language. | - | | /setloc | `setloc.lua` | \<location\> | Sets your location to the given value. | - | | /setsteam | `steam.lua` | \<text\> | Sets your Steam username to the given text | - | | /setwelcome | `administration.lua` | \<text\> | Sets the group's welcome message to the given text. Markdown formatting is supported. | - | | /shorten | `shorten.lua` | \<url\> | Shortens the given URL using one of the given URL shorteners. | - | | /shout | `shout.lua` | \<text\> | Shouts the given text in multiple directions! | - | | /slap | `slap.lua` | [target] | Slaps someone, or something. | - | | /snapchat | `snapchat.lua` | \<Snapchat username\> | Sends the "Snap" code for the given Snapchat username. | /sc | | /spotify | `spotify.lua` | \<query\> | Searches Spotify for a track matching the given search query and returns the most relevant result. | - | | /statistics | `statistics.lua` | - | Shows statistical information about the current chat's top ten users (ordered by message count). | /stats | | /steam | `steam.lua` | [username] | Displays information about the given Steam user. If no username is specified then information about your Steam account (if applicable) is sent. | - | | /synonym | `synonym.lua` | \<word\> | Sends a word similar to the word given. | - | | /time | `time.lua` | [location] | If no arguments are given; the current time, date, and timezone for your location are sent (if applicable). Otherwise, the current time, date and timezone for the given location is returned. The returned location is the first relevant result on Google Maps for the given search query. | - | | /translate | `translate.lua` | [locale] \<text\> | If a locale is given, the given text is translated into the said locale's language. If no locale is given then the given text is translated into the bot's configured language. If the command is used in reply to a message containing text, then the replied-to text is translated and the translation is returned. | /tl | | /twitch | `twitch.lua` | \<query\> | Searches Twitch for the given search query and returns the most relevant result(s). | - | | /unicode | `unicode.lua` | \<text\> | Returns the given text as a JSON-encoded table of Unicode (UTF-32) values. | - | | /urbandictionary | `urbandictionary.lua` | \<query\> | Searches the Urban Dictionary for the given search query and returns the most relevant result(s). | /urban, /ud | | /uuid | `uuid.lua` | - | Generates a random UUID. | /guid | | /weather | `weather.lua` | [location] | If no arguments are given, the weather forecast for your known location is given. If a location is given, then the weather forecast for that location is given instead. | - | | /whitelist | `administration.lua` | [user] | Allows a previously-blacklisted user to use the bot in the chat again. The user must be specified by username/ID, or by reply. | - | | /whois | `whois.lua` | \<IP address\> | Performs a WHOIS lookup for the given IP address and returns the result. | - | | /wikipedia | `wikipedia.lua` | \<query\> | Searches Wikipedia for the given search query and returns the most relevant article. | /wiki, /w | | /xkcd | `xkcd.lua` | [n | query] | Returns the latest xkcd strip and its alt text. If a number is given, returns that number strip. If 'r' is passed in place of a number, returns a random strip. Any other text passed as the command argument will search Google for a relevant strip and, if applicable, return it. | - | | /yify | `yify.lua` | \<query\> | Searches Yify Torrents for the given search query and returns the most relevant result(s). | - | | /yomama | `yomama.lua` | - | Tells a Yo' Mama joke! | - | | /youtube | `youtube.lua` | \<query\> | Searches YouTube for the given search query and returns the most relevant result(s). | /yt | Arguments enclosed in [square brackets] are optional, and arguments enclosed in <angle brackets> are required. ## Telegram API Below you will find each currently-documented method and its corresponding function and information. ### sendMessage Use this function to send text messages using Telegram's `sendMessage` method. ```Lua mattata.send_message( chat_id, text, parse_mode, disable_web_page_preview, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |-----------------------------|----------------------------------------------------------------------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | text | String | Yes | Text of the message to be sent | | parse\_mode | String | Optional | Send `Markdown` or `HTML`, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. | | disable\_web\_page\_preview | Boolean | Optional | Disables link previews for links in this message | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ### forwardMessage Use this function to forward messages of any kind using Telegram's `forwardMessage` method. ```Lua mattata.forward_message( chat_id, from_chat_id, disable_notification, message_id ) ``` | Parameters | Type | Required | Description | |-----------------------|-------------------|----------|---------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | from\_chat\_id | Integer or String | Yes | Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | message\_id | Integer | Yes | Message identifier in the chat specified in *from\_chat\_id* | ### sendPhoto Use this function to send photos using Telegram's `sendPhoto` method. ```Lua mattata.send_photo( chat_id, photo, caption, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | photo | InputFile or String | Yes | Photo to send. Pass a file\_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. | | caption | String | Optional | Photo caption (may also be used when resending photos by *file\_id*), 0-200 characters | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ### sendAudio Use this function to send audio files using Telegram's `sendAudio` method, if you want Telegram clients to display them in the music player. Your audio must be in the `.mp3` format. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. ```Lua mattata.send_audio( chat_id, audio, caption, duration, performer, title, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | audio | InputFile or String | Yes | Audio file to send. Pass a file\_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. | | caption | String | Optional | Audio caption, 0-200 characters | | duration | Integer | Optional | Duration of the audio in seconds | | performer | String | Optional | Performer | | title | String | Optional | Track name | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | | ### sendDocument Use this function to send general files using Telegram's `sendDocument` method. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. ```Lua mattata.send_document( chat_id, document, caption, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | document | InputFile or String | Yes | File to send. Pass a file\_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. | | caption | String | Optional | Document caption (may also be used when resending documents by *file\_id*), 0-200 characters | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ### sendSticker Use this function to send `.webp` stickers using Telegram's `sendSticker` method. ```Lua mattata.send_sticker( chat_id, sticker, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | sticker | InputFile or String | Yes | Sticker to send. Pass a file\_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a `.webp` file from the Internet, or upload a new one using multipart/form-data. | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ### sendVideo Use this function to send video files using Telegram's `sendVideo` method. Telegram clients support `.mp4` videos (other formats may be sent using `sendDocument`). Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. ```Lua mattata.send_video( chat_id, video, duration, width, height, caption, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | video | InputFile or String | Yes | Video to send. Pass a file\_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. | | duration | Integer | Optional | Duration of sent video in seconds | | width | Integer | Optional | Video width | | height | Integer | Optional | Video height | | caption | String | Optional | Video caption (may also be used when resending videos by *file\_id*), 0-200 characters | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ### sendVoice Use this function to send audio files using Telegram's `sendVoice` method, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an `.ogg` file encoded with `OPUS` (other formats may be sent as Audio or Document). Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. ```Lua mattata.send_voice( chat_id, voice, caption, duration, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | voice | InputFile or String | Yes | Audio file to send. Pass a file\_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. | | caption | String | Optional | Voice message caption, 0-200 characters | | duration | Integer | Optional | Duration of the voice message in seconds | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ### sendLocation Use this function to send a location on a map using Telegram's `sendLocation` method. ```Lua mattata.send_location( chat_id, latitude, longitude, disable_notification, reply_to_message_id, reply_markup ) ``` | Parameters | Type | Required | Description | |------------------------|----------------------------------------------------------------------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | chat\_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | | latitude | Float number | Yes | Latitude of location | | longitude | Float number | Yes | Longitude of location | | disable\_notification | Boolean | Optional | Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound. | | reply\_to\_message\_id | Integer | Optional | If the message is a reply, ID of the original message | | reply\_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. | ## External Usage You can use the mattata API without initialising the entire library (i.e. no plugin system etc.) by referencing the library in your code. This can be done in the following way: ```Lua local mattata = require('mattata') -- Blah, blah; your code goes here ``` Now, if you wish to make a request to the Telegram API, you need to use the `mattata.request()` function; which takes 4 parameters. Below is a table containing each parameter, the type of value it takes and a brief description of what it's for. | Parameters | Type | Required | Description | |------------|---------------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | endpoint | String | Yes | The API URL (with the token and method) which you'd like to make the request to (e.g. `https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/sendMessage`) | | parameters | Table | Yes | A key-value table of parameters and their respective values (if you're using the official Telegram bot API, check out the documented examples above) | | file | InputFile or String | Optional | A table of a single key/value pair, where the key is the name of the parameter and the value is the filename (if these are included in parameters instead, mattata will attempt to send the filename as a file ID or URL) | | timeout | Boolean | Optional | If set to true, the request will timeout after 1 second | Here's an example script which, when executed, will send the message `Hello, World!` to the chat ID `-100123456789` using the `sendMessage` method via the default API endpoint, `https://api.telegram.org/bot`, using the token `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`: ```Lua local mattata = require('mattata') -- Load the library local request, code = mattata.request( -- Make the request to the Telegram bot API 'https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/sendMessage', { ['chat_id'] = -100123456789, ['text'] = 'Hello, World!' } ) if not request then print('The Telegram bot API returned the following error: ' .. code) return false end return true ``` It is easier to make requests if you're using mattata for its intended purpose (a plugin-based bot), however it really is that easy to make a request to the bot API - in any snippet of Lua! Here's an example bot which uses long-polling to get updates, and responds to `/ping` with `PONG`: ```Lua api = require('mattata') token = '' -- Enter your token here last = last or 0 while true do local request = api.get_updates( 5, last + 1, token ) if request then for _, update in ipairs(request.result) do last = update.update_id if update.message and update.message.text and update.message.text == '/ping' then api.request( string.format( 'https://api.telegram.org/bot%s/sendMessage', token ), { ['chat_id'] = update.message.chat.id, ['text'] = 'PONG' } ) end end else print('Error') end end ``` ## Contribute As well as feedback and suggestions, you can contribute to the mattata project in the form of a monetary donation. This makes the biggest impact since it helps pay for things such as server hosting and domain registration. A donation of any sum is appreciated and, if you so wish, you can donate [here](https://paypal.me/wrxck). I'd like to take a moment to thank the following people for their donation: * j0shu4 * para949 * aRandomStranger * mochicon * xenial * fizdog * caidens
Java
UTF-8
715
2.65625
3
[]
no_license
package com.yihang; /** * @Author: yihangjou(周逸航) * @Site: www.yihang.ml * @cnBlogs: https://www.cnblogs.com/yihangjou/ * @Date: create in 2020/7/17 22:35 */ public class TestDemo { static void tune(Rodents r) { r.play(10); r.eat(); System.out.println("------------------"); } static void tuneAll(Rodents[] R) { for (Rodents r : R) { tune(r); } } public static void main(String[] args) { // TODO Auto-generated method stub Rodents[] rodents = { new Mouses(), new Gerbils(), new SmallRed(), new BigBlack() }; tuneAll(rodents); } }
C++
UTF-8
864
2.75
3
[]
no_license
// // Created by michal on 08.01.19. // #include "SocketPuller.h" #include <unistd.h> #include <cstdio> #include <sys/select.h> #include <iostream> SocketPuller::SocketPuller(int socketDescriptor): socketDescriptor(socketDescriptor) {} bool SocketPuller::canRead(){ fd_set rfds; FD_ZERO(&rfds); FD_SET(socketDescriptor, &rfds); struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; int retval = select(socketDescriptor+1, &rfds, NULL, NULL, &tv); if (retval == -1) perror("select()"); return retval != 0; } void *SocketPuller::pullBytes(size_t length) { void* buffer = new char[length]; ssize_t readBytes = read(socketDescriptor, buffer, length); if (readBytes == 0) throw EndOfBytesException(); else return buffer; } SocketPuller::~SocketPuller() { close(socketDescriptor); }
Java
UTF-8
6,841
1.789063
2
[ "Apache-2.0" ]
permissive
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.eventregistry.rest.service.api.runtime; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.flowable.eventregistry.api.EventDeployment; import org.flowable.eventregistry.rest.service.BaseSpringRestTestCase; import org.flowable.eventregistry.rest.service.api.EventRestUrls; import org.flowable.eventregistry.test.ChannelDeploymentAnnotation; import org.flowable.eventregistry.test.EventDeploymentAnnotation; import org.flowable.task.api.Task; import com.fasterxml.jackson.databind.node.ObjectNode; public class EventInstanceCollectionResourceTest extends BaseSpringRestTestCase { @Deployment(resources = { "org/flowable/eventregistry/rest/service/api/repository/boundaryEvent.bpmn20.xml" }) @EventDeploymentAnnotation(resources = { "org/flowable/eventregistry/rest/service/api/repository/simpleEvent.event" }) @ChannelDeploymentAnnotation(resources = { "org/flowable/eventregistry/rest/service/api/repository/simpleChannel.channel" }) public void testSendEvent() throws Exception { ProcessInstance processInstance = processRuntimeService.startProcessInstanceByKey("process", Collections.singletonMap("customerIdVar", "123")); Task task = processTaskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("task"); ObjectNode requestNode = objectMapper.createObjectNode(); // first send event that doesn't match process boundary event requestNode.put("eventDefinitionKey", "myEvent"); requestNode.put("channelDefinitionKey", "myChannel"); ObjectNode payloadNode = requestNode.putObject("eventPayload"); payloadNode.put("customerId", "notExisting"); payloadNode.put("productNumber", "p456"); HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + EventRestUrls.createRelativeResourceUrl(EventRestUrls.URL_EVENT_INSTANCE_COLLECTION)); httpPost.setEntity(new StringEntity(requestNode.toString())); CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_NO_CONTENT); closeResponse(response); task = processTaskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("task"); // now send event with matching correlation value requestNode.put("eventDefinitionKey", "myEvent"); payloadNode = requestNode.putObject("eventPayload"); payloadNode.put("customerId", "123"); payloadNode.put("productNumber", "p456"); httpPost = new HttpPost(SERVER_URL_PREFIX + EventRestUrls.createRelativeResourceUrl(EventRestUrls.URL_EVENT_INSTANCE_COLLECTION)); httpPost.setEntity(new StringEntity(requestNode.toString())); response = executeRequest(httpPost, HttpStatus.SC_NO_CONTENT); closeResponse(response); task = processTaskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("taskAfterBoundary"); } @Deployment(resources = { "org/flowable/eventregistry/rest/service/api/repository/boundaryEvent.bpmn20.xml" }) @EventDeploymentAnnotation(resources = { "org/flowable/eventregistry/rest/service/api/repository/simpleEvent2.event" }) @ChannelDeploymentAnnotation(resources = { "org/flowable/eventregistry/rest/service/api/repository/simpleChannel.channel" }) public void testSendEventWithMultipleEventDefinitions() throws Exception { EventDeployment deployment2 = repositoryService.createDeployment() .addClasspathResource("org/flowable/eventregistry/rest/service/api/repository/simpleEvent.event") .deploy(); ProcessInstance processInstance = processRuntimeService.startProcessInstanceByKey("process", Collections.singletonMap("customerIdVar", "123")); Task task = processTaskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("task"); ObjectNode requestNode = objectMapper.createObjectNode(); // first send event that doesn't match process boundary event requestNode.put("eventDefinitionKey", "myEvent"); requestNode.put("channelDefinitionKey", "myChannel"); ObjectNode payloadNode = requestNode.putObject("eventPayload"); payloadNode.put("customerId", "notExisting"); payloadNode.put("productNumber", "p456"); HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + EventRestUrls.createRelativeResourceUrl(EventRestUrls.URL_EVENT_INSTANCE_COLLECTION)); httpPost.setEntity(new StringEntity(requestNode.toString())); CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_NO_CONTENT); closeResponse(response); task = processTaskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("task"); // now send event with matching correlation value requestNode.put("eventDefinitionKey", "myEvent"); payloadNode = requestNode.putObject("eventPayload"); payloadNode.put("customerId", "123"); payloadNode.put("productNumber", "p456"); httpPost = new HttpPost(SERVER_URL_PREFIX + EventRestUrls.createRelativeResourceUrl(EventRestUrls.URL_EVENT_INSTANCE_COLLECTION)); httpPost.setEntity(new StringEntity(requestNode.toString())); response = executeRequest(httpPost, HttpStatus.SC_NO_CONTENT); closeResponse(response); task = processTaskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("taskAfterBoundary"); repositoryService.deleteDeployment(deployment2.getId()); } }
Java
UTF-8
529
2.015625
2
[]
no_license
package vn.com.qlthuvien.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import vn.com.qlthuvien.model.BookCategory; import vn.com.qlthuvien.model.ClassID.BookCategoryID; @Repository public interface BookCategoryRepository extends JpaRepository<BookCategory, BookCategoryID> { Page<BookCategory> findAllByStatusIs(Boolean status, Pageable pageable); }
Java
UTF-8
326
2.5625
3
[]
no_license
package model; public class NoteText { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } public void printText() { System.out.println(text); System.out.println("__________________________"); } }
C++
UTF-8
1,047
2.796875
3
[]
no_license
#ifndef _triangle_hpp_ #define _triangle_hpp_ 1 namespace bigcpp { namespace chapter2 { class Point { private: double x{0.0}; double y{0.0}; public: Point(double x, double y): x{x}, y{y}{}; inline double get_x(){return this->x;}; inline double get_y(){return this->y;}; }; // class Triangle class Triangle { private: Point point_a; Point point_b; Point point_c; public: Triangle(Point point_a, Point point_b, Point point_c): point_a{point_a}, point_b{point_b}, point_c{point_c}{}; bool check_if_valid(); double get_long_of_ab(); double get_long_of_ac(); double get_long_of_bc(); double get_angle_abc(); double get_angle_bac(); double get_angle_acb(); double get_primeter(); double get_area(); }; } // namespace } // namespace #endif
Java
UTF-8
323
1.726563
2
[]
no_license
package com.smeshariks.pms.dto; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class MaterialDto { private String title; private String description; private Integer balance; private Integer cost; private Integer minimumVolume; private Integer isEquipment; }
Java
UTF-8
2,676
2.765625
3
[ "MIT" ]
permissive
package com.wennersanner.libraryapi.repository; import com.wennersanner.libraryapi.model.Book; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; @ExtendWith (SpringExtension.class) @ActiveProfiles("test") @DataJpaTest //indica que feremos teste com jpa public class BookRepositoryTest { @Autowired TestEntityManager entityManager; @Autowired BookRepository repository; @Test @DisplayName ("Deve retornar verdadeiro quando existir um livro na base com o isbn informado") public void returnTrueWhenIsbExist() { String isbn = "123"; Book book = createNewBook(isbn); entityManager.persist (book); boolean exists = repository.existsByIsbn (isbn); Assertions.assertThat (exists) .isTrue (); } @Test @DisplayName ("Deve retornar falso quando não existir um livro na base com o isbn informado") public void returnFalseWhenIsbnDoesnTExist() { String isbn = "123"; boolean exists = repository.existsByIsbn (isbn); Assertions.assertThat (exists) .isFalse (); } @Test @DisplayName("Deve obter um livro por id") public void finByIdTest() { Book book = createNewBook("123"); entityManager.persist(book); Optional<Book> foundBook = repository.findById(book.getId()); Assertions.assertThat(foundBook.isPresent()).isTrue(); } @Test @DisplayName("Deve salvar um livro") public void saveBookTest() { Book book = createNewBook("123"); Book savedBook = repository.save(book); Assertions.assertThat(savedBook.getId()).isNotNull(); } @Test @DisplayName("Deve remover um livro") public void deleteBookTest() { Book book = createNewBook("123"); entityManager.persist (book); Book foundBook = entityManager.find(Book.class, book.getId()); repository.delete(foundBook); Book deleteBook = entityManager.find(Book.class, book.getId()); Assertions.assertThat(deleteBook).isNull(); } public static Book createNewBook(String isbn) { return Book.builder().title("Aventuras").author("fulano").isbn(isbn).build(); } }
Java
UTF-8
1,624
2.546875
3
[]
no_license
package com.xpf.android.retrofit.mvp.base; import android.os.Bundle; import androidx.annotation.Nullable; import android.util.Log; /** * Created by x-sir on 2019/4/19 :) * Function:带有生命周期的所有 Presenter 的基类 * {@link # https://github.com/xinpengfei520/RxJavaRetrofit2Demo} */ public abstract class MvpBasePresenter<V extends IBaseView> { private static final String TAG = "MvpBasePresenter"; private V mBaseView; public MvpBasePresenter() { } /** * Presenter被创建后调用 * * @param savedState 被意外销毁后重建后的 Bundle */ public void onCreatePersenter(@Nullable Bundle savedState) { Log.i(TAG, "onCreatePresenter()"); } /** * 绑定 View * * @param view */ public void onBindView(V view) { this.mBaseView = view; Log.i(TAG, "onBindView()"); } /** * 解绑 View,避免当请求网络数据未完成时 Activity 退出所造成的内存泄露 */ public void onUnbindView() { this.mBaseView = null; Log.i(TAG, "onUnbindView()"); } /** * Presenter 被销毁时调用 */ public void onDestroyPresenter() { Log.i(TAG, "onDestroyPresenter()"); } /** * 在 Presenter 意外销毁的时候被调用,它的调用时机和 Activity、Fragment、View 中的 onSaveInstanceState 的时机相同 * * @param outState */ public void onSaveInstanceState(Bundle outState) { Log.i(TAG, "onSaveInstanceState()"); } public V getView() { return mBaseView; } }
Java
UTF-8
232
1.625
2
[]
no_license
package com.liu.service; public interface LoginService { Integer getLoginInfoAdm(String id,String password); Integer getLoginInfoStu(String id, String password); Integer getLoginInfoTea(String id, String password); }
PHP
UTF-8
953
3.203125
3
[]
no_license
<?php $today = date("d"); $today2 = date("m"); $today3 = date("Y"); $todayt =date("H:i:s:A"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dates</title> </head> <style> small { color: green; font-size: 24px; } span { color: #fff; background: grey; width: 100%; border-radius: 20%; padding: 3px 3px; height: 100%; } span:hover { color: red; background: #fff; } </style> <body> <div class="today"> <h1>php date function</h1> <small>Day</small> <p><?php echo $today ?></p><span><?php echo $todayt ?></span> <br> <small>month</small> <p><?php echo $today2 ?></p><span><?php echo $todayt ?></span> <br> <small>Year</small> <p><?php echo $today3 ?></p><span><?php echo $todayt ?></span> <br> </div> </body> </html>
JavaScript
UTF-8
537
2.796875
3
[]
no_license
'use strict'; (function () { var ESC_KEYCODE = 27; var ENTER_KEYCODE = 13; var LEFT_MOUSE_BUTTON_CODE = 0; var ENTER_KEY = 'Enter'; var isEscEvent = function (evt, action) { if (evt.keyCode === ESC_KEYCODE) { action(); } }; var isEnterEvent = function (evt, action) { if (evt.keyCode === ENTER_KEYCODE) { action(); } }; window.keyboardUtil = { leftMouseButtonCode: LEFT_MOUSE_BUTTON_CODE, enterKey: ENTER_KEY, isEscEvent: isEscEvent, isEnterEvent: isEnterEvent }; })();
Java
UTF-8
1,720
1.585938
2
[]
no_license
// isComment package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog.listeners.price; import android.text.InputFilter; import android.text.Spanned; import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.R; import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog.ProductDialogCache; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; /** * isComment */ public class isClassOrIsInterface implements InputFilter { private static final String isVariable = "isStringConstant"; private static final String isVariable = "isStringConstant"; private String isVariable; private static final String isVariable = "isStringConstant"; public isConstructor(ProductDialogCache isParameter) { NumberFormat isVariable = isNameExpr.isMethod(); if (isNameExpr instanceof DecimalFormat) { DecimalFormatSymbols isVariable = ((DecimalFormat) isNameExpr).isMethod(); isNameExpr = isNameExpr.isMethod(isNameExpr.isMethod()); } else { isNameExpr = isNameExpr.isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } } @Override public CharSequence isMethod(CharSequence isParameter, int isParameter, int isParameter, Spanned isParameter, int isParameter, int isParameter) { String isVariable = isNameExpr.isMethod(); isNameExpr = isNameExpr.isMethod(isNameExpr, "isStringConstant"); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr); return isNameExpr; } }
Markdown
UTF-8
1,938
3
3
[ "MIT" ]
permissive
![Project Presentation](https://github.com/bytesbay/web3-token/raw/main/resources/logo.jpg "Web3 Token") # Web3 Token Web3 Token is a new way to authenticate users. A replacement for JWT in hybrid dApps. See [this article](https://medium.com/@bytesbay/you-dont-need-jwt-anymore-974aa6196976) for more info (later I'll add this info to this readme). ## Install ```bash $ npm i web3-token ``` ## Example usage (Client side) ```js import Web3Token from 'web3-token'; // Connection to MetaMask wallet const web3 = new Web3(ethereum); await ethereum.enable(); // getting address from which we will sign message const address = (await web3.eth.getAccounts())[0]; // generating a token with 1 day of expiration time const token = await Web3Token.sign(msg => web3.eth.personal.sign(msg, address), '1d'); // attaching token to authorization header ... for example ``` ## Example usage (Server side) ```js const Web3Token = require('web3-token'); // getting token from authorization header ... for example const token = req.headers['Authorization'] const { address, body } = await Web3Token.verify(token); // now you can find that user by his address // (better to do it case insensitive) req.user = await User.findOne({ address }); ``` ## API Argument | Name | Description | Required | Example --- | --- | --- | --- | --- 1 | `signer` | A function that returns a promise with signature string eg: web3.personal.sign(`data`, `address`) | `required` | `(body) => web3.personal.sign(body, 0x23..1234)` 2 | `expire_in` | A string that represents a time span ([see ms module](https://github.com/vercel/ms)) or a number of milliseconds | `optional` (default: `1d`) | `1 day` 3 | `body` | An object that will be appended to a signature's body. Can only contain string values. Can be used for some custom data. | `optional` | `{ 'Custom-data': 'some custom data' }` ## License Web3 Token is released under the MIT license. © 2021 Miroslaw Shpak
JavaScript
UTF-8
797
2.984375
3
[ "MIT" ]
permissive
$(document).ready(function(){ var quotes,authors,ran,newquote,newauthor,colors,newcolor; function getquote(){ quotes=["I'm hopeless and awkward and desperate for love.","I drink and I know things","I'm against having emotions, not against using them"]; authors=["-Chandler Bing","-Tyrion Lannister","-Harvey Specter"]; colors=["red","green","blue"]; ran=Math.floor((Math.random()*4)); newquote=quotes[ran]; newauthor=authors[ran]; newcolor=colors[ran]; $('#quote').text(<i class="fa fa-quote-left">newquote</i>); $('#author').text(newauthor); $('body').css("background-color",newcolor); } $('#new').on("click",function(){ getquote(); }); $('#tweet').on("click",function(){ window.open("https://twitter.com/intent/tweet?text="+newquote+" "+newauthor); }); });
C++
UTF-8
691
3.5
4
[]
no_license
#include "Person.h" using namespace std; Person::Person() { this->name = "No name"; this->mail = "no@mail.com"; } Person::Person(string name, string mail) { this->name = name; this->mail = mail; } string Person::getName() const { return name; } string Person::getMail() const { return mail; } int Person::compare(const Person &right) const { if (name.compare(right.name) != 0){ return name.compare(right.name); } return mail.compare(right.mail); } bool operator==(const Person& left, const Person& right) { return left.compare(right) == 0; } bool operator!=(const Person& left, const Person& right) { return left.compare(right) != 0; }
Java
UTF-8
942
2.578125
3
[]
no_license
package com.rd.familytree.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PBTester { public static void main(String[] args) { ProcessBuilder pd = new ProcessBuilder("ssh", "-q", "-o", "\"StrictHostKeyChecking no\"", "qassp@10.50.152.223", "whoami"); Process process = null; String result = null; try { process = pd.start(); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } result = builder.toString(); } catch (InterruptedException | IOException e) { System.out.println("failed"); e.printStackTrace(); } System.out.println("result : "+result); } }
C++
UTF-8
1,800
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double ld; #define L 25 // Kevin Mathew T // Birla Institute of Technology, Mesra // GitHub - https://github.com/KevinMathewT // CodeForces - https://codeforces.com/profile/KevinMathew // CodeChef - https://www.codechef.com/users/KevinMathew // HackerRank - https://www.hackerrank.com/KevinMathew? ll n, q, parent[1000010][L], d[1000010]; vector<ll> tree[1000010]; void dfs(ll u, ll p, ll di){ parent[u][0] = p; d[u] = di; for(ll v : tree[u]) if(v != p) dfs(v, u, di + 1); } ll raise(ll x, ll v){ for(ll i=0;i<L && x != -1;i++) if(v & (1 << L)) x = parent[x][L]; return x; } ll LCA(ll u, ll v){ if(u == v) return u; if(d[u] != d[v]) if(d[u] > d[v]) u = raise(u, d[u] - d[v]); else v = raise(v, d[v] - d[u]); if(u == v) return u; while(u != v) for(ll i=L-1;i>=0;i--) if(parent[u][i] != parent[v][i]){ u = parent[u][i]; v = parent[v][i]; break; } u = parent[u][0]; return u; } void solve(){ cin >> n >> q; for(ll i=0;i<n-1;i++){ ll u, v; cin >> u >> v; tree[u].push_back(v); tree[v].push_back(u); } for(ll i=1;i<=n;i++) for(ll j=0;j<L;j++) parent[i][j] = 0; dfs(1, 0, 0); for(ll i=1;i<L;i++) for(ll j=1;j<=n;j++) parent[j][i] = parent[parent[j][i-1]][i-1]; while(q--){ ll a, da, b, db; cin >> a >> da >> b >> db; ll lca = LCA(a, b); if((da + db) != (d[a] + d[b] - (2 * d[lca]))){ cout << "-1\n"; continue; } if(da <= (d[lca] - d[a])) cout << raise } } int main() { freopen("input.txt", "r", stdin); //Comment freopen("output.txt", "w", stdout); //this out. ios::sync_with_stdio(false); //Not cin.tie(NULL); //this. cout.tie(0); //or this. ll T; cin >> T; while(T--) solve(); return 0; }
JavaScript
UTF-8
652
3.09375
3
[]
no_license
/** * 防抖 * 立即执行版实现 * @param {*} func * @param {*} wait * @param {*} immediate * @returns */ export function debounce(func, wait, immediate) { let timeout; return function () { const context = this; const args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { // 立即执行 console.log('!timeout', !timeout) if (!timeout) func.apply(context, args) timeout = setTimeout(function () { timeout = null; }, wait) } else { // 不立即执行 timeout = setTimeout(function () { func.apply(context, args) }, wait); } } }
Python
UTF-8
1,551
3.75
4
[]
no_license
#Exercise Question 3: Read all product sales data and show it using a multiline plot # Display the number of units sold per month for each product using multiline plots. (i.e., Separate Plotline for each product for each product). import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('company_sales_data.csv') print(df) monthList = df['month_number'].tolist() # print("Month List", monthList) faceCreamSalesData = df['facecream'].tolist() # print("Face cream List Data", faceCreamSalesData) faceWashSalesData = df['facewash'].tolist() # print("Face wash List Data", faceWashSalesData) toothPasteSalesData = df['toothpaste'].tolist() # print("Tooth Past List Data", toothPasteSalesData) bathingSoapSalesData = df['bathingsoap'].tolist() shampooSalesData = df['shampoo'].tolist() plt.plot(monthList, faceCreamSalesData, label = "Face Cream Sales Data", marker= 'o', linewidth= 3) plt.plot(monthList, faceWashSalesData, label = "Face Wash Sales Data", marker= 'o', linewidth= 3) plt.plot(monthList, toothPasteSalesData, label = "Toothpest Sales Data", marker= 'o', linewidth= 3) plt.plot(monthList, bathingSoapSalesData, label = "Bathing soap Sales Data", marker= 'o', linewidth= 3) plt.plot(monthList, shampooSalesData, label = "Shampoo Sales Data", marker= 'o', linewidth= 3) plt.xlabel('Month Number') plt.ylabel('Sales units in number') plt.legend(loc='upper left') plt.xticks(monthList) plt.yticks([1000, 2000, 4000, 6000, 8000, 10000, 12000, 15000, 18000]) plt.title('Sales data') plt.show()
Markdown
UTF-8
2,192
3.171875
3
[]
no_license
# Adverity assignment solution Here it is Kotlin/SpringBoot solution for given assignment. Main idea is to use SpringEL as a parser for expression and calculate group-by, filter, and fields values dinamically by SpringEL framework. ## Usage and main syntax Central model class is `ClickRow` which is the abstaction for the row in data csv: ```kotlin data class ClickRow ( var id: Long?, var datasource: String, var campaign: String, var daily: LocalDate, var clicks: Int, var impressions: Int ) ``` To access the data one needs to use `/clicks` endpoint. This is the REST endpoint and has the following format: `http://localhost:8080/clicks/groups/GROUPS/fields/FIELDS[/filters/FILTERS]?from=FROM_DATE&to=TO_DATE` where: * `GROUPS` -- is a comma separated list of fields to group for `ClickRow` objects. For example: `datasource,campaign` * `FIELDS` -- is a comma separated list of expressions that will be calculated on top of the groups: * * `sum('field_name')` -- for a given group calculates sum for the field, * * `f('field_name')` -- for a given group it takes first element in the group and field value of this object * `/filters/FILTERS` -- optional section of comma separated list of expressions that will be calculated for each `ClickRow` object. For example, `clicks < 100` * `FROM_DATE`, `TO_DATE` -- optionals parameters date start date end (inclusive) ## Example queries * Clicks per `datasource` for a given range `{HOST}/adverity/clicks/groups/datasource/fields/sum('clicks')?from=2019-10-10&to=2019-11-10` * CTR per `datasource` and `campaign` for a given range `{HOST}/adverity/clicks/groups/datasource,campaign/fields/1.0*sum('clicks')%2Fsum('impressions')?from=2019-10-10&to=2019-11-10` * `Impressions` over time daily `{HOST}/adverity/clicks/groups/daily/fields/sum('impressions')?from=2019-10-10&to=2019-11-10` ## Assumptions * for non-grouping queries, please use Identity group: `id`. For production code, we need to add special handling of non-grouping queries * when field A requested that not presented in group clause, we return first element. In future, to avoid misleadings, we need to return error or warning in this case
Java
UTF-8
618
2.609375
3
[]
no_license
package rmitest; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; /** * * @author Derek * Defines the actual functions for the RMI. */ public class RMIDemoFunct extends UnicastRemoteObject implements RMIDemo { /** * Required for a Serializable Object */ private static final long serialVersionUID = 1L; /** * Must provide a default constructor... */ protected RMIDemoFunct() throws RemoteException { super(); } @Override public double addNumbers( double x, double y ) throws RemoteException { System.out.println("In RMIDemoServer"); return x + y; } }
C#
UTF-8
7,842
3.421875
3
[]
no_license
using System; using System.Collections.Generic; namespace Battleship { public class Program { private const String PossibleColumns = "ABCDEFGH"; public ShipLocation Board1ShipLocation { get; set; } public ShipLocation Board2ShipLocation { get; set; } public readonly List<Location> Board1HitLocations = new List<Location>(); public readonly List<Location> Board2HitLocations = new List<Location>(); private GamePiece[,] _p1GameBoard; private GamePiece[,] _p2GameBoard; // ReSharper disable once UnusedParameter.Local static void Main(string[] args) { new Program().Run(); } private void Run() { WriteLine("Game Starting..."); Board1ShipLocation = ReadShipLocation(1); Board2ShipLocation = ReadShipLocation(2); var isPlayer1Turn = true; while (true) { var playerShot = ReadPlayerShot(isPlayer1Turn); if (isPlayer1Turn) { Board2HitLocations.Add(playerShot); } else { Board1HitLocations.Add(playerShot); } if (CheckGameOver(isPlayer1Turn)) { var player = isPlayer1Turn ? 1 : 2; WriteLine($"Congratulations Player {player}, you sunk my battleship"); WriteLine("Game over...."); WriteLine(GetAsciiBoard(true)); WriteLine(GetAsciiBoard(false)); break; } isPlayer1Turn = !isPlayer1Turn; } ReadLine("Press [Enter] to end program..."); } //Note it is important Blank is the first entry //As arrays initialized of Enum types initialize everything to the //First index in this enum enum GamePiece { Blank, // LEAVE AS FIRST! Ship, ShipHit, Miss } public bool CheckGameOver(bool isPlayer1Turn) { var shipLocation = isPlayer1Turn ? Board2ShipLocation : Board1ShipLocation; var hitLocations = isPlayer1Turn ? Board2HitLocations : Board1HitLocations; GamePiece[,] gameBoard; if (isPlayer1Turn) { _p2GameBoard = new GamePiece[8, 8]; gameBoard = _p2GameBoard; } else { _p1GameBoard = new GamePiece[8, 8]; gameBoard = _p1GameBoard; } foreach (var location in shipLocation.GetLocations()) { gameBoard[location.Row, location.Column] = GamePiece.Ship; } int shipHitCount = 0; foreach (var hitLocation in hitLocations) { if (gameBoard[hitLocation.Row, hitLocation.Column] == GamePiece.Ship) { gameBoard[hitLocation.Row, hitLocation.Column] = GamePiece.ShipHit; shipHitCount++; } else { gameBoard[hitLocation.Row, hitLocation.Column] = GamePiece.Miss; } } return shipHitCount == 3; } public String GetAsciiBoard(bool player1) { var gameBoard = player1 ? _p1GameBoard : _p2GameBoard; var player = player1 ? 1 : 2; var result = $"Player {player} Board:\n"; result += " A B C D E F G H\n"; for (int i = 0; i < gameBoard.GetLength(0); i++) { //Add the row number result += i + 1; for (int j = 0; j < gameBoard.GetLength(1); j++) { var currentPiece = gameBoard[i, j]; char c; switch (currentPiece) { case GamePiece.Blank: c = '-'; break; case GamePiece.Miss: case GamePiece.ShipHit: c = 'X'; break; case GamePiece.Ship: c = 'S'; break; default: throw new Exception("Invalid GamePiece"); } result += " " + c; } result += "\n"; } return result; } private Location ReadPlayerShot(Boolean isPlayer1Turn) { var player = isPlayer1Turn ? 1 : 2; var otherPlayer = isPlayer1Turn ? 2 : 1; var strLocation = ReadLine($"Player {player}: Provide a location to hit Player {otherPlayer}. Format: B5").Trim().ToUpper(); var location = ParseLocation(strLocation); if (location == null) { WriteLine("Invalid Entry"); return ReadPlayerShot(isPlayer1Turn); } return location; } public ShipLocation ReadShipLocation(int player) { var strLocation = ReadLine($"Please enter the ship location for Player {player}. Format A3 A5"); var shipLocation = ParseShipLocation(strLocation); if (shipLocation == null || !shipLocation.Valid()) { WriteLine("Invalid Entry"); return ReadShipLocation(player); } return shipLocation; } public ShipLocation ParseShipLocation(String strShipLocation) { if (strShipLocation == null) { return null; } strShipLocation = strShipLocation.Trim().ToUpper(); if (strShipLocation.Length != 5) { return null; } var strLocations = strShipLocation.Split(' '); if (strLocations.Length != 2) { return null; } var shipLocation = new ShipLocation { Start = ParseLocation(strLocations[0]), End = ParseLocation(strLocations[1]) }; if (shipLocation.Start == null || shipLocation.End == null) { return null; } return shipLocation; } public Location ParseLocation(String strLocation) { if (strLocation.Length != 2) { return null; } var column = strLocation.ToCharArray()[0].ToString(); if (!PossibleColumns.Contains(column)) { return null; } var strRow = strLocation.ToCharArray()[1].ToString(); if (!int.TryParse(strRow, out int row)) { return null; } row = row - 1; if (row < 0 || row > 7) { return null; } var colInt = PossibleColumns.IndexOf(column, StringComparison.InvariantCultureIgnoreCase); var location = new Location { Column = colInt, Row = row }; return location; } private void WriteLine(String message) { Console.WriteLine(message); } private String ReadLine(String message) { if (message != null) { WriteLine(message); } return Console.ReadLine(); } } }
C#
UTF-8
550
2.578125
3
[ "MIT" ]
permissive
using System.Text.RegularExpressions; public class PasswordFieldView : InputFieldView { Regex expectedString = new Regex("^.{22,}$"); protected void Start() { input.onValueChanged.AddListener( delegate { ValueChangeCheck(); } ); input.asteriskChar = "•"[0]; } protected override void ValueChangeCheck() { inputText = input.text; if ( expectedString.IsMatch( input.text ) ) { IsValidate = true; ActiveHint( false ); } else { IsValidate = false; ActiveHint(true); } InputText_OnChange(); } }
Go
UTF-8
456
3.125
3
[]
no_license
package types type UnsignedShort uint16 func (short UnsignedShort) Encode(w Writer) (err error) { err = w.WriteByte(byte(short << 8)) err = w.WriteByte(byte(short)) return } func (short UnsignedShort) Decode(r Reader) (n int, err error) { var ( s1 byte //stream short 1 s2 byte //stream short 2 ) s1, err = r.ReadByte() s2, err = r.ReadByte() if err != nil { return 0, err } short = UnsignedShort(uint16(s1)<<8 | uint16(s2)) return }
Python
UTF-8
1,247
2.703125
3
[]
no_license
#-*- coding: UTF-8 -*- import pandas as pd import numpy as np from operator import itemgetter import time import copy def save_res(res): try: fp = open("F:\\ss\\py\\taobao\\output_data\\0320\\0320_3.txt","w+") for item in res: fp.write(str(item)+"\n") fp.close() except IOError: print("fail to open file") if __name__ == '__main__': file_path1 = "F:\\ss\\py\\taobao\\output_data\\0320\\0320_2.txt" file_path2 = "F:\\ss\\py\\taobao\\input_data\\ronghe\\sim.csv" history_data = pd.read_table(file_path1, sep='\s+', names=['item_id', 'items_list']) sim_data = pd.read_table(file_path2, sep='\s+', names=['item_id', 'sim_items_list']) his_sim_not_same = pd.merge(sim_data,history_data,on=['item_id'],how='left') his_sim_not_same = his_sim_not_same[his_sim_not_same['items_list'].isnull()].drop(['items_list'],axis=1).rename(columns={'sim_items_list':'items_list'}) #融合 res = [his_sim_not_same,history_data] res = pd.concat(res) res_arr=[] for dim_item in res.iterrows(): item_id = dim_item[1]['item_id'] item_name = dim_item[1]['items_list'] s = str(item_id) + " " +item_name res_arr.append(s) save_res(res_arr)
Rust
UTF-8
815
3.1875
3
[]
no_license
//$(which true); dst=/var/tmp/sut; out=${dst}/$0.bin; //$(which mkdir) -p ${dst}; //$(which rustc) -o "${out}" 1>&2 "$0" && "${out}" "$@"; exit $? ////////////////////////////////// // macros do not have namespaces!! ////////////////////////////////// macro_rules! say { // matches no argument () => { // call to say!() will be expanded to println!("thereisacow"); }; // match an expression and assign it to x // arguments (if many) can be separated by comma // *: allow repeating ( $( $x:expr ),* ) => { print!("there are: "); // iterate over all the arguments (repeating N times) $( print!("{}", $x); )* println!(""); } } fn main() { say!(); say!(1); say!('a', 'b', 'c'); assert!(1 == 1); }
Python
UTF-8
1,988
4
4
[]
no_license
#### # Stuart Kettenring # 6/27/2014 # # Because I do not have any projects to use as examples # of my programming, I have taken a few problems from # projecteuler.net and solved them here. I hope this # serves as a decent example of my programming abilities. ## import time #### # Helper functions ## #Will determine whether or not 'n' is a prime number. def isPrime(n): half = n/2 for i in range (2, int(half)): if(int(n) % i == 0): return False return True #Test efficiency of primes functions def testingPrimes(n): start = time.clock() isPrime(n) elapsed = time.clock() elapsed = elapsed - start print ("Time spent in (primeSum) is: ", elapsed) start = time.clock() primeSum(n) elapsed = time.clock() elapsed = elapsed - start print ("Time spent in (isprimetest) is: ", elapsed) #### # Problem 7: (10001st) prime number ## def prime(n): foundPrime = 1 #count starts at 2 num = 2 while (foundPrime <= n): num += 1 if(isPrime(num)): foundPrime += 1 print("The %d prime number is: %d"%(n, num)) #### # Problem 10: sum of primes (below 2 million). # using Sieve of Eratosthenes as algorithm. ## def primeSum(n): num = [] sqrt = n**(1/2.0) + 2 start = 0 step = 2 #populate list to work with. 'p' means prime for i in range(2, n): num.append([i,'p']) #and 'x' means not prime for i in range(2, int(sqrt)): for j in range(start + step, len(num), step): if(num[j][1] == 'p'): num[j][1] = 'x' #move to next prime number to test start += 1 while(num[start][1] == 'x'): start += 1 step = num[start][0] #then find sum pSum =0 for i in range(len(num)): if(num[i][1] == 'p'): pSum += num[i][0] print("The sum of all prime numbers below 2 million is: %d"%(pSum))
C++
UTF-8
1,559
3.5625
4
[]
no_license
// Program to use the dictionary lookup program #include <stdio.h> #include <string.h> #include<stdlib.h> #include <stdbool.h> struct entry { char word[15]; char definition[50]; }; bool equalStrings (const char s1[], const char s2[]) { int i = 0; bool areEqual; while ( s1[i] == s2 [i] && s1[i] != '\0' && s2[i] != '\0' ) ++i; if ( s1[i] == '\0' && s2[i] == '\0' ) areEqual = true; else areEqual = false; return areEqual; } // function to look up a word inside a dictionary int lookup(const struct entry dictionary[], const char search[],const int entries) { int i; bool equalStrings(const char s1[], const char s2[]); for ( i = 0; i < entries; ++i ) if ( equalStrings (search, dictionary[i].word) ) return i; return -1; } int main (void) { const struct entry dictionary[100] = { { "aardvark", "a burrowing African mammal" }, { "abyss", "a bottomless pit" }, { "acumen", "mentally sharp; keen" }, { "addle", "to become confused" }, { "aerie", "a high nest" }, { "affix", "to append; attach" }, { "agar", "a jelly made from seaweed" }, { "ahoy", "a nautical call of greeting" }, { "aigrette", "an ornamental cluster of feathers" }, { "ajar", "partially opened" } }; char word[10]; int entries = 10; int entry; int lookup(const struct entry dictionary[], const char search[], const int entries); printf("Enter word: "); scanf("%14s", word); entry = lookup (dictionary, word, entries); if ( entry != -1 ) printf("%s\n", dictionary[entry].definition); else printf("Sorry, the word %s is not in my dictionary.\n", word); system("pause"); return 0; }
Python
UTF-8
1,079
3.875
4
[]
no_license
import random rand = random.randint(0, 999) print("\nThis program generates a random number between 0 and 999") print("Please try and guess it!") b = 0 def guess(): global b global rand d = input("\nWhat is your guess? \n \n") b = b+1 strcheck(d) a = int(d) if a == rand: print("\nGood Job, you did it!") print("You took", b, "guesses to find it! \n") play = input("Would you like to play again? \n \n").lower() if play == "yes": b = 0 rand = random.randint(0,999) guess() else: print("\nSorry to see you go, come back again soon!") exit() elif a > 999: print("\nThats higher than the max! Try again!") guess() elif a < 0: print("\nThe number isn't negative! Try again!") guess() elif a > rand: print("\nToo high! Try again!") guess() elif a < rand: print("\nToo low! Try again!") guess() else: print("\nI'm not sure how you got here, but please try again!") guess() def strcheck(d): try: float(d) return True except ValueError: print ("\nThats not a number, please try again!") guess() return False guess()
JavaScript
UTF-8
2,868
2.578125
3
[ "MIT" ]
permissive
const { buildYup } = require("../src"); let valid; test("yup inserts custom messages for required fields", () => { const message = { title: "users", type: "object", required: ["username"], properties: { username: { type: "string", matches: "foo" }, }, }; const config = { errMessages: { username: { required: "User is required", matches: "User must be foo", }, }, }; try { const yupSchema = buildYup(message, config); valid = yupSchema.validateSync({ foo: "dfds", }); } catch (e) { console.log(e.errors); valid = e.errors[0]; } expect(valid).toBe("User is required"); }); test("yup inserts custom messages for regex fields", () => { const message2 = { title: "users", type: "object", properties: { place: { type: "object", required: ["amazon"], properties: { amazon: { type: "string", pattern: /(foo|bar)/ }, }, }, }, }; const config = { errMessages: { amazon: { pattern: "Pattern must be foo or bar", }, }, }; try { const yupSchema = buildYup(message2, config); valid = yupSchema.validateSync({ place: { amazon: "xyz" }, }); } catch (e) { valid = e.errors[0]; } expect(valid).toBe("Pattern must be foo or bar"); }); test("yup uses custom error message function", () => { const message2 = { title: "users", type: "object", required: ["amazon"], properties: { amazon: { type: "string", pattern: /(foo|bar)/, title: "amazonas" }, }, }; const config = { errMessages: { amazon: { pattern: (constraints, { title, parentNode }) => { return `Pattern must be ${constraints.pattern} for ${title}`; }, }, }, }; try { const yupSchema = buildYup(message2, config); valid = yupSchema.validateSync({ amazon: "dfds", }); } catch (e) { valid = e.errors[0]; } expect(valid).toBe("Pattern must be /(foo|bar)/ for amazonas"); }); test("yup uses custom error message function", () => { const message2 = { title: "coffee", type: "object", properties: { place: { type: "object", required: ["amazon"], properties: { amazon: { type: "string", pattern: /(foo|bar)/, title: "amazonas" }, }, }, }, }; const config = { errMessages: { amazon: { pattern: (constraints, { title, parentNode }) => { return `Pattern must be ${constraints.pattern} for ${title}`; }, }, }, }; try { const yupSchema = buildYup(message2, config); valid = yupSchema.validateSync({ place: { amazon: "zyx" }, }); } catch (e) { valid = e.errors[0]; } expect(valid).toBe("Pattern must be /(foo|bar)/ for amazonas"); });
JavaScript
UTF-8
3,154
2.71875
3
[ "MIT" ]
permissive
// We commonly need to grab the url where we are or came from for our animation scenes // By default this will return a string enter- + the url path without domain var getEnterExitString = function(e) { var url = e + '-' + $(location).attr('pathname').replace(/\//g, ''); console.log(url) return url; } // Smoothstate needs typicall document onready functions to be fired again once a new page loads. So we move typical actions like this into their own functions and call them with the smooothState OnAfter function. // Init the mobile nav function var navToggle = function (e) { $('body').toggleClass('is-navbar-active'); e.preventDefault(); } // Force collapes of the navbar on anchor links and scroll top function var anchorSetup = function (e) { $( "a" ).click(function() { $('body').removeClass('is-navbar-active'); }); $( ".js-scroll-top" ).click(function() { $('body').animate({ scrollTop: 0 }, 600); }); } // Video loader if you are on not on a touch device var videoLoad = function() { $('.js-media-hold').each(function() { var url_video = $(this).attr("data-video"); if (Modernizr.video.h264 && url_video) { $(this).append("<label for='" + $(this).attr("data-id") + "' class='hide'>Video of " + $(this).attr("data-title") + "</label><video id='" + $(this).attr("data-id") + "' playsinline muted autoplay loop class='aspect__fill'><source src='" + $(this).attr("data-video") + " 'type='video/mp4'></video>"); } else { $(this).append("<img class='aspect__fill' src='" + $(this).attr("data-img") + " ' alt='" + $(this).attr("data-title") + " ' />"); } }) }; // On Document Ready $(function() { 'use strict'; var $body = $('html, body'), smoothState = $('#js-main').smoothState({ //smoothState options prefetch: true, pageCacheSize: 8, blacklist: ".no-smoothstate, [target], [data-type='image'] a", scroll: false, onStart: { duration: 600, render: function($container) { $('#js-main').attr('data-exit', getEnterExitString('exit')); // Scroll page back up $body.animate({ scrollTop: 0 }, 600); // Set classes for animation fading $('#js-main') .removeClass('transition-start') .addClass('transition-end'); } }, // OnBefore onBefore: function($currentTarget, $content) { }, onAfter: function($container, $newContent) { // Add the transition start class for transitions duh $('#js-main') .removeClass('transition-end') .addClass('transition-start') .attr('data-enter', getEnterExitString('enter')); videoLoad(); anchorSetup(); } }).data('smoothState'); // On ready functions that need to be fired before smoothState is ready // Kick off video load function videoLoad(); anchorSetup(); // Kick off the animation class on first load since smoothstate is not yet available $('#js-main') .attr('data-enter', getEnterExitString('enter')) .addClass('transition-start') .smoothState(); // Set up navToggle Function $(document).on('click', '.js-nav-toggle', navToggle); });
C++
UTF-8
1,265
4.125
4
[ "LicenseRef-scancode-warranty-disclaimer", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <functional> #include <iostream> #include <mutex> #include <thread> #include <vector> using namespace std; /// List containing elements that cannot be removed class ThreadSafeGrowingList { private: mutex vec_mutex; // protects volatile data vector<int> vec; // contains data public: /// Thread-safe wrapper for emplace_back void add(int i) { lock_guard<mutex> lock(vec_mutex); // locks until end-of-scope vec.emplace_back(i); } // Thread-safe iteration void for_each(function<void(int)> action) { lock_guard<mutex> lock(vec_mutex); // locks until end-of-scope for (auto elem: vec) action(elem); // perform some action on each element } }; int main() { ThreadSafeGrowingList list; vector<thread> threads; for (int i = 0; i < 10; ++i) { threads.emplace_back([&list, i] { list.add(i); }); } // This thread may be executed at *any* time // since the other threads don't *have* to be executed before this point. // Therefore, this for_each will print a random number of elements in an arbitrary order. list.for_each([](int value) { cout << value << endl; this_thread::sleep_for(200ms); }); for (auto &thread : threads) thread.join(); } // vim:softtabstop=2:shiftwidth=2
C++
UTF-8
2,205
2.703125
3
[]
no_license
using VI = vector <int>; using VVI = vector <VI>; template <typename C> struct Edge { int to; int cp; C cap; Edge() {} Edge(int pt, C pcap, int pcp) : to(pt), cap(pcap), cp(pcp) { } }; template <typename C> class FlowGraph { using VE = vector <Edge<C>>; using VVE = vector <VE>; const C INF = 10000000; VVE adja; int src; int sink; int V; VI dist; VI num; public: FlowGraph (int pv) : V(pv) { adja = VVE(pv); dist = VI(pv); num = VI(pv+1); // can be num[V] } void addEdge(int f, int t, C c) { adja[f].push_back( Edge(t, c, adja[t].size()) ); adja[t].push_back( Edge(f, 0, adja[f].size()-1) ); } C aug(int now, C leftCap) { if(now == sink) { return leftCap; } C remainCap = leftCap; int minDist = V; for(int i = 0; i < adja[now].size(); i++) { int nextv = adja[now][i].to; if(adja[now][i].cap > 0 && dist[now] == dist[nextv]+1) { C flow = aug(nextv, min(remainCap, adja[now][i].cap)); adja[now][i].cap -= flow; remainCap -= flow; adja[nextv][ adja[now][i].cp ].cap += flow; if (dist[src] == V || remainCap == 0) { return leftCap-remainCap; } } } if(dist[src] == V) { return leftCap-remainCap; } if(remainCap == leftCap) { for(int i = 0; i < adja[now].size(); i++) { if(adja[now][i].cap) { minDist = min(minDist, dist[ adja[now][i].to ]+1); } } if(--num[ dist[now] ]) { ++num[ dist[now] = minDist ]; } else { dist[src] = V; } } return leftCap-remainCap; } C flow(int psrc, int psink) { C ret = 0; src = psrc; sink = psink; fill(dist.begin(), dist.end(), 0); fill(num.begin(), num.end(), 0); num[src] = V; while (dist[src] < V) { ret += aug(src, INF); } return ret; } };
C++
UTF-8
931
3.03125
3
[]
no_license
#include <iostream> #include <chrono> #include <thread> #include <mutex> #include <deque> #include <functional> #include <vector> #include <iterator> #include <algorithm> class thread_guard { public: std::thread t; explicit thread_guard(std::thread myt): t(std::move(myt)) { if(!t.joinable()) throw std::logic_error("MyError"); } ~thread_guard() {t.join();} thread_guard(thread_guard&& obj) { t = std::move(obj.t); } thread_guard(thread_guard const &) = delete; thread_guard& operator=(thread_guard const &) = delete; }; std::mutex mx; void hey() { std::lock_guard<std::mutex> g(mx); std::cout << "Hey" << std::endl; } void f() { std::vector<thread_guard> v; for(int i = 0; i < 20; i++) v.push_back(thread_guard{std::thread(hey)}); //------- } int main(){ f(); //std::chrono::milliseconds dura( 2000 ); //std::this_thread::sleep_for( dura ); }
Markdown
UTF-8
5,751
3.484375
3
[]
no_license
## JavaScript 标准对象 --- ### 内置对象 *内置对象*(internal object)指的是 JavaScript 核心语言中所包含的类与对象。它们直接由 ECMAScript 标准定义,与运行环境没有关系,但任何 JavaScript 环境都必须预先按照标准实现这些对象,无论是台式计算机,还是移动设备,抑或是手掌大小的单片机。内置对象与语法本身,构成了 JavaScript 的核心语言。 内置对象既包含真真正正的对象(如 `Math`),又包括基本类型所对应的类(如 `Number`)和建立其他一些对象的类(如 `Promise`),还有一些就是单纯的函数和变量(如 `parseInt` 和 `NaN`)。内置对象如同构成 JavaScript 强大力量的基础元件,因此也叫*内置基元*。 **1. 内置变量和普通函数** 我们之前已经介绍了三个内置变量:`Infinity`,`NaN` 和 `undefined`,还有四个内置函数:`parseInt`,`parseFloat`,`isNaN`,`isFinite`。除此之外还有一些函数: - `encodeURI` 和 `encodeURIComponent` 根据将一段普通文本根据*统一资源标识符*的要求编码为对应的*安全版本*。这些函数将在第九章介绍。 - `decodeURI` 和 `decodeURIComponent` 执行相应编码的逆操作。这些函数将在第九章介绍。 - `eval` 将一段字符串视为 JavaScript 代码并执行。如果代码是一个表达式,那么 `eval` 会求出它的值。由于必须对字符串进行编译和解释,因此 `eval` 执行的速度很慢。 以下是 `eval` 函数的示例。 ```javascript let code = prompt("请输入一个算式"); if (/[^\d()+*/-%\s]/.test(code)) { alert("这不是一个算式!"); } else { alert(`算式的值是:${eval(code)}`); } ``` `eval` 函数具有诸多争议,它有时被称为 evil(邪恶的)。当编程语言的某项特性很容易被错误使用,这项特性就被视为邪恶的。使用 `eval` 的唯一原因是动态地执行运行时才产生的代码,但这些代码从何而来呢?如果代码的来源不受信任,就会使应用程序有被注入恶意代码的风险,甚至破坏应用程序。 根据人们的经验,如果我们需要使用 `eval` 来解析一些东西,我们先考虑一下是否有其它替代品可以达成同样目的。一些策略是单纯地解析而不执行,例如 `JSON.parse`。如果我们必须要使用 `eval`,就要保证代码一定是安全的,没有无限循环,没有奇怪的赋值或函数调用等。在上面的示例中,我们使用正则表达式对用户输入的内容进行检查,确保文本仅包含数字、括号和几个运算符,才会调用 `eval` 来求值。我们可以在实践中思考怎样为 `eval` 创建一个安全的执行环境。 **2. Math** **3. Object** **4. Array** **5. Boolean、Number 和 String** **6. Function** **7. Date** **8. 错误对象** 技术上讲,我们可以使用任何东西来作为一个异常对象。甚至可以是基础类型,比如数字或者字符串。但是更好的方式是用对象,尤其是有 `name` 和 `message` 属性的对象(某种程度上和内置的异常有可比性)。 JavaScript 有很多内置的标准异常构造器,我们也可以用它们来构造标准的异常对象。 | JavaScript 标准异常构造器 | 描述 | | ------------------------- | --------------------------------------------------- | | `Error` | 默认或自定义的错误。 | | `EvalError` | 用错误的方式使用 `eval` 函数。 | | `InternalError` | JavaScript 引擎遇到的内部错误,如:“递归嵌套太多”。 | | `RangeError` | 数值变量或参数超出其有效范围。 | | `ReferenceError` | 无效的引用、求值过程。 | | `SyntaxError` | JavaScript 引擎在解析代码时遇到的语法错误。 | | `TypeError` | 变量或参数不属于有效类型。 | | `URIError` | 给 `encodeURI` 或 `decodeURI` 传递的参数无效。 | 使用异常构造器的方式如下: ```javascript let error = new Error(message); // 或者 let error = new SyntaxError(message); let error = new ReferenceError(message); // ... ``` 对于内置的异常对象(不是对于其他的对象,而是对于异常对象),`name` 属性刚好是构造器的名字。`message` 则来自于参数所提供的异常信息。例如: ```javascript let error = new Error("不知道发生了什么 (O_o)??"); alert(error.name); // "Error" alert(error.message); // "不知道发生了什么 (O_o)??" ``` 我们可以使用任何东西来作为一个异常对象。甚至可以是基础类型,比如数字或者字符串。但是更好的方式是用对象,尤其是有 `name` 和 `message` 属性的对象。而内置的异常构造器同时为我们设定好了异常所属的类型,因此尽量使用具体的异常构造器。如果异常不是特定的,那么可以直接用 `Error` 构造器。 异常构造器可以通过 `new` 运算符建立新的异常对象,包含下列属性: - `message` —— 我们能阅读的异常提示信息。 - `name` —— 异常名称(异常对象的构造函数的名称)。 - `stack` —— 异常发生时的调用栈。 **9. JSON** **10. Map 和 WeakMap ** **11. Set 和 WeakSet** **12. Proxy** ### 宿主对象
Ruby
UTF-8
2,916
4.9375
5
[ "MIT" ]
permissive
require 'pry' =begin Convert a String to a Signed Number! In the previous exercise, you developed a method that converts simple numeric strings to Integers. In this exercise, you're going to extend that method to work with signed numbers. Write a method that takes a String of digits, and returns the appropriate number as an integer. The String may have a leading + or - sign; if the first character is a +, your method should return a positive number; if it is a -, your method should return a negative number. If no sign is given, you should return a positive number. You may assume the string will always contain a valid number. You may not use any of the standard conversion methods available in Ruby, such as String#to_i, Integer(), etc. You may, however, use the string_to_integer method from the previous lesson. Examples string_to_signed_integer('4321') == 4321 string_to_signed_integer('-570') == -570 string_to_signed_integer('+100') == 100 1. Understand the problem - input - string (of valid digits) - output - signed integer - rules - cannot use standad conversion methods like String#to_i, Integer(), etc. - You may, however, use the string_to_integer method from the previous lesson. - work with signed numbers: - if the first character is a +, your method should return a positive number - if it is a -, your method should return a negative number. - If no sign is given, you should return a positive number. 2. Test cases string_to_number("1") == 1 string_to_number("123") == 123 string_to_number("2020") == 2020 3. Describe your algorithm - take first character of string - find out if its a sign character (+ or -) - if it is: - identify sign character - convert rest of string to number - sum sign to number - else - convert whole of string to number - return number 4. Begin coding =end DIGITS = { "0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, } SIGN = { "+" => +1, "-" => -1, } def string_to_integer(string) digits = string.chars.map { |char| DIGITS[char] } value = 0 digits.each { |digit| value = 10 * value + digit } value end def string_to_signed_integer(string) sign = SIGN[string[0]] if sign string = string[1..] num = string_to_integer(string) num *= sign else num = string_to_integer(string) end end def string_to_signed_integer(string) sign = +1 if SIGN[string[0]] sign = SIGN[string[0]] string = string[1..] end string_to_integer(string) * sign end def string_to_signed_integer(string) case string[0] when '-' -string_to_integer(string[1..-1]) when '+' string_to_integer(string[1..-1]) else string_to_integer(string) end end puts string_to_signed_integer('4321') == 4321 puts string_to_signed_integer('-570') == -570 puts string_to_signed_integer('+100') == 100
Java
UTF-8
1,688
4.34375
4
[]
no_license
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { // Create tasks Runnable task1 = new Task1(1000000); Runnable task2 = new Task2(1000000); // Create threads Thread thread1 = new Thread(task1); Thread thread2 = new Thread(task2); // Start threads thread1.start(); thread2.start(); } } // The task for printing a character. class Task1 implements Runnable { private int times; public Task1(int times) { this.times = times; } @Override /** Override the run() method to tell the system * what task to perform */ public void run() { for (int i = 0; i <this.times; i++) { try { System.out.println("Task1 is running.."); Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } // The task class for printing numbers class Task2 implements Runnable { private int times; public Task2(int times) { this.times = times; } @Override /** Tell the thread how to run */ public void run() { for (int i = 0; i <this.times; i++) { try { System.out.println(" Task2 is running.."); Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }
Java
UTF-8
1,265
1.84375
2
[]
no_license
package com.ps.credit.card; import com.ps.credit.card.repository.CreditCardRepository; import javax.annotation.PostConstruct; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = CreditCardProcessorApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public abstract class IntegrationTest { private MockMvc mockMvc; @Autowired protected CreditCardRepository creditCardRepository; @Autowired protected WebApplicationContext webApplicationContext; @PostConstruct public void mockMvc() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } protected MockMvc mvc() { return mockMvc; } protected void clearDB() { creditCardRepository.deleteAllInBatch(); } }
Java
UTF-8
797
2.015625
2
[]
no_license
package orderTest; import baseTest.BaseTest; import org.junit.Test; public class OrderTest extends BaseTest { @Test public void orderOrnaments() { homePage .openHomePage() .clickOnShoppingBagButton() .checkShoppingBagIsEmpty() .clickOnNextLogo() .selectAllHomeAccessoriesCategory() .selectOrnamentsSubcategory() .openOrnamentsPage() .clickOnGreenCeramicAppleOrnaments() .clickOnAddToBagButton() .checkNumberOfItemsInShoppingBag(1) .clickOnOrnamentsBreadcrumb() .clickOnGreenCeramicPearOrnaments() .clickOnAddToBagButton() .checkNumberOfItemsInShoppingBag(2); } }
Java
UTF-8
893
2.78125
3
[ "Unlicense" ]
permissive
package za.co.blts.samples.i18n; import java.util.Locale; import java.util.ResourceBundle; /** * @author Kholofelo Maloma * @since 3/23/2017. */ public class JavaI18nExample { public static void main(String[] args) { //Default bundle ResourceBundle resourceBundle = ResourceBundle.getBundle("ApplicationMessages", Locale.getDefault()); ResourceBundle resourceBundleFr = ResourceBundle.getBundle("ApplicationMessages", Locale.FRANCE); printMessages(resourceBundle); printMessages(resourceBundleFr); } private static void printMessages(ResourceBundle bundle) { System.out.println(bundle.getString("CountryName")); System.out.println(bundle.getString("CurrencyCode")); System.out.println(); System.out.println(); System.out.println(); System.out.println(bundle.getString("FirstSomething")); } }
JavaScript
UTF-8
1,272
3.203125
3
[ "Apache-2.0" ]
permissive
// A GameObject should be a geometric shape + a "draw" function // Eventually this should include a path to an image or animation const drawing = require('./drawing'); const physicsSettings = require('./physicsSettings').physicsSettings; const Victor = require('victor'); // Basic object just bundles a shape with a way of drawing that shape class GameObject { constructor(shape, options) { this.shape = shape; this.color = options.color || "WHITE"; this.collidable = options.collidable || false; } get isDynamic() { return false; } get isCollidable() { return this.collidable; } update(dt) {} draw() { drawing.fillPoly(this.shape.points, this.color); } } // Object that handles Newtonian speed/accel with its "update" method class DynamicObject extends GameObject { constructor(shape, options) { super(shape, options); this.vel = options.vel || new Victor(0, 0); this.accel = options.accel || new Victor(0, -physicsSettings.gravity); } get isDynamic() { return true; } update(dt) { this.vel.add(this.accel.clone().multiplyScalar(dt)); this.shape.move(this.vel.clone().multiplyScalar(dt)); } } exports.GameObject = GameObject; exports.DynamicObject = DynamicObject;
TypeScript
UTF-8
2,259
3.421875
3
[]
no_license
import { NumberDial, radix } from './number-dials'; export const maxDigits = 3; export const minDigits = 1; export const power = maxDigits; /** * ## Model: NumberGroup * - Represent a group of number dials that collectively represent a number. * - Is iterable: start from the ends (`first`, `last`) and iterate using `dial.right` and `dial.left`. * - Is resizable, within bounds, using `grow()` and `shrink()`. * #### Dependencies * - NumberDial * #### TODO * - None */ export class NumberGroup { /** Member Variables **/ private _dials = [ ]; /** Constructors **/ constructor() { // every NumberGroup starts with one NumberDial set to 1 this._dials = [ new NumberDial(this) ]; } /** Properties **/ get dials(): NumberDial[] { return this._dials; } get length(): number { return this._dials.length; } get value(): number { let value = 0; for (let dial = this.first; dial; dial = dial.right()) { value *= radix; value += dial.value; } return value; } /** Iterables **/ get first(): NumberDial { return this._dials[0]; } get last(): NumberDial { return this._dials[this._dials.length - 1]; } left(dial: NumberDial, ensure?: boolean): NumberDial { if (!dial) return null; let idx = this.dials.indexOf(dial); if (-1 == idx) return null; if (0 == idx) { if (ensure && this.grow(0)) { ++idx; } else { return null; } } return this.dials[idx - 1]; } right(dial: NumberDial): NumberDial { if (!dial) return null; let idx = this.dials.indexOf(dial); if (-1 == idx) return null; if (this._dials.length - 1 == idx) return null; return this.dials[idx + 1]; } /** Resizeable **/ grow(value?: number) { if (maxDigits > this.length) { this.dials.unshift(new NumberDial(this, value)); return true; } return false; } shrink() { if (minDigits < this.length) { this.dials.shift(); return true; } return false; } remove(dial: NumberDial): boolean { let idx = this.dials.indexOf(dial); if (idx > -1 && this.length > 1) { this.dials.splice(idx, 1); return true; } return false; } }
Java
UTF-8
7,461
1.796875
2
[]
no_license
package org.meta_environment.rascal.interpreter.load; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.ISourceLocation; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.io.PBFReader; import org.meta_environment.ValueFactoryFactory; import org.meta_environment.errors.SubjectAdapter; import org.meta_environment.errors.SummaryAdapter; import org.meta_environment.rascal.ast.ASTFactory; import org.meta_environment.rascal.ast.AbstractAST; import org.meta_environment.rascal.ast.Module; import org.meta_environment.rascal.interpreter.Configuration; import org.meta_environment.rascal.interpreter.Names; import org.meta_environment.rascal.interpreter.asserts.ImplementationError; import org.meta_environment.rascal.interpreter.staticErrors.ModuleLoadError; import org.meta_environment.rascal.interpreter.staticErrors.SyntaxError; import org.meta_environment.rascal.parser.ASTBuilder; import org.meta_environment.rascal.parser.ModuleParser; import org.meta_environment.uptr.Factory; public class ModuleLoader { protected static final ASTBuilder BUILDER = new ASTBuilder(new ASTFactory()); private java.util.List<IModuleFileLoader> loaders = new LinkedList<IModuleFileLoader>(); private java.util.List<ISdfSearchPathContributor> contributors = new LinkedList<ISdfSearchPathContributor>(); private ModuleParser MODULE_PARSER = new ModuleParser(); public ModuleLoader() { } public void addFileLoader(IModuleFileLoader loader) { loaders.add(0, loader); } public void addSdfSearchPathContributor(ISdfSearchPathContributor contrib) { contributors.add(0, contrib); } private InputStream getInputStream(String name) { for (IModuleFileLoader loader : loaders) { try { return loader.getSourceInputStream(name); } catch (IOException e) { // this happens regularly } } return null; } private IConstructor tryLoadBinary(String name){ IConstructor tree = null; InputStream inputStream = null; try { inputStream = getInputStream(getBinaryFileName(name)); if (inputStream != null) { PBFReader pbfReader = new PBFReader(); tree = (IConstructor) pbfReader.read(ValueFactoryFactory.getValueFactory(), inputStream); } } catch (IOException ioex){ // Ignore; this is allowed. } finally{ if(inputStream != null){ try{ inputStream.close(); }catch(IOException ioex){ throw new ImplementationError(ioex.getMessage(), ioex); } } } return tree; } public Module loadModule(String name, AbstractAST ast) { if (isSdfModule(name)) { return null; } try { // IConstructor tree = tryLoadBinary(name); // <-- Don't do this if you want to generate new binaries. IConstructor tree = null; if (tree == null) { String fileName = getFileName(name); tree = parseModule(fileName, name, ast); } return BUILDER.buildModule(tree); } catch (FactTypeUseException e) { throw new ImplementationError("Unexpected PDB typecheck exception", e); } catch (IOException e) { throw new ModuleLoadError(name, e.getMessage(), ast); } } private boolean isSdfModule(String name) { for (String path : getSdfSearchPath()) { if (new File(new File(path), name + Configuration.SDF_EXT).exists()) { return true; } } return false; } private List<String> getSdfSearchPath() { List<String> result = new LinkedList<String>(); for (ISdfSearchPathContributor c : contributors) { result.addAll(c.contributePaths()); } return result; } private static String getFileName(String moduleName) { String fileName = moduleName.replaceAll("::", "/") + Configuration.RASCAL_FILE_EXT; fileName = Names.unescape(fileName); return fileName; } private static String getSdfFileName(String moduleName) { String fileName = moduleName.replaceAll("::", "/") + Configuration.SDF_EXT; fileName = Names.unescape(fileName); return fileName; } private static String getBinaryFileName(String moduleName) { String fileName = moduleName.replaceAll("::", "/") + Configuration.RASCAL_BIN_FILE_EXT; fileName = Names.unescape(fileName); return fileName; } private SyntaxError parseError(IConstructor tree, String file, String mod) throws MalformedURLException { SubjectAdapter subject = new SummaryAdapter(tree).getInitialSubject(); IValueFactory vf = ValueFactoryFactory.getValueFactory(); URL url = new URL("file://" + file); ISourceLocation loc = vf.sourceLocation(url, subject.getOffset(), subject.getLength(), subject.getBeginLine(), subject.getEndLine(), subject.getBeginColumn(), subject.getEndColumn()); return new SyntaxError("module " + mod, loc); } @SuppressWarnings("unchecked") public IConstructor parseCommand(String command, String fileName) throws IOException { // TODO: add support for concrete syntax here (now it ignores the sdf imports) return MODULE_PARSER.parseCommand(Collections.EMPTY_SET, Collections.EMPTY_LIST, fileName, command); } public IConstructor parseModule(String fileName, String name, AbstractAST ast) throws IOException { InputStream inputStream = null; Set<String> sdfImports; try { inputStream = getInputStream(fileName); if (inputStream == null) { throw new ModuleLoadError(name, "not in path", ast); } sdfImports = MODULE_PARSER.getSdfImports(getSdfSearchPath(), fileName, inputStream); } finally { if (inputStream != null) { inputStream.close(); } } InputStream secondInputStream = null; try { List<String> sdfSearchPath = getSdfSearchPath(); secondInputStream = getInputStream(fileName); IConstructor tree = MODULE_PARSER.parseModule(sdfSearchPath, sdfImports, fileName, secondInputStream); if (tree.getConstructorType() == Factory.ParseTree_Summary) { throw parseError(tree, fileName, name); } return tree; } finally { if (secondInputStream != null) { secondInputStream.close(); } } } public IConstructor parseModule(String fileName, String name, String moduleString) throws IOException { List<String> sdfSearchPath = getSdfSearchPath(); InputStream inputStream = null; Set<String> sdfImports; try { inputStream = new ByteArrayInputStream(moduleString.getBytes()); sdfImports = MODULE_PARSER.getSdfImports(sdfSearchPath, fileName, inputStream); } finally { if (inputStream != null) { inputStream.close(); } } InputStream secondInputStream = null; try { secondInputStream = new ByteArrayInputStream(moduleString.getBytes()); IConstructor tree = MODULE_PARSER.parseModule(sdfSearchPath, sdfImports, fileName, secondInputStream); if (tree.getConstructorType() == Factory.ParseTree_Summary) { throw parseError(tree, fileName, name); } return tree; } finally { if (secondInputStream != null) { secondInputStream.close(); } } } }
Java
UTF-8
301
2.296875
2
[]
no_license
package com.dimitrisli.springHibernateMySQL.dao; import com.dimitrisli.springHibernateMySQL.model.Person; public interface PersonORMDao { public void create(Person person); public Person read(String name, String surname); public void update(Person person); public void delete(Person person); }
C#
UTF-8
1,226
3.6875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProgrammingRecovery.Recoveries { class FormatChecker { // This application takes an input and tells you if the input is a number or not public void FormatCheck() { bool input = false; while (input == false) { //Console Reset Console.Clear(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Please give an input: "); string numberInput = Console.ReadLine(); if (int.TryParse(numberInput, out int numberToOut)) Console.WriteLine("\nThe input was a number!"); else Console.WriteLine("\nThe Input was not a number!"); Console.WriteLine("\nPress Escape to exit the application, or press Enter to continue..."); ConsoleKeyInfo userInput = Console.ReadKey(); if (userInput.Key == ConsoleKey.Escape) input = true; else continue; } } } }
PHP
UTF-8
473
3.140625
3
[ "MIT" ]
permissive
<?php namespace App\Exceptions; use Exception; class AppException extends Exception { protected string $status; public function __construct( string $message, string $status = 'error', int $statusCode = 400 ) { $this->message = $message; $this->status = $status; $this->statusCode = $statusCode; } public function getStatus() { return $this->status; } public function getStatusCode() { return $this->statusCode; } }
C++
UTF-8
544
2.703125
3
[]
no_license
#include <iostream> #include <string> #include <clocale> using namespace std; int main() { setlocale(LC_CTYPE, "rus"); float a,b,s; string c; cin>>a>>b; cin>>c; if (c == "+"){ s=a+b; cout<<s<<endl; }else if (c == "-"){ s=a-b; cout<<s<<endl; }else if (c == "*"){ s=a*b; cout<<s<<endl; }else if (c == "/"){ s=a/b; cout<<s<<endl; }else { cout<<"\n������"<<endl; } return 0; }
Swift
UTF-8
460
2.515625
3
[ "MIT" ]
permissive
// // RoundedView.swift // AtlasSDK // // Created by Yelyzaveta Kartseva on 19.05.2021. // import UIKit class RoundedView: BaseView { // MARK: - Properties @IBInspectable var cornerRadius: CGFloat = 8.0 { didSet { self.layer.cornerRadius = self.cornerRadius } } // MARK: - Lifecycle override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.cornerRadius } }
Java
UTF-8
3,677
2.15625
2
[]
no_license
package com.cpe.backend; import com.cpe.backend.Addjob.entity.Addjob; import com.cpe.backend.Addjob.repository.AddjobRepository; import com.cpe.backend.Addjob.entity.Information; import com.cpe.backend.Addjob.repository.InformationRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.dao.DataIntegrityViolationException; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Optional; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest public class InformationTests { private Validator validator; @Autowired private InformationRepository informationRepository; @BeforeEach public void setup() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } @Test void b6007409_testInformationPattren(){ Information information = new Information(); information.setInformation_type("WebsiteAAA123"); Set<ConstraintViolation<Information>> result = validator.validate(information); assertEquals(1, result.size()); ConstraintViolation<Information> message = result.iterator().next(); assertEquals("must match \"[a-zA-Z]{1,50}$\"",message.getMessage()); assertEquals("Information_type",message.getPropertyPath().toString()); } @Test void b6007409_testInformationNotnull() { Information information = new Information(); information.setInformation_type(null); Set<ConstraintViolation<Information>> result = validator.validate(information); assertEquals(1, result.size()); assertEquals("must not be null", result.iterator().next().getMessage()); assertEquals("Information_type", result.iterator().next().getPropertyPath().toString()); } @Test void b6007409_testInformationMustGreaterEqual4() { Information information = new Information(); information.setInformation_type("ttt"); Set<ConstraintViolation<Information>> result = validator.validate(information); assertEquals(1, result.size()); assertEquals("size must be between 4 and 30", result.iterator().next().getMessage()); assertEquals("Information_type", result.iterator().next().getPropertyPath().toString()); } @Test void b6007409_testInformationMustLessEqual30() { Information information = new Information(); information.setInformation_type("Arhhassdaassadasdasdasdadasdasdasdasdasd"); Set<ConstraintViolation<Information>> result = validator.validate(information); assertEquals(1, result.size()); assertEquals("size must be between 4 and 30", result.iterator().next().getMessage()); assertEquals("Information_type", result.iterator().next().getPropertyPath().toString()); } @Test void b6007409_testInformationSuccess() { Information information = new Information(); information.setInformation_type("Website"); information = informationRepository.saveAndFlush(information); Optional<Information> found = informationRepository.findById(information.getId()); assertEquals(information.getInformation_type(), found.get().getInformation_type()); } }
C#
UTF-8
2,486
3.296875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeepInCShape { class 匿名方法捕获变量 { //static void Main(string[] args) //{ // // EnclosinMethod(); // //Methhod02(); // Method03(); // Console.ReadKey(); //} static void EnclosinMethod() { int outVar = 5; //外部变量 string capturedVar = "captured"; if (DateTime.Now.Hour == 23) { int normalLocalVar = DateTime.Now.Minute; //普通方法的局部变量 Console.WriteLine(normalLocalVar); } Action x = delegate() { string anonLocal = "匿名方法内的局部变量"; Console.WriteLine("捕获外部变量:--"+capturedVar + anonLocal); //捕获外部变量 }; x(); } //测试局部变量实例化 static void Methhod02() { List<Action> List = new List<Action>(); for (int i = 0; i < 5; i++) //for循环的的i只在匿名方法中实例一次 { int counter = i*10; List.Add(delegate { Console.WriteLine(counter + "----i:" + i); counter++; }); } foreach (var action in List) { action(); //执行全部5个委托实例 } //此时会从实例counter变量停止的地方继续 List[0](); //第一个委托执行3次 List[0](); List[0](); List[1](); //第2个委托执行1次 } //扑捉不同作用域的变量 static void Method03() { Action[] actions = new Action[2]; int outside = 0; for (int i = 0; i < 2; i++) { int inside = 0; actions[i] = delegate { Console.WriteLine("(out:{0},in:{1})", outside, inside); outside++; inside++; }; } Action first = actions[0]; Action second = actions[1]; first(); first(); first(); second(); second(); } } }
JavaScript
UTF-8
1,972
2.921875
3
[ "MIT" ]
permissive
class Partido{ constructor(nombre = "", dipu =0, imagen= "") { this.nombre=nombre; this.dipu=dipu; this.imagen=imagen; } } function success(data){ console.log("Ha ido todo guay"); //console.log("Objetos devueltos: " +data); let listado =[]; for (index in data){ let partido = new Partido( data[index].nombre, data[index].dipu, data[index].imagen); listado.push(partido); } for (index in listado){ console.log(listado[index]); $("#botones_partidos") .append( "<button id='part-" +listado[index].nombre+"'"+ "data-nombre='"+listado[index].nombre+"'" + "data-dipu='"+listado[index].dipu+"'" + "data-imagen='"+listado[index].imagen+"'" + ">" + "<img src='http://cursosdedesarrollo.com/pactometro/img/"+listado[index].imagen+"'/>" +"<h2>"+listado[index].dipu+"</h2>"+ "</button>"); $("#table_partidos").append( "<tr>" + "<td>"+listado[index].nombre+"</td>"+ "<td>"+listado[index].dipu+"</td>"+ "<td><img src='https://cursosdedesarrollo.com/pactometro/img/"+listado[index].imagen+"'/></td>"+ "</tr>" ) } $("#partidos li").click((evento)=>{ console.log($(evento.currentTarget).attr("data-nombre")); }) } function showError(error){ console.log("Ha petado"); console.log("Error: "+ error); } $(document).ready ((event) => { console.log("Hola JQuery"); // Llamada normal let url="https://cursosdedesarrollo.com/pactometro/resultados.json"; /* $.ajax(url) .done(success) .fail(showError); */ $.getJSON({ url: url, dataType: "json", type: "get", success: success, error: showError }); });